text,title "C_sharp : I am using NDesk.Options to parse command line arguments for a C # command line program . It is working fine , except I want my program to exit unsuccessfully , and show the help output , if the user includes arguments that I did not expect.I am parsing options thusly : With this code , if I use an argument improperly , such as specifying -- filter without =myfilter after it then NDesk.Options will throw an OptionException and everything will be fine . However , I also expected an OptionException to be thrown if I pass in an argument that does n't match my list , such as -- someOtherArg . But this does not happen . The parser just ignores that and keeps on trucking.Is there a way to detect unexpected args with NDesk.Options ? var options = new OptionSet { { `` r|reset '' , `` do a reset '' , r = > _reset = r ! = null } , { `` f|filter= '' , `` add a filter '' , f = > _filter = f } , { `` h| ? |help '' , `` show this message and exit '' , v = > _showHelp = v ! = null } , } ; try { options.Parse ( args ) ; } catch ( OptionException ) { _showHelp = true ; return false ; } return true ;",NDesk.Options - detect invalid arguments "C_sharp : Basically NUnit , xUnit , MbUnit , MsTest and the like have methods similar to the following : However , there are a limited number of such comparison operators built-in ; and they duplicate the languages operators needlessly . When I want anything even slightly complex , such as ... I 'm often either left digging through the manual to find the equivalent of the expression in NUnit-speak , or am forced to fall-back to plain boolean assertions with less helpful error messages.C # , however , integrates well with arbitrary Expressions - so it should be possible to have a method with the following signature : Such a method could be used to both execute the test ( i.e . validate the assertion ) and to also provide less-opaque diagnostics in case of test failure ; after all , an expression can be rendered to pseudo-code to indicate which expression failed ; and with some effort , you could even evaluate failing expressions intelligently to give some clue of the value of subexpressions.For example : At a minimum , it would make the use of a parallel language for expressions unnecessary , and in some cases it might make failure messages more useful.Does such a thing exist ? Edit : After trying ( and liking ! ) Power Assert , I ended up reimplementing it to address several limitations . My variant of this is published as ExpressionToCode ; see my answer below for a list of improvements . Assert.IsGreater ( a , b ) //or , a little more discoverableAssert.That ( a , Is.GreaterThan ( b ) ) Assert.That ( a.SequenceEquals ( b ) ) void That ( Expression < Func < bool > > expr ) ; Assert.That ( ( ) = > a == b ) ; //could inspect expression and print a and bAssert.That ( ( ) = > a < b & & b < c ) ; //could mention the values of `` a < b '' and `` b < c '' and/or list the values of a , b , and c .",Is there a C # unit test framework that supports arbitrary expressions rather than a limited set of adhoc methods ? "C_sharp : I have a problem that may be fairly unique . I have an application that runs on a headless box for long hours when I am not present , but is not critical . I would like to be able to debug this application remotely using Visual Studio . In order to do so , I have code that looks like this : The idea being that this way , I hit an error while I am away , and the application effectively pauses itself and waits for a remote debugger attach , which after the first continue automatically gets the right context thanks to the Debugger.Break call.Here is the problem : Implementing SuspendAllButCurrentThread turns out to be nontrivial . Thread.Suspend is deprecated , and I ca n't P/Invoke down to SuspendThread because there 's no one-to-one mapping between managed threads and native threads ( since I need to keep the current thread alive ) . I do n't want to install Visual Studio on the machine in question if it can possibly be avoided . How can I make this work ? // Suspend all other threads to prevent loss// of state while we investigate the issue.SuspendAllButCurrentThread ( ) ; var remoteDebuggerProcess = new Process { StartInfo = { UseShellExecute = true , FileName = MsVsMonPath ; } } ; // Exception handling and early return removed here for brevity.remoteDebuggerProcess.Start ( ) ; // Wait for a debugger attach.while ( ! Debugger.IsAttached ) { Thread.Sleep ( 500 ) ; } Debugger.Break ( ) ; // Once we get here , we 've hit continue in the debugger . Restore all of our threads , // then get rid of the remote debugging tools.ResumeAllButCurrentThread ( ) ; remoteDebuggerProcess.CloseMainWindow ( ) ; remoteDebuggerProcess.WaitForExit ( ) ;",C # suspending all threads "C_sharp : The following code works as I want it to , but causes a warning : Warning 1 Because this call is not awaited , execution of the current method continues before the call is completed . Consider applying the 'await ' operator to the result of the call.Is there an alternative to Task.Run ( ) that will kick off this thread in a nice terse way ? /// < summary > /// StartSubscriptionsAsync must be called if you want subscription change notifications./// This starts the subscription engine . We always create one subscription for/// Home DisplayName to start ( but ignore any updates ) ./// < /summary > public async Task StartSubscriptionsAsync ( ) { await _subscriptionClient.ConnectAsync ( Host , Port ) ; // Generates a compiler warning , but it is what we want Task.Run ( ( ) = > ReadSubscriptionResponses ( ) ) ; // We do a GetValue so we know we have a good connection SendRequest ( `` sys : //Home ? f ? ? '' + `` Name '' ) ; if ( FastMode ) EnableFastMode ( ) ; foreach ( var subscription in _subscriptions ) { SendSubscriptionRequest ( subscription.Value ) ; } }",Alternative to Task.Run that does n't throw warning "C_sharp : I 'm writing a Roslyn analyzer to raise a diagnostic when a certain library method is used within a certain method in a certain kind of class , but I can not retrieve the symbol in the parent or ancestor syntax nodes.For example , And this is the code for analyzing the SyntaxNode of SyntaxKind.InvocationExpressionSo my question is , is it possible to retrieve SymbolInfo from an ancestor SyntaxNode.Is my approach correct or should I try another approach ? class C { void M ( ) { MyLibrary.SomeMethod ( ) ; } } private void AnalyzeNode ( SyntaxNodeAnalysisContext context ) { var invocationExpression = context.Node as InvocationExpressionSyntax ; var methodSymbol = context.SemanticModel.GetSymbolInfo ( invocationExpression ) .Symbol as IMethodSymbol ; if ( methodSymbol == null ) { return ; } // check if it is the library method I am interested in . No problems here if ( ! methodSymbol.Name.Equals ( `` SomeMethod '' ) || ! methodSymbol.ContainingSymbol.ToString ( ) .Equals ( `` MyNamespace.MyLibrary '' ) ) { return ; } // this retrieves outer method `` M '' . var outerMethodSyntax = invocationExpression.FirstAncestorOrSelf < MethodDeclarationSyntax > ( ) ; if ( outerMethodSyntax == null ) { return ; } // symbol.Symbol is always null here var symbol = context.SemanticModel.GetSymbolInfo ( outerMethodSyntax ) ; ...",Roslyn : Retrieving Symbol in parent or ancestor SyntaxNode "C_sharp : I 'm working on some test automation for a service , and figured out a neat way to roll up some common setup & verification into a 'session ' class.Conceptually , a test case might look like this : In the Session object constructor I set up a connection to the service I 'm testing with proper authentication per role etc , and in the session Dispose ( ) method I have a common validation block that , for instance , checks that no server-side errors or warnings have been raised during the session lifetime.Now , of course , this is sort of abusing the IDispose pattern , and if test code inside a using blocks throws an exception AND the validation block also throws an exception the second exception will mask the first.Conceptually , if we have this scenario : ... and the assert fails or the call to managerSession.DoJob ( ) throws an exception , then I would like the Session Dispose ( ) method to skip the validation block , i.e ... .such that the test method never fails with 'Service connection has errors ' if it actually fails with 'Manager did not do his job'My question is : Is it at all possible to implement the 'NoExceptionThrown ( ) ' method here ? Is there some global property that can be checked , or something hidden in Thread.CurrentThread that could be utilized ? Update : My question is not how to refactor this : - ) I could of course use this pattern instead : With the static method ForRole ( ) defined likeBut I am curious whether there exists some way of grabbing the exception state as described above . using ( var managerSession = new Session ( managerRole ) ) { // A manager puts some items in warehouse } using ( var employeeSession = new Session ( employeeRole ) ) { // An employee moves items from warehouse to store } using ( var customerSession = new Session ( customerRole ) ) { // A customer can buy items from the store } using ( var managerSession = new Session ( managerRole ) ) { Assert.IsTrue ( managerSession.DoJob ( ) , `` Manager did not do his job '' ) ; } public void Dispose ( ) { if ( NoExceptionThrown ( ) ) { Assert.IsFalse ( this.serviceConnection.HasErrors ( ) , `` Service connection has errors '' ) ; } this.serviceConnection.Dispose ( ) ; } Session.ForRole ( managerRole , ( session ) = > { /* Test code here */ } ) ; public static void ForRole ( Role r , Action < Session > code ) { var session = new Session ( r ) ; try { code ( session ) ; Assert.IsFalse ( session.serviceConnection.HasErrors ( ) ) ; } finally { session.Dispose ( ) ; } }",How can I check if any exception has already been thrown ? "C_sharp : In C # , what 's the best way to delay handling of all known events until an entity has been fully modified ? Say , for example that an entity - MyEntity - has the properties ID , Name and Description ... When modifying each of these properties , an event is fired for each modification.Sometimes , the ID is the only property modified and sometimes all properties are modified . I want the registered listeners of the modification event to wait until all properties being modified in the `` batch '' have been modified.What is the best way to accomplish this ? In my head , something similar to the UnitOfWork-pattern , where it is possible to wrap a using statement around the method call in the top level of the call stack but have no clue how to implement such a thing ... Edit : As a clarification ... Listeners are spread out through the application and are executing in other threads . Another actor sets - for example - the name it must call the MyEntity.Name property to set the value . Due to the design , the modification of the Name property can trigger other properties to change , thus the need for listeners to know that the modification of properties have been completed . public class MyEntity { public Int32 ID { get ; set ; } public String Name { get ; set ; } public String Description { get ; set ; } }",Delay event handling until events have been fired "C_sharp : I have an object with a string-typed parameter called 'baan_cat_fam_code ' . The code below is my attempt to find all items in the query that have a baan_cat_fam_code that exist in a generic string list called catFamCd . The problem is that this wo n't compile - I get an error that states for some reason the predicate s is typed as char . So I append .ToString ( ) to the argument in the .Contains method . However , when the code runs , I get the following exception thrown when the result of the query is bound to a listbox.This has got me scratching my head . Any assistance would be greatly appreciated.Thanks ! query = query.Where ( r = > r.baan_cat_family_code.Any ( s = > catFamCode.Contains ( s ) ) ) ; `` Argument type 'char ' is not assignable to parameter type 'string ' '' `` The argument 'value ' was the wrong type . Expected 'System.Char ' . Actual 'System.String ' . ''",LINQ Any ( ) argument versus parameter data type issues "C_sharp : This is something I 'm having a hard time wrapping my head around . I understand that Action < T > is contravariant and is probably declared as such.However , I do n't understand why an Action < Action < T > > is covariant . T is still not in an output position . I 'd really appreciate it if someone could try to explain the reasoning / logic behind this . I dug around a little bit and found this blog post which tries to explain it . In particular , I did n't quite follow what was meant here under the `` Explanation for covariance of input '' subsection . It is the same natural if the “ Derived - > Base ” pair is replaced by “ Action - > Action ” pair . internal delegate void Action < in T > ( T t ) ;",Why is Action < Action < T > > covariant ? "C_sharp : I came across the following code snippet and was wondering what the purpose of writing a constructor this way was ? Does n't this ( ) just set X and Y to zero ? Is this not a pointless action seeing as afterwards they are immediately set to x and y ? public struct DataPoint { public readonly long X ; public readonly double Y ; public DataPoint ( long x , double y ) : this ( ) { this.X = x ; this.Y = y ; } }",Struct constructor calls this ( ) "C_sharp : I 'm using This GoogleJsonWebToken class to generate an access token to be used with json calls to the Google Calendar API . It works perfectly fine in IIS Express on my dev machine when I use the following ( using my actual service account email ) : To test this I 'm just calling @ Token in my cshtml razor view . When I publish this to my Azure website it does n't work . If i leave the GoogleJsonWebToken class unmodified I get a very unhelpful 502 - Web server received an invalid response while acting as a gateway or proxy server . with no other information.After some Google searches I found this SO post which is a similar problem . So I tried their solution I get System.Security.Cryptography.CryptographicException : The system can not find the file specified . when that is run from my Azure Website . When it is run from my dev machine I get System.Net.WebException : The remote server returned an error : ( 400 ) Bad Request . which I think is because with that solution the CspKeyContainerInfo.KeyContainerName is null whereas the original unmodified class when run on my dev machine gives me something like { C0E26DC5-5D2C-4C77-8E40-79560F519588 } which is randomly generated each time and this value is used in the process of signing the signature.I then found this SO post but that solution yielded the same results as the last solution.I have also tried most of the different combinations of X509KeyStorageFlags to no avail.How can I either generate the CspKeyContainerInfo.KeyContainerName myself or otherwise successfully generate the X509Certificate2 ? string p12Path = HttpContext.Current.Server.MapPath ( `` ~/App_Data/certificate.p12 '' ) ; var auth = GoogleJsonWebToken.GetAccessToken ( `` uniquestring @ developer.gserviceaccount.com '' , p12Path , `` https : //www.googleapis.com/auth/calendar '' ) ; string Token = auth [ `` access_token '' ] ;",502 error when generating X509Certificate2 from p12 certificate in Azure Websites for Google API "C_sharp : I would like to get Exams and Test entities that have a UserTest entity with a UserId that is either equal to `` 0 '' or to a provided value . I had a number of suggestions but so far none have worked . One suggestion was to start by getting UserTest data and the other solution was to start by getting Exam data . Here 's what I have when I used the UserTests as the source starting point.I have the following LINQ : When I check _uow.UserTests with the debugger it 's a repository and when I check the dbcontext 's configuration.lazyloading then it is set to false.Here 's my classes : When I looked at the output I saw something like this : Note that it gets a UserTest object , then gets a test object and then an exam object . However the exam object contains a test collection and then it heads back down again and gets the different tests and the unit tests inside of those : UserTest > Test > Exam > Test > UserTest ? I have tried hard to ensure lazy loading is off and debug tell me it 's set to false . I am using EF6 and WebAPI but not sure if that makes a difference as I am debugging at the C # level . var userTests = _uow.UserTests .GetAll ( ) .Include ( t = > t.Test ) .Include ( t = > t.Test.Exam ) .Where ( t = > t.UserId == `` 0 '' || t.UserId == userId ) .ToList ( ) ; public class Exam { public int ExamId { get ; set ; } public int SubjectId { get ; set ; } public string Name { get ; set ; } public virtual ICollection < Test > Tests { get ; set ; } } public class Test { public int TestId { get ; set ; } public int ExamId { get ; set ; } public string Title { get ; set ; } public virtual ICollection < UserTest > UserTests { get ; set ; } } public class UserTest { public int UserTestId { get ; set ; } public string UserId { get ; set ; } public int TestId { get ; set ; } public int QuestionsCount { get ; set ; } } [ { `` userTestId '' :2 , `` userId '' : '' 0 '' , `` testId '' :12 , `` test '' : { `` testId '' :12 , '' examId '' :1 , `` exam '' : { `` examId '' :1 , '' subjectId '' :1 , `` tests '' : [ { `` testId '' :13 , '' examId '' :1 , '' title '' : '' Sample Test1 '' , `` userTests '' : [ { `` userTestId '' :3 , `` userId '' : '' 0 '' ,",Why is my code doing lazy loading even after I turned it off at every possible point ? "C_sharp : I 've never really got my head around what constitutes `` good '' exception handling . A quick google search shows that , almost unanimously , people agree that catching and rethrowing exceptions deep in the call stack is bad . Above , I have an example of some code I 'm writing . This is pretty low in a typical call stack . I did this because , without this code , it is a bit difficult to find exactly what course failed to deploy . My question is , if I did something similar in many ( if not all ) methods , to add more context to an exception , why would this be considered anti-pattern ? Thanks ! public void DeployCourse ( Course course , Client client ) { if ( course == null ) throw new ArgumentNullException ( `` Course can not be null '' ) ; if ( client == null ) throw new ArgumentNullException ( `` Client can not be null '' ) ; try { _ftp.Transfer ( client.Server.IPAddress , course.PackageUrl , course.CourseName ) ; } catch ( Exception e ) { var newException = new Exception ( String.Format ( `` Error deploying Course : { 0 } to Client : { 1 } . See inner exception for more details '' , course.CourseName , client.Name ) , e ) ; throw newException ; } }",Catching and Throwing exceptions ; Why is this considered an anti-pattern "C_sharp : I 've been trying to figure out why I 'm getting a TaskCanceledException for a bit of async code that has recently started misbehaving . I 've reduced my issue down to a small code snippet that has me scratching my head : As far as I 'm aware , this should simply pause for a second and then close . The ContinueWith wo n't be called ( this only applies to my actual use-case ) . However , instead I 'm getting a TaskCanceledException and I 've no idea where that is coming from ! static void Main ( string [ ] args ) { RunTest ( ) ; } private static void RunTest ( ) { Task.Delay ( 1000 ) .ContinueWith ( t = > Console.WriteLine ( `` { 0 } '' , t.Exception ) , TaskContinuationOptions.OnlyOnFaulted ) .Wait ( ) ; }",TaskCanceledException with ContinueWith "C_sharp : I was running VS2013 's code analysis on one of my current projects , and came across `` CA1001 : Types that own disposable fields should be disposable . '' A simple example that generates the warning ( presuming DisposableClass implements IDisposable ) is : However , converting the field variable to a property no longer generates the warning , even if the circumstance is that the property will be instantiated by the class : In the first case it 's clear that the class should implement the IDisposable pattern , and dispose of its disposableClass field appropriately . My question : is the lack of a warning for the second case a limitation of the code analysis tool ? Should the class still implement IDisposable and dispose of the property , despite the lack of a warning ? class HasDisposableClassField { private DisposableClass disposableClass ; } class HasDisposableClassProperty { private DisposableClass disposableClass { get ; set ; } public HasDisposableClassProperty ( ) { disposableClass = new DisposableClass ( ) ; } }",Implementing IDisposable - Disposable Fields vs . Disposable Properties "C_sharp : I 've spent a while trying to understand why my WPF app was n't databinding to an enum property propertly and this is the cause.Essentially the problem was that there was no default value set for the enum property in the constructor of the class I was binding to , so it was defaulting to zero.Is there someway I can tell the C # compiler that I want it to only accept valid values ( and default to the lowest value ) ? I do n't want my property to accept invalid values , and I do n't want to have to write setter code for every property that uses an enum . static void Main ( string [ ] args ) { MyEnum x = 0 ; Console.WriteLine ( x.ToString ( ) ) ; Console.ReadLine ( ) ; } public enum MyEnum { First = 1 , Second = 2 }",Why would C # allow an invalid enum value "C_sharp : Pour in your posts . I 'll start with a couple , let us see how much we can collect.To provide inline event handlers likeTo find items in a collectionFor iterating a collection , likeLet them come ! ! button.Click += ( sender , args ) = > { } ; var dogs= animals.Where ( animal = > animal.Type == `` dog '' ) ; animals.ForEach ( animal= > Console.WriteLine ( animal.Name ) ) ;",In what ways do you make use of C # Lambda Expressions ? "C_sharp : TLDR ; Screens newly referencing an external ResourceDictionary file in VS2015 style correctly at run-time , but not at design-time . What gives ? At work , we have a WinForms product which houses many WinForms screens with one developer actively adding new ones , as well as a handful of WPF screens with me adding new ones . Noticing a lot repetitious code/styling in existing WPF screens , I created a single project to house this - to be referenced by all existing/future WPF screens.Project : WpfHelperPlatform target : Any CPUTarget framework : .NET Framework 4.6WpfHelper.dll deployed to ... \Trunk\Project\Externals ... \Trunk\Utilities\WpfHelper\WpfHelper\Resources\GlobalResources.xamlBuild Action : PageResourceDictionary containing generic stylesI have referenced ... \Trunk\Project\Externals\WpfHelper.dll in six projects , adding the following code to each of their resource files : All screens are located in ... \Trunk\Project\Plugins.Recent ChangesJust recently I upgraded Visual Studios 2013 to 2015 . Around the same time , the other screen developer upgraded all existing screen project 's target frameworks to .NET Framework 4.6 from .NET Framework 3.5/4.0.Successful ProjectsI referenced WpfHelper.dll prior to the Recent Changes.Styles applied correctly at Design-time and Run-time.Failed ProjectsI referenced WpfHelper.dll after the Recent Changes.Styles applied correctly at Run-time only.During Design-time , the error is thrown : An error occurred while finding the resource dictionary `` pack : //application , , , /WpfHelper ; component/Resources/GlobalResources.xaml '' .Where the local Resources.xaml are used , the subsequent error is thrown : Value can not be null . Parameter name : itemWhat I have tried : After reading an extensive list of articles and Q & A 's : Design Time WPF XAML Resource DictionariesHow to load a ResourceDictionary at Design Time in WPFError finding resource dictionary in separate assemblyProblems loading merged resource dictionaries in .NET 4.0Pack URIs in Windows Presentation FoundationVS2013 : An error occurred while finding the resource dictionaryAn error occurred while finding the resource dictionaryError finding merged resource dictionary in another assemblyTrouble referencing a Resource Dictionary that contains a Merged DictionaryWPF VS2013 : An error occurred while finding the resource dictionaryApp runs normally but has “ errors ” during design time : “ does not exist in namespace ” and “ an error occured when finding the resource dictionary ” Resource Dictionary as Linked FileVisual Studio 2015 XAML Resource Dictionary ErrorI tried all the following to no avail : Change project Platform target to `` Any CPU '' Change project Target framework from/to .NET Framework 4.6Ensure all Resource.xaml files had the same Build Action ( Page ) , etc.Checked each project 's AssemblyInfo.cs file . Failing projects included ( and I removed ) the following : Manually cleared the temp folder in AppsData , Cleaned & Rebuilt projects.Re-opened projects.Rebooted.Right-click copied WpfHelper.dll references from working projects and pasted into references of failing projects.Added the WpfHelper.Resources.GlobalResources.xaml as a Linked file to the failed projects.Nagged every co-worker.Added the full pack URI for sub-dictionaries used in GlobalResources.xaml.Killed the designer and rebuilt the project.I 'm out of ideas and lost in research . I 've templated one of the working solutions and used that for creating new screens - that creates new screens which successfully display at design-time . It 's something about these pre-existing screens . How can I get the failed projects to correctly display styled resources at design-time ? < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' pack : //application : , , ,/WpfHelper ; Component/Resources/GlobalResources.xaml '' / > < /ResourceDictionary.MergedDictionaries > ╔══════════╦═════════════════╦═════════════════╦══════════════════╦════════════════════════════════════════════════╗║ ║ Resource Works ? ║ Platform Target ║ Target Framework ║ Reference File Path ║╠══════════╬═════════════════╬═════════════════╬══════════════════╬════════════════════════════════════════════════╣║ Project1 ║ Succeeded ║ Any CPU ║ .NET 4.6 ║ ... \Project1\Project1\Resources\Resources.xaml ║║ Project2 ║ Succeeded ║ x86 ║ .NET 4.6 ║ ... \Project2\Project2\Resources\Resources.xaml ║║ Project3 ║ Succeeded ║ Any CPU ║ .NET 4.6 ║ ... \Project3\Project3\Resources\Resources.xaml ║║ Project4 ║ Failed ║ x86 ║ .NET 4.6 ║ ... \Project4\Project4\Resources\Resources.xaml ║║ Project5 ║ Failed ║ x86 ║ .NET 4.6 ║ ... \Project5\Project5\Resources\Resources.xaml ║║ Project6 ║ Failed ║ Any CPU ║ .NET 4.6 ║ ... \Project6\Project6\Resources\Resources.xaml ║╚══════════╩═════════════════╩═════════════════╩══════════════════╩════════════════════════════════════════════════╝ [ assembly : ThemeInfo ( ResourceDictionaryLocation.None , ResourceDictionaryLocation.SourceAssembly ) ]",Design-time Error finding the Resource Dictionary - Inconsistent between projects "C_sharp : This might sound like a weird question but I do n't get it ... Let 's say I have an application which connects to a server to do some stuff . This connect might fail and throw an exception which I can catch.However , in case that the connect is succcesful the application shall continue ... The `` server talking '' however is executed in any case . It does n't matter if the exception occured or not.How can I make sure that the `` server talking '' is only executed if the connect was successful ? Do I have to move all of the following code inside the trystatement ? What is a clean way to program such a behavior ? try { Client.connect ( ) ; } catch ( System.Exception ex ) { // Do some exception handling ... } finally { // Do some cleanup ... } try { Client.connect ( ) ; } catch ( System.Exception ex ) { // Do some exception handling ... } finally { // Do some cleanup ... } // Talk to the server ...",Continue after try-catch-finally "C_sharp : I 've created a custom language package , which extends ProjectPackage . I can create the new project correctly . I would like to be able to add new source files to the project by using the Add- > New Item ... ( Ctrl+Shift+A ) menu item . However , when I click this at the moment the list of available templates is empty . I would like to add my own custom template to the menu of available templates for this project type . Is there some documentation for accomplishing this ? The only mentions I have seen have been registry hacks , but there has to be a way to do the programmatically I would think.Is there a particular method I can override to populate the list ? Do I really need to make a template , or can I just show the 'template name ' , 'icon ' and provide the correct file extension ( the files should be empty when created , so I think a template is largely wasted on what I want to do ) .Here 's the path I 've been traveling down thus far . I figured I could set my project type and GUID in my custom .vproj file ( .vproj is the file extension that my custom project is registered under ) . I thought I could quickly create a item template with the same ProjectType as my .vproj file.Alas , this template does not show up at all , even though I 've included it in VSIX and copied it to the output directory . If I put this template in the same folder as my .vproj , it will appear as a template for creating a new project ( wrong ! ) and still wo n't appear in my new items list . This could all derive from the fact that I do not use a VSTemplate for creating my project . Instead I use [ ProvideProjectFactoryAttribute ] to let VS2010 know where my vproj file is , and it will use the vproj file ( which I guess you could call a template , but it is n't a VSTemplate , it is a Project ) to base the new project off of.This is where I am at so far , and I 'm continuing to try new things . I 'm hoping someone might have the answer I am looking for . Thanks , Giawa < VSTemplate Version= '' 3.0.0 '' xmlns= '' http : //schemas.microsoft.com/developer/vstemplate/2005 '' Type= '' Item '' > < TemplateData > < Icon > VerilogSource.ico < /Icon > < DefaultName > module.v < /DefaultName > < Name > Basic Verilog Module < /Name > < Description > A basic Verilog module for quickly adding new files to the project . < /Description > < ProjectType > VerilogProject < /ProjectType > < /TemplateData > < TemplateContent > < ProjectItem TargetFileName= '' $ fileinputname $ .v '' ReplaceParameters= '' true '' > module.v < /ProjectItem > < /TemplateContent > < /VSTemplate >",VS2010 MPF : Populating 'Add- > New Item ... ' list for a custom project C_sharp : I have this code in JAVA and works fineThe output as expected is3656667I am a little confused aboud a.length ( ) because it is suposed to return the length in chars but String must store every < 256 char in 16 bits or whatever a unicode character would need.But the question is how can i do the same i C # ? .I need to scan a string and act depending on some unicode characters found.The real code I need to translate isThanks in advance.How much i love JAVA : ) . Just need to deliver a Win APP that is a cliend of a Java / Linux app server . String a = `` ABC '' ; System.out.println ( a.length ( ) ) ; for ( int n = 0 ; n < a.length ( ) ; n++ ) System.out.println ( a.codePointAt ( n ) ) ; String str = this.getString ( ) ; int cp ; boolean escaping = false ; for ( int n = 0 ; n < len ; n++ ) { //=================================================== cp = str.codePointAt ( n ) ; //LOOKING FOR SOME EQUIVALENT IN C # //=================================================== if ( ! escaping ) { ... . //Closing all braces below .,CodePointAt equivalent in c # "C_sharp : Looking at I supplied the exact structure to look for : M/d/yyyy hh : mm : ss ttQuestionIf so , Why should I need to specify CultureInfo also ? DateTime.TryParseExact ( dateString , `` M/d/yyyy hh : mm : ss tt '' , CultureInfo.InvariantCulture , 0 , out dateValue )",Why does TryParseExact require CultureInfo if I specify the exact structure ? "C_sharp : I have a slightly complex requirement of performing some tasks in parallel , and having to wait for some of them to finish before continuing . Now , I am encountering unexpected behavior , when I have a number of tasks , that I want executed in parallel , but inside a ContinueWith handler . I have whipped up a small sample to illustrate the problem : The basic pattern is : - Task 1 should be executed in parallel with Task 2.- Once the first part of part 1 is done , it should do some more things in parallel . I want to complete , once everything is done.I expect the following result : Instead , what happens , is that the await Task.WhenAll ( innerTasks.ToArray ( ) ) ; does not `` block '' the continuation task from completing . So , the inner tasks execute after the outer await Task.WhenAll ( task1 , task2 ) ; has completed . The result is something like : If , instead , I use Task.WaitAll ( innerTasks.ToArray ( ) ) , everything seems to work as expected . Of course , I would not want to use WaitAll , so I wo n't block any threads.My questions are : Why is this unexpected behavior occuring ? How can I remedy the situation without blocking any threads ? Thanks a lot in advance for any pointers ! var task1 = Task.Factory.StartNew ( ( ) = > { Console.WriteLine ( `` 11 '' ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` 12 '' ) ; } ) .ContinueWith ( async t = > { Console.WriteLine ( `` 13 '' ) ; var innerTasks = new List < Task > ( ) ; for ( var i = 0 ; i < 10 ; i++ ) { var j = i ; innerTasks.Add ( Task.Factory.StartNew ( ( ) = > { Console.WriteLine ( `` 1_ '' + j + `` _1 '' ) ; Thread.Sleep ( 500 ) ; Console.WriteLine ( `` 1_ '' + j + `` _2 '' ) ; } ) ) ; } await Task.WhenAll ( innerTasks.ToArray ( ) ) ; //Task.WaitAll ( innerTasks.ToArray ( ) ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` 14 '' ) ; } ) ; var task2 = Task.Factory.StartNew ( ( ) = > { Console.WriteLine ( `` 21 '' ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` 22 '' ) ; } ) .ContinueWith ( t = > { Console.WriteLine ( `` 23 '' ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` 24 '' ) ; } ) ; Console.WriteLine ( `` 1 '' ) ; await Task.WhenAll ( task1 , task2 ) ; Console.WriteLine ( `` 2 '' ) ; 1 < - Start11 / 21 < - The initial task start12 / 22 < - The initial task end13 / 23 < - The continuation task startSome combinations of `` 1_ [ 0..9 ] _ [ 1..2 ] '' and 24 < - the `` inner '' tasks of task 1 + the continuation of task 2 end14 < - The end of the task 1 continuation2 < - The end 1 < - Start11 / 21 < - The initial task start12 / 22 < - The initial task end13 / 23 < - The continuation task startSome combinations of `` 1_ [ 0..9 ] _ [ 1..2 ] '' and 24 < - the `` inner '' tasks of task 1 + the continuation of task 2 end2 < - The endSome more combinations of `` 1_ [ 0..9 ] _ [ 1..2 ] '' < - the `` inner '' tasks of task 114 < - The end of the task 1 continuation",Unexpected behavior with await inside a ContinueWith block "C_sharp : I 'm using ApiController . I struggle to understand why ApiControllers differ from Controllers in certain ways . TakeI 'm accustomed to Controller types which allow me to create method without specifying the legal verbs via Attributes : In the latter case I can perform GET/POST without specifying HttpGetAttribute . I find this behavior confusing for a few reasons : There 's now two HttpGet : System.Web.Http.HttpGet and System.Web.Mvc.HttpGetSystem.Web.Http.HttpGet is required , System.Web.Mvc.HttpGet is not required for GET requestsApiController requests require a unique route /api/controller ... Controller 's allows me to fall into the pit of success . The newer ApiController requires hand holding . I noticed the default template has a syntax that I do n't understand : The verb is the method name along with some funky [ FromBody ] thing going on . Maybe this is why things are setup this way ? What assumptions exist about the usage of ApiController that led to this design ? public class QuestionCommentController : ApiController { QuestionCommentCRUD crud = new QuestionCommentCRUD ( ) ; // GET api/questioncomment/5 [ HttpGet ] public string Read ( int id ) public class QuestionCommentController : Controller { QuestionCommentCRUD crud = new QuestionCommentCRUD ( ) ; // GET questioncomment/5 public string Read ( int id ) public void Post ( [ FromBody ] string value ) { }",Why does ApiController require explicit Http verbs on methods ? C_sharp : I have a XML like following Now what is best way to write each job node in a separate file without bringing the wholefile in to memory using xmlreader and xmlwriter or anyother options ? < Jobs > < job > ... . < /job > < job > ... . < /job > ... . < /Jobs >,Splitting large xml files in to sub files without memory contention C_sharp : Anyone created an open source C # parser for Web Links HTTP `` Link '' header ? See : http : //tools.ietf.org/html/rfc5988.Example : Thanks.Update : Ended up creating my own parser : https : //github.com/JornWildt/Ramone/blob/master/Ramone/Utility/WebLinkParser.cs . Feel free to use it . Link : < http : //example.com/TheBook/chapter2 > ; rel= '' previous '' ; title= '' previous chapter '',A C # parser for Web Links ( RFC 5988 ) "C_sharp : I want to check that an IEnumerable contains exactly one element . This snippet does work : However it 's not very efficient , as Count ( ) will enumerate the entire list . Obviously , knowing a list is empty or contains more than 1 element means it 's not empty . Is there an extension method that has this short-circuiting behaviour ? bool hasOneElement = seq.Count ( ) == 1",How do I ensure a sequence has a certain length ? "C_sharp : In WPF I can specify that a control container is a Focus Scope and that tab navigation should cycle through the controls ( i.e . when I tab out of the final control , focus will return to the first ) : What I am trying to do is to detect when focus leaves the final field . Without knowing precisely the number of controls within the focus scope , does anyone know if this is possible ? < Border FocusManager.IsFocusScope= '' True '' KeyboardNavigation.TabNavigation= '' Cycle '' > < ItemsControl ItemsSource= '' { Binding } '' > < ItemsControl.ItemTemplate > < DataTemplate > < TextBox x : Name= '' Editor '' Text= '' { Binding } '' / > < /DataTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl > < /Border >",Detect WPF focus reaching end of focus scope "C_sharp : I am enumerating printers connected in the PC . I done it using C # System.Printing namespace.It works well . But mostly it shows software printers like Microsoft XPS Document writer , Microsoft Fax etc . I would like to know is it possible to remove these ssoftware printers from enumeration . The code I have done is show below : PrintQueue printQueue = null ; LocalPrintServer localPrintServer = new LocalPrintServer ( ) ; // Retrieving collection of local printer on user machinePrintQueueCollection localPrinterCollection = localPrintServer.GetPrintQueues ( new [ ] { EnumeratedPrintQueueTypes.Local , EnumeratedPrintQueueTypes.Connections } ) ; System.Collections.IEnumerator localPrinterEnumerator = localPrinterCollection.GetEnumerator ( ) ; while ( localPrinterEnumerator.MoveNext ( ) ) { // Get PrintQueue from first available printer printQueue = ( PrintQueue ) localPrinterEnumerator.Current ; if ( ! printQueue.IsOffline ) { MessageBox.Show ( printQueue.FullName.ToString ( ) ) ; string s = `` Printer found `` + printQueue.FullName.ToString ( ) ; listBox1.Items.Add ( s ) ; } else { // No printer exist , return null PrintTicket // return null ; } }",Identify the original printer "C_sharp : The following code in C # ( .Net 3.5 SP1 ) is an infinite loop on my machine : It reached the number 16777216.0 and 16777216.0 + 1 is evaluates to 16777216.0 . Yet at this point : i + 1 ! = i.This is some craziness.I realize there is some inaccuracy in how floating point numbers are stored . And I 've read that whole numbers greater 2^24 than can not be properly stored as a float.Still the code above , should be valid in C # even if the number can not be properly represented.Why does it not work ? You can get the same to happen for double but it takes a very long time . 9007199254740992.0 is the limit for double . for ( float i = 0 ; i < float.MaxValue ; i++ ) ;",C # float infinite loop "C_sharp : I 'm interested in ASP.NET 5 on my Windows and Mac OS machines . To get started , I installed Visual Studio 2015 RC on my Windows machine . I created a new , empty web site for ASP.NET 5 ( aka vNext ) . I updated the template with a Views directory and included the MVC and Static Files nuget packages . I can successfully run this `` Hello World '' app . I also was successful in checking it into GitHub and automatically deploying it to Azure as a Website.Then , I cloned the repository on my Mac OS machine . I successfully ran dnu restore to get the packages . I then ran dnx . run . When I do this , I get an error though . The error is : What am I doing wrong ? I have a Startup.cs file . I know it works based on the fact that it runs on Windows and in Azure . Yet , I ca n't figure out what I 'm missing . My Startup.cs file looks like this : Startup.csWhat did I do wrong ? 'Website ' does not contain a static 'Main ' method suitable for an entry point using Microsoft.AspNet.Builder ; using Microsoft.AspNet.Hosting ; using Microsoft.Framework.ConfigurationModel ; using Microsoft.Framework.DependencyInjection ; namespace Test.Site.Web { public class Startup { public void ConfigureServices ( IServiceCollection services ) { services.AddMvc ( ) ; } public void Configure ( IApplicationBuilder app ) { app.UseErrorPage ( ) ; app.UseStaticFiles ( ) ; app.UseMvc ( routes = > { routes.MapRoute ( `` default '' , `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' } ) ; } ) ; app.UseMvc ( ) ; app.UseWelcomePage ( ) ; } } }",Running ASP.NET 5 Cross-Platform C_sharp : I do write c++ accessor to class member asIt seems that the only protection of this sort in c # is to define property with private ( or undefined ) set . But this protects only against assignments not against manipulation of the some-class state.Side note : c++ allows m_x to be deleted through const pointer - IMHO this is simply amazing oversight of standard bodies . SomeClass const & x ( ) const { return m_x ; },What is c # analog of C++ const reference return value "C_sharp : This might be the worst StackOverflow title I 've ever written . What I 'm actually trying to do is execute an asynchronous method that uses the async/await convention ( and itself contains additional await calls ) from within a synchronous method multiple times in parallel while maintaining the same thread throughout the execution of each branch of the parallel execution , including for all await continuations . To put it another way , I want to execute some async code synchronously , but I want to do it multiple times in parallel . Now you can see why the title was so bad . Perhaps this is best illustrated with some code ... Assume I have the following : The caller is synchronous ( from a console application ) . Let me try illustrating what I 'm trying to do with an attempt to use Task.WaitAll ( ... ) and wrapper tasks : The desired behavior is for MethodA , MethodB , and MethodC to all be run on the same thread , both before and after the continuation , and for this to happen 4 times in parallel on 4 different threads . To put it yet another way , I want to remove the asynchronous behavior of my await calls since I 'm making the calls parallel from the caller.Now , before I go any further , I do understand that there 's a difference between asynchronous code and parallel/multi-threaded code and that the former does n't imply or suggest the latter . I 'm also aware the easiest way to achieve this behavior is to remove the async/await declarations . Unfortunately , I do n't have the option to do this ( it 's in a library ) and there are reasons why I need the continuations to all be on the same thread ( having to do with poor design of said library ) . But even more than that , this has piqued my interest and now I want to know from an academic perspective.I 've attempted to run this using PLINQ and immediate task execution with .AsParallel ( ) .Select ( x = > x.MethodA ( ) .Result ) . I 've also attempted to use the AsyncHelper class found here and there , which really just uses .Unwrap ( ) .GetAwaiter ( ) .GetResult ( ) . I 've also tried some other stuff and I ca n't seem to get the desired behavior . I either end up with all the calls on the same thread ( which obviously is n't parallel ) or end up with the continuations executing on different threads.Is what I 'm trying to do even possible , or are async/await and the TPL just too different ( despite both being based on Tasks ) ? public class MyAsyncCode { async Task MethodA ( ) { // Do some stuff ... await MethodB ( ) ; // Some other stuff } async Task MethodB ( ) { // Do some stuff ... await MethodC ( ) ; // Some other stuff } async Task MethodC ( ) { // Do some stuff ... } } public void MyCallingMethod ( ) { List < Task > tasks = new List < Task > ( ) ; for ( int c = 0 ; c < 4 ; c++ ) { MyAsyncCode asyncCode = new MyAsyncCode ( ) ; tasks.Add ( Task.Run ( ( ) = > asyncCode.MethodA ( ) ) ) ; } Task.WaitAll ( tasks.ToArray ( ) ) ; }",How to execute nested async/await code in parallel while maintaining the same thread on await continuations ? C_sharp : Possible Duplicate : Java equivalent of C # 's verbatim strings with @ An example in C # would be : Another example is the answer to this question . string path = @ '' C : \myfile.txt '' ;,Java equivalent to C # 's @ symbol for escaping \ "C_sharp : BackgroundCurrently , if I want to create a new object in C # or Java , I type something similar to the following : List < int > listOfInts = new List < int > ( ) ; //C # ArrayList < String > data = new ArrayList < String > ( ) ; //JavaC # 3.0 sought to improve conciseness by implementing the following compiler trick : var listofInts = new List < int > ( ) ; QuestionSince the compiler already knows that I want to create a new object of a certain type ( By the fact that I 'm instantiating it without assigning it a null reference or assigning a specific method to instantiate it ) , then why ca n't I do the following ? Follow Up Questions : What are possible pitfalls of this approach . What edge cases could I be missing ? Would there be other ways to shorten instantiation ( without using VB6-esque var ) and still retain meaning ? NOTE : One of the main benefits I see in a feature like this is clarity . Let say var was n't limited . To me it is useless , its going to get the assignment from the right , so why bother ? New ( ) to me actually shortens it an gives meaning . Its a new ( ) whatever you declared , which to me would be clear and concise . //default constructors with no parameters : List < int > listOfInts = new ( ) ; //c # ArrayList < String > data = new ( ) ; //Java",Introducing Brevity Into C # / Java "C_sharp : Is it possible to copy this functionality of offering an abstract method in an enum that inner enum constants must override and provide functionality to ? If it ca n't : :Could you provide a way which I can implement lots of specific logic in a similar manner ? Edit : : I know that enums in C # are not really 'objects ' like they are in Java , but I wish to perform similar logic.Edit : : To clarify , I do not want to provide concrete classes for each specific bit of logic . IE , creating an interface acceptPlayer and creating many new classes is not appropiate public enum Logic { PAY_DAY { @ Override public void acceptPlayer ( Player player ) { // Perform logic } } , COLLECT_CASH { @ Override public void acceptPlayer ( Player player ) { // Perform logic } } , ETC_ETC { @ Override public void acceptPlayer ( Player player ) { // Perform logic } } ; public abstract void acceptPlayer ( Player player ) ; }",Is it possible to mimic this java enum code in c # "C_sharp : I want to read packets from my SslStream.I send the packets using websocket . Also , this function is started after i finished the WS Handshake so it is for reading data frames.This is the function for reading : Once i receive a packet , this is what gets printed out to the console : Can the problem be in this function or is it the Browser which sends the packets ? I use the `` socket.read ( ) '' function in my Websocket Server written in Java and there is no problem , so it must be C # right ? Edit # 1 : Javascript code for sending : byte [ ] buffer = new byte [ 16 * 1024 ] ; int read ; while ( true ) { read = input.Read ( buffer , 0 , buffer.Length ) ; Console.WriteLine ( `` Length : `` + read + `` Buffer : `` + GetNumberOfSlotsUsed ( buffer ) ) ; if ( read < = 0 ) { ... } else if ( read < 3 ) { ... } else { ... } } Length : 1 Buffer : 1Length : 57 Buffer : 57 var socket = new WebSocket ( serviceUrl , protocol ) ; socket.onopen = function ( ) { socket.send ( omeString ) ; }",SslStream .read ( ) returns with first byte once a packet "C_sharp : I mock an interface from which the object is serialized by the tested code by the Newtonsoft JsonConvert.SerializeObject.The serializer throws an exception with the following error : Newtonsoft.Json.JsonSerializationException : Self referencing loop detected for property 'Object ' with type 'Castle.Proxies.IActionProxy ' . Path 'Mock'.Newtonsoft tries to serialized the proxy object IActionProxy , that has a property Mock that loops on that serialized object.Curiously changing serializer options..does not solve the problem , serialization become infiniteThank you for help about this issue , I would be happy to have a way of using Moq in that caseUPDATE : here is a sample code to produce the exception : We have to consider the serialization ( SerializeObject ) is called by the tested code in a library I do n't have access to . ReferenceLoopHandling = ReferenceLoopHandling.Serialize ( ot Ignore ) PreserveReferencesHandling = PreserveReferencesHandling.All Mock < IAction > _actionMock = new Mock < IAction > ( ) .SetupAllProperties ( ) ; Newtonsoft.Json.JsonConvert.SerializeObject ( _actionMock.Object ) ; // JsonSerializationException ( this line is in a method which i 'm not responsible of ) // IAction is any interface with some properties",How to mock ( with Moq ) an interface that is serialized by Newtonsoft.json ? "C_sharp : This only happens on one of my machines . I think it 's an environment configuration problem . All machines run ESET Smart Security software firewall . Any ideas ? using System ; using System.Net ; using System.Diagnostics ; using System.Threading ; namespace Test { static class Program { [ STAThread ] static void Main ( ) { bool exit = false ; WebClient wc = new WebClient ( ) ; DateTime before = DateTime.Now ; wc.DownloadStringAsync ( new Uri ( `` http : //74.125.95.147 '' ) , `` First '' ) ; // IP Address of google , so DNS requests do n't add to time . wc.DownloadStringCompleted += delegate ( object sender , DownloadStringCompletedEventArgs e ) { Debug.WriteLine ( e.UserState + `` Call : `` + ( DateTime.Now - before ) ) ; if ( ( string ) e.UserState == `` First '' ) { before = DateTime.Now ; wc.DownloadStringAsync ( new Uri ( `` http : //74.125.95.147 '' ) , `` Second '' ) ; } else exit = true ; } ; /* * * Output : * * First Call : 00:00:13.7647873 * Second Call : 00:00:00.0740042 * */ while ( ! exit ) Thread.Sleep ( 1000 ) ; } } }",DownloadStringAsync blocks thread for 14 seconds on first call "C_sharp : I 'm converting code from C++ to C # . I have this line : Can I do that in C # ? typedef bool ( *proc ) ( int* , ... ) ;",How to create a `` typedef to a function pointer '' in C # ? "C_sharp : I recently wrote the following code : This works as intended . The same code written with async/await is ( obviously ) simpler : I had a quick look at the generated IL for the 2 versions : the async/await is bigger ( not a surprise ) but I was wondering if the async/await code generator analyses the fact that a continuation is actually synchronous to use TaskContinuationOptions.ExecuteSynchronously where it can ... and I failed to find this in the IL generated code . If anyone knows this or have any clue about it , I 'd be pleased to know ! Task < T > ExecAsync < T > ( string connectionString , SqlCommand cmd , Func < SqlCommand , T > resultBuilder , CancellationToken cancellationToken = default ( CancellationToken ) ) { var tcs = new TaskCompletionSource < T > ( ) ; SqlConnectionProvider p ; try { p = GetProvider ( connectionString ) ; Task < IDisposable > openTask = p.AcquireConnectionAsync ( cmd , cancellationToken ) ; openTask .ContinueWith ( open = > { if ( open.IsFaulted ) tcs.SetException ( open.Exception.InnerExceptions ) ; else if ( open.IsCanceled ) tcs.SetCanceled ( ) ; else { var execTask = cmd.ExecuteNonQueryAsync ( cancellationToken ) ; execTask.ContinueWith ( exec = > { if ( exec.IsFaulted ) tcs.SetException ( exec.Exception.InnerExceptions ) ; else if ( exec.IsCanceled ) tcs.SetCanceled ( ) ; else { try { tcs.SetResult ( resultBuilder ( cmd ) ) ; } catch ( Exception exc ) { tcs.TrySetException ( exc ) ; } } } , TaskContinuationOptions.ExecuteSynchronously ) ; } } ) .ContinueWith ( _ = > { if ( ! openTask.IsFaulted ) openTask.Result.Dispose ( ) ; } , TaskContinuationOptions.ExecuteSynchronously ) ; } catch ( Exception ex ) { tcs.SetException ( ex ) ; } return tcs.Task ; } async Task < T > ExecAsync < T > ( string connectionString , SqlCommand cmd , Func < SqlCommand , T > resultBuilder , CancellationToken cancellationToken = default ( CancellationToken ) ) { SqlConnectionProvider p = GetProvider ( connectionString ) ; using ( IDisposable openTask = await p.AcquireConnectionAsync ( cmd , cancellationToken ) ) { await cmd.ExecuteNonQueryAsync ( cancellationToken ) ; return resultBuilder ( cmd ) ; } }",async/await vs. hand made continuations : is ExecuteSynchronously cleverly used ? "C_sharp : I am trying to wrap my head around the concept of anamorphism . In functional programming , an anamorphism is a generalization of the concept of unfolds on lists . Formally , anamorphisms are generic functions that can corecursively construct a result of a certain type and which is parameterized by functions that determine the next single step of the construction.Its dual , catamorphism , is nicely described in this post : What is a catamorphism and can it be implemented in C # 3.0 ? .A nice example of catamorphic behavior in C # is the LINQ 's Aggregate method.What would an anamorphic equivalent be ? Is it correct to think of a pseudo-random number generator Random as an anamorphic construct or should the process of unfolding always include an accumulator function like the one below ( code snippet taken from Intro to Rx ) ? IEnumerable < T > Unfold < T > ( T seed , Func < T , T > accumulator ) { var nextValue = seed ; while ( true ) { yield return nextValue ; nextValue = accumulator ( nextValue ) ; } }","What is an anamorphism , and how does one look like in C # ?" "C_sharp : We have scenario where external API returns either User XML or Error XML based on whether request succeed or failed.At the moment I 'm passing User POCO to the restsharp and works fine . But if it fails , this object is NULL . And we wo n't know why it failed unless we parse the Error XML manually.Is there a way to workaround this ? e.g.On execution of above method the API can return Error xml object . How do I get Error object on fail and User on success ? var restClient = new RestClient ( baseURL ) ; var request = new RestRequest ( uri ) ; request.Method = Method.POST ; var response = restClient.Execute < User > ( request ) ;",Is it possible to pass 2 types of objects to Restsharp ? "C_sharp : I 'm building my first enterprise grade solution ( at least I 'm attempting to make it enterprise grade ) . I 'm trying to follow best practice design patterns but am starting to worry that I might be going too far with abstraction.I 'm trying to build my asp.net webforms ( in C # ) app as an n-tier application . I 've created a Data Access Layer using an XSD strongly-typed dataset that interfaces with a SQL server backend . I access the DAL through some Business Layer Objects that I 've created on a 1:1 basis to the datatables in the dataset ( eg , a UsersBLL class for the Users datatable in the dataset ) . I 'm doing checks inside the BLL to make sure that data passed to DAL is following the business rules of the application . That 's all well and good . Where I 'm getting stuck though is the point at which I connect the BLL to the presentation layer . For example , my UsersBLL class deals mostly with whole datatables , as it 's interfacing with the DAL . Should I now create a separate `` User '' ( Singular ) class that maps out the properties of a single user , rather than multiple users ? This way I do n't have to do any searching through datatables in the presentation layer , as I could use the properties created in the User class . Or would it be better to somehow try to handle this inside the UsersBLL ? Sorry if this sounds a little complicated ... Below is the code from the UsersBLL : Some guidance in the right direction would be greatly appreciated ! ! Thanks all ! Max using System ; using System.Data ; using PedChallenge.DAL.PedDataSetTableAdapters ; [ System.ComponentModel.DataObject ] public class UsersBLL { private UsersTableAdapter _UsersAdapter = null ; protected UsersTableAdapter Adapter { get { if ( _UsersAdapter == null ) _UsersAdapter = new UsersTableAdapter ( ) ; return _UsersAdapter ; } } [ System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Select , true ) ] public PedChallenge.DAL.PedDataSet.UsersDataTable GetUsers ( ) { return Adapter.GetUsers ( ) ; } [ System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Select , false ) ] public PedChallenge.DAL.PedDataSet.UsersDataTable GetUserByUserID ( int userID ) { return Adapter.GetUserByUserID ( userID ) ; } [ System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Select , false ) ] public PedChallenge.DAL.PedDataSet.UsersDataTable GetUsersByTeamID ( int teamID ) { return Adapter.GetUsersByTeamID ( teamID ) ; } [ System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Select , false ) ] public PedChallenge.DAL.PedDataSet.UsersDataTable GetUsersByEmail ( string Email ) { return Adapter.GetUserByEmail ( Email ) ; } [ System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Insert , true ) ] public bool AddUser ( int ? teamID , string FirstName , string LastName , string Email , string Role , int LocationID ) { // Create a new UsersRow instance PedChallenge.DAL.PedDataSet.UsersDataTable Users = new PedChallenge.DAL.PedDataSet.UsersDataTable ( ) ; PedChallenge.DAL.PedDataSet.UsersRow user = Users.NewUsersRow ( ) ; if ( UserExists ( Users , Email ) == true ) return false ; if ( teamID == null ) user.SetTeamIDNull ( ) ; else user.TeamID = teamID.Value ; user.FirstName = FirstName ; user.LastName = LastName ; user.Email = Email ; user.Role = Role ; user.LocationID = LocationID ; // Add the new user Users.AddUsersRow ( user ) ; int rowsAffected = Adapter.Update ( Users ) ; // Return true if precisely one row was inserted , // otherwise false return rowsAffected == 1 ; } [ System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Update , true ) ] public bool UpdateUser ( int userID , int ? teamID , string FirstName , string LastName , string Email , string Role , int LocationID ) { PedChallenge.DAL.PedDataSet.UsersDataTable Users = Adapter.GetUserByUserID ( userID ) ; if ( Users.Count == 0 ) // no matching record found , return false return false ; PedChallenge.DAL.PedDataSet.UsersRow user = Users [ 0 ] ; if ( teamID == null ) user.SetTeamIDNull ( ) ; else user.TeamID = teamID.Value ; user.FirstName = FirstName ; user.LastName = LastName ; user.Email = Email ; user.Role = Role ; user.LocationID = LocationID ; // Update the product record int rowsAffected = Adapter.Update ( user ) ; // Return true if precisely one row was updated , // otherwise false return rowsAffected == 1 ; } [ System.ComponentModel.DataObjectMethodAttribute ( System.ComponentModel.DataObjectMethodType.Delete , true ) ] public bool DeleteUser ( int userID ) { int rowsAffected = Adapter.Delete ( userID ) ; // Return true if precisely one row was deleted , // otherwise false return rowsAffected == 1 ; } private bool UserExists ( PedChallenge.DAL.PedDataSet.UsersDataTable users , string email ) { // Check if user email already exists foreach ( PedChallenge.DAL.PedDataSet.UsersRow userRow in users ) { if ( userRow.Email == email ) return true ; } return false ; } }",Object oriented n-tier design . Am I abstracting too much ? Or not enough ? "C_sharp : I need to parse fragments of user-written C # code and replace all variables that are n't defined locally with method calls . I.e.has to become : I 'm using Microsoft.CodeAnalysis.CSharp and the CSharpSyntaxTree to examine the string , but it does n't give me enough information to perform the replace . Or if it does , I do n't know where to look for it . I 've pasted the SyntaxTree layout below . All the variables occur as IdentifierName nodes , but I do n't know how to tell different IdentifierNames apart . Where to go from here ? public class Foo { public dynamic Bar ( ) { return Math.Min ( x + width , maxWidth ) ; } } public class Foo { public dynamic Bar ( ) { return Math.Min ( Resolve ( `` x '' ) + Resolve ( `` width '' ) , Resolve ( `` maxWidth '' ) ) ; } } CompilationUnit [ 0..99 ) { code : public class Foo\n { \n public dynamic Bar ( ) \n { \n return Math.Min ( x + width , maxWidth ) ; \n } \n } tokens : EndOfFileToken [ ] nodes { ClassDeclaration [ 0..99 ) { code : public class Foo\n { \n public dynamic Bar ( ) \n { \n return Math.Min ( x + width , maxWidth ) ; \n } \n } tokens : PublicKeyword [ public ] ClassKeyword [ class ] IdentifierToken [ Foo\n ] OpenBraceToken [ { \n ] CloseBraceToken [ } ] nodes { MethodDeclaration [ 21..98 ) { code : public dynamic Bar ( ) \n { \n return Math.Min ( x + width , maxWidth ) ; \n } \n tokens : PublicKeyword [ public ] IdentifierToken [ Bar ] nodes { IdentifierName [ 30..38 ) { code : dynamic tokens : IdentifierToken [ dynamic ] } ParameterList [ 41..45 ) { code : ( ) \n tokens : OpenParenToken [ ( ] CloseParenToken [ ) \n ] } Block [ 45..98 ) { code : { \n return Math.Min ( x + width , maxWidth ) ; \n } \n tokens : OpenBraceToken [ { \n ] CloseBraceToken [ } \n ] nodes { ReturnStatement [ 50..93 ) { code : return Math.Min ( x + width , maxWidth ) ; \n tokens : ReturnKeyword [ return ] SemicolonToken [ ; \n ] nodes { InvocationExpression [ 61..90 ) { code : Math.Min ( x + width , maxWidth ) nodes { SimpleMemberAccessExpression [ 61..69 ) { code : Math.Min tokens : DotToken [ . ] nodes { IdentifierName [ 61..65 ) { code : Math tokens : IdentifierToken [ Math ] } IdentifierName [ 66..69 ) { code : Min tokens : IdentifierToken [ Min ] } } } ArgumentList [ 69..90 ) { code : ( x + width , maxWidth ) tokens : OpenParenToken [ ( ] CommaToken [ , ] CloseParenToken [ ) ] nodes { Argument [ 70..79 ) { code : x + width nodes { AddExpression [ 70..79 ) { code : x + width tokens : PlusToken [ + ] nodes { IdentifierName [ 70..72 ) { code : x tokens : IdentifierToken [ x ] } IdentifierName [ 74..79 ) { code : width tokens : IdentifierToken [ width ] } } } } } Argument [ 81..89 ) { code : maxWidth nodes { IdentifierName [ 81..89 ) { code : maxWidth tokens : IdentifierToken [ maxWidth ] } } } } } } } } } } } } } } } } }",Replace all variables in C # code with methods "C_sharp : Experiencing some unexpected performance from Microsoft ImmutableList from NuGet package Microsoft.Bcl.Immutable version 1.0.34 and also 1.1.22-betaWhen removing items from the immutable list the performance is very slow.For an ImmutableList containing 20000 integer values ( 1 ... 20000 ) if starting to remove from value 20000 to 1 it takes about 52 seconds to remove all items from the list.If I do the same with a generic List < T > where I create a copy of the list after each remove operation it takes about 500 ms.I was a bit surprised by these results since I thought the ImmutableList would be faster than copying a generic List < T > , but perhaps this is to be expected ? Example CodeUpdateIf removing items from the start of the ImmutableList , like with a normal foreach loop , then performance is a lot better . Removing all items then takes less than 100 ms.This is not something you can do in all scenarios , but can be good to know . // Generic List Testvar genericList = new List < int > ( ) ; var sw = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < 20000 ; i++ ) { genericList.Add ( i ) ; genericList = new List < int > ( genericList ) ; } sw.Stop ( ) ; Console.WriteLine ( `` Add duration for List < T > : `` + sw.ElapsedMilliseconds ) ; IList < int > completeList = new List < int > ( genericList ) ; sw.Restart ( ) ; // Remove from 20000 - > 0.for ( int i = completeList.Count - 1 ; i > = 0 ; i -- ) { genericList.Remove ( completeList [ i ] ) ; genericList = new List < int > ( genericList ) ; } sw.Stop ( ) ; Console.WriteLine ( `` Remove duration for List < T > : `` + sw.ElapsedMilliseconds ) ; Console.WriteLine ( `` Items after remove for List < T > : `` + genericList.Count ) ; // ImmutableList Testvar immutableList = ImmutableList < int > .Empty ; sw.Restart ( ) ; for ( int i = 0 ; i < 20000 ; i++ ) { immutableList = immutableList.Add ( i ) ; } sw.Stop ( ) ; Console.WriteLine ( `` Add duration for ImmutableList < T > : `` + sw.ElapsedMilliseconds ) ; sw.Restart ( ) ; // Remove from 20000 - > 0.for ( int i = completeList.Count - 1 ; i > = 0 ; i -- ) { immutableList = immutableList.Remove ( completeList [ i ] ) ; } sw.Stop ( ) ; Console.WriteLine ( `` Remove duration for ImmutableList < T > : `` + sw.ElapsedMilliseconds ) ; Console.WriteLine ( `` Items after remove for ImmutableList < T > : `` + immutableList.Count ) ;",Slow performance from ImmutableList < T > Remove method in Microsoft.Bcl.Immutable "C_sharp : I was looking at the implemention of and I 'm struggling to grasp how it works . Lets says that TEventHandler is the standard : then the code that is puzzling me is : ( n.b I 've specialised this generic code to this specific example instance . ) How is it that CreateDelegate is creating a delegate of signature ( obj , args ) that is bound to an invoke method of signature ( args ) on the action ? Where is obj going ? It feels a bit like it might be around having an open delegate on action and we are coercing the 'this ' to be 'firstArguemnt ' from CreateDelegate and allowing the args to fall through . If so feels kinda dirty ? Observable.FromEvent < TEventHandler , TEventHandlerArgs > ( add , remove ) public delegate void EventHandler ( object sender , EventArgs e ) ; TEventHandler d = ( TEventHandler ) Delegate.CreateDelegate ( typeof ( TEventHandler ) , ( object ) new Action < EventArgs > ( observer.OnNext ) , typeof ( Action < EventArgs > ) .GetMethod ( `` Invoke '' ) ) ;",Observable.FromEvent & CreateDelegate param mapping "C_sharp : I 've added a LineTransformerClass that is derived from DocumentColorizingTransformer to the TextEditor : Is there any programmatic way of invoking invalidation on the Linetransformer ? I 've readily assumed that since it is added to the textview , the following should work : But they do n't . Just in case , I 've tried the following as well : TxtEditCodeViewer.TextArea.TextView.LineTransformers.Add ( new ColorizeAvalonEdit ( ) ) ; TxtEditCodeViewer.TextArea.TextView.InvalidateVisual ( ) ; TxtEditCodeViewer.TextArea.TextView.InvalidateArrange ( ) ; TxtEditCodeViewer.TextArea.TextView.InvalidateMeasure ( ) ; //TxtEditCodeViewer.TextArea.TextView.InvalidateVisual ( ) ; //TxtEditCodeViewer.TextArea.TextView.InvalidateArrange ( ) ; //TxtEditCodeViewer.TextArea.TextView.InvalidateMeasure ( ) ; //TxtEditCodeViewer.InvalidateVisual ( ) ; //TxtEditCodeViewer.InvalidateArrange ( ) ; //TxtEditCodeViewer.InvalidateMeasure ( ) ; //TxtEditCodeViewer.TextArea.InvalidateArrange ( ) ; //TxtEditCodeViewer.TextArea.InvalidateMeasure ( ) ; //TxtEditCodeViewer.TextArea.InvalidateVisual ( ) ;",Avalonedit How to invalidate Line Transformers "C_sharp : I am trying to localize responses of my web api.I created a Resource file ( Messges.resx ) in my project containing all the strings that are localized . And using Accept-Language header to identify user 's language.In the responses I can set the string as : which will get the string for that name in language of the current thread culture . I will have to change thread 's current culture to the culture found from Accept-Language header . But I do n't want to change the culture of the thread since this will also change number/date formatting which is problematic for me.Another alternative I see is- using ResourceManager and passing the culture as-This way I wo n't have to change the culture of the thread . But the problem with this approach is- string names are n't type safe anymore . A typo in the string name passed to GetString ( ) may result into null values returned.Is there any other approach I can adopt to avoid both the problems above ? response = Messages.KEY_GOOD_MORNING Messages.ResourceManager.GetString ( `` KEY_GOOD_MORNING '' , CultureInfo.CreateSpecificCulture ( lang.value ) )",How to safely get localized string in Web Api Controllers ? "C_sharp : Does anybody know how to use xUnit with `` Theory '' and `` InlineData '' with enum values ? This here is leading to the tests not being recognized as tests and not run : The tests work and run if I use the int values of the enum instead of the enum values . [ Theory ] [ InlineData ( `` 12h '' , 12 , PeriodUnit.Hour ) ] [ InlineData ( `` 3d '' , 3 , PeriodUnit.Day ) ] [ InlineData ( `` 1m '' , 1 , PeriodUnit.Month ) ] public void ShouldParsePeriod ( string periodString , int value , PeriodUnit periodUnit ) { var period = Period.Parse ( periodString ) ; period.Value.Should ( ) .Be ( value ) ; period.PeriodUnit.Should ( ) .Be ( periodUnit ) ; }",.NET Core 2.2 : xUnit Theory Inlinedata not working with enum values "C_sharp : In my MVC3 application I have a custom controller factory that has CreateController ( ) method working as follows : the problem is host is null sometimes - I see NullReferenceException for some requests and the exception stack trace points exactly at that line.Why would null be retrieved here ? How do I handle such cases ? public IController CreateController ( RequestContext requestContext , string controllerName ) { string host = requestContext.HttpContext.Request.Headers [ `` Host '' ] ; if ( ! host.EndsWith ( SomeHardcodedString ) ) { // FAILS HERE //some special action } //proceed with controller creation }",Why would HttpContext not contain a `` Host '' header ? "C_sharp : I have two paths : And I want to detect if the both paths are the same.I want it because I 'm trying to move one file to another directory.So for the paths above , an exception is thrown.I know I can use try and catch , but there is another way ? I thought about removing d $ \Main from the second path and then compare , but it 's not always true..Any help appreciated ! \\10.11.11.130\FileServer\Folder2\Folder3\\\10.11.11.130\d $ \Main\FileServer\Folder2\Folder3\",Detect if two paths are the same "C_sharp : I 'm trying to plot a histogram using the C # .NET Chart control ( System.Windows.Forms.DataVisualization.Charting ) . I have it set up as a Column chart . The data is retrieved via a Histogram object using the NMath libraries , so it does all the sorting into bins and such . Everything looks fine until I switch the y axis to a log scale . To get things to even show up , I set the DataPoint of any bin with 0 entries to have a y-value of 0.001 instead of 0 . I then set the minimum of the y axis to 0.1 and the max to something beyond the biggest bin . The result is that all of the columns start at a y-value of 1 instead of at the minimum . Any bin with 0 entries has a column which extends downward ( toward the 0.001 ) . Screenshot available hereThe code which sets the min/max/intervals on the axis is below.I 'm probably not setting a property on the axis I need to , but is there a way to have the columns all extend upward from the minimum on the y axis , even if that minimum is less than 1 ? ETA : If I remove the DataPoints with 0 counts from the Series , I no longer get the downward bars between 0.1 and 1 . But , all the other bars still start at 1 and go upwards , instead of starting at the minimum.ETA again : I 'm thinking I could use a RangeColumn type of chart , and specify the min and max y values for each bin . That does n't seem very elegant , as I 'll need to change between RangeColumn and Column type when the user switches the axis to log mode and back , or keep adjusting the minimum y value of the RangeColumn data points ( from 0 to 0.1 and back ) . And that seems like more of a workaround and not a solution . double ymin = FindMinimumYValue ( ) ; double mag = Math.Floor ( Math.Log10 ( ymin ) ) ; ymin = Math.Pow ( 10 , mag ) ; yAxis.Minimum = ymin ; double ymax = FindMaximumYValue ( ) ; mag = Math.Ceiling ( Math.Log10 ( ymax ) ) ; ymax = Math.Pow ( 10 , mag ) ; yAxis.Maximum = ymax ; yAxis.Interval = 1 ; yAxis.MajorGrid.Interval = 1 ; yAxis.MajorTickMark.Interval = 1 ; yAxis.MinorGrid.Interval = 1 ; yAxis.MinorTickMark.Interval = 1 ;",Histogram / column chart not showing bars all the way to the bottom "C_sharp : I have binary serialized objects in database . They are serialized with protobuf.Now I need to generate some viewer to see the content of Database.So , i read stream from database and deserialized it back to the objects.It works and the result is list of objects : Now , I would like to save this list of objects to file to see the content of database . I thought it would be the best to save it to xml . So , i have tried : But i get an error : Can not deserialize type 'My.Entities.IdBase ' because it contains property 'Key ' which has no public setter.What now ? I ca n't change the class definitions to have setters . Should i save objects to json or plain text instead ? Or should i extract all properties and values and save it to some xml ? Any code example ? var dbData = readData ( someType ) ; //it is IList collection var serializer = new XmlSerializer ( dbData.GetType ( ) ) ;",Can not deserialize type without setter "C_sharp : I have a weird problem when I 'm trying to cast an object via an extension method . I have a class where I wrap some functionality around an IPAddress.I do n't like the look of all the parenthesis to extract the IPAddress out of the object : I 'd rather be able to do something like this : In order to do this I wrote the following Extension Method : Unfortunately with this I 'm getting an InvalidCastException : I understand that in this particular case I could simply expose the IPAddress with a getter , but we also have more complex explicit casts that I would like to do this with.EDITThanks to Chris Sinclair 's comment on using dynamic I have updated the extension method to look like : There is some overhead with using dynamic , but it is more than fast enough for my needs . It also seems to work with all the basic type casting I 've tried . // Dumbed down version of classpublic sealed class PrefixLengthIPAddress { public static explicit operator IPAddress ( PrefixLengthIPAddress address ) { return ( address ! = null ) ? address._address : null ; } public PrefixLengthIPAddress ( IPAddress address ) { _address = address ; _length = address.GetLength ( ) ; } private readonly ushort _length ; private readonly IPAddress _address ; } var family = ( ( IPAddress ) prefixLengthAddress ) .AddressFamily ; var family = prefixLengthAddress.CastAs < IPAddress > ( ) .AddressFamily ; public static T CastAs < T > ( this object value ) where T : class { return ( T ) value ; } var family = ( ( IPAddress ) prefixLengthAddress ) .AddressFamily ; // Worksvar family = prefixLengthAddress.CastAs < IPAddress > ( ) .AddressFamily ; // InvalidCastException public static T CastAs < T > ( this object value ) { return ( T ) ( ( dynamic ) value ) ; }",Using Explicit Cast in an Extension Method "C_sharp : My goal is to detect discrete GPU on multi-gpu systems ( for example integrated Intel HD Graphics + discrete AMD Radeon card ) with C # I 've usually use that code : It works like a charm for my example , described above . But it 's not suitable for AMD , VIA , etc ( I do n't know exactly all manufacturers ) integrated cards.So is there universal approach to cut off all integrated GPUs ? String gpuName = String.Empty ; ManagementObjectCollection objectCollection = new ManagementObjectSearcher ( `` SELECT Name FROM Win32_VideoController '' ) .Get ( ) ; foreach ( ManagementObject managementObject in objectCollection ) { foreach ( PropertyData propertyData in managementObject.Properties ) { if ( ( gpuName == String.Empty ) || ( propertyData.Value.ToString ( ) .ToLower ( ) .IndexOf ( `` intel '' ) == -1 ) ) { gpuName = propertyData.Value.ToString ( ) ; break ; } } }",Detect discrete GPU "C_sharp : I am having a problem with different appearance in Blend/VS2012 IDE and in Debugging.In IDE , the Rectangle is at the center , but when it is compiled or debugged , the size of the margin is different . In my view , this occurs because the size of the window border is different . I really want to fix this problem . Any suggestions ? Thank You.XAMLEdited XAML code : Result is the same . Is this problem of my PC ? < Window x : Class= '' WpfApplication2.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 202 '' Width= '' 194 '' > < Grid HorizontalAlignment= '' Left '' Height= '' 171 '' VerticalAlignment= '' Top '' Width= '' 186 '' > < Rectangle Fill= '' # FFF4F4F5 '' HorizontalAlignment= '' Left '' Height= '' 151 '' Margin= '' 10,10,0,0 '' Stroke= '' Black '' VerticalAlignment= '' Top '' Width= '' 166 '' / > < /Grid > < Window x : Class= '' WpfApplication2.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 202 '' Width= '' 194 '' > < Grid HorizontalAlignment= '' Left '' Height= '' 171 '' VerticalAlignment= '' Top '' Width= '' 186 '' > < Rectangle Fill= '' # FFF4F4F5 '' HorizontalAlignment= '' Center '' Height= '' 151 '' Margin= '' 10 '' Stroke= '' Black '' VerticalAlignment= '' Center '' Width= '' 166 '' / > < /Grid >",C # WPF different size from IDE after debugging ? "C_sharp : I 'm aware that a params modifier ( which turns in one parameter of array type into a so-called `` parameter array '' ) is specifically not a part of the method signature . Now consider this example : This compiles with no warnings . Then saying : gives an error ( No overload for method 'Eat ' takes 3 arguments ) . Now , I know that the compiler translates the params modifier into an application of the System.ParamArrayAttribute onto the parameter in question . In general there 's no problem in applying one collection of attributes to a parameter of a virtual method , and then decorating the `` corresponding '' parameter in an overriding method in a derived class with a different set of attributes.Yet the compiler chooses to ignore my params keyword silently . Conversely , if one makes it the other way round , and applies params to the parameter in the base class Giraffid , and then omits the keyword in the override in Okapi , the compiler chooses to decorate both methods with the System.ParamArrayAttribute . I verified these things with IL DASM , of course.My question : Is this documented behavior ? I have searched thoroughly through the C # Language Specification without finding any mention of this.I can say that at least the Visual Studio development environment is confused about this . When typing the 2 , 4 , 6 in the above method call , the intellisense shows me void Okapi.Eat ( params int [ ] leaves ) in a tip.For comparision , I also tried implementing an interface method and changing the presence/absence of params in interface and implementing class , and I tried defining a delegate type and changing params or not in either the delegate type definition or the method whose method group I assigned to a variable of my delegate type . In these cases it was perfectly possible to change params-ness . class Giraffid { public virtual void Eat ( int [ ] leaves ) { Console.WriteLine ( `` G '' ) ; } } class Okapi : Giraffid { public override void Eat ( params int [ ] leaves ) { Console.WriteLine ( `` O '' ) ; } } var okapi = new Okapi ( ) ; okapi.Eat ( 2 , 4 , 6 ) ; // will not compile !",Changing the params modifier in a method override "C_sharp : Before beginning this question , I should point out that my knowledge of ASP.NET & C # is pretty much nil.I 'm in the process of trying to integrate the ASP.NET version of CKFinder v3 into a site built in a different language and all is going well so far ; I have everything setup as I want it and it 's working when I grant unrestricted access to CKF but I 'm stuck at the point now of trying to restrict access to it by authenticating only certain members of my site to use it . All the pages that CKFinder appears on on my site are only accessible by those certain members but I need an extra level of security if , for example , anyone figures out the direct path to my `` ckfinder.html '' file.In the ASP version of CKFinder , I simply added this line in the function that checks my member 's privileges , where isEditor was a boolean whose value was assigned per member based on information from my database : and then edited the CheckAuthentication ( ) function in CKFinder 's `` config.asp '' file to read : Reading through this `` Howto '' , authentication seems to be much more complex in v3 but , after a lot of trial and error and some help from Lesiman , I created this C # file , which is located in my CKF directory : Loading that page produces no errors ( which does n't necessarily mean it 's working as trying to write anything to screen from within the public class does n't work , for some reason ) so now I 'm at the stage of somehow checking that file for authentication.Originally , I had tried loading it via XMLHttp from within my function that checks membership privileges for the site but , as I suspected and as Lesmian confirmed , that would n't work . After more trial & error , I added code to check website member privileges to the C # file , which leads me to where I am now : stuck ! What do I need to edit within CKFinder in order to have it use this custom file to check whether or not a user is authenticated ? session ( `` accessckf '' ) =isEditor function CheckAuthentication ( ) CheckAuthentication=session ( `` accessckf '' ) end function < % @ page codepage= '' 65001 '' debug= '' true '' language= '' c # '' lcid= '' 6153 '' % > < % @ import namespace= '' CKSource.CKFinder.Connector.Core '' % > < % @ import namespace= '' CKSource.CKFinder.Connector.Core.Authentication '' % > < % @ import namespace= '' CKSource.CKFinder.Connector.Core.Builders '' % > < % @ import namespace= '' CKSource.CKFinder.Connector.Host.Owin '' % > < % @ import namespace= '' Owin '' % > < % @ import namespace= '' System.Data.Odbc '' % > < % @ import namespace= '' System.Threading '' % > < % @ import namespace= '' System.Threading.Tasks '' % > < script runat= '' server '' > public void Configuration ( IAppBuilder appBuilder ) { var connectorBuilder=ConfigureConnector ( ) ; var connector=connectorBuilder.Build ( new OwinConnectorFactory ( ) ) ; appBuilder.Map ( `` /path/to/connector '' , builder= > builder.UseConnector ( connector ) ) ; } public ConnectorBuilder ConfigureConnector ( ) { var connectorBuilder=new ConnectorBuilder ( ) ; connectorBuilder.SetAuthenticator ( new MyAuthenticator ( ) ) ; return connectorBuilder ; } public class MyAuthenticator : IAuthenticator { public Task < IUser > AuthenticateAsync ( ICommandRequest commandRequest , CancellationToken cancellationToken ) { var domain=HttpContext.Current.Request.Url.Host ; var cookie=HttpContext.Current.Request.Cookies [ urlDomain ] ; var password= '' '' ; var username= '' '' ; var user=new User ( false , null ) ; if ( cookie ! =null ) { if ( cookie [ `` username '' ] ! =null ) username=cookie [ `` username '' ] ; if ( cookie [ `` password '' ] ! =null ) password=cookie [ `` password '' ] ; if ( username ! = '' '' & & password ! = '' '' ) { var connection=new OdbcConnection ( `` database= [ database ] ; driver=MySQL ; pwd= [ pwd ] ; server= [ server ] ; uid= [ uid ] ; '' ) ; connection.Open ( ) ; OdbcDataReader records=new OdbcCommand ( `` SELECT ISEDITOR FROM MEMBERS WHERE USERNAME= ' '' +username+ '' ' AND PASSWORD= ' '' +password+ '' ' '' , connection ) .ExecuteReader ( ) ; if ( records.HasRows ) { records.Read ( ) ; bool isEditor=records.GetString ( 0 ) == '' 1 '' ; var roles= '' member '' ; if ( isEditor ) roles= '' editor , member '' ; user=new User ( isEditor , roles.Split ( ' , ' ) ) ; } records.Close ( ) ; connection.Close ( ) ; } } return Task.FromResult ( ( IUser ) user ) ; } } < /script >",Authenticating Website Members as Users in CKFinder v3 "C_sharp : This piece of code worked perfectly in VS 2010 . Now that I have VS 2013 it no longer writes to the file . It does n't error or anything . ( I get an alert in Notepad++ stating that the file has been updated , but there is nothing written . ) It all looks fine to me . Any Ideas ? using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.IO ; namespace ConsoleApplication2 { class Program { static void Main ( string [ ] args ) { String line ; try { //Pass the file path and file name to the StreamReader constructor StreamReader sr = new StreamReader ( `` C : \\Temp1\\test1.txt '' ) ; StreamWriter sw = new StreamWriter ( `` C : \\Temp2\\test2.txt '' ) ; //Read the first line of text line = sr.ReadLine ( ) ; //Continue to read until you reach end of file while ( line ! = null ) { //write the line to console window Console.WriteLine ( line ) ; int myVal = 3 ; for ( int i = 0 ; i < myVal ; i++ ) { Console.WriteLine ( line ) ; sw.WriteLine ( line ) ; } //Write to the other file sw.WriteLine ( line ) ; //Read the next line line = sr.ReadLine ( ) ; } //close the file sr.Close ( ) ; Console.ReadLine ( ) ; } catch ( Exception e ) { Console.WriteLine ( `` Exception : `` + e.Message ) ; } finally { Console.WriteLine ( `` Executing finally block . `` ) ; } } } }",StreamWriter Not working in C # "C_sharp : the situation I 'm in is following : I have an interpolated string looking like this : And a format that should be used on it in : Now I 'd like to use the format in the property Format in the interpolated string , but I do n't know how.I.E : i 'd like something like this to be the result : Could someone help ? DateTime DateOfSmth ; string PlaceOfSmth ; $ '' { DateOfSmth } , { PlaceOfSmth } '' .Trim ( ' ' , ' , ' ) ; string Format = `` { 0 : dd.MM.yyyy } '' ; $ '' { DateOfSmth : Format } , { PlaceOfSmth } '' .Trim ( ' ' , ' , ' ) ;",use format string from a property C_sharp : I just learned the hard way that IntPtr.Zero can not be compared to default ( IntPtr ) . Can someone tell me why ? IntPtr.Zero == new IntPtr ( 0 ) - > `` could not evaluate expression '' IntPtr.Zero == default ( IntPtr ) -- > `` could not evaluate expression '' IntPtr.Zero == ( IntPtr ) 0 - > `` could not evaluate expression '' IntPtr.Zero.Equals ( IntPtr.Zero ) -- > `` Enum value was out of legal range '' exceptionIntPtr.Zero.Equals ( default ( IntPtr ) ) -- > `` Enum value was out of legal range '' exceptionIntPtr.Zero == IntPtr.Zero -- > truenew IntPtr ( 0 ) == new IntPtr ( 0 ) -- > true,why is it not possible to compare IntPtr.Zero and default ( IntPtr ) ? "C_sharp : I have a Windows Form with data bound textBox which displays a phone number formated like this : ( 800 ) 555-5555 . The data is stored as decimal and then I display it in the correct format . The problem though is when I click into the textBox and then click on somthing else it changes from ( 800 ) 555-5555 back to 8005555555 . The formating is lost . I tried reformating the digits again on the textBox leave event but that does n't work . What could be causing this ? vs 2010 c # to Format first I do thisthen i do this private string FormatCustPhoneBox ( string a ) { string phone = a ; for ( int j = 0 ; j < phone.Length ; j++ ) { if ( ! Char.IsDigit ( phone , j ) ) { phone = phone.Remove ( j , 1 ) ; //Remove any non numeric chars . j -- ; } } return phone ; } private void FormatPhoneNum ( ) { decimal iPhone = decimal.Parse ( CustomerPhone1Box.Text ) ; CustomerPhone1Box.Text = string.Format ( `` { 0 : ( # # # ) # # # - # # # # } '' , iPhone ) ; }",TextBox formatting lost when focus changes C_sharp : I have a below classI have a query string like `` my location_Locations/new york_City/city street_Address/200_MaxRecord/20_PageSize '' Above string contains the exact property names of the class SearchModel . Now I want to do something like below : - public class SearchModel { public string Locations { get ; set ; } public string City { get ; set ; } public string Address { get ; set ; } public string MaxRecord { get ; set ; } public string PageSize { get ; set ; } ... . ... . Approx 80 properties } SearchModel model = new SearchModel ( ) ; string [ ] Parameters = `` my location_Locations/new york_City/city street_Address/200_MaxRecord/20_PageSize '' .Split ( '/ ' ) ; foreach ( string item in Parameters ) { string [ ] value=item.Split ( ' _ ' ) ; model.value [ 1 ] = value [ 0 ] ; },Bind object properties with string dynamically "C_sharp : I have an application with two classes , A and B . The class A has inside a reference to class B . The destructors of the classes do some cleanup of resources but they have to be called in the right order , first the destructor of A and then the destructor of B . What is happening is that somehow the destructor of B is called first and then the destructor of A is crashing because is trying to execute methods from a disposed object.Is this behavior of the GC correct ? I expected the GC to detect that A has a reference to B and then call the A destructor first . Am I right ? Thanks mates ! PD : In case of doubt about destructor/finalizer/disposer etc that 's what we have : ~A ( ) { this.Dispose ( ) ; } ~B ( ) { this.Dispose ( ) ; }",Why garbage collector takes objects in the wrong order ? "C_sharp : I have a CustomAuthorize attribute that checks to see if a user has access to functionality ( a user or role can be associated with items from a hierarchical set of functions ) .For a given action method ... This works but I 'm concerned that changes to the Security object could cause problems that wo n't be detected until run-time . I realize that I can write unit tests to mitigate this risk but I would like to know if it is possible to check the attribute parameter at compile time . I also like having Intellisense help me type this expression.Ideally , I could pass a lambda expression.Unfortunately this is not currently possible ( additional info from Microsoft ) .I also tried encapsulating the expression hoping it would be evaluated and then passed to the attribute as a string , but this also failed to compile with the same error ( Expression can not contain anonymous methods or lambda expressions ) .How can I add some design-time / build-time support for my custom attribute parameters ? [ CustomAuthorize ( `` Security.Admin.ManageWidgets.Update '' ) ] [ CustomAuthorize ( i = > i.Admin.ManageWidgets.Update ) ] [ CustomAuthorize ( LambdaToString ( i = > i.Admin.ManageWidgets.Update ) ) ]",Checking custom attribute parameters at design/build time "C_sharp : I wonder if this is too a broad question , but recently I made myself to come across a piece of code I 'd like to be certain on how to translate from C # into proper F # . The journey starts from here ( 1 ) ( the original problem with TPL-F # interaction ) , and continues here ( 2 ) ( some example code I 'm contemplating to translate into F # ) .The example code is too long to reproduce here , but the interesting functions are ActivateAsync , RefreshHubs and AddHub . Particularly the interesting points are AddHub has a signature of private async Task AddHub ( string address ) .RefreshHubs calls AddHub in a loop and collects a list of tasks , which it then awaits in the very end by await Task.WhenAll ( tasks ) and consequently the return value matches its signature of private async Task RefreshHubs ( object _ ) .RefreshHubs is called by ActivateAsync just as await RefreshHubs ( null ) and then in the end there 's a call await base.ActivateAsync ( ) matching the function signature public override async Task ActivateAsync ( ) .Question : What would be the correct translation of such function signatures to F # that still maintains the interface and functionality and respects the default , custom scheduler ? And I 'm not otherwise too sure of this `` async/await in F # '' either . As in how to do it `` mechanically '' . : ) The reason is that in the link `` here ( 1 ) '' there seem to be problem ( I have n't verified this ) in that F # async operations do not respect a custom , cooperative scheduler set by the ( Orleans ) runtime . Also , it 's stated here that TPL operations escape the scheduler and go to the task pool and their use is therefore prohibited.One way I can think of dealing with this is with a F # function as followsThe startAsPlainTask function is by Sacha Barber from here . Another interesting option could be here as < edit : I just noticed the Task.WhenAll would need to be awaited too . But what would be the proper way ? Uh , time to sleep ( a bad pun ) ... < edit 2 : At here ( 1 ) ( the original problem with TPL-F # interaction ) in Codeplex it was mentioned that F # uses synchronization contexts to push work to threads , whereas TPL does not . Now , this is a plausible explanation , I feel ( although I 'd still have problems in translating these snippets properly regardless of the custom scheduler ) . Some interesting additional information could be to had fromHow to get a Task that uses SynchronizationContext ? And how are SynchronizationContext used anyway ? Await , SynchronizationContext , and Console Apps wherein an example SingleThreadSynchronizationContext is provided that looks like queues the work to be executed . Maybe this ought to be used ? I think I need to mention Hopac in this context , as an interesting tangential and also mention I 'm out of reach for the next 50 odd hours or so in case all my cross-postings go out of hand. < edit 3 : Daniel and svick give good advice in the comments to use a custom task builder . Daniel provides a link to a one that 's already defined in FSharpx.Looking at the the source I see the interface with the parameters are defined as If one were to use this in Orleans , it looks like the TaskScheduler ought to be TaskScheduler.Current as per documentation here Orleans has it 's own task scheduler which provides the single threaded execution model used within grains . It 's important that when running tasks the Orleans scheduler is used , and not the .NET thread pool . Should your grain code require a subtask to be created , you should use Task.Factory.StartNew : await Task.Factory.StartNew ( ( ) = > { /* logic */ } ) ; This technique will use the current task scheduler , which will be the Orleans scheduler . You should avoid using Task.Run , which always uses the .NET thread pool , and therefore will not run in the single-threaded execution model.It looks there 's a subtle difference between TaskScheduler.Current and TaskScheduler.Default . Maybe this warrants a question on in which example cases there 'll be an undesired difference . As the Orleans documentation points out not to use Task.Run and instead guides to Task.Factory.StartNew , I wonder if one ought to define TaskCreationOptions.DenyAttachChild as is recommended by such authorities as Stephen Toub at Task.Run vs Task.Factory.StartNew and Stephen Cleary at StartNew is Dangerous . Hmm , it looks like the .Default will be .DenyAttachChilld unless I 'm mistaken.Moreover , as there is a problem with Task.Run viz Task.Factory.CreateNew regarding the custom scheduler , I wonder if this particular problem could be removed by using a custom TaskFactory as explained in Task Scheduler ( Task.Factory ) and controlling the number of threads and How to : Create a Task Scheduler That Limits Concurrency.Hmm , this is becoming quite a long `` pondering '' already . I wonder how should I close this ? Maybe if svick and Daniel could make their comments as answers and I 'd upvote both and accept svick 's ? //Sorry for the inconvenience of shorterned code , for context see the link `` here ( 1 ) '' ... override this.ActivateAsync ( ) = this.RegisterTimer ( new Func < obj , Task > ( this.FlushQueue ) , null , TimeSpan.FromMilliseconds ( 100.0 ) , TimeSpan.FromMilliseconds ( 100.0 ) ) | > ignore if RoleEnvironment.IsAvailable then this.RefreshHubs ( null ) | > Async.awaitPlainTask | > Async.RunSynchronously else this.AddHub ( `` http : //localhost:48777/ '' ) | > Async.awaitPlainTask | > Async.RunSynchronously //Return value comes from here . base.ActivateAsync ( ) member private this.RefreshHubs ( _ ) = //Code omitted , in case mor context is needed , take a look at the link `` here ( 2 ) '' , sorry for the inconvinience ... //The return value is Task . //In the C # version the AddHub provided tasks are collected and then the //on the last line there is return await Task.WhenAll ( newHubAdditionTasks ) newHubs | > Array.map ( fun i - > this.AddHub ( i ) ) | > Task.WhenAllmember private this.AddHub ( address ) = //Code omitted , in case mor context is needed , take a look at the link `` here ( 2 ) '' , sorry for the inconvinience ... //In the C # version : // ... //hubs.Add ( address , new Tuple < HubConnection , IHubProxy > ( hubConnection , hub ) ) // } //so this is `` void '' and could perhaps be Async < void > in F # ... //The return value is Task . hubConnection.Start ( ) | > Async.awaitTaskVoid | > Async.RunSynchronously TaskDone.Done module Async = let AwaitTaskVoid : ( Task - > Async < unit > ) = Async.AwaitIAsyncResult > > Async.Ignore type TaskBuilder ( ? continuationOptions , ? scheduler , ? cancellationToken ) = let contOptions = defaultArg continuationOptions TaskContinuationOptions.None let scheduler = defaultArg scheduler TaskScheduler.Default let cancellationToken = defaultArg cancellationToken CancellationToken.None",Translating async-await C # code to F # with respect to the scheduler "C_sharp : For our new Windows 10 application ( C # + XAML ) we are using the new https : //github.com/Microsoft/winsdkfb/ login , however since we have migrated to this login I am having no luck with facebook login.We are using FBResult result = await sess.LoginAsync ( permissions ) ; and I am getting this error all the time : `` Not Logged In : You are not logged in . Please login and try again . `` My code is litteraly a copy and paste from the samples they did on github : I have checked my SID and FacebookAppId and they are the same on both the app and the Facebook website.by doing this : it is generating me an SID that looks like this : ms-app : //s-1-15-2-0000-bla-bla-bla-667/ so I tried adding ms-app : // to the facebook developer settings page but it did not want it , so I tried removing ms-app : // from the SID when passing it to WinAppId but still no luckI have filled the field Windows Store SID wih My FBAppId : does anyone have this issue ? Edit 1 : My code is copy and paste from here : http : //microsoft.github.io/winsdkfb/Edit2 : playing the samples from Microsoft my issues is coming from my Application Id.I did follow step 6 : ( Enable OAuth login ) Select the created app on developers.facebook.com.Click “ Settings ” from the menu on the left.Click on the “ Advanced ” tab.Under the “ OAuth Settings ” section , enable “ Client OAuth Login ” and “ Embedded browser OAuth Login ” .Click on “ Save Changes ” . public async Task < string > LogIntoFacebook ( ) { //getting application Id string SID = WebAuthenticationBroker.GetCurrentApplicationCallbackUri ( ) .ToString ( ) ; //// Get active session FBSession sess = FBSession.ActiveSession ; sess.FBAppId = FacebookAppId ; sess.WinAppId = SID ; //setting Permissions FBPermissions permissions = new FBPermissions ( PermissionList ) ; try { // Login to Facebook FBResult result = await sess.LoginAsync ( permissions ) ; if ( result.Succeeded ) { // Login successful return sess.AccessTokenData.AccessToken ; } else { // Login failed return null ; } } catch ( InvalidOperationException ex ) { SimpleIoc.Default.GetInstance < IErrorService > ( ) .ReportErrorInternalOnly ( ex ) ; return null ; } catch ( Exception ex ) { SimpleIoc.Default.GetInstance < IErrorService > ( ) .ReportErrorInternalOnly ( ex ) ; return null ; } return null ; } //getting application Idstring SID = WebAuthenticationBroker.GetCurrentApplicationCallbackUri ( ) .ToString ( ) ;",Microsoft winsdkfb Not Logged In : You are not logged in . Please login and try again . C # WinRT "C_sharp : According to C # specification in 10.4 Constants : The type specified in a constant declaration must be sbyte , byte , short , ushort , int , uint , long , ulong , char , float , double , decimal , bool , string , an enum-type , or a reference-type . Each constant-expression must yield a value of the target type or of a type that can be converted to the target type by an implicit conversion ( §6.1 ) .Why then I ca n't do following : That should be possible , because : where T : class means , that The type argument must be a reference type ; this applies also to any class , interface , delegate , or array type ( from MSDN ) it satisfies another words from specification : the only possible value for constants of reference-types other than string is null.Any possible explanation ? public class GenericClass < T > where T : class { public const T val = null ; }",where t : class generic constraint and const value declaration "C_sharp : Consider the code : Is there a way to make such casting work ? I know that IGeneral can not be casted to ISpecific in general case . But in my particular situation I wish I could do something like this : But having the specificFunc as Object and having ISpecific type only via specificFuncAsObject.GetType ( ) public interface IGeneral { } public interface ISpecific : IGeneral { } public Func < IGeneral , String > Cast ( Object specificFuncAsObject ) { var generalFunc = specificFuncAsObject as Func < IGeneral , String > ; Assert.IsNotNull ( generalFunc ) ; // < -- - casting did n't work return generalFunc ; } Func < ISpecific , String > specificFunc = specific = > `` Hey ! `` ; var generalFunc = Cast ( specificFunc ) ; Func < IGeneral , String > generalFunc = new Func < IGeneral , String > ( general = > specificFunc ( general as ISpecific ) ) ;",How can I cast a delegate that takes a derived-type argument to a delegate with a base-type argument ? "C_sharp : I am experimenting on optimizing some mathematical operations using C # .net within a package called Grasshopper ( part of Rhino3D ) . The operation is quite simple but the list on which it has to be performed is big and may get much bigger.I am using Parallel.ForEach and lists in my C # script and the number of final results I get is lower than what is expected . This is most probably due to the fact that list.add is not thread safe ( or not thread safe within the software I 'm building it on top of ) .Please help me figure out a simple and efficient way of running this simple math operation over several hundreds of values using CPU multithreading ( or if you have suggestions about GPU CUDA ) .I hope that the obscure and specific software does not bother you because as far as I know it performs identically to normal C # .Net/Python/VB.Net . private void RunScript ( double z , int x , List < double > y , ref object A ) { List < double > temp = new List < double > ( ) ; double r ; System.Threading.Tasks.Parallel.ForEach ( y , numb = > { r = Math.Pow ( ( numb * x ) , z ) ; temp.Add ( r ) ; } ) ; A = temp ;",C # .net multithreading "C_sharp : I have an object with a property that I 'd like to map as Serializable . NHibernate supports this : Is there a way to accomplish this in Fluent NHibernate ? There 's an SO question ( Map to Serializable in Fluent NHibernate ) that would seem to address this , but the only response there does n't work for me.If I set I get the following Exception : < property name= '' FeeGenerator '' column= '' FeeGenerator '' type= '' Serializable '' / > CustomType < NHibernate.Type.SerializableType > ( ) ; Could not instantiate IType SerializableType : System.MissingMethodException : No parameterless constructor defined for this object .",Mapping to SerializableType in Fluent NHibernate "C_sharp : I need to list all extension methods found on the file.This is what I 'm doing so far ( looks like it 's working ) : Even though I could n't test all cases it looks like this is working.But I was wondering if there was a more concise way to approach this solution.Is there some sort of IsExtension or some SyntaxKind.ExtensionMethod ? I took a look but could not find anything obvious , at least.I 'm using the latest Roslyn Sept/12 var methods = nodes.OfType < MethodDeclarationSyntax > ( ) ; var extensionMethods = methods.Where ( m = > m.Modifiers.Any ( t = > t.Kind == SyntaxKind.StaticKeyword ) & & m.ParameterList.Parameters.Any ( p = > p.Modifiers.Any ( pm = > pm.Kind == SyntaxKind.ThisKeyword ) ) ) ;",How to get extension methods on Roslyn ? "C_sharp : Sorry if this has been asked before , but I find it a hard thing to search for : If I use BeginSend ( ) on a .NET socket , what kind of behaviour should I expect in code similar to this ( pseudo ) code : Main Program Code : Network.OutBound classAs im using BeginSend ( ) , when the first SendData ( messageOne ) is called , it will immediately return and the second SendData ( messageTwo ) will be called.However , consider a case where a large amount of data is being sent for both message one and message two , and the send completes with a partial amount of data and so BeginSend ( ) is recalled to send the remaining data.Would this cause the two messages ' bytes in the outgoing socket to be mixed up ? They would both be running in seperate threadpool threads and would both be sending on the same socket . I understand TCP sockets ensure data arrives in order , but how does the runtime/socket layer know if my BeginSend ( ) is a subsequent attempt to finish sending messageOne , or the start of messageTwo ? As far as it is concerned , wouldnt the data be sent and received on the remote end be in the same order as it was written to the socket in ( even though this is where the potential for mix up seems to be ) If thats the case , the what is the point of Begin/End Send if I have to serialize access to it ? Should I have some sort of flag that gets raised when messageOne has been fully sent ( even if it took several BeginSend ( ) attempts to send all the data ) so the Main Program code can wait for it to complete before attempting to sending a different message ? Should I write some sort of outgoing queue wrapper ? Or am I missing something ? Network.OutBound.SendData ( messageOne ) ; Network.OutBound.SendData ( messageTwo ) ; public void SendData ( byte [ ] buffer ) { connectedSocket.BeginSend ( buffer,0 , buffer.Length , SocketFlags.None , SendCompleteMethod ) ; } private void SendComplete ( arResult ) { int bytesSent ; bytesSent = arResult.EndSend ( ) ; if ( bytesSent < arResult.state.buffer.Length ) { //Not all data sent yet , recall BeginSend connectedSocket.BeginSend ( buffer , bytesSent , buffer.Length - bytesSent , SocketFlags.None , SendCompleteMethod ) ; } else { //All data sent successfully } }",Async Socket Writes - Potential for send operations to get mixed up ? ( .NET Sockets ) "C_sharp : To my knowledge this in a extension method is passed as a ref variable . I can verify this by doingMy List < int > ints is now 1 , 2 , 3 , 4 , 5 , 0.However when I do I would expect my List < int > ints to be 3 , 4 , 5 but remains untouched . Am I missing something obvious ? public static void Method < T > ( this List < T > list ) { list.Add ( default ( T ) ) ; } List < int > ints = new List < int > ( new int [ ] { 1 , 2 , 3 , 4 , 5 } ) ; ints.Method ( ) ; public static void Method < T > ( this List < T > list , Func < T , bool > predicate ) { list = list.Where ( predicate ) .ToList ( ) ; } List < int > ints = new List < int > ( new int [ ] { 1 , 2 , 3 , 4 , 5 } ) ; ints.Method ( i = > i > 2 ) ;",Extension method and local 'this ' variable "C_sharp : I have an if else tree that is going to grow as I add additional items for it to maintain and I 'm looking at the best way to write it for maintainability I 'm starting with this code and thinking of re-factoring it to something like thisI take a performance hit but I can manage all of my controls is a single placemy other thought was to make each selected control block it own method , something like thisI do n't take a performance hit but I 'm maintaining the controls in multiple locationI 'm leaning for option one just because I like maintainability aspect of it . private void ControlSelect ( ) { if ( PostingType == PostingTypes.Loads & & ! IsMultiPost ) { singleLoadControl.Visible = true ; singleTruckControl.Visible = false ; multiTruckControl.Visible = false ; multiLoadControl.Visible = false ; } else if ( PostingType == PostingTypes.Trucks & & ! IsMultiPost ) { singleLoadControl.Visible = false ; singleTruckControl.Visible = true ; multiTruckControl.Visible = false ; multiLoadControl.Visible = false ; } else if ( PostingType == PostingTypes.Loads & & IsMultiPost ) { singleLoadControl.Visible = false ; singleTruckControl.Visible = false ; multiTruckControl.Visible = false ; multiLoadControl.Visible = true ; } else if ( PostingType == PostingTypes.Trucks & & IsMultiPost ) { singleLoadControl.Visible = false ; singleTruckControl.Visible = false ; multiTruckControl.Visible = true ; multiLoadControl.Visible = false ; } } private void ControlSelect ( ) { List < UserControl > controlList = GetControlList ( ) ; string visableControl = singleLoadControl.ID ; if ( PostingType == PostingTypes.Loads & & ! IsMultiPost ) { visableControl = singleLoadControl.ID ; } else if ( PostingType == PostingTypes.Trucks & & ! IsMultiPost ) { visableControl = singleTruckControl.ID ; } else if ( PostingType == PostingTypes.Loads & & IsMultiPost ) { visableControl = multiLoadControl.ID ; } else if ( PostingType == PostingTypes.Trucks & & IsMultiPost ) { visableControl = multiTruckControl.ID ; } foreach ( UserControl userControl in controlList ) { userControl.Visible = ( userControl.ID == visableControl ) ; } } private List < UserControl > GetControlList ( ) { List < UserControl > controlList = new List < UserControl > { singleLoadControl , multiTruckControl , singleTruckControl , multiLoadControl } ; return controlList ; } private void SetSingleLoadControlAsSelected ( ) { singleLoadControl.Visible = true ; singleTruckControl.Visible = false ; multiTruckControl.Visible = false ; multiLoadControl.Visible = false ; }",Refactoring an If else tree "C_sharp : The title says it all , here 's the same with some formatting : Why ca n't I writebut this is okay : ( The same goes for all generics and is n't limited to HashSet ) public bool IsHashSet ( object obj ) { return obj is HashSet < > ; } public bool IsHashSet ( object obj ) { return obj.GetType ( ) == typeof ( HashSet < > ) ; }",Why ca n't I write if ( object is HashSet < > ) but it 's okay if I write ( object.GetType ( ) == typeof ( HashSet < > ) ) "C_sharp : I always thought that these two methods were similar : Yet , they yield different results when converting them to a List < Func < int > > : The output is : Why is this ? public static IEnumerable < Func < int > > GetFunctions ( ) { for ( int i = 1 ; i < = 10 ; i++ ) yield return new Func < int > ( ( ) = > i ) ; } public static IEnumerable < Func < int > > GetFunctionsLinq ( ) { return Enumerable.Range ( 1 , 10 ) .Select ( i = > new Func < int > ( ( ) = > i ) ) ; } List < Func < int > > yieldList = GetFunctions ( ) .ToList ( ) ; List < Func < int > > linqList = GetFunctionsLinq ( ) .ToList ( ) ; foreach ( var func in yieldList ) Console.WriteLine ( `` [ YIELD ] { 0 } '' , func ( ) ) ; Console.WriteLine ( `` ================== '' ) ; foreach ( var func in linqList ) Console.WriteLine ( `` [ LINQ ] { 0 } '' , func ( ) ) ; [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11 [ YIELD ] 11================== [ LINQ ] 1 [ LINQ ] 2 [ LINQ ] 3 [ LINQ ] 4 [ LINQ ] 5 [ LINQ ] 6 [ LINQ ] 7 [ LINQ ] 8 [ LINQ ] 9 [ LINQ ] 10",Different results between yield return and LINQ Select "C_sharp : When working with HashSets in C # , I recently came across an annoying problem : HashSets do n't guarantee unicity of the elements ; they are not Sets . What they do guarantee is that when Add ( T item ) is called the item is not added if for any item in the set item.equals ( that ) is true . This holds no longer if you manipulate items already in the set . A small program that demonstrates ( copypasta from my Linqpad ) : It will happily manipulate the items in the collection to be equal , only filtering them out when a new HashSet is built . What is advicible when I want to work with sets where I need to know the entries are unique ? Roll my own , where Add ( T item ) adds a copy off the item , and the enumerator enumerates over copies of the contained items ? This presents the challenge that every contained element should be deep-copyable , at least in its items that influence it 's equality.Another solution would be to roll your own , and only accepts elements that implement INotifyPropertyChanged , and taking action on the event to re-check for equality , but this seems severely limiting , not to mention a whole lot of work and performance loss under the hood.Yet another possible solution I thought of is making sure that all fields are readonly or const in the constructor . All solutions seem to have very large drawbacks . Do I have any other options ? void Main ( ) { HashSet < Tester > testset = new HashSet < Tester > ( ) ; testset.Add ( new Tester ( 1 ) ) ; testset.Add ( new Tester ( 2 ) ) ; foreach ( Tester tester in testset ) { tester.Dump ( ) ; } foreach ( Tester tester in testset ) { tester.myint = 3 ; } foreach ( Tester tester in testset ) { tester.Dump ( ) ; } HashSet < Tester > secondhashset = new HashSet < Tester > ( testset ) ; foreach ( Tester tester in secondhashset ) { tester.Dump ( ) ; } } class Tester { public int myint ; public Tester ( int i ) { this.myint = i ; } public override bool Equals ( object o ) { if ( o== null ) return false ; Tester that = o as Tester ; if ( that == null ) return false ; return ( this.myint == that.myint ) ; } public override int GetHashCode ( ) { return this.myint ; } public override string ToString ( ) { return this.myint.ToString ( ) ; } }",HashSets do n't keep the elements unique if you mutate their identity "C_sharp : I would like to use a global-scoped action filter in my MVC 3 application using Ninject ; however , I 'm trying to understand the lifetime of that filter , its dependencies , and how to introduce variations to its dependencies by decorating my controllers and/or action methods.I 'd like to have my filter type depend on objects whose lifetimes are bound to request scope , so , something like this : ... and in the module config ... And an attribute on controllers and/or action methods to represent an application-specific `` request type '' : Am I understanding properly how this should work ? Will a new instance of MyGlobalActionFilter get spun up and injected on each HTTP request ? If this wo n't work , what am I missing , and what would be a better way to make this work ? Also , with injecting the RequestType , the BindFilter syntax here seems unnecessarily verbose , I 'm not sure if it works like I expect , and it seems there would be a better way to inject a default RequestType into the action filter if a RequestTypeAttribute is n't present on the controller or the action method.Please enlighten me ! public sealed class MyGlobalActionFilter : IActionFilter { public MyGlobalActionFilter ( IService1 svc1 , IService2 svc2 , RequestType reqType ) { // code here } // IActionFilter implementation here ... } Bind < IService1 > ( ) .To < ConcreteService1 > ( ) .InRequestScope ( ) Bind < IService2 > ( ) .To < ConcreteService2 > ( ) .InRequestScope ( ) BindFilter < MyGlobalActionFilter > ( FilterScope.Global , null ) .WhenControllerHas < RequestTypeAttribute > ( ) .WithConstructorArgumentFromControllerAttribute < RequestTypeAttribute > ( `` reqType '' , x = > x.RequestType ) ; BindFilter < MyGlobalActionFilter > ( FilterScope.Global , null ) .WhenActionMethodHas < RequestTypeAttribute > ( ) .WithConstructorArgumentFromActionAttribute < RequestTypeAttribute > ( `` reqType '' , x = > x.RequestType ) ; BindFilter < MyGlobalActionFilter > ( FilterScope.Global ) .When ( x = > true ) .WithConstructorArgument ( `` reqType '' , RequestType.Undefined ) [ RequestType ( RequestType.Type1 ) ] public sealed class SomeController : Controller { /* code here*/ }",Questions on lifetime of Ninject-created action filters in MVC 3 "C_sharp : I have a TableView with a custom UITableViewCell . In each cell I have multiple buttons , when any of the buttons is click after scrolling down and up it calls itself the many times I scroll down and up . I have read and research for a solution and I have n't found a solution . I know the problem is the cell are being reuse so that 's why the buttons are being call multiple times but I ca n't find a way to prevent it.I added console write line statements through the code and the else part in MoveToWindow is never call . Could that be the reason why ? Research material for solution : my code is calling twice the btndelete method in uitableviewUIButton click event getting called multiple times inside custom UITableViewCellMy Code : namespace Class.iOS { public partial class CustomCell : UITableViewCell { public static readonly NSString Key = new NSString ( `` CustomCell '' ) ; public static readonly UINib Nib ; public int Row { get ; set ; } public event EventHandler LikeButtonPressed ; private void OnLikeButtonPressed ( ) { if ( LikeButtonPressed ! = null ) { LikeButtonPressed ( this , EventArgs.Empty ) ; } } public override void MovedToWindow ( ) { if ( Window ! = null ) { btnAdd.TouchUpInside += HandleLikeButtonPressed ; } else { btnAdd.TouchUpInside -= HandleLikeButtonPressed ; } } private void HandleLikeButtonPressed ( object sender , EventArgs e ) { OnLikeButtonPressed ( ) ; } static CustomCell ( ) { Nib = UINib.FromName ( `` CustomCell '' , NSBundle.MainBundle ) ; } public CustomCell ( ) { } public CustomCell ( IntPtr handle ) : base ( handle ) { } public void UpdateCell ( string Name , int number ) { // some code } public class TableSource : UITableViewSource { public override nint RowsInSection ( UITableView tableview , nint section ) { return 8 ; } private void HandleLikeButtonPressed ( object sender , EventArgs e ) { var cell = ( CustomCell ) sender ; var row = cell.Row ; switch ( row ) { case 0 : cell.label.Text = `` '' break ; case 1 : cell.label.Text = `` '' break ; } } public override UITableViewCell GetCell ( UITableView tableView , NSIndexPath indexPath ) { var cell = tableView.DequeueReusableCell ( CustomCell.Key ) as CustomCell ; cell.Row = indexPath.Row ; if ( cell == null ) { cell = new CustomCell ( ) ; var views = NSBundle.MainBundle.LoadNib ( `` CustomCell '' , cell , null ) ; cell.LikeButtonPressed += HandleLikeButtonPressed ; cell = Runtime.GetNSObject ( views.ValueAt ( 0 ) ) as CustomCell ; } cell.UpdateCell ( // some code ) ; return cell ; } } } }",iOS TableView button is being called multiple times "C_sharp : Here is the simple example : Now , everytime I use that method I have to intercept CookinDone event and move on.But how can I simplify that by making return type of the method as Boolean and return result upon the Cookin completion ? if I put there something like while ( bw.IsBusy ) it will screw my ActivityIndicator , freeze the main thread and I feel it would be the lousiest thing to do . There are also some Monitor.Wait stuff and some other stuff like TaskFactory , but all that stuff seems to be too complicated to use in simple scenarios . It might be also different in different environments , like some approach is good for WPF apps , some for something else and whatnot , but there should be a general pattern is n't that right ? How do you do that guys ? public event EventHandler CookinDone = delegate { } ; public void CoockinRequest ( ) { var indicator = new ActivityIndicator ( ) ; ActivityIndicator.Show ( `` Oooo coockin ' something cool '' ) ; var bw = new BackgroundWorker ( ) ; bw.DoWork += ( sender , e ) = > CockinService.Cook ( ) ; bw.RunWorkerCompleted += ( sender , e ) = > { indicator.Hide ( ) ; CookinDone.Invoke ( this , null ) ; } ; bw.RunWorkerAsync ( ) ; } var cook = new Cook ( ) ; cook.CookinDone += ( sender , e ) = > MessageBox.Show ( `` Yay , smells good '' ) ; cook.CoockinRequest ( ) ; if ( CoockinRequest ( ) ) MessageBox.Show ( 'Yay , smells even better ' ) ;",Asynchronous call in synchronous method "C_sharp : Here is a simple generic type with a unique generic parameter constrained to reference types : The generated IL by csc.exe is : So each parameter is boxed before proceeding with the comparison.But if the constraint indicates that `` T '' should never be a value type , why is the compiler trying to box r1 and r2 ? class A < T > where T : class { public bool F ( T r1 , T r2 ) { return r1 == r2 ; } } ldarg.1box ! Tldarg.2box ! Tceq",Why the compiler emits box instructions to compare instances of a reference type ? "C_sharp : Say I 've got an object that exists for the duration of an application . Let 's call it GlobalWorker . GlobalWorker has events e.g . UserLoggedIn to which other objects can subscribe . Now imagine I 've got a Silverlight page or an asp.net page or something , that subscribes to the UserLoggedIn event when it is constructed . Does the existence of this event prevent the page from being garbage collected ? If so , what 's the best pattern to use in this instance : weak event-handlers , move the subscription to the Load event and unsubscribe in the UnLoad event ? public SomePage ( ) { GlobalWorker.Instance.UserLoggedIn += new EventHandler ( OnUserLoggedIn ) ; } private void OnLoggedIn ( object sender , EventArgs e ) { }",Eventhandlers and application lifetime objects in c # - should I unhook ? "C_sharp : I know that if I mark code as DEBUG code it wo n't run in RELEASE mode , but does it still get compiled into an assembly ? I just wan na make sure my assembly is n't bloated by extra methods . [ Conditional ( DEBUG ) ] private void DoSomeLocalDebugging ( ) { //debugging }",Conditional DEBUG - Does it still compile into RELEASE code ? "C_sharp : By benchmarking this code against the c++ version , I discover than performance are 10 times slower than c++ version . I have no problem with that , but that lead me to the following question : It seems ( after a few search ) that JIT compiler ca n't optimize this code as c++ compiler can do , namely just call sqrt once and apply *1000000 on it.Is there a way to force JIT to do it ? using System ; namespace ConsoleApplication1 { class TestMath { static void Main ( ) { double res = 0.0 ; for ( int i =0 ; i < 1000000 ; ++i ) res += System.Math.Sqrt ( 2.0 ) ; Console.WriteLine ( res ) ; Console.ReadKey ( ) ; } } }",JIT & loop optimization "C_sharp : This is somewhat related to Does functional programming replace GoF design patterns ? Since the introduction of lambdas and dynamics in C # , are there any of the standard design patterns that could be considered obsolete or solved in some other way using lambdas or other language features ? For example , the dynamic features of C # can now be used to do multi methods.http : //achoiusa.wordpress.com/2009/08/27/exploring-c-4-0-multimethods/ ( I think Marc Gravell had some post about this to ? ) Personally I tend to do factories using Func of T nowdays.e.g.Anyone got other examples ? [ Edit ] Ofcourse the patterns do n't go obsolete per se but some patterns are paradigm specific and thus since C # is now multi paradigm , some of the functional properties of C # may make some of the OOP patterns less attractive . public static class SomeFactory { public static Func < IUnitOfWork > GetUoW = ( ) = > new EF4UoW ( new SomeModelContainer ( ) ) ; } // usagevar uow = SomeFactory.GetUoW ( ) ; // testabillityvar testUoW = new InMemUoW ( ) ; testUoW.Add ( new Customer ( ) ... ) ; SomeFactory.GetUoW = ( ) = > testUoW ; // the service can get an UoW using the factoryvar result = SomeDomainService.DoStuff ( ... ) ;",Examples of functional or dynamic techniques that can substitute for object oriented Design Patterns "C_sharp : I 've got an interface with type T objects like soI 've got a bunch of these interfaces with all different type T 's . How can I add these interfaces into a List of some sort , iterate through the list and call a common method used by the interface . Any ideas ? Is there an alternative approach ? If I add it to a list , I just ca n't see a way of casting the type T correctly . public interface IService < T >",Iterating through list of interfaces "C_sharp : Firstly I believe that the first time is just a condition to see this blocking more clearly . For next times , somehow it still blocks the UI slightly but not obvious like when not using async.I can say that because I can see the difference between using that QueryAsync and a simple wrapping code with Task.Run ( ( ) = > connection.Query < T > ) which works fine and of course much better than QueryAsync ( in UX ) .The code is just simple like this : The code working fine ( without blocking UI ) is like this : I know that Task.Run ( ) is not actually async to the detail but at least it puts the whole work to another thread and makes the UI free from being blocked and frozen.I guess this might be a bug in Dapper , please take sometime to test this . I 'm not so sure how to exactly reproduce this , but if possible please try a Winforms project , a fairly large Oracle database and of course as I said you can see it the most obviously by the first time querying ( so be sure to run the clearing-cache query against the Oracle server before each test ) .Finally if you have some explanation and solution to this ( of course without using Task.Run ) , please share in your answer . public async Task < IEnumerable < Item > > LoadItemsAsync ( ) { using ( var con = new OracleConnection ( connectionString ) ) { var items = await con.QueryAsync < dynamic > ( `` someQuery '' ) ; return items.Select ( e = > new Item { ... } ) ; } } //in UI thread , load items like this : var items = await LoadItemsAsync ( ) ; public async Task < IEnumerable < Item > > LoadItemsAsync ( ) { using ( var con = new OracleConnection ( connectionString ) ) { var items = await Task.Run ( ( ) = > con.Query < dynamic > ( `` someQuery '' ) ) ; return items.Select ( e = > new Item { ... } ) ; } } //in UI thread , load items like this : var items = await LoadItemsAsync ( ) ;",Dapper QueryAsync blocks UI for the first time querying ( against Oracle server ) ? "C_sharp : So I read MSDN and Stack Overflow . I understand what the Action Delegate does in general but it is not clicking no matter how many examples I do . In general , the same goes for the idea of delegates . So here is my question . When you have a function like this : What is this , and what should I pass to it ? public GetCustomers ( Action < IEnumerable < Customer > , Exception > callBack ) { }",Please Explain .NET Delegates C_sharp : Following method shall only be called if it has been verified that there are invalid digits ( by calling another method ) . How can I test-cover the throw-line in the following snippet ? I know that one way could be to merge together the VerifyThereAreInvalidiDigits and this method . I 'm looking for any other ideas.I also would not want to write a unit test that exercises code that should never be executed . public int FirstInvalidDigitPosition { get { for ( int index = 0 ; index < this.positions.Count ; ++index ) { if ( ! this.positions [ index ] .Valid ) return index ; } throw new InvalidOperationException ( `` Attempt to get invalid digit position whene there are no invalid digits . `` ) ; } },How do I test code that should never be executed ? "C_sharp : C # Homework question : I just added some `` play again '' logic using a do-while loop . This was my original code : Which gave me an error : I moved String playAgain = `` N '' ; to the line ABOVE my do ( see comment ) and it worked fine.I 'm trying to understand what exactly I did to fix this . It seems like it was a scope issue , but it also seems to me that defining a variable within a loop could conceivably pass it to the end of the loop . I 've looked through my textbooks , and there 's not anything about scope as it relates to loops . That would suggest to me that scope within loops is n't an issue , but this is behaving as if it were a scope issue . I 'm confusing myself thinking about it.If it was a scope issue I 'd like to have a better understanding of the scope of do ... while loops within a method . If it was n't a scope issue , it was a lucky guess on my part . In that case what was wrong and how did moving that line of code fix it ? namespace demo { class Program { static void Main ( string [ ] args ) { Info myInfo = new Info ( ) ; myInfo.DisplayInfo ( `` Daniel Wilson '' , `` 4 - Hi-Lo Game '' ) ; // I moved String playAgain = `` N '' ; to here do { DWHiLowUI theUI = new DWHiLowUI ( ) ; theUI.Play ( ) ; String playAgain = `` N '' ; Console.WriteLine ( `` Enter ' Y ' to play again , any other key to exit . `` ) ; playAgain = Console.ReadLine ( ) ; } while ( ( playAgain == `` Y '' ) || ( playAgain == '' y '' ) ) ; Console.ReadLine ( ) ; } } } Error 7 The name 'playAgain ' does not exist in the current context",How does scope factor into `` do ... while '' loops and vice versa ? "C_sharp : As a means of introducing lazy formatting evaluation in a library I am developing , I have defined the delegatesand something along the lines of the following classHowever , this is behaving strangely enough : when running from an external project , the statementdoes not compile , failing with the errorwhilecompiles and works with no problems , printing 1,2,3 in the console . Why do I have to qualify the message argument with MessageFormatterDelegate type in the second lambda expression ? Is there any way to circunvent this behaviour ? public delegate string MessageFormatterDelegate ( string message , params object [ ] arguments ) ; public delegate string MessageFormatterCallback ( MessageFormatterDelegate formatterDelegate ) ; public static class TestClass { public static string Evaluate ( MessageFormatterCallback formatterCallback ) { return ( formatterCallback ( String.Format ) ) ; } } Console.WriteLine ( TestClass.Evaluate ( message = > message ( `` { 0 } , { 1 } , { 2 } '' , 1 , 2 , 3 ) ) ) ; Error 1 Delegate 'MessageFormatterDelegate ' does not take 4 arguments Console.WriteLine ( TestClass.Evaluate ( ( MessageFormatterDelegate message ) = > message ( `` { 0 } , { 1 } , { 2 } '' , 1 , 2 , 3 ) ) ) ;",Strange Behaviour Using Delegates and Lambdas "C_sharp : How do I get the drop down to display as part of my editor template ? So I have a Users entity and a Roles entity . The Roles are passed to the view as a SelectList and User as , well , a User . The SelectList becomes a drop down with the correct ID selected and everything thanks to this sample . I 'm trying to get an all-in-one nicely bundled EditorTemplate for my entities using MVC 3 so that I can just call EditorForModel and get the fields laid out nicely with a drop down added whenever I have a foreign key for things like Roles , in this particular instance.My EditorTemlates\User.cshtml ( dynamically generating the layout based on ViewData ) : On the View I 'm then binding the SelectList seperately , and I want to do it as part of the template.My Model : My Controller : My View : Hopefully that 's clear enough , let me know if you could use more clarification . Thanks in advance ! < table style= '' width : 100 % ; '' > @ { int i = 0 ; int numOfColumns = 3 ; foreach ( var prop in ViewData.ModelMetadata.Properties .Where ( pm = > pm.ShowForDisplay & & ! ViewData.TemplateInfo.Visited ( pm ) ) ) { if ( prop.HideSurroundingHtml ) { @ Html.Display ( prop.PropertyName ) } else { if ( i % numOfColumns == 0 ) { @ Html.Raw ( `` < tr > '' ) ; } < td class= '' editor-label '' > @ Html.Label ( prop.PropertyName ) < /td > < td class= '' editor-field '' > @ Html.Editor ( prop.PropertyName ) < span class= '' error '' > @ Html.ValidationMessage ( prop.PropertyName , '' * '' ) < /span > < /td > if ( i % numOfColumns == numOfColumns - 1 ) { @ Html.Raw ( `` < /tr > '' ) ; } i++ ; } } } < /table > public class SecurityEditModel { [ ScaffoldColumn ( false ) ] public SelectList roleList { get ; set ; } public User currentUser { get ; set ; } } public ViewResult Edit ( int id ) { User user = repository.Users.FirstOrDefault ( c = > c.ID == id ) ; var viewModel = new SecurityEditModel { currentUser = user , roleList = new SelectList ( repository.Roles.Where ( r = > r.Enabled == true ) .ToList ( ) , `` ID '' , `` RoleName '' ) } ; return View ( viewModel ) ; } @ model Nina.WebUI.Models.SecurityEditModel @ { ViewBag.Title = `` Edit '' ; Layout = `` ~/Views/Shared/_Layout.cshtml '' ; } < h2 > Edit < /h2 > @ using ( Html.BeginForm ( `` Edit '' , `` Security '' ) ) { @ Html.EditorFor ( m = > m.currentUser ) < table style= '' width : 100 % ; '' > < tr > < td class= '' editor-label '' > User Role : < /td > < td class= '' editor-field '' > < ! -- I want to move this to the EditorTemplate -- > @ Html.DropDownListFor ( model = > model.currentUser.RoleID , Model.roleList ) < /td > < /tr > < /table > < div class= '' editor-row '' > < div class= '' editor-label '' > < /div > < div class= '' editor-field '' > < /div > < /div > < div class= '' editor-row '' > & nbsp ; < /div > < div style= '' text-align : center ; '' > < input type= '' submit '' value= '' Save '' / > & nbsp ; & nbsp ; < input type= '' button '' value= '' Cancel '' onclick= '' location.href= ' @ Url.Action ( `` List '' , `` Clients '' ) ' '' / > < /div > }",MVC 3 Editor Template with Dynamic Drop Down "C_sharp : Thanks to Loading an ECC private key in .NET , I 'm able to load ECC private keys into .NET Core 3 and performing signature tasks with them.I have , however run into one key that can not be loaded by ECDSA.ImportPrivateKey . What 's weird is that looking at it with openssl changes the key bytes to something that .NET Core 3 can understand.Code to import the failing private key ( this is the actual key that fails ) : The ImportECPrivateKey call fails with System.Security.Cryptography.CryptographicException : ASN1 corrupted data inside System.Security.Cryptography.EccKeyFormatHelper.FromECPrivateKey ( ReadOnlyMemory ` 1 keyData , AlgorithmIdentifierAsn & algId , ECParameters & ret ) The original PEM file looks like this : openssl converts the private key to something else : Using this form of the PEM file , .NET Core 3 can import the private key.My question is : What is going on ; Why is openssl changing the private key to another format ( how can I tell which format is which ? ) , and why can .NET Core 3 understand one format and not the other ? ecdsa = ECDsa.Create ( ) ; var pem = `` MHYCAQEEH5t2Xlmsw5uqw3W9+/3nosFi6i3V901uW6ZzUpvVM0qgCgYIKoZIzj0DAQehRANCAASck2UuMxfyDYBdJC0mHNeToqMBhJuMZYSgkUNbK/xzD7e3cwr5okPx0pZdSMfDmyi1dBujtIIxFK9va1bdVAR9 '' ; var derArray = Convert.FromBase64String ( pem ) ; ecdsa.ImportECPrivateKey ( derArray , out _ ) ; $ cat private_key_cert_265.pem -- -- -BEGIN EC PRIVATE KEY -- -- -MHYCAQEEH5t2Xlmsw5uqw3W9+/3nosFi6i3V901uW6ZzUpvVM0qgCgYIKoZIzj0DAQehRANCAASck2UuMxfyDYBdJC0mHNeToqMBhJuMZYSgkUNbK/xzD7e3cwr5okPx0pZdSMfDmyi1dBujtIIxFK9va1bdVAR9 -- -- -END EC PRIVATE KEY -- -- - $ openssl ec -in private_key_cert_265.pemread EC keywriting EC key -- -- -BEGIN EC PRIVATE KEY -- -- -MHcCAQEEIACbdl5ZrMObqsN1vfv956LBYuot1fdNblumc1Kb1TNKoAoGCCqGSM49AwEHoUQDQgAEnJNlLjMX8g2AXSQtJhzXk6KjAYSbjGWEoJFDWyv8cw+3t3MK+aJD8dKWXUjHw5sotXQbo7SCMRSvb2tW3VQEfQ== -- -- -END EC PRIVATE KEY -- -- -",.NET Core 3 unable to load ECC private key C_sharp : Possible Duplicate : casting vs using the 'as ' keyword in the CLR or foreach ( MyClass i in x ) { if ( i is IMy ) { IMy a = ( IMy ) i ; a.M1 ( ) ; } } foreach ( MyClass i in x ) { IMy a = i as IMy ; if ( a ! = null ) { a.M1 ( ) ; } },Should I prefer the 'is ' or 'as ' operator ? "C_sharp : If I have a list containing an arbitrary number of lists , like so : ... is there any way to somehow `` zip '' or `` rotate '' the lists into something like this ? The obvious solution would be to do something like this : ... but I was wondering if there was a cleaner way of doing so , using linq or otherwise ? var myList = new List < List < string > > ( ) { new List < string > ( ) { `` a '' , `` b '' , `` c '' , `` d '' } , new List < string > ( ) { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } , new List < string > ( ) { `` w '' , `` x '' , `` y '' , `` z '' } , // ... etc ... } ; { { `` a '' , `` 1 '' , `` w '' , ... } , { `` b '' , `` 2 '' , `` x '' , ... } , { `` c '' , `` 3 '' , `` y '' , ... } , { `` d '' , `` 4 '' , `` z '' , ... } } public static IEnumerable < IEnumerable < T > > Rotate < T > ( this IEnumerable < IEnumerable < T > > list ) { for ( int i = 0 ; i < list.Min ( x = > x.Count ( ) ) ; i++ ) { yield return list.Select ( x = > x.ElementAt ( i ) ) ; } } // snipvar newList = myList.Rotate ( ) ;",How to `` zip '' or `` rotate '' a variable number of lists ? "C_sharp : I have a base class vehicle and some children classes like car , motorbike etc.. inheriting from vehicle.In each children class there is a function Go ( ) ; now I want to log information on every vehicle when the function Go ( ) fires , and on that log I want to know which kind of vehicle did it.Example : How can I know in the function Log that car called me during the base ( ) ? Thanks , Omri public class vehicle { public void Go ( ) { Log ( `` vehicle X fired '' ) ; } } public class car : vehicle { public void Go ( ) : base ( ) { // do something } }","In C # , can I know in the base class what children inherited from me ?" "C_sharp : I have an external component ( C++ ) , which I want to call from my C # code.The code is something like this : So the problem is that , at the first call it 's working well , the external component called , I got back result . But when I try to call it in an other thread , I got an exception : System.InvalidCastException : Unable to cast COM object of type 'System.__ComObject ' ... .I 'm sure this exception throwed , because of the STAThread . Because if I remove the [ STAThread ] attribute from the Main function , the same occurs with the first call of the external component , which was worked fine.How can I call this external component from an other thread to get rid of this exception ? UPDATE -- -- -- -- -- -- -Other crazy thing occurs now . When I start the program from Visual Studio with F5 , the problem occurs in the first call as well , but when I execute directly the binary .exe file , it 's working ( from the other thread it is n't : ( ) .If I switch the build from Debug to Release and starting it from Visual Studio with F5 , the first call working again.Why does it happen ? Thanks for you help in advance ! Best Regards , Zoli using System.Text ; using System.Threading ; using System.Threading.Tasks ; namespace dgTEST { class Program { [ STAThread ] static void Main ( string [ ] args ) { ExtComponentCaller extCompCaller = new ExtComponentCaller ( ) ; result = extCompCaller.Call ( input ) ; Thread t = new Thread ( new ThreadStart ( ( ) = > { try { result = extCompCaller.Call ( input ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.ToString ( ) ) ; } } ) ) ; t.SetApartmentState ( ApartmentState.STA ) ; t.Start ( ) ; t.Join ( ) ; } } }",C # STAThread COMException "C_sharp : I was playing with C # and wanted to speed up a program . I made changes and was able to do so . However , I need help understanding why the change made it faster . I 've attempted to reduce the code to something easier to understand in a question . Score1 and Report1 is the slower way . Score2 and Report2 is the faster way . The first method first stores a string and an int in a struct in parallel . Next , in a serial loop , it loops through an array of those structs and writes their data to a buffer . The second method first writes the data to a string buffer in parallel . Next , in a serial loop , it writes the string data to a buffer . Here are some sample run times : Run 1 Total Average Time = 0.492087 secRun 2 Total Average Time = 0.273619 secWhen I was working with an earlier non-parallel version of this , the times were almost the same . Why the difference with the parallel version ? Even if I reduce the loop in Report1 to write a single line of output to the buffer it is still slower ( total time about .42 sec ) .Here is the simplified code : using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Diagnostics ; using System.Threading.Tasks ; using System.IO ; namespace OptimizationQuestion { class Program { struct ValidWord { public string word ; public int score ; } ValidWord [ ] valid ; StringBuilder output ; int total ; public void Score1 ( string [ ] words ) { valid = new ValidWord [ words.Length ] ; for ( int i = 0 ; i < words.Length ; i++ ) { StringBuilder builder = new StringBuilder ( ) ; foreach ( char c in words [ i ] ) { if ( c ! = ' U ' ) builder.Append ( c ) ; } if ( words [ i ] .Length == 3 ) { valid [ i ] = new ValidWord { word = builder.ToString ( ) , score = words [ i ] .Length } ; } } } public void Report1 ( StringBuilder outputBuffer ) { int total = 0 ; foreach ( ValidWord wordInfo in valid ) { if ( wordInfo.score > 0 ) { outputBuffer.AppendLine ( String.Format ( `` { 0 } { 1 } '' , wordInfo.word.ToString ( ) , wordInfo.score ) ) ; total += wordInfo.score ; } } outputBuffer.AppendLine ( string.Format ( `` Total = { 0 } '' , total ) ) ; } public void Score2 ( string [ ] words ) { output = new StringBuilder ( ) ; total = 0 ; for ( int i = 0 ; i < words.Length ; i++ ) { StringBuilder builder = new StringBuilder ( ) ; foreach ( char c in words [ i ] ) { if ( c ! = ' U ' ) builder.Append ( c ) ; } if ( words [ i ] .Length == 3 ) { output.AppendLine ( String.Format ( `` { 0 } { 1 } '' , builder.ToString ( ) , words [ i ] .Length ) ) ; total += words [ i ] .Length ; } } } public void Report2 ( StringBuilder outputBuffer ) { outputBuffer.Append ( output.ToString ( ) ) ; outputBuffer.AppendLine ( string.Format ( `` Total = { 0 } '' , total ) ) ; } static void Main ( string [ ] args ) { Program [ ] program = new Program [ 100 ] ; for ( int i = 0 ; i < program.Length ; i++ ) program [ i ] = new Program ( ) ; string [ ] words = File.ReadAllLines ( `` words.txt '' ) ; Stopwatch stopwatch = new Stopwatch ( ) ; const int TIMING_REPETITIONS = 20 ; double averageTime1 = 0.0 ; StringBuilder output = new StringBuilder ( ) ; for ( int i = 0 ; i < TIMING_REPETITIONS ; ++i ) { stopwatch.Reset ( ) ; stopwatch.Start ( ) ; output.Clear ( ) ; Parallel.ForEach < Program > ( program , p = > { p.Score1 ( words ) ; } ) ; for ( int k = 0 ; k < program.Length ; k++ ) program [ k ] .Report1 ( output ) ; stopwatch.Stop ( ) ; averageTime1 += stopwatch.Elapsed.TotalSeconds ; GC.Collect ( ) ; } averageTime1 /= ( double ) TIMING_REPETITIONS ; Console.WriteLine ( string.Format ( `` Run 1 Total Average Time = { 0:0.000000 } sec '' , averageTime1 ) ) ; double averageTime2 = 0.0 ; for ( int i = 0 ; i < TIMING_REPETITIONS ; ++i ) { stopwatch.Reset ( ) ; stopwatch.Start ( ) ; output.Clear ( ) ; Parallel.ForEach < Program > ( program , p = > { p.Score2 ( words ) ; } ) ; for ( int k = 0 ; k < program.Length ; k++ ) program [ k ] .Report2 ( output ) ; stopwatch.Stop ( ) ; averageTime2 += stopwatch.Elapsed.TotalSeconds ; GC.Collect ( ) ; } averageTime2 /= ( double ) TIMING_REPETITIONS ; Console.WriteLine ( string.Format ( `` Run 2 Total Average Time = { 0:0.000000 } sec '' , averageTime2 ) ) ; Console.ReadLine ( ) ; } } }",Help understanding C # optimization "C_sharp : I can see a rectangle and text on the screen , so the markup seems to be correct but in the editor , there 's a blue squiggly and the message that the tags are n't recognized . It seem to be the case for all SVG-related elements.Is there a way to fix it ? I noticed that I did n't have intellisense for those elements , neither . Do I need to add a packages for that ? This is what it looks like in my VS15 . < svg width= '' 400 '' height= '' 400 '' > < g transform= '' translate ( 0,0 ) '' > < rect width= '' 5 '' height= '' 5 '' > < /rect > < circle cx= '' 40 '' cy= '' 19 '' r= '' 25 '' > < /circle > < text x= '' 37 '' y= '' 9.5 '' dy= '' .35em '' > my text < /text > < /g > < /svg >","Visual Studio 2015 does n't recognize svg , rect , g , circle etc" "C_sharp : I 'm trying to implement quicksort in a functional style using C # using linq , and this code randomly works/does n't work , and I ca n't figure out why.Important to mention : When I call this on an array or list , it works fine . But on an unknown-what-it-really-is IEnumerable , it goes insane ( loses values or crashes , usually . sometimes works . ) The code : Can you find any faults here that would cause this to fail ? Edit : Some better test code : public static IEnumerable < T > Quicksort < T > ( this IEnumerable < T > source ) where T : IComparable < T > { if ( ! source.Any ( ) ) yield break ; var pivot = source.First ( ) ; var sortedQuery = source.Skip ( 1 ) .Where ( a = > a.CompareTo ( source.First ( ) ) < = 0 ) .Quicksort ( ) .Concat ( new [ ] { pivot } ) .Concat ( source.Skip ( 1 ) .Where ( a = > a.CompareTo ( source.First ( ) ) > 0 ) .Quicksort ( ) ) ; foreach ( T key in sortedQuery ) yield return key ; } var rand = new Random ( ) ; var ienum = Enumerable.Range ( 1 , 100 ) .Select ( a = > rand.Next ( ) ) ; var array = ienum.ToArray ( ) ; try { array.Quicksort ( ) .Count ( ) ; Console.WriteLine ( `` Array went fine . `` ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Array did not go fine ( { 0 } ) . `` , ex.Message ) ; } try { ienum.Quicksort ( ) .Count ( ) ; Console.WriteLine ( `` IEnumerable went fine . `` ) ; } catch ( Exception ex ) { Console.WriteLine ( `` IEnumerable did not go fine ( { 0 } ) . `` , ex.Message ) ; }",C # functional quicksort is failing "C_sharp : Suppose I have a WinForms DataGridView control and I data bind it to an IList of a custom type , like this : This displays the list items with column names `` Name '' and `` Age '' neatly inferred ( by reflection ) from the public properties of the list items . ( The first item according to my tests . ) But if I do the same using a DataTable : ... how does the DataGridView know how to use the DataTable 's columns instead of its public properties ? Neither DataTable nor DataRow seem to implement any interface supplying this information . Or does DataGridView know about the DataTable type , and treats this type of data source differently ? The reason I 'm asking is because I would like to implement my own `` dynamic '' data source type that does not rely on fixed properties . public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } private void Form1_Load ( object sender , EventArgs e ) { var data = new ArrayList ( ) ; data.Add ( new Person ( `` Bob '' , 25 ) ) ; data.Add ( new Person ( `` Alice '' , 23 ) ) ; this.dataGridView1.DataSource = data ; } DataTable dt = new DataTable ( ) ; dt.Columns.Add ( `` Name '' ) ; dt.Columns.Add ( `` Row '' ) ; dt.Rows.Add ( `` Bob '' , 25 ) ; dt.Rows.Add ( `` Alice '' , 23 ) ; this.dataGridView1.DataSource = dt ;",How does data binding work with DataTable ? "C_sharp : I have code as shown belowIn this code I have a factory which is returning the concrete instances . But every time I need to have a new implementation of the ICar interface , I have to change the CreateCar ( ) method of the CarFactory . It seems like I am not supporting the Open Closed Principle of the SOLID principles . Please suggest is there a better way to handle this scenario . public interface ICar { void Created ( ) ; } public class BigCar : ICar { public void Created ( ) { } } public class SmallCar : ICar { public void Created ( ) { } } public class LuxaryCar : ICar { public void Created ( ) { } } public class CarFactory { public ICar CreateCar ( int carType ) { switch ( carType ) { case 0 : return new BigCar ( ) ; case 1 : return new SmallCar ( ) ; case 2 : return new LuxaryCar ( ) ; default : break ; } return null ; } }",Factory class is not supporting SOLID principle "C_sharp : I am reading a text file into a dictionary using a short Linq expressionThis works just fine as long as I dont have duplicate keys in my text file . Is there a short way to filter those without going the long way and iterating over the lines [ ] array ? string [ ] lines = File.ReadAllLines ( path ) ; var dictionary = lines.Select ( line = > line.Split ( ' ; ' ) ) .ToDictionary ( keyValue = > keyValue [ 0 ] , bits = > bits [ 1 ] ) ;",Read text file into dictionary without duplicates "C_sharp : When comparing to a minimum or maximum of two numbers/functions , does C # short-circuit if the case is true for the first one and would imply truth for the second ? Specific examples of these cases areandSince Math.Max ( y , z ( ) ) will return a value at least as large as y , if x < y then there is no need to evaluate z ( ) , which could take a while . Similar situation with Math.Min.I realize that these could both be rewritten along the lines ofin order to short-circuit , but I think it 's more clear what the comparison is without rewriting . Does this short-circuit ? if ( x < Math.Max ( y , z ( ) ) ) if ( x > Math.Min ( y , z ( ) ) ) if ( x < y || x < z ( ) )",Does comparing to Math.Min or Math.Max short-circuit ? "C_sharp : I 'm trying to send emails using gmail 's username and password in a Windows application . However , the following code is sending the mail to only the first email address when I collect multiple email address in my StringBuilder instance.What am I doing wrong , and how can I sort out my problem ? var fromAddress = new MailAddress ( username , DefaultSender ) ; var toAddress = new MailAddress ( builder.ToString ( ) ) ; //builder reference having multiple email addressstring subject = txtSubject.Text ; string body = txtBody.Text ; ; var smtp = new SmtpClient { Host = HostName , Port = 587 , EnableSsl = true , DeliveryMethod = SmtpDeliveryMethod.Network , UseDefaultCredentials = false , Credentials = new NetworkCredential ( username , password ) , //Timeout = 1000000 } ; var message = new MailMessage ( fromAddress , toAddress ) { Subject = subject , Body = body , IsBodyHtml = chkHtmlBody.Checked } ; if ( System.IO.File.Exists ( txtAttechments.Text ) ) { System.Net.Mail.Attachment attechment = new Attachment ( txtAttechments.Text ) ; message.Attachments.Add ( attechment ) ; } if ( this.Enabled ) this.Enabled = false ; smtp.Send ( message ) ;",How to send email with multiple addresses in C # "C_sharp : I am working on a windows application , where i have to provide the user , a way to change the proxy settings by opening the IE settings window . Google chrome uses the same method , when you try to change the proxy settings in chrome , it will open internet explorer properties window with the connection tab selected.I have observed that chrome is running run32dll.exe to achieve this , but it is also passing some arguments along with itSystem.Diagnostics.Process.Start ( `` rundll32.exe '' , `` SomeArgumentsHere '' ) ; my only problem is i do n't know what arguments it is passing.To simplify my question , i want to know a way to open IE settings window with the connection tab selected , from my C # .net applicationUpdate the following code worked for me System.Diagnostics.Process.Start ( `` inetcpl.cpl '' , `` ,4 '' ) ;",How to internet explorer properties window in C # "C_sharp : Possible Duplicate : At what point does using a StringBuilder become insignificant or an overhead ? Related/Duplicate QuestionsString vs StringBuilderAt what point does using a StringBuilder become insignificant or an overhead ? As plain as possible I have this method 1 : I am wondering if method 2 be faster if I would do : cmd2.CommandText = ( `` insert into `` + TableName + `` values ( `` + string.Join ( `` , '' , insertvalues ) + `` ) ; '' ) ; StringBuilder sb2 = new StringBuilder ( ) ; sb2.Append ( `` insert into `` ) ; sb2.Append ( TableName ) ; sb2.Append ( `` values ( `` ) ; sb2.Append ( string.Join ( `` , '' , insertvalues ) ) ; sb2.Append ( `` ) ; '' ) ; cmd2.CommandText = sb2.ToString ( ) ;",Worth having a StringBuilder for 5 concatenations ? "C_sharp : I 've tested the speed of retrieving , updating and removing values in a dictionary using a ( int , int , string ) tuple as key versus the same thing with a nested Dictionary : Dictionary > > .My tests show the tuple dictionary to be a lot slower ( 58 % for retrieving , 69 % for updating and 200 % for removing ) . I did not expect that . The nested dictionary needs to do more lookups , so why is the tuple dictionary that much slower ? My test code : Extra info on the test : The dictionary contains a total of 10 000 entries . The keys are incrementing : ( [ 0-100 ] , [ 0-100 ] , '' Property [ 0-100 ] '' ) .In a single test 100 keys are retrieved ( for which 10 % was not present in the dictionary ) , 100 values are updated ( for which 10 % are new ) or 100 keys are removed ( for which 10 % were not in the dictionary to begin with ) . Retrieval , updating and removing were 3 separate tests . Each test was executed 1000 times . I compared both the mean and median execution time . public static object TupleDic_RemoveValue ( object [ ] param ) { var dic = param [ 0 ] as Dictionary < ( int did , int eid , string name ) , string > ; var keysToRetrieve = param [ 2 ] as List < ( int did , int eid , string name ) > ; foreach ( var key in keysToRetrieve ) { dic.Remove ( key ) ; } return dic ; } public static object NestedDic_RemoveValue ( object [ ] param ) { var dic = param [ 1 ] as Dictionary < int , Dictionary < int , Dictionary < string , string > > > ; var keysToRetrieve = param [ 2 ] as List < ( int did , int eid , string name ) > ; foreach ( var key in keysToRetrieve ) { if ( dic.TryGetValue ( key.did , out var elementMap ) & & elementMap.TryGetValue ( key.eid , out var propertyMap ) ) propertyMap.Remove ( key.name ) ; } return dic ; }",Dictionary with tuple key slower than nested dictionary . Why ? "C_sharp : I have function implementation of DDE client using Win Api in C # . Everything works fine in case that I call DdeInitializeW and DdeConnect in single thread.Specifically , these are wrapper definitions : If I called DdeInitializeW and DdeConnect in different threads , DdeConnect return null pointer.Also , if I called both of them ( established DDE connection ) in one thread , I ca n't use this DDE channel in another thread ( i 'm getting INVALIDPARAMETER DDE error ) . As I said , everything works without problems in single thread . [ DllImport ( `` user32.dll '' ) ] protected static extern int DdeInitializeW ( ref int id , DDECallback cb , int afcmd , int ulres ) ; [ DllImport ( `` user32.dll '' ) ] static extern IntPtr DdeConnect ( int idInst , // instance identifier IntPtr hszService , // handle to service name string IntPtr hszTopic , // handle to topic name string IntPtr pCC // context data ) ;",C # Win Api DDE connection multithread "C_sharp : When an exception is possible to be thrown in a finally block how to propagate both exceptions - from catch and from finally ? As a possible solution - using an AggregateException : These exceptions can be handled like in following snippet : internal class MyClass { public void Do ( ) { Exception exception = null ; try { //example of an error occured in main logic throw new InvalidOperationException ( ) ; } catch ( Exception e ) { exception = e ; throw ; } finally { try { //example of an error occured in finally throw new AccessViolationException ( ) ; } catch ( Exception e ) { if ( exception ! = null ) throw new AggregateException ( exception , e ) ; throw ; } } } } private static void Main ( string [ ] args ) { try { new MyClass ( ) .Do ( ) ; } catch ( AggregateException e ) { foreach ( var innerException in e.InnerExceptions ) Console.Out.WriteLine ( `` -- -- Error : { 0 } '' , innerException ) ; } catch ( Exception e ) { Console.Out.WriteLine ( `` -- -- Error : { 0 } '' , e ) ; } Console.ReadKey ( ) ; }",What is the best practice in C # to propagate an exception thrown in a finally block without losing an exception from a catch block ? "C_sharp : I 'm switching to the latest version of ReactiveUI ( 7.0 ) and I 'm running into some incompatibilities and would like to know the suggested way to handle this : ReactiveUI 6.xThis now throws an exception : Command requires parameters of type System.Reactive.Unit , but received parameter of type System.Windows.Input.MouseButtonEventArgs.I fixed this by using the following code , but is this the right way ? Texts.Events ( ) .MouseUp .InvokeCommand ( ViewModel , x = > x.DoSomething ) ; Texts.Events ( ) .MouseUp .Select ( x = > Unit.Default ) .InvokeCommand ( ViewModel , x = > x.DoSomething ) ;",InvokeCommand arguments with ReactiveUI 7 "C_sharp : Consider the following code : When I run this code in visual studio express 2010 I do n't get an exception , as expected . I 'd expect one because I 'm removing something from a list while iterating it.What I do get is a list back with only the first child node removed : Why do I not get an invalid operation exception ? Note that the equivilent code in IDEOne.com does give the expected exception : http : //ideone.com/qoRBbbAlso note that if i remove all the LINQ ( .Cast ( ) .Where ( ) ) I get the same result , only one node removed , no exception.Is there some issue with my settings in VSExpress ? Note that I know deferred execution is involved , but I 'd expect the where clause , when iterated upon to iterate upon the source enumeration ( child note ) , which would give the exception I 'm expecting.My issue is that I do n't get that exception in VSexpress , but do in IDEOne ( I 'd expect it in both/all cases , or at least if not , I 'd expect the correct result ) .From Wouter 's answer it seems it 's invalidating the iterator when the first child is removed , rather than giving an exception . Is there anything official that says this ? Is this behaviour to be expected in other cases ? I 'd call invalidating the iterator silently rather than with an exception `` Silent but deadly '' . using System ; using System.Collections.Generic ; using System.Linq ; using System.Xml ; using System.Xml.Linq ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { XmlDocument xmlDoc = new XmlDocument ( ) ; xmlDoc.LoadXml ( @ '' < Parts > < Part name= '' '' DisappearsOk '' '' disabled= '' '' true '' '' > < /Part > < Part name= '' '' KeepMe '' '' disabled= '' '' false '' '' > < /Part > < Part name= '' '' KeepMe2 '' '' > < /Part > < Part name= '' '' ShouldBeGone '' '' disabled= '' '' true '' '' > < /Part > < /Parts > '' ) ; XmlNode root = xmlDoc.DocumentElement ; List < XmlNode > disabledNodes = new List < XmlNode > ( ) ; try { foreach ( XmlNode node in root.ChildNodes.Cast < XmlNode > ( ) .Where ( child = > child.Attributes [ `` disabled '' ] ! = null & & Convert.ToBoolean ( child.Attributes [ `` disabled '' ] .Value ) ) ) { Console.WriteLine ( `` Removing : '' ) ; Console.WriteLine ( XDocument.Parse ( node.OuterXml ) .ToString ( ) ) ; root.RemoveChild ( node ) ; } } catch ( Exception Ex ) { Console.WriteLine ( `` Exception , as expected '' ) ; } Console.WriteLine ( ) ; Console.WriteLine ( XDocument.Parse ( root.OuterXml ) .ToString ( ) ) ; Console.ReadKey ( ) ; } } }","Linq , XmlNodes , foreach 's and exceptions" "C_sharp : I came across the following question for an interview.For a given number of digits , generate all the numbers such that the value of a higher order digit is less than a lower order digit.145 // 1 < 4 < 5Is there a better ( efficient ) way to do this than the one I have come up with : EDIT : Output for 3 digits:123124125126127128129134135136137138139145146147148149156157158159167168169178179189234235236237238239245246247248249256257258259267268269278279289345346347348349356357358359367368369378379389456457458459467468469478479489567568569578579589678679689789 public static void GenerateSpecialNumbers ( int noDigits ) { int prod = 1 ; for ( int i=0 ; i < noDigits ; i++ ) { prod = prod * 10 ; } int minValue = prod/10 ; int maxValue = prod - 1 ; for ( int i = minValue ; i < maxValue ; i++ ) { bool isValid = true ; int num = i ; int max = int.MaxValue ; while ( num > 0 ) { int digit = num % 10 ; if ( digit > = max ) { isValid = false ; break ; } max = digit ; num = num/10 ; } if ( isValid ) Console.WriteLine ( i ) ; } }",Generating all the increasing digit numbers "C_sharp : I currently have the following code : Input string user can be in one of two formats : Whats the most elegant way in C # to convert either one of these strings to : string user = @ '' DOMAIN\USER '' ; string [ ] parts = user.Split ( new string [ ] { `` \\ '' } , StringSplitOptions.None ) ; string user = parts [ 1 ] + `` @ '' + parts [ 0 ] ; DOMAIN\USERDOMAIN\\USER ( with a double slash ) USER @ DOMAIN",C # convert DOMAIN\USER to USER @ DOMAIN "C_sharp : I have this class : The test code is : The Output is : So , obj2 's private member is accessed from another object obj1 . I think this is kind of strange.ADDHere is an useful link mentioned by Habib : Why are private fields private to the type , not the instance ? class C { private String msg ; public void F ( C obj , String arg ) { obj.msg = arg ; // this is strange , the msg should n't be accessible here . } public void Output ( ) { Console.WriteLine ( msg ) ; } } C obj1 = new C ( ) ; C obj2 = new C ( ) ; obj1.F ( obj2 , `` from obj1 '' ) ; obj2.Output ( ) ; from obj1",Why is this private member accessible ? "C_sharp : I 'm writing a program to help me search for a keyword inside thousands of files . Each of these files has unnecessary lines that i need to ignore because they mess with the results . Luckily they 're all located after a specific line inside those files.What i 've already got is a search , without ignoring the lines after that specific line , returning an Enumerable of the file names containing the keyword.Is there a simple and fast way to implement this functionality ? It does n't necessarily have to be in Linq as i 'm not even sure if this would be possible.Edit : An example to make it clearer.This is how the text files are structured : xxxxxxstringyyyyyyI want to search the xxx lines until either the keyword is found or the string and then skip to the next file . The yyy lines i want to ignore in my search . var searchResults = files.Where ( file = > File.ReadLines ( file.FullName ) .Any ( line = > line.Contains ( keyWord ) ) ) .Select ( file = > file.FullName ) ;",Searching in text files for a keyword until a string is encountered C_sharp : Automatic properties let me replace this code : with this code : with a few changes here and there - but is there a way to replace this code : with something similar ? private MyType myProperty ; public MyType MyProperty { get { return myPropertyField ; } } public MyType MyProperty { get ; private set ; } private readonly MyType myProperty ; public MyType MyProperty { get { return myPropertyField ; } },Is there a way to make readonly ( not just private ) automatic properties ? "C_sharp : My issue : inserting a set of data works on my local machine/MySQL database , but on production it causes a Duplicate entry for key 'PRIMARY ' error . As far as I can tell both setups are equivalent.My first thought was that it 's a collation issue , but I 've checked that the tables in both databases are using utf8_bin.The table starts out empty and I am doing .Distinct ( ) in the code , so there should n't be any duplicate entries.The table in question : Database.cs : MyTable.cs : Then using it : I 'm at a loss how there could be duplicate entries in the database after doing a .Distinct ( ) in the code , when using utf8_bin , especially since it works on one machine but not another . Does anyone have any ideas ? CREATE TABLE ` mytable ` ( ` name ` varchar ( 100 ) CHARACTER SET utf8 NOT NULL , ` appid ` int ( 11 ) NOT NULL , -- A few other irrelevant fields PRIMARY KEY ( ` name ` , ` appid ` ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin ; [ DbConfigurationType ( typeof ( MySql.Data.Entity.MySqlEFConfiguration ) ) ] public class Database : DbContext { public DbSet < MyTable > MyTable { get ; set ; } public static Database Get ( ) { /* Not important */ } //etc . } [ Table ( `` mytable '' ) ] public class MyTable : IEquatable < MyTable > , IComparable , IComparable < MyTable > { [ Column ( `` name '' , Order = 0 ) , Key , Required , DatabaseGenerated ( DatabaseGeneratedOption.None ) ] public string Name { get { return _name ; } set { _name = value.Trim ( ) .ToLower ( ) ; } } private string _name ; [ Column ( `` appid '' , Order = 1 ) , Key , Required , DatabaseGenerated ( DatabaseGeneratedOption.None ) ] public int ApplicationId { get ; set ; } //Equals ( ) , GetHashCode ( ) , CompareTo ( ) , == ( ) etc . all auto-generated by Resharper to use both Name and ApplicationId . //Have unit-tests to verify they work correctly . } using ( Database db = Database.Get ( ) ) using ( DbContextTransaction transaction = db.Database.BeginTransaction ( IsolationLevel.ReadUncommitted ) ) { IEnumerable < MyTable > newEntries = GetNewEntries ( ) ; //Verify no existing entries already in the table ; not necessary to show since table is empty anyways db.MyTable.AddRange ( newEntries.Distinct ( ) ) ; }","`` Duplicate entry for key primary '' on one machine but not another , with same data ?" "C_sharp : With the introduction of Roslyn , C # gets the benefit of the Safe Navigation operator.This is brilliant for objects that use dot notations e.g.In this instance myClass is null but the safe operator saves me from the exception . My question is if you have an indexed object is there an equivalent implementation of the safe navigation operator ? An example of needing this would look like this : In this instance myClass2 is not null but the ArrayOfStrings property is , so when I try and access it it will throw an exception . Because there is no dot notation between ArrayOfStrings and the index I ca n't add the safe nav operator . Because this is an array I can use the safe nav operator in the following way , but this does n't work for other collections such as Lists and DataRows MyClass myClass = null ; var singleElement = myClass ? .ArrayOfStrings [ 0 ] ; var myClass2 = new MyClass { ArrayOfStrings = null } ; var singleElement2 = myClass2 ? .ArrayOfStrings [ 0 ] ; var myClass3 = new MyClass { ArrayOfStrings = null } ; var singleElement3 = myClass3 ? .ArrayOfStrings ? .GetValue ( 0 ) ;",Safe Navigation of indexed objects "C_sharp : Not quite sure why this is happening , but I want to be able to modify the XNA color value : I thought having the ExpandableObjectConverter attribute would fix the issue , but it has not yet done so.Edit : I was able to patch together the following working code : private Color _color = Color.White ; [ System.ComponentModel.Category ( `` VisibleInEditor '' ) ] [ System.ComponentModel.TypeConverter ( typeof ( System.ComponentModel.ExpandableObjectConverter ) ) ] public Color Color { get { return _color ; } set { _color = value ; } } public class ColorTypeConverter : ExpandableObjectConverter { public override bool CanConvertTo ( ITypeDescriptorContext context , System.Type destinationType ) { return destinationType == typeof ( Color ) ; } public override object ConvertTo ( ITypeDescriptorContext context , System.Globalization.CultureInfo culture , object value , System.Type destinationType ) { if ( destinationType == typeof ( string ) & & value is Color ) { Color color = ( Color ) value ; return string.Format ( `` { 0 } , { 1 } , { 2 } , { 3 } '' , color.R , color.G , color.B , color.A ) ; } else return base.ConvertTo ( context , culture , value , destinationType ) ; } public override bool CanConvertFrom ( ITypeDescriptorContext context , System.Type sourceType ) { return sourceType == typeof ( string ) ; } public override object ConvertFrom ( ITypeDescriptorContext context , System.Globalization.CultureInfo culture , object value ) { if ( value is string ) { try { string strVal = value as string ; var parts = strVal.Split ( ' , ' ) ; byte r = byte.Parse ( parts [ 0 ] ) ; byte g = byte.Parse ( parts [ 1 ] ) ; byte b = byte.Parse ( parts [ 2 ] ) ; byte a = byte.Parse ( parts [ 3 ] ) ; return new Color ( r , g , b , a ) ; } catch { throw new ArgumentException ( `` Can not convert ' '' + ( string ) value + `` 'to type Color '' ) ; } } else return base.ConvertFrom ( context , culture , value ) ; } public override object CreateInstance ( ITypeDescriptorContext context , System.Collections.IDictionary propertyValues ) { return new Color ( ( byte ) propertyValues [ `` R '' ] , ( byte ) propertyValues [ `` G '' ] , ( byte ) propertyValues [ `` B '' ] , ( byte ) propertyValues [ `` A '' ] ) ; } public override bool GetCreateInstanceSupported ( ITypeDescriptorContext context ) { return true ; } public override PropertyDescriptorCollection GetProperties ( ITypeDescriptorContext context , object value , Attribute [ ] attributes ) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties ( value , attributes ) ; string [ ] sortOrder = new string [ 4 ] ; sortOrder [ 0 ] = `` R '' ; sortOrder [ 1 ] = `` G '' ; sortOrder [ 2 ] = `` B '' ; sortOrder [ 3 ] = `` A '' ; // Return a sorted list of properties return properties.Sort ( sortOrder ) ; } public override bool GetPropertiesSupported ( ITypeDescriptorContext context ) { return true ; } }",WinForms Property Grid wo n't allow me to change struct value "C_sharp : I hate having a bunch of `` left/right '' methods . Every time a property is added or removed , I have to fix up each method . And the code itself just looks ... wrong.Really this is just an unrolled loop that iterates through the properties , copying them between objects . So why not be honest about that fact ? Reflection to the rescue ! I may just be trying to force a paradigm I learned from Lua onto C # , but this particular example does n't seem too smelly to me . From here , I started to do some more complex things that were sensitive to the order of the fields . For example , rather than having a stack of virtually identical if statements to compose a string from the fields , I just iterate over them in the desired order : So now I have the iterability I wanted , but I still have stacks of code mirroring each property I 'm interested in ( I 'm also doing this for CompareTo , using a different set of properties in a different order ) . Worse than that is the loss of strong typing . This is really starting to smell.Well what about using attributes on each property to define the order ? I started down this road and indeed it worked well , but it just made the whole thing look bloated . It works great semantically , but I 'm always wary of using advanced features just because they 're `` neat . '' Is using reflection in this way overkill ? Is there some other solution to the left/right code problem I 'm missing ? public Foo ( Foo other ) { this.Bar = other.Bar ; this.Baz = other.Baz ; this.Lur = other.Lur ; this.Qux = other.Qux ; this.Xyzzy= other.Xyzzy ; } public Foo ( IFoo other ) { foreach ( var property in typeof ( IFoo ) .GetProperties ( ) ) { property.SetValue ( this , property.GetValue ( other , null ) , null ) ; } } public override string ToString ( ) { var toJoin = new List < string > ( ) ; foreach ( var property in tostringFields ) { object value = property.GetValue ( this , null ) ; if ( value ! = null ) toJoin.Add ( value.ToString ( ) ) ; } return string.Join ( `` `` , toJoin.ToArray ( ) ) ; } private static readonly PropertyInfo [ ] tostringFields = { typeof ( IFoo ) .GetProperty ( `` Bar '' ) , typeof ( IFoo ) .GetProperty ( `` Baz '' ) , typeof ( IFoo ) .GetProperty ( `` Lur '' ) , typeof ( IFoo ) .GetProperty ( `` Qux '' ) , typeof ( IFoo ) .GetProperty ( `` Xyzzy '' ) , } ;",How to use reflection to simplify constructors & comparisons ? "C_sharp : I am creating a reliable , stateful , service actor . Question : Is there a way to pass initialization data during the actor proxy creation ( ActorProxy.Create ( ) ) ? Basically an equivalent to a constructor for my actor.Current thoughts : I can achieve this by following up the proxy creation call with an actor method call in charge of initializing the state.E.g.My concern with such approach : This operation is not atomic . It may leave my actor in an inconsistent stateThis initialization method is now available throughout the life of the actor , which is undesired . //Danger , the following calls are not atomicITokenManager tokenActor = ActorProxy.Create < IMyActor > ( actorId , `` AppName '' ) ; //Something could happen here and leave my actor in an unknown stateawait tokenActor.InitializeAsync ( desiredInitialState ) ;",How to pass data to ` OnActivateAsync ( ) ` to initialize my stateful actor ? "C_sharp : I have dictionary which I 'm mapping using Fluent NHibernate . The dictionary has a complex key type CultureInfo . My database ca n't store that type so I want to use a string representation of it.In mappings other than dictionary mappings , I can successfully map CultureInfo-properties using a user type convention . Now I wonder how to do it for dicationary mappings.Here 's the entity that contains the dictionary : And here 's the auto mapping override for the entity : This mapping ( obviously ) causes the following error : Failed to convert parameter value from a CultureInfo to a String.I know NHibernate has a type custom type implementation for CultureInfo ( I 'm using it for mapping properties ) but how do I specify it in my mapping override ? public class MultilingualPhrase : Entity { private IDictionary < CultureInfo , string > languageValues ; public virtual IDictionary < CultureInfo , string > LanguageValues { get { return languageValues ; } } } public void Override ( AutoMapping < MultilingualPhrase > mapping ) { mapping .HasMany ( n = > n.LanguageValues ) .Access.ReadOnlyPropertyThroughCamelCaseField ( ) .AsMap < string > ( `` CultureName '' ) .Element ( `` Phrase '' ) .Table ( `` MultilingualPhraseValues '' ) ; }",How to map a dictionary with a complex key type ( CultureInfo ) using FluentNHibernate "C_sharp : I 'm trying to make this code working : this work for sync version of code , like this : but do n't work ( db operation throw an exception ) for async version of the same codeIs it somehow possible to convert async Action or Func to Delegate and invoke it without loosing async state ? protected async Task RunIsolated < TServ1 , TServ2 > ( Action < TServ1 , TServ2 > action ) { await RunInScope ( action , typeof ( TServ1 ) , typeof ( TServ2 ) ) ; } protected async Task < TResult > RunIsolatedForResult < TService , TResult > ( Func < TService , TResult > func ) { return ( TResult ) await RunInScope ( func , typeof ( TService ) ) ; } private Task < object > RunInScope ( Delegate d , params object [ ] args ) { using ( var scope = _serviceProvider.CreateScope ( ) ) { object [ ] parameters = args.Cast < Type > ( ) .Select ( t = > scope.ServiceProvider.GetService ( t ) ) .ToArray ( ) ; return Task.FromResult ( d.DynamicInvoke ( parameters ) ) ; } } await RunIsolated < Service > ( serv = > serv.SaveAsync ( item ) .Wait ( ) ) ; await RunIsolated < Service > ( async serv = > await serv.SaveAsync ( item ) ) ;",how to cast async Func or Action to Delegate and invoke it C_sharp : I just noticed that given the following code : the Microsoft C # 3.0 ( VS2008 SP1 ) compiler will optimize it to this : This is on Debug build without Optimization enabled . Why does the compiler do that ? Is it faster in terms of execution ? I used Reflector to find that out ( I was actually looking for something different ) if ( x.ID > 0 & & ! x.IsCool ) if ( ! ( ( x.Id < = 0 ) || x. IsCool ) ),Compiler Magic : Why ? "C_sharp : Recently I used a class that inherits from a collection instead of having the collection instantiated within the class , is this acceptable or does it create unseen problems further down the road ? Examples below for the sake of clarity : instead of something like : Any thoughts ? public class Cars : List < aCar > public class Cars { List < aCar > CarList = new List < aCar > ( ) ; }",Classes with Collections as Properties vs . Classes Inheriting Collections "C_sharp : When I run the following code in my test , Moq understandably throws the following exception : System.NotSupportedException : Invalid verify on a non-virtual ( overridable in VB ) member : writer = > writer.WriteAttributeString ( `` ID '' , .language.LanguageID.ToString ( ) ) .Stupid abstract XmlWriter still has some non-abstract , non-virtual methods , like WriteAttributeString ( ) : ( I looked for an XmlWriterBase or a System.Xml.Abstractions , like I do for HttpContext and Co. , but found nothing : ( How would I overcome this so I can test that my WriteXml method is doing what it 's supposed to be doing ? Mock < XmlWriter > mockXmlWriter = new Mock < System.Xml.XmlWriter > ( ) ; Language language = Language.GetLangauge ( langId ) ; language.WriteXml ( mockXmlWriter.Object ) ; mockXmlWriter.Verify ( writer = > writer.WriteAttributeString ( `` ID '' , language.LanguageID.ToString ( ) ) ) ;",How to mock System.Xml.XmlWriter.WriteAttributeString ( ) with moq ? "C_sharp : I have serialized a list of objects with protobuf-net.Theoretically , the .bin file can contain millions of objects.Let 's assume the objects are of a class containing the following : I have to take a query and create a list containing the objects matching the query.What is the correct way to extract the matching objects from the serialized file using LINQ ? public string EventName ;",Mass filtering with protobuf-net "C_sharp : I have a model class which is loaded from a `` GetById '' method in my repository class . I now need to add additional properties to this entity , which are n't saved in the database , but are calculated by a service class . Something like : So in order to load/saturate a MyEntity object , I need to load from the db , and then call the generator to determine the `` woo factor '' ( ahem ) . Where should this code go from an architectural viewpoint ? Current thoughts:1 ) In the repository : I feel like I 'm handing too much responsibility to the repo if I add it here.2 ) In the `` MyEntity '' class . Add the code in here that perhaps lazy-loads the WooFactor when it is accessed . This would add a lot of dependencies to MyEntity.3 ) A separate service class - seems overkill and un-necessary . public class MyEntity { public int ThingId { get ; set ; } ; public string ThingName { get ; set ; } // Set from the service public int WooFactor { get ; set ; } } public class WooFactorGenerator { public int CalculateWooFactor ( MyEntity thing ) ; // Hits other services and repo 's to eventually determine the woo factor . } // Code to get a `` MyEntity '' : var myEntity = repo.GetById ( 1 ) ; var gen = new WooFactorGenerator ( ) ; myEntity.WooFactor = gen.CalculateWooFactor ( myEntity ) ;",C # Domain Model + repository : Where to put code that loads an entity "C_sharp : I try to understand an extension method similar to this codeThis is my code inside RoslynPad : But i get this error error CS1109 : Extension methods must be defined in a top level static class ; PersonExtensions is a nested classI found this question extension-methods-must-be-defined-in-a-top-level-static-class- and the answers are good.Adding a namespace Foo returns error CS7021 : Can not declare namespace in script code It seems that roslynpad adds stuff behind the scene . So how can i make sure that my extension method is defined in a top-level static class ? var p = new Person ( `` Tim '' ) ; p.LastName = `` Meier '' ; // reader.Get < bool > ( `` IsDerivat '' ) ; var IsOlivia = p.Get < bool > ( `` Olivia '' ) ; public static class PersonExtensions { public static T Get < T > ( this Person person , string name ) { return ( T ) person.NewFirstName ( name ) ; } } public class Person { public Person ( string firstName ) { this.FirstName = firstName ; } public string FirstName { get ; private set ; } public string LastName { get ; set ; } public object NewFirstName ( string name ) { this.FirstName = name ; return ( object ) this.FirstName ; } }",Using Extension methods in RoslynPad "C_sharp : This is a common scenario I run into , where I have two ( or more ) actors getting some data asynchronously , and then I need to do an operation when they 're all finished.What is the common pattern to do this ? Here 's a simplified example.To kick this off I send the MasterActor a DoSomeWork message . What is the common way to do an operation when I have both a Actor1Response and an Actor2Response . I do n't really want to have logic in each receive handler checking if the other one is finished or anything like that . I guess what i 'm thinking of something similar to a Task.WaitAll ( ) method.Am I just attacking the problem the wrong way ? Do I need to re-write the actors in a different way ? Any common patterns or solutions would be awesome . public MasterActor : ReceiveActor { public MasterActor ( ) { Initialize ( ) ; } public void Initiaize ( ) { Receive < DoSomeWork > ( _ = > { var actor1 = Context.ActorOf ( Props.Create ( ( ) = > new Actor1 ( ) ) ; var actor2 = Context.ActorOf ( Props.Create ( ( ) = > new Actor2 ( ) ) ; // pretend these actors send responses to their senders // for sake of example each of these methods take between 1 and 3 seconds actor1.Tell ( new GetActor1Data ( ) ) ; actor2.Tell ( new GetActor2Data ( ) ) ; } ) ; Receive < Actor1Response > ( m = > { //actor 1 has finished it 's work } ) ; Receive < Actor2Response > ( m = > { //actor 2 has finished it 's work } ) ; } }",Akka.net waiting for multiple pieces of data "C_sharp : I 'm creating a program that allow user define formulas with on 4 basic operation : add , subtract , divide , multiple using XML . Let 's take an example : User want to define formula like ( a + b ) x ( c + d ) . The format of the xml as following : EDIT I had implement thisEDIT Solve . Many thanks to Yaniv 's suggestion . My solution as follow : classesI just have to decorate Calculator property with : < xPlugins > < xPlugin > < Multiple > < Add > < Operator > < value > 1 < /value > < /Operator > < Operator > < value > 2 < /value > < /Operator > < /Add > < Add > < Operator > < value > 3 < /value > < /Operator > < Operator > < value > 4 < /value > < /Operator > < /Add > < /Multiple > < /xPlugin > < /xPlugins > //root elementpublic class xPlugins { [ XmlElement ( `` xPlugin '' , typeof ( xPlugin ) ) ] public xPlugin [ ] Plugin { get ; set ; } } public class xPlugin { [ XmlElement ( `` Multiple '' , typeof ( Multiple ) ) ] [ XmlElement ( `` Add '' , typeof ( Add ) ) ] [ XmlElement ( `` Subtract '' , typeof ( Divide ) ) ] [ XmlElement ( `` Divide '' , typeof ( Divide ) ) ] [ XmlElement ( `` Operator '' , typeof ( Operand ) ) ] public Calculator calculator { get ; set ; } } //Deseirialize ultilitystatic class readXML { public static void getObject ( ref xPlugins plugins ) { try { List < Type > type = new List < Type > ( ) ; type.Add ( typeof ( Add ) ) ; type.Add ( typeof ( Minus ) ) ; type.Add ( typeof ( Multiple ) ) ; type.Add ( typeof ( Subtract ) ) ; type.Add ( typeof ( Operator ) ) ; XmlSerializer xml = new XmlSerializer ( typeof ( xPlugin ) , type.ToArray ( ) ) ; FileStream fs = new FileStream ( `` test.xml '' , FileMode.Open ) ; plugins = ( xPlugins ) xml.Deserialize ( fs ) ; } catch ( Exception ex ) { throw ; } } } public abstract class Calculator { [ XmlElement ( `` Multiple '' , typeof ( Multiple ) ) ] [ XmlElement ( `` Add '' , typeof ( Add ) ) ] [ XmlElement ( `` Subtract '' , typeof ( Subtract ) ) ] [ XmlElement ( `` Divide '' , typeof ( Divide ) ) ] [ XmlElement ( `` Operator '' , typeof ( Operand ) ) ] public List < Calculator > calculators { get ; set ; } public virtual int Calculate ( ) { return 0 ; } } public class Operator : Calculator { public int value { get ; set ; } public Operator ( ) { } public override int Calculate ( ) { return value ; } } public class Add : Calculator { public Add ( ) { } public override int Calculate ( ) { List < int > value = new List < int > ( ) ; foreach ( Calculator calculator in calculators ) { value.Add ( calculator.Calculate ( ) ) ; } return value.Sum ( ) ; } } public class Minus : Calculator { public Minus ( ) { } public override int Calculate ( ) { int value = calculators [ 0 ] .Calculate ( ) ; for ( int i = 1 ; i < calculators.Count ; i++ ) { value -= calculators [ i ] .Calculate ( ) ; } return value ; } } public class Divide : Calculator { public Divide ( ) { } public override int Calculate ( ) { int value = calculators [ 0 ] .Calculate ( ) ; for ( int i = 1 ; i < calculators.Count ; i++ ) { value /= calculators [ i ] .Calculate ( ) ; } return value ; } } public class Multiple : Calculator { public Multiple ( ) { } public override int Calculate ( ) { int value = calculators [ 0 ] .Calculate ( ) ; for ( int i = 1 ; i < calculators.Count ; i++ ) { value *= calculators [ i ] .Calculate ( ) ; } return value ; } } //running testprivate void button1_Click ( object sender , EventArgs e ) { readXML.getObject ( ref this.plugins ) ; foreach ( Calculator plugin in plugins.calculators ) { plugin.Calculate ( ) ; } } [ XmlElement ( `` Multiple '' , typeof ( Multiple ) ) ] [ XmlElement ( `` Add '' , typeof ( Add ) ) ] [ XmlElement ( `` Subtract '' , typeof ( Divide ) ) ] [ XmlElement ( `` Divide '' , typeof ( Divide ) ) ] [ XmlElement ( `` Operator '' , typeof ( Operand ) ) ]",Deserialize xml into super class object with C # "C_sharp : I am using the Microsoft RedisOutputCacheProvider and have a very simple PartialView which I am caching based on the current user 's SessionId via VaryByCustom : This works great and caches as expected , however I wanted to manually expire this OutputCache from another page . I tried : But that does n't seem to work . I also ca n't see any of the OutputCache keys via either my Redis store , or via my backend code , but I can definitely see the view being cached . [ OutputCache ( VaryByCustom = `` User '' , Duration = 3600 ) ] [ ChildActionOnly ] public ActionResult Notifications ( ) { return PartialView ( `` Partials/Notifications '' ) ; } Response.RemoveOutputCacheItem ( `` /Controller/Notifications '' ) ;",Using Response.RemoveOutputCacheItem with RedisOutputCacheProvider "C_sharp : I am attempting to apply the Strategy pattern to a particular situation , but am having an issue with how to avoid coupling each concrete strategy to the context object providing data for it . The following is a simplified case of a pattern that occurs a few different ways , but should be handled in a similar way.We have an object Acquisition that provides data relevant to a specific frame of time - basically a bunch of external data collected using different pieces of hardware . It 's already too large because of the amount of data it contains , so I do n't want to give it any further responsibility . We now need to take some of this data , and based on some configuration send a corresponding voltage to a piece of hardware.So , imagine the following ( much simplified ) classes : Now , every concrete strategy class has to be coupled to my Acquisition class , which is also one of the most likely classes to be modified since it 's core to our application . This is still an improvement over the old design , which was a giant switch statement inside the Acquisition class . Each type of data may have a different conversion method ( while Battery is a simple pass-through , others are not at all that simple ) , so I feel Strategy pattern or similar should be the way to go.I will also note that in the final implementation , IAnalogOutputter would be an abstract class instead of an interface . These classes will be in a list that is configurable by the user and serialized to an XML file . The list must be editable at runtime and remembered , so Serializable must be part of our final solution . In case it makes a difference.How can I ensure each implementation class gets the data it needs to work , without tying it to one of my most important classes ? Or am I approaching this sort of problem in the completely wrong manner ? class Acquisition { public Int32 IntegrationTime { get ; set ; } public Double Battery { get ; set ; } public Double Signal { get ; set ; } } interface IAnalogOutputter { double getVoltage ( Acquisition acq ) ; } class BatteryAnalogOutputter : IAnalogOutputter { double getVoltage ( Acquisition acq ) { return acq.Battery ; } }",Avoiding coupling with Strategy pattern "C_sharp : I 'm moving from the easy world of Ninject over to the fast world of Simple Injector , but I 'm getting stuck with SolrNet . A lot of the popular IoC 's have SolrNet integrations already , but not SimpleInjector.I 've started creating my own integration by converting the Unity stuff found athttps : //github.com/mausch/SolrNet/tree/master/Unity.SolrNetIntegrationDoes anyone either know if this has been done before ( by someone with better knowledge than me ) or can anyone convert the below to use simple injector : So far I have : But the injectionConstructor lines are obviously not for simple injector.ThanksUPDATEI should have mention that I was using solrNet 0.4.x so config will be slightly different.After looking at Steven 's answer I now have : but with this I get the error : The constructor of the type MappingValidator contains the parameter of type IValidationRule [ ] with name 'rules ' that is not registered . Please ensure IValidationRule [ ] is registered in the container , or change the constructor of MappingValidator . private static void RegisterSolrOperations ( SolrCore core , IUnityContainer container , bool isNamed = true ) { var ISolrReadOnlyOperations = typeof ( ISolrReadOnlyOperations < > ) .MakeGenericType ( core.DocumentType ) ; var ISolrBasicOperations = typeof ( ISolrBasicOperations < > ) .MakeGenericType ( core.DocumentType ) ; var ISolrOperations = typeof ( ISolrOperations < > ) .MakeGenericType ( core.DocumentType ) ; var SolrServer = typeof ( SolrServer < > ) .MakeGenericType ( core.DocumentType ) ; var registrationId = isNamed ? core.Id : null ; var injectionConstructor = new InjectionConstructor ( new ResolvedParameter ( ISolrBasicOperations , registrationId ) , new ResolvedParameter ( typeof ( IReadOnlyMappingManager ) ) , new ResolvedParameter ( typeof ( IMappingValidator ) ) ) ; container.RegisterType ( ISolrOperations , SolrServer , registrationId , injectionConstructor ) ; container.RegisterType ( ISolrReadOnlyOperations , SolrServer , registrationId , injectionConstructor ) ; } private static void RegisterSolrOperations ( SolrCore core , Container container , bool isNamed = true ) { var ISolrReadOnlyOperations = typeof ( ISolrReadOnlyOperations < > ) .MakeGenericType ( core.DocumentType ) ; var ISolrBasicOperations = typeof ( ISolrBasicOperations < > ) .MakeGenericType ( core.DocumentType ) ; var ISolrOperations = typeof ( ISolrOperations < > ) .MakeGenericType ( core.DocumentType ) ; var SolrServer = typeof ( SolrServer < > ) .MakeGenericType ( core.DocumentType ) ; var registrationId = isNamed ? core.Id : null ; var injectionConstructor = new InjectionConstructor ( new ResolvedParameter ( ISolrBasicOperations , registrationId ) , new ResolvedParameter ( typeof ( IReadOnlyMappingManager ) ) , new ResolvedParameter ( typeof ( IMappingValidator ) ) ) ; container.Register ( ISolrOperations , SolrServer , registrationId , injectionConstructor ) ; container.Register ( ISolrReadOnlyOperations , SolrServer , registrationId , injectionConstructor ) ; } container.RegisterSingle < IReadOnlyMappingManager > ( new MemoizingMappingManager ( new AttributesMappingManager ( ) ) ) ; container.Register < ISolrDocumentPropertyVisitor , DefaultDocumentVisitor > ( ) ; container.Register < ISolrFieldParser , DefaultFieldParser > ( ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrDocumentActivator < > ) , typeof ( SolrDocumentActivator < > ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrDocumentResponseParser < > ) , typeof ( SolrDocumentResponseParser < > ) ) ; container.Register < ISolrFieldSerializer , DefaultFieldSerializer > ( ) ; container.Register < ISolrQuerySerializer , DefaultQuerySerializer > ( ) ; container.Register < ISolrFacetQuerySerializer , DefaultFacetQuerySerializer > ( ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrAbstractResponseParser < > ) , typeof ( DefaultResponseParser < > ) ) ; container.Register < ISolrHeaderResponseParser , HeaderResponseParser < string > > ( ) ; container.Register < ISolrExtractResponseParser , ExtractResponseParser > ( ) ; container.RegisterAll < IValidationRule > ( new [ ] { typeof ( MappedPropertiesIsInSolrSchemaRule ) , typeof ( RequiredFieldsAreMappedRule ) , typeof ( UniqueKeyMatchesMappingRule ) } ) ; container.Register < ISolrConnection > ( ( ) = > new SolrConnection ( url ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrMoreLikeThisHandlerQueryResultsParser < > ) , typeof ( SolrMoreLikeThisHandlerQueryResultsParser < > ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrQueryExecuter < > ) , typeof ( SolrQueryExecuter < > ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrDocumentSerializer < > ) , typeof ( SolrDocumentSerializer < > ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrBasicOperations < > ) , typeof ( SolrBasicServer < > ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrBasicReadOnlyOperations < > ) , typeof ( SolrBasicServer < > ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrOperations < > ) , typeof ( SolrServer < > ) ) ; container.RegisterAllOpenGeneric ( typeof ( ISolrReadOnlyOperations < > ) , typeof ( SolrServer < > ) ) ; container.Register < ISolrSchemaParser , SolrSchemaParser > ( ) ; container.Register < ISolrDIHStatusParser , SolrDIHStatusParser > ( ) ; container.Register < IMappingValidator , MappingValidator > ( ) ;",Simple Injector and SolrNet "C_sharp : I am trying to practice manual dependency injection ( no framework yet ) to remove tight coupling in my code . This is just for practice - I do n't have a specific implementation in mind.So far simple constructor injection has worked fine.However I can not work out how to solve creating a tight coupling when one class must use another within a parallel loop . Example : Avoiding the obvious fact that a parallel loop will be slower than a standard loop in the above case , how could i write the Processor.DoStuffInParallel ( ) method to avoid the current hard dependency on the Worker class ? public class Processor { private IWorker worker ; public Processor ( IWorker worker ) { this.worker = worker ; } public List < string > DoStuff ( ) { var list = new List < string > ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { list.Add ( worker.GetString ( ) ) ; } return list ; } public List < string > DoStuffInParallel ( ) { var list = new System.Collections.Concurrent.ConcurrentBag < string > ( ) ; Parallel.For ( 0 , 10 , i = > { //is there any trivial way to avoid this ? ? list.Add ( new Worker ( ) .GetString ( ) ) ; } ) ; return list.ToList ( ) ; } } public class Worker : IWorker { public string GetString ( ) { //pretend this relies on some instance variable , so it not threadsafe return `` a string '' ; } }",Dependency injection with parallel processing "C_sharp : I 'm using NUnit mocks and would like to specify that I expect a call but without saying what the arguments will be for example : Obviously filling in the correct syntax instead of ANY_ARGUMENT.Is there a way to do this ? If I specify no arguments - NUnit fails the test because it expected 0 arguments but received 1 . mock.ExpectAndReturn ( `` Equals '' , true , ANY_ARGUMENT ) ;",Is there a way to specify ANYTHING as an argument to NUnit Mocks Expect call ? "C_sharp : I have a problem with my client side script not calculating the same values as my server side code : For example : This gives a figure of 0.28500000000000003However my server side code ( C # ) calculates a figures of 0.285 which when rounded to 2 decimal places gives 0.28If I try and round 0.28500000000000003 to 2 decimal places I get 0.29.How do I get my Javascript to create a figure that matches my server side code.It looks like I have to go through 2 lots of rounding - firstly to remove the trailing 3 , then the rounding to the required decimal places.For example : Is this the best workaround ? ( this is a re-wording of a question I opened and deleted earlier ) var x = ( 2.85 * .1 ) ; alert ( x ) ; var x = 0.2850000000003 ; x = parseFloat ( x.toFixed ( 3 ) ) x = x.toFixed ( 2 ) alert ( x ) ;",Javascript floating point problem - Rounding issue ? "C_sharp : I have a generic type that should be specified with an Enum type ( actually , it 's one of several specified enums , but I 'll settle for System.Enum ) .Of course the compiler balks at code like : with a `` Constraint can not be special class 'System.Enum ' '' exception.The only solution I 've been able to come up so far is using the static type initializer to inspect the type parameter and throw an exception if it is not , in fact , an Enum , like this : which at least gives me runtime security that it wont we used with a non-enum parameter . However this feels a bit hacky , so is there a better way to accomplish this , ideally with a compile-time construct ? class Generic < T > where T : Enum { } class Generic < T > { static Generic ( ) { if ( typeof ( T ) .BaseType ! = typeof ( Enum ) ) throw new Exception ( `` Invalid Generic Argument '' ) ; } }",Restricting the generic type parameter to System.Enum "C_sharp : The following event can possibly get called hundreds of times a frame.I understand that using `` is '' causes a cast to be made and then when i want to do something with it , cast it a second time . Is there a more efficient way to check the type ? I made a console app trying `` if ( body2.Tag.GetType ( ) == typeOf ( Dog ) ) '' but it appears to be even slower than using `` is '' .Thanks . public bool OnCollision ( Body body1 , Body body2 ) { if ( body2.Tag is Dog ) ( ( Dog ) body2.Tag ) .Bark ( ) ; }",Fastest Type Comparison ? "C_sharp : I overrided Template of a control in ResourceDictionary Generic.xaml . In that I added a button on which i wanted to add some events.So in Loaded event of control I did Some where on Internet I read that I can doWhen I tried doing this suggestion for GetTemplateChild says Do Not Use.So my question is Why not to use GetTemplateChild . Is it obsolete ? AndWhat is the difference between FrameWorkTemplate.FindName and ControlTemplate.FindName ? < Setter Property= '' Template '' > < Setter.Value > -- Added my button here . < /Setter.Value > < /Setter > Button b = ( Button ) mycontrol.Template.FindName ( `` PARTName '' , mycontrol ) //Add Events on my button public override void OnApplyTemplate ( ) { base.OnApplyTemplate ( ) ; UIElement editingelement = GetTemplateChild ( `` PART_EditingElement '' ) ; if ( editingelement ! = null ) { // do something } }",Is GetTemplateChild Obsolete in .Net 3.5 and what is the difference between FrameWorkTemplate.FindName and ControlTemplate.FindName C_sharp : I have 3 ( Edit ) mutually exclusive IEnumerables that I want to iterate over . I want to do something like this : The best way I can think of is : Is there a more concise way to do this ? Seems like combinding IEnumberables should be trivial . IEnumerable < Car > redCars = GetRedCars ( ) ; IEnumerable < Car > greenCars = GetGreenCars ( ) ; IEnumerable < Car > blueCars = GetBlueCars ( ) ; foreach ( Car c in ( redCars + greenCars + blueCars ) ) { c.DoSomething ( ) ; } ... ... List < Car > allCars = new List ( ) ; allCars.AddRange ( redCars ) ; allCars.AddRange ( greenCars ) ; allCars.AddRange ( blueCars ) ; foreach ( car in allCars ) { ... } ...,Foreach over a collection of IEnumerables "C_sharp : A piece of code in the CMS I 'm using ( DNN ) throws the following exception : '' Index was outside the bounds of the array . `` With the stacktrace saying : It is an issue that only happens sometimes ( I suspect it has something to do with the cache getting broken ) and only in production . This means I ca n't consistently reproduce it . I 'm mostly interested in how it might happen.How is it possible that a call to 'Contains ' triggers an index out of bounds ? Extra infoThe code calling the Contains works the following way ( I 've simplified the code to make the important parts more readable . The links lead to the exact classes and linenumbers ) CustomUrlDictController.csCacheController.csDataCache ( 1 , 2 ) Full stack trace at System.Collections.Generic.List ` 1.Contains ( T item ) List < int > urlPortals ; var cc = new CacheController ( ) ; cc.GetFriendlyUrlIndexFromCache ( out urlPortals ) ; var boolean = urlPortals.Contains ( portalId ) ; // This is where the exception happens . void GetFriendlyUrlIndexFromCache ( out List < int > urlPortals ) { urlPortals = null ; object rawPortals = DataCache.GetCache ( UrlPortalsKey ) ; if ( rawPortals ! = null ) { urlPortals = ( List < int > ) rawPortals ; } } object GetCache ( string CacheKey ) { return Cache [ cacheKey ] ; } InnerMessage : Index was outside the bounds of the array.InnerStackTrace : at System.Collections.Generic.List ` 1.Contains ( T item ) at DotNetNuke.Entities.Urls.CustomUrlDictController.FetchCustomUrlDictionary ( Int32 portalId , Boolean forceRebuild , Boolean bypassCache , FriendlyUrlSettings settings , SharedDictionary ` 2 & customAliasForTabs , Guid parentTraceId ) at DotNetNuke.Entities.Urls.TabPathHelper.GetTabPath ( TabInfo tab , FriendlyUrlSettings settings , FriendlyUrlOptions options , Boolean ignoreCustomRedirects , Boolean homePageSiteRoot , Boolean isHomeTab , String cultureCode , Boolean isDefaultCultureCode , Boolean hasPath , Boolean & dropLangParms , String & customHttpAlias , Boolean & isCustomPath , Guid parentTraceId ) at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.ImproveFriendlyUrlWithMessages ( TabInfo tab , String friendlyPath , String pageName , PortalSettings portalSettings , Boolean ignoreCustomRedirects , FriendlyUrlSettings settings , List ` 1 & messages , Boolean cultureSpecificAlias , Guid parentTraceId ) at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.ImproveFriendlyUrl ( TabInfo tab , String friendlyPath , String pageName , PortalSettings portalSettings , Boolean ignoreCustomRedirects , Boolean cultureSpecificAlias , FriendlyUrlSettings settings , Guid parentTraceId ) at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.FriendlyUrlInternal ( TabInfo tab , String path , String pageName , String portalAlias , PortalSettings portalSettings ) at DotNetNuke.Entities.Urls.AdvancedFriendlyUrlProvider.FriendlyUrl ( TabInfo tab , String path , String pageName , PortalSettings portalSettings ) at DotNetNuke.Services.Url.FriendlyUrl.DNNFriendlyUrlProvider.FriendlyUrl ( TabInfo tab , String path , String pageName , PortalSettings settings ) at DotNetNuke.Common.Globals.NavigateURL ( Int32 tabID , Boolean isSuperTab , PortalSettings settings , String controlKey , String language , String pageName , String [ ] additionalParameters ) at DotNetNuke.Common.Globals.NavigateURL ( Int32 tabID , String controlKey , String [ ] additionalParameters ) at Ventrian.SimpleGallery.RandomPhoto.GetAlbumUrl ( String albumID ) at Ventrian.SimpleGallery.RandomPhoto.BindPhoto ( PlaceHolder phPhoto , PhotoInfo objPhoto ) at Ventrian.SimpleGallery.RandomPhoto.dlGallery_OnItemDataBound ( Object sender , DataListItemEventArgs e ) at System.Web.UI.WebControls.DataList.OnItemDataBound ( DataListItemEventArgs e ) at System.Web.UI.WebControls.DataList.CreateItem ( Int32 itemIndex , ListItemType itemType , Boolean dataBind , Object dataItem ) at System.Web.UI.WebControls.DataList.CreateControlHierarchy ( Boolean useDataSource ) at System.Web.UI.WebControls.BaseDataList.OnDataBinding ( EventArgs e ) at System.Web.UI.WebControls.BaseDataList.DataBind ( ) at Ventrian.SimpleGallery.RandomPhoto.Page_Load ( Object sender , EventArgs e )",Index Out Of Bounds on List.Contains "C_sharp : Given a base class Coinand two derived classes Coin50Cent and Coin25CentThe task is to create an object of a CoinMachine ( used for coin exchange , e.g . puting 50 cent coin returns two 25 cent coins ) that corresponds the following requierments : CoinMachine must have two collections of Coin25Cent and Coin50cent objects . The collections must be derived from an abstract generic class CoinStack < T > that has two methodsvoid Push ( T item ) ; T Pop ( ) ; CoinMachine must work as followsHere 's my implementationSeems like I have a problem with casting in abstract CoinStack class . public class Coin { } public class Coin50 : Coin { } public class Coin25 : Coin { } CoinMachine.Push ( new Coin25 ( ) ) ; // puts 25cent in 25c stackCoinMachine.Push ( new Coin50 ( ) ) ; // puts 50cent in 50c stackCoinMachine.Pop ( ) ; // gets 50cent from 50c stackCoinMachine.Pop ( ) ; // gets 25cent from 25c stack namespace ConsoleApplication1 { /* Given condition */ class Program { static void Main ( string [ ] args ) { CoinMachine.Push ( new Coin25 ( ) ) ; CoinMachine.Push ( new Coin50 ( ) ) ; CoinMachine.Pop < Coin50 > ( ) ; CoinMachine.Pop < Coin25 > ( ) ; } } public class Coin { } public class Coin50 : Coin { } public class Coin25 : Coin { } /* End given condition */ public interface ICoinStack { T Pop < T > ( ) ; void Push < T > ( T item ) ; } /* The problem within this abstract class */ public abstract class CoinStack < T > : ICoinStack { private Queue < T > _stack = new Queue < T > ( ) ; public T Pop < T > ( ) { return _stack.Dequeue ( ) ; } public void Push < T > ( T item ) { _stack.Enqueue ( item ) ; } } public class CoinStack50 : CoinStack < Coin50 > { } public class CoinStack25 : CoinStack < Coin25 > { } public class CoinMachine { private static Dictionary < Type , ICoinStack > map ; static CoinMachine ( ) { map = new Dictionary < Type , ICoinStack > ( ) { { typeof ( Coin50 ) , new CoinStack50 ( ) } , { typeof ( Coin25 ) , new CoinStack25 ( ) } } ; } public static T Pop < T > ( ) { var type = typeof ( T ) ; return map [ type ] .Pop < T > ( ) ; } public static void Push < T > ( T item ) { var type = typeof ( T ) ; map [ type ] .Push ( item ) ; } } }",Casting in generic abstract class that implements interface "C_sharp : We have a .NET 4 Website Project created using Visual Studio 2013 , it references the System.Net.Http .dll.This is the line in web.config that loads the .dll : The project builds fine but when we try to “ Publish Web Site ” it gives the following error : The type or namespace name ‘ Http ’ does not exist in the namespace ‘ System.Net ’ ( are you missing an assembly reference ? ) It looks like the assembly might be loading from the GAC , we have tried putting the assembly in the application ’ s BIN folder but this makes no difference – it is still showing as a GAC reference on the project property pages.We have also tried adding : As suggested here : Could not load file or assembly System.Web.Http.WebHost after published to Azure web siteBut this does not seem to work either.We have changed the Target Framework to 3.5 and 4.5 with no effect.We have tried publishing from several different machines.EDIT : We have tried the nuget package suggest in RobAda and it has n't had the desired effect , we are still getting errors . < add assembly= '' System.Net.Http , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a '' / > < runtime > < assemblyBinding > < dependentAssembly > < assemblyIdentity name= '' System.Net.Http '' publicKeyToken= '' b03f5f7f11d50a3a '' culture= '' neutral '' / > < codeBase version= '' 1.0.0.0 '' href= '' /bin/System.Net.Http.dll '' / > < /dependentAssembly > < /assemblyBinding >",ASP.NET Website Project builds but errors on publish "C_sharp : Adding EF Core to a NET Standard project introduces transitive dependency versions incompatible with NuGet packages in other projectsI have a solution with multiple .NET Standard 2.0 projects.One Project A uses the Google.Protobuf ( 3.11.2 ) NuGet package , that depends on A few other projects also depend on System.Memory and all use the same dependency versions.Another Project B uses Microsoft.EntityFrameworkCore ( 3.1.0 ) NuGet package that depends on Even though the System.Memory version is ( 4.5.3 ) in both cases , it depends on System.Buffers , System.Numerics.Vectors and System.Runtime.CompilerServices.Unsafe and their versions differ.When I run the application that uses these projects ( a Microsoft Prism WPF .NET Framework 4.8 app that uses Unity IoC ) UnityContainer throws the following exception : System.IO.FileLoadException : 'Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe , Version=4.0.4.1 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a ' or one of its dependencies . The located assembly 's manifest definition does not match the assembly reference . After searching for a solution I added this to my NuGet.Config : In both , % appdata % \Nuget and in the root folder of the .sln file.I also deleted the % userprofile % \.nuget\packages folder.Then I removed the NuGet packages from the projects and added them back again , but their dependecies come with the same versions as before.If I navigate to `` Manage NuGet Packages for Solution ... '' in Visual Studio and choose `` Consolidate '' it just says `` No packages found '' System.Memory ( 4.5.3 ) System.Buffers ( 4.4.0 ) System.Numerics.Vectors ( 4.4.0 ) System.Runtime.CompilerServices.Unsafe ( 4.5.2 ) System.Memory ( 4.5.3 ) System.Buffers ( 4.5.0 ) System.Numerics.Vectors ( 4.5.0 ) System.Runtime.CompilerServices.Unsafe ( 4.7.0 ) < config > < add key= '' DependencyVersion '' value= '' Highest '' / > < /config >",Unable to consolidate NuGet package transitive dependency versions in two NET Standard projects "C_sharp : What is a shorthand way to String.Join a non-string array as in the second example ? string [ ] names = { `` Joe '' , `` Roger '' , `` John '' } ; Console.WriteLine ( `` the names are { 0 } '' , String.Join ( `` , `` , names ) ) ; //okdecimal [ ] prices = { 39.99M , 29.99m , 29.99m , 19.99m , 49.99m } ; Console.WriteLine ( `` the prices are { 0 } '' , String.Join ( `` , `` , prices ) ) ; //bad overload",What is the best way to String.Join a non-string array ? "C_sharp : I have a subclass of DynamicObject and I would like to implement implicit casting for primitive types similarly as DO 's explicit casting method TryConvert ; that is , without writing multiple implicit operator [ type ] functions.Usage : Is that possible and if so , how ? dynamic myDynamicObject = new MyDynamicObject ( `` 1 '' ) ; int sum = 1 + myDynamicObject ; // instead of int i = 1 + ( int ) myDynamicObject ;",DynamicObject implicit casting "C_sharp : I want to expose an IObservable from my service layer . For simplicity lets say that internally the service layer is getting Message from a remote server ( via a socket ) and that the socket library requires an object of IMessageReponse that has a MessageReceived method to be passed to it . Internally the service layer creates a MessageResponse object and get notified by a Action callback when a message arrives . Given this design I need to be able to push new messages to the IObservable but in any of the examples I 've seen , Observable.XYZ does n't seem to support a simple Send/Publish/Push method ... How do I wireup my Observable.XYZ in this scenario ? ? ? I want something like this ... note I know this is a very basic implementation of IObservable , but I would n't have thought I would need to write this code myself ... I would have thought that something would have been there for me out of the box . public class PushObservable < T > : IObservable < T > { private IList < IObserver < T > > _listeners = new List < IObserver < T > > ( ) ; public void Send ( T value ) { foreach ( var listener in _listeners ) listener.OnNext ( value ) ; } public IDisposable Subscribe ( IObserver < T > observer ) { _listeners.Add ( observer ) ; } }",IObservable - How to Send/Publish/Push new values to collection "C_sharp : I wish to implement OWIN as per the example I could find here : http : //www.asp.net/web-api/overview/security/individual-accounts-in-web-api However , since this way of working is new to me especially using my self created database I would like some guidance.I can submit my registration request without a problem.The post takes me to the AccountController : This triggers the below code : ApplicationUserManager : But for some weird reason I 'm gettingEven though I do n't use name anywhere ? ! Where is this name coming from ? So I presume I 'm doing something wrong but it 's hard to debug without a clear explanation on how to implement OWIN with an existing DB.Below my context/entity and users table that I would like to use to store me user data.context : users : IdentityUser : Edit : If I add UserName back to my new users object before I try to call CreateAsync , the error is gone but I get another one instead : Edit II : I also have this issue in the tutorial code ! This is just a freaking bug in .NET ? Edit IIII tried to do an override as you can see in the partial class Users above . But I still have the same error . [ AllowAnonymous ] [ Route ( `` Register '' ) ] public async Task < IHttpActionResult > Register ( RegisterBindingModel model ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } try { var email = model.Email ; var password = model.Password ; var user = new users ( ) { Email = email , PasswordHash = password , Password = password } ; IdentityResult result = await UserManager.CreateAsync ( user , model.Password ) ; if ( ! result.Succeeded ) { return GetErrorResult ( result ) ; } return Ok ( ) ; } catch ( Exception ex ) { throw ; } } public ApplicationUserManager UserManager { get { return _userManager ? ? Request.GetOwinContext ( ) .GetUserManager < ApplicationUserManager > ( ) ; } private set { _userManager = value ; } } public class ApplicationUserManager : UserManager < users > { public ApplicationUserManager ( IUserStore < users > store ) : base ( store ) { } public static ApplicationUserManager Create ( IdentityFactoryOptions < ApplicationUserManager > options , IOwinContext context ) { var manager = new ApplicationUserManager ( new UserStore < users > ( context.Get < DaumAuctionEntities > ( ) ) ) ; var dataProtectionProvider = options.DataProtectionProvider ; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6 , RequireNonLetterOrDigit = false , RequireDigit = false , RequireLowercase = true , RequireUppercase = true , } ; if ( dataProtectionProvider ! = null ) { manager.UserTokenProvider = new DataProtectorTokenProvider < users > ( dataProtectionProvider.Create ( `` ASP.NET Identity '' ) ) ; } return manager ; } } modelState : { undefined : [ `` Name can not be null or empty . '' ] } public partial class DaumAuctionEntities : IdentityDbContext < users > { public DaumAuctionEntities ( ) : base ( `` name=DaumAuctionEntities '' ) { } public DbSet < addresses > addresses { get ; set ; } public DbSet < auctions > auctions { get ; set ; } public DbSet < images > images { get ; set ; } public DbSet < users > users { get ; set ; } } public partial class users : IdentityUser { public override string UserName { get { return Email ; } set { Email = value ; } } override public string PasswordHash { get { return Password ; } set { Password = value ; } } public async Task < ClaimsIdentity > GenerateUserIdentityAsync ( UserManager < users > manager , string authenticationType ) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync ( this , authenticationType ) ; // Add custom user claims here return userIdentity ; } } public partial class users { public int Id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public System.DateTime CreatedDate { get ; set ; } public Nullable < System.DateTime > ModifiedDate { get ; set ; } } `` The specified type member 'UserName ' is not supported in LINQ to Entities . Only initializers , entity members , and entity navigation properties are supported . ''",Implementing OWIN using existing Database name validation ? "C_sharp : How can I do the Ruby method `` Flatten '' Ruby Method in C # . This method flattens a jagged array into a single-dimensional array.For example : s = [ 1 , 2 , 3 ] # = > [ 1 , 2 , 3 ] t = [ 4 , 5 , 6 , [ 7 , 8 ] ] # = > [ 4 , 5 , 6 , [ 7 , 8 ] ] a = [ s , t , 9 , 10 ] # = > [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 , [ 7 , 8 ] ] , 9 , 10 ] a.flatten # = > [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10",Flatten Ruby method in C # "C_sharp : I 'm glad C # does n't let you access static members 'as though ' they were instance members . This avoids a common bug in Java : On the other hand , it does let you access static members 'through ' derived types . Other than operators ( where it saves you from writing casts ) , I ca n't think of any cases where this is actually helpful . In fact , it actively encourages mistakes such as : I personally keep committing similar errors over and over when I am searching my way through unfamiliar APIs ( I remember starting off with expression trees ; I hit BinaryExpression . in the editor and was wondering why on earth IntelliSense was offering me MakeUnary as an option ) .In my ( shortsighted ) opinion , this feature : Does n't reduce verbosity ; the programmer has to specify a type-name one way or another ( excluding operators and cases when one is accessing inherited static members of the current type ) . Encourages bugs/ misleading code such as the one above.May suggest to the programmer that static methods in C # exhibit some sort of 'polymorphism ' , when they do n't . ( Minor ) Introduces 'silent ' , possibly unintended rebinding possibilities on recompilation . ( IMO , operators are a special case that warrant their own discussion . ) Given that C # is normally a `` pit of success '' language , why does this feature exist ? I ca n't see its benefits ( other than 'discoverability ' , which could always be solved in the IDE ) , but I see lots of problems . Thread t = new Thread ( .. ) ; t.sleep ( .. ) ; //Probably does n't do what the programmer intended . // Nasty surprises ahead - wo n't throw ; does something unintended : // Creates a HttpWebRequest instead.var ftpRequest = FtpWebRequest.Create ( @ '' http : //www.stackoverflow.com '' ) ; // Something seriously wrong here.var areRefEqual = Dictionary < string , int > .ReferenceEquals ( dict1 , dict2 ) ;",Why is it useful to access static members `` through '' inherited types ? "C_sharp : I 'm trying to code a WCF service on Monotouch/Monodevelop for IOS . I was using standard attributes like [ DataMember ] / [ DataContract ] for my serializable object and [ ServiceContract ] / [ OperationContract ] for my interface . Everything worked fine , but when I tried to implement a method returning an IEnumerable on the interface implementation ( server side ) , it did n't worked.So to solve my problem I tried to use the latest version of protobuf-net being protobuf-net v2 beta r404 . But I 'm still getting a serialization error from Protobuf-net . Note that the IEnumerable in `` MyObject '' serialize without problem . Here 's how my code looks right now : MyObject : My interface ( Server side on Windows ) : My interface ( client side on IOS , I ca n't add ProtoBehavior as attribute becuase it is not in the ISO dll of protobuf ) : My interface implementation : [ ProtoContract ] public class MyObject { public MyObject ( ) { } [ ProtoMember ( 1 ) ] public int Id { get ; set ; } [ ProtoMember ( 2 ) ] public IEnumerable < MyObject > myObjects { get ; set ; } } [ ServiceContract ] public interface ITouchService { [ OperationContract , ProtoBehavior ] MyObject Execute ( ) ; [ OperationContract , ProtoBehavior ] IEnumerable < MyObject > ExecuteENUM ( ) ; } [ ServiceContract ] public interface ITouchService { [ OperationContract ] MyObject Execute ( ) ; [ OperationContract ] IEnumerable < MyObject > ExecuteENUM ( ) ; } public class TouchService : ITouchService { public MyObject Execute ( ) { var myObject = new MyObject ( ) { Id = 9001 } ; var myList = new List < MyObject > ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { myList.Add ( new MyObject ( ) { Id = i } ) ; } // Will serialize myObject.myObjects = myList ; return myObject ; } public IEnumerable < MyObject > ExecuteENUM ( ) { var myEnum = new List < MyObject > ( ) ; for ( int i = 0 ; i < 10 ; i++ ) { myEnum.Add ( new MyObject ( ) { Id = i } ) ; } return myEnum ; } }",Serializing an IEnumerable trough WCF using Protobuf-net and Monotouch for IOS "C_sharp : I am trying to sort the lists inside a list by their minimum integer value . This is where I am at so far.For example : The output of my Linq shall be , to sort the lists by the minimum value in the list of lists . The sequence for the Lists in my example would be : y - > z - > xI have tried a lot of linq expressions and searched through the web . The question seems to be very simple ... Thanks for any kind of help ! var SortedList = from lists in List orderby lists.List.Min ( Min= > Min.value ) ascending select list ; var x = new List < int > { 5 , 10 , 4 , 3 , 0 } ; var y = new List < int > { 4 , -1 , -5 , 3 , 2 } ; var z = new List < int > { 3 , 1 , 0 , -2 , 2 } ; var ListofLists = new List < List < int > > { x , y , z } ;",Sort a list of lists by minimum value "C_sharp : Given a .NET type object found through reflection , is it possible to pretty print or decompile this type as a C # declaration , taking into account C # type aliases , etc . ? For example , I want to be able to print out methods close to what was originally written in the source.If there is n't anything in the .NET framework , is there a third-party library ? I might possibly have a look at ILSpy . Int32 - > intString - > string Nullable < Int32 > - > int ? List < au.net.ExampleObject > - > List < ExampleObject >",Get C # -style type reference from CLR-style type full name "C_sharp : LINQPad example : Uncommenting the Two ( PrintInteger ) ; line results in an error : can not convert from 'method group ' to 'System.Linq.Expressions.Expression < System.Action < int > > 'This is similar to Convert Method Group to Expression , but I 'm interested in the `` why . '' I understand that Features cost money , time and effort ; I 'm wondering if there 's a more interesting explanation . void Main ( ) { One ( i = > PrintInteger ( i ) ) ; One ( PrintInteger ) ; Two ( i = > PrintInteger ( i ) ) ; // Two ( PrintInteger ) ; - wo n't compile } static void One ( Action < int > a ) { a ( 1 ) ; } static void Two ( Expression < Action < int > > e ) { e.Compile ( ) ( 2 ) ; } static void PrintInteger ( int i ) { Console.WriteLine ( i ) ; }",Why are lambdas convertible to expressions but method groups are not ? "C_sharp : I have a small problem with asynchronous loading scripts on my web page.I need to load all scripts of page asynchronously . I tried many procedures , which I found on google , but still it is not perfect.Now I have it like this : Split all scripts from layout to one bundle including jquery.On bottom of the page call RenderFormat with async tag.Now this is where I get the problem : I need to solve the situation where the scripts are being rendered by @ RenderFormat . The problem is that thosescripts are being rendered earlier than I need.For example I have this in Home/Index file : or simplyHere we get error , `` $ is not defined '' , because jquery is not loaded yet.After content , in Layout file I have : If I take all of my scripts on page and give them to one bundle , everything is fine , but I do n't want scripts to get rendered , I need to do that only in a specific section.Next idea was to create a custom RenderSection method , that will do someting like this : Is there way , how to solve it ? Thank you very much for your time . @ Scripts.RenderFormat ( `` < script async type=\ '' text/javascript\ '' src=\ '' { 0 } \ '' > < /script > '' , `` ~/bundles/raphael '' ) ... $ ( `` .datapicker '' ) .datapicker ( ) ; ... ... @ Scripts.RenderFormat ( `` < script async type=\ '' text/javascript\ '' src=\ '' { 0 } \ '' > < /script > '' , `` ~/bundles/frontall '' ) ... @ RenderSection ( `` scripts '' , required : false ) function async ( u , c ) { var d = document , t = 'script ' , o = d.createElement ( t ) , s = d.getElementsByTagName ( t ) [ 0 ] ; o.src = u ; if ( c ) { o.addEventListener ( 'load ' , function ( e ) { c ( null , e ) ; } , false ) ; } s.parentNode.appendChild ( o , s ) ; } async ( `` /bundles/jquery '' , function ( ) { //here , load scripts from inner pages . Index , Detail ... } ) ;",Mvc complete asynchronous scripts loading "C_sharp : I have the following code which has the goal to wait for all given wait handles but is cancellable by a specific wait handle : This works only for ManualReset events . When using AutoReset events WaitAny resets all signalled events but returns only the first signalled ( according MSDN ) .Any ideas how to get this done with AutoReset events in a proper way without polling ? public static bool CancelableWaitAll ( WaitHandle [ ] waitHandles , WaitHandle cancelWaitHandle ) { var waitHandleList = new List < WaitHandle > ( ) ; waitHandleList.Add ( cancelWaitHandle ) ; waitHandleList.AddRange ( waitHandles ) ; int handleIdx ; do { handleIdx = WaitHandle.WaitAny ( waitHandleList.ToArray ( ) ) ; waitHandleList.RemoveAt ( handleIdx ) ; } while ( waitHandleList.Count > 1 & & handleIdx ! = 0 ) ; return handleIdx ! = 0 ; }",C # WaitHandle cancelable WaitAll "C_sharp : I am learning MVC 3 and I have not found people using some logic codes inside a property of a data model class.They do the data model class as follows ( for example ) : Is it ok to have logic codes inside a property as follows ? Edit 1 : This is my real scenario : Child table data model : Parent table data model : Consumer : public class Customer { public int CustomerId { get ; set ; } //other properties without any logic code . } public class Customer { private int customerId ; public int CustomerId { get { return customerId ; } set { customerId=value ; // some logic codes go here . } } //other properties go here . } namespace MvcApplication1.Models { public class Choice { public int ChoiceId { get ; set ; } public string Description { get ; set ; } public bool IsCorrect { get ; set ; } public QuizItem QuizItem { get ; set ; } } } namespace MvcApplication1.Models { public class QuizItem { public int QuizItemId { get ; set ; } public string Question { get ; set ; } private IEnumerable < Choice > choices ; public IEnumerable < Choice > Choices { get { return choices ; } set { choices = value ; foreach ( var x in choices ) x.QuizItem = this ; } } } } namespace MvcApplication1.Controllers { public class HomeController : Controller { public ActionResult Index ( ) { var data = new List < QuizItem > { new QuizItem { QuizItemId = 1 , Question = `` What color is your hair ? `` , Choices = new Choice [ ] { new Choice { ChoiceId=1 , Description= '' Black . `` , IsCorrect=true } , new Choice { ChoiceId=2 , Description= '' Red . `` , IsCorrect=false } , new Choice { ChoiceId=3 , Description= '' Yellow . `` , IsCorrect=false } } } , new QuizItem { QuizItemId = 2 , Question = `` What color is your noze ? `` , Choices = new Choice [ ] { new Choice { ChoiceId=1 , Description= '' Pink . `` , IsCorrect=false } , new Choice { ChoiceId=2 , Description= '' Maroon . `` , IsCorrect=true } , new Choice { ChoiceId=3 , Description= '' Navy Blue . `` , IsCorrect=false } } } } ; return View ( data ) ; } } }",Is it OK to have some logic codes inside a property of a data model class ? "C_sharp : Possible Duplicate : difference between throw and throw new Exception ( ) I 'm a programmer working on adding new functionality to legacy code . While debugging , I parsed over this Catch block , which got an angry `` object not set to reference of object '' notice from Visual Studio : What does it mean to `` throw '' . I 'm familiar with throw new [ exceptiontype ] ... but what does it mean to just ... throw ? Is this good practice , or should I alter this code to ease the trials of the developers after me ? And why does Visual Studio yell at me for doing this ? catch ( Exception ex ) { SporeLog.Log ( `` Failed to create new SavedDocumentList with Name : `` + name , ex ) ; throw ; }",Using `` Throw '' in a catchblock ( and nothing else ! ) "C_sharp : When adding a controller for a model , the generated actions will look something like thisNow in my case I take a string id which can map to DB IDs in several ways , producing several lines of code for retrieval of the correct entity . Copy & pasting that code to every action which takes an id to retrieve an entity feels very inelegant . Putting the retrieval code in a private function of the controller reduces the amount of duplicate code but I 'm still left with this : Is there a way to perform the lookup in an attribute and pass the entity to the action ? Coming from python , this could easily be achieved with a decorator . I managed to do something similar for WCF services by implementing an IOperationBehavior which still does not feel as straight-forward . Since retrieving an entity by id is something you frequently need to do I 'd expect there to be a way other than copy & pasting code around.Ideally it would look something like this : where EntityLookup takes an arbitrary function mapping string id to Entity and either returns HttpNotFound or calls the action with the retrieved entity as the parameter . public ActionResult Edit ( int id = 0 ) { Entity entity = db.Entities.Find ( id ) ; if ( entity == null ) { return HttpNotFound ( ) ; } return View ( entity ) ; } var entity = GetEntityById ( id ) ; if ( entity == null ) return HttpNotFound ( ) ; [ EntityLookup ( id = > db.Entities.Find ( id ) ) ] public ActionResult Edit ( Entity entity ) { return View ( entity ) ; }",Automatically pass Entity to Controller Action "C_sharp : When trying to deploy a web application to Azure using a service account with the Google .net client library it is returning with the following error 502 - Web server received an invalid response while acting as a gateway or proxy server.Code example : The code above works when run in development . However when deployed to AZURE it returns an error . var certificate = new X509Certificate2 ( KeyFilePath , `` notasecret '' , X509KeyStorageFlags.Exportable ) ; ServiceAccountCredential credential = new ServiceAccountCredential ( new ServiceAccountCredential.Initializer ( serviceAccountEmail ) { Scopes = new string [ ] { AnalyticsService.Scope.Analytics } ; } .FromCertificate ( certificate ) ) ; // Create the service.AnalyticsService service = new AnalyticsService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = `` Analytics API Sample '' , } ) ;",Web server received an invalid response while acting as a gateway or proxy server "C_sharp : I have a timer app and I want to vibrate the phone once the timer has finished . I can currently play a sound until the OK button is pressed , but it only vibrates once . How can repeat the vibration until the user presses the OK button ? This is my current codeUPDATE : I have tried Joe 's response , which works if I do n't call MessageBox.Show ( ) It seems to stop at this point until OK is pressed . SoundEffectInstance alarmSound = PlaySound ( @ '' Alarms/ '' +alarmSoundString ) ; VibrateController vibrate = VibrateController.Default ; vibrate.Start ( new TimeSpan ( 0,0,0,0,1000 ) ) ; MessageBoxResult alarmBox = MessageBox.Show ( `` Press OK to stop alarm '' , `` Timer Finished '' , MessageBoxButton.OK ) ; if ( alarmBox == MessageBoxResult.OK ) { alarmSound.Stop ( ) ; vibrate.Stop ( ) ; }",Vibrate until message box closed Windows Phone 7 "C_sharp : We have a solution where we are storing a fairly large/complex C # object in our database as binary data . My concern is that when changes are made to this class , we run the risk that data saved to the database will fail on deserialization after the code change.Here are is the code we 're using to serialize objects : Here is our Deserialize method : My question is , what has to change/how much has to change in order for deserialization of an older object to fail ? public static byte [ ] SerializeObject ( object toBeSerialized ) { var stream = new MemoryStream ( ) ; var serializer = new BinaryFormatter ( ) ; serializer.Serialize ( stream , toBeSerialized ) ; stream.Position = 0 ; return stream.ToArray ( ) ; } public static T DeserializeObject < T > ( byte [ ] toBeDeserialized ) { using ( var input = new MemoryStream ( toBeDeserialized ) ) { var formatter = new BinaryFormatter ( ) ; input.Seek ( 0 , SeekOrigin.Begin ) ; return ( T ) formatter.Deserialize ( input ) ; } }",How much does a class/object have to change in order for binary-deserialization to fail "C_sharp : Possible Duplicate : Runtime exception , recursion too deep I 'm getting a problem while developing a c # .net program and I 've simplified it to a simple problem , I need to understand why does this code throw a stackoverflow exception if I call the function like this : but works fine if I call it like thishere is the function : tried to make the code as simple as it can get ... I understand that there is a stack that gets overflowed but which stack ? How can I fix this ? Thanks . CheckFunc ( 16000 ) ; CheckFunc ( 1000 ) ; private void CheckFunc ( Int32 i ) { if ( i == 0 ) MessageBox.Show ( `` good '' ) ; else CheckFunc ( i - 1 ) ; }",stackoverflow by a recursion "C_sharp : I have the following code to get a list of Month names : For some reason , this keeps returning an additional empty string value along with the Month names : I am using Xamarin Studio . Anyone else encounter this before ? var monthNames = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames ;",.Net CultureInfo Month Names returning an extra empty string "C_sharp : I am currently working on a game in XNA and I 'm not sure on how I should go about doing the following ... I have a base class of buildings as suchI then have multiple subclasses for building types eg.My question is , what is the best way of setting the default values for building subclasses . For example , the woodRequired for a townhall is set to 500 but at various places in code I need to access this value before I have an instance of townhall declared ( When checking if there is enough wood to build ) . I currently have a global array of default variables for each building type but im wondering if there is a better way of doing this . public class BuildingsBase { private int _hp ; public int hp { get { return _hp ; } set { _hp= value ; } } private int _woodRequired ; public int woodRequired { get { return _woodRequired ; } set { _woodRequired = value ; } } } public class TownHall : BuildingsBase { public int foodHeld ; public TownHall ( ) { foodHeld = 100 ; woodRequired = 500 ; } } if ( Globals.buildingDefaults [ BuildingType.Townhall ] .woodRequired < Globals.currentWood ) { Townhall newTH = new Townhall ( ) ; }",C # Subclass Best Practice "C_sharp : I want to zoom in the pdf file in an iframe on + button click and zoom out on -here is my design and c # . File given in src is a dummy one and i am loading the actual file at onload of the page.any approach is fine for me whether it be JavaScript , Css , Jquery , serverside..please help.. thanks in advance.onload on serverside : < div style= '' padding-bottom : 5px ; margin-top:1 % ; width:18 % ; float : left ; text-align : right ; '' > < asp : Button ID= '' ZoomIn '' Text= '' + '' runat= '' server '' / > < asp : Button ID= '' ZoomOut '' Text= '' - '' runat= '' server '' / > < /div > < div id= '' Container '' style= '' float : left ; width:100 % ; text-align : center ; padding-bottom : 5px ; '' > < iframe class= '' Zoomer '' id= '' iFmManl '' runat= '' server '' src= '' ~\sample.pdf '' width= '' 100 % '' height= '' 900px '' style= '' border : 0px inset black ; margin-left : 0px ; '' title= '' Domain Dictionary '' > < /iframe > < /div > < /div > protected void Page_Load ( object sender , EventArgs e ) { iFmManl.Attributes [ `` src '' ] = FileName + `` # toolbar=0 & navpanes=0 & view=Fit '' ; }",Zooming a PDF inside an iframe upon Button click "C_sharp : Is it bad policy to have lots of `` work '' classes ( such as Strategy classes ) , that only do one thing ? Let 's assume I want to make a Monster class . Instead of just defining everything I want about the monster in one class , I will try to identify what are its main features , so I can define them in interfaces . That will allow to : Seal the class if I want . Later , other users can just create a new class and still have polymorphism by means of the interfaces I 've defined . I do n't have to worry how people ( or myself ) might want to change/add features to the base class in the future . All classes inherit from Object and they implement inheritance through interfaces , not from mother classes.Reuse the strategies I 'm using with this monster for other members of my game world.Con : This model is rigid . Sometimes we would like to define something that is not easily achieved by just trying to put together this `` building blocks '' .My idea would be next to make a series of different Strategies that could be used by different monsters . On the other side , some of them could also be used for totally different purposes ( i.e. , I could have a tank that also `` swims '' ) . The only problem I see with this approach is that it could lead to a explosion of pure `` method '' classes , i.e. , Strategy classes that have as only purpose make this or that other action . In the other hand , this kind of `` modularity '' would allow for high reuse of stratagies , sometimes even in totally different contexts.What is your opinion on this matter ? Is this a valid reasoning ? Is this over-engineering ? Also , assuming we 'd make the proper adjustments to the example I gave above , would it be better to define IWalk as : orbeing that doing this I would n't need to define the methods on Monster itself , I 'd just have public getters for IWalkStrategy ( this seems to go against the idea that you should encapsulate everything as much as you can ! ) Why ? Thanks public class AlienMonster : IWalk , IRun , ISwim , IGrowl { IWalkStrategy _walkStrategy ; IRunStrategy _runStrategy ; ISwimStrategy _swimStrategy ; IGrowlStrategy _growlStrategy ; public Monster ( ) { _walkStrategy = new FourFootWalkStrategy ( ) ; ... etc } public void Walk ( ) { _walkStrategy.Walk ( ) ; } ... etc } interface IWalk { void Walk ( ) ; } interface IWalk { IWalkStrategy WalkStrategy { get ; set ; } //or something that ressembles this }",Strategy pattern and `` action '' classes explosion "C_sharp : I 'm creating a DateTime by adding a day to the current date ( shown below ) . I need the specific time set as shown below as well . This code below works great until I get to the end of the month where I 'm trying to add a day.Can you help me change my code so that it works when the current day is at the end of a month and I 'm trying to add a day so that it switches to December 1st instead of November 31st ( for example ) and throws an error . var ldUserEndTime = new DateTime ( dateNow.Year , dateNow.Month , dateNow.Day + 1 , 00 , 45 , 00 ) ;",How to add day to DateTime at end of month ? "C_sharp : Let 's say I have this structure , and this structure.How would I convert from one structure to the other ? [ StructLayout ( LayoutKind.Explicit ) ] public struct Chapter4Time { [ FieldOffset ( 0 ) ] public UInt16 Unused ; [ FieldOffset ( 2 ) ] public UInt16 TimeHigh ; [ FieldOffset ( 4 ) ] public UInt16 TimeLow ; [ FieldOffset ( 6 ) ] public UInt16 MicroSeconds ; } [ StructLayout ( LayoutKind.Explicit ) ] public struct IEEE_1588Time { [ FieldOffset ( 0 ) ] public UInt32 NanoSeconds ; [ FieldOffset ( 4 ) ] public UInt32 Seconds ; }",Casting explicitly-laid out structures "C_sharp : I have a number of Windows 7 PC 's that need patching with a particular Windows update , using the Windows Update API in a C # console app . The API needs to search the installed updates and report back if it 's already installed and perform the installation if not . Whilst testing on a Virtual PC ( Windows 7 Professional Hyper-v client ) I have a situation similar to the target PCs ( Windows 7 Embedded ) where the following code returns ( very quickly and without any exceptions ) 0 updates . Which I know to be wrong . In fact , it even returns this after I install a .msu update.Code : Now for the fun part . If I open up the Windows Update from the Control Panel and click 'Check for updates ' , it goes off for a while and comes back with a bunch of updates to install . At this point , if I run the above code , it works as expected and reports over 200 installed updates.It appears that the manual process of searching for updates starts/restarts some services and/or other processes , however , I am struggling to figure out exactly what I need to do to the system to get it into the correct state . I expect the answer will be a simple case of starting service x or process y with a set of args , but which ? Some ( not all ) of the things I have tried but did not alter the behavior : Started the BITS service , restarted Windows Update ServiceTried launching wuauclt.exe with various switches ( documentedhere in the comments ) With the machine in a state where the code runs correctly ( after I run WU manually ) , I have noticed the process wuauclt.exe appears to start when the above code is run . When it 's in the target state ( before I run WU manually ) , wuauclt.exe does not start , and I am not able to launch this manually , I suspect this is a big clue . One other clue is the state of Windows Update before I run it manually . In the control panel windows update looks like this : After running WU and installing updates via that method , and the machine is in a state where the code runs as expected WU looks like : To sum up , I need this process to automate the installation of an update . If I detect 0 installed updates , I know the machine is in a particular state , so I will need to launch/restart some processes and services ( programmatically ) to get the machine into the correct state before running my code . Knowing what to run/restart is the essence of this problem . UpdateSession uSession = new UpdateSession ( ) ; IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher ( ) ; uSearcher.Online = false ; try { ISearchResult sResult = uSearcher.Search ( `` IsInstalled=1 And IsHidden=0 '' ) ; Console.WriteLine ( `` Found `` + sResult.Updates.Count + `` updates '' ) ; foreach ( IUpdate update in sResult.Updates ) { Console.WriteLine ( update.Title ) ; if ( update.Title.ToLower ( ) .Contains ( `` kb123456 '' ) ) { //Update is not required ReportInstalled ( ) ; return ; } } //If we get here , the update is not installed InstallUpdate ( ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Something went wrong : `` + ex.Message ) ; }",Windows Update API with C # not finding any installed updates "C_sharp : First of all let 's say I have two separated aggregates Basket and Order in an e-commerece website.Basket aggregate has two entities Basket ( which is the aggregate root ) and BaskItem defined as following ( I have removed factories and other aggregate methods for simplicity ) : The second aggregate which is Order has Order as aggregate root and OrderItem as entity and Address and CatalogueItemOrdered as value objects defined as following : Now If the user wants to checkout after adding several items to basket there are several actions should be applied : Updating Basket ( maybe some items ' quantity has been changed ) Adding/Setting new OrderDeleting the basket ( or flag as deleted in DB ) Paying via CreditCard using specific Payment gateway.As I can see there are several transactions should be executed because depending on DDD in every transaction only one aggregate should be changed.So could you please guide me to how can I implement that ( maybe by using Eventual consistency ) in a way I do n't break DDD principles ? PS : I appreciate any references or resources public class Basket : BaseEntity , IAggregateRoot { public int Id { get ; set ; } public string BuyerId { get ; private set ; } private readonly List < BasketItem > items = new List < BasketItem > ( ) ; public IReadOnlyCollection < BasketItem > Items { get { return items.AsReadOnly ( ) ; } } } public class BasketItem : BaseEntity { public int Id { get ; set ; } public decimal UnitPrice { get ; private set ; } public int Quantity { get ; private set ; } public string CatalogItemId { get ; private set ; } } public class Order : BaseEntity , IAggregateRoot { public int Id { get ; set ; } public string BuyerId { get ; private set ; } public readonly List < OrderItem > orderItems = new List < OrderItem > ( ) ; public IReadOnlyCollection < OrderItem > OrderItems { get { return orderItems.AsReadOnly ( ) ; } } public DateTimeOffset OrderDate { get ; private set ; } = DateTimeOffset.Now ; public Address DeliverToAddress { get ; private set ; } public string Notes { get ; private set ; } } public class OrderItem : BaseEntity { public int Id { get ; set ; } public CatalogItemOrdered ItemOrdered { get ; private set ; } public decimal Price { get ; private set ; } public int Quantity { get ; private set ; } } public class CatalogItemOrdered { public int CatalogItemId { get ; private set ; } public string CatalogItemName { get ; private set ; } public string PictureUri { get ; private set ; } } public class Address { public string Street { get ; private set ; } public string City { get ; private set ; } public string State { get ; private set ; } public string Country { get ; private set ; } public string ZipCode { get ; private set ; } }",How to implement checkout in a DDD-based application ? "C_sharp : I have a method where I 'd like to use a Rectangle optional parameter with default value of ( 1,1,1,1 ) .How do I resolve this ? ( I 'm using XNA , so it 's a Microsoft.Xna.Framework.Rectangle . ) void Method ( int i , int j = 1 , Rectangle rect = new Rectangle ( 1,1,1,1 ) ) { } //error",Optional parameter in method not compile-time constant error with Rectangle "C_sharp : The structure of the XML is as follows : Id , and price are both integer values . Name and description are strings.I 've found Linq to XML great for what I 've used it for , this is just a snippet . But , on the other hand I get the feeling it should or could be cleaner . The casting seems the most obvious issue in this snippet.Any advice ? var subset = from item in document.Descendants ( `` Id '' ) where item.Value == itemId.ToString ( ) select new PurchaseItem ( ) { Id = int.Parse ( item.Parent.Element ( `` Id '' ) .Value ) , Name = item.Parent.Element ( `` Name '' ) .Value , Description = item.Parent.Element ( `` Description '' ) .Value , Price = int.Parse ( item.Parent.Element ( `` Price '' ) .Value ) } ; < Items > < Item > < Id > < /Id > < Name > < /Name > < Description > < /Description > < Price > < /Price > < /Item > < /Items >",Is Linq-XML always so messy ? "C_sharp : I 've many examples using LINQ how to divide a list into sub-list according to max items in each list . But In this case I 'm interested in diving a sub-lists using sizemb as a weight - having a max total filesize per list of 9mb.The above list should then be divided into 3 lists . If any 'files ' are more than 9mb they should be in their own list.I made a non LINQ-version here : public class doc { public string file ; public int sizemb ; } var list = new List < doc > ( ) { new doc { file = `` dok1 '' , sizemb = 5 } , new doc { file = `` dok2 '' , sizemb = 5 } , new doc { file = `` dok3 '' , sizemb = 5 } , new doc { file = `` dok4 '' , sizemb = 4 } , } ; int maxTotalFileSize = 9 ; var lists = new List < List < doc > > ( ) ; foreach ( var item in list ) { //Try and place the document into a sub-list var availableSlot = lists.FirstOrDefault ( p = > ( p.Sum ( x = > x.sizemb ) + item.sizemb ) < maxGroupSize ) ; if ( availableSlot == null ) lists.Add ( new List < doc > ( ) { item } ) ; else availableSlot.Add ( item ) ; }",LINQ : Split list into groups according to weight/size "C_sharp : I want to implement TypeConverter for a custom type , Thickness . I 've looked over the microsoft released typeconverters like SizeConverter.When I type a string or change one of the properties on my Thickness property , the designer works with it , it just does n't save the change to 'Designer.cs ' . It has to be the conversion from the type 'Thickness ' to 'InstanceDescriptor ' but I ca n't find anything wrong with my code ... Here is Thickness : And here is the type converter : The only thing I can think of is does the converter have to be in a seperate assembly than the designer code using it ? [ TypeConverter ( typeof ( ThicknessConverter ) ) ] public struct Thickness { Double top ; Double bottom ; Double right ; Double left ; public Thickness ( Double uniformLength ) { top = uniformLength ; bottom = uniformLength ; right = uniformLength ; left = uniformLength ; } public Thickness ( Double left , Double top , Double right , Double bottom ) { this.left = left ; this.top = top ; this.right = right ; this.bottom = bottom ; } public Double Top { get { return top ; } set { top = value ; } } public Double Bottom { get { return bottom ; } set { bottom = value ; } } public Double Right { get { return right ; } set { right = value ; } } public Double Left { get { return left ; } set { left = value ; } } public Double UniformLength { get { if ( ! IsUniform ) throw new InvalidOperationException ( ) ; else return top ; } set { top = value ; bottom = value ; right = value ; bottom = value ; } } public Boolean IsUniform { get { return top == bottom & & bottom == right & & bottom == left ; } } } public class ThicknessConverter : TypeConverter { public ThicknessConverter ( ) { } public override Boolean CanConvertTo ( ITypeDescriptorContext context , Type destinationType ) { return destinationType == typeof ( String ) || destinationType == typeof ( InstanceDescriptor ) ; } public override Object ConvertTo ( ITypeDescriptorContext context , System.Globalization.CultureInfo culture , Object value , Type destinationType ) { Thickness thickness = ( Thickness ) value ; if ( destinationType == typeof ( String ) ) { if ( thickness.IsUniform ) return thickness.Right.ToString ( ) ; else return thickness.Left + `` , '' + thickness.Top + `` , '' + thickness.Right + `` , '' + thickness.Bottom ; } else if ( destinationType == typeof ( InstanceDescriptor ) ) { if ( thickness.IsUniform ) return new InstanceDescriptor ( typeof ( Thickness ) .GetConstructor ( new Type [ ] { typeof ( Double ) } ) , new Object [ ] { thickness.UniformLength } ) ; else { ConstructorInfo constructor = typeof ( Thickness ) .GetConstructor ( new Type [ ] { typeof ( Double ) , typeof ( Double ) , typeof ( Double ) , typeof ( Double ) } ) ; return new InstanceDescriptor ( constructor , new Object [ ] { thickness.Left , thickness.Top , thickness.Right , thickness.Bottom } ) ; } } else return null ; } public override Boolean CanConvertFrom ( ITypeDescriptorContext context , Type sourceType ) { return sourceType == typeof ( String ) ; } public override Object ConvertFrom ( ITypeDescriptorContext context , System.Globalization.CultureInfo culture , Object value ) { if ( value is String ) { String stringValue = ( String ) value ; if ( stringValue.Contains ( `` , '' ) ) { String [ ] stringValues = stringValue.Split ( ' , ' ) ; Double [ ] values = new Double [ stringValues.Length ] ; if ( values.Length == 4 ) { try { for ( Int32 i = 0 ; i < 4 ; i++ ) values [ i ] = Double.Parse ( stringValues [ i ] ) ; } catch ( Exception ) { return new Thickness ( ) ; } return new Thickness ( values [ 0 ] , values [ 1 ] , values [ 2 ] , values [ 3 ] ) ; } else return new Thickness ( ) ; } else { try { return new Thickness ( Double.Parse ( stringValue ) ) ; } catch ( Exception ) { return new Thickness ( ) ; } } } else return base.ConvertFrom ( context , culture , value ) ; } public override Boolean GetCreateInstanceSupported ( ITypeDescriptorContext context ) { return true ; } public override Object CreateInstance ( ITypeDescriptorContext context , System.Collections.IDictionary propertyValues ) { return new Thickness ( ( Double ) propertyValues [ `` Left '' ] , ( Double ) propertyValues [ `` Top '' ] , ( Double ) propertyValues [ `` Right '' ] , ( Double ) propertyValues [ `` Bottom '' ] ) ; } public override Boolean GetPropertiesSupported ( ITypeDescriptorContext context ) { return true ; } public override PropertyDescriptorCollection GetProperties ( ITypeDescriptorContext context , Object value , Attribute [ ] attributes ) { PropertyDescriptorCollection collection = TypeDescriptor.GetProperties ( typeof ( Thickness ) ) ; collection = collection.Sort ( new String [ ] { `` Left '' , `` Top '' , `` Right '' , `` Bottom '' } ) ; collection.RemoveAt ( 4 ) ; collection.RemoveAt ( 4 ) ; return collection ; } }",Implementing TypeConverter for Windows Forms "C_sharp : withreplacewith System.Tuple is type but used like a variable error map < pair < unsigned int , unsigned int > , unsigned int > kmapValues ; private Dictionary < KeyValuePair < uint , uint > , uint > kmapValues ; kmapValues [ make_pair ( j , i ) ] = 1 kmapValues [ Tuple ( j , i ) ] = 1 // got error",How to translate make_pair in c++ to c # ? "C_sharp : I started messing around with multithreading for a CPU intensive batch process I 'm running . Essentially I 'm trying to condense multiple single page tiffs into single PDF documents . This works fine with a foreach loop or standard iteration but can be very slow for several 100 page documents . I tried the following based on a some examples I found to use multithreading and it has significant performance improvements however it obliterates the page order instead of 1,2,3,4 it will be 1,3,4,2,6,5 on what thread completes first . My question is how would I utilize this technique while maintaining the page order and if I can will it negate the performance benefit of the multithreading ? Thank you in advance . PdfDocument doc = new PdfDocument ( ) ; string mail = textBox1.Text ; string [ ] split = mail.Split ( new string [ ] { Environment.NewLine } , StringSplitOptions.None ) ; int counter = split.Count ( ) ; // Source must be array or IList.var source = Enumerable.Range ( 0 , 100000 ) .ToArray ( ) ; // Partition the entire source array.var rangePartitioner = Partitioner.Create ( 0 , counter ) ; double [ ] results = new double [ counter ] ; // Loop over the partitions in parallel.Parallel.ForEach ( rangePartitioner , ( range , loopState ) = > { // Loop over each range element without a delegate invocation . for ( int i = range.Item1 ; i < range.Item2 ; i++ ) { f_prime = split [ i ] .Replace ( `` `` , `` '' ) ; PdfPage page = doc.AddPage ( ) ; XGraphics gfx = XGraphics.FromPdfPage ( page ) ; XImage image = XImage.FromFile ( f_prime ) ; double x = 0 ; gfx.DrawImage ( image , x , 0 ) ; } } ) ;",Multithreading for loop while maintaining order "C_sharp : I have an IIS 7.5 website running .NET 4.0 in Classic pipeline mode.I have created a simple default image setup where if an image is called but the physical file does not exist the request is redirected to a default image using the following code in the Application_BeginRequest event : This works fine on my VS2010 dev server but when on a production environment the Application_BeginRequest event is not called for JPG requests and all I get is the standard HTTP Error 404.0 - Not Found error.I have tried setting the runAllManagedModulesForAllRequests option in the Web.Config to true but this does not appear to help : From my understanding this should cause all requests to go through .NET and therefore trigger the Application_BeginRequest event ? Desired Outcome : I 'd like all requests to go through .NET so that the Application_BeginRequest event is called for JPGs and a default image is returned if no image is found . protected void Application_BeginRequest ( object sender , EventArgs e ) { if ( Request.PhysicalPath.EndsWith ( `` .jpg '' ) & & File.Exists ( Request.PhysicalPath ) == false ) { Context.RewritePath ( `` ~/images/nophoto.jpg '' ) ; } } < system.webServer > < modules runAllManagedModulesForAllRequests= '' true '' > < /modules > < /system.webServer >",Application_BeginRequest not fired for JPG on production server "C_sharp : I am trying to create a quick class so that I can make writing sorting code for a grid much easier to work with and maintain , and to keep code repetition down . To do this I came up with the following class : The idea is that you create a quick configuration of the different sort options , what OrderBy expression is used for that , and optionally an object that is related to that sort option . This allows my code to look like : and then I can sort by just doingThis works great when the sorted variable is a string , but when it is not a string I get the following exception : Can not order by type 'System.Object'.I 'm assuming this is because I am storing the expression as Expression < Func < TSource , object > > and not being more specific about that 2nd generic . I do n't understand how I can keep all my different sort options ( even for non-string properties ) in one class . I guess one of the issues is that the Linq.OrderBy ( ) clause takes Expression < Func < TSource , TKey > > as it 's parameter , but I am not wrapping my head around how Linq.OrderBy ( ) is able to infer what TKey should be , and therefore I can not understand how to take advantage of that inference to store these expressions with the proper TKey.Any ideas ? public class SortConfig < TSource , TRelatedObject > where TSource : class where TRelatedObject : class { public IList < SortOption > Options { get ; protected set ; } public SortOption DefaultOption { get ; set ; } public SortConfig ( ) { Options = new List < SortOption > ( ) ; } public void Add ( string name , Expression < Func < TSource , object > > sortExpression , TRelatedObject relatedObject , bool isDefault = false ) { var option = new SortOption { FriendlyName = name , SortExpression = sortExpression , RelatedObject = relatedObject } ; Options.Add ( option ) ; if ( isDefault ) DefaultOption = option ; } public SortOption GetSortOption ( string sortName ) { if ( sortName.EndsWith ( `` asc '' , StringComparison.OrdinalIgnoreCase ) ) sortName = sortName.Substring ( 0 , sortName.LastIndexOf ( `` asc '' , StringComparison.OrdinalIgnoreCase ) ) ; else if ( sortName.EndsWith ( `` desc '' , StringComparison.OrdinalIgnoreCase ) ) sortName = sortName.Substring ( 0 , sortName.LastIndexOf ( `` desc '' , StringComparison.OrdinalIgnoreCase ) ) ; sortName = sortName.Trim ( ) ; var option = Options.Where ( x = > x.FriendlyName.Trim ( ) .Equals ( sortName , StringComparison.OrdinalIgnoreCase ) ) .FirstOrDefault ( ) ; if ( option == null ) { if ( DefaultOption == null ) throw new InvalidOperationException ( string.Format ( `` No configuration found for sort type of ' { 0 } ' , and no default sort configuration exists '' , sortName ) ) ; option = DefaultOption ; } return option ; } public class SortOption { public string FriendlyName { get ; set ; } public Expression < Func < TSource , object > > SortExpression { get ; set ; } public TRelatedObject RelatedObject { get ; set ; } } } protected void InitSortConfig ( ) { _sortConfig = new SortConfig < xosPodOptimizedSearch , HtmlAnchor > ( ) ; _sortConfig.Add ( `` name '' , ( x = > x.LastName ) , lnkSortName , true ) ; _sortConfig.Add ( `` team '' , ( x = > x.SchoolName ) , lnkSortTeam ) ; _sortConfig.Add ( `` rate '' , ( x = > x.XosRating ) , lnkSortRate ) ; _sortConfig.Add ( `` pos '' , ( x = > x.ProjectedPositions ) , null ) ; _sortConfig.Add ( `` height '' , ( x = > x.Height ) , lnkSortHeight ) ; _sortConfig.Add ( `` weight '' , ( x = > x.Weight ) , lnkSortWeight ) ; _sortConfig.Add ( `` city '' , ( x = > x.SchoolCity ) , lnkSortCity ) ; _sortConfig.Add ( `` state '' , ( x = > x.SchoolState ) , lnkSortState ) ; } // Get desired sorting configuration InitSortConfig ( ) ; var sortOption = _sortConfig.GetSortOption ( sort ) ; bool isDescendingSort = sort.EndsWith ( `` desc '' , StringComparison.OrdinalIgnoreCase ) ; // Setup columns InitSortLinks ( ) ; if ( sortOption.RelatedObject ! = null ) { // Make modifications to html anchor } // Form query var query = PodDataContext.xosPodOptimizedSearches.AsQueryable ( ) ; if ( isDescendingSort ) query = query.OrderByDescending ( sortOption.SortExpression ) ; else query = query.OrderBy ( sortOption.SortExpression ) ;",How can I dynamically store expressions used for Linq Orderby ? C_sharp : I have a generic class that takes a type T. Within this class I have a method were I need to compare a type T to another type T such as : The comparison operation inside of MyMethod fails with Compiler Error CS0019 . Is it possible to add a constraint to T to make this work ? I tried adding a where T : IComparable < T > to the class definition to no avail . public class MyClass < T > { public T MaxValue { // Implimentation for MaxValue } public T MyMethod ( T argument ) { if ( argument > this.MaxValue ) { // Then do something } } },Binary comparison operators on generic types "C_sharp : AFAIK void means nothing in terms of programming language . So why in .Net framework it is declared as struct ? using System.Runtime.InteropServices ; namespace System { /// < summary > /// Specifies a return value type for a method that does not return a value . /// < /summary > /// < filterpriority > 2 < /filterpriority > [ ComVisible ( true ) ] [ Serializable ] [ StructLayout ( LayoutKind.Sequential , Size = 1 ) ] public struct Void { } }",Why is return type void declared as struct in .NET ? "C_sharp : In my quest to understand C # properly , I find myself asking what are the practical differences between specifying an interface constraint on a generic method argument , and simply specifying the interface as the type of the argument ? EDITI know my example is very narrow as it 's just an example . I 'm quite interested in differences that go outside its scope . public interface IFoo { void Bar ( ) ; } public static class Class1 { public static void Test1 < T > ( T arg1 ) where T : IFoo { arg1.Bar ( ) ; } public static void Test2 ( IFoo arg1 ) { arg1.Bar ( ) ; } }",Interface constraint on generic method arguments "C_sharp : I have come across a few ways to write a business logic in asp.net but I am wondering for 2 example below , what are the benefits of using a struct to store class variables : namespace Shopping { public struct ShoppingCart { public string Color ; public int ProductId ; } public partial class MyShoppingCart { public decimal GetTotal ( string cartID ) { } // Some other methods ... } } namespace Shopping { public partial class MyShoppingCart { public string Color { get ; set ; } public int ProductId { get ; set ; } public decimal GetTotal ( string cartID ) { } // Some other methods ... } }",Business logic class "C_sharp : I have a simple page displaying thumbnail list , I want to to add a pager , i have added two action linkswhen i click on the link i 'm redirected to instead of does anyone know why the ' # ' character is added to the URL ? Route copnfig : < li class= '' ui-pagination-next '' > @ Html.ActionLink ( `` Next '' , `` Paginate '' , `` Home '' , new { nbSkip = ViewBag.nextSkip } , null ) < /li > http : //localhost:41626/ # /Home/Paginate ? nbSkip=60 http : //localhost:41626/Home/Paginate ? nbSkip=60 , public class RouteConfig { public static void RegisterRoutes ( RouteCollection routes ) { routes.IgnoreRoute ( `` { resource } .axd/ { *pathInfo } '' ) ; routes.MapRoute ( name : `` Default '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; } }",why a # character is added to the url ? "C_sharp : Assuming my Awesome class has a property Bazinga , which is a String with the default value of `` Default value '' , I could go : As you may already be aware , enumerating the enumerableOfAwesome again will not make you happy , if you expect to find your `` New value '' strings safely tucked away in all the Bazinga . Instead , outputting them to the console would render : Default value Default value Default value Default value Default value ( .NET Fiddle here ) This is all well and dandy from some deferred execution point-of-view , and that issue has been discussed already before , like here and here . My question however is why the enumerator implementations do not return immutable objects ; If persistence over several enumerations is not guaranteed , then what use is there of the ability to set values , save making people confused ? Maybe this is n't a very good question , but I 'm sure your answers will be enlightening . var enumerableOfAwesome = Enumerable .Range ( 1 , 5 ) .Select ( n = > new Awesome ( ) ) ; foreach ( var a in enumerableOfAwesome ) a.Bazinga = `` New value '' ;",Why are IEnumerable Projections not Immutable ? "C_sharp : Background : I have an attribute that indicates that a property of field in an object IsMagic . I also have a Magician class that runs over any object and MakesMagic by extracting each field and property that IsMagic and wraps it in a Magic wrapper.The Magician can MakeMagic on anObject with at least one field or property that IsMagic to produce a generic List of Magic , like so : Notice that Magic wrappers can only go around properties or fields of certain types . This means that only property or field that contains data of specific types should be marked as IsMagic . To make matters more complicated , I expect the list of specific types to change as business needs evolve ( since programming Magic is in such high demand ) .The good news is that the Magic has some build time safety . If I try to add code like new Magic ( true ) Visual Studio will tell me it 's wrong , since there is no constructor for Magic that takes a bool . There is also some run-time checking , since the Magic.CanMakeMagicFromType method can be used to catch problems with dynamic variables.Problem Description : The bad news is that there 's no build-time checking on the IsMagic attribute . I can happily say a Dictionary < string , bool > field in some class IsMagic , and I wo n't be told that it 's a problem until run-time . Even worse , the users of my magical code will be creating their own mundane classes and decorating their properties and fields with the IsMagic attribute . I 'd like to help them see problems before they become problems.Proposed Solution : Ideally , I could put some kind of AttributeUsage flag on my IsMagic attribute to tell Visual Studio to use the Magic.CanMakeMagicFromType ( ) method to check the property or field type that the IsMagic attribute is being attached to . Unfortunately , there does n't seem to be such an attribute.However , it seems like it should be possible to use Roslyn to present an error when IsMagic is placed on a field or property that has a Type that ca n't be wrapped in Magic.Where I need help : I am having trouble designing the Roslyn analyser . The heart of the problem is that Magic.CanMakeMagicFromType takes in System.Type , but Roslyn uses ITypeSymbol to represent object types.The ideal analyzer would : Not require me to keep a list of allowed types that can be wrapped in Magic . After all , Magic has a list of constructors that serve this purpose.Allow natural casting of types . For instance , if Magic has a constructor that takes in IEnumerable < bool > , then Roslyn should allow IsMagic to be attached to a property with type List < bool > or bool [ ] . This casting of Magic is critical to the Magician 's functionality.I 'd appreciate any direction on how to code a Roslyn analyzer that is `` aware '' of the constructors in Magic . using System ; using System.Collections.Generic ; using System.Linq ; using System.Reflection ; namespace MagicTest { /// < summary > /// An attribute that allows us to decorate a class with information that identifies which member is magic . /// < /summary > [ AttributeUsage ( AttributeTargets.Property|AttributeTargets.Field , AllowMultiple = false ) ] class IsMagic : Attribute { } public class Magic { // Internal data storage readonly public dynamic value ; # region My ever-growing list of constructors public Magic ( int input ) { value = input ; } public Magic ( string input ) { value = input ; } public Magic ( IEnumerable < bool > input ) { value = input ; } // ... # endregion public bool CanMakeMagicFromType ( Type targetType ) { if ( targetType == null ) return false ; ConstructorInfo publicConstructor = typeof ( Magic ) .GetConstructor ( new [ ] { targetType } ) ; if ( publicConstructor ! = null ) return true ; // We can make Magic from this input type ! ! ! return false ; } public override string ToString ( ) { return value.ToString ( ) ; } } public static class Magician { /// < summary > /// A method that returns the members of anObject that have been marked with an IsMagic attribute . /// Each member will be wrapped in Magic . /// < /summary > /// < param name= '' anObject '' > < /param > /// < returns > < /returns > public static List < Magic > MakeMagic ( object anObject ) { Type type = anObject ? .GetType ( ) ? ? null ; if ( type == null ) return null ; // Sanity check List < Magic > returnList = new List < Magic > ( ) ; // Any field or property of the class that IsMagic gets added to the returnList in a Magic wrapper MemberInfo [ ] objectMembers = type.GetMembers ( ) ; foreach ( MemberInfo mi in objectMembers ) { bool isMagic = ( mi.GetCustomAttributes < IsMagic > ( ) .Count ( ) > 0 ) ; if ( isMagic ) { dynamic memberValue = null ; if ( mi.MemberType == MemberTypes.Property ) memberValue = ( ( PropertyInfo ) mi ) .GetValue ( anObject ) ; else if ( mi.MemberType == MemberTypes.Field ) memberValue = ( ( FieldInfo ) mi ) .GetValue ( anObject ) ; if ( memberValue == null ) continue ; returnList.Add ( new Magic ( memberValue ) ) ; // This could fail at run-time ! ! ! } } return returnList ; } } } using System ; using System.Collections.Generic ; namespace MagicTest { class Program { class Mundane { [ IsMagic ] public string foo ; [ IsMagic ] public int feep ; public float zorp ; // If this [ IsMagic ] , we 'll have a run-time error } static void Main ( string [ ] args ) { Mundane anObject = new Mundane { foo = `` this is foo '' , feep = -10 , zorp = 1.3f } ; Console.WriteLine ( `` Magic : '' ) ; List < Magic > myMagics = Magician.MakeMagic ( anObject ) ; foreach ( Magic aMagic in myMagics ) Console.WriteLine ( `` { 0 } '' , aMagic.ToString ( ) ) ; Console.WriteLine ( `` More Magic : { 0 } '' , new Magic ( `` this works ! `` ) ) ; //Console.WriteLine ( `` More Magic : { 0 } '' , new Magic ( Mundane ) ) ; // build-time error ! Console.WriteLine ( `` \nPress Enter to continue '' ) ; Console.ReadLine ( ) ; } } }",Create Roslyn C # analyzer that is aware of constructor argument types for class in assembly "C_sharp : in protobuf-net is it possible to partially deserialize a message based on a base type ? In my system I have an inheritance hierarchy where every message inherits from a MessageBase . The MessageBase has a uint MessageType . Ideally I only want to deserialize the MessageBase and check if it ’ s a MessageType I ’ m interested in then I can either throw away the message or make the decision to deserialize the actual message . This is to save the cost of deserialize ( I have a cpu cycle budget and lots of messages to process ) .Example usage shown below.Thanks a lot . MessageBase msgBase = ..deserialize ; if ( msgBase.MessageType = 1 ) //1 is the Tick msg type { Tick tick = ..deserialize actual msg ; //do something with tick } //throw away msgBase [ ProtoContract , ProtoInclude ( 1 , typeof ( Tick ) ) ] public class MessageBase { protected uint _messageType ; [ ProtoMember ( 1 ) ] public uint MessageType { get { return _messageType ; } set { _messageType = value ; } } } [ ProtoContract ] public public class Tick : MessageBase { private int _tickId ; private double _value ; public Tick ( ) { _messageType = 1 ; } [ ProtoMember ( 1 ) ] public int TickID { get { return _tickId ; } set { _tickId = value ; } } [ ProtoMember ( 2 ) ] public double Value { get { return _value ; } set { _value = value ; } } }",In protobuf-net is it possible to partially deserialize a message based on a base type "C_sharp : I can query for the SalesReceipt object : The SalesReceipt has a list of SalesReceipt Lines in ORSalesReceiptLineRetList , but none of those lines are the payment line . There is no way to get the TxnLineID from the SalesReceipt object for the payment line ( that I can find ) .What I 'm trying to do is find a particular TxnLineID from the SalesReceipt , so that I can mark it as cleared . When I do a search , I can see there is a transaction line ( the one below in the Credit Card Batches : Visa/MC account ) . How can I find the TxnLineID For that particular line ? Here is a screenshot showing the transaction marked as cleared which I accomplished through the UI by clicking the box in the Cleared column . public bool GetSalesReceipt ( string sRefNum , string sAccount , out ISalesReceiptRet ret ) { ret = null ; IMsgSetRequest msr = sm.CreateMsgSetRequest ( `` US '' , 4 , 0 ) ; msr.Attributes.OnError = ENRqOnError.roeStop ; ISalesReceiptQuery q = msr.AppendSalesReceiptQueryRq ( ) ; q.metaData.SetValue ( ENmetaData.mdMetaDataAndResponseData ) ; q.ORTxnQuery.TxnFilter.ORRefNumberFilter.RefNumberFilter.RefNumber.SetValue ( sRefNum ) ; q.ORTxnQuery.TxnFilter.ORRefNumberFilter.RefNumberFilter.MatchCriterion.SetValue ( ENMatchCriterion.mcContains ) ; q.ORTxnQuery.TxnFilter.AccountFilter.ORAccountFilter.FullNameList.Add ( sAccount ) ; q.IncludeLineItems.SetValue ( true ) ; IMsgSetResponse resp = sm.DoRequests ( msr ) ; if ( resp.ResponseList.Count == 0 ) return false ; IResponseList rl = resp.ResponseList ; if ( rl.Count == 1 ) { IResponse r = rl.GetAt ( 0 ) ; if ( r.Detail == null ) return false ; if ( r.StatusCode ! = 0 ) return false ; if ( r.Type.GetValue ( ) == ( short ) ENResponseType.rtSalesReceiptQueryRs ) { ISalesReceiptRetList crl = ( ISalesReceiptRetList ) r.Detail ; if ( crl.Count == 1 ) ret = crl.GetAt ( 0 ) ; } } if ( ret == null ) return false ; return true ; }",How do you find the TxnLineID of a payment line from a Quickbooks transaction if it is part of a Sales Receipt ? "C_sharp : The following code compiles successfully : The following code fails to be evaluated if pasted into the watch window or the Immediate Window : The error message is : Why does this happen ? string foo = new string ( new char [ ] { ' b ' , ' a ' , ' r ' } ) ; new string ( new char [ ] { ' b ' , ' a ' , ' r ' } ) ; 'new string ( new char [ ] { ' b ' , ' a ' , ' r ' } ) ' threw an exception of type 'System.ArgumentException ' base { System.SystemException } : { `` Only NewString function evaluation can create a new string . '' } Message : `` Only NewString function evaluation can create a new string . '' ParamName : null",Why ca n't I use new string in the debugger ? "C_sharp : I am creating an application that needs to track when a process starts , then raise an event when it 's finished.I have code that works perfectly , and does exactly what I need on an English machine , but when I run the same application on a French language machine it fails.here 's the code that failsthe error hits when it tries to start the query : wstart.Start ( ) ; and does the same for wstop.Start ( ) ; I can only guess it has something to do with the language and the query string , but I 'm clutching at straws.The error it comes up with is : '' demande non analysable '' Any help is gratefully recieved ! MartynEdit : Tested on 2 identical Machines , only difference being the language chosen on first startup . qstart = new WqlEventQuery ( `` __InstanceCreationEvent '' , new TimeSpan ( 0 , 0 , 0 , 0 , 5 ) , `` TargetInstance isa \ '' Win32_Process\ '' '' ) ; qstop = new WqlEventQuery ( `` __InstanceDeletionEvent '' , new TimeSpan ( 0 , 0 , 0 , 0 , 5 ) , `` TargetInstance isa \ '' Win32_Process\ '' '' ) ; try { using ( wstart = new ManagementEventWatcher ( qstart ) ) { wstart.EventArrived += new EventArrivedEventHandler ( ProcessStarted ) ; Log.DebugEntry ( `` BeginProcess ( ) - Starting wstart Event '' ) ; wstart.Start ( ) ; } } catch ( Exception ex ) { Log.DebugEntry ( `` error on wstart : `` + ex.Message ) ; } using ( wstop = new ManagementEventWatcher ( qstop ) ) { wstop.EventArrived += new EventArrivedEventHandler ( ProcessStopped ) ; Log.DebugEntry ( `` BeginProcess ( ) - Starting wstop Event '' ) ; wstop.Start ( ) ; }",WMI query in C # does not work on NON-English Machine "C_sharp : In ViewComponent object , HttpContext and User are read-only properties.How to unit test such a component ? I 'm using the MSTest Freamwork.The follow properties are used in my code CookieSessionUser ( System.Security.Principal ) public ViewViewComponentResult Invoke ( ) { var vm = new SummaryViewModel ( ) ; if ( User.Identity is ClaimsIdentity identity & & identity.IsAuthenticated ) { vm.IsAuthenticated = true ; vm.UserName = identity.Claims.FirstOrDefault ( c = > c.Type == `` UserName '' ) .Value ; vm.PhotoUrl = identity.Claims.FirstOrDefault ( c = > c.Type == `` FacePicture '' ) .Value ; } return View ( vm ) ; } [ TestMethod ] public void UserSummaryVcTest ( ) { var component = new UserSummaryViewComponent ( ) ; var model = component.Invoke ( ) .ViewData.Model as SummaryViewModel ; Assert.AreEqual ( `` UserName '' , model.UserName ) ; }",How to unit test ViewComponent.Invoke ( ) ? "C_sharp : I 'm building an application that will take an image of a single person 's whole body and will produce a `` mugshot '' for that person.Mugshot meaning an image of the person 's whole face , neck , hair and ears at the same general size of another mugshot.Currently I 'm usinghttp : //askernest.com/archive/2008/05/03/face-detection-in-c.aspxto implement OpenCV and I 'm usingas my cascades.I use all of the cascades because a single one will not detect all my faces . After I get all of the faces detected by all of the cascades I find my average square and use that for my final guess of how tall and wide the mugshot should be.My problem is 3 parts.My current process is rather slow . How can I speed up the detection process ? Edit : I 'm finding that the processing time is directly related to photo size . Reducing the size of the photos may prove to be helpful.A single cascade will not detect all the faces I come across so I 'm using all of them . This of course produces many varied squares and a few false positives . What method can I use to identify false positives and leave them out of the average square calculation ? ex . Edit : I 'm implementing an average of values within standard deviation . Will post code soon.I 'm not exactly sure of the best way find the mugshot given the square coordinates of the face . Where can I find face to mugshot ratios ? Edit : Solved this one . Assuming all my heads are ratios of their faces.I just need to get rid of those false positives.Ok make that 4 issues.Our camera that we will be using is currently out of commission so I do n't have a method of capturing images at the moment . Where can I find full body images of people that is n't pure pron like google 's image search for full body images ? Edit : `` Person standing '' Makes a good search : ) harrcascade_frontalface_default.xml harrcascade_frontalface_alt.xml harrcascade_frontalface_alt2.xml harrcascade_frontalface_alt_tree.xml static public Rectangle GetMugshotRectangle ( Rectangle rFace ) { int y2 , x2 , w2 , h2 ; //adjust as neccessary double heightRatio = 2 ; y2 = Convert.ToInt32 ( rFace.Y - rFace.Height * ( heightRatio - 1.0 ) / 2.0 ) ; h2 = Convert.ToInt32 ( rFace.Height * heightRatio ) ; //height to width ratio is 1.25 : 1 in mugshots w2 = Convert.ToInt32 ( h2 * 4 / 5 ) ; x2 = Convert.ToInt32 ( ( rFace.X + rFace.Width / 2 ) - w2 / 2 ) ; return new Rectangle ( x2 , y2 , w2 , h2 ) ; }",How to obtain a `` mugshot '' from face detection squares ? "C_sharp : I want to display a ToolTip message below a TextBox , but also want them to be right aligned . I was able to position the ToolTip message at the right edge of the textbox , so I tried to move the message left by message length.So I tried to get the string length by using TextRenderer.MeasureText ( ) , but the position is a little bit off as shown below.I tried with different flags in the MeasureText ( ) function but it did n't help , and since ToolTip message has a padding , I went for TextFormatFlags.LeftAndRightPadding.To be clear , this is what I would like to achieve : private void button1_Click ( object sender , EventArgs e ) { ToolTip myToolTip = new ToolTip ( ) ; string test = `` This is a test string . `` ; int textWidth = TextRenderer.MeasureText ( test , SystemFonts.DefaultFont , textBox1.Size , TextFormatFlags.LeftAndRightPadding ) .Width ; int toolTipTextPosition_X = textBox1.Size.Width - textWidth ; myToolTip.Show ( test , textBox1 , toolTipTextPosition_X , textBox1.Size.Height ) ; }",How to align right edges of a control and ToolTip Message in C # "C_sharp : We have a lot of nested async methods and see behavior that we do not really understand . Take for example this simple C # console applicationWhen we run this sample with the following arguments : We get a StackOverflowException and this is the last message we see in the console : When we change the arguments intoWe end with this messageSo the StackOverflowException occurs on the unwinding of the stack ( not really sure if we should call it that , but the StackOverflowException occurs after the recursive call in our sample , in synchronous code , a StackOverflowException will always occur on the nested method call ) . In the case that we throw an exception , the StackOverflowException occurs even earlier.We know we can solve this by calling Task.Yield ( ) in the finally block , but we have a few questions : Why does the Stack grow on the unwinding path ( in comparison to amethod that does n't cause a thread switch on the await ) ? Why does the StackOverflowException occurs earlier in the Exception case than when we do n't throw an exception ? using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; using System.Text ; using System.Threading ; using System.Threading.Tasks ; namespace AsyncStackSample { class Program { static void Main ( string [ ] args ) { try { var x = Test ( index : 0 , max : int.Parse ( args [ 0 ] ) , throwException : bool.Parse ( args [ 1 ] ) ) .GetAwaiter ( ) .GetResult ( ) ; Console.WriteLine ( x ) ; } catch ( Exception ex ) { Console.WriteLine ( ex ) ; } Console.ReadKey ( ) ; } static async Task < string > Test ( int index , int max , bool throwException ) { await Task.Yield ( ) ; if ( index < max ) { var nextIndex = index + 1 ; try { Console.WriteLine ( $ '' b { nextIndex } of { max } ( on threadId : { Thread.CurrentThread.ManagedThreadId } ) '' ) ; return await Test ( nextIndex , max , throwException ) .ConfigureAwait ( false ) ; } finally { Console.WriteLine ( $ '' e { nextIndex } of { max } ( on threadId : { Thread.CurrentThread.ManagedThreadId } ) '' ) ; } } if ( throwException ) { throw new Exception ( `` '' ) ; } return `` hello '' ; } } } AsyncStackSample.exe 2000 false e 331 of 2000 ( on threadId : 4 ) AsyncStackSample.exe 2000 true e 831 of 2000 ( on threadId : 4 )",StackOverflowExceptions in nested async methods on unwinding of the stack "C_sharp : I am using Newtonsoft JSON.NET to serialize/deserialize stuff for me . But I have this list wherein they are of Object type : When I serialize that with TypeNameHandling set to TypeNameHandling.All , I was expecting that it will also give a $ type for each instance on the list but does n't seem to be the case . Here is the actual output : I need this to have specific Type Name Handling for those primitive types because if I add an Int32 value in to the list and when it comes back after deserializing it JSON.NET sets it as Int64 . That is a big deal for me because I am trying to invoke some methods and to do that I need to compare the parameters and they MUST have the same types . Is there a way or a setting you can set in JSON.NET to achieve what I need ? I 've seen this post but what it does is that he is trying to change the default behavior and always return Int32 which is not what I 'm looking for . Any help would be appreciated . Thanks var list = new List < Object > ( ) { `` hi there '' , 1 , 2.33 } ; { `` $ type '' : `` System.Collections.Generic.List ` 1 [ [ System.Object , mscorlib ] ] , mscorlib '' , `` $ values '' : [ `` hi there '' , 1 , 2.33 ] }",JSON.NET - How do I include Type Name Handling for primitive C # types that are stored in an array/list as Object type "C_sharp : In Stephan Cleary 's recent blog post about Async Console Apps on .NET CoreCLR he shows us that in CoreCLR ( currently running on Visual Studio 2015 , CTP6 ) , the entry point `` Main '' can actually be marked as async Task , compile properly and actually run : Gives the following output : This is strengthend by a blog post from the ASP.NET team called A Deep Dive into the ASP.NET 5 Runtime : In addition to a static Program.Main entry point , the KRE supports instance-based entry points . You can even make the main entry point asynchronous and return a Task . By having the main entry point be an instance method , you can have services injected into your application by the runtime environment.We know that up until now , An entry point can not be marked with the 'async ' modifier . So , how is that actually possible in the new CoreCLR runtime ? public class Program { public async Task Main ( string [ ] args ) { Console.WriteLine ( `` Hello World '' ) ; await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) ; Console.WriteLine ( `` Still here ! `` ) ; Console.ReadLine ( ) ; } }",Entry point can be marked with the 'async ' modifier on CoreCLR ? "C_sharp : I am trying to solve a problem where the session id seems to clearing mysteriously during postback . I am sure that the value is being set and there is no other place in my code where i am clearing that session . Also , I am storing the value of the session id in my page 's viewstate . During the postback the viewstate is empty which essentially means that when the value was assigned to viewstate the session variable was null . Is it possible that during code execution , session object is cleared because of timeout ? So lets say if i have following code.is it be theoretically possible that even though session [ `` id '' ] is not null in line1 it is null on line5 because of time out . if ( session [ `` id '' ] == null ) : line1 { : line2 session [ `` id '' ] = // Generate some unique id : line3 } : line4viewstate [ `` id '' ] = session [ `` id '' ] ; : line5",Can a session expire during the page processing in C # "C_sharp : I 'm working on a huge system based on Asp.net MVC 3.0 and working on Mono-2.10.8 ( Windows 7 ) .Everything was fine until a moment couple of days ago.Inside my API I have several utility classes using dictionaries . For example , like this one : And randomly I get exceptions like this : Most of the time everything is fine and KeyUtility works correct , but on rare occasions I get such an exception.Despite it looks like thread safety issue , the dictionary ReverseAlphabet is always accessed for reading only and never for writing . Once it 's created in static constructor it 's only accessed with TryGetValue . As I understand from MSDN article it should be thread safe in this case.Moreover , I have n't seen this problem before.What should I look at ? I even ca n't create a reproduction as I have completely no idea what is wrong.Mono-2.10.8 and older versions proved to be stable with dictionaries . I 've been using it for a couple of years intensively and have never seen this sort of exception before.How to fix this ? UPD : I 've remembered that near the time of the begining of troubles what i 've done is statically linked mono with my executable ( i 'm embedding mono into my application ) . I simply downloaded sources of mono . Compilled it without any changes except i set up libmono 's output to static library . I 've also linked with libeay32 and sqlite3 . All multithread ( MT ) . Maybe this change could affect an application ? Unfortunately i ca n't check this under standalone mono . Before this i was linking all libraries dynamically and everything was fine.UPD2 : Here is the link to the complete sources : http : //pastebin.com/RU4RNCki public static class KeyUtility { static KeyUtility ( ) { Alphabet = new [ ] { ' A ' , ' B ' , ' C ' , 'D ' , ' E ' , ' F ' , ' G ' , ' H ' , ' J ' , ' K ' , ' L ' , 'M ' , ' N ' , ' P ' , ' R ' , 'S ' , 'T ' , ' U ' , ' V ' , ' X ' , ' Y ' , ' Z ' , ' 0 ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' } ; ReverseAlphabet = Alphabet .Select ( ( c , i ) = > new { Char = c , Value = i } ) .ToDictionary ( k = > k.Char , v = > ( byte ) v.Value ) ; } internal static char [ ] Alphabet ; private static IDictionary < char , byte > ReverseAlphabet ; public static string ToKey ( byte [ ] key , int groupSize ) { //Accessing Alphabet to generate string key from bytes } public static byte [ ] FromKey ( string key ) { //Accessing ReverseAlphabet to get bytes from string key } } System.IndexOutOfRangeException : Array index is out of range.at System.Collections.Generic.Dictionary ` 2 < char , byte > .TryGetValue ( char , byte & ) < 0x000a1 > at MyAPI.KeyUtility.FromKey ( string ) < 0x0009a > at MyApp.Controllers.AboutController.Index ( ) < 0x002df > at ( wrapper dynamic-method ) object.lambda_method ( System.Runtime.CompilerServices.Closure , System.Web.Mvc.ControllerBase , object [ ] ) < 0x0002f > at System.Web.Mvc.ActionMethodDispatcher.Execute ( System.Web.Mvc.ControllerBase , object [ ] ) < 0x0001b > at System.Web.Mvc.ReflectedActionDescriptor.Execute ( System.Web.Mvc.ControllerContext , System.Collections.Generic.IDictionary ` 2 < string , object > ) < 0x000ff > at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod ( System.Web.Mvc.ControllerContext , System.Web.Mvc.ActionDescriptor , System.Collections.Generic.IDictionary ` 2 < string , object > ) < 0x00019 > at System.Web.Mvc.ControllerActionInvoker/ < > c__DisplayClass15. < InvokeActionMethodWithFilters > b__12 ( ) < 0x00066 > at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter ( System.Web.Mvc.IActionFilter , System.Web.Mvc.ActionExecutingContext , System.Func ` 1 < System.Web.Mvc.ActionExecutedContext > ) < 0x000b8 >","Mysterious behavior of Dictionary < TKey , TSource >" "C_sharp : Hello I am working on a WPF platform targeting .NET framework 4.5.2 . I am writing a downloader for my application . Here is the code : Now I want at button click the download must be paused and at another button click the download must be resumed . I tried working with .set ( ) property of an AutoReset event and .Reset ( ) property of the same but it did n't work . I need help . My button click code are : I have also tried this link How to pause/suspend a thread then continue it ? . nothing happensI 've also gone through Adding pause and continue ability in my downloader but I failed to incorporate the solution in my above code as I am also updating the download progress on the UI . private void Download ( Dictionary < int , FileAndLinkClass > MyLinks ) { ApplicationDownloadThread = new Thread ( ( ) = > { foreach ( KeyValuePair < int , FileAndLinkClass > item in MyLinks ) { fileNo++ ; WebClient myWebClient = new WebClient ( ) ; myWebClient.DownloadProgressChanged += MyWebClient_DownloadProgressChanged ; myWebClient.DownloadFileCompleted += MyWebClient_DownloadFileCompleted ; // Download the Web resource and save it into the current filesystem folder . string downloadedFileAdress = System.IO.Path.Combine ( fileLocation , $ '' { item.Value.FileName } '' ) ; myWebClient.DownloadFileAsync ( new Uri ( item.Value.Link ) , downloadedFileAdress ) ; while ( myWebClient.IsBusy ) { } } } ) ; ApplicationDownloadThread.IsBackground = false ; ApplicationDownloadThread.Start ( ) ; //UnZipAndCreateUpdatePackage ( MyLinks ) ; } private AutoResetEvent waitHandle = new AutoResetEvent ( true ) ; private void StartDownloadBtn_Click ( object sender , RoutedEventArgs e ) { waitHandle.Set ( ) ; } private void StopDownloadBtn_Click ( object sender , RoutedEventArgs e ) { waitHandle.Reset ( ) ; }",Pause and resume a download WPF "C_sharp : OK , I do n't think the title says it right ... but here goes : I have a class with about 40 Enums in it . i.e : Now say I have a Dictionary of strings and values , and each string is the name of above mentioned enums : I need to change `` aaa '' into HooBoo.aaa to look up 0 . Ca n't seem to find a way to do this since the enum is static . Otherwise I 'll have to write a method for each enum to tie the string to it . I can do that but thats mucho code to write.Thanks , Cooter Class Hoohoo { public enum aaa : short { a = 0 , b = 3 } public enum bbb : short { a = 0 , b = 3 } public enum ccc : short { a = 0 , b = 3 } } Dictionary < string , short > { `` aaa '' :0 , '' bbb '' :3 , '' ccc '' :0 }",Possible to load an Enum based on a string name ? "C_sharp : I 'm trying to experiment with using Exchange EWS 2 on debian via Mono ( Version 2.10.8.1 & 3.0.6 ) I 'm developing on windows 8 using vs2012 . The program works just fine on windows and i get the expected output.On mono however I keep getting the following output and exception.Apparently it is attempting to look up a host which it ca n't find.Both my windows and linux systems are using the same dns server so it is n't that causing the problem.I read through the trace on windows when it works - and the trace shows that the lookups fail a few times and the autodiscover method tries a few different urls until it hits on one that works - on mono however it seems to fall over after the first failure and that 's the end of it.I 've tried googling for using ews on mono but i have n't found anyone who is doing it so i 'm not really sure what else to try.The code used is below - pretty much all of it is taken from code examples onhttp : //msdn.microsoft.com/en-us/library/exchange/dd633709 ( v=exchg.80 ) .aspxThe answer from BeepBeep helped me to solve this.After using BeepBeep 's suggestion i then had a problem that Mono appeared not to have dnsapi.dll ( according to the exceptions ) . I resolved this by skipping autodiscover for now.In order to do that , i replacedwithThen I had an error with the certificate ( the exception said something like 'error with request or decryption ' ) - suffice to say , you need to know that mono does n't include any root ca certificates by default , more info here : Mono FAQ about SecurityI chose the lazier way to get the certs i wanted , using mozroots tool . This however did not work as expected and the error persisted.I then used the tlstest also from the above FAQ to determine the problem - it was related to the certificate chain i was using ( the root was accepted , but the intermediate was not being accepted ) . I then used the third tool documented in the FAQ ( certmgr ) to install the certificates.Following that , it all works . < Trace Tag= '' AutodiscoverConfiguration '' Tid= '' 1 '' Time= '' 2013-03-07 19:09:05Z '' > Starting SCP lookup for domainName='example.com ' , root path= '' < /Trace > Connect ErrorUnhandled Exception : LdapException : ( 91 ) Connect ErrorSystem.Net.Sockets.SocketException : No such host is known at System.Net.Dns.hostent_to_IPHostEntry ( System.String h_name , System.String [ ] h_aliases , System.String [ ] h_addrlist ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Dns.GetHostByName ( System.String hostName ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Dns.GetHostEntry ( System.String hostNameOrAddress ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Dns.GetHostAddresses ( System.String hostNameOrAddress ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Sockets.TcpClient.Connect ( System.String hostname , Int32 port ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Sockets.TcpClient..ctor ( System.String hostname , Int32 port ) [ 0x00000 ] in < filename unknown > :0 at Novell.Directory.Ldap.Connection.connect ( System.String host , Int32 port , Int32 semaphoreId ) [ 0x00000 ] in < filename unknown > :0 [ ERROR ] FATAL UNHANDLED EXCEPTION : LdapException : ( 91 ) Connect ErrorSystem.Net.Sockets.SocketException : No such host is known at System.Net.Dns.hostent_to_IPHostEntry ( System.String h_name , System.String [ ] h_aliases , System.String [ ] h_addrlist ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Dns.GetHostByName ( System.String hostName ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Dns.GetHostEntry ( System.String hostNameOrAddress ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Dns.GetHostAddresses ( System.String hostNameOrAddress ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Sockets.TcpClient.Connect ( System.String hostname , Int32 port ) [ 0x00000 ] in < filename unknown > :0 at System.Net.Sockets.TcpClient..ctor ( System.String hostname , Int32 port ) [ 0x00000 ] in < filename unknown > :0 at Novell.Directory.Ldap.Connection.connect ( System.String host , Int32 port , Int32 semaphoreId ) [ 0x00000 ] in < filename unknown > :0 class Program { private static int verbose = 10 ; private static string loginEmail = `` email @ example.com '' ; private static string password = `` # # # # # # # # # # # # # '' ; static void Main ( string [ ] args ) { try { ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack ; ExchangeService service = new ExchangeService ( ExchangeVersion.Exchange2010_SP2 ) ; service.Credentials = new WebCredentials ( loginEmail , password ) ; if ( verbose > = 10 ) { service.TraceEnabled = true ; service.TraceFlags = TraceFlags.All ; } service.AutodiscoverUrl ( loginEmail , RedirectionUrlValidationCallback ) ; Console.WriteLine ( `` AutoDiscover Completed '' ) ; getContacts ( service ) ; Console.ReadLine ( ) ; } catch ( Exception e ) { Console.WriteLine ( e.Message ) ; foreach ( string key in e.Data.Keys ) { Console.WriteLine ( String.Format ( `` { 0 } : { 1 } '' , key , e.Data [ key ] ) ) ; } throw e ; } } private static void getContacts ( ExchangeService service ) { // Get the number of items in the Contacts folder . ContactsFolder contactsfolder = ContactsFolder.Bind ( service , WellKnownFolderName.Contacts ) ; // Set the number of items to the number of items in the Contacts folder or 1000 , whichever is smaller . int numItems = contactsfolder.TotalCount < 1000 ? contactsfolder.TotalCount : 1000 ; // Instantiate the item view with the number of items to retrieve from the Contacts folder . ItemView view = new ItemView ( numItems ) ; // To keep the request smaller , request only the display name property . //view.PropertySet = new PropertySet ( BasePropertySet.IdOnly , ContactSchema.DisplayName ) ; // Retrieve the items in the Contacts folder that have the properties that you selected . FindItemsResults < Item > contactItems = service.FindItems ( WellKnownFolderName.Contacts , view ) ; // Display the list of contacts . foreach ( Item item in contactItems ) { if ( item is Contact ) { Contact contact = item as Contact ; Console.WriteLine ( ) ; Console.WriteLine ( contact.DisplayName ) ; if ( verbose > = 2 ) { Console.WriteLine ( `` `` + contact.Id ) ; } try { Console.WriteLine ( `` `` + contact.EmailAddresses [ EmailAddressKey.EmailAddress1 ] .ToString ( ) ) ; } catch ( Exception e ) { if ( verbose > = 5 ) { Console.WriteLine ( `` `` + `` Email Address 1 Not Available : `` + e.Message ) ; } } } } } # region taken from tutorial private static bool CertificateValidationCallBack ( object sender , System.Security.Cryptography.X509Certificates.X509Certificate certificate , System.Security.Cryptography.X509Certificates.X509Chain chain , System.Net.Security.SslPolicyErrors sslPolicyErrors ) { // If the certificate is a valid , signed certificate , return true . if ( sslPolicyErrors == System.Net.Security.SslPolicyErrors.None ) { return true ; } // If there are errors in the certificate chain , look at each error to determine the cause . if ( ( sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors ) ! = 0 ) { if ( chain ! = null & & chain.ChainStatus ! = null ) { foreach ( System.Security.Cryptography.X509Certificates.X509ChainStatus status in chain.ChainStatus ) { if ( ( certificate.Subject == certificate.Issuer ) & & ( status.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.UntrustedRoot ) ) { // Self-signed certificates with an untrusted root are valid . continue ; } else { if ( status.Status ! = System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.NoError ) { // If there are any other errors in the certificate chain , the certificate is invalid , // so the method returns false . return false ; } } } } // When processing reaches this line , the only errors in the certificate chain are // untrusted root errors for self-signed certificates . These certificates are valid // for default Exchange server installations , so return true . return true ; } else { // In all other cases , return false . return false ; } } private static bool RedirectionUrlValidationCallback ( string redirectionUrl ) { // The default for the validation callback is to reject the URL . bool result = false ; Uri redirectionUri = new Uri ( redirectionUrl ) ; // Validate the contents of the redirection URL . In this simple validation // callback , the redirection URL is considered valid if it is using HTTPS // to encrypt the authentication credentials . if ( redirectionUri.Scheme == `` https '' ) { result = true ; } return result ; } # endregion } service.AutodiscoverUrl ( loginEmail , RedirectionUrlValidationCallback ) ; service.Url = new Uri ( `` https : //blah.com/ews/exchange.asmx '' ) ;",Running Exchange EWS on Mono LdapException "C_sharp : I 'm trying to combine two fields into a unique index with EF6 . But the update-database command wo n't add the 'Owner ' field into the index . I 'm thinking it 's because it 's not a primitive type but a FK , but I 'm unsure how to fix it.Generated indexes : CREATE UNIQUE NONCLUSTERED INDEX [ IX_FundIdentifierAndOwner ] ON [ dbo ] . [ Funds ] ( [ Identifier ] ASC ) ; CREATE UNIQUE NONCLUSTERED INDEX [ IX_FundNameAndOwner ] ON [ dbo ] . [ Funds ] ( [ Name ] ASC ) ; CREATE NONCLUSTERED INDEX [ IX_Owner_Id ] ON [ dbo ] . [ Funds ] ( [ Owner_Id ] ASC ) ; Any help is greatly appreciated ! public class Fund { [ Key ] public int FundId { get ; set ; } [ Required ] [ Index ( `` IX_FundNameAndOwner '' , IsUnique = true , Order = 1 ) ] [ Index ( `` IX_FundIdentifierAndOwner '' , IsUnique = true , Order=1 ) ] public ApplicationUser Owner { get ; set ; } [ Required ] [ Index ( `` IX_FundNameAndOwner '' , IsUnique = true , Order=2 ) ] [ MaxLength ( 25 ) ] public string Name { get ; set ; } [ Required ] [ Index ( `` IX_FundIdentifierAndOwner '' , IsUnique = true , Order=2 ) ] [ MaxLength ( 25 ) ] public string Identifier { get ; set ; } public double Balance { get ; set ; } }",C # EF6 index attribute not working "C_sharp : So I 'm not the most experienced with the C # programming language , however I 've been making a few test applications here and there.I 've noticed that the more threads I create for an application I 'm working on , the more my GUI starts to freeze . I 'm not sure why this occurs , I previously thought that part of the point of multi-threading an application was to avoid the GUI from freezing up.An explanation would be appreciated.Also , here 's the code I use to create the threads : and here 's what the threads run : private void runThreads ( int amount , ThreadStart address ) { for ( int i = 0 ; i < amount ; i++ ) { threadAmount += 1 ; Thread currentThread = new Thread ( address ) ; currentThread.Start ( ) ; } } private void checkProxies ( ) { while ( started ) { try { WebRequest request = WebRequest.Create ( `` http : //google.co.nz/ '' ) ; request.Timeout = ( int ) timeoutCounter.Value * 1000 ; request.Proxy = new WebProxy ( proxies [ proxyIndex ] ) ; Thread.SetData ( Thread.GetNamedDataSlot ( `` currentProxy '' ) , proxies [ proxyIndex ] ) ; if ( proxyIndex ! = proxies.Length ) { proxyIndex += 1 ; } else { started = false ; } request.GetResponse ( ) ; workingProxies += 1 ; } catch ( WebException ) { deadProxies += 1 ; } lock ( `` threadAmount '' ) { if ( threadAmount > proxies.Length - proxyIndex ) { threadAmount -= 1 ; break ; } } } }",Threads cause GUI to freeze up "C_sharp : According to microsoft documentation the [ BigInt ] datatype seems to have no defined maximum value and theoretically can hold an infinitely large number , but I found that after the 28th digit , some weird things start to occur : As you can see , on the first command1 , the BigInt works as intended , but with one more digit , some falloff seems to occur where it translates 99999999999999999999999999999 to 99999999999999991433150857216 however , the prompt throws no error and you can continue to add more digits until the 310th digitwhich will throw the errorWhich I believe is a console issue rather than a BigInt issue because the error does n't mention the [ BigInt ] datatype unlike numbers too big for other datatypes likeAs for C # , System.Numerics.BigInt will start throwing an error at the 20th digit , 99999999999999999999 when hard coded : When trying to build in Visual Studio I get the errorHowever , I can enter a bigger number to ReadLine without causing an errorWhich seems to indeed be infinite . The input ( 24720 characters total ) works fine2So what is causing all of this weird activity with [ BigInt ] ? 1 which is 28 digits according to ( [ Char [ ] ] '' $ ( [ BigInt ] 9999999999999999999999999999 ) '' ) .count2 I am too lazy to count the digits and trying to parse the digits into PowerShell causes an error . According to this it is 24720 characters PS C : \Users\Neko > [ BigInt ] 99999999999999999999999999999999999999999999999999999999PS C : \Users\Neko > [ BigInt ] 9999999999999999999999999999999999999999999991433150857216 PS C : \Users\Neko > [ BigInt ] 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999100000000000000001097906362944045541740492309677311846336810682903157585404911491537163328978494688899061249669721172515611590283743140088328307009198146046031271664502933027185697489699588559043338384466165001178426897626212945177628091195786707458122783970171784415105291802893207873272974885715430223118336PS C : \Users\Neko\ > [ BigInt ] 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 At line:1 char:318+ ... 999999999999999999999999999999999999999999999999999999999999999999999+ ~The numeric constant 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 is not valid . + CategoryInfo : ParserError : ( : ) [ ] , ParentContainsErrorRecordException + FullyQualifiedErrorId : BadNumericConstant PS C : \Users\Neko > [ UInt64 ] 1844674407370955161518446744073709551615PS C : \Users\Neko > [ UInt64 ] 18446744073709551616Cannot convert value `` 18446744073709551616 '' to type `` System.UInt64 '' . Error : `` Value was either too large or too smallfor a UInt64 . `` At line:1 char:1+ [ UInt64 ] 18446744073709551616+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument : ( : ) [ ] , RuntimeException + FullyQualifiedErrorId : InvalidCastIConvertible namespace Test { class Test { static void Main ( ) { System.Numerics.BigInteger TestInput ; System.Numerics.BigInteger Test = 99999999999999999999 ; System.Console.WriteLine ( Test ) ; } } } Integral constant is too large namespace Test { class Test { static void Main ( ) { System.Numerics.BigInteger TestInput ; TestInput = System.Numerics.BigInteger.Parse ( System.Console.ReadLine ( ) ) ; System.Console.WriteLine ( TestInput ) ; } } } 99999999999 ...",BigInt inconsistencies in PowerShell and C # "C_sharp : I have a scenario where I 'd like to add an item to the ValidationContext and check for it in the EF triggered entity validation . I 'm doing this in a wizard so I can only validate certain things on specific steps . ( If there 's a good pattern for that please do share it ) .The problem is that the validation is triggered , twice actually , before the controller action is even hit . I wish I understood why . I 'm not sure how to get the item in ValidationContext before that happens , so I ca n't tell the validation what step I 'm on.Furthermore , if I only do the custom validation when save changes is triggered by checking for the item as I have in my code below , then I get no automatic model validation errors displayed when the page refreshes.In my custom context : Service that sets the entity : In my entityController : public WizardStep Step { get ; set ; } protected override DbEntityValidationResult ValidateEntity ( DbEntityEntry entityEntry , IDictionary < object , object > items ) { items.Add ( `` ValidationStep '' , Step ) ; return base.ValidateEntity ( entityEntry , items ) ; } public void SaveChanges ( WizardStep step ) { _context.Step = step ; _context.SaveChanges ( ) ; } public IEnumerable < ValidationResult > Validate ( ValidationContext validationContext ) { // Step will only be present when called from save changes . Calls from model state validation wo n't have it if ( validationContext.Items.ContainsKey ( `` ValidationStep '' ) ) { var validationStep = ( WizardStep ) validationContext.Items [ `` ValidationStep '' ] ; if ( validationStep == WizardStep.Introduction ) { if ( criteria ) { yield return new ValidationResult ( $ '' Error message `` , new [ ] { `` field '' } ) ; } } } } public ActionResult MyAction ( HomeViewModel vm ) { try { _incidentService.AddOrUpdate ( vm.Enttiy ) ; _incidentService.SaveChanges ( WizardStep.Introduction ) ; } catch ( Exception ex ) { return View ( vm ) ; } return RedirectToAction ( `` Index '' ) ; }",MVC and EF Validation with added ValidationContext item "C_sharp : I want to do something after user finishes downloadingWhat I tried is to add the following events to test controller but they all fires before user finish downloading ( except destructor it never gets called ) public class TestController : Controller { public FilePathResult Index ( ) { return File ( `` path/to/file '' , `` mime '' ) ; } } protected override void EndExecute ( IAsyncResult asyncResult ) { base.EndExecute ( asyncResult ) ; } protected override void EndExecuteCore ( IAsyncResult asyncResult ) { base.EndExecuteCore ( asyncResult ) ; } protected override void OnActionExecuted ( ActionExecutedContext filterContext ) { base.OnActionExecuted ( filterContext ) ; } protected override void OnResultExecuted ( ResultExecutedContext filterContext ) { base.OnResultExecuted ( filterContext ) ; } protected override void Dispose ( bool disposing ) { base.Dispose ( disposing ) ; } ~TestController ( ) { // }",Completed event for FilePathResult "C_sharp : EDIT 04/06/18 = > Updated question with last statusSo I have this working .Net 4.6 Stateful Service that currently run on my Windows Service Fabric cluster deployed on Azure.Starting from 09/2017 , I should be able to move to Linux : https : //blogs.msdn.microsoft.com/azureservicefabric/2017/09/25/service-fabric-6-0-release/So I 'm trying to deploy it on Linux so I can save costs.First things first , I 've migrated all my code from .Net 4.6 to .Net Core 2.0 . Now I can compile my binaries without issues . I 've basically created new .Net Core projects and then moved all my source code from .Net 4.6 projects to the new .Net Core ones.Then I 've updated my Service Fabric application . I removed my previous SF services from my sfproj , then I 've added my new .Net Core ones.Looks like there is a warning ( nothing on the output window though ) , but it 's here anyway if I try to create a new empty Statful service using .Net core 2.0 through the template provided by Service Fabric Tools 2.0 ( beta ) : So I 'm going to live with it.On my dev machine , I 've modified the 2 csproj projects that contain my Stateful services so they can run locally as Windows executables . I 've used the win7-x64 runtimeIdentifier.Running my SF cluster locally on my Windows machine is fine.Then I 've slightly changed the previous csproj files for Linux . I used the ubuntu.16.10-x64 runtimeIdentifier.Also I 've changed the ServiceManifest.xml file to target the linux-compatible binary : entryPoint.sh is a basic script that eventually executes : Then I 've successfully deployed to my secured SF Linux cluster from Visual Studio . Unfortunately I have the following errors for both my stateful services : Error event : SourceId='System.Hosting ' , Property='CodePackageActivation : Code : EntryPoint ' . There was an error during CodePackage activation.The service host terminated with exit code:134Looks like my binary crashes when starting . So here are my questions : Is the approach right to deploy a C # .Net Core SF stateful service on Linux from Visual Studio ? EDIT : looking inside the LinuxsyslogVer2v0 table , I get the following error : starthost.sh [ 100041 ] : Unhandled Exception : System.IO.FileLoadException : Could not load file or assembly 'System.Threading.Thread , Version=4.1.0.0 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a ' . The located assembly 's manifest definition does not match the assembly reference . ( Exception from HRESULT : 0x80131040 ) I found the following bug report : https : //github.com/dotnet/sdk/issues/1502Unfortunately , I still get the error without using MSBuild ( using dotnet deploy ) .EDIT : further clarification : My boss want me to run on Linux because starting from D1v2 machines , it 's half the price compared to Windows machines ( no license etc . ) My .NET Core 2.0 services successfully run on Windows . So the .NET Core port should be fine . < ! -- Code package is your service executable . -- > < CodePackage Name= '' Code '' Version= '' 1.9.6 '' > < EntryPoint > < ExeHost > < Program > entryPoint.sh < /Program > < /ExeHost > < /EntryPoint > < /CodePackage > dotnet $ DIR/MyService.dll",Deploy a C # Stateful Service Fabric application from Visual Studio to Linux "C_sharp : I saw this code on Richter 's book : The following code demonstrates how to have a thread pool thread calla method starting immediately and then every 2 seconds thereafter : However , ( sorry ) , I still do n't understand what lines # 7 , # 8 meansAnd of course - why was it initialized ( line # 9 ) to Timeout.Infinite ( which is obviously : `` do n't start the timer '' ) ( I do understand the general purpose for preventing overlaps , but I believe there is also a GC race condition pov here . ) editthe namespace is System.Threading /*1*/ internal static class TimerDemo/*2*/ { /*3*/ private static Timer s_timer ; /*4*/ public static void Main ( ) /*5*/ { /*6*/ Console.WriteLine ( `` Checking status every 2 seconds '' ) ; /*7*/ // Create the Timer ensuring that it never fires . This ensures that/*8*/ // s_timer refers to it BEFORE Status is invoked by a thread pool thread/*9*/ s_timer = new Timer ( Status , null , Timeout.Infinite , Timeout.Infinite ) ; /*10*/ // Now that s_timer is assigned to , we can let the timer fire knowing/*11*/ // that calling Change in Status will not throw a NullReferenceException/*12*/ s_timer.Change ( 0 , Timeout.Infinite ) ; /*13*/ Console.ReadLine ( ) ; // Prevent the process from terminating/*14*/ } /*15*/ // This method 's signature must match the TimerCallback delegate/*16*/ private static void Status ( Object state ) /*17*/ { /*18*/ // This method is executed by a thread pool thread/*20*/ Console.WriteLine ( `` In Status at { 0 } '' , DateTime.Now ) ; /*21*/ Thread.Sleep ( 1000 ) ; // Simulates other work ( 1 second ) /*22*/ // Just before returning , have the Timer fire again in 2 seconds/*23*/ s_timer.Change ( 2000 , Timeout.Infinite ) ; /*24*/ // When this method returns , the thread goes back/*25*/ // to the pool and waits for another work item/*26*/ } /*27*/ }",Timer initialization and Race condition in c # ? "C_sharp : I have the following method and for some reason the first call to Copy to seems to do nothing ? Anyone know why ? In input to the method is compressed and base64 can supply that method to if need . private byte [ ] GetFileChunk ( string base64 ) { using ( MemoryStream compressedData = new MemoryStream ( Convert.FromBase64String ( base64 ) , false ) , uncompressedData = new MemoryStream ( ) ) { using ( GZipStream compressionStream = new GZipStream ( compressedData , CompressionMode.Decompress ) ) { // first copy does nothing ? ? second works compressionStream.CopyTo ( uncompressedData ) ; compressionStream.CopyTo ( uncompressedData ) ; } return uncompressedData.ToArray ( ) ; } }",Why do I need two calls to stream CopyTo ? "C_sharp : This is C # 4.0.I have a class that stores WeakReferences on some Actions like that : This class has another method allowing to execute the Actions passed to it later but it 's of little importance in this question.and I consume this class this way : Bar being a third class in my application.My question : In the KeepReference method , how can I know if the Action passed in parameter refers to an anonymous method ( this.Bar = b ; ) or a concrete method ( this.Whatever ) ? I checked the properties of action . I could n't find any property on action ( like IsAbstract ) of a IsAnonymous kind . The underlying type is MethodInfo which makes sense because after compiling I can see in ildasm the anonymous method `` became '' a normal method on Foobar . In ildasm I can also see that the anonymous method is not a full pink square but a white square surrounded by pink and in its definition there 's a call to some CompilerServices classes but I do n't know how to take advantage of this back in C # . I 'm sure it 's possible to get to know about the real nature of action . What am I missing ? public class LoremIpsum { private Dictionary < Type , List < WeakReference > > references = new Dictionary < Type , List < WeakReference > > ( ) ; public void KeepReference < T > ( Action < T > action ) { if ( this.references.ContainsKey ( typeof ( T ) ) ) { this.references [ typeof ( T ) ] .Add ( new WeakReference ( action ) ) ; } else { this.references.Add ( typeof ( T ) , new List < WeakReference > { new WeakReference ( action ) } ) ; } } } public class Foobar { public Bar Bar { get ; set ; } public void Foo ( LoremIpsum ipsum ) { ipsum.KeepReference < Bar > ( ( b ) = > { this.Bar = b ; } ) ; ipsum.KeepReference < Bar > ( this.Whatever ) ; } public void Whatever ( Bar bar ) { // Do anything , for example ... : this.Bar = bar } }",How to know if an Action is an anonymous method or not ? "C_sharp : In my WPF application using .Net 4.6 I have an event which fires new data points at a high rate ( several hundred per second ) , but not all the time . This data is displayed in a chart . I would like to update the chart every 50 ms and not after each new data point.To achieve that I though of using Buffer ( TimeSpan.FromMilliseconds ( 50 ) ) from Rx , which in theory works fine . BUT my subscriber is also called every 50 ms if no new data points are created which is not exactly what I want.I created a little sample application to test that out : You need to add the `` Rx-Linq '' NuGet package for it to run or use the following Fiddle : https : //dotnetfiddle.net/TV5tD4There you see several `` 0 elements received '' which is what I would like to avoid . I know I could simple check for e.Count == 0 , but as I use multiple of such buffers this does not seem optimal to me.Is there a way to only create new buffered blocks of element if elements are available ? I am also open for other approaches to solve my problem of batching events on a time basis - I already looked into TPL Dataflows BatchBlock , but that seems to only support count based block sizes . using System ; using System.Reactive.Linq ; namespace RxTester { public class Program { private static event EventHandler TheEvent ; static void Main ( string [ ] args ) { var observable = Observable.FromEvent < EventHandler , EventArgs > ( h = > ( s , e ) = > h ( e ) , h = > TheEvent += h , h = > TheEvent -= h ) ; var subscriber = observable.Buffer ( TimeSpan.FromMilliseconds ( 1000 ) ) .Subscribe ( e = > Console.WriteLine ( $ '' { DateTime.Now.ToLongTimeString ( ) } : { e.Count } elements received ... '' ) ) ; var random = new Random ( ) ; var timer = new System.Timers.Timer ( 2000 ) { AutoReset = true , Enabled = true } ; timer.Elapsed += ( s , e ) = > { var amount = random.Next ( 1 , 10 ) ; for ( int i = 0 ; i < amount ; ++i ) TheEvent ? .Invoke ( null , null ) ; } ; Console.ReadLine ( ) ; timer.Enabled = false ; subscriber.Dispose ( ) ; } } }",Rx Buffer without empty calls to subscriber C_sharp : Can this code return null ? Can this line ( or a similar one ) return anything except than true or false ( e.g . null ) ? ( this.Result == Result.OK ),Can it returns null ? ( this.Result ==Result.OK ) "C_sharp : The best practice is to collect all the async calls in a collection inside the loop and do Task.WhenAll ( ) . Yet , want to understand what happens when an await is encountered inside the loop , what would the returned Task contain ? what about further async calls ? Will it create new tasks and add them to the already returned Task sequentially ? As per the code belowThe steps I assumed areLoopAsync gets calledcount is set to zero , code enters while loop , condition is checkedSomeNetworkCallAsync is called , and the returned task is awaitedNew task/awaitable is created New task is returned to CallLoopAsync ( ) Now , provided there is enough time for the process to live , How / In what way , will the next code lines like count++ and further SomeNetworkCallAsync be executed ? Update - Based on Jon Hanna and Stephen Cleary : So there is one Task and the implementation of that Task will involve 5 calls to NetworkCallAsync , but the use of a state-machine means those tasks need not be explicitly chained for this to work . This , for example , allows it to decide whether to break the looping or not based on the result of a task , and so on.Though they are not chained , each call will wait for the previous call to complete as we have used await ( in state m/c , awaiter.GetResult ( ) ; ) . It behaves as if five consecutive calls have been made and they are executed one after the another ( only after the previous call gets completed ) . If this is true , we have to be bit more careful in how we are composing the async calls.For ex : Instead of writing It should be written So that we can say RefactoredSomeWorkAsync is faster by 2 seconds , because of the possibility of parallelismIs this correct ? - Yes . Along with `` async all the way '' , `` Accumulate tasks all the way '' is good practice . Similar discussion is here private void CallLoopAsync ( ) { var loopReturnedTask = LoopAsync ( ) ; } private async Task LoopAsync ( ) { int count = 0 ; while ( count < 5 ) { await SomeNetworkCallAsync ( ) ; count++ ; } } private async Task SomeWorkAsync ( ) { await SomeIndependentNetworkCall ( ) ; // 2 sec to complete var result1 = await GetDataFromNetworkCallAsync ( ) ; // 2 sec to complete await PostDataToNetworkAsync ( result1 ) ; // 2 sec to complete } private Task [ ] RefactoredSomeWorkAsync ( ) { var task1 = SomeIndependentNetworkCall ( ) ; // 2 sec to complete var task2 = GetDataFromNetworkCallAsync ( ) .ContinueWith ( result1 = > PostDataToNetworkAsync ( result1 ) ) .Unwrap ( ) ; // 4 sec to complete return new [ ] { task1 , task2 } ; } private async Task CallRefactoredSomeWorkAsync ( ) { await Task.WhenAll ( RefactoredSomeWorkAsync ( ) ) ; //Faster , 4 sec await SomeWorkAsync ( ) ; // Slower , 6 sec }","Inside a loop , does each async call get chained to the returned task using task 's continuewith ?" "C_sharp : I do n't think this is possible but here goes ... I want to add method that can handle n numer of generics . for example : will work for one typewill work for two typesIs there a way to work with n types - e.g . the reason I want to do this is to implement a static nhibernate helper method which can load from multiple assemblies - right now it works great for one assembly . My current method is as shown below : Where the line : m.FluentMappings.AddFromAssemblyOf ( ) , I would like to add multiple types e.g . } Obviously this could n't work I 'm not completely dumb but I am not so hot on generics - can someone confirm that this is n't possible : - ) .. ? What would be the most elegant way of achieving this effect in your opinion.. ? bool < T > MyMethod ( ) where T : Isomething { } bool < T , K > MyMethod ( ) where T : Isomething { } bool < T [ ] > MyMethod ( ) where T : Isomething { } public static ISessionFactory GetMySqlSessionFactory < T > ( string connectionString , bool BuildSchema ) { //configuring is meant to be costly so just do it once for each db and store statically if ( ! AllFactories.ContainsKey ( connectionString ) ) { var configuration = Fluently.Configure ( ) .Database ( MySQLConfiguration.Standard .ConnectionString ( connectionString ) .ShowSql ( ) //for development/debug only.. .UseOuterJoin ( ) .QuerySubstitutions ( `` true 1 , false 0 , yes ' Y ' , no ' N ' '' ) ) .Mappings ( m = > { m.FluentMappings.AddFromAssemblyOf < T > ( ) ; m.AutoMappings.Add ( AutoMap.AssemblyOf < T > ( ) .Conventions.Add < CascadeAll > ) ; } ) .ExposeConfiguration ( cfg = > { new SchemaExport ( cfg ) .Create ( BuildSchema , BuildSchema ) ; } ) ; AllFactories [ connectionString ] = configuration.BuildSessionFactory ( ) ; } return AllFactories [ connectionString ] ; } foreach ( T in T [ ] ) { m.FluentMappings.AddFromAssemblyOf < T > ( )",C # generics - possible to create a method with n Generic types.. ? "C_sharp : My class named S looks like that : When I use using statement , f ( ) method does n't call s.Dispose ( ) method . I thought it should call Dispose method even if the exception occurs . That 's what I read in MSDN : `` The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object '' . Am I missing something ? Calling s.f ( ) ends my program without disposing of my object s. I think I do n't have to use try/catch , because using statement should do it for me . public class S : IDisposable { public void Dispose ( ) { // some code } public void f ( ) { throw new Exception ( `` exception '' ) ; } } using ( S s = new S ( ) ) { s.f ( ) ; }",Using statement does n't work correctly "C_sharp : i 've created a SignalR application but when i set the KeepAliveInternal and ClientTimeOutInterval a value in the hub configuration , the application ignore it and always set to `` 30,000ms '' for both . This is my code : I 've read the SignalR Net Core docs and there is no limit for these two properties . The timeout always is `` 30,000 '' even i set those to differente values . public void ConfigureServices ( IServiceCollection services ) { services.AddRazorPages ( ) ; services.AddSignalR ( ) .AddHubOptions < ActivityHub > ( SetConfig ) ; // Local function to set hub configuration void SetConfig ( HubOptions < ActivityHub > options ) { options.ClientTimeoutInterval = TimeSpan.FromMinutes ( 30 ) ; options.KeepAliveInterval = TimeSpan.FromMinutes ( 15 ) ; } }",SignalR - Change server timeout response "C_sharp : I have the following mapping in my Castle Windsor xml file which has worked okay ( unchanged ) for some time : I got this from the Windsor documentation at http : //www.castleproject.org/container/documentation/v1rc3/usersguide/genericssupport.html.Since I upgraded Windsor , I now get the following exception at runtime : Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : System.TypeLoadException : GenericArguments [ 0 ] , 'T ' , on 'MyApp.Models.Repositories.Linq.BasicRepository ` 1 [ TEntity ] ' violates the constraint of type parameter 'TEntity ' . Source Error : Line 44 : public static void ConfigureIoC ( ) Line 45 : { Line 46 : var windsor = new WindsorContainer ( `` Windsor.xml '' ) ; Line 47 : Line 48 : ServiceLocator.SetLocatorProvider ( ( ) = > new WindsorServiceLocator ( windsor ) ) ; I 'm using ASP.NET MVC 1.0 , Visual Studio 2008 and Castle Windsor as downloaded from http : //sourceforge.net/projects/castleproject/files/InversionOfControl/2.1/Castle-Windsor-2.1.1.zip/downloadCan anyone shed any light on this ? I 'm sure the upgrade of Castle Windsor is what caused it - it 's been working well for ages.UPDATE : I fixed it myself in the end . See my answer below for details . < component id= '' defaultBasicRepository '' service= '' MyApp.Models.Repositories.IBasicRepository ` 1 , MyApp.Models '' type= '' MyApp.Models.Repositories.Linq.BasicRepository ` 1 , MyApp.Models '' lifestyle= '' perWebRequest '' / >",Castle Windsor upgrade causes TypeLoadException for generic types "C_sharp : I am trying to open a pdf file using the below working code I previously used on another app , but this time I am getting System.Runtime.InteropServices.COMException when the flow hits this line : Windows.System.Launcher.LaunchFileAsync ( pdffile ) ; What is the meaning of this exception and how to get rid of it ? Please note that without caring about this exception ( disabling it ) , the file still can not be opened.Please note : the file exists in my isolated folder ( checked with wpowertool ) , I tried with 2 different files so it shouldnt be a matter of file corruption . this MSDN post belongs to me . Yes , the file is installed and I have acrobat reader.Please note that this C # code is a phonegap/cordova plugin which is called via javascript in my hybrid application . public void openFile ( string options ) { System.Diagnostics.Debug.WriteLine ( `` options : `` + options ) ; string optVal = JsonHelper.Deserialize < string [ ] > ( options ) [ 0 ] ; asyncOpen ( optVal ) ; } public async Task asyncOpen ( string filename ) { filename = filename.Substring ( 2 , filename.Length - 2 ) ; filename = filename.Replace ( `` // '' , `` / '' ) .Replace ( `` / '' , `` \\ '' ) ; Windows.Storage.StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder ; Debug.WriteLine ( `` local : `` + local.Path ) ; Windows.Storage.StorageFile pdffile = await local.GetFileAsync ( filename ) ; Debug.WriteLine ( `` pdffile : `` + pdffile.Name ) ; //// Launch the pdf file . Windows.System.Launcher.LaunchFileAsync ( pdffile ) ; }",System.Runtime.InteropServices.COMException when launching a pdf file on Windows Phone "C_sharp : In more industry or automation related applications ( that mostly heavily rely on external components which they have to manage ) , you 'll often end up with the case that the domain contains models which are more than just abstractions from the real problem , but also representations of and pointers to something that physically exist outside of the domain.For example , take this domain entity that represents a network device : Instead of just storing or validating such entities or taking actions upon entity changes , an application may need to manage external components based upon their representations inside the domain . Now , is DDD even suitable for such cases ? Are those managers domain services ? Eric Evans describes in his famous blue book that a domain service needs to be a stateless model implementing methods taken from the ubiquitos language to fullfil a request that the entity , or a repository can not handle by itself . But what if a service needs to be stateful ? A simple example : An application needs to monitor configured IP devices within the network in order to notify other application inside the domain about state events . If a IP device gets registered inside the application ( stored inside a database , for example ) , a `` ping-service '' gets notified and starts to monitor the device.Other components could then handle those status events and e.g . stop talking to the device via other protocols if the device goes offline.Now , what are those components ? At first I thought they are domain services because they serve a certain requirement of the domain . However , they are stateful as well as do not specifically represent the ubiquitos language ( the task of a ping-service is to ping a domain entity and report it 's status , however the ping-service does not implement a method that would clients allow to ping a device ) .Are they application services ? Where do such components fit inside the DDD pattern ? public class NetworkDevice { public IPAddress IpAddress { get ; set ; } } public class PingMonitor : IDisposable , IHandle < DeviceRegisteredEvent > , IHandle < DeviceRemovedEvent > { public List < NetworkDevice > _devices = new List < NetworkDevice > ( ) ; public void Handle ( DeviceRegisteredEvent @ event ) { _devices.Add ( @ event.Device ) ; } public void Handle ( DeviceRemovedEvent @ event ) { _devices.Remove ( @ event.Device ) ; } public void PingWorker ( ) { foreach ( var device in _devices ) { var status = Ping ( device.IpAddress ) ; if ( status ! = statusBefore ) DomainEvents.Raise < DeviceStateEvent > ( new DeviceStateEvent ( device , status ) ) ; } } }","Where do long running , stateful 'services ' fit in DDD ?" "C_sharp : I am designing a set of 'service ' layer objects ( data objects andinterface definitions ) for a WCF web service ( that will be consumedby third party clients i.e . not in-house , so outside my direct control ) .I know that I amnot going to get the interface definition exactly right - and amwanting to prepare for the time when I know that I will have tointroduce a breaking set of new data objects . However , the realityof the world I am in is that I will also need to run my first versionsimultaneously for quite a while.The first version of my service will have URL of http : //host/app/v1service.svcand when the times comes by new version will live athttp : //host/app/v2service.svcHowever , when it comes to the data objects and interfaces , Iam toying with putting the 'major ' version of the interface numberinto the actual namespace of the classes.When the time comes for a fundamental change to the service , I will introducesome classes likeThe advantages as I see it are that I will be able to have a singleset of code serving both interface versions , sharing functionalitywhere possible . This is because Iwill be able to reference both interface versions as a distinctset of C # objects . Similarly , clients may use both interfaceversions simultaneously , perhaps using V1.Widget in some legacycode whilst new bits move on to V2.Widget.Can anyone tell why this is a stupid idea ? I have a nagging feelingthat this is a bit smelly..notes : I am obviously not proposing every single new version of the servicewould be in a new namespace . Presumably I will do as manynon-breaking interface changes as possible , but I know that Iwill hit a point where all the data modelling will probably need asignificant rewrite.I understand assembly versioning etc but I think this question istangential to that type of versioning . But I could be wrong . namespace Company.Product.V1 { [ DataContract ( Namespace = `` company-product-v1 '' ) ] public class Widget { [ DataMember ] string widgetName ; } public interface IFunction { Widget GetWidgetData ( int code ) ; } } namespace Company.Product.V2 { [ DataContract ( Namespace = `` company-product-v2 '' ) ] public class Widget { [ DataMember ] int widgetCode ; [ DataMember ] int widgetExpiry ; } public interface IFunction { Widget GetWidgetData ( int code ) ; } }",should I ever put a major version number into a C # /Java namespace ? "C_sharp : For the following line of C # code : If I evaluate `` bitty '' in the Watch window , I do n't see the members of the collection . If I evaluate `` bitty , results '' , which is supposed to enumerate the IEnumerable and show the results , I get the message `` Only Enumerable types can have Results View '' , even though a BitArray IS an IEnumerable.Why does the debugger do this ? CLARIFICAITON : I 'm asking what is happening inside the VS Debugger Expression Evaluator , NOT asking how to view a BitArray in the debugger.. BitArray bitty = new BitArray ( new [ ] { false , false , true , false } ) ;",Why wo n't Visual Studio Debugger enumerate a BitArray and show me the results ? "C_sharp : On the MSDN , I have found following : Is it reference ? If so I do not understand its meaning as when SampleEvent became null , so does the temp public event EventHandler < MyEventArgs > SampleEvent ; public void DemoEvent ( string val ) { // Copy to a temporary variable to be thread-safe . EventHandler < MyEventArgs > temp = SampleEvent ; if ( temp ! = null ) temp ( this , new MyEventArgs ( val ) ) ; }",Question regarding to value/reference type of events "C_sharp : Is there a way to convert the property selector Expression < Func < T , TProperty > > to Expression < Func < object , object > > and vice versa ? I already know how to convert to Expression < Func < T , object > > using ... ... but I need to effectively cast both , the argument and the result of the function , not just e.g replace them with a ExpressionVisitor because they need to be casted back later . Expression < Func < T , TProperty > > oldExp ; Expression.Lambda < Func < T , object > > ( Expression.Convert ( oldExp.Body , typeof ( object ) ) , oldExp.Parameters ) ;","Convert Expression < Func < T , TProperty > > to Expression < Func < object , object > > and vice versa" "C_sharp : In this question I asked about NHibernate session lifetime . I 'm using a desktop application , but with client/server separation , so the conclusion is that I will use one session per server request , as the server side is where all the NHibernate magic happens . My problem now is how to handle it . I 've had problems before with loading of referenced data when the session is prematurely closed . The problem is that I see the following on my referenced classes when debugging - hence the referenced data is n't loaded yet : base { NHibernate.HibernateException } = { `` Initializing [ MyNamespace.Foo # 14 ] -failed to lazily initialize a collection of role : MyNamespace.Foo.Bars , no session or session was closed '' } From what I understand it does n't load all even though I commit the transaction . So I 've learned that I need to keep my session open for a while , but how long ? My question is basically if I 'm handling the lifetime properly , or what I should change to be on the right track . Honestly I ca n't see how this can be wrong , so what I 'd really like is a function call to ensure that the referenced data is fetched . I 'm not using lazy loading , so I thought they would be loaded immediately.. ? Current architecture : Using a `` service behavior '' class that does the transaction . This is IDisposable , so the service itself it using a using-clause around it . The NHibernateSessionFactory provides a static factory which hence will be resused . // This is the service - the function called `` directly '' through my WCF service . public IList < Foo > SearchForFoo ( string searchString ) { using ( var serviceBehavior = new FooServiceBehavior ( new NhibernateSessionFactory ( ) ) ) { return serviceBehavior.SearchForFoo ( searchString ) ; } } public class FooServiceBehavior : IDisposable { private readonly ISession _session ; public FooServiceBehavior ( INhibernateSessionFactory sessionFactory ) { _session = sessionFactory.OpenSession ( ) ; } public void Dispose ( ) { _session.Dispose ( ) ; } public IList < Foo > SearchForFoo ( string searchString ) { using ( var tx = _session.BeginTransaction ( ) ) { var result = _session.CreateQuery ( `` from Foo where Name= : name '' ) .SetString ( `` name '' , searchString ) .List < Name > ( ) ; tx.Commit ( ) ; return result ; } }",How to handle NHibernate session lifetime using services ? "C_sharp : I have a large arbitrary JSON structure as a JObject reference in my code.I want to serialise this structure , except when I encounter a JObject containing a property called type with value `` encrypted '' then I want to remove the adjacent data property before writing the object . In other words , if I encounter this : It will be serialized as this : I ca n't mutate the structure , and cloning it before mutating would be too inefficient , so I tried using a JsonConverter as follows : However the CanConvert function only seems to be called with types not derived from JToken , so my WriteJson function is never called.Is there another way to achieve this ? Edit : Here is some code you can use for testing : { type : `` encrypted '' , name : `` some-name '' , data : `` < base64-string > '' } { type : `` encrypted '' , name : `` some-name '' } public class RemoveEncryptedDataSerializer : JsonConverter { public override bool CanConvert ( Type objectType ) { return objectType == typeof ( JObject ) ; } public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer ) { throw new NotImplementedException ( ) ; } public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { var o = ( JObject ) value ; if ( o.Value < string > ( `` type '' ) ! = `` encrypted '' ) { o.WriteTo ( writer ) ; return ; } var copy = o.DeepClone ( ) ; copy [ `` data '' ] ? .Parent.Remove ( ) ; copy.WriteTo ( writer ) ; } } [ TestMethod ] public void ItShouldExcludeEncryptedData ( ) { var input = JObject.Parse ( @ '' { a : { type : 'encrypted ' , name : 'some-name ' , data : 'some-data ' } } '' ) ; var expected = JObject.Parse ( @ '' { a : { type : 'encrypted ' , name : 'some-name ' , } } '' ) ; var output = input.ToString ( Formatting.Indented , new RemoveEncryptedDataSerializer ( ) ) ; Assert.AreEqual ( expected.ToString ( Formatting.Indented ) , output ) ; }",Serializing a JSON.NET JObject while filtering out certain properties "C_sharp : I want to use AddDays ( ) method in for loop . But it does n't work . in spite of using in loop , day value is not increasing . Then it is transforming infinite loop . For example ; How I use AddDays ( ) method in a for loopThank you so much DateTime exDt = tempPermissionWarning [ i ] .planned_start_date ; for ( DateTime dt = exDt ; dt < = newTo ; dt.AddDays ( 1 ) ) { context = context + dt.ToShortDateString ( ) + `` æ '' + tempPermissionWarning [ i ] .resource_name ) + ¨ '' ; }",AddDays ( ) in for loop "C_sharp : I 've figured out a way to bind user controls inside a tree view dynamically with ReactiveUI . But ... The top level binding to the HierachicalDataSource is in the XAML not the code behind , and I need to set the ItemsSource directly and not use this.OneWayBind per the general pattern for ReactiveUI binding.So , my question is : did I miss something in the ReactiveUI framework that would let me bind with this.OneWayBind and move the HierachicalDataTemplete into the code behind or a custom user control ? In particular- Is there another overload of OneWayBind supporting Hierarchical Data Templates , or a way to suppress the data template generation for the call when using it ? UpdateI 've added selected item , and programatic support for Expand and Selected to my test project , but I had to add a style to the XAML . I 'd like to replace that with a simple RxUI Bind as well . Updated the examples.Here are the key details : Tree Control in Main View main view code behindMainViewModelTreeItem base classPerson Classperson view user controlPerson view code behindPet work the same as person.And the full project is here ReactiveUI Tree view Sample < TreeView Name= '' FamilyTree '' > < TreeView.Resources > < Style TargetType= '' { x : Type TreeViewItem } '' > < Setter Property= '' IsSelected '' Value= '' { Binding IsSelected , Mode=TwoWay } '' / > < Setter Property= '' IsExpanded '' Value= '' { Binding IsExpanded , Mode=TwoWay } '' / > < /Style > < HierarchicalDataTemplate DataType= '' { x : Type local : TreeItem } '' ItemsSource= '' { Binding Children } '' > < reactiveUi : ViewModelViewHost ViewModel= '' { Binding ViewModel } '' / > < /HierarchicalDataTemplate > < /TreeView.Resources > < /TreeView > public partial class MainWindow : Window , IViewFor < MainVM > { public MainWindow ( ) { InitializeComponent ( ) ; //build viewmodel ViewModel = new MainVM ( ) ; //Register views Locator.CurrentMutable.Register ( ( ) = > new PersonView ( ) , typeof ( IViewFor < Person > ) ) ; Locator.CurrentMutable.Register ( ( ) = > new PetView ( ) , typeof ( IViewFor < Pet > ) ) ; //NB . ! Do not use 'this.OneWayBind ... ' for the top level binding to the tree view //this.OneWayBind ( ViewModel , vm = > vm.Family , v = > v.FamilyTree.ItemsSource ) ; FamilyTree.ItemsSource = ViewModel.Family ; } ... } public class MainVM : ReactiveObject { public MainVM ( ) { var bobbyJoe = new Person ( `` Bobby Joe '' , new [ ] { new Pet ( `` Fluffy '' ) } ) ; var bob = new Person ( `` Bob '' , new [ ] { bobbyJoe } ) ; var littleJoe = new Person ( `` Little Joe '' ) ; var joe = new Person ( `` Joe '' , new [ ] { littleJoe } ) ; Family = new ReactiveList < TreeItem > { bob , joe } ; _addPerson = ReactiveCommand.Create ( ) ; _addPerson.Subscribe ( _ = > { if ( SelectedItem == null ) return ; var p = new Person ( NewName ) ; SelectedItem.AddChild ( p ) ; p.IsSelected = true ; p.ExpandPath ( ) ; } ) ; } public ReactiveList < TreeItem > Family { get ; } ... } public abstract class TreeItem : ReactiveObject { private readonly Type _viewModelType ; bool _isExpanded ; public bool IsExpanded { get { return _isExpanded ; } set { this.RaiseAndSetIfChanged ( ref _isExpanded , value ) ; } } bool _isSelected ; public bool IsSelected { get { return _isSelected ; } set { this.RaiseAndSetIfChanged ( ref _isSelected , value ) ; } } private TreeItem _parent ; protected TreeItem ( IEnumerable < TreeItem > children = null ) { Children = new ReactiveList < TreeItem > ( ) ; if ( children == null ) return ; foreach ( var child in children ) { AddChild ( child ) ; } } public abstract object ViewModel { get ; } public ReactiveList < TreeItem > Children { get ; } public void AddChild ( TreeItem child ) { child._parent = this ; Children.Add ( child ) ; } public void ExpandPath ( ) { IsExpanded = true ; _parent ? .ExpandPath ( ) ; } public void CollapsePath ( ) { IsExpanded = false ; _parent ? .CollapsePath ( ) ; } } public class Person : TreeItem { public string Name { get ; set ; } public Person ( string name , IEnumerable < TreeItem > children = null ) : base ( children ) { Name = name ; } public override object ViewModel = > this ; } < UserControl x : Class= '' TreeViewInheritedItem.PersonView '' ... > < StackPanel > < TextBlock Name= '' PersonName '' / > < /StackPanel > < /UserControl > public partial class PersonView : UserControl , IViewFor < Person > { public PersonView ( ) { InitializeComponent ( ) ; this.OneWayBind ( ViewModel , vm = > vm.Name , v = > v.PersonName.Text ) ; } ... }",How to use ReactiveUI with a Hierarchical Data Source ( Tree view ) "C_sharp : I have some troubles with deserializing.If I use it 's working normally , but in case when I use just < CardNumber / > - object is not deserializing ( Is there any way to deserialize empty element as Guid.Empty ? Property which should be mapped with value of this element : Same situation in JSON works normally and use Guid.Empty instead of empty element value < Order > ... < CardNumber / > ... < /Order > < CardNumber > 00000000-0000-0000-0000-000000000000 < /CardNumber > [ XmlElement ( ElementName = `` CardNumber '' ) ] [ JsonProperty ( `` CardNumber '' ) ] public Guid ? CardNumber { get ; set ; } { `` CardNumber '' : `` '' }",Deserialize empty XML element as Guid.Empty "C_sharp : I have just started trying out the Windows Speech to Text capabilities in C # .Net . I currently have the basics working ( IE - Say something , and it will provide output based on what you say ) . However , I am struggling to figure out how to actually recieve user input as a variable.What I mean by this , is that for example . If the user says : Then I want to be able to take the word John as a variable and then store that as say , the persons username.My current SpeechRecognized event is as follows : NB : writeConsolas is just a glorified append line to a RichTextBox.I would like to add another case which does the following : Obviously , there is no such method , but that is the general idea that I wish to implement . Is there a way to search for specific phrases ( IE : Call me ) and take the following word ? EDIT : I should note , that the e.Result.Text only returns words that it can match to Text in the dictionary . `` Call me John '' void zeusSpeechRecognised ( object sender , SpeechRecognizedEventArgs e ) { writeConsolas ( e.Result.Text , username ) ; switch ( e.Result.Grammar.RuleName ) { case `` settingsRules '' : switch ( e.Result.Text ) { case `` test '' : writeConsolas ( `` What do you want me to test ? `` , me ) ; break ; case `` change username '' : writeConsolas ( `` What do you want to be called ? `` , me ) ; break ; case `` exit '' : writeConsolas ( `` Do you wish me to exit ? `` , me ) ; break ; } break ; } } case `` call me '' username = e.Result.GetWordFollowingCallMe ( ) //Obv not a method , but thats the general idea . break ;",Get user input from Speech ? "C_sharp : I 've got a bit of code that is acting as a light weight , non-blocking , critical section . I am hoping that no matter what happens with _func and cancellationToken in the Task.Run clause , that the continuation is guaranteed to run such that the Exit statement in its finally block will always execute.Is it safe to assume that the finally block below , short of catastrophic failure in the process , will be executed with roughly the same guarantees that finally normal operates with ? if ( Enter ( ) ) { Task.Run < T > ( _func , cancellationToken ) .ContinueWith ( ( antecedent ) = > { try { antecedent.Wait ( cancellationToken ) ; Interlocked.Exchange < T > ( ref _result , antecedent.Result ) ; } catch ( AggregateException e ) { Interlocked.Exchange ( ref _exceptions , e ) ; } catch ( OperationCanceledException ) { ResetState ( ) ; } catch ( Exception e ) { Interlocked.Exchange ( ref _exceptions , new AggregateException ( e ) ) ; } finally { Exit ( ) ; } } ) }",Is ContinueWith guaranteed to execute ? "C_sharp : How can I see the document DB sql query ( in a string ) generated by a linq statement before it gets sent to the server ? I want to use this for tracing purposes . _documentClient.CreateDocumentQuery < MyType > ( UriFactory.CreateDocumentCollectionUri ( DatabaseName , CollectionName ) ) .Where ( ... . ) .SelectMany ( ... )",How can I trace the query produced by the documentdb Linq provider ? "C_sharp : I need to get the Jack Information of the Audio Device in MS Windows 7 using C # , C++ or any .NET framework.I checked NAudio framework but seems is impossible to use it in this case.Also those links are not usefull https : //msdn.microsoft.com/en-us/library/windows/desktop/dd370793 ( v=vs.85 ) .aspx and https : //msdn.microsoft.com/en-us/library/windows/desktop/dd370812 ( v=vs.85 ) .aspx.And this approach does n't help as well.Any clue how to get this info or at least some MSDN refernece to that property ? P.S . Here is C++ code to obtaim similar properties of Audio Device that I use but can not get how to get Jack Information ManagementObjectSearcher objSearcher = new ManagementObjectSearcher ( `` SELECT * FROM Win32_SoundDevice '' ) ; ManagementObjectCollection objCollection = objSearcher.Get ( ) ; foreach ( ManagementObject obj in objCollection ) { foreach ( PropertyData property in obj.Properties ) { Debug.WriteLine ( String.Format ( `` { 0 } : { 1 } '' , property.Name , property.Value ) ) ; } } # pragma once # include `` Mmdeviceapi.h '' # include `` PolicyConfig.h '' # include `` Propidl.h '' # include `` NotificationClient.h '' # include `` AudioDevice.h '' namespace AudioDeviceUtil { ref class MmDeviceApiWrapper { public : MmDeviceApiWrapper ( void ) { //.Net threads are coinitialized ... //CoInitializeEx ( NULL , COINIT_MULTITHREADED ) ; notificationRegistered = false ; audioDeviceNotificationHelper = gcnew AudioDeviceNotificationHelper ( ) ; pNotifyClient = NULL ; } virtual ~MmDeviceApiWrapper ( void ) { //CoUninitialize ( ) ; if ( notificationRegistered ) RegisterForNotification ( false ) ; } static property AudioDeviceNotificationHelper^ AudioDeviceNotification { AudioDeviceNotificationHelper^ get ( ) { return audioDeviceNotificationHelper ; } } ; static property bool IsRegisteredForNotification { bool get ( ) { return notificationRegistered ; } } // Enumerates playback device list and marks the default device by the appropriate flag static System : :Collections : :Generic : :List < AudioDevice^ > ^ GetPlaybackDeviceList ( ) { System : :Collections : :Generic : :List < AudioDevice^ > ^ playbackDevices = gcnew System : :Collections : :Generic : :List < AudioDevice^ > ( ) ; HRESULT hr = S_OK ; //CoInitialize ( NULL ) ; HRESULT hr2 = S_OK ; //HRESULT hr3 = S_OK ; if ( SUCCEEDED ( hr ) ) { IMMDeviceEnumerator *pEnum = NULL ; // Create a multimedia device enumerator . hr = CoCreateInstance ( __uuidof ( MMDeviceEnumerator ) , NULL , CLSCTX_ALL , __uuidof ( IMMDeviceEnumerator ) , ( void** ) & pEnum ) ; if ( SUCCEEDED ( hr ) ) { IMMDevice *pDevice ; IMMDeviceCollection *pDevices ; LPWSTR wstrDefaultID = L '' '' ; // Enumerate the output devices . hr = pEnum- > EnumAudioEndpoints ( eRender , DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED | DEVICE_STATE_DISABLED , & pDevices ) ; if ( SUCCEEDED ( hr ) ) { HRESULT hrDef = pEnum- > GetDefaultAudioEndpoint ( eRender , eConsole , & pDevice ) ; if ( SUCCEEDED ( hrDef ) ) { hrDef = pDevice- > GetId ( & wstrDefaultID ) ; } System : :Diagnostics : :Trace : :WriteLineIf ( ! SUCCEEDED ( hrDef ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] GetDefaultAudioEndPoint failed : { 0 : X } '' , hr ) , `` Error '' ) ; } if ( SUCCEEDED ( hr ) ) { UINT count ; pDevices- > GetCount ( & count ) ; if ( SUCCEEDED ( hr ) ) { for ( unsigned int i = 0 ; i < count ; i++ ) { hr = pDevices- > Item ( i , & pDevice ) ; if ( SUCCEEDED ( hr ) ) { LPWSTR wstrID = NULL ; DWORD dwState = 0 ; hr = pDevice- > GetId ( & wstrID ) ; hr2 = pDevice- > GetState ( & dwState ) ; if ( SUCCEEDED ( hr ) & & SUCCEEDED ( hr2 ) ) { IPropertyStore *pStore ; hr = pDevice- > OpenPropertyStore ( STGM_READ , & pStore ) ; if ( SUCCEEDED ( hr ) ) { //PROPVARIANT jackSubType ; //PropVariantInit ( & jackSubType ) ; //hr3 = pStore- > GetValue ( PKEY_Device_JackSubType , & jackSubType ) ; // PROPVARIANT friendlyName ; PropVariantInit ( & friendlyName ) ; hr = pStore- > GetValue ( PKEY_Device_FriendlyName , & friendlyName ) ; if ( SUCCEEDED ( hr ) ) { System : :String^ name = gcnew System : :String ( friendlyName.pwszVal ) ; playbackDevices- > Add ( gcnew AudioDevice ( gcnew System : :String ( wstrID ) , name , ( AudioDeviceStateType ) dwState , 0 == wcscmp ( wstrID , wstrDefaultID ) ) ) ; PropVariantClear ( & friendlyName ) ; } /*if ( SUCCEEDED ( hr3 ) ) { PropVariantClear ( & jackSubType ) ; } */ pStore- > Release ( ) ; } } System : :Diagnostics : :Trace : :WriteLineIf ( ! ( SUCCEEDED ( hr ) & & SUCCEEDED ( hr2 ) ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] GetID or GetState failed : { 0 : X } '' , hr ) , `` Error '' ) ; pDevice- > Release ( ) ; } } } pDevices- > Release ( ) ; } pEnum- > Release ( ) ; } } System : :Diagnostics : :Trace : :WriteLineIf ( ! ( SUCCEEDED ( hr ) & & SUCCEEDED ( hr2 ) ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] Error : GetPlaybackDeviceList failed : { 0 : X } , { 1 : X } '' , hr , hr2 ) , `` Error '' ) ; //CoUninitialize ( ) ; return playbackDevices ; } // Get default playback device on the system static AudioDevice^ GetDefaultPlaybackDevice ( ) { AudioDevice^ defaultPlaybackDevice = nullptr ; HRESULT hr = S_OK ; //CoInitialize ( NULL ) ; //HRESULT hr = CoInitializeEx ( NULL , COINIT_MULTITHREADED ) ; HRESULT hr2 = S_OK ; if ( SUCCEEDED ( hr ) ) { IMMDeviceEnumerator *pEnum = NULL ; // Create a multimedia device enumerator . hr = CoCreateInstance ( __uuidof ( MMDeviceEnumerator ) , NULL , CLSCTX_ALL , __uuidof ( IMMDeviceEnumerator ) , ( void** ) & pEnum ) ; if ( SUCCEEDED ( hr ) ) { IMMDevice *pDevice ; // Enumerate the output devices . hr = pEnum- > GetDefaultAudioEndpoint ( eRender , eConsole , & pDevice ) ; LPWSTR wstrID = NULL ; hr = pDevice- > GetId ( & wstrID ) ; DWORD dwState = 0 ; hr2 = pDevice- > GetState ( & dwState ) ; if ( SUCCEEDED ( hr ) & & SUCCEEDED ( hr2 ) ) { IPropertyStore *pStore ; hr = pDevice- > OpenPropertyStore ( STGM_READ , & pStore ) ; if ( SUCCEEDED ( hr ) ) { PROPVARIANT friendlyName ; PropVariantInit ( & friendlyName ) ; hr = pStore- > GetValue ( PKEY_Device_FriendlyName , & friendlyName ) ; if ( SUCCEEDED ( hr ) ) { defaultPlaybackDevice = gcnew AudioDevice ( gcnew System : :String ( friendlyName.pwszVal ) , gcnew System : :String ( wstrID ) , ( AudioDeviceStateType ) dwState , true ) ; } PropVariantClear ( & friendlyName ) ; } pStore- > Release ( ) ; } pDevice- > Release ( ) ; } } System : :Diagnostics : :Trace : :WriteLineIf ( ! ( SUCCEEDED ( hr ) & & SUCCEEDED ( hr2 ) ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] Error : GetDefaultPlaybackDevice failed : { 0 : X } , { 1 : X } '' , hr , hr2 ) , `` Error '' ) ; //CoUninitialize ( ) ; return defaultPlaybackDevice ; } // Set default playback device on the system // returns true if succeeded . static bool SetDefaultPlaybackDevice ( LPCWSTR devIDString ) { IPolicyConfigVista *pPolicyConfig ; ERole reserved = eConsole ; HRESULT hr = CoCreateInstance ( __uuidof ( CPolicyConfigVistaClient ) , NULL , CLSCTX_ALL , __uuidof ( IPolicyConfigVista ) , ( LPVOID * ) & pPolicyConfig ) ; System : :Diagnostics : :Trace : :WriteLineIf ( ! SUCCEEDED ( hr ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] SetDefaultPlaybackDevice CoCreate failed : { 0 : X } '' , hr ) , `` Error '' ) ; if ( SUCCEEDED ( hr ) ) { System : :Diagnostics : :Trace : :WriteLine ( System : :String : :Format ( `` [ MmDeviceApiWrapper ] SetDefaultPlaybackDevice to devId { 0 } '' , gcnew System : :String ( devIDString ) ) , `` Information '' ) ; hr = pPolicyConfig- > SetDefaultEndpoint ( devIDString , reserved ) ; System : :Diagnostics : :Trace : :WriteLineIf ( SUCCEEDED ( hr ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] SetDefaultPlaybackDevice SetDefEndPoint succeeded . `` ) , `` Information '' ) ; System : :Diagnostics : :Trace : :WriteLineIf ( ! SUCCEEDED ( hr ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] SetDefaultPlaybackDevice SetDefEndPoint failed : { 0 : X } '' , hr ) , `` Error '' ) ; pPolicyConfig- > Release ( ) ; } return SUCCEEDED ( hr ) ; } static bool RegisterForNotification ( ) { if ( ! notificationRegistered ) { pNotifyClient = new CMMNotificationClient ( audioDeviceNotificationHelper ) ; notificationRegistered = RegisterForNotification ( true ) ; } return notificationRegistered ; } static bool UnRegisterForNotification ( ) { if ( notificationRegistered & & pNotifyClient ) { notificationRegistered = ! RegisterForNotification ( false ) ; SAFE_DELETE ( pNotifyClient ) ; return notificationRegistered ; } else { return false ; } } private : static AudioDeviceNotificationHelper^ audioDeviceNotificationHelper ; static bool notificationRegistered ; static CMMNotificationClient* pNotifyClient ; // Registered or unregister for notification . // The clients can use the event of the A // returns true if succeeded . static bool RegisterForNotification ( bool registerForNotification ) { HRESULT hr = S_OK ; //CoInitialize ( NULL ) ; if ( SUCCEEDED ( hr ) ) { IMMDeviceEnumerator *pEnum = NULL ; // Create a multimedia device enumerator . hr = CoCreateInstance ( __uuidof ( MMDeviceEnumerator ) , NULL , CLSCTX_ALL , __uuidof ( IMMDeviceEnumerator ) , ( void** ) & pEnum ) ; if ( SUCCEEDED ( hr ) ) { IMMNotificationClient* pNotify = ( IMMNotificationClient* ) ( pNotifyClient ) ; if ( ! registerForNotification ) { hr = pEnum- > UnregisterEndpointNotificationCallback ( pNotify ) ; } else { hr = pEnum- > RegisterEndpointNotificationCallback ( pNotify ) ; } System : :Diagnostics : :Trace : :WriteLineIf ( SUCCEEDED ( hr ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] { 0 } Register for notification succeeded . `` , registerForNotification ? `` '' : `` Un '' ) , `` Information '' ) ; System : :Diagnostics : :Trace : :WriteLineIf ( ! SUCCEEDED ( hr ) , System : :String : :Format ( `` [ MmDeviceApiWrapper ] Error : { 0 } Register for notification not succeded ! Code : { 1 } '' , registerForNotification ? `` '' : `` Un '' , ( hr == E_POINTER ? `` E_POINTER '' : ( hr == E_OUTOFMEMORY ? `` E_OUTOFMEMORY '' : ( hr == E_NOTFOUND ? `` E_NOTFOUND '' : `` NOT_DEFINED '' ) ) ) ) , `` Error '' ) ; } pEnum- > Release ( ) ; } //CoUninitialize ( ) ; return SUCCEEDED ( hr ) ; } } ; }",How to get Jack Information of Audio Device in MS WIndows 7 "C_sharp : .NET now supports the null coalescing operatorI might be overlooking something obvious , but is there something similar for the ternary operator , such that instead of doingit would n't be needed to call amethod ( ) twice ? var item = aVal ? ? aDefaultVal ; var item = aclass.amethod ( ) > 5 ? aclass.amethod ( ) : 5 ;",Single call ternary operator "C_sharp : I 'm new to Entity Framework and am trying to figure things out . I have a database created that 's not very complicated . There 's about 7 tables and 3 of those are mapping tables to associate one table record w/ another . The example I 'm using here is this : Table UserUserIdUserNameTable RoleRoleIdRoleNameTable : UserRoleUserIdRoleIdThe foreign keys are mapped in my database . When I create a new Entity Model inside of VS 2008 , the diagram seems to have the relationships correct , but does not create a table for the UserRole table . The relationship is mapped as a Many to Many between User & Role.My problem is that I can create new users and I can create new roles , but I can not figure out how to create a new user with an existing role . Furthermore , the UserRole table is probably not mapped correctly within the model to begin with . Here 's my code so far : Here 's the error I am getting : Unable to update the EntitySet 'UserRoles ' because it has a DefiningQuery and no element exists in the element to support the current operation.Here is the xml that pertains to the UserRole table : It was pulling teeth just to figure out how to query the context such that it gave me an actual Role entity . I 'm sure the issue is something to do with how UserRole is mapped , but I 'm just getting started here and have n't any idea where that might have gone wrong.And I really have searched google & this site , but I suppose I have n't come up with the right search parameters to find a question that helps me fix this . I found one question that said EF has issues with this , but if you 're mapping table makes both columns a primary key , it works itself out . I 'm not sure how to do that . Is this done in the database ( using SQL SERVER 2005 EXPRESS ) or in the mapping ? This is a personal project so I can post more details about the code or xml if needed . Any and all help will be appreciated . ObjectQuery < Role > roles = context.Roles ; Role role = context.Roles.Where ( c = > c.RoleName == `` Subscriber '' ) .First ( ) ; User user = new User { DisplayName = `` TestCreate2 '' , Email = `` test @ test.com '' , Password = `` test '' } ; context.AttachTo ( `` Roles '' , role ) ; user.Roles.Add ( role ) ; context.AddToUsers ( user ) ; context.SaveChanges ( ) ; < EntitySet Name= '' UserRoles '' EntityType= '' RememberTheJourneyModel.Store.UserRoles '' store : Type= '' Tables '' store : Schema= '' dbo '' store : Name= '' UserRoles '' > < DefiningQuery > SELECT [ UserRoles ] . [ Role_id ] AS [ Role_id ] , [ UserRoles ] . [ User_id ] AS [ User_id ] FROM [ dbo ] . [ UserRoles ] AS [ UserRoles ] < /DefiningQuery > < /EntitySet >","Using Entity Framework , how do I reflect a many to many relationship and add entites that exist to a new entity being created ?" C_sharp : Why does this not work ? Do I not understand delegate covariance correctly ? public delegate void MyDelegate ( object obj ) public class MyClass { public MyClass ( ) { //Error : Expected method with 'void MyDelegate ( object ) ' signature _delegate = MyMethod ; } private MyDelegate _delegate ; public void MyMethod ( SomeObject obj ) { } },Delegate Covariance Confusion Conundrum ! "C_sharp : I have a line of code , something like : Output is : 2.25 for example . Is it possible to escape a dot from the output string view with String.Format function ? For . ex . 225 , To make my question more clear , I need the same effect like : But need to do it by String.Format template.. Thanks . mbar.HealthLabel.text = String.Format ( `` { 0:0.0 } '' , _hp ) ; Math.Floor ( _hp * 100 ) .ToString ( ) ;",C # String format : escape a dot "C_sharp : Today I was playing around with Entity Framework and I 've read that the generated IL for C # was different than VB.NET for the following code : VB.NET : C # : They produce the following IL : VB : C # : As it seems the VB.NET version of this code will contact the database every time the code is executed while the C # version will retrieve the entities from the cache when the code is executed multiple times.Why would they make both languages behave in such a different manner ? It was my misconception that both languages just differed in syntax and had almost exactly the same generated IL.Are there any more examples where both languages generated such different IL ? Dim ctx As New TravelEntitiesSub Main ( ) CallContext ( ) CallContext ( ) CallContext ( ) End SubPrivate Sub CallContext ( ) Dim someCustomer = From x In ctx.Customer Where x.CustomerId.Equals ( 5 ) Select x Console.WriteLine ( someCustomer.Count ( ) ) End Sub private static TravelEntities ctx = new TravelEntities ( ) ; static void Main ( string [ ] args ) { CallContext ( ) ; CallContext ( ) ; CallContext ( ) ; } private static void CallContext ( ) { var someCustomer = from x in ctx.Customer where x.CustomerId.Equals ( 5 ) select x ; Console.WriteLine ( someCustomer.Count ( ) ) ; } .method private static void CallContext ( ) cil managed { // Code size 195 ( 0xc3 ) .maxstack 7 .locals init ( [ 0 ] class [ System.Core ] System.Linq.IQueryable ` 1 < class VB_IL_Difference.Customer > someCustomer , [ 1 ] class [ System.Core ] System.Linq.Expressions.ParameterExpression VB $ t_ref $ S0 , [ 2 ] class [ System.Core ] System.Linq.Expressions.Expression [ ] VB $ t_array $ S0 , [ 3 ] class [ System.Core ] System.Linq.Expressions.ParameterExpression [ ] VB $ t_array $ S1 , [ 4 ] class [ System.Core ] System.Linq.Expressions.ParameterExpression VB $ t_ref $ S1 , [ 5 ] class [ System.Core ] System.Linq.Expressions.ParameterExpression [ ] VB $ t_array $ S2 ) IL_0000 : nop IL_0001 : ldsfld class VB_IL_Difference.TravelEntities VB_IL_Difference.Module1 : :ctx IL_0006 : callvirt instance class [ System.Data.Entity ] System.Data.Objects.ObjectSet ` 1 < class VB_IL_Difference.Customer > VB_IL_Difference.TravelEntities : :get_Customer ( ) IL_000b : ldtoken VB_IL_Difference.Customer IL_0010 : call class [ mscorlib ] System.Type [ mscorlib ] System.Type : :GetTypeFromHandle ( valuetype [ mscorlib ] System.RuntimeTypeHandle ) IL_0015 : ldstr `` x '' IL_001a : call class [ System.Core ] System.Linq.Expressions.ParameterExpression [ System.Core ] System.Linq.Expressions.Expression : :Parameter ( class [ mscorlib ] System.Type , string ) IL_001f : stloc.1 IL_0020 : ldloc.1 IL_0021 : ldtoken method instance int32 VB_IL_Difference.Customer : :get_CustomerId ( ) IL_0026 : call class [ mscorlib ] System.Reflection.MethodBase [ mscorlib ] System.Reflection.MethodBase : :GetMethodFromHandle ( valuetype [ mscorlib ] System.RuntimeMethodHandle ) IL_002b : castclass [ mscorlib ] System.Reflection.MethodInfo IL_0030 : call class [ System.Core ] System.Linq.Expressions.MemberExpression [ System.Core ] System.Linq.Expressions.Expression : :Property ( class [ System.Core ] System.Linq.Expressions.Expression , class [ mscorlib ] System.Reflection.MethodInfo ) IL_0035 : ldtoken method instance bool [ mscorlib ] System.Int32 : :Equals ( int32 ) IL_003a : call class [ mscorlib ] System.Reflection.MethodBase [ mscorlib ] System.Reflection.MethodBase : :GetMethodFromHandle ( valuetype [ mscorlib ] System.RuntimeMethodHandle ) IL_003f : castclass [ mscorlib ] System.Reflection.MethodInfo IL_0044 : ldc.i4.1 IL_0045 : newarr [ System.Core ] System.Linq.Expressions.Expression IL_004a : stloc.2 IL_004b : ldloc.2 IL_004c : ldc.i4.0 IL_004d : ldc.i4.5 IL_004e : box [ mscorlib ] System.Int32 IL_0053 : ldtoken [ mscorlib ] System.Int32 IL_0058 : call class [ mscorlib ] System.Type [ mscorlib ] System.Type : :GetTypeFromHandle ( valuetype [ mscorlib ] System.RuntimeTypeHandle ) IL_005d : call class [ System.Core ] System.Linq.Expressions.ConstantExpression [ System.Core ] System.Linq.Expressions.Expression : :Constant ( object , class [ mscorlib ] System.Type ) IL_0062 : stelem.ref IL_0063 : nop IL_0064 : ldloc.2 IL_0065 : call class [ System.Core ] System.Linq.Expressions.MethodCallExpression [ System.Core ] System.Linq.Expressions.Expression : :Call ( class [ System.Core ] System.Linq.Expressions.Expression , class [ mscorlib ] System.Reflection.MethodInfo , class [ System.Core ] System.Linq.Expressions.Expression [ ] ) IL_006a : ldc.i4.1 IL_006b : newarr [ System.Core ] System.Linq.Expressions.ParameterExpression IL_0070 : stloc.3 IL_0071 : ldloc.3 IL_0072 : ldc.i4.0 IL_0073 : ldloc.1 IL_0074 : stelem.ref IL_0075 : nop IL_0076 : ldloc.3 IL_0077 : call class [ System.Core ] System.Linq.Expressions.Expression ` 1 < ! ! 0 > [ System.Core ] System.Linq.Expressions.Expression : :Lambda < class [ mscorlib ] System.Func ` 2 < class VB_IL_Difference.Customer , bool > > ( class [ System.Core ] System.Linq.Expressions.Expression , class [ System.Core ] System.Linq.Expressions.ParameterExpression [ ] ) IL_007c : call class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 0 > [ System.Core ] System.Linq.Queryable : :Where < class VB_IL_Difference.Customer > ( class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 0 > , class [ System.Core ] System.Linq.Expressions.Expression ` 1 < class [ mscorlib ] System.Func ` 2 < ! ! 0 , bool > > ) IL_0081 : ldtoken VB_IL_Difference.Customer IL_0086 : call class [ mscorlib ] System.Type [ mscorlib ] System.Type : :GetTypeFromHandle ( valuetype [ mscorlib ] System.RuntimeTypeHandle ) IL_008b : ldstr `` x '' IL_0090 : call class [ System.Core ] System.Linq.Expressions.ParameterExpression [ System.Core ] System.Linq.Expressions.Expression : :Parameter ( class [ mscorlib ] System.Type , string ) IL_0095 : stloc.s VB $ t_ref $ S1 IL_0097 : ldloc.s VB $ t_ref $ S1 IL_0099 : ldc.i4.1 IL_009a : newarr [ System.Core ] System.Linq.Expressions.ParameterExpression IL_009f : stloc.s VB $ t_array $ S2 IL_00a1 : ldloc.s VB $ t_array $ S2 IL_00a3 : ldc.i4.0 IL_00a4 : ldloc.s VB $ t_ref $ S1 IL_00a6 : stelem.ref IL_00a7 : nop IL_00a8 : ldloc.s VB $ t_array $ S2 IL_00aa : call class [ System.Core ] System.Linq.Expressions.Expression ` 1 < ! ! 0 > [ System.Core ] System.Linq.Expressions.Expression : :Lambda < class [ mscorlib ] System.Func ` 2 < class VB_IL_Difference.Customer , class VB_IL_Difference.Customer > > ( class [ System.Core ] System.Linq.Expressions.Expression , class [ System.Core ] System.Linq.Expressions.ParameterExpression [ ] ) IL_00af : call class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 1 > [ System.Core ] System.Linq.Queryable : :Select < class VB_IL_Difference.Customer , class VB_IL_Difference.Customer > ( class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 0 > , class [ System.Core ] System.Linq.Expressions.Expression ` 1 < class [ mscorlib ] System.Func ` 2 < ! ! 0 , ! ! 1 > > ) IL_00b4 : stloc.0 IL_00b5 : ldloc.0 IL_00b6 : call int32 [ System.Core ] System.Linq.Queryable : :Count < class VB_IL_Difference.Customer > ( class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 0 > ) IL_00bb : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_00c0 : nop IL_00c1 : nop IL_00c2 : ret } // end of method Module1 : :CallContext .method private hidebysig static void CallContext ( ) cil managed { // Code size 141 ( 0x8d ) .maxstack 7 .locals init ( [ 0 ] class [ System.Core ] System.Linq.IQueryable ` 1 < class C_IL_Difference.Customer > someCustomer , [ 1 ] class [ System.Core ] System.Linq.Expressions.ParameterExpression CS $ 0 $ 0000 , [ 2 ] class [ System.Core ] System.Linq.Expressions.Expression [ ] CS $ 0 $ 0001 , [ 3 ] class [ System.Core ] System.Linq.Expressions.ParameterExpression [ ] CS $ 0 $ 0002 ) IL_0000 : nop IL_0001 : ldsfld class C_IL_Difference.TravelEntities C_IL_Difference.Program : :ctx IL_0006 : callvirt instance class [ System.Data.Entity ] System.Data.Objects.ObjectSet ` 1 < class C_IL_Difference.Customer > C_IL_Difference.TravelEntities : :get_Customer ( ) IL_000b : ldtoken C_IL_Difference.Customer IL_0010 : call class [ mscorlib ] System.Type [ mscorlib ] System.Type : :GetTypeFromHandle ( valuetype [ mscorlib ] System.RuntimeTypeHandle ) IL_0015 : ldstr `` x '' IL_001a : call class [ System.Core ] System.Linq.Expressions.ParameterExpression [ System.Core ] System.Linq.Expressions.Expression : :Parameter ( class [ mscorlib ] System.Type , string ) IL_001f : stloc.1 IL_0020 : ldloc.1 IL_0021 : ldtoken method instance int32 C_IL_Difference.Customer : :get_CustomerId ( ) IL_0026 : call class [ mscorlib ] System.Reflection.MethodBase [ mscorlib ] System.Reflection.MethodBase : :GetMethodFromHandle ( valuetype [ mscorlib ] System.RuntimeMethodHandle ) IL_002b : castclass [ mscorlib ] System.Reflection.MethodInfo IL_0030 : call class [ System.Core ] System.Linq.Expressions.MemberExpression [ System.Core ] System.Linq.Expressions.Expression : :Property ( class [ System.Core ] System.Linq.Expressions.Expression , class [ mscorlib ] System.Reflection.MethodInfo ) IL_0035 : ldtoken method instance bool [ mscorlib ] System.Int32 : :Equals ( int32 ) IL_003a : call class [ mscorlib ] System.Reflection.MethodBase [ mscorlib ] System.Reflection.MethodBase : :GetMethodFromHandle ( valuetype [ mscorlib ] System.RuntimeMethodHandle ) IL_003f : castclass [ mscorlib ] System.Reflection.MethodInfo IL_0044 : ldc.i4.1 IL_0045 : newarr [ System.Core ] System.Linq.Expressions.Expression IL_004a : stloc.2 IL_004b : ldloc.2 IL_004c : ldc.i4.0 IL_004d : ldc.i4.5 IL_004e : box [ mscorlib ] System.Int32 IL_0053 : ldtoken [ mscorlib ] System.Int32 IL_0058 : call class [ mscorlib ] System.Type [ mscorlib ] System.Type : :GetTypeFromHandle ( valuetype [ mscorlib ] System.RuntimeTypeHandle ) IL_005d : call class [ System.Core ] System.Linq.Expressions.ConstantExpression [ System.Core ] System.Linq.Expressions.Expression : :Constant ( object , class [ mscorlib ] System.Type ) IL_0062 : stelem.ref IL_0063 : ldloc.2 IL_0064 : call class [ System.Core ] System.Linq.Expressions.MethodCallExpression [ System.Core ] System.Linq.Expressions.Expression : :Call ( class [ System.Core ] System.Linq.Expressions.Expression , class [ mscorlib ] System.Reflection.MethodInfo , class [ System.Core ] System.Linq.Expressions.Expression [ ] ) IL_0069 : ldc.i4.1 IL_006a : newarr [ System.Core ] System.Linq.Expressions.ParameterExpression IL_006f : stloc.3 IL_0070 : ldloc.3 IL_0071 : ldc.i4.0 IL_0072 : ldloc.1 IL_0073 : stelem.ref IL_0074 : ldloc.3 IL_0075 : call class [ System.Core ] System.Linq.Expressions.Expression ` 1 < ! ! 0 > [ System.Core ] System.Linq.Expressions.Expression : :Lambda < class [ mscorlib ] System.Func ` 2 < class C_IL_Difference.Customer , bool > > ( class [ System.Core ] System.Linq.Expressions.Expression , class [ System.Core ] System.Linq.Expressions.ParameterExpression [ ] ) IL_007a : call class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 0 > [ System.Core ] System.Linq.Queryable : :Where < class C_IL_Difference.Customer > ( class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 0 > , class [ System.Core ] System.Linq.Expressions.Expression ` 1 < class [ mscorlib ] System.Func ` 2 < ! ! 0 , bool > > ) IL_007f : stloc.0 IL_0080 : ldloc.0 IL_0081 : call int32 [ System.Core ] System.Linq.Queryable : :Count < class C_IL_Difference.Customer > ( class [ System.Core ] System.Linq.IQueryable ` 1 < ! ! 0 > ) IL_0086 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_008b : nop IL_008c : ret } // end of method Program : :CallContext",Generated IL differences for VB.NET and C # C_sharp : If I have a dynamic parameter the compiler seems to ditch the return type and think it 's dynamic.For example : You would think that : Should read as But it thinks that it is : Does adding a dynamic parameter to the signature completely stop the compiler from knowing what the return should be despite the return being strongly typed ? public MethodResult IsValid ( object userLogin ) { return new MethodResult ( ) ; } var isValidResult = IsValid ( someObject ( ) ) ; dynamic - > MethodResult dynamic - > dynamic,Dynamic parameter causes compiler to think method return is dynamic "C_sharp : I have a dataset that contains caller , callee fiels and i need some LINQ query to operate on this dataset equivalent to this sql query SELECT CASE WHEN caller < callee THEN callee ELSE caller END AS caller1 , CASE WHEN caller < callee THEN caller ELSE callee END AS caller2 , Count ( * ) AS [ Count ] FROM YourTable GROUP BY CASE WHEN caller < callee THEN callee ELSE caller END , CASE WHEN caller < callee THEN caller ELSE callee END",Case Query in LINQ equivalent to sql query "C_sharp : I have just tested something that I was sure would fail miserably , but to my surprise , it worked flawlessly , and proves to myself that I am still quite mystified by how async-await works.I created a thread , passing an async void delegate as the thread 's body.Here 's an oversimplification of my code : The thing is that as far as I understand , when the execution hits the await keyword , there is an implicit return from the method , in this case the body of the looping thread , while the rest of the code is wrapped in a callback continuation.Because of this fact , I was pretty sure that the thread would terminate as soon as the await yielded execution , but that 's not the case ! Does anybody know how this magic is actually implemented ? Is the async functionality stripped down and the async waits synchronously or is there some black magic being done by the CLR that enables it to resume a thread that has yielded because of an await ? var thread = new Thread ( async ( ) = > { while ( true ) { await SomeLengthyTask ( ) ; ... } } ) ; thread.Start ( ) ; thread.Join ( ) ;","Async thread body loop , It just works , but how ?" "C_sharp : In terms of object size , how do properties instead Get/Set methods affect object size if the exposed properties do not represent a state but simply delegate its getter and setter calls to another entity ? For example , consider the following classes : I am guessing that when a new Person is created , the CLR will take into consideration the potential size of AddressName property when determining how much memory to allocate . However , if all I exposed was the Get/Set AddressName methods , there will be no additional memory allocated to cater for an AddressName property . So , to conserve memory footprint , it is better in this case to use Get/Set methods . However , this will not make a difference with the Name property of the Address class as state is being preserved . Is this assumption correct ? public class Person { Address _address = new Address ( ) ; public string AddressName { get { return _address.Name ; } set { _address.Name = value ; } } public string GetAddressName ( ) { return _address.Name ; } public void SetAddressName ( string name ) { _address.Name = name ; } } public Address { public string Name { get ; set ; } }",Effect of properties or get/set methods on object size "C_sharp : We 've been running into a lot of deadlocks as part of exposing some of existing code over Web API . I 've been able to distill the problem down to this very simple example that will hang forever : To me , that code seems simple enough . This might seem a bit contrived but that 's only because I 've tried simplifying the problem as much as possible . It seems having two ContinueWiths chained like this will cause the deadlock - if I comment out the first ContinueWith ( that is n't really doing anything anyway ) , it will work just fine . I can also 'fix ' it by not giving the specific scheduler ( but that is n't a workable solution for us since our real code needs to be on the correct/original thread ) . Here , I 've put the two ContinueWiths right next to each other but in our real application there is a lot of logic that is happening and the ContinueWiths end up coming from different methods.I know I could re-write this particular example using async/await and it would simplify things and seems to fix the deadlock . However , we have a ton of legacy code that has been written over the past few years - and most of it was written before async/await came out so it uses ContinueWith 's heavily . Re-writing all that logic is n't something we 'd like to do right now if we can avoid it . Code like this has worked fine in all the other scenarios we 've run into ( Desktop App , Silverlight App , Command Line App , etc . ) - it 's just Web API that is giving us these problems.Is there anything that can be done generically that can solve this kind of deadlock ? I 'm looking for a solution that would hopefully not involve re-writing all ContinueWith 's to use async/await.Update : The code above is the entire code in my controller . I 've tried to make this reproducible with the minimal amount of code . I 've even done this in a brand new solution . The full steps that I did : From Visual Studio 2013 Update 1 on Windows 7 ( with .NET Framework 4.5.1 ) , create a new Project using the ASP.NET Web Application TemplateSelect Web API as the template ( on the next screen ) Replace the Get ( ) method in the auto-created ValuesController with the example given in my original codeHit F5 to start the app and navigate to ./api/values - the request will hang foreverI 've tried hosting the web site in IIS as well ( instead of using IIS Express ) I also tried updating all the various Nuget packages so I was on the latest of everythingThe web.config is untouched from what the template created . Specifically , it has this : public class MyController : ApiController { public Task Get ( ) { var context = TaskScheduler.FromCurrentSynchronizationContext ( ) ; return Task.FromResult ( 1 ) .ContinueWith ( _ = > { } , context ) .ContinueWith ( _ = > Ok ( DateTime.Now.ToLongTimeString ( ) ) , context ) ; } } < system.web > < compilation debug= '' true '' targetFramework= '' 4.5 '' / > < httpRuntime targetFramework= '' 4.5 '' / > < /system.web >",Deadlock with ContinueWiths in WebAPI "C_sharp : I 'm trying to get into the unit testing and TDD way of doing things but I 've come across a problem I 'm not sure what to do with.I have a collection that saves itself to disk using XDocument and XmlWriter . I know you should n't write the file to disk then check it so I had the XmlWriter output to a memory stream then I checked the contents of the memory stream . The function looks like this : And the unit test isThe assert here fails too fragile ( I know I could use String.Compare ( ) but it would have similar issues . ) , Am I testing the right thing ? Am I mocking the wrong thing ? All input greatly appreciated ! public void Save ( ) { using ( XmlWriter xmlWriter = XmlWriter.Create ( m_StreamProvider.SaveFileStream ( m_FilenameProvider.Filename ) ) ) { XDocument xDoc = new XDocument ( new XElement ( `` BookmarkCollection '' , Items.Select ( bookmark = > new XElement ( `` Bookmark '' , new XElement ( `` Name '' , bookmark.Name ) , new XElement ( `` Link '' , bookmark.Link ) , new XElement ( `` Remarks '' , bookmark.Remarks ) , new XElement ( `` DateAdded '' , bookmark.DateAdded ) , new XElement ( `` DateLastAccessed '' , bookmark.DateLastAccessed ) ) ) ) ) ; xDoc.Save ( xmlWriter ) ; } } [ Test ] public void Save_OneItemCollection_XmlCreatedCorrectly ( ) { //Arrange MemoryStreamProvider streamProvider = new MemoryStreamProvider ( ) ; IBookmarkCollection collection = XBookmarkTestHelpers.GetXBookmarkCollection ( streamProvider ) ; IBookmark bookmarkToAdd = XBookmarkTestHelpers.GetIBookmark ( `` myLink '' ) ; collection.Add ( bookmarkToAdd ) ; //Act collection.Save ( ) ; //Assert streamProvider.WriteStrean.Position = 0 ; String generatedXml = Encoding.Default.GetString ( streamProvider.WriteStrean.GetBuffer ( ) ) ; Assert.IsTrue ( String.Equals ( generatedXml , m_ExpectedOneItemString ) , `` XML does not match '' ) ; }",Unit testing a function that outputs via XmlWriter ? "C_sharp : I have used the code from this blog , as below but abridged , and I see the WinForm inside my main window , but the sample text I placed on it in a label is not visible.And : [ System.Windows.Markup.ContentProperty ( `` Child '' ) ] public class WinFormsHost : HwndHost { public WinFormsHost ( ) { var form = new ChildForm ( ) ; Child = form ; } private System.Windows.Forms.Form child ; public event EventHandler < ChildChangedEventArgs > ChildChanged ; public System.Windows.Forms.Form Child { get { return child ; } set { HwndSource ps = PresentationSource.FromVisual ( this ) as HwndSource ; if ( ps ! = null & & ps.Handle ! = IntPtr.Zero ) { throw new InvalidOperationException ( `` Can not set the Child property after the layout is done . `` ) ; } Form oldChild = child ; child = value ; OnChildChanged ( oldChild ) ; } } private void CheckChildValidity ( ) { if ( child == null || child.Handle == IntPtr.Zero ) { throw new ArgumentNullException ( `` child form can not be null '' ) ; } } public Boolean ShowCaption { get { CheckChildValidity ( ) ; return ( GetWindowStyle ( Child.Handle ) & WindowStyles.WS_BORDER ) == WindowStyles.WS_CAPTION ; } set { if ( child == null ) { this.ChildChanged += delegate { if ( value ) { SetWindowStyle ( Child.Handle , GetWindowStyle ( Child.Handle ) | WindowStyles.WS_CAPTION ) ; } else { SetWindowStyle ( Child.Handle , GetWindowStyle ( Child.Handle ) & ~WindowStyles.WS_CAPTION ) ; } } ; } else { if ( value ) { SetWindowStyle ( Child.Handle , GetWindowStyle ( Child.Handle ) | WindowStyles.WS_CAPTION ) ; } else { SetWindowStyle ( Child.Handle , GetWindowStyle ( Child.Handle ) & ~WindowStyles.WS_CAPTION ) ; } } } } protected override HandleRef BuildWindowCore ( HandleRef hwndParent ) { CheckChildValidity ( ) ; HandleRef childHwnd = new HandleRef ( Child , child.Handle ) ; SetWindowStyle ( childHwnd.Handle , WindowStyles.WS_CHILD | GetWindowStyle ( childHwnd.Handle ) ) ; WindowsFormsHost.EnableWindowsFormsInterop ( ) ; System.Windows.Forms.Application.EnableVisualStyles ( ) ; SetParent ( childHwnd.Handle , hwndParent.Handle ) ; return childHwnd ; } } < Window x : Class= '' WinFormsHost '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : wf= '' clr-namespace : System.Windows.Forms ; assembly=System.Windows.Forms '' xmlns : cc= '' clr-namespace : XTime.Shell.WinformsHost '' Title= '' Hosting Form In WPF '' > < cc : WinFormsHost ShowCaption= '' False '' > < wf : Form/ > < /cc : WinFormsHost > < /Window >",Why is my WPF hosted WinForm blank ? "C_sharp : I would like to iterate through the System.Drawing.Color struct and use it to init a pen list.I tried it like this , but the type of field is not Fitting : Please help me out . colorList = new List < System.Drawing.Pen > ( ) ; foreach ( var field in typeof ( System.Drawing.Color ) .GetFields ( ) ) { if ( field.FieldType.Name == `` Color '' & & field.Name ! = null ) { colorList.Add ( new System.Drawing.Pen ( field , ( float ) 1 ) ) ; } }",Iterate through System.Drawing.Color struct and use it to create System.Drawing.Pen "C_sharp : In Haskell , there 's two ways of providing an alias for types : type and newtype . type provides a type synonym , which means the synonym is regarded by the type checker as exactly the same as the original type : A newtype is similar , but is regarded by the type checker as a different type : In C # , you can define type synonyms with a top-level using declaration : However , a strongly-typed , compiler-checked type alias does not seem to be present in C # by default . I 've looked into automatic code generation with T4 templates and CodeDOM to generate a class wrapper , but I do n't really know how I could cleanly integrate those into my programming flow.Ideally , I would like to be able to say on a top-level : This kicks the code generation into gear at compile-time . If that 's not possible or provides a chicken-and-egg issue for IntelliSense , an automatic compilation option that runs every x minutes ( or a button or whatever ) would be nice . type UserId = InthasAccess : : UserId - > BoolhasAccess id = { -- stuff -- } -- Elsewhere in the programlogin : : Int - > Boollogin n = hasAccess n -- Typechecker wo n't complain newtype UserId = UserId InthasAccess : : UserId - > BoolhasAccess ( UserId id ) = { -- stuff -- } -- Elsewhere in the programlogin : : Int - > Boollogin n = hasAccess n -- Typechecker will complain , n is n't a UserId ! using UserId = Int ; // Something like this ? using Int.UserId ; /* Elsewhere */var id = new UserId ( 5 ) ; public bool HasAccess ( UserId id ) { /* Stuff */ }",What is C # 's equivalent to Haskell 's newtype ? "C_sharp : When you turn on the `` Break when an exception is thrown '' feature in the Visual Studio debugger it breaks everywhere for selected exception types . The way to tell it not to break in a specific method is to decorate these methods with DebuggerStepThrough attribute ( or DebuggerHidden ) .This , evidently , does n't work for an async method for some reason.Here 's a snippet that reproduces the issue . The debugger will break inside the TestAsync even though it 's marked with the attributes and it will not break inside Test as excepted ( the only difference between them is the first is marked with the async keyword ) : So , is this behavior intended ? Is it a bug ? Is there a workaround ? public class Attributes { public async Task Run ( ) { await TestAsync ( ) ; await Test ( ) ; } [ DebuggerHidden ] [ DebuggerStepThrough ] public async Task TestAsync ( ) { try { throw new Exception ( `` Async '' ) ; } catch { } await Task.Delay ( 100 ) ; } [ DebuggerHidden ] [ DebuggerStepThrough ] public Task Test ( ) { try { throw new Exception ( `` sync '' ) ; } catch { } return Task.Delay ( 100 ) ; } }","DebuggerStepThrough , DebuggerHidden do n't work in an async-await method" C_sharp : I tried doing something like this : It gives error . Why I ca n't implement two interfaces ? class Student : IPersonalDetails : IOtherDetails { //Code },Can a class implement two interfaces at the same time ? "C_sharp : SetInstrumentInfo and GetInstrumentInfo are called from different threads.InstrumentInfo is immutable class.Am I guaranteed to have the most recent copy when calling GetInstrumentInfo ? I 'm afraid that I can receive `` cached '' copy . Should I add kind of synchronization ? Declaring instrumentInfos as volatile would n't help because I need declare array items as volatile , not array itself.Do my code has problem and if so how to fix it ? UPD1 : I need my code to work in real life not to correspond to all specifications ! So if my code works in real life but will not work `` theoretically '' on some computer under some environment - that 's ok ! I need my code to work on modern X64 server ( currently 2 processors HP DL360p Gen8 ) under Windows using latest .NET Framework.I do n't need to work my code under strange computers or Mono or anything elseI do n't want to introduce latency as this is HFT software . So as `` Microsoft 's implementation uses a strong memory model for writes . That means writes are treated as if they were volatile '' I likely do n't need to add extra Thread.MemoryBarrier which will do nothing but add latency . I think we can rely that Microsoft will keep using `` strong memory model '' in future releases . At least it 's very unlikely that Microsoft will change memory model . So let 's assume it will not.UPD2 : The most recent suggestion was to use Thread.MemoryBarrier ( ) ; . Now I do n't understand exact places where I must insert it to make my program works on standard configuration ( x64 , Windows , Microsoft .NET 4.0 ) . Remember I do n't want to insert lines `` just to make it possible to launch your program on IA64 or .NET 10.0 '' . Speed is more important for me than portability . However it would be also interesting how to update my code so it will work on any computer.UPD3.NET 4.5 solution : private InstrumentInfo [ ] instrumentInfos = new InstrumentInfo [ Constants.MAX_INSTRUMENTS_NUMBER_IN_SYSTEM ] ; public void SetInstrumentInfo ( Instrument instrument , InstrumentInfo info ) { if ( instrument == null || info == null ) { return ; } instrumentInfos [ instrument.Id ] = info ; // need to make it visible to other threads ! } public InstrumentInfo GetInstrumentInfo ( Instrument instrument ) { return instrumentInfos [ instrument.Id ] ; // need to obtain fresh value ! } public void SetInstrumentInfo ( Instrument instrument , InstrumentInfo info ) { if ( instrument == null || info == null ) { return ; } Volatile.Write ( ref instrumentInfos [ instrument.Id ] , info ) ; } public InstrumentInfo GetInstrumentInfo ( Instrument instrument ) { InstrumentInfo result = Volatile.Read ( ref instrumentInfos [ instrument.Id ] ) ; return result ; }",How to guarantee that an update to `` reference type '' item in Array is visible to other threads ? "C_sharp : .Net4 C # VSTO4 Excel Add-In : The following function is called very often , let 's say every second : After a while , I am getting the following exception : Calling code is : I have no idea why I am getting an exception ! Can it maybe help to take a `` using '' in GetWorksheetUniqueIdentifier ? Does anyone have an answer ? /// < summary > /// Gets a unique identifier string of for the worksheet in the format [ WorkbookName ] WorksheetName /// < /summary > /// < param name= '' workbook '' > The workbook. < /param > /// < param name= '' worksheet '' > The worksheet. < /param > /// < returns > /// A unique worksheet identifier string , or an empty string . /// < /returns > public static string GetWorksheetUniqueIdentifier ( Workbook workbook , dynamic worksheet ) { if ( workbook == null ) return string.Empty ; if ( worksheet == null ) return string.Empty ; //Note : Worksheet can also be a diagram ! return string.Format ( `` [ { 0 } ] { 1 } '' , workbook.Name , worksheet.Name ) ; } System.OutOfMemoryException at System.Collections.Generic.Dictionary ` 2.Resize ( ) at System.Collections.Generic.Dictionary ` 2.Insert ( TKey key , TValue value , Boolean add ) at Microsoft.CSharp.RuntimeBinder.Semantics.SYMTBL.InsertChildNoGrow ( Symbol child ) at Microsoft.CSharp.RuntimeBinder.Semantics.SymFactoryBase.newBasicSym ( SYMKIND kind , Name name , ParentSymbol parent ) at Microsoft.CSharp.RuntimeBinder.Semantics.SymFactory.CreateLocalVar ( Name name , ParentSymbol parent , CType type ) at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.PopulateLocalScope ( DynamicMetaObjectBinder payload , Scope pScope , ArgumentObject [ ] arguments , IEnumerable ` 1 parameterExpressions , Dictionary ` 2 dictionary ) at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.BindCore ( DynamicMetaObjectBinder payload , IEnumerable ` 1 parameters , DynamicMetaObject [ ] args , DynamicMetaObject & deferredBinding ) at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind ( DynamicMetaObjectBinder payload , IEnumerable ` 1 parameters , DynamicMetaObject [ ] args , DynamicMetaObject & deferredBinding ) at Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind ( DynamicMetaObjectBinder action , RuntimeBinder binder , IEnumerable ` 1 args , IEnumerable ` 1 arginfos , DynamicMetaObject onBindingError ) at Microsoft.CSharp.RuntimeBinder.CSharpInvokeMemberBinder.FallbackInvokeMember ( DynamicMetaObject target , DynamicMetaObject [ ] args , DynamicMetaObject errorSuggestion ) at System.Dynamic.DynamicMetaObject.BindInvokeMember ( InvokeMemberBinder binder , DynamicMetaObject [ ] args ) at System.Dynamic.InvokeMemberBinder.Bind ( DynamicMetaObject target , DynamicMetaObject [ ] args ) at System.Dynamic.DynamicMetaObjectBinder.Bind ( Object [ ] args , ReadOnlyCollection ` 1 parameters , LabelTarget returnLabel ) at System.Runtime.CompilerServices.CallSiteBinder.BindCore [ T ] ( CallSite ` 1 site , Object [ ] args ) at System.Dynamic.UpdateDelegates.UpdateAndExecute3 [ T0 , T1 , T2 , TRet ] ( CallSite site , T0 arg0 , T1 arg1 , T2 arg2 ) at CallSite.Target ( Closure , CallSite , Object , Object ) at TestAddIn.ExcelAccessor.GetWorksheetUniqueIdentifier ( Workbook workbook , Object worksheet ) at TestAddIn.ExcelAccessor.GetCurrentWorksheetUniqueIdentifier ( ) at TestAddIn.ExcelAccessor.timerExcelObserver_Tick ( Object sender , EventArgs e ) -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- private static Timer timerExcelObserver = new Timer ( ) ; ... timerExcelObserver.Tick += new EventHandler ( this.timerExcelObserver_Tick ) ; timerExcelObserver.Interval = 1000 ; timerExcelObserver.Start ( ) ; ... private void timerExcelObserver_Tick ( object sender , EventArgs e ) { ... var updatedWorksheetIdentifierString = GetCurrentWorksheetUniqueIdentifier ( ) ; ... } public static string GetCurrentWorksheetUniqueIdentifier ( ) { return GetWorksheetUniqueIdentifier ( ExcelApplication.ActiveWorkbook , ExcelApplication.ActiveSheet ) ; } using ( worksheet ) { return string.Format ( `` [ { 0 } ] { 1 } '' , workbook.Name , worksheet.Name ) ; }",Worksheet.Name causes OutOfMemoryException "C_sharp : I have spent an extensive number of weeks doing multithreaded coding in C # 4.0 . However , there is one question that remains unanswered for me.I understand that the volatile keyword prevents the compiler from storing variables in registers , thus avoiding inadvertently reading stale values . Writes are always volatile in .Net , so any documentation stating that it also avoids stales writes is redundant.I also know that the compiler optimization is somewhat `` unpredictable '' . The following code will illustrate a stall due to a compiler optimization ( when running the release compile outside of VS ) : The code behaves as expected . However , if I uncomment out the //Thread.Yield ( ) ; line , then the loop will exit.Further , if I put a Sleep statement before the do loop , it will exit . I do n't get it.Naturally , decorating _loop with volatile will also cause the loop to exit ( in its shown pattern ) .My question is : What are the rules the complier follows in order to determine when to implicity perform a volatile read ? And why can I still get the loop to exit with what I consider to be odd measures ? EDITIL for code as shown ( stalls ) : IL with Yield ( ) ( does not stall ) : class Test { public struct Data { public int _loop ; } public static Data data ; public static void Main ( ) { data._loop = 1 ; Test test1 = new Test ( ) ; new Thread ( ( ) = > { data._loop = 0 ; } ) .Start ( ) ; do { if ( data._loop ! = 1 ) { break ; } //Thread.Yield ( ) ; } while ( true ) ; // will never terminate } } L_0038 : ldsflda valuetype ConsoleApplication1.Test/Data ConsoleApplication1.Test : :dataL_003d : ldfld int32 ConsoleApplication1.Test/Data : :_loopL_0042 : ldc.i4.1 L_0043 : beq.s L_0038L_0045 : ret L_0038 : ldsflda valuetype ConsoleApplication1.Test/Data ConsoleApplication1.Test : :dataL_003d : ldfld int32 ConsoleApplication1.Test/Data : :_loopL_0042 : ldc.i4.1 L_0043 : beq.s L_0046L_0045 : ret L_0046 : call bool [ mscorlib ] System.Threading.Thread : :Yield ( ) L_004b : pop L_004c : br.s L_0038",When to use volatile to counteract compiler optimizations in C # "C_sharp : Let 's say I want to get extra type-checking for working with primitives that mean different things semantically : The point is we ca n't compare `` apples to oranges '' , so wrapping up the actual int in a struct means we get type checking and some extra readability and documentation by code.My question is : what is the overhead associated with doing this , both in terms of memory and speed ? Since structs are value types , would variables containing these structs be 32 bits or larger ? What about performance overhead of using these structs instead of primitives - is there a large overhead for the operator overloads ? Any other advice on the wisdom of doing this ? public struct Apple { readonly int value ; // Add constructor + operator overloads } public struct Orange { readonly int value ; // Add constructor + operator overloads }",Overhead of using structs as wrappers for primitives for type-checking ? "C_sharp : I have a very specific requirement . In my web app , I have to generate a pdf invoice from the database values , and an email body . I can easily send this using SMTP which works perfect . But , problem is we ca n't rely on system to always be perfect , and this is an invoice . So , we need to open the default mail client instead of using SMTP . Right now , I have following codeThis opens the email perfectly , but no attachment is working . Path is supposed to be /Web/Temp/123.pdf . If I use the same path as normal url like below , it opens the file in new window properly.So , clearly file exists , but it exists on the server . Outlook on the other hand open on client machine . So , I ca n't use the full determined path like C : \Web\Temp\123.pdf . If I try that , it will try to find the file on client machine , where the folder itself might not exist . I am trying to figure out what can I do here . If there is another method I should try . P.S . No , I ca n't send the email directly . That will cause a hell lot more problem in future for me.Edit : I also found one weird problem . If I add a double quote to the file path in attachment , a \ is added automatically . @ '' & attachment= '' '' '' + Server.MapPath ( emailAttachment ) + @ '' '' '' ' ) ; '' gives me output as & attachment=\ '' C : \Web\Temp\123.pdf\ '' .I am trying to escape that double quote and somehow it adds that slash . I know this is a completely different problem , but thought I should mention here , instead of creating a new question.Edit : I tried a fixed path on localhost . So , I am basically testing the app on the same machine where file is getting stored . still , no attachment at all . Updated the path to make sure it is proper . Now , it just throws error saying command line argument not valid.Edit : Is there any other method I can try ? I have the file path on the server side . Maybe I can download the file automatically to some default folder on client machine and open from there ? Is that possible ? Edit : I tried one more option.The Process.Start line works but it does nothing at all . There is no process that starts , no error either . Edit : yay . I finally got the user to approve using a separate form to display the subject and body , instead of opening the default mail client . although , I would still prefer to solve this problem as is . //Code to create the script for emailstring emailJS = `` '' ; emailJS += `` window.open ( 'mailto : testmail @ gmail.com ? body=Test Mail '' + `` & attachment= '' + emailAttachment + `` ' ) ; '' ; //Register the script for post backClientScript.RegisterStartupScript ( this.GetType ( ) , `` mailTo '' , emailJS , true ) ; ClientScript.RegisterStartupScript ( this.GetType ( ) , `` newWindow '' , `` window.open ( '/Web/Temp/123.pdf ' ) ; '' , true ) ; string emailJS = `` '' ; emailJS += @ '' window.open ( 'mailto : jitendragarg @ gmail.com ? body=Test Mail '' + emailAttachment + @ '' & attachment= '' ; emailJS += @ '' '' '' D : \Dev\CSMS\CSMSWeb\Temp\635966781817446275.Pdf '' '' ' ) ; '' ; //emailJS += Server.MapPath ( emailAttachment ) + @ '' ' ) ; '' ; //Register the script for post backClientScript.RegisterStartupScript ( this.GetType ( ) , `` mailTo '' , emailJS , true ) ; emailJS += @ '' mailto : testmail @ gmail.com ? body=Test Mail '' + @ '' & attachment= '' ; emailJS += @ '' \\localhost\CSMSWeb\Temp\635966781817446275.Pdf '' ; //emailJS += Server.MapPath ( emailAttachment ) + @ '' ' ) ; '' ; Process.Start ( emailJS ) ;",Attaching auto generated pdf to email in asp.net app "C_sharp : If I have a string like `` 123‍‍‍ '' , how can I split it into an array , which would look like [ `` '' , `` 1 '' , `` 2 '' , `` 3 '' , `` ‍‍‍ '' ] ? If I use ToCharArray ( ) the first Emoji is split into 2 characters and the second into 7 characters.UpdateThe solution now looks like this : Please note that , as mentioned in the comments , it does n't work for the family emoji . It only works for emojis that have 2 characters or less . The output of the example would be : [ `` '' , `` 1 '' , `` 2 '' , `` 3 '' , `` ‍ '' , `` ‍ '' , `` ‍ '' , `` '' ] public static List < string > GetCharacters ( string text ) { char [ ] ca = text.ToCharArray ( ) ; List < string > characters = new List < string > ( ) ; for ( int i = 0 ; i < ca.Length ; i++ ) { char c = ca [ i ] ; if ( c > ‭65535‬ ) continue ; if ( char.IsHighSurrogate ( c ) ) { i++ ; characters.Add ( new string ( new [ ] { c , ca [ i ] } ) ) ; } else characters.Add ( new string ( new [ ] { c } ) ) ; } return characters ; }",How can I split a Unicode string into multiple Unicode characters in C # ? "C_sharp : When I write this : Visual studio suggests that the null check can be simplified.and simplifies it toAre those really the same ? ReferenceEquals ( x , null ) x is null","Is there a difference between x is null and ReferenceEquals ( x , null ) ?" "C_sharp : Why ca n't I change these settings shown in the image below ? This is a clickOnce application , and my problem is that I want to change by publish path , assembly name , product name , install URL , and preform some app.config translations based on the build configuration . I am able to achieve this by manually editing the csproj like soI 'm just confused why these options are disabled in visual studio and if I 'm missing something . Perhaps I 'm confused and these controls were n't even intended for this purpose.Also , I 'm going to be investigating Squirrel.Windows as an alternative later , but for now I wanted to learn more about this . < PropertyGroup Condition= '' ' $ ( Configuration ) ' == 'Debug ' `` > < AssemblyName > someApplicationTest < /AssemblyName > < ProductName > Some Application Test < /ProductName > < PublishUrl > c : \publish\someApplicationTest\ < /PublishUrl > < InstallUrl > http : //sub.example.com/someApplicationTest/ < /InstallUrl > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) ' == 'Release ' `` > < AssemblyName > someApplication < /AssemblyName > < ProductName > Some Application < /ProductName > < PublishUrl > c : \publish\someApplication\ < /PublishUrl > < InstallUrl > http : //sub.example.com/someApplication/ < /InstallUrl > < /PropertyGroup >",Publish Configuration disabled for csproj "C_sharp : I am a bit confused as to how I am supposed to implement functions like the following : In the ASP.NET Core CustomIdentityProvider Sample and the Actual ASP.NET Core Identity UserStoreBase class they do the following : Are these functions about just simply extracting the Normalized Name from an already populated User object and additionally updating the Normalized Name on an already populated User object . I am not seeing the purpose of these functions can someone explain ? Also do I need to actually persist the NormalizedUserName and NormalizedRoleName in my custom User/Role tables or are they not required ? GetNormalizedRoleNameAsync ( TRole , CancellationToken ) SetNormalizedRoleNameAsync ( TRole , String , CancellationToken ) GetNormalizedUserNameAsync ( TUser , CancellationToken ) SetNormalizedUserNameAsync ( TUser , String , CancellationToken ) GetUserNameAsync ( TUser , CancellationToken ) SetUserNameAsync ( TUser , String , CancellationToken ) public Task SetNormalizedUserNameAsync ( ApplicationUser user , string normalizedName , CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested ( ) ; if ( user == null ) throw new ArgumentNullException ( nameof ( user ) ) ; if ( normalizedName == null ) throw new ArgumentNullException ( nameof ( normalizedName ) ) ; user.NormalizedUserName = normalizedName ; return Task.FromResult < object > ( null ) ; } public Task < string > GetUserNameAsync ( ApplicationUser user , CancellationToken cancellationToken ) { cancellationToken.ThrowIfCancellationRequested ( ) ; if ( user == null ) throw new ArgumentNullException ( nameof ( user ) ) ; return Task.FromResult ( user.UserName ) ; }",Explanation of GetNormalizedUserNameAsync and SetNormalizedUserNameAsync functions in ASP.NET Identity UserStore "C_sharp : I tried many different modifications but nothing helps . When I dig into sources it 's a bunch of deep magic involving static state like ConditionalWeakTable etc . private readonly ReactiveList < Item > _list = new ReactiveList < Item > ( ) ; private decimal _sum ; public decimal Sum { get { return _sum ; } set { this.RaiseAndSetIfChanged ( ref _sum , value ) ; } } _list .Changed .Select ( _ = > _list.Select ( i = > i.Value ) .Sum ( ) ) .ToProperty ( this , x = > x.Sum )",ReactiveUI - why is simple ReactiveList.Changed - > ToProperty not working ? "C_sharp : Consider the following snippet of code : And the surprising output is : I would expect it to select the overridden Foo ( int x ) method , since it 's more specific . However , C # compiler picks the non-inherited Foo ( object o ) version . This also causes a boxing operation.What is the reason for this behaviour ? using System ; class Base { public virtual void Foo ( int x ) { Console.WriteLine ( `` Base.Foo ( int ) '' ) ; } } class Derived : Base { public override void Foo ( int x ) { Console.WriteLine ( `` Derived.Foo ( int ) '' ) ; } public void Foo ( object o ) { Console.WriteLine ( `` Derived.Foo ( object ) '' ) ; } } public class Program { public static void Main ( ) { Derived d = new Derived ( ) ; int i = 10 ; d.Foo ( i ) ; } } Derived.Foo ( object )",C # method override resolution weirdness "C_sharp : We are using an external API that returns its results using the object name `` Data '' . This `` Data '' can represent two different objects -one in the form of an json object array and another int the form of a single json object.I have a created two separate c # classes that represents the JSON object data and a c # root object class to capture the JSON objects when being converted using JsonConvert.DeserializeObject ... How would one go about representing these objects correctly in C # see below examples of results : below is example of 1 resulting API CallBelow is example 2 of resulting API callHow would I construct the ApiResponse Class to cater for the Generic `` Data '' object json string returned - so that I can use the generic `` JsonConvert.DeserializeObject ( await response.Content.ReadAsStringAsync ( ) , Settings ) ; '' { success : true , Data : [ { id:1 , name : '' Paul '' } , { id:2 , name : '' neville '' } , { id:3 , name : '' jason '' } ] } public class User { public int id { get ; set ; } public string name { get ; set ; } } public class ApiResponse { public bool success { get ; set ; } public List < User > Data { get ; set ; } } { success : true , Data : { id:1 , classSize:30 , minAge:25 , maxAge:65 } } public class AgeClass { public int id { get ; set ; } public int classSize { get ; set ; } public int minAge { get ; set ; } public int maxAge { get ; set ; } } public class ApiResponse { public bool success { get ; set ; } public AgeClass Data { get ; set ; } }",c # Generic data object using newtonsofts JsonConvert DeserializeObject "C_sharp : I have simple program like this : I decided to see the CIL code of such program ( I am interested in Foo 's constructor ) . Here is it : I wondered , when I saw the second line , ldarg.0 , what does it mean ? this pointer ? But the object was not created yet . How can I modify its members ? My assumption is that before calling constructor , clr first allocates memory for the object . Then initializes members to default values , and then invokes the constructor . Another interesting moment that the object calling is last . I thought that it would be first . public class Foo { public Foo ( ) { } public int MyInt { get ; set ; } = 10 ; public List < int > MyList { get ; set ; } = new List < int > ( ) ; } public class Program { static public void Main ( ) { Console.WriteLine ( new Foo ( ) .MyInt ) ; Console.ReadLine ( ) ; } } .method public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed { // Code size 26 ( 0x1a ) .maxstack 8 IL_0000 : ldarg.0 IL_0001 : ldc.i4.s 10 IL_0003 : stfld int32 Foo : : ' < MyInt > k__BackingField ' IL_0008 : ldarg.0 IL_0009 : newobj instance void class [ mscorlib ] System.Collections.Generic.List ` 1 < int32 > : :.ctor ( ) IL_000e : stfld class [ mscorlib ] System.Collections.Generic.List ` 1 < int32 > Foo : : ' < MyList > k__BackingField ' IL_0013 : ldarg.0 IL_0014 : call instance void [ mscorlib ] System.Object : :.ctor ( ) IL_0019 : ret } // end of method Foo : :.ctor",What is the first argument in a parameterless constructor ? "C_sharp : I have a page in a Windows Phone 8.1 app where I have a few components that should be able to have three different color states . They should either be red , blue or the current theme 's foreground color.Therefore , if my app is started using the Dark theme on the phone , and then the user steps out of the app and changes the Light theme , and steps in to my app again , I need to immediately change components that had the old theme 's foreground color.Since the components are supposed to change between different colors ( where the theme 's foreground color is just one of them ) I ca n't set their Foreground to PhoneForegroundColor in XAML.What I 've done is to add a Resuming event listener that does this : But ... the Resuming event is fired before the resources of Application.Current are updated , so I end up with the same color as before . If the user steps out again and in again , it 'll work since Application.Current.Resources [ `` PhoneForegroundColor '' ] was updated at some point after the Resuming event the previous time.Question : When can I first read the updated Application.Current.Resources [ `` PhoneForegroundColor '' ] , since Resuming does n't seem to be the right place ? Question : Alternatively , is there a way for myTextBlock to inherit another component 's ForegroundColor ( CSS-ish ) , so that I can change the myTextBlock.Foreground programatically between Red/Blue/Inherit without having to mind changes to the Phone Theme within my app 's lifecycle ? Any suggestions appreciated ! myTextBlock.Foreground = new SolidColorBrush ( ( Color ) Application.Current.Resources [ `` PhoneForegroundColor '' ] ) ;",When to programmatically check for theme changes in Windows Phone 8.1 "C_sharp : I have created the following C # program : When I run this using dotnet run , I see the following behavior : Windows : Exception text written to console , `` Disposed '' printed ~20 second later , program exits.Linux : Exception text written to console , program exits immediately . `` Disposed '' never written.The delay on Windows is annoying , but the fact that Dispose ( ) is n't called at all on Linux is troubling . Is this expected behavior ? EDITS Clarifications/additions from the conversation below : This is not specific to using/Dispose ( ) , which is just a special case of try/finally . The behavior also occurs generally with try/finally - the finally block is not run . I have updated the title to reflect this.I have also checked for the execution of Dispose ( ) by writing a file to the filesystem , just to ensure that problem was n't related to stdout being disconnected from the console before Dispose ( ) is run in the case of an unhandled exception . Behavior was the same.Dispose ( ) does get called if the exception is caught anywhere within the application . It 's when it goes completely unhandled by the application that this behavior occurs.On Windows , the long gap is not due to compilation delay . I started timing when the exception text was written to the console.My original experiment was doing dotnet run on both platforms , which means separate compilations , but I have also tried by doing dotnet publish on Windows and directly running the output on both platforms , with the same result . The only difference is that , when run directly on Linux , the text `` Aborted ( core dumped ) '' is written after the exception text.Version details : dotnet -- version - > 1.0.4.Compiling to netcoreapp1.1 , running on .NET Core 1.1.lsb-release -d - > Ubuntu 16.04.1 LTS namespace dispose_test { class Program { static void Main ( string [ ] args ) { using ( var disp = new MyDisposable ( ) ) { throw new Exception ( `` Boom '' ) ; } } } public class MyDisposable : IDisposable { public void Dispose ( ) { Console.WriteLine ( `` Disposed '' ) ; } } }",.NET Core : Finally block not called on unhandled exception on Linux "C_sharp : I have a rolling file appender configured with this : This works fine , but I was wondering if there was a way to move the old log files into an `` archive '' folder , instead of having them moved to the same folder ? < appender name= '' RollingLogFileAppender '' type= '' log4net.Appender.RollingFileAppender '' > < file value= '' appname '' / > < appendToFile value= '' true '' / > < rollingStyle value= '' Composite '' / > < datePattern value= '' ' . 'yyyyMMdd'.log ' '' / > < maxSizeRollBackups value= '' 30 '' / > < maximumFileSize value= '' 10MB '' / > < staticLogFileName value= '' false '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % date [ % thread ] % -5level % logger - % message % newline '' / > < /layout > < /appender >","Is there a way to move old log files , from a log4net RollingLogFileAppender into a different folder ?" "C_sharp : What 's the difference between the two ? EDIT : If there are no difference , which is the better choice ? Thanks ! object.ProgressChanged += new EventHandler < ProgressChangedEventArgs > ( object_ProgressChanged ) object.ProgressChanged += object_ProgressChanged ; void installableObject_InstallProgressChanged ( object sender , ProgressChangedEventArgs e ) { EventHandler < ProgressChangedEventArgs > progress = ProgressChanged ; if ( installing ! = null ) installing ( this , e ) ; }",Difference between wiring events using `` new EventHandler < T > '' and not using new EventHandler < T > '' ? "C_sharp : I have a list of elements which can be easily compared using Equals ( ) . I have to shuffle the list , but the shuffle must satisfy one condition : The i'th element shuffledList [ i ] must not equal elements at i +/- 1 nor elements at i +/- 2 . The list should be considered circular ; that is , the last element in the list is followed by the first , and vice versa.Also , if possible , I would like to check if the shuffle is even possible.Note : I 'm using c # 4.0.EDIT : Based on some responses , I will explain a little more : The list wont have more than 200 elements , so there is n't a real need for good performance . If it takes 2 secs to calculate it it 's not the best thing , but it 's not the end of the world either . The shuffled list will be saved , and unless the real list changes , the shuffled list will be used.Yes , it 's a `` controlled '' randomness , but I expect that severals run on this method would return different shuffled lists.I will make further edits after I try some of the responses below.EDIT 2 : Two sample list that fails with Sehe 's implementation ( Both have solutions ) : Sample1 : Possible solution : List < int > shuffledList1 = new List < int > { 9,3,1,4,7,9,2,6,8,1,4,9,2,0,6,5,7,8,4,3,10,9,6,7,8,5,3,9,1,2,7,8 } Sample 2 : Verify : I 'm using this method , that it 's not the most eficient nor elegant piece of code I 've made , but it does it 's work : EDIT 3 : Another test input that fails sometimes : ` List < int > list1 = new List < int > { 0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,9,10 } ; ` ` List < int > list2 = new List < int > { 0,1,1,2,2,2,3,3,4,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,8,8,9,9,9,9,10 } ; ` public bool TestShuffle < T > ( IEnumerable < T > input ) { bool satisfied = true ; int prev1 = 0 ; int prev2 = 0 ; int next1 = 0 ; int next2 = 0 ; int i = 0 ; while ( i < input.Count ( ) & & satisfied ) { prev1 = i - 1 ; prev2 = i - 2 ; next1 = i + 1 ; next2 = i + 2 ; if ( i == 0 ) { prev1 = input.Count ( ) - 1 ; prev2 = prev1 - 1 ; } else if ( i == 1 ) prev2 = input.Count ( ) - 1 ; if ( i == ( input.Count ( ) - 1 ) ) { next1 = 0 ; next2 = 1 ; } if ( i == ( input.Count ( ) - 2 ) ) next2 = 0 ; satisfied = ( ! input.ElementAt ( i ) .Equals ( input.ElementAt ( prev1 ) ) ) & & ( ! input.ElementAt ( i ) .Equals ( input.ElementAt ( prev2 ) ) ) & & ( ! input.ElementAt ( i ) .Equals ( input.ElementAt ( next1 ) ) ) & & ( ! input.ElementAt ( i ) .Equals ( input.ElementAt ( next2 ) ) ) ; if ( satisfied == false ) Console.WriteLine ( `` TestShuffle fails at `` + i ) ; i++ ; } return satisfied ; } List < int > list3 = new List < int > ( ) { 0,1,1,2,2,3,3,3,4,4,4,5,5,5,5,6,6,6,6,7,7,7,8,8,8,8,9,9,9,9,10,10 } ;",Shuffle list with some conditions "C_sharp : I 've often heard that in the .NET 2.0 memory model , writes always use release fences . Is this true ? Does this mean that even without explicit memory-barriers or locks , it is impossible to observe a partially-constructed object ( considering reference-types only ) on a thread different from the one on which it is created ? I 'm obviously excluding cases where the constructor leaks the this reference . For example , let 's say we had the immutable reference type : Would it be possible with the following code to observe any output other than `` John 20 '' and `` Jack 21 '' , say `` null 20 '' or `` Jack 0 '' ? Does this also mean that I can make all shared fields of deeply-immutable reference-types volatile and ( in most cases ) just get on with my work ? public class Person { public string Name { get ; private set ; } public int Age { get ; private set ; } public Person ( string name , int age ) { Name = name ; Age = age ; } } // We could make this volatile to freshen the read , but I do n't want// to complicate the core of the question.private Person person ; private void Thread1 ( ) { while ( true ) { var personCopy = person ; if ( personCopy ! = null ) Console.WriteLine ( personCopy.Name + `` `` + personCopy.Age ) ; } } private void Thread2 ( ) { var random = new Random ( ) ; while ( true ) { person = random.Next ( 2 ) == 0 ? new Person ( `` John '' , 20 ) : new Person ( `` Jack '' , 21 ) ; } }",Is it possible to observe a partially-constructed object from another thread ? "C_sharp : The C # code formatting in Xamarin Studio ( i.e . when hitting Ctrl-I to format the document ) puts end of line comments onto a new line . I ca n't find any way to change this in the C # code formatting policy settings . How to change this to preserve end of line comments on the same line ? For example , take this code : If I hit Ctrl-I ( or alternately click Edit > Format > Format Document from the menu , or select the code and click Edit > Format > Format Selection from the menu ) , the code is reformatted as : I 'm using v4.2.2 build 2 v4.3 build 52 on OS X.Note : it seems this is a bug . So my question really is -- has anyone who has also encountered this come up with a fix or workaround and if so what is it ? public class Foo { int bar ; // comment } public class Foo { int bar ; // comment }",How to set code formatting to allow end-of-line comments ? "C_sharp : I am trying to do a request-response communication module in c # , using a SerialPort . The This is a very simple implementation , just to demonstrate that it kinda-works ( SerialPort is not working properly ( it is a USB virtual COM port ) , and sometimes eats a few characters , probably some windows driver bug ) .However the demo does not work : -/When Using a propertygrid on the form , which reads out properties of an object , which in turn sends a request to read a property from the remote device , something very strange happens : More than one simulteneous call to SendCommand is made at once.I tried using a lock { } block to make the calls sequenctial , but it does not work . Even with the lock , more than one call is enters the protected area.Can you please tell me what am I doing wrong ? My code : The output : Notice the two ENTER-s , without an EXIT between them ? How is that possible ? SerialPort sp ; public byte [ ] SendCommand ( byte [ ] command ) { //System.Threading.Thread.Sleep ( 100 ) ; lock ( sp ) { Console.Out.WriteLine ( `` ENTER '' ) ; try { string base64 = Convert.ToBase64String ( command ) ; string request = String.Format ( `` { 0 } { 1 } \r '' , target_UID , base64 ) ; Console.Out.Write ( `` Sending request ... { 0 } '' , request ) ; sp.Write ( request ) ; string response ; do { response = sp.ReadLine ( ) ; } while ( response.Contains ( `` QQ== '' ) ) ; Console.Out.Write ( `` Response is : { 0 } '' , response ) ; return Convert.FromBase64String ( response.Substring ( target_UID.Length ) ) ; } catch ( Exception e ) { Console.WriteLine ( `` ERROR ! `` ) ; throw e ; } finally { Console.Out.WriteLine ( `` EXIT '' ) ; } } } ENTERSending request ... C02UgAABAA=Response is : cgAABAAARwAAAA==EXITENTERSending request ... C02UgQARwA=ENTERSending request ... C02UgAABAA=Response is : gQARwAAPHhtbD48bWVzc2FnZT5IZWxsbyBYWDIhPC9tZXNzYWdlPjxkZXN0aW5haXRvbj5NaXNpPC9kZXN0aW5hdGlvbj48L3htbD4=",Locking error in c # "C_sharp : I have a sample Java app that I got when I downloaded javaaccessablity-2.0.2 that makes use of Java Accessibility ( via the Java Access Bridge WindowsAccessBridge-32.dll ) . Although it calls the getAccessibleContextFromHWND successfully it returns false.Please note that I get the correct value for hWnd which I verified through Inspect tool.I have a 64-bit Java SDK installed in my windows 64-bit system . And the following is the code I tried . I have tried with WindowsAccessBridge-64.dll also but it gives the same behavior which is vmID and _acParent are returned as zero instead of non zero values.I have read a similar post but it did n't solve my issue . class Program { [ return : MarshalAs ( UnmanagedType.Bool ) ] [ DllImport ( `` WindowsAccessBridge-32.dll '' , CallingConvention = CallingConvention.Cdecl ) ] public extern static bool getAccessibleContextFromHWND ( IntPtr hwnd , out Int32 vmID , out Int64 acParent ) ; [ DllImport ( `` WindowsAccessBridge-32.dll '' , CallingConvention = CallingConvention.Cdecl , ThrowOnUnmappableChar = true , CharSet = CharSet.Unicode ) ] private extern static void Windows_run ( ) ; [ DllImport ( `` user32.dll '' , SetLastError = true ) ] static extern IntPtr FindWindow ( string lpClassName , string lpWindowName ) ; static void Main ( string [ ] args ) { Int32 vmID = 0 ; Int64 _acParent =0 ; Windows_run ( ) ; IntPtr hWnd = ( IntPtr ) FindWindow ( `` SunAwtFrame '' , '' Standalone SwingApp '' ) ; bool retVal = getAccessibleContextFromHWND ( hWnd , out vmID , out _acParent ) ; } }",Running sample Java app for JavaAccessability in C # with 64-bit Java SDK and 64-bit windows "C_sharp : I am working on a project , and I have a generic abstract type that takes a type parameter that is itself derived from the abstract type . If you want to know why I would do this , please see this question.I have run into an interesting problem with overloading a method in a derived class that is defined in the abstract class . Here is a code sample : In the sample above , the overload of Convert that does not exist in the abstract parent ( and is less derived ) is called . I would expect that the most derived version , from the parent class , would be called.In trying to troubleshoot this problem , I ran into an interesting solution : When the derived type argument is removed from the base class , the most derived version of Convert is called . I would not expect this difference , since I would not have expected the interface of the abstract version of Convert to have changed . However , I must be wrong . Can anyone explain why this difference occurs ? Thank you very much in advance . public abstract class AbstractConverter < T , U > where U : AbstractConvertible where T : AbstractConverter < T , U > { public abstract T Convert ( U convertible ) ; } public class DerivedConvertibleConverter : AbstractConverter < DerivedConvertibleConverter , DerivedConvertible > { public DerivedConvertibleConverter ( DerivedConvertible convertible ) { Convert ( convertible ) ; } public override DerivedConvertibleConverter Convert ( DerivedConvertible convertible ) { //This will not be called System.Console.WriteLine ( `` Called the most derived method '' ) ; return this ; } public DerivedConvertibleConverter Convert ( Convertible convertible ) { System.Console.WriteLine ( `` Called the least derived method '' ) ; return this ; } } public abstract class AbstractConvertible { } public class Convertible : AbstractConvertible { } public class DerivedConvertible : Convertible { } public abstract class AbstractConverter < U > where U : AbstractConvertible { public abstract AbstractConverter < U > Convert ( U convertible ) ; } public class DerivedConvertibleConverter : AbstractConverter < DerivedConvertible > { public DerivedConvertibleConverter ( DerivedConvertible convertible ) { Convert ( convertible ) ; } public override DerivedConvertibleConverter Convert ( DerivedConvertible convertible ) { System.Console.WriteLine ( `` Called the most derived method '' ) ; return this ; } public DerivedConvertibleConverter Convert ( Convertible convertible ) { System.Console.WriteLine ( `` Called the least derived method '' ) ; return this ; } } public abstract class AbstractConvertible { } public class Convertible : AbstractConvertible { } public class DerivedConvertible : Convertible { }",C # Method Overload Problem With Class Derived From Generic Abstract Class "C_sharp : I have test code like this : First I tried running it without deriving A from CriticalFinalizerObject . Finalizer was n't called after end of this program.That surprised me as I thought it was more deterministic but okay . Then I 've read about CriticalFinalizerObject 's that ensure their finalizers will be called . I derived A from it.Guess what . It still does n't get executed.What am I doing/understanding wrong ? ( Please do n't write obvious stuff about garbage collector being non-deterministic , I know that . It is not the case as the program is over and I imagined I could safely clean up after a nice unhandled managed exception . ) public class A : CriticalFinalizerObject { ~A ( ) { File.WriteAllText ( `` c : \\1.txt '' , `` 1z1z1 '' ) ; } } class Program { static void Main ( string [ ] args ) { A a = new A ( ) ; throw new Exception ( ) ; } }",Finalizer not called after unhandled exception even with CriticalFinalizerObject "C_sharp : Possible Duplicate : Threads synchronization . How exactly lock makes access to memory 'correct ' ? This question is inspired by this one.We got a following test classActual result is very close to expected value 100 000 000 ( 50 000 000 x 2 , since 2 loops are running at the same time ) , with around 600 - 200 difference ( mistake is approx 0.0004 % on my machine which is very low ) . No other way of synchronization can provide such way of approximation ( its either a much bigger mistake % or its 100 % correct ) We currently understand that such level of preciseness is because of program runs in the following way : Time is running left to right , and 2 threads are represented by two rows.whereblack box represents process of acquiring , holding and releasing thelock plus represents addition operation ( schema represents scale on my PC , lock takes approximated 20 times longer than add ) white box represents period that consists of try to acquire lock , and further awaiting for it to become availableAlso lock provides full memory fence.So the question now is : if above schema represents what is going on , what is the cause of such big error ( now its big cause schema looks like very strong syncrhonization schema ) ? We could understand difference between 1-10 on boundaries , but its clearly no the only reason of error ? We can not see when writes to ms_Sum can happen at the same time , to cause the error.EDIT : many people like to jump to quick conclusions . I know what synchronization is , and that above construct is not a real or close to good way to synchronize threads if we need correct result . Have some faith in poster or maybe read linked answer first . I do n't need a way to synchronize 2 threads to perform additions in parallel , I am exploring this extravagant and yet efficient , compared to any possible and approximate alternative , synchronization construct ( it does synchronize to some extent so its not meaningless like suggested ) class Test { private static object ms_Lock=new object ( ) ; private static int ms_Sum = 0 ; public static void Main ( ) { Parallel.Invoke ( HalfJob , HalfJob ) ; Console.WriteLine ( ms_Sum ) ; Console.ReadLine ( ) ; } private static void HalfJob ( ) { for ( int i = 0 ; i < 50000000 ; i++ ) { lock ( ms_Lock ) { } // empty lock ms_Sum += 1 ; } } }",Thread synchronization . Why exactly this lock is n't enough to synchronize threads "C_sharp : I have created a .NET library compiled by LabVIEW which has a function that takes an array of numbers and a multiplicand . This function will return an array where each number has been multiplied with the multiplicand . When the function is called in C # , it turns out that the function takes a non-zero indexed array ( double [ * ] ) and an int as the parameters and return another non-zero indexed array.I 'm able to create a non-zero indexed array with C # 's Array.CreateInstance ( ) method . However I 'm not able to pass this array into the function since the data type required is double [ * ] .From the research on the internet , it seems like .NET does not support non-zero indexed array type . I 've tried to find a way to modify the LabVIEW program to generate the function that takes in a zero-indexed array without avail . Any advice on how I can go around this issue ? Update 1LabVIEW block diagramC # ProgramSignature of the LabVIEW function in C # Update 2Tried to use C # 's Reflection to call the LabVIEW function with the following codes , but encounter TargetInvocationException.Inner exception messageUnable to cast object of type 'System.Double [ * ] ' to type 'System.Double [ ] '.Inner exception stack traceat NationalInstruments.LabVIEW.Interop.DataMarshal.InitMarshalArrayIn ( IntPtr data , Array array , Marshal1DArray val ) at LabVIEW.Interop.LabVIEWInteropExports.MultiplyArray ( Double [ * ] input__32Array , Int32 numeric ) It seems like at some point of the execution , the program tries to marshal the type double [ * ] to double [ ] with InitMarshalArrayIn ( ) function in the assembly that comes with LabVIEW . const int Length = 5 ; const int LowerBound = 1 ; // Instanstiate a non-zero indexed array . The array is one-dimensional and// has size specified by Length and lower bound specified by LowerBound.Array numbers = Array.CreateInstance ( typeof ( double ) , new int [ ] { Length } , new int [ ] { LowerBound } ) ; // Initialize the array.for ( int i = numbers.GetLowerBound ( 0 ) ; i < = numbers.GetUpperBound ( 0 ) ; i++ ) { numbers.SetValue ( i , i ) ; } var variable = LabVIEWExports.Multiply ( numbers , 2 ) ; // This is invalid as numbers is not typed double [ * ] .Console.ReadKey ( ) ; const int Length = 5 ; const int LowerBound = 1 ; const string methodName = `` MultiplyArray '' ; const string path = @ '' C : \ '' ; Array numbers = Array.CreateInstance ( typeof ( double ) , new int [ ] { Length } , new int [ ] { LowerBound } ) ; for ( int i = numbers.GetLowerBound ( 0 ) ; i < = numbers.GetUpperBound ( 0 ) ; i++ ) { numbers.SetValue ( i , i ) ; } Assembly asm = Assembly.LoadFile ( path + `` LabVIEW.Interop.dll '' ) ; Type type = asm.GetType ( `` LabVIEW.Interop.LabVIEWInteropExports '' ) ; if ( type ! = null ) { MethodInfo methodInfo = type.GetMethod ( methodName ) ; if ( methodInfo ! = null ) { object result = methodInfo.Invoke ( methodInfo , new object [ ] { array , multiplicand } ) ; // Throw exception . } } Console.ReadKey ( ) ;",Non-zero indexed array "C_sharp : The ASP.NET project I am working on has 3 layers ; UI , BLL , and DAL . I wanted to know if it was acceptable for the UI to pass a lambda expression to the BLL , or if the UI should pass parameters and the Service method should use those parameters to construct the lambda expression ? Here is an example class showing both senarios.For the above class is it acceptable for the UI to call the following : or should it only be allowed to call GetJob ( int jobID ) ? This is a simple example , and my question is in general , should the UI layer be able to pass lambda expressions into the service layer instead of calling a specific method ? public class JobService { IRepository < Job > _repository ; public JobService ( IRepository < Job > repository ) { _repository = repository ; } public Job GetJob ( int jobID ) { return _repository.Get ( x = > x.JobID == jobID ) .FirstOrDefault ( ) ; } public IEnumerable < Job > Get ( Expression < Func < Job , bool > > predicate ) { return _repository.Get ( predicate ) ; } } JobService jobService = new JobService ( new Repository < Job > ( ) ) ; Job job = jobService.Get ( x = > x.JobID == 1 ) .FirstOrDefault ( ) ;",Should the UI layer be able to pass lambda expressions into the service layer instead of calling a specific method ? "C_sharp : I develop a Windows C # application which can work in Online and Offline mode.When in Online mode it connects to a SQL Server . In Offline mode it connects to a local DB.I use the Microsoft Sync Framework 2.1 to sync the 2 databases on demand.Until now I used a LocalDB instance of SQL Server as the local database . But it is a pain to setup the system automatically during the installation process of my application . So I tought to use SQL Server Compact 3.5 or 4.0 which is very easy to distribute ( comes in a single file ) .But I can not get it to even compile the provisioning code of the Compact DB : which I used before ( without the Ce classes ) but SqlCeSyncScopeProvisioning can not be resolved . Something is terribly wrong here.How can I sync my CompactDB to distribute this as my local database ? DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription ( `` MyScope '' ) ; SqlCeConnection clientConn = new SqlCeConnection ( OfflineConnectionString ) ; var clientProvision = new SqlCeSyncScopeProvisioning ( clientConn , scopeDesc ) ; clientProvision.Apply ( ) ;",MS Sync Framework and SQL Server Compact "C_sharp : Please , take a look at the following code snippet . I simply open the excel file myfile.xlsx and I add rows from an object of type List < Account > ( where my Account object only has Date , Account and Amount properties ) , and store the file with the name myoutputfile.xlsx . I would like the cells where I write the dates to have a date format , and the cells where I have amounts to have a numeric format . However , if I try the code below , all cells are formatted with the # .00 format ( dates as well ) . I 've tried everything , can someone please tell me what 's going on ? I am using NPOI . XSSFWorkbook wb ; var fileName = `` C : /tmp/myfile.xlsx '' ; var outputFileName = `` C : /tmp/myoutputfile.xlsx '' ; using ( var file = new FileStream ( fileName , FileMode.Open , FileAccess.ReadWrite ) ) { wb = new XSSFWorkbook ( file ) ; } XSSFSheet sheet = ( XSSFSheet ) wb.GetSheetAt ( 0 ) ; for ( int i = 0 ; i < accountRecs.Count ( ) ; ++i ) { var rec = accountRecs [ i ] ; var row = sheet.CreateRow ( i ) ; var dateCell = row.CreateCell ( 3 ) ; dateCell.SetCellValue ( rec.Date ) ; dateCell.CellStyle.DataFormat = wb.CreateDataFormat ( ) .GetFormat ( `` dd/MM/yyyy '' ) ; var accountCell = row.CreateCell ( 4 ) ; accountCell.SetCellValue ( rec.Account ) ; var totalValueCell = row.CreateCell ( 16 ) ; totalValueCell.SetCellValue ( rec.Amount ) ; totalValueCell.CellStyle.DataFormat = wb.CreateDataFormat ( ) .GetFormat ( `` # .00 '' ) ; } using ( var file = new FileStream ( outputFileName , FileMode.Create , FileAccess.Write ) ) { wb.Write ( file ) ; file.Close ( ) ; }",NPOI formats all cells the same way "C_sharp : I am confused by the syntax for removing event handlers in C # .The `` new '' creates a new object on each line , so you add one objectand then ask it to remove a different object.What is really going on under the covers that this can work ? It sure is n't obvious from the syntax . Something += new MyHandler ( HandleSomething ) ; // addSomething -= new MyHandler ( HandleSomething ) ; // remove",C # event removal syntax "C_sharp : I want to provide my Angular app through the root route / and the REST API through /api/* . For the Angular routing I have to redirect all requests to /index.html except the requests for existing files ( e.g . media files ) and my API controller routes . With the Startup.cs below it 's close to be working : Opening http : //localhost:5000 will return the index.html and the angular routing is working , that I get redirected to http : //localhost:5000/homeAPI calls are still workingExisting CSS/JavaScript files are returnedThe following is not working : Refreshing or opening directly http : //localhost:5000/home will end up in a 404 . I guess /home is not redirected to the index.html.What I 'm missing here ? public class Startup { private readonly IWebHostEnvironment _webHostEnvironment ; public Startup ( IWebHostEnvironment webHostEnvironment ) { _webHostEnvironment = webHostEnvironment ; } public void ConfigureServices ( IServiceCollection services ) { services.AddSpaStaticFiles ( options = > { options.RootPath = `` wwwroot '' ; } ) ; services.AddControllers ( ) ; } public void Configure ( IApplicationBuilder app , IWebHostEnvironment env ) { app.UseDefaultFiles ( ) ; app.UseSpaStaticFiles ( ) ; app.UseCors ( ) ; app.UseSwagger ( ) ; app.UseSwaggerUI ( c = > { /* ... */ } ) ; app.UseRouting ( ) ; app.UseEndpoints ( endpoints = > { endpoints.MapControllers ( ) ; } ) ; } }",How to host an Angular app inside .NET Core 3.1 WebAPI ? "C_sharp : I have got a grid [ Grid1 ] that build its dataRows when a button [ search ] is clicked , I managed to Ajaxify it by placing it in an UpdatePanel and it worked fine . Before Ajaxifying Grid 1 , another grid [ Grid2 ] and some other controls [ Text and Labels ] used to get populated/updated when a row in Grid 1 was clicked .The Grid2 and other controls used to get populated/updated on the OnItemCommand Event of Grid 1.Its the code in the OnItemCommand that binds the related data to Grid2 and other controls.After I placed the Grid 1 in the update panel , they stopped updating . It will work fine if I place Grid2 and other controls in the same Update Panel but the page is designed in a way that I cant have those controls in the same UpdatePanel as the first Grid nor I dont intend to use another Update Panel.I hope I 'm making some sense . I 'm a newbie in .Net so please excuse . Please find the code below.The code below in the code behind stopped working < asp : ScriptManager EnablePartialRendering= '' true '' ID= '' ScriptManager1 '' runat= '' server '' > < /asp : ScriptManager > < asp : UpdatePanel ID= '' UpdatePanel1 '' runat= '' server '' UpdateMode= '' Conditional '' ChildrenAsTriggers = '' True '' > < ContentTemplate > < asp : DataGrid ID= '' grdJobs '' runat= '' server '' AllowPaging= '' true '' AlternatingItemStyle-CssClass= '' gridAltItemStyle '' AutoGenerateColumns= '' False '' CellPadding= '' 0 '' DataKeyField= '' code '' CssClass= '' datagridBox '' GridLines= '' horizontal '' PagerStyle-Mode= '' NumericPages '' HeaderStyle-CssClass= '' gridHeaderStyle '' ItemStyle-CssClass= '' gridItemStyle '' PagerStyle-CssClass= '' gridPagerStyle '' Width= '' 445px '' OnPageIndexChanged= '' grdJobs_PageIndexChanged '' OnItemCreated= '' grdJobs_ItemCreated '' OnItemCommand= '' grdJobs_ItemCommand '' OnItemDataBound= '' grdJobs_ItemDataBound '' > < Columns > < asp : BoundColumn DataField= '' J_ID '' HeaderText= '' Job '' > < /asp : BoundColumn > < asp : BoundColumn DataField= '' Contract '' HeaderText= '' Contract '' ReadOnly= '' True '' > < /asp : BoundColumn > < asp : BoundColumn DataField= '' J_Fault_Line1 '' HeaderText= '' Fault '' ReadOnly= '' True '' > < /asp : BoundColumn > < asp : BoundColumn DataField= '' j_p_id '' HeaderText= '' Fault '' Visible= '' false '' > < /asp : BoundColumn > < asp : ButtonColumn Text= '' < img src=images/addFeedback.gif style=border : 0px ; alt=Add Feedback > '' ButtonType= '' LinkButton '' HeaderText= '' Add '' CommandName= '' Load '' ItemStyle-cssClass= '' Col_9_Item_2 '' > < /asp : ButtonColumn > < /Columns > < /asp : DataGrid > < asp : ImageButton ID= '' cmdLkp '' ImageUrl= '' Images/search.gif '' runat= '' server '' OnClick= '' cmdLkp_Click '' / > < /ContentTemplate > < /asp : UpdatePanel > protected void grdJobs_ItemCommand ( object source , DataGridCommandEventArgs e ) { if ( e.CommandName == `` Load '' ) { functionToBindDataToGrid2 ( ) ; functionToBindDataToOtherControls ( ) ; } } protected void grdJobs_ItemDataBound ( object sender , DataGridItemEventArgs e ) { e.Item.Attributes.Add ( `` onclick '' , `` javascript : __doPostBack ( 'grdJobs $ ctl '' + ( ( Convert.ToInt32 ( e.Item.ItemIndex + 3 ) .ToString ( `` 00 '' ) ) ) + `` $ ctl00 ' , '' ) '' ) ; }","How to update controls [ DataGrid , TextBoxes and Label ] based on a row selection made in DataGrid that resideds in a updatePanel ?" "C_sharp : What is the proper way to create a variable that will house a list of anonymous objects that are generated through a LINQ query while keeping the variable declaration outside of a try/catch and the assignment being handled inside of a try/catch ? At the moment I 'm declaring the variable as IEnumberable < object > , but this causes some issues down the road when I 'm trying to use it later ... i.e.EDIT : If it 's relevant ( do n't think it is ) the list of objects is being returned as a Json result from an MVC3 action . I 'm trying to reduce the time that some using statements are open with the DB as I 'm having some performance issues that I 'm trying to clear up a bit . In doing some of my testing I came across this issue and ca n't seem to find info on it.EDIT 2 : If I could request the avoidance of focusing on LINQ . While LINQ is used the question is more specific to the scoping issues associated with Anonymous objects . Not the fact that LINQ is used ( in this case ) to generate them.Also , a couple of answers have mentioned the use of dynamic while this will compile it does n't allow for the usages that I 'm needing later on the method . If what I 'm wanting to do is n't possible then at the moment the answer appears to be to create a new class with the definition that I 'm needing and to use that . var variableDeclaration ; try { ... assignment ... } catch ...",Anonymous type scoping issue "C_sharp : I am using MediatR with the following classes : Where Envelope is a wrapper class : The GetPostsRequest , sent by the mediator , is executed by the Handler : MediatR allows the use of Behaviors which executes before the Handler of a specific Request . I created a ValidationBehavior as follows : And I registered the ValidationBehavior on the ASP.NET Core application : When I call the API I get the following error : What am I missing ? public class GetPostsRequest : IRequest < Envelope < GetPostsResponse > > { public Int32 Age { get ; set ; } } public class GetPostResponse { public String Title { get ; set ; } public String Content { get ; set ; } } public class Envelope < T > { public List < T > Result { get ; private set ; } = new List < T > ( ) ; public List < Error > Errors { get ; private set ; } = new List < Error > ( ) ; } public class GetPostsRequestHandler : IRequestHandler < GetPostsRequest , Envelope < GetPostsResponse > > { public async Task < Envelope < GetPostsResponse > > Handle ( GetPostsRequest request , CancellationToken cancellationToken ) { } } public class ValidationBehavior < TRequest , TResponse > : IPipelineBehavior < TRequest , Envelope < TResponse > > where TRequest : IRequest < Envelope < TResponse > > { private readonly IEnumerable < IValidator < TRequest > > _validators ; public ValidationBehavior ( IEnumerable < IValidator < TRequest > > validators ) { _validators = validators ; } public Task < Envelope < TResponse > > Handle ( TRequest request , CancellationToken cancellationToken , RequestHandlerDelegate < Envelope < TResponse > > next ) { ValidationContext context = new ValidationContext ( request ) ; List < Error > errors = _validators .Select ( x = > x.Validate ( context ) ) .SelectMany ( x = > x.Errors ) .Select ( x = > new Error ( ErrorCode.DataNotValid , x.ErrorMessage , x.PropertyName ) ) .ToList ( ) ; if ( errors.Any ( ) ) return Task.FromResult < Envelope < TResponse > > ( new Envelope < TResponse > ( errors ) ) ; return next ( ) ; } } services.AddScoped ( typeof ( IPipelineBehavior < , > ) , typeof ( ValidationBehavior < , > ) ) ; An unhandled exception has occurred while executing the request.System.ArgumentException : GenericArguments [ 0 ] , 'TRequest ' , on 'ValidationBehavior ` 2 [ TRequest , TResponse ] ' violates the constraint of type 'TRequest ' . -- - > System.TypeLoadException : GenericArguments [ 0 ] , 'TRequest ' , on 'ValidationBehavior ` 2 [ TRequest , TResponse ] ' violates the constraint of type parameter 'TRequest ' .",Constraint Violated Exception on MediatR Behavior "C_sharp : Well this question may seem odd but it 's simple - my point is if i have a `` goto '' ( brtrue etc ) in the decompiled code like exampleand I add a command after that **** call will the br at the top point to ret like it should or to that code.does Cecil do it by itself or I have to take care of all those branches ? : /it would n't be very hard to fix them but if Cecil does n't then I simply wo n't start this project , I 've no time ( or knowledge ) for advanced IL magic : P ( yes I know it wo n't be IL_0003 it 's just for example ) br IL_0003call *****IL_0003 : ret",Does Mono.Cecil take care of branches etc location ? "C_sharp : Does any one know if it is possible to host multiple instances of WebApplicationFactory < TStartop > ( ) in the same unit test ? I have tried and ca n't seem to get anywhere with this one issue.i.eWebHost is just a helper class that allows me to build factory and then a client easily in one line.Under the covers all it does is this : new WebApplicationFactory < TStartup > ( ) but a few other things too.It would be nice if i could stand up another instace of a different web server to test server to server functionality.Does anyone know if this is possible or not ? _client = WebHost < Startup > .GetFactory ( ) .CreateClient ( ) ; var baseUri = PathString.FromUriComponent ( _client.BaseAddress ) ; _url = baseUri.Value ; _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ( `` Bearer '' , `` Y2E890F4-E9AE-468D-8294-6164C59B099Y '' ) ;",AspNetCore Integration Testing Multiple WebApplicationFactory Instances ? "C_sharp : First of all , I did n't find a good example of custom implementation of the ObservableBase or AnonymousObservable . I have no idea which one I need to implement in my case if any . The situation is this.I use a third-party library and there is a class let 's call it Producer which allows me to set a delegate on it like objProducer.Attach ( MyHandler ) . MyHandler will receive messages from the Producer . I 'm trying to create a wrapper around the Producer to make it observable and ideally to be it a distinct type instead of creating just an instance of observable ( like Observable.Create ) .EDITED : Third-party Producer has the following interfaceas I mentioned I have no control over the source code of it . It is intended to be used like this : create an instance , call Attach and pass a delegate , call Start which basically initiates receiving messages inside the provided delegated when Producer receives them or generates them.I was thinking about creating public class ProducerObservable : ObservableBase < Message > so that when somebody subscribes to it I would ( Rx library would ) push messages to the observers . It seems that I need to call Attach somewhere in the constructor of my ProducerObservable , then I need somehow to call OnNext on the observers attached to it . Does it mean that I have to code all this : add a list of observers LinkedList < IObserver < Message > > to the class and then add observers when SubscribeCore abstract method is called on the ProducerObservable ? Then apparently I would be able to enumerate the LinkedList < IObserver < Message > > in the MyHandler and call OnNext for each one . All these looks feasible but it does n't feel exactly right . I would expect .net reactive extensions to be better prepare to situations like this and have at least the implementation of the LinkedList < IObserver < Message > > ready somewhere in base class . public delegate void ProducerMessageHandler ( Message objMessage ) ; public class Producer : IDisposable { public void Start ( ) ; public void Attach ( ProducerMessageHandler fnHandler ) ; public void Dispose ( ) ; }",Is it the best to implement ObservableBase in this situation or is there another way ? "C_sharp : I want to serialize a custom object : In json . To do this , I use a custom converter : I use a JsonSerializerSettings to serialize to json.net knows which type implement ( for HttpPostedFileBase ) .The object is serialized correctly but I have this error for the serialization : and this is the value of my serialized object : What 's wrong in the deserialization ? EDITI have tested a class to test ... and now it works : In the serialization I noticed this difference : instead ofBut finally I do n't want to create a wrapper or whatever ... and I do n't understand why it works with this type and not with the HttpPostedFileWrapper . public class MyCustomObject { public string Name { get ; set ; } public DateTime Date { get ; set ; } public List < HttpPostedFileBase > Files { get ; set ; } public MyCustomObject ( ) { Files = new List < HttpPostedFileBase > ( ) ; } } public class HttpPostedFileConverter : JsonConverter { public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { var stream = ( Stream ) value ; using ( var sr = new BinaryReader ( stream ) ) { var buffer = sr.ReadBytes ( ( int ) stream.Length ) ; writer.WriteValue ( Convert.ToBase64String ( buffer ) ) ; } } var settings = new JsonSerializerSettings ( ) ; settings.Converters.Add ( new HttpPostedFileConverter ( ) ) ; settings.TypeNameHandling = TypeNameHandling.Objects ; JsonSerializationException Error converting value `` /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDA { `` $ type '' : `` ConsoleApplication1.MyCustomObject , ConsoleApplication1 '' , `` Name '' : `` Test2 '' , `` Date '' : `` 2016-11-03T12:35:14.6020154+01:00 '' , `` Files '' : [ { `` $ type '' : `` System.Web.HttpPostedFileWrapper , System.Web '' , `` ContentLength '' : 1024 , `` FileName '' : `` Pannigale.jpg '' , `` ContentType '' : `` image/jpg '' , `` InputStream '' : `` /9j/4AAQ ... KKAP//Z '' } ] } public class TestHttpFile : HttpPostedFileBase { string fullFileName = @ '' C : \Pictures\SBK-1299-Panigale-S_2015_Studio_R_B01_1920x1080.mediagallery_output_image_ [ 1920x1080 ] .jpg '' ; public override int ContentLength { get { return 1024 ; } } public override string FileName { get { return `` Pannigale.jpg '' ; } } public override string ContentType { get { return `` image/jpg '' ; } } public override Stream InputStream { get { return File.OpenRead ( fullFileName ) ; } } } `` $ type '' : `` ConsoleApplication1.TestHttpFile , ConsoleApplication1 '' , `` $ type '' : `` System.Web.HttpPostedFileWrapper , System.Web '' ,",Error converting value from string to stream "C_sharp : Having these basic definitions I 'm wondering why this wo n't compile : But this will : The error message is `` The type arguments for method 'System.Linq.Enumerable.Select ( System.Collections.Generic.IEnumerable , System.Func ) ' can not be inferred from the usage . `` The Resharper error tip says it 's confused between and ... but the signature for MyFunc is clear - it just takes one ( string ) parameter.Can anyone shed some light here ? bool MyFunc ( string input ) { return false ; } var strings = new [ ] { `` aaa '' , `` 123 '' } ; var b = strings.Select ( MyFunc ) ; var c = strings.Select ( elem = > MyFunc ( elem ) ) ; Select ( this IEnumerable < string > , Func < string , TResult > ) Select ( this IEnumerable < string > , Func < string , int , TResult > )",Simple Linq expression wo n't compile "C_sharp : I am implementing logging in my app via NLog . This is my Nlog.Config : When I deploy the app out with ClickOnce , no log.txt file is being created . No errors occur , and my app runs as normal , but nothing is happening.How to solve this problem ? < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < nlog xmlns= '' http : //www.nlog-project.org/schemas/NLog.xsd '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < targets async= '' true '' > < target xsi : type= '' File '' name= '' ExceptionTarget '' fileName= '' LOG.txt '' layout= '' $ { date : format=dd MMM yyyy HH-mm-ss } $ { uppercase : $ { level } } $ { newline } $ { message } $ { exception : :maxInnerExceptionLevel=5 : format=ToString } $ { newline } $ { stacktrace } $ { newline } '' / > < /targets > < targets async= '' true '' > < target xsi : type= '' File '' name= '' InfoTarget '' fileName= '' LOG.txt '' layout= '' $ { date : format=mm-ss } $ { uppercase : $ { level } } $ { newline } $ { message } $ { newline } '' / > < /targets > < rules > < logger name= '' * '' level= '' Error '' writeTo= '' ExceptionTarget '' / > < logger name= '' * '' level= '' Info '' writeTo= '' InfoTarget '' / > < /rules > < /nlog >",NLog does n't logging with ClickOnce "C_sharp : Is there a way to tell JSON.net that when it attempts to deserialize using a constructor ( if there is no default constructor ) , that it should NOT assign default value to constructor parameters and that it should only call a constructor if every constructor parameter is represented in the JSON string ? This same serializer SHOULD use default values when calling property/field setters , the rule is only scoped to constructors . None of the enum values here seem to be appropriate : http : //www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htmThe solution should NOT rely on applying any attributes to the types being deserialized.for example , the json string `` { } '' will deserialize to an object of type Dog by setting the Dog 's age to 0 ( the default value for an int ) . I 'd like to a generalized , not-attribute-based solution to prevent this from happening . In this case , { `` age '' :4 } would work because age is specified in the JSON string and corresponds to the constructor parameter.However , if Dog is specified as such , then `` { } '' should deserialize to a Dog with Age == 0 , because the Dog is not being created using a constructor.And to head-off any questions about `` why would you want to do this '' ... Objects with constructors are typically qualitatively different than POCOs as it relates to their properties . Using a constuctor to store property values instead of settable properties on a POCO typically means that you want to validate/constrain the property values . So it 's reasonable not to allow deserialization with default values in the presence of constuctor ( s ) . public class Dog { public Dog ( int age ) { this.Age = age ; } public int Age { get ; } } public class Dog { public int Age { get ; set ; } }","JSON.net should not use default values for constructor parameters , should use default for properties" "C_sharp : Possible Duplicate : Is it better to declare a variable inside or outside a loop ? Resharper wants me to change this : ... to this : ... but in this way ( it seems , at least , that ) the vars are being declared N times , once for each time through the while loop . Is the Resharperized way really better than the original ? int Platypus ; string duckBill1 ; string duckBill2 ; string duckBill3 ; . . .using ( OracleDataReader odr = ocmd.ExecuteReader ( ) ) { while ( odr.Read ( ) ) { Platypus = odr.GetInt32 ( `` Platypus '' ) ; duckBill1 = odr.GetString ( `` duckBill1 '' ) ; duckBill2 = odr.GetString ( `` duckBill2 '' ) ; duckBill3 = odr.GetString ( `` duckBill3 '' ) ; switch ( Platypus ) { . . . using ( OracleDataReader odr = ocmd.ExecuteReader ( ) ) { while ( odr.Read ( ) ) { int Platypus = odr.GetInt32 ( `` Platypus '' ) ; string duckBill1 = odr.GetString ( `` duckBill1 '' ) ; string duckBill2 = odr.GetString ( `` duckBill2 '' ) ; string duckBill3 = odr.GetString ( `` duckBill3 '' ) ; switch ( Platypus ) { . . .",Is this `` move declaration closer to usage '' really preferable ? "C_sharp : In this example ASP.Net MVC 4 program I have a user fill in details about a horse race . The race has a name a well as a list of horses involved . Each horse has a name and an age.The form uses ajax and javascript to allow the person to add and delete horse input fields on the fly , which is then submitted all at once when the submit button is pressed.To make this process easy for me , I 'm using an html helper made by Matt Lunn.While I do n't understand all the details ( please read the blog post ) , I do know that it changes the index values into guids rather than sequential integers . This allows me to delete items in the middle of the list without needing to recalculate indexes.Here is the rest of my code for my MCVEHomeController.csModels.csIndex.cshtmlViews/Shared/EditorTemplates/Horse.cshtmlViews/Home/AjaxMakeHorseEntry.cshtmlThe data flow works with this code . A person is able to create and delete horse entries as much as they want on the page , and when the form is submitted all entered values are given to the action method.However , if the user does not enter in the [ Required ] information on a horse entry , ModelState.IsValid will be false showing the form again , but no validation messages will be shown for the Horse properties . The validation error do show up in the ValidationSummary list though.For example , if Race Name is left blank , along with one Horse 's Name , a validation message will be shown for the former . The latter will have a validation < span > with the class `` field-validation-valid '' .I 'm very sure this is caused because the EditorForMany method creates new guids for each property each time the page is created , so validation messages ca n't be matched to the correct field.What can I do to fix this ? Do I need to abandon guid index creation or can an alteration be made to the EditorForMany method to allow validation messages to be passed along correctly ? public static MvcHtmlString EditorForMany < TModel , TValue > ( this HtmlHelper < TModel > html , Expression < Func < TModel , IEnumerable < TValue > > > expression , string htmlFieldName = null ) where TModel : class { var items = expression.Compile ( ) ( html.ViewData.Model ) ; var sb = new StringBuilder ( ) ; if ( String.IsNullOrEmpty ( htmlFieldName ) ) { var prefix = html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix ; htmlFieldName = ( prefix.Length > 0 ? ( prefix + `` . '' ) : String.Empty ) + ExpressionHelper.GetExpressionText ( expression ) ; } foreach ( var item in items ) { var dummy = new { Item = item } ; var guid = Guid.NewGuid ( ) .ToString ( ) ; var memberExp = Expression.MakeMemberAccess ( Expression.Constant ( dummy ) , dummy.GetType ( ) .GetProperty ( `` Item '' ) ) ; var singleItemExp = Expression.Lambda < Func < TModel , TValue > > ( memberExp , expression.Parameters ) ; sb.Append ( String.Format ( @ '' < input type= '' '' hidden '' '' name= '' '' { 0 } .Index '' '' value= '' '' { 1 } '' '' / > '' , htmlFieldName , guid ) ) ; sb.Append ( html.EditorFor ( singleItemExp , null , String.Format ( `` { 0 } [ { 1 } ] '' , htmlFieldName , guid ) ) ) ; } return new MvcHtmlString ( sb.ToString ( ) ) ; } public class HomeController : Controller { [ HttpGet ] public ActionResult Index ( ) { var model = new Race ( ) ; //start with one already filled in model.HorsesInRace.Add ( new Horse ( ) { Name = `` Scooby '' , Age = 10 } ) ; return View ( model ) ; } [ HttpPost ] public ActionResult Index ( Race postedModel ) { if ( ModelState.IsValid ) //model is valid , redirect to another page return RedirectToAction ( `` ViewHorseListing '' ) ; else //model is not valid , show the page again with validation errors return View ( postedModel ) ; } [ HttpGet ] public ActionResult AjaxMakeHorseEntry ( ) { //new blank horse for ajax call var model = new List < Horse > ( ) { new Horse ( ) } ; return PartialView ( model ) ; } } public class Race { public Race ( ) { HorsesInRace = new List < Horse > ( ) ; } [ Display ( Name = `` Race Name '' ) , Required ] public string RaceName { get ; set ; } [ Display ( Name = `` Horses In Race '' ) ] public List < Horse > HorsesInRace { get ; set ; } } public class Horse { [ Display ( Name = `` Horse 's Name '' ) , Required ] public string Name { get ; set ; } [ Display ( Name = `` Horse 's Age '' ) , Required ] public int Age { get ; set ; } } @ model CollectionAjaxPosting.Models.Race < h1 > Race Details < /h1 > @ using ( Html.BeginForm ( ) ) { @ Html.ValidationSummary ( ) < hr / > < div > @ Html.DisplayNameFor ( x = > x.RaceName ) @ Html.EditorFor ( x = > x.RaceName ) @ Html.ValidationMessageFor ( x = > x.RaceName ) < /div > < hr / > < div id= '' horse-listing '' > @ Html.EditorForMany ( x = > x.HorsesInRace ) < /div > < button id= '' btn-add-horse '' type= '' button '' > Add New Horse < /button > < input type= '' submit '' value= '' Enter Horses '' / > } < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { //add button logic $ ( ' # btn-add-horse ' ) .click ( function ( ) { $ .ajax ( { url : ' @ Url.Action ( `` AjaxMakeHorseEntry '' ) ' , cache : false , method : 'GET ' , success : function ( html ) { $ ( ' # horse-listing ' ) .append ( html ) ; } } ) } ) ; //delete-horse buttons $ ( ' # horse-listing ' ) .on ( 'click ' , 'button.delete-horse ' , function ( ) { var horseEntryToRemove = $ ( this ) .closest ( 'div.horse ' ) ; horseEntryToRemove.prev ( 'input [ type=hidden ] ' ) .remove ( ) ; horseEntryToRemove.remove ( ) ; } ) ; } ) ; < /script > @ model CollectionAjaxPosting.Models.Horse < div class= '' horse '' > < div > @ Html.DisplayNameFor ( x = > x.Name ) @ Html.EditorFor ( x = > x.Name ) @ Html.ValidationMessageFor ( x = > x.Name ) < /div > < div > @ Html.DisplayNameFor ( x = > x.Age ) @ Html.EditorFor ( x = > x.Age ) @ Html.ValidationMessageFor ( x = > x.Age ) < /div > < button type= '' button '' class= '' delete-horse '' > Remove Horse < /button > < hr / > < /div > @ model IEnumerable < CollectionAjaxPosting.Models.Horse > @ Html.EditorForMany ( x = > x , `` HorsesInRace '' )",How can I get validation messages to render on collection properties when using new guid indexes each time ? "C_sharp : I 'm confused by a problem we have in our project . I tried to simplify it to reproduce the effect : To me this looks fine , but the compiler complains on the last call , because it tries to DoTheFoo < T > ( T bar ) , instead of DoTheFoo < T > ( IFoo < T > foo ) and complains that the argument type does not fit.When I remove the method DoTheFoo < T > ( T bar ) , the last call works ! When I change it to DoTheFoo < T > ( Foo < T > foo ) , it works , but I ca n't use thatIt is not too hard to work around this in our current code . But it is a ) strange and b ) too bad that we ca n't have these two overloaded methods.Is there a common rule that explains this behaviour ? Is it possible to make it work ( except of giving the methods different names ) ? interface IBar { } class Bar : IBar { } interface IFoo < T > where T : IBar { } class Foo < T > : IFoo < T > where T : IBar { } class Class1 { public void DoTheFoo < T > ( T bar ) where T : IBar { } public void DoTheFoo < T > ( IFoo < T > foo ) where T : IBar { } public void Test ( ) { var bar = new Bar ( ) ; var foo = new Foo < Bar > ( ) ; DoTheFoo ( bar ) ; // works DoTheFoo < Bar > ( foo ) ; // works DoTheFoo ( ( IFoo < Bar > ) foo ) ; // works DoTheFoo ( foo ) ; // complains } }",C # Method overloading and generic interface "C_sharp : When I run the following code I get a NullReferenceException saying that an object reference not set to an instance of the object . I 've successfully inserted with dapper using less complex objects but the same format , so am not sure what I 'm doing wrong.I first tried doing the simpler way of just passing in fogbugzCase instead of the anonymous object but resulted in a different exception about CategoryId.Anyone see what I 'm missing ? public void Foo ( IEnumerable < FogbugzCase > cases ) { // using a singleton for the SqlConnection using ( SqlConnection conn = CreateConnection ( ) ) { foreach ( FogbugzCase fogbugzCase in cases ) { conn.Execute ( `` INSERT INTO fogbugz.Cases ( CaseId , Title , ProjectId , CategoryId , Root , MilestoneId , Priority , Status , EstimatedHours , ElapsedHours , AssignedTo , ResolvedBy , IsResolved , IsOpen , Opened , Resolved , Uri , ResolveUri , OutlineUri , SpecUri , ParentId , Backlog ) VALUES ( @ BugId , @ Title , @ ProjectId , @ CategoryId , @ RootId , @ MilestoneId , @ Priority , @ StatusId , @ EstimatedHours , @ ElapsedHours , @ PersonAssignedToId , @ PersonResolvedById , @ IsResolved , @ IsOpen , @ Opened , @ Resolved , @ Uri , @ ResolveUri , @ OutlineUri , @ Spec , @ ParentId , @ Backlog ) ; '' , new { BugId = fogbugzCase.BugId , Title = fogbugzCase.Title , ProjectId = fogbugzCase.Project.Id , CategoryId = fogbugzCase.Category.Id , RootId = fogbugzCase.Root , MilestoneId = fogbugzCase.Milestone.Id , Priority = fogbugzCase.Priority , StatusId = fogbugzCase.Status.Id , EstimatedHours = fogbugzCase.EstimatedHours , ElapsedHours = fogbugzCase.ElapsedHours , PersonAssignedToId = fogbugzCase.PersonAssignedTo.Id , PersonResolvedById = fogbugzCase.PersonResolvedBy.Id , IsResolved = fogbugzCase.IsResolved , IsOpen = fogbugzCase.IsOpen , Opened = fogbugzCase.Opened , Resolved = fogbugzCase.Resolved , Uri = fogbugzCase.Uri , OutlineUri = fogbugzCase.OutlineUri , Spec = fogbugzCase.Spec , ParentId = fogbugzCase.ParentId , Backlog = fogbugzCase.Backlog } ) ; } } }",NullReferenceException when inserting with Dapper "C_sharp : I am stumped . Perhaps someone can shed some light on WCF client behavior I am observing . Using the WCF samples , I 've started playing with different approaches to WCF client/server communication . While executing 1M of test requests in parallel , I was using SysInternals TcpView to monitor open ports . Now , there are at least 4 different ways to call the client : Create the client , do your thing , and let GC collect itCreate the client in a using block , than do your thingCreate the client channel from factory in a using block , than do your thingCreate the client or channel , but use WCF Extensions to do your thingNow , to my knowledge , only options 2-4 , explicitly call client.Close ( ) . During their execution I see a lot of ports left in the TIME_WAIT state . I 'd expect option 1 to be the worst case scenario , due to reliance on the GC . However , to my surprise , it seems to be the cleanest of them all , meaning , it leaves no lingering ports behind.What am I missing ? UPDATE : Source code private static void RunClientWorse ( ConcurrentBag < double > cb ) { var client = new CalculatorClient ( ) ; client.Endpoint.Address = new EndpointAddress ( `` net.tcp : //localhost:8000/ServiceModelSamples/service '' ) ; RunClientCommon ( cb , client ) ; } private static void RunClientBetter ( ConcurrentBag < double > cb ) { using ( var client = new CalculatorClient ( ) ) { client.Endpoint.Address = new EndpointAddress ( `` net.tcp : //localhost:8000/ServiceModelSamples/service '' ) ; RunClientCommon ( cb , client ) ; } } private static void RunClientBest ( ConcurrentBag < double > cb ) { const string Uri = `` net.tcp : //localhost:8000/ServiceModelSamples/service '' ; var address = new EndpointAddress ( Uri ) ; //var binding = new NetTcpBinding ( `` netTcpBinding_ICalculator '' ) ; using ( var factory = new ChannelFactory < ICalculator > ( `` netTcpBinding_ICalculator '' , address ) ) { ICalculator client = factory.CreateChannel ( ) ; ( ( IContextChannel ) client ) .OperationTimeout = TimeSpan.FromSeconds ( 60 ) ; RunClientCommon ( cb , client ) ; } } private static void RunClientBestExt ( ConcurrentBag < double > cb ) { const string Uri = `` net.tcp : //localhost:8000/ServiceModelSamples/service '' ; var address = new EndpointAddress ( Uri ) ; //var binding = new NetTcpBinding ( `` netTcpBinding_ICalculator '' ) ; new ChannelFactory < ICalculator > ( `` netTcpBinding_ICalculator '' , address ) .Using ( factory = > { ICalculator client = factory.CreateChannel ( ) ; ( ( IContextChannel ) client ) .OperationTimeout = TimeSpan.FromSeconds ( 60 ) ; RunClientCommon ( cb , client ) ; } ) ; }","WCF using , closing and extensions" "C_sharp : In lots of tutorials for UnitTesting , the way to mark a TestMethod was different . I saw these options : What is the difference ? [ TestMethod ] [ TestMethod ( ) ]",Why put parentheses on TestMethod attribute in UnitTest "C_sharp : I 'm trying to build a console application in .NET vNext from Windows PowerShell . So far I have upgraded the package by kvm upgradefrom which I got package version `` KRE-svr50-x86.1.0.0-alpha3-10070 '' and also checked the `` alias '' to conform the version.Now , I wrote a console app contains following lines : and bellow the project.jsonAnd now , whenever I try to run this from Windows Poweshell it lists out missing dll ( specifically namespace System ) bellow the build output : ( both json and cs files in a same folder so no error related to json ) kpm build ( 1,12 ) : error CS0246 : The type or namespace name 'System ' could not found ( are you missing a using directive or an assembly reference ? ) How to refer the library.Please help me to find where ( what ) I 'm missing and how to fix it ... using System ; public class Program { public static void Main ( ) { Console.WriteLine ( `` Why Soo serious ! ! ! ! `` ) ; } } { `` dependencies '' : { `` System.Console '' : `` 4.0.0.0 '' } , `` configurations '' : { `` net45 '' : { } , `` k10 '' : { } } }",How to build-run vNext application from Windows Powershell ? "C_sharp : I have the following code in a WPF application using Reactive Extensions for .NET : Will there be a steady increase of memory while the mouse is moving on this dialog ? Reading the code , I would expect that the moveEvents observable will contain a huge amount of MouseEventArgs after a while ? Or is this handled in some smart way I 'm unaware of ? public MainWindow ( ) { InitializeComponent ( ) ; var leftButtonDown = Observable.FromEvent < MouseButtonEventArgs > ( this , `` MouseLeftButtonDown '' ) ; var leftButtonUp = Observable.FromEvent < MouseButtonEventArgs > ( this , `` MouseLeftButtonUp '' ) ; var moveEvents = Observable.FromEvent < MouseEventArgs > ( this , `` MouseMove '' ) .SkipUntil ( leftButtonDown ) .SkipUntil ( leftButtonUp ) .Repeat ( ) .Select ( t = > t.EventArgs.GetPosition ( this ) ) ; moveEvents.Subscribe ( point = > { textBox1.Text = string.Format ( string.Format ( `` X : { 0 } , Y : { 1 } '' , point.X , point.Y ) ) ; } ) ; }",Reactive Extensions memory usage "C_sharp : Sometimes , during service registrations , I need to resolve other ( already registered ) services from the DI container . With containers like Autofac or DryIoc this was no big deal since you could register the service on one line and on the next line you could immediately resolve it.But with Microsoft 's DI container you need to register the service , then build a service provider and only then you are able resolve the services from that IServiceProvider instance.See the accepted answer this SO question : ASP.NET Core Model Binding Error Messages LocalizationTo be able to localize the ModelBindingMessageProvider.ValueIsInvalidAccessor message , the answer suggests to resolve a IStringLocalizerFactory through the service provider built based on the current service collection.What is the cost of `` building '' the service provider at that point and are there any side effects of doing that , since the service provider will be built at least once more ( after all services are added ) ? public void ConfigureServices ( IServiceCollection services ) { services.AddLocalization ( options = > { options.ResourcesPath = `` Resources '' ; } ) ; services.AddMvc ( options = > { var F = services.BuildServiceProvider ( ) .GetService < IStringLocalizerFactory > ( ) ; var L = F.Create ( `` ModelBindingMessages '' , `` AspNetCoreLocalizationSample '' ) ; options.ModelBindingMessageProvider.ValueIsInvalidAccessor = ( x ) = > L [ `` The value ' { 0 } ' is invalid . `` ] ; // omitted the rest of the snippet } ) }",What are the costs and possible side effects of calling BuildServiceProvider ( ) in ConfigureServices ( ) "C_sharp : Now that we have tremendous functionality thanks to LINQ , I 'm wondering which syntax is preferable . For example , I found the following method ( just thought it was a good example ) : If we were to convert it to a LINQ approach , it would look like this ( not tested ) : Which would you would rather see and maintain ? Is this crazy or genius ? foreach ( FixtureImageServicesData image in _fixture.Images ) { if ( image.Filename ! = _selectedFixtureImage.Filename & & image.IsPrimary ) { image.IsPrimary = false ; image.IsChanged = true ; } } _fixture.Images.Where ( x = > x.Filename ! = _selectedFixtureImage.Filename & & x.IsPrimary ) .ForEach ( x = > { x.IsPrimary = false ; x.IsChanged = true ; } ) ;",Is it wise to use LINQ to replace loops ? "C_sharp : I understand that the behaviour of SelectMany is to effectively merge the results of each value produced into a single stream so the ordering in nondeterministic.How do I do something similar to concatAll in RxJs in C # .This is effectively what I want to do , Given a Range , Wait a bit for each then concat in the order that they started in . Obviously this is a toy example but the idea is there.Blair var obs = Observable.Range ( 1 , 10 ) .SelectMany ( x = > { return Observable.Interval ( TimeSpan.FromSeconds ( 10 - x ) ) .Take ( 3 ) ; } ) .Concat ( ) ;",Reactive Extensions SelectMany and Concat "C_sharp : I have written a WPF application which is capturing display and sound from TV Card from with through C # code . I can get the display from TV card , but I ca n't get any sound from TV Card . BTW , I 'm using .NET framework 3.5 with Visual Studio 2010 . My question is how can I get the sound from the TV card ? Lastly , I tried anything like below by using DirectSound library of DirectX . However , I got the following errors.The best overloaded method match for'Microsoft.DirectX.DirectSound.Device.SetCooperativeLevel ( System.Windows.Forms.Control , Microsoft.DirectX.DirectSound.CooperativeLevel ) ' has some invalidarguments.Argument 1 : can not convert from 'Wpfvideo.MainWindow ' to'System.Windows.Forms.Control'Code : private DS.Device soundDevice ; private SecondaryBuffer buffer ; private ArrayList soundlist = new ArrayList ( ) ; private void InitializeSound ( ) { soundDevice = new DS.Device ( ) ; soundDevice.SetCooperativeLevel ( this , CooperativeLevel.Priority ) ; BufferDescription description = new BufferDescription ( ) ; description.ControlEffects = false ; buffer = new SecondaryBuffer ( CaptureDeviceName , description , soundDevice ) ; buffer.Play ( 0 , BufferPlayFlags.Default ) ; SecondaryBuffer newshotsound = buffer.Clone ( soundDevice ) ; newshotsound.Play ( 0 , BufferPlayFlags.Default ) ; }",Capturing sound from TV Card with C # "C_sharp : I have the following lines of code : It works fine , if I stop the project and launch it again , I get the following error : [ System.IO.IOException ] = { `` The process can not access the file ' C : \website\TransList.xslt ' because it is being used by another process . `` } I then have have to goto the command line and do a IISRESET to get , I can also reset the app pool , this is easiest at this time as this is just my dev box . Now I do have the call in a try catch statement , but I can not access the xslt object in the handler.The xslt object does n't seem to have a close or dispose method . The garbage collector never gets a shot at it , it seems.Any ideas ? xslt.Load ( XmlReader.Create ( new FileStream ( @ '' C : \website\TransList.xslt '' , System.IO.FileMode.Open ) ) ) ; xslt.Transform ( mydoc.CreateReader ( ) , null , sw ) ;",How can I stop IIS 7 locking .XSLT file in C # C_sharp : Possible Duplicate : Create Generic method constraining T to an Enum Given a generic method that only operates on enum valuesHow do I constrain T such that only enum values are accepted ? I 've tried using struct however this disallows the use calling my method with a nullable enum type . static void < T > method ( T enum ) where T ? ? ? ? ? { // do something with enum ... },Generic C # method taking where the enum value as a parameter "C_sharp : Like many other people , I 've always been confused by volatile reads/writes and fences . So now I 'm trying to fully understand what these do.So , a volatile read is supposed to ( 1 ) exhibit acquire-semantics and ( 2 ) guarantee that the value read is fresh , i.e. , it is not a cached value . Let 's focus on ( 2 ) .Now , I 've read that , if you want to perform a volatile read , you should introduce an acquire fence ( or a full fence ) after the read , like this : How exactly does this prevent the read operation from using a previously cached value ? According to the definition of a fence ( no read/stores are allowed to be moved above/below the fence ) , I would insert the fence before the read , preventing the read from crossing the fence and being moved backwards in time ( aka , being cached ) .How does preventing the read from being moved forwards in time ( or subsequent instructions from being moved backwards in time ) guarantee a volatile ( fresh ) read ? How does it help ? Similarly , I believe that a volatile write should introduce a fence after the write operation , preventing the processor from moving the write forward in time ( aka , delaying the write ) . I believe this would make the processor flush the write to the main memory.But to my surprise , the C # implementation introduces the fence before the write ! UpdateAccording to this example , apparently taken from `` C # 4 in a Nutshell '' , fence 2 , placed after a write is supposed to force the write to be flushed to main memory immediately , and fence 3 , placed before a read , is supposed to guarantee a fresh read : The ideas in this book ( and my own personal beliefs ) seem to contradict the ideas behind C # 's VolatileRead and VolatileWrite implementations . int local = shared ; Thread.MemoryBarrier ( ) ; [ MethodImplAttribute ( MethodImplOptions.NoInlining ) ] // disable optimizationspublic static void VolatileWrite ( ref int address , int value ) { MemoryBarrier ( ) ; // Call MemoryBarrier to ensure the proper semantic in a portable way . address = value ; } class Foo { int _answer ; bool complete ; void A ( ) { _answer = 123 ; Thread.MemoryBarrier ( ) ; // Barrier 1 _complete = true ; Thread.MemoryBarrier ( ) ; // Barrier 2 } void B ( ) { Thread.MemoryBarrier ( ) ; // Barrier 3 ; if ( _complete ) { Thread.MemoryBarrier ( ) ; // Barrier 4 ; Console.WriteLine ( _answer ) ; } } }",Where to places fences/memory barriers to guarantee a fresh read/committed writes ? "C_sharp : I am trying to get my C # .NET Plugin to draw a table in AutoCAD with information based on a .NET form the users fills out . The code I am using to attempt this is based off this page . Modifying it for my plan , the code looks like this : This issue comes in near the bottom at this lineIt says that BlockTableRecord has no extension ModelSpace even though I took that right the the example I listed . I need to know if there is a way to fix that or if it was replaced with something else . using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using Autodesk.AutoCAD.ApplicationServices ; using Autodesk.AutoCAD.DatabaseServices ; using Autodesk.AutoCAD.EditorInput ; using Autodesk.AutoCAD.Geometry ; using Autodesk.AutoCAD.Runtime ; namespace WindowsDoors.NET { class OpeningDataTable : Table { private int rowCount = 0 ; private static Document doc = Application.DocumentManager.MdiActiveDocument ; //Current drawing private static Database db = doc.Database ; //subclass of Document , private static Editor ed = doc.Editor ; //Editor object to ask user where table goes , subclass of Document public OpeningDataTable ( bool isWindow ) { PromptPointResult pr = ed.GetPoint ( `` \nEnter table insertion point : `` ) ; if ( pr.Status == PromptStatus.OK ) { //Setting information about the table TableStyle = db.Tablestyle ; SetSize ( 2 , 5 ) ; SetRowHeight ( 3 ) ; SetColumnWidth ( 15 ) ; Position = pr.Value ; //Creating titles to add String [ ] columnTitles = new String [ 5 ] ; columnTitles [ 0 ] = `` Mark '' ; columnTitles [ 1 ] = `` Width '' ; columnTitles [ 2 ] = `` Height '' ; columnTitles [ 3 ] = `` Header\nMaterial '' ; columnTitles [ 4 ] = `` Packers\n ( Each Side ) '' ; //Adding titles to table addRow ( columnTitles ) ; } } public void addRow ( String [ ] data ) { // Use a nested loop to format each cell for ( int i = 0 ; i < data.Length ; i++ ) { ParseOption s = new ParseOption ( ) ; Cells [ rowCount , i ] .TextHeight = 1 ; Cells [ rowCount , i ] .SetValue ( data [ i ] , s ) ; } GenerateLayout ( ) ; Transaction tr = doc.TransactionManager.StartTransaction ( ) ; using ( tr ) { BlockTable bt = ( BlockTable ) tr.GetObject ( doc.Database.BlockTableId , OpenMode.ForRead ) ; BlockTableRecord btr = ( BlockTableRecord ) tr.GetObject ( bt [ BlockTableRecord.ModelSpace ] , OpenMode.ForWrite ) ; btr.AppendEntity ( this ) ; tr.AddNewlyCreatedDBObject ( this , true ) ; tr.Commit ( ) ; } } } } ( BlockTableRecord ) tr.GetObject ( bt [ BlockTableRecord.ModelSpace ] , OpenMode.ForWrite ) ;",Drawing Tables in AutoCAD "C_sharp : I am writing a program to clean excel files from empty rows and columns , i started from my own question Fastest method to remove Empty rows and Columns From Excel Files using Interop and everything is going fine.The problem is that i want to prevent excel from showing the password dialog when the workbook is password protected and to throw an exception instead of that.i am using the following code to open excel files using interop : i tried to pass an empty password as some links suggestedOr using but no luck.any suggestions ? m_XlApp = New Excel.Application m_XlApp.visible = False m_XlApp.DisplayAlerts = False Dim m_xlWrkbs As Excel.Workbooks = m_XlApp.Workbooks Dim m_xlWrkb As Excel.Workbook m_xlWrkb = m_xlWrkbs.Open ( strFile ) m_xlWrkb.DoNotPromptForConvert = true m_xlWrkb = m_xlWrkbs.Open ( strFile , Password : = '' '' ) m_xlWrkb.Unprotect ( `` '' )",Excel interop prevent showing password dialog "C_sharp : I ran into an interesting problem when I tried to use Entity Framework Core with the new nullable reference types in C # 8.0.The Entity Framework ( various flavors ) allows me to declare DBSet properties that I never initalize . For example : The DbContext constructor reflects over the type and initializes all of the DbSet properties , so I know that all the properties will be non-null by the conclusion of the constructor . If I omit the # pragma 's i get the expected warnings because my code does not initialize these properties.Turning off the warnings seems like a blunt instrument when all I want to do is inform the compiler that a property will not be null ? If turns out I can fool the compiler like this : This code has the advantage that it is very narrow -- it only applies to the specific property 's initialization and will not suppress other warnings . The disadvantage is that this is nonsense code because assigning a property to itself really ought to do nothing.Is there a preferred idiom for informing the compiler that it just does not know that the property has been initialized ? public class ApplicationDbContext : IdentityDbContext { # pragma warning disable nullable public ApplicationDbContext ( DbContextOptions < ApplicationDbContext > options ) : base ( options ) { } # pragma warning restore nullable public DbSet < Probe > Probes { get ; set ; } public DbSet < ProbeUnitTest > ProbeUnitTests { get ; set ; } } Data\ApplicationDbContext.cs ( 10,12,10,32 ) : warning CS8618 : Non-nullable property 'Probes ' is uninitialized . Data\ApplicationDbContext.cs ( 10,12,10,32 ) : warning CS8618 : Non-nullable property 'ProbeUnitTests ' is uninitialized . public ApplicationDbContext ( DbContextOptions < ApplicationDbContext > options ) : base ( options ) { Probes = Probes ; ProbeUnitTests = ProbeUnitTests ; }",How can I hint the C # 8.0 nullable reference system that a property is initalized using reflection "C_sharp : I 'm executing a Google apps script with my C # app about once every 1.5 minutes . The apps script moves content between spreadsheets , and edits sheets . I also use the Drive API.My script runs fine over long periods , except for the fact that I get an authorization errors for 5 minutes every hour.Here is my code that handles authorization : I get my services like this : But around the end of the hour , the apps script call throws the following error : Just to be clear , it works at all other times , just not in those 5 minutes near the end of the hour . I did activate Google Drive API on both my developers console , and under Resources > Advanced Google services ... in the apps script editor.So what is going on ? Can this be fixed ? class Authentication { public static ScriptService ScriptsAuthenticateOauth ( UserCredential credential ) { try { ScriptService service = new ScriptService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = `` MyApp '' , } ) ; return service ; } catch ( Exception ex ) { Console.WriteLine ( DateTime.Now.ToString ( `` HH : mm '' ) + `` : An authentication error occurred : `` + ex.InnerException ) ; return null ; } } public static UserCredential getCredential ( string clientId , string clientSecret , string userName ) { string [ ] scopes = new string [ ] { DriveService.Scope.Drive , // view and manage your files and documents DriveService.Scope.DriveAppdata , // view and manage its own configuration data DriveService.Scope.DriveAppsReadonly , // view your drive apps DriveService.Scope.DriveFile , // view and manage files created by this app DriveService.Scope.DriveMetadataReadonly , // view metadata for files DriveService.Scope.DriveReadonly , // view files and documents on your drive DriveService.Scope.DriveScripts , // modify your app scripts ScriptService.Scope.Drive , `` https : //www.googleapis.com/auth/spreadsheets '' , `` https : //spreadsheets.google.com/feeds '' , `` https : //docs.google.com/feeds '' } ; return GoogleWebAuthorizationBroker.AuthorizeAsync ( new ClientSecrets { ClientId = clientId , ClientSecret = clientSecret } , scopes , userName , CancellationToken.None , new FileDataStore ( `` Google.Sheet.Sync.Auth.Store '' ) ) .Result ; } public static DriveService DriveAuthenticateOauth ( UserCredential credential ) { try { DriveService service = new DriveService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = `` MyApp '' , } ) ; // Console.WriteLine ( `` Auth success '' ) ; return service ; } catch ( Exception ex ) { // Console.WriteLine ( ex.InnerException ) ; Console.WriteLine ( DateTime.Now.ToString ( `` HH : mm '' ) + `` : An authentication error occurred : `` + ex.InnerException ) ; return null ; } } } var credential = Authentication.getCredential ( CLIENT_ID , CLIENT_SECRET , Environment.UserName ) ; DriveService driveService = Authentication.DriveAuthenticateOauth ( credential ) ; ScriptService scriptService = Authentication.ScriptsAuthenticateOauth ( credential ) ; Script error message : Authorization is required to perform that action .",Google apps script execution API service authorization fails once per hour "C_sharp : I 've been teaching myself LINQ recently and applying it to various little puzzles . However , one of the problems I have run into is that LINQ-to-objects only works on generic collections . Is there a secret trick/ best practice for converting a non-generic collection to a generic collection ? My current implementation copies the non-generic collection to an array then operates on that , but I was wondering if there was a better way ? public static int maxSequence ( string str ) { MatchCollection matches = Regex.Matches ( str , `` H+|T+ '' ) ; Match [ ] matchArr = new Match [ matches.Count ] ; matches.CopyTo ( matchArr , 0 ) ; return matchArr .Select ( match = > match.Value.Length ) .OrderByDescending ( len = > len ) .First ( ) ; }",What 's the best way to convert non-generic collection to a generic collection ? "C_sharp : I have a following method declaration in VB and need to translate it into C # : Particularly I am not sure if it the ByRef argument specifier is equivalent to ref is C # .Also I do n't know if Shared == static and whether it must be extern.Probably lot of you are proficient in both VB and C # , so I 'd be grateful for providing correct declaration in C # . < DllImport ( `` winspool.Drv '' , EntryPoint : = '' OpenPrinterW '' , _ SetLastError : =True , CharSet : =CharSet.Unicode , _ ExactSpelling : =True , CallingConvention : =CallingConvention.StdCall ) > _Public Shared Function OpenPrinter ( ByVal src As String , ByRef hPrinter As IntPtr , ByVal pd As Int16 ) As BooleanEnd Function",VB to C # rewriting question "C_sharp : I 've seen this question asked before , but I have not seen any definite answers , and definitely not any answers that solve my problem . I created a windows service to send faxes ( semi-automatically ) using the FAXCOMEXLib library . So far , my service has been successful at sending text files ( .txt ) . But when I try to send pdf , jpg , or tif files , I get the `` Operation failed '' error . In SO , I 've seen a lot of discussion about the permissions of the user that the service is running under . I 've tried a lot of different options ( Local Service , Local User , custom user with admin privileges , allow service to interact with desktop ) . But nothing seems to make a difference . It seems that the service does not have permissions to open the appropriate app to `` print '' the pdf , jpg , or tif file . But I am only speculating . Has anyone been successful in sending a fax through FAXCOMEXLib in a Windows service ? Here is my code that sends the fax : In case you 're wondering , yes , those files do exist on the server with those names , and they are valid files ( I can open them up in Adobe Reader and Picture Viewer ) . And this also works just fine if I run this locally on my dev machine . And of course , the appropriate viewer pops up before sending ( on my local machine ) . My guess is that for some reason the service can not open the viewer . Has anyone been successful sending a PDF this way in a Windows service ? fileName = @ '' D : \temp\FaxTest.txt '' ; //THIS WORKS//fileName = @ '' D : \temp\FaxTest.pdf '' ; //Operation failed//fileName = @ '' D : \temp\FaxTest.tif '' ; //Operation failedfaxDoc.Sender.Name = faxRec.From ; faxDoc.Sender.Company = faxRec.From ; faxDoc.Body = fileName ; faxDoc.Subject = faxRec.ReferenceId ; faxDoc.DocumentName = faxRec.ReferenceId ; var to = `` xxxxxxxxxx '' ; faxDoc.Recipients.Add ( to , `` Some Name '' ) ; var serverName = Environment.MachineName ; string [ ] returnVal = faxDoc.Submit ( serverName ) ;",How can I send a fax for a pdf from a Windows Service using FAXCOMEXLib ? "C_sharp : I 'm trying to debug remotely an application that 's being hosted on Linux `` Debian GNU/Linux 8 ( jessie ) '' with.NET Command Line Tools ( 2.1.500 ) I 'm connecting via Visual Studio via SSHand I 've tried both modes : Managed .NET Core for UnixNative ( GDB ) Project has been compiled on Windowsand alsoand works perfectly fine , but for some reason I 'm receiving : Managed .NET Core for Unix : Fail to attach to process : Unable to enumerate running instances of the CoreCLR in the specific processAnd if that 's relevant ( probably not , because other people use Managed .NET Core for Unix for that ) Native ( GDB ) : Unable to start debugging . Unable to estabilish a connection to GDB . Debug output may containt more informationdebug information : In Visual Studio process is listed as : Anybody has an idea what can cause that ? You can see how people do that with Raspberry Pi here : https : //youtu.be/ySzTCl-H10w ? t=955 dotnet publish -- configuration Release -r linux-x64 dotnet publish -- configuration Debug -r linux-x64 Starting unix command : 'gdb -- interpreter=mi'bash : gdb : command not foundgdb -- interpreter=mi exited with code 127 . Process : MyProjectNameTitle : /home/deploy/app/MyProjectName StartUpArgument",Visual Studio remote debugging application hosted on Linux - unable to enumerate running instances of the CoreCLR in the specific process "C_sharp : I 'm currently writing a web services based front-end to an existing application . To do that , I 'm using the WCF LOB Adapter SDK , which allows one to create custom WCF bindings that expose external data and operations as web services.The SDK provides a few interfaces to implement , and some of their methods are time-constrained : the implementation is expected to complete its work within a specified timespan or throw a TimeoutException.Investigations led me to the question `` Implement C # Generic Timeout '' , which wisely advises to use a worker thread . Armed with that knowledge , I can write : However , the consensus is not clear about what to do with the worker thread if it times out . One can just forget about it , like the code above does , or one can abort it : Now , aborting a thread is widely considered as wrong . It breaks work in progress , leaks resources , messes with locking and does not even guarantee the thread will actually stop running . That said , HttpResponse.Redirect ( ) aborts a thread every time it 's called , and IIS seems to be perfectly happy with that . Maybe it 's prepared to deal with it somehow . My external application probably isn't.On the other hand , if I let the worker thread run its course , apart from the resource contention increase ( less available threads in the pool ) , would n't memory be leaked anyway , because work.EndInvoke ( ) never gets called ? More specifically , would n't the MetadataRetrievalNode [ ] array returned by work remain around forever ? Is this only a matter of choosing the lesser of two evils , or is there a way not to abort the worker thread and still reclaim the memory used by BeginInvoke ( ) ? public MetadataRetrievalNode [ ] Browse ( string nodeId , int childStartIndex , int maxChildNodes , TimeSpan timeout ) { Func < MetadataRetrievalNode [ ] > work = ( ) = > { // Return computed metadata ... } ; IAsyncResult result = work.BeginInvoke ( null , null ) ; if ( result.AsyncWaitHandle.WaitOne ( timeout ) ) { return work.EndInvoke ( result ) ; } else { throw new TimeoutException ( ) ; } } public MetadataRetrievalNode [ ] Browse ( string nodeId , int childStartIndex , int maxChildNodes , TimeSpan timeout ) { Thread workerThread = null ; Func < MetadataRetrievalNode [ ] > work = ( ) = > { workerThread = Thread.CurrentThread ; // Return computed metadata ... } ; IAsyncResult result = work.BeginInvoke ( null , null ) ; if ( result.AsyncWaitHandle.WaitOne ( timeout ) ) { return work.EndInvoke ( result ) ; } else { workerThread.Abort ( ) ; throw new TimeoutException ( ) ; } }","When implementing time-constrained methods , should I abort the worker thread or let it run its course ?" "C_sharp : I 've updated my ASP.NET Mvc 5 web application to use the new c # 8.0 features through Visual Studio 2019 and everything works fine until I try to use these new features inside a Razor view.For example , if I try to use the new switch expression : The compiler wo n't complain until I try to reach the page , giving me a compilation error.I suspect that Microsoft.CodeDom.Providers.DotNetCompilerPlatform must be updated but it seems that there is no update available.Is there any way to use c # 8.0 language features in Razor views ? @ { ViewBag.Title = `` About '' ; var foo = 1 ; var bar = foo switch { 1 = > `` one '' , 2 = > `` two '' , _ = > string.Empty } ; } < h2 > @ ViewBag.Title. < /h2 > < h3 > @ ViewBag.Message < /h3 > < p > Use this area to provide additional information. < /p >",How to use new c # 8.0 features in Razor views "C_sharp : I 'm currently working on a prototype in C # that utilises CQRS and event sourcing and I 've hit a performance bottleneck in my projections to an SQL database.My first prototype was built with Entity Framework 6 , code first . This choice was made primarily to get going and because the read side would benefit from LINQ . Every ( applicable ) event is consumed by multiple projections , which either create or update the corresponding entity.Such a projection currently look like this : This is n't very well performing , most likely for the reason that I call DbContext.SaveChanges ( ) in the IRepository.Save ( ) method . One for each event.What options should I explore next ? I do n't want to spent days chasing ideas that might prove to be only marginally better.I currently see the following options : Stick with EF , but batch process the events ( i.e . new/save context every X number of events ) as long as the projection is running behind.Try to do more low-level SQL , for example with ADO.NET.Do n't use SQL to store the projections ( i.e . use NoSQL ) I expect to see millions of events because we plan to source a large legacy application and migrate data in the form of events . New projections will also be added often enough so the processing speed is an actual issue.Benchmarks : The current solution ( EF , save after every event ) processes ~200 events per second ( per projection ) . It does not scale directly with the number of active projections ( i.e . N projections process less than N * 200 events/second ) .When the projections are n't saving the context , the number of events/second increases marginally ( less than double ) When the projections do n't do anything ( single return statement ) , the processing speed of my prototype pipeline is ~30.000 events/second globallyUpdated benchmarksSingle-threaded inserts via ADO.NET TableAdapter ( new DataSet and new TableAdapter on each iteration ) : ~2.500 inserts/second . Did not test with projection pipeline but standaloneSingle-threaded inserts via ADO.NET TableAdapter that does not SELECT after inserting : ~3.000 inserts/secondSingle-threaded ADO.NET TableAdapter batch-insert of 10.000 rows ( single dataset , 10.000 rows in-memory ) : > 10.000 inserts/second ( my sample size and window was too small ) public async Task HandleAsync ( ItemPlacedIntoStock @ event ) { var bookingList = new BookingList ( ) ; bookingList.Date = @ event.Date ; bookingList.DeltaItemQuantity = @ event.Quantity ; bookingList.IncomingItemQuantity = @ event.Quantity ; bookingList.OutgoingItemQuantity = 0 ; bookingList.Item = @ event.Item ; bookingList.Location = @ event.Location ; bookingList.Warehouse = @ event.Warehouse ; using ( var repository = new BookingListRepository ( ) ) { repository.Add ( bookingList ) ; await repository.Save ( ) ; } }",Improve performance of event sourcing projections to RDBMS ( SQL ) via .NET C_sharp : Does anyone know or care to speculate why implicit typing is limited to local variables ? But why not ... var thingy = new Foo ( ) ; var getFoo ( ) { return new Foo ( ) ; },Implicit typing ; why just local variables ? "C_sharp : i am programatically adding Webcontrols in to a User Control i am also adding a javascript event passing the controlID as a parameter but the clientID is the one i assigned a it does not contain the one that asp.net generatesi can workAround this by adding the parent control IDOn which Page life cycle are the Client IDs generated ? var txt = new TextBox ( ) ; txt.ID = `` MyID '' +Number ; chkBox.Attributes.Add ( `` onClick '' , `` EnableTxtBox ( ' '' +txt.ClientID + `` ' ) ; '' ) ; chkBox.Attributes.Add ( `` onClick '' , `` EnableTxtBox ( ' '' + this.ClientID+ '' _ '' +txt.ClientID + `` ' ) ; '' ) ;",On which Page life cycle are the Client IDs generated ? "C_sharp : How can I trasfrom the following sql statement into linqI have tried thisbut I am getting this error I know that it may be easy and simple . However , being new in linq , I have n't the approrpiate experience to deal with it . Any help would be appreciated . Thanks in advance . select AdsProperties.AdsProID , AdsProperties.IsActive , AdsProperties.Name , case when AdsProperties.ControlType =1 then -- TextBox 'Textbox ' when AdsProperties.ControlType =2 then -- DropDown 'Dropdown ' when AdsProperties.ControlType =3 then -- ConboBox 'ComboBox ' else -- RadioButton 'RadioButtont ' end as ControlType from CLF.utblCLFAdsPropertiesMaster as AdsProperties var query = from AdsProperties in db.utblCLFAdsPropertiesMasters select new { AdsProperties.AdsProID , AdsProperties.Name , AdsProperties.IsActive , ControlType = AdsProperties.ControlType == 1 ? ( int ? ) '' TextBox '' : null , ControlType = AdsProperties.ControlType == 2 ? ( int ? ) '' Dropdown '' : null , ControlType = AdsProperties.ControlType == 3 ? ( int ? ) '' ComboBox '' : null , ControlType = AdsProperties.ControlType == 4 ? ( int ? ) '' RadioButton '' : null ) } ; dt = query.CopyToDataTableExt ( ) ; ` an anynomous type can not have multiple properties with the same name `",select case in linq in C # "C_sharp : So here is the scenario , I am refactoring some spaghetti code . My first problem was a chain of classes that newed up other classes , I fixed this by making the ctor of the class I want to test ( Search.cs ) take the class it needs as a dependency , it looks like this now . I 'm newing it up further up the chain . That is all good but I have a little problem . The class that I am ctor injecting inherits from another class , I have Resharper and I have extracted interfaces but the problem is the dependency class inherits from another concrete class - see what I mean ? I do n't know what to do about the inheritance on DatabaseConnect ? How do I mock that ? Obviously if that was n't there I would be all set I could mock an ISearchDatabaseConnect and away we go but I am stuck on the inheritance of a concrete class . I am sure people have run into this before my googl'ing was a failure when it came to finding examples about this . Thanks in advance for any useful suggestions . public Search ( XmlAccess xmlFile , SearchDatabaseConnect searchDatabaseConnection ) { this.xmlFile = xmlFile ; FsdcConnection = searchDatabaseConnection ; Clear ( ) ; } public class SearchDatabaseConnect : DatabaseConnect , ISearchDatabaseConnect { // }",Mocking a class that inherits from another class "C_sharp : We are trying to use the ServiceStack clients on a Xamarin project and we are failing to make it work . We see that only very recently the PCL has been added to nuget , which we are trying to use right now.If we add ServiceStack.Client.Pcl v4.0.7 with the following line ( anywhere ) it fails on iOS : When debugging it , it seems to fail on PclExportClient.Instance , which returns a null reference in the constructor of ServiceClientBase . When trying the same on an Android project it does seem to work just fine.Are we doing something wrong or is the PCL simply not ready yet and should we instead try to approach it in a different way ? I have been looking at the RemoteInfo example , which does seem to work , but that is still using V3 and we prefer to work with the latest version.We 've also tried running the PclTest , but when running that we get the very same error : If you have any ideas what we are doing wrong or if you know of an alternative way to get this working on Xamarin.iOS , please let us know . var client = new JsvServiceClient ( `` http : //localhost/ '' ) ;",Using ServiceStack.Client on Xamarin.iOS "C_sharp : Hopefully this is n't too obscure for SO , but consider the following P/Invoke signature : I 'd like to redesign this signature to use SafeHandles , as follows : However , according to MSDN , the InputHandle argument must be a null pointer when the HandleType argument is SQL_HANDLE_ENV and a non-null pointer otherwise . How do I capture those semantics in a single P/Invoke signature ? Please include an example call-site in your answer . My current solution is to use two signatures . [ DllImport ( `` odbc32.dll '' , CharSet = CharSet.Unicode ) ] internal static extern OdbcResult SQLAllocHandle ( OdbcHandleType HandleType , IntPtr InputHandle , ref IntPtr OutputHandlePtr ) ; [ DllImport ( `` odbc32.dll '' , CharSet = CharSet.Unicode ) ] internal static extern OdbcResult SQLAllocHandle ( OdbcHandleType HandleType , MySafeHandle InputHandle , ref MySafeHandle OutputHandlePtr ) ;",How can a SafeHandle be used in a P/Invoke signature that requires a null pointer in certain cases ? "C_sharp : I have a class with an API that allows me to ask for objects until it throws an IndexOutOfBoundsException.I want to wrap it into an iterator , to be able to write cleaner code . However , I need to catch the exception to stop iterating : But ... When used with expression , a yield return statement can not appear in a catch block or in a try block that has one or more catch clauses . For more information , see Exception Handling Statements ( C # Reference ) .Statements ( C # Reference ) . ( from the msdn ) How can I still wrap this api ? static IEnumerable < object > Iterator ( ExAPI api ) { try { for ( int i = 0 ; true ; ++i ) { yield return api [ i ] ; // will throw eventually } } catch ( IndexOutOfBoundsException ) { // expected : end of iteration . } }",.NET iterator to wrap throwing API "C_sharp : I 'm trying to create a bitmap image , and have the following code : In order to get a ToArray ( ) extension , I came across this question . So I added : To my code . However , when I run , I get the following error : Exception thrown : 'System.ArgumentException ' in System.Runtime.WindowsRuntime.dll Additional information : The specified buffer index is not within the buffer capacity.When I drill into the details , it says in the Stack Trace : at > System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray ( IBuffer source , UInt32 sourceIndex , Int32 count ) at > System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray ( IBuffer source ) Is this method of extracting a pixel array still applicable to the UWP ? If it is , is there any way to get more detail from this error message ? RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap ( ) ; await renderTargetBitmap.RenderAsync ( uielement ) ; IBuffer pixels = await renderTargetBitmap.GetPixelsAsync ( ) ; . . .var pixelArray = pixels.ToArray ( ) ; using System.Runtime.InteropServices.WindowsRuntime ; // For ToArray",Error using using RenderTargetBitmap in UWP "C_sharp : I want to add a row using data from a ExpandoObject , which is similar to a Dictionary < string , object > . The string is the header of the column and the object 's value is value of the column.Everytime , when I get new data I 'm creating a new GridView , because the number of columns can be different . In the List myItems are all rows Dictionary < string , object > , that I want to show in my view.This is how I add the columns to my view : Direct after this I try to add the rows : I tryed to modify this solution for an other purpose . This solution works very well , if I only want to add values of the type string , but now I also want to display an image in the gridview , but if I add one to my gridview , it shows me just : `` System.Windows.Controls.Image '' Now I want to know , if I can modify my code so as I can display any type ( or at least images and strings ) in a gridview or do I have to use a completly new way and would be the way ? EDIT : In the previous approaches , it was said , that I need to create a new DataTemplate to show an image , but none of the solutions ( Solution 1 , Solution 2 ) I found is working for me . List < Column > columns = new List < Column > ( ) ; myItemValues = ( IDictionary < string , object > ) myItems [ 0 ] ; // Key is the column , value is the value foreach ( var pair in myItemValues ) { Column column = new Column ( ) ; column.Title = pair.Key ; column.SourceField = pair.Key ; columns.Add ( column ) ; } view.Columns.Clear ( ) ; foreach ( var column in columns ) { Binding binding = new Binding ( column.SourceField ) ; if ( column.SourceField == `` Icon '' ) { view.Columns.Add ( new GridViewColumn { Header = column.Title , DisplayMemberBinding = binding , CellTemplate = new DataTemplate ( typeof ( Image ) ) } ) ; } else { view.Columns.Add ( new GridViewColumn { Header = column.Title , DisplayMemberBinding = binding } ) ; } } foreach ( dynamic item in myItems ) { this.listView.Items.Add ( item ) ; }",Add column to listview that contains an image "C_sharp : I have a actionresult that I think is pretty heavy , so I wonder how can I optimize it so it gets better performance . This web application will be used for by +100 , 000 users at same time.Right now my Actionresult does the following things : Retrieve XML file from a internet urlFills the xml data to my DBDB data fills my ViewmodelReturns the model to the viewThis 4 functions triggers everytime a user visits the view . This is why I think this Actionresult is very badly made by me . How can I add this following things to my Actionresults ? add a timer to retrieve XML file and fill xml data to DB , like every 10 minute , so it doesnt trigger everytime a user visits the view . The only function that needs to trigger everytime a user visits the site is the viewmodel binding and returning the model . How can I accomplish this ? Note : the xml file gets updated with new data every 10 min or so.I have around 50 actionresults that does the same get xml data and adds to database but 50 different xml files.If the xml URL is offline it should skip the whole xml retrieve and DB add and just do the modelbindingThis is my actionresult : Right now everytime a user visits the index view , it will get XML data and add it to the DB , so the bad fix Ive done in my repository is following on addNews : Any kind of solution and info is highly appreciated ! public ActionResult Index ( ) { //Get data from xml url ( This is the code that shuld not run everytime a user visits the view ) var url = `` http : //www.interneturl.com/file.xml '' ; XNamespace dcM = `` http : //search.yahoo.com/mrss/ '' ; var xdoc = XDocument.Load ( url ) ; var items = xdoc.Descendants ( `` item '' ) .Select ( item = > new { Title = item.Element ( `` title '' ) .Value , Description = item.Element ( `` description '' ) .Value , Link = item.Element ( `` link '' ) .Value , PubDate = item.Element ( `` pubDate '' ) .Value , MyImage = ( string ) item.Elements ( dcM + `` thumbnail '' ) .Where ( i = > i.Attribute ( `` width '' ) .Value == `` 144 '' & & i.Attribute ( `` height '' ) .Value == `` 81 '' ) .Select ( i = > i.Attribute ( `` url '' ) .Value ) .SingleOrDefault ( ) } ) .ToList ( ) ; //Fill my db entities with the xml data ( This is the code that shuld not run everytime a user visits the view ) foreach ( var item in items ) { var date = DateTime.Parse ( item.PubDate ) ; if ( ! item.Title.Contains ( `` : '' ) & & ! ( date < = DateTime.Now.AddDays ( -1 ) ) ) { News NewsItem = new News ( ) ; Category Category = new Category ( ) ; var CategoryID = 2 ; var WorldCategoryID = re.GetByCategoryID ( CategoryID ) ; NewsItem.Category = WorldCategoryID ; NewsItem.Description = item.Description ; NewsItem.Title = item.Title.Replace ( `` ' '' , `` '' ) ; NewsItem.Image = item.MyImage ; NewsItem.Link = item.Link ; NewsItem.Date = DateTime.Parse ( item.PubDate ) ; re.AddNews ( NewsItem ) ; re.save ( ) ; } } //All code below this commenting needs to run everytime a user visits the view var GetAllItems = re.GetAllWorldNewsByID ( ) ; foreach ( var newsitemz in GetAllItems ) { if ( newsitemz.Date < = DateTime.Now.AddDays ( -1 ) ) { re.DeleteNews ( newsitemz ) ; re.save ( ) ; } } var model = new ItemViewModel ( ) { NewsList = new List < NewsViewModel > ( ) } ; foreach ( var NewsItems in GetAllItems ) { FillProductToModel ( model , NewsItems ) ; } return View ( model ) ; } public void AddNews ( News news ) { var exists = db.News.Any ( x = > x.Title == news.Title ) ; if ( exists == false ) { db.News.AddObject ( news ) ; } else { db.News.DeleteObject ( news ) ; } }",How can I optimize this actionresult for better performance ? I need put put a timer on when to `` GET '' XML data from a url and etc "C_sharp : I was wondering if someone might be able to demonstrate how to use Type 's GetMethod ( ) method to retrieve a MethodInfo object for the following signature : Thanks , Xam Class.StaticMethod < T > ( T arg1 , IInterface1 arg2 , IEnumerable < IInterface2 > arg3 )",How to get the correct MethodInfo object when a class uses generics and generic type parameters "C_sharp : After checking these SO articles : cascade-delete-in-entity-framework , ef6-1-soft-delete-with-cascade-delete , cascading-soft-delete , method-for-cascading-soft-deletes-in-parent-child-relationships and reasons-for-cascading-soft-deletes and not finding a solution ... I have SoftDelete working for my Entity Models . I have overridden SaveChanges ( ) in my Context : I have set CascadeOnDelete for my Child Entities . Because I override the deleted EntityState it does n't cascade . Does anybody know a way to put only the Navigation properties in a foreach loop ? Or a better way to handle SoftDeletes ? Thank you in advance , public override int SaveChanges ( ) { ChangeTracker.DetectChanges ( ) ; foreach ( DbEntityEntry < ISoftDeletable > entity in ChangeTracker.Entries < ISoftDeletable > ( ) ) { if ( entity.State == EntityState.Deleted ) { entity.State = EntityState.Modified ; entity.Entity.IsDeleted = true ; } } return base.SaveChanges ( ) ; }",How do I Cascade a SoftDelete ? "C_sharp : From the book : The assignments in 3 ) is illegal because int is not a reference type and so int [ ] is not implicitly convertible to Object [ ] I do n't get this . on line 2 ) it shows that int is implicitly convertible to Object , and in the third line , it says int [ ] is not implicitly convertable . wha ? ? 1 ) int i = 7 ; 2 ) Object o = i ; // Implicit boxing int -- > Object3 ) Object [ ] a3 = new int [ ] { 1 , 2 } ; // Illegal : no array conversion","Confused about boxing , casting , implicit etc" "C_sharp : I was just experimenting to see what happens when a cold task ( i.e . a Task which has n't been started ) is awaited . To my surprise the code just hung forever and `` Finsihed '' is never printed . I would expect that an exception is thrown.Then I though perhaps the task can be started from another thread , so I changed the code to : But it is still blocked at task1.Wait ( ) . Does anyone know if there is way to start a cold task after it has being awaited ? Otherwise it seems there is no point in being able to await a cold task , so perhaps the task should either be started when awaited or an exception should be thrown.UpdateI was awaiting the wrong task , i.e . the outer task returned by Test1 rather than the one newed inside it . The InvalidOperationException mentioned by @ Jon Skeet was being thrown inside Task.Run however because the resulting task was not observed , the exception was not thrown on the main thread . Putting a try/catch inside Task.Run or calling Wait ( ) or Result on the task returned by Task.Run threw the exception on the main console thread . public async Task Test1 ( ) { var task = new Task ( ( ) = > Thread.Sleep ( 1000 ) ) ; //task.Start ( ) ; await task ; } void Main ( ) { Test1 ( ) .Wait ( ) ; Console.WriteLine ( `` Finished '' ) ; } public async Task Test1 ( ) { var task = new Task ( ( ) = > Thread.Sleep ( 1000 ) ) ; //task.Start ( ) ; await task ; Console.WriteLine ( `` Test1 Finished '' ) ; } void Main ( ) { var task1 = Test1 ( ) ; Task.Run ( ( ) = > { Task.Delay ( 5000 ) ; task1.Start ( ) ; } ) ; task1.Wait ( ) ; Console.WriteLine ( `` Finished '' ) ; }",Why awaiting cold Task does not throw C_sharp : I 'm trying to do something likeIs this doable somehow ? string heading = $ '' Weight in { imperial ? `` lbs '' : '' kg '' } '',How do I use string interpolation with string literals ? C_sharp : This LINQ query expression fails with Win32Exception `` Access is denied '' : And this fails with IOException `` The device is not ready '' : What is the best way to filter out inaccessible objects and avoid exceptions ? Process.GetProcesses ( ) .Select ( p = > p.MainModule.FileName ) DriveInfo.GetDrives ( ) .Select ( d = > d.VolumeLabel ),Try-Catch with fluent expressions "C_sharp : In my project I use the following class : Filter < T > .Checker < U > which also has the interface IChecker . It looks like this : The Filter class filters objects of type T. The filter uses the IChecker list to check different fields in the class T in which U is the type of this field in T.In some other method in a different class I want to create an instance of a checker . In that method the type of T is Transaction , which is know at compile time . The type of U is only known by a Type instance . The code below show how you would normally create an instance of generic class knowing the Type.I want to take this a little bit further and do the following : The part typeof ( Filter < Transaction > .Checker < > ) does n't compile . The compiler says : Unexpected use of an unbounded generic name . Is it possible get the type of a nested Generic class in a Generic class in C # ? class Filter < T > { public interface IChecker { ... } public class Checker < U > : IChecker { ... } List < IChecker > checkers ; ... } Type type = typeof ( MyObject < > ) .MakeGenericType ( objectType ) ; object myObject = Activator.CreateInstance ( type ) ; Type type = typeof ( Filter < Transaction > .Checker < > ) .MakeGenericType ( objectType ) ; object myObject = Activator.CreateInstance ( type ) ;",Get Type of a nested Generic class in a Generic class in C # "C_sharp : I want to migrate my code from Newtonsoft Json.Net to MicroSoft standard System.Text.Json . But I could not find an alternative for JToken.DeepEqualBasically the code must compare two JSON in unit Test . Reference JSON , and Result JSON . I used the mechanism in Newtonsoft to create two JObject and after compare it with JToken.DeepEqual . Here is the example code : If I am correct the Newtonsoft JObject similar in System.Text.Json.JsonDocument , and I am able to create it , just I do n't know how to compare the contents of it.Of course , the string compare is not a solution , because the format of the JSON is does n't matter and the order of the properties also not matter . [ TestMethod ] public void ExampleUnitTes ( ) { string resultJson = TestedUnit.TestedMethod ( ) ; string referenceJson = @ '' { ... bla bla bla ... ... some JSON Content ... ... bla bla bla ... } '' ; JObject expected = ( JObject ) JsonConvert.DeserializeObject ( referenceJson ) ; JObject result = ( JObject ) JsonConvert.DeserializeObject ( resultJson ) ; Assert.IsTrue ( JToken.DeepEquals ( result , expected ) ) ; } System.Text.Json.JsonDocument expectedDoc = System.Text.Json.JsonDocument.Parse ( referenceJson ) ; System.Text.Json.JsonDocument resultDoc = System.Text.Json.JsonDocument.Parse ( json ) ; Compare ? ? ? ( expectedDoc , resulDoc ) ;",What is equivalent in JToken.DeepEqual in System.Text.Json "C_sharp : How to iterate through pure JSON Array like the following , in C # Newtonsoft ? or , All the existing answers that I found on SO are in KeyValuePair format , not this pure JSON Array format . Thx . [ 78293270 , 847744 , 32816430 ] [ `` aa '' , `` bb '' , `` cc '' ] JArray array = JsonConvert.DeserializeObject < JArray > ( json ) ; foreach ( JObject item in array ) { // now what ? }",JSON Array Iteratiion in C # Newtonsoft "C_sharp : This is within a xaml file.I need to mask a box 's input with a regular expression.I need it to contain either 10 numbers or 13 numbers ( in sequence , with no symbols ) I have : which works fine , but when i want to add a mask of ten in , it breaks : Any ideas ? < ... ValidationRegEx= '' \d { 13 } '' / > < ... ValidationRegEx= '' \d { 13 } | \d { 10 } '' / >",How to mask input by regular expressions ? either 1112223333 or 1112223333444 "C_sharp : I can not for the life of me figure out whats going on and who I ca n't post to my service using json . I 've tried reading every comment under the sun from google on the issues I have but everything is currently bringing me to a dead end . Please help ! I pass the postback service off to a third party by a callback URL in a post to a service . The Third party then posts back in Json back to my wcf service using the call back url . I have no problem with the initial post but they and myself are not able to hit the callback service . I tried yet Fiddler returns a 400 error but i 'm not sure why . I need a little more than web links and such to fix this problem . please help ! Web.config fileWeb InterfaceTest Clientcurrent trace log . < system.serviceModel > < services > < service behaviorConfiguration= '' serviceBehavior '' name= '' IBVWebService.InstantBankVerificationPostBack '' > < endpoint address= '' http : //localhost:64337/InstantBankVerificationPostBack.svc '' behaviorConfiguration= '' web '' binding= '' webHttpBinding '' contract= '' IBVWebService.IInstantBankVerificationPostBack '' > < /endpoint > < endpoint contract= '' IMetadataExchange '' binding= '' mexHttpBinding '' address= '' mex '' / > < /service > < /services > < behaviors > < endpointBehaviors > < behavior name= '' web '' > < webHttp/ > < /behavior > < /endpointBehaviors > < serviceBehaviors > < behavior name= '' serviceBehavior '' > < serviceMetadata httpGetEnabled= '' true '' / > < serviceDebug includeExceptionDetailInFaults= '' false '' / > < /behavior > < /serviceBehaviors > < /behaviors > [ OperationContract ] [ WebInvoke ( Method = `` POST '' , BodyStyle = WebMessageBodyStyle.WrappedRequest , RequestFormat = WebMessageFormat.Json ) ] void PostBack ( String json ) ; WebClient client = new WebClient ( ) ; client.Headers [ `` Content-type '' ] = `` application/json '' ; client.Encoding = System.Text.Encoding.UTF8 ; string jsonInput = `` { 'data ' : 'testvalue ' } '' ; client.UploadString ( `` http : //localhost:64337/InstantBankVerificationPostBack.svc/PostBack '' , jsonInput ) ;",WCF service using Json Bad Request "C_sharp : As I progress on my little math library I 'm stumbling upon certain aspects of C # and the .NET Framework that I 'm having some trouble understanding.This time it 's operator overloading and specifically the term overloading itself . Why is it called overloading ? Do all objects by default have an implementation of all operators ? That is , is : predefined somewhere and somehow ? If so , why then if I try o1 + o2 I get the compile time error Operator '+ ' can not be applied to operands of type 'object ' and 'object ' ? This would somehow imply that by default objects do not have predefined operators so then how come the term overloading ? I ask this , because in my math library , working with 3D geometry elements , I have the following structs : Vector and Point . Now , internally I want to allow the following construct to create vectors : As this is not mathematically 100 % correct but very useful internally to reduce code clutter , I do n't want to expose this operator publicly , so my initial intention was to simply do : Surprisingly ( for me ) I got the following compile time error : User-defined operator 'Geometry.operator + ( Geometry.Vector , Geometry.Vector ) ' must be declared static and public '' .Now this restriction that all operators must be public does seem to make some sense with the whole overloading aspect of operators but it seems that it is all kind of inconsistent : Objects by default do not have predefined operators : I ca n't do object + object by default or myTpye + myType without explicitly defining the + operator beforehand.Defining operators is not described as creating an operator , it 's described as overloading which somehow is inconsistent ( to me ) with point 1.You can not restrict access modifier of an operator , they have to be public , which does not make sense considering point 1. but sort of makes sense considering point 2.Can somebody explain the mess I 'm making of all this in simple terms ? public static object operator + ( object o1 , object o2 ) static Vector operator - ( Point p1 , Point p2 ) { ... } internal static Vector operator - ( Point p1 , Point p2 ) { ... }",Confused about operator overloading "C_sharp : I am having a method called LoadData which gets data from DataBase and fills a DataGridView.I am using a Stopwatch to measure how long my method takes to finish it 's job as below : I want something that can do The following : so that I can pass the LoadData method to it and it does the rest for me.How can I do that ? private void btnLoadData_Click ( object sender , EventArgs e ) { var sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; LoadData ( ) ; sw.Stop ( ) ; ShowTakenTime ( sw.ElapsedMilliseconds ) ; } private void MeasureTime ( Method m ) { var sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; m.Invoke ( ) ; sw.Stop ( ) ; ShowTakenTime ( sw.ElapsedMilliseconds ) ; } MeasureTime ( LoadData ( ) ) ;",Pass a method as a parameter to another method "C_sharp : I have developed a point of sale system using MVC 4.The responsiveness and loading times on Windows and Mac is instant but on an iPad it takes 8-13 seconds to load a page or perform an action such as adding items to basket . To improve the speed of the web application I enabled compression in IIS and minified all my java script files I also used bundling to bundle the following .js files together which supposedly improves loading of pages as well : jquery-1.8.2.min.jsknockout-2.2.0.jsjquery.easing.1.3.jsb.popup.min.js ( used for displaying a modal popup only 6KB ) The other javascript files I use on pages are between 5KB and 15KB.After doing all this the application seems to be a few seconds quicker , but still takes unacceptably long ( 8-10 seconds ) .Has anyone experienced similar performance issues on an iPad and how did you resolve it ? Is there anything else I can do to improve performance ? I 'm using Windows Server 2003 and IIS 6.0Here 's my bundle registration code : And this is where I call it on the master page : public static void RegisterBundles ( BundleCollection bundles ) { bundles.Add ( new ScriptBundle ( `` ~/bundles/jquery '' ) .Include ( `` ~/Scripts/jquery-1.8.2.min.js '' , `` ~/Scripts/jquery.easing.1.3.js '' , `` ~/Scripts/knockout-2.2.0.js '' , `` ~/Scripts/common/common.min.js '' , `` ~/Scripts/popup.min.js '' ) ) ; bundles.Add ( new StyleBundle ( `` ~/Content/css '' ) .Include ( `` ~/Content/site.css '' ) ) ; BundleTable.EnableOptimizations = true ; } @ using System.Configuration < ! DOCTYPE html > < html > < head > < meta charset= '' utf-8 '' / > < meta name= '' viewport '' content= '' width=device-width '' / > < meta name= '' apple-mobile-web-app-capable '' content= '' yes '' > < title > Prestige SSC < /title > @ Scripts.Render ( `` ~/bundles/jquery '' ) @ RenderSection ( `` scripts '' , required : false ) @ Styles.Render ( `` ~/Content/css '' ) < script type= '' text/javascript '' > var screenRefreshTime = ' @ ConfigurationManager.AppSettings [ `` ScreenRefreshTime '' ] .ToString ( ) ' ; screenRefreshTime = parseInt ( screenRefreshTime ) ; < /script > < /head > < body > @ RenderBody ( ) < /body > < /html >",MVC 4 website very slow on iPad "C_sharp : I create a new AWS Lambda .NET Core 3.1 project , then run it using AWS Lambda Test Tools , then I get this page as expected : However , if I install one of these packages : Microsoft.EntityFrameworkCore.SqlServerMicrosoft.Data.SqlClientWhen I run , I get this error and the test page wo n't open : I have a .NET Core 2.1 Lambda project with this package and it works fine , it only fails in .NET Core 3.1.Below is my .csproj in case anyone wants to give a try.This works fine deployed on AWS Lambda , it only fails running it locally with the Mock Tools.Removing Microsoft.EntityFrameworkCore.SqlServer makes it work again.This was also posted in github a while ago , I 'm hoping someone else ran into this and has a fix . AWS .NET Core 3.1 Mock Lambda Test Tool ( 0.10.0 ) Unknown error occurred causing process exit : Dependency resolution failed for component C : \Users\siri\repos\bolao-futebol\website-core\AWSLambda1\bin\Debug\netcoreapp3.1\AWSLambda1.dll with error code -2147450740 . Detailed error : Error : An assembly specified in the application dependencies manifest ( AWSLambda1.deps.json ) was not found : package : 'runtime.win-x64.runtime.native.System.Data.SqlClient.sni ' , version : ' 4.4.0'path : 'runtimes/win-x64/native/sni.dll'at System.Runtime.Loader.AssemblyDependencyResolver..ctor ( String componentAssemblyPath ) at Amazon.Lambda.TestTool.Runtime.LambdaAssemblyLoadContext..ctor ( String lambdaPath ) in C : \codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LambdaAssemblyLoadContext.cs : line 28at Amazon.Lambda.TestTool.Runtime.LocalLambdaRuntime.Initialize ( String directory , IAWSService awsService ) in C : \codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LocalLambdaRuntime.cs : line 71at Amazon.Lambda.TestTool.Runtime.LocalLambdaRuntime.Initialize ( String directory ) in C : \codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\Runtime\LocalLambdaRuntime.cs : line 46at Amazon.Lambda.TestTool.TestToolStartup.Startup ( String productName , Action ` 2 uiStartup , String [ ] args , RunConfiguration runConfiguration ) in C : \codebuild\tmp\output\src142363207\src\Tools\LambdaTestTool\src\Amazon.Lambda.TestTool\TestToolStartup.cs : line 77 < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < TargetFramework > netcoreapp3.1 < /TargetFramework > < GenerateRuntimeConfigurationFiles > true < /GenerateRuntimeConfigurationFiles > < AWSProjectType > Lambda < /AWSProjectType > < /PropertyGroup > < ItemGroup > < PackageReference Include= '' Amazon.Lambda.Core '' Version= '' 1.1.0 '' / > < PackageReference Include= '' Amazon.Lambda.Serialization.SystemTextJson '' Version= '' 1.0.0 '' / > < PackageReference Include= '' Amazon.Lambda.SQSEvents '' Version= '' 1.1.0 '' / > < PackageReference Include= '' Amazon.Lambda.AspNetCoreServer '' Version= '' 5.0.0 '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.SqlServer '' Version= '' 3.1.0 '' / > < /ItemGroup > < /Project >",.NET Core 3.1 - Dependency resolution failed for component - AWS Mock Lambda Test Tools "C_sharp : I 'm trying to compile an assembly from my code with C # code provider.When I access the compiled assembly with compilerResult.CompiledAssembly , everything works . However , when I instead do Assembly.Load ( path ) , I get the following exception : System.IO.FileLoadException : Could not load file or assembly ' C : \Users\Name\Desktop\output.dll ' or one of its dependencies . The given assembly name or codebase was invalid . ( Exception from HRESULT : 0x80131047 ) What am I doing wrong ? Here 's the code : [ Test ] public static void CompileCodeIntoAssembly ( ) { var code = `` public class X { } '' ; var file = Path.Combine ( Environment.GetFolderPath ( Environment.SpecialFolder.Desktop ) , `` output.cs '' ) ; File.WriteAllText ( file , code ) ; using ( var provider = new CSharpCodeProvider ( ) ) { var parameters = new CompilerParameters { GenerateInMemory = false , // we want the dll saved to disk GenerateExecutable = false , CompilerOptions = `` /target : library /lib : \ '' '' + typeof ( Class2 ) .Assembly.Location + `` \ '' '' , OutputAssembly = Path.Combine ( Environment.GetFolderPath ( Environment.SpecialFolder.Desktop ) , `` output.dll '' ) , } ; parameters.ReferencedAssemblies.AddRange ( new [ ] { `` System.dll '' , typeof ( Class1 ) .Assembly.Location , } ) ; var compilerResult = provider.CompileAssemblyFromFile ( parameters , file ) ; if ( compilerResult.Errors.Count > 0 ) { compilerResult.Errors.Cast < object > ( ) .ToDelimitedString ( Environment.NewLine ) .Dump ( ) ; throw new Exception ( ) ; } var assembly = Assembly.Load ( parameters.OutputAssembly ) ; //var assembly = compilerResult.CompiledAssembly ; // this method works var type = assembly.GetTypes ( ) .Single ( t = > t.Name == `` X '' ) ; }",Weird Assembly.Load error trying to load assembly compiled with C # code provider "C_sharp : I 'm running code that sometimes yields this : It appears for any value > = 32 , only the value % 32 is shifted . Is there some `` optimization '' occurring in the framework ? UInt32 current ; int left , right ; ... //sometimes left == right and no shift occurscurrent < < = ( 32 + left - right ) ; //this workscurrent < < = ( 32 - right ) ; current < < = left ;",C # : Shift left assignment operator behavior "C_sharp : Given the following sample codes : What is the difference betweenand ? In this example , the second statement generates compile error while the first one does not . static void SomeMethod ( ) { Action < int , int > myDelegate ; // ... myDelegate = delegate { Console.WriteLine ( 0 ) ; } ; myDelegate = delegate ( ) { Console.WriteLine ( 0 ) ; } ; // compile error } myDelegate = delegate { Console.WriteLine ( 0 ) ; } ; myDelegate = delegate ( ) { Console.WriteLine ( 0 ) ; } ;",Assigning anonymous method to delegate using parentheses gives compiler error ? "C_sharp : If I try an invalid cast from a class to an interface , then the compiler does n't complain ( the error occurs at runtime ) ; it does complain , however , if I try a similar cast to an abstract class.Why does n't the compiler reject the cast from Foo to IBar , when it 's ( seemingly ? ) invalid ? Or , to flip the question , if the compiler allows this `` invalid '' cast to the interface IBar , why does n't it allow the similar `` invalid '' cast to the abstract class aBaz ? class Program { abstract class aBaz { public abstract int A { get ; } } interface IBar { int B { get ; } } class Foo { public int C { get ; } } static void Main ( ) { Foo foo = new Foo ( ) ; // compiler error , as expected , since Foo does n't inherit aBaz aBaz baz = ( aBaz ) foo ; // no compiler error , even though Foo does n't implement IBar IBar bar = ( IBar ) foo ; } }",Why no compiler error when I cast a class to an interface it does n't implement ? "C_sharp : I 've inherited a VS-2015 C # application and would like to migrate it to VS 2017 or 2019 . It has a packages.config file with 4 packages : The first few lines of the project 's sln file are : I 'd like to migrate the packages.config file to a csproj file.In Visual Studio 2017 , I tried migrating it by right-clicking on packages.config and clicking 'Migrate packages.config to PackageReference ' , but it gives me an error - `` Operation Failed - Project is not Eligible for Migration . '' I also tried this tool : https : //github.com/hvanbakel/CsprojToVs2017and this also fails.Is there really no way to migrate this to csproj ? < package id= '' AjaxControlToolkit '' version= '' 15.1.4.0 '' targetFramework= '' net4 '' / > < package id= '' EntityFramework '' version= '' 6.0.0 '' targetFramework= '' net4 '' / > < package id= '' Microsoft.AspNet.Providers '' version= '' 2.0.0 '' targetFramework= '' net4 '' / > < package id= '' Microsoft.AspNet.Providers.Core '' version= '' 2.0.0 '' targetFramework= '' net4 '' / > Microsoft Visual Studio Solution File , Format Version 12.00 # Visual Studio 14VisualStudioVersion = 14.0.25420.1MinimumVisualStudioVersion = 10.0.40219.1Project ( `` { E24C65DC-7377-472B-9ABA-BC803B73C61A } '' )",VS 2015 to 2017 migrate to package reference failed "C_sharp : What is best way to loop through an enumeration looking for a matching value ? string match = `` A '' ; enum Sample { A , B , C , D } foreach ( ... ) { //should return Sample.A }",Loop through enumeration "C_sharp : I am using DBContext.Database.SqlQuery < entity > to execute stored procedure from my C # code repository.It works fine but I want to know that why it is executing procedure like below : rather than And is there any way that my all procedures execute from c # like thisEXEC GetCaseList @ CaseStage = 9 rather than exec sp_executesql N'EXEC GetCaseList @ CaseStage ' , N ' @ CaseStage int ' , @ CaseStage=9 ? How can I make SQL Server Profiler to treat procedure name as object rather than SP_EXECUTESQL ? Note : I want to execute procedure from c # as EXEC GetCaseList @ CaseStage = 9 because I am saving trace data through SQL Server Profiler in table format . And in ObjectName column , it is showing sp_executesql as object rather than procedure name ( GetCaseList ) as object . I can make changes only from c # code . exec sp_executesql N'EXEC GetCaseList @ CaseStage ' , N ' @ CaseStage int ' , @ CaseStage=9 EXEC GetCaseList @ CaseStage = 9",SQL Server Recognise SP_EXECUTESQL as object rather than Procedure Name "C_sharp : We have to integrate our project with back end Oracle Platform . And this integration is via various WebServices . I have all WSDLs and XSDs for all these integrations . And I need to generate DataContracts from these WSDLs & XSDs.Now the problem is , mostly all of these integration shares some common data types . and I want to reuse them.e.g , in this case , I want to reuse the oracle.common.CommonDataTypes between integration1 & 2.so far I have tried WSCF.blue & WSCF . But these tools generating all the code in a single folder ( and single namespace ) and not following namespaces.I want to generate classes under namespaces like oracle , oracle.commonData , oracle.integration1 , oracle.ebo etc.so is that any way that generated Datacontracts follows exact namespace notation as the XSDs have ? Integration1 : oracle/common/commonDataTypes.xsd oracle/integration1/someXSD.xsd oracle/ebo/baseTypes.xsdIntegration2 : oracle/common/commonDataTypes.xsd oracle/integration2/someXSD.xsd oracle/ebo/baseTypes.xsdIntegration3 : oracle/commonDataTypes.xsd oracle/integration2/someXSD.xsd oracle/ebo/baseTypes.xsd",Generating DataContracts with exact namespace as in XSD "C_sharp : Does anyone know how to move my SDL.net video surface around the screen programtically ? I ca n't find any properties in Surface or Video which do the job , and FromHandle is returning Null.The window is initializing falling off the bottom of the screen.Any ideas ? Update : I 've seen this code but ca n't work out an equivilent C # implimentation . Can anyone help ? Failing that , how much work is involved in including some c++ in my c # project ? Thanks . Surface videoContext = Video.SetVideoMode ( 1024 , 768 , 32 , false , false , false , true , true ) ; var a = System.Windows.Forms.Control.FromHandle ( Video.WindowHandle ) ; var b = System.Windows.Forms.NativeWindow.FromHandle ( Video.WindowHandle ) ; # ifdef WIN32 # include < SDL_syswm.h > SDL_SysWMinfo i ; SDL_VERSION ( & i.version ) ; if ( SDL_GetWMInfo ( & i ) ) { HWND hwnd = i.window ; SetWindowPos ( hwnd , HWND_TOP , x , y , width , height , flags ) ; }",moving SDL video surface "C_sharp : Just started learning C # . I plan to use it for heavy math simulations , including numerical solving . The problem is I get precision loss when adding and subtracting double 's , as well as when comparing . Code and what it returns ( in comments ) is below : Would appreciate any help and clarifications ! What puzzles me is that ( x + foo ) ==foo returns True . namespace ex3 { class Program { static void Main ( string [ ] args ) { double x = 1e-20 , foo = 4.0 ; Console.WriteLine ( ( x + foo ) ) ; // prints 4 Console.WriteLine ( ( x - foo ) ) ; // prints -4 Console.WriteLine ( ( x + foo ) ==foo ) ; // prints True BUT THIS IS FALSE ! ! ! } } }","Double comparison precision loss in C # , accuracy loss happening when adding subtracting doubles" "C_sharp : Does LINQ have a way to `` memorize '' its previous query results while querying ? Consider the following case : Now , if two or more Foo have same collection of Bar ( no matter what the order is ) , they are considered as similar Foo . Example : In the above case , foo1 is similar to foo2 but both foo1 and foo2 are not similar tofoo3Given that we have a query result consisting IEnumerable or IOrderedEnumerable of Foo . From the query , we are to find the first N foo which are not similar . This task seems to require a memory of the collection of bars which have been chosen before.With partial LINQ we could do it like this : The topNFoos List will serve as a memory of the previous query and we can skip the Foo q in the foreach loop which already have identical Bars with Any of the Foo in the topNFoos.My question is , is there any way to do that in LINQ ( fully LINQ ) ? If the `` memory '' required is from a particular query item q or a variable outside of the query , then we could use let variable to cache it : But if it must come from the previous querying of the query itself then things start to get more troublesome.Is there any way to do that ? Edit : ( I currently am creating a test case ( github link ) for the answers . Still figuring out how can I test all the answers fairly ) ( Most of the answers below are aimed to solve my particular question and are in themselves good ( Rob 's , spender 's , and David B 's answers which use IEqualityComparer are particularly awesome ) . Nevertheless , if there is anyone who can give answer to my more general question `` does LINQ have a way to `` memorize '' its previous query results while querying '' , I would also be glad ) ( Apart from the significant difference in performance for the particular case I presented above when using fully/partial LINQ , one answer aiming to answer my general question about LINQ memory is Ivan Stoev 's . Another one with good combination is Rob 's . As to make myself clearer , I look for general and efficient solution , if there is any , using LINQ ) public class Foo { public int Id { get ; set ; } public ICollection < Bar > Bars { get ; set ; } } public class Bar { public int Id { get ; set ; } } foo1.Bars = new List < Bar > ( ) { bar1 , bar2 } ; foo2.Bars = new List < Bar > ( ) { bar2 , bar1 } ; foo3.Bars = new List < Bar > ( ) { bar3 , bar1 , bar2 } ; private bool areBarsSimilar ( ICollection < Bar > bars1 , ICollection < Bar > bars2 ) { return bars1.Count == bars2.Count & & //have the same amount of bars ! bars1.Select ( x = > x.Id ) .Except ( bars2.Select ( y = > y.Id ) ) .Any ( ) ; //and when excepted does not return any element mean similar bar } public void somewhereWithQueryResult ( ) { . . List < Foo > topNFoos = new List < Foo > ( ) ; //this serves as a memory for the previous query int N = 50 ; //can be any number foreach ( var q in query ) { //query is IOrderedEnumerable or IEnumerable if ( topNFoos.Count == 0 || ! topNFoos.Any ( foo = > areBarsSimilar ( foo.Bars , q.Bars ) ) ) topNFoos.Add ( q ) ; if ( topNFoos.Count > = N ) //We have had enough Foo break ; } } var topNFoos = from q in query //put something select q ; int index = 0 ; var topNFoos = from q in query let qc = index++ + q.Id //depends on q or variable outside like index , then it is OK select q ;",LINQ with Querying `` Memory '' "C_sharp : I dont know if what I 'd like to do is simply not possible : or I 'm not thinking about it in the correct way.I 'm trying to construct a repository interface class which accepts a generic type and uses this as the basis for the return on most of its methods , ie : This would then be inherited by an actual repository class , like so : The idea is that within a ClientRepository , for example , I will want to perform operations against a few different object types ( ClientAccount , ClientEmailAddress etc ) ; but in the main the types of operations needed are all the same.When I try to use the TestClientRepository ( after implementing the Interfaces explicitly ) I can not see the multiple Find and Add methods . Can anyone help ? Thanks . public interface IRepository < T > { void Add ( T source ) ; T Find ( int id ) ; } public class TestClientRepository : IRepository < ClientEmailAddress > , IRepository < ClientAccount > { }",C # interfaces with same method name "C_sharp : I created a asp : Repeater that I fill with .ascx controls : On page I have : Inside Product.ascx.cs I have : On Product.ascx I have : Problem is when I click on image button I get error : I have tried to change first code to this : But then when I click on image button ImportantData is empty.What I did wrong here ? protected void Page_Load ( object sender , EventArgs e ) { Repeater1.DataSource = listOfData ; Repeater1.DataBind ( ) ; } < uc : Product runat= '' server '' ImportantData= ' < % # Eval ( `` ImportantData '' ) % > ' id= '' DetailPanel1 '' / > public int ImportantData { get ; set ; } protected void Page_Load ( object sender , EventArgs e ) { } < asp : ImageButton ID= '' btn_Ok '' runat= '' server '' onclick= '' btn_Ok_Click '' ImageUrl= '' ~/image.png '' / > A critical error has occurred . Invalid postback or callback argument . Event validation is enabled using < pages enableEventValidation= '' true '' / > in configuration or < % @ Page EnableEventValidation= '' true '' % > in a page ... protected void Page_Load ( object sender , EventArgs e ) { if ( ! Page.IsPostBack ) { Repeater1.DataSource = listOfData ; Repeater1.DataBind ( ) ; } // Repeater1.DataBind ( ) ; // and tried to put DataBind ( ) here }",Losing value when clicking on button in ascx control that is rendered in asp : Repeater "C_sharp : I 'm currently exploring threading implementation in C # WinForms and I created this simple app : I 'm just wondering why the memory usage of this app keeps growing after I start , stop , start , and stop again the application . I 'm having a thought that my thread instance does n't really terminate or abort when I press the stop button . Please consider my code below , and any help or suggestions will be greatly appreciated . using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; using System.Threading ; namespace ThreadingTest { public partial class Form1 : Form { private delegate void TickerDelegate ( string s ) ; bool stopThread = false ; TickerDelegate tickerDelegate1 ; Thread thread1 ; public Form1 ( ) { InitializeComponent ( ) ; tickerDelegate1 = new TickerDelegate ( SetLeftTicker ) ; } private void Form1_Load ( object sender , EventArgs e ) { thread1 = new Thread ( new ThreadStart ( disp ) ) ; thread1.Start ( ) ; } void disp ( ) { while ( stopThread == false ) { listBox1.Invoke ( tickerDelegate1 , new object [ ] { DateTime.Now.ToString ( ) } ) ; Thread.Sleep ( 1000 ) ; } } private void SetLeftTicker ( string s ) { listBox1.Items.Add ( s ) ; } private void btnStop_Click ( object sender , EventArgs e ) { stopThread = true ; if ( thread1.IsAlive ) { thread1.Abort ( ) ; } } private void btnStart_Click ( object sender , EventArgs e ) { stopThread = false ; thread1 = new Thread ( new ThreadStart ( disp ) ) ; thread1.Start ( ) ; } private void btnCheck_Click ( object sender , EventArgs e ) { if ( thread1.IsAlive ) { MessageBox.Show ( `` Is Alive ! `` ) ; } } private void btnClear_Click ( object sender , EventArgs e ) { listBox1.Items.Clear ( ) ; } } }","Simple Threading , why does this happen ? ( C # WinForms )" "C_sharp : I am writing a program that moves csv files from a `` queue '' folder to a `` processing '' folder , then a third party process called import.exe is launched taking the csv file path as an argument . Import.exe is a long running task.I need the program to continue running and checking the queue for new files . For this reason I ’ ve chosen a Windows Service application as it will be long running.My problem is that I am overwhelmed with options and ca n't understand if I should approach this problem with background threads or parallel programming , or most likely a combination of both.So far I have this code which is just running synchronously.You will quickly see that at the moment , I am just wildly firing processes without anyway to manage or check for completion . I have commented out process.WaitForExit ( ) as obviously this is a blocking call.I also tried creating an array of Tasks , and running these asynchronously . But at the end I still had to call Task.WaitAll ( ) before I could read the result . So even if one finishes early , it must wait for the longest running task.I think I need to try loop through creating processes asynchronously perhaps using tasks , but I don ’ t understand how to do this as a background process , so that I can keep the service timer checking for number of processes if it needs to create more . public int maxConcurrentProcesses = 10 ; protected override void OnStart ( string [ ] args ) { // Set up a timer to trigger every minute . System.Timers.Timer timer = new System.Timers.Timer ( 60000 ) ; timer.Elapsed += new System.Timers.ElapsedEventHandler ( this.OnTimer ) ; timer.Start ( ) ; } private void OnTimer ( object sender , System.Timers.ElapsedEventArgs args ) { // How many instances of import.exe are running ? Process [ ] importProcesses = Process.GetProcessesByName ( `` import '' ) ; int countRunning = importProcesses.Count ( ) ; // If there are less than maxConcurrentProcesses , create as many as needed to reach maxConcurrentProcesses if ( countRunning < maxConcurrentProcesses ) { int processesToStart = maxConcurrentProcesses - countRunning ; for ( int i = 0 ; i < processesToStart ; i++ ) { FireOffImport ( ) ; } } } private void FireOffImport ( ) { // Get the first file returned from the Queue folder string filePathSource = GetNextCSVInQueue ( ) ; if ( filePathSource ! = `` '' ) { // … // commandArguments = create our arguments here // … // Move the file to processing folder here // … // Give a new process the import tool location and arguments ProcessStartInfo startInfo = new ProcessStartInfo ( importLocation + `` \\import.exe '' , commandArguments ) ; try { Process process = Process.Start ( startInfo ) ; // process.WaitForExit ( 20000 ) ; // If the process has exited , there will be 4 csv files created in the same directory as the file . } catch ( Exception ex ) { // Deal with exception here } } }",Running external processes asynchronously in a windows service "C_sharp : In my app I am creating some concurrent web requests and I am satisfied when any one of them completes , so I am using the method Task.WhenAny : First Completed Url : https : //superuser.com Data : 121.954 chars What I do n't like to this implementation is that the non-completed tasks continue downloading data I no longer need , and waste bandwidth I would prefer to preserve for my next batch of requests . So I am thinking about cancelling the other tasks , but I am not sure how to do it . I found how to use a CancellationToken to cancel a specific web request : Now I need an implementation of Task.WhenAny that will take an array of urls , and will use my DownloadUrl function to fetch the data of the fastest responding site , and will handle the cancellation logic of the slower tasks . It would be nice if it had a timeout argument , to offer protection against never-ending tasks . So I need something like this : Any ideas ? var urls = new string [ ] { `` https : //stackoverflow.com '' , `` https : //superuser.com '' , `` https : //www.reddit.com/r/chess '' , } ; var tasks = urls.Select ( async url = > { using ( var webClient = new WebClient ( ) ) { return ( Url : url , Data : await webClient.DownloadStringTaskAsync ( url ) ) ; } } ) .ToArray ( ) ; var firstTask = await Task.WhenAny ( tasks ) ; Console.WriteLine ( $ '' First Completed Url : { firstTask.Result.Url } '' ) ; Console.WriteLine ( $ '' Data : { firstTask.Result.Data.Length : # ,0 } chars '' ) ; public static async Task < ( string Url , string Data ) > DownloadUrl ( string url , CancellationToken cancellationToken ) { try { using ( var webClient = new WebClient ( ) ) { cancellationToken.Register ( webClient.CancelAsync ) ; return ( url , await webClient.DownloadStringTaskAsync ( url ) ) ; } } catch ( WebException ex ) when ( ex.Status == WebExceptionStatus.RequestCanceled ) { cancellationToken.ThrowIfCancellationRequested ( ) ; throw ; } } public static Task < Task < TResult > > WhenAnyEx < TSource , TResult > ( this IEnumerable < TSource > source , Func < TSource , CancellationToken , Task < TResult > > taskFactory , int timeout ) { // What to do here ? }",Task.WhenAny with cancellation of the non completed tasks and timeout "C_sharp : I 'm currently fighting with some app compat settings , specifically a certain shim , and looking into the compatibilty section of the application manifest.Details aside , one thing that strikes me as odd is that , even with Visual Studio 2015 , there does n't seem to be any default for the application compatibility manifest ( * ) -- or rather , default is none , thereby defaulting to `` Windows Vista '' wrt . the stuff listed in Application Manifest.This seems totally odd to me , but maybe I 'm missing something : Every new application in either Visual-C++/Native or C # that is newly created by any team that is not aware of this stuff ( and I daresay there 's a lot of such teams ) will run in Windows Vista compatibility mode . Is this actually the case ? Is there a rationale for this ? ( * ) : And while I 'm at it : Good overviewList of Windows 7 vs. Vista compatibility bulletsFor Windows 8For Windows 8.1For Windows 10 ( ? ) ... < compatibility xmlns= '' urn : schemas-microsoft-com : compatibility.v1 '' > < application > < supportedOS Id= '' { ... } '' / >",Default Application Compatibilty Manifest for new Visual-Studio projects ? C_sharp : I 'm experimenting with Zoombox control from Xceed . Unfortunately nothing happens on mouse wheel or pan . Am I missing something here ? https : //github.com/xceedsoftware/wpftoolkit < Window x : Class= '' UI.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : xcdg= '' http : //schemas.xceed.com/wpf/xaml/datagrid '' xmlns : xctk= '' http : //schemas.xceed.com/wpf/xaml/toolkit '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 800 '' Width= '' 700 '' > < Grid > < xctk : Zoombox MinScale= '' 0.5 '' MaxScale= '' 100 '' > < Grid Width= '' 600 '' Height= '' 400 '' Background= '' Yellow '' > < Ellipse Fill= '' Blue '' / > < /Grid > < /xctk : Zoombox > < /Grid > < /Window >,Zoombox from Xceed WPF Toolkit not working "C_sharp : Let 's say i have the following model which is obtained via Entity Framework : Get all the users from the user table : Reder the users in the View ( @ model IEnumerable ) : My new boss is telling me that doing it this way is not MVC conform and the performance will be very bad . What i should do is to materalize all USERS in the Controller with .ToList ( ) . I am not sure what is better , because either way the users have to be materialized and i dont see any performance losses . public class User { public string Name { get ; set ; } public int Id { get ; set ; } } IEnumerable < User > users = from u in myDbContext.Users select u ; @ foreach ( var item in Model ) { < tr > @ item.Id < /tr > < tr > @ item.Name < /tr > }",Is Deferred Execution in Asp.net MVC View a very bad thing ? "C_sharp : Have a HEX colour code string in the database ( `` # ADD8E6 '' ) and I want to use this to change the background colour of a MigraDoc cell . I have found Color.Parse ( ) function , however it is n't changing the colour of my cell . I have had to do the following : I know that the Cell.Shading.Color is correct because if I apply Cell.Shading.Color = Colors.AliceBlue then the cell does change colour as expected . I understand the Color.Parse requires the HEX code to start with 0x rather than # . I tried using the # and it failed ... At least with what I have got it is rendering ... just not with my colour . string colourHex = ( database.HexCode ) .Replace ( `` # '' , `` 0x '' ) ; var colourObject = MigraDoc.DocumentObjectModel.Color.Parse ( colourHex ) ; Cell.Shading.Color = colourObject ;",MigraDoc - Setting Cell Colour from Hex "C_sharp : Let 's take the following extension method : I 'm curious as to why this code compiles and runs : Within In , values is an Object [ ] , as if the List < int > gets converted on the fly to an array . To me , it seems that params T [ ] does not match IEnumerable < int > , which is why I 'm surprised this even runs.Now this code : Does not run and generates the compiler error : Error 2 Argument 2 : can not convert from 'System.Collections.Generic.IEnumerable ' to 'int [ ] 'This is what I 'd expect from the first one actually . Can someone explain what 's going on here ? Thanks ! static class Extensions { public static bool In < T > ( this T t , params T [ ] values ) { return false ; } } var x = new Object ( ) ; IEnumerable < int > p = new List < int > { 1 , 2 , 3 } ; var t2 = x.In ( p ) ; var x = 5 ; IEnumerable < int > p = new List < int > { 1 , 2 , 3 } ; var t2 = x.In ( p ) ;","Confused as to why this C # code compiles , while similar code does not" "C_sharp : Here 's the scenario : I have one message that needs to be processed by multiple subscribers , BUT only one per service ( There will be multiple instances running for each service ) .Message # 1 , needs to be processed by Subscribers # 1 and # 3 . Message # 2 , needs to be processed by Subscribers # 2 and # 4 . Message # 3 , subscribers # 1 and # 3 again . Basically , each message should round robin to each of the load balanced services that are subscribing to each message , grouped by each service that is connecting . Is this possible without creating multiple topics ? Even if it 's not round robin per-say , I 'd like to use best effort to load balance across multiple services . Is this possible ? Publisher # 1 ═══╗ ╔═══ Round Robin ═══╦═══ Subscriber # 1 ( Service 1 ) ║ ║ ╚═══ Subscriber # 2 ( Service 1 ) ╠═══ Topic ═══╣ ║ ║ ╔═══ Subscriber # 3 ( Service 2 ) Publisher # 2 ═══╝ ╚═══ Round Robin ═══╩═══ Subscriber # 4 ( Service 2 )",Azure Service Bus - Round Robin Topic to Multiple Services C_sharp : I 'm looking for an easy way to syntax highlight C # code into HTML from the command line . Ideally this would be something like : ... produces test.html . syntax-highlighter test.cs,Command-line tool to syntax highlight C # into HTML ? "C_sharp : I have a SQL query : Error : Column 'orders ' can not be null at System.Data.Odbc.OdbcConnection.HandleError String S = Editor1.Content.ToString ( ) ; Response.Write ( S ) ; string sql = `` insert into testcase.ishan ( nmae , orders ) VALUES ( ' 9 ' , @ S ) '' ; OdbcCommand cmd = new OdbcCommand ( sql , myConn ) ; cmd.Parameters.AddWithValue ( `` @ S '' , S ) ; cmd.ExecuteNonQuery ( ) ;",SQL query error - `` Column can not be null '' "C_sharp : I have a very simple EF operation that fails : break the relationship between two entities as shown in the code below : The database was generated code-first . The entities are defined like this : However , breaking the relationship does n't work , Teacher keeps pointing to the same entity . When stepping with the debugger , I see that the Teacher property does n't become null after .Teacher = null . I tried it with the synchronous alternative , which had the same effect : public async Task RemoveCurrentTeacherOfGroup ( int groupId ) { var group = await _dataContext.Groups.SingleAsync ( g = > g.Id == groupId ) ; group.Teacher = null ; await _dataContext.SaveChangesAsync ( ) ; } public class Teacher { public int Id { get ; set ; } .. public virtual List < Group > Groups { get ; set ; } } public class Group { public int Id { get ; set ; } .. public virtual Teacher Teacher { get ; set ; } } public void RemoveCurrentTeacherOfGroup ( int groupId ) { var group = _dataContext.Groups.Single ( g = > g.Id == groupId ) ; group.Teacher = null ; _dataContext.SaveChanges ( ) ; }",Relationship not set to null "C_sharp : Possible Duplicate : How do I check for nulls in an ‘ == ’ operator overload without infinite recursion ? I have an object that looks like this : This works fine for comparing instances to each other , but I also want to be able to handle an expression such as : Doing this causes an exception on the following line : Since y is null.I 've tried changing this function to : However , this creates a stack overflow since the implementation uses its own overridden comparison operator.What 's the trick to getting the == operator to handle comparisons to null ? Thanks ! public class Tags { int mask ; public static bool operator ! = ( Tags x , Tags y ) { return ! ( x == y ) ; } public static bool operator == ( Tags x , Tags y ) { return x.mask == y.mask ; } } if ( tags1 == null ) return x.mask == y.mask ; public static bool operator == ( Tags x , Tags y ) { if ( x == null & & y == null ) return true ; if ( x == null || y == null ) return false ; return x.mask == y.mask ; }",C # equality operators override ( == and ! = ) "C_sharp : 2 days ago , there was a question related to string.LastIndexOf ( String.Empty ) returning the last index of string : Do C # strings end with empty string ? So I thought that ; a string can always contain string.empty between characters like : After this , I wanted to test if String.IndexOf ( String.Empty ) was returning 0 because since String.Empty can be between any char in a string , that would be what I expect it to return and I was n't wrong.It actually returned 0 . I started to think that if I could split a string with String.Empty , I would get at least 2 string and those would be String.Empty and rest of the string since String.IndexOf ( String.Empty ) returned 0 and String.LastIndexOf ( String.Empty ) returned length of the string.. Here is what I coded : The problem here is , I ca n't obviously convert String.Empty to char [ ] and result in an empty string [ ] . I would really love to see the result of this operation and the reason behind this . So my questions are : Is there any way to split a string with String.Empty ? If it is not possible but in an absolute world which it would be possible , would it return an array full of chars like [ 0 ] = `` t '' [ 1 ] = `` e '' [ 2 ] = `` s '' and so on or would it just return the complete string ? Which would make more sense and why ? `` testing '' == `` t '' + String.Empty + `` e '' + String.Empty + '' sting '' + String.Empty ; string testString = `` testing '' ; int index = testString.LastIndexOf ( string.Empty ) ; // index is 6index = testString.IndexOf ( string.Empty ) ; // index is 0 string emptyString = string.Empty ; char [ ] emptyStringCharArr = emptyString.ToCharArray ( ) ; string myDummyString = `` abcdefg '' ; string [ ] result = myDummyString.Split ( emptyStringCharArr ) ;",String.Empty in strings "C_sharp : More of a usability question.I 'm building a big MVVM application , and I find myself copying / modifying this piece of code all over the place : Is there a way in Visual Studio to generate this code with a shortcut or something ? I have Resharper and VS 2015 , and I ca n't find the command that would automatically do that for me . public NodeKind Kind { get { return ( NodeKind ) this.GetValue ( KindProperty ) ; } set { this.SetValue ( KindProperty , value ) ; } } public static readonly DependencyProperty KindProperty = DependencyProperty.Register ( `` Kind '' , typeof ( NodeKind ) , typeof ( DashboardNode ) ) ;",Is there a way to automatically create DependencyProperty in MVVM "C_sharp : I made some DataGrid Customization to be looks like a Cards View , i know there is some different ways to do this but for some other dependencies i need it a datagrid , i customized the Row Style as below : and the DataGrid Xaml Code : I got this result : Its looks like good , but i lost the Selection Behavior , when select an item no action . please help me . < Style x : Key= '' CardStyle '' TargetType= '' { x : Type DataGridRow } '' > < Setter Property= '' BorderBrush '' Value= '' Gray '' / > < Setter Property= '' BorderThickness '' Value= '' 1 '' / > < Setter Property= '' Margin '' Value= '' 2.5 '' / > < Setter Property= '' Background '' Value= '' White '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type DataGridRow } '' > < Border x : Name= '' DGR_Border '' BorderBrush= '' { TemplateBinding BorderBrush } '' BorderThickness= '' { TemplateBinding BorderThickness } '' Background= '' { TemplateBinding Background } '' SnapsToDevicePixels= '' True '' > < SelectiveScrollingGrid > < SelectiveScrollingGrid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < ColumnDefinition Width= '' * '' / > < /SelectiveScrollingGrid.ColumnDefinitions > < SelectiveScrollingGrid.RowDefinitions > < RowDefinition Height= '' * '' / > < RowDefinition Height= '' Auto '' / > < /SelectiveScrollingGrid.RowDefinitions > < ! -- Replacment of DataGridCellsPresenter -- > < ContentControl Grid.Column= '' 1 '' Content= '' { Binding } '' ContentTemplate= '' { Binding ItemTemplate , RelativeSource= { RelativeSource AncestorType=DataGrid } } '' SnapsToDevicePixels= '' { TemplateBinding SnapsToDevicePixels } '' > < /ContentControl > < DataGridDetailsPresenter Grid.Column= '' 1 '' Grid.Row= '' 1 '' SelectiveScrollingGrid.SelectiveScrollingOrientation= '' { Binding AreRowDetailsFrozen , ConverterParameter= { x : Static SelectiveScrollingOrientation.Vertical } , Converter= { x : Static DataGrid.RowDetailsScrollingConverter } , RelativeSource= { RelativeSource AncestorType= { x : Type DataGrid } } } '' Visibility= '' { TemplateBinding DetailsVisibility } '' / > < DataGridRowHeader Grid.RowSpan= '' 2 '' SelectiveScrollingGrid.SelectiveScrollingOrientation= '' Vertical '' Visibility= '' { Binding HeadersVisibility , ConverterParameter= { x : Static DataGridHeadersVisibility.Row } , Converter= { x : Static DataGrid.HeadersVisibilityConverter } , RelativeSource= { RelativeSource AncestorType= { x : Type DataGrid } } } '' / > < /SelectiveScrollingGrid > < /Border > < ControlTemplate.Triggers > < Trigger Property= '' IsMouseOver '' Value= '' True '' > < Setter TargetName= '' DGR_Border '' Property= '' Background '' Value= '' LightGray '' / > < /Trigger > < Trigger Property= '' IsSelected '' Value= '' True '' > < Setter TargetName= '' DGR_Border '' Property= '' Background '' Value= '' Gray '' / > < /Trigger > < /ControlTemplate.Triggers > < /ControlTemplate > < /Setter.Value > < /Setter > < Style.Triggers > < MultiTrigger > < MultiTrigger.Conditions > < Condition Property= '' IsSelected '' Value= '' True '' / > < /MultiTrigger.Conditions > < Setter Property= '' Background '' Value= '' Red '' / > < /MultiTrigger > < MultiTrigger > < MultiTrigger.Conditions > < Condition Property= '' ItemsControl.AlternationIndex '' Value= '' 1 '' / > < Condition Property= '' IsSelected '' Value= '' False '' / > < /MultiTrigger.Conditions > < Setter Property= '' Background '' Value= '' LightGray '' / > < /MultiTrigger > < /Style.Triggers > < /Style > < DataGrid HeadersVisibility= '' None '' SelectionUnit= '' FullRow '' RowStyle= '' { StaticResource CardStyle } '' ScrollViewer.HorizontalScrollBarVisibility= '' Disabled '' > < DataGrid.ItemTemplate > < DataTemplate > < Label Content= '' { Binding } '' HorizontalContentAlignment= '' Center '' VerticalContentAlignment= '' Center '' / > < /DataTemplate > < /DataGrid.ItemTemplate > < DataGrid.ItemsPanel > < ItemsPanelTemplate > < WrapPanel IsItemsHost= '' True '' Orientation= '' Horizontal '' / > < /ItemsPanelTemplate > < /DataGrid.ItemsPanel > < /DataGrid >",How to make DataGrid looks like a CardView ? "C_sharp : I am new to asp.net development.I am currently working of asp.net web application.While resolving an issue came across exception `` thread is being aborted '' . I went through several article to get deep understanding for the exception.I read this great article on codeprojectby Shivprasad koirala which explained me about the use of Server.Transfer and Response.Redirect.Then I went to this post by Thomas Marquardtwhich made me conclude Respose.Redirect ( url , false ) but better to useBut again this article by Imrambaloch saysthere is a security concern using Response.Redirect ( url , false ) , and to instead use Now in the end I am a bit confused as which is the recommended way to redirect.My question : What is the best way to redirect user eliminating the security concerns and performance issues ? Is Server.Transfer really that bad as compared to Response.Redirect ? Server.ClearError ( ) ; Response.Redirect ( url , false ) ; Context.ApplicationInstance.CompleteRequest ( ) ; Response.Redirect ( url , false ) ; var context = HttpContext.Current ; if ( context ! = null ) { context.ApplicationInstance.CompleteRequest ( ) ; }",What is the best approach for redirecting user in asp.net ? "C_sharp : I am using Roslyn to analyze C # code . One of the things I need to have is analyzing a class declaration node and get information about : Its base classIts implemented interfacesI can get access to the class declaration node ( type ClassDeclarationSyntax ) , and from there I can get access to the BaseList : However baseList contains both interfaces and classes . I need ti distinguish classes from interfaces . How ? Do I need to use the SemanticModel ? I 've searched Roslyn 's Wiki and discovered that it is possible to access semantic information from my AST.But how to get those info from here ? Thanks ClassDeclarationSyntax node = ... ; // The class declarationBaseListSyntax baseList = node.BaseList ; SyntaxTree programRoot = ... ; // Getting the AST rootCSharpCompilation compilation = CSharpCompilation.Create ( `` Program '' ) .AddReferences ( MetadataReference.CreateFromFile ( typeof ( object ) .Assembly.Location ) ) .AddSyntaxTrees ( programRoot ) ;",How to tell classes from interfaces in Roslyn 's ` BaseList ` ? "C_sharp : my current navigation stack has two pages . First is page A , second is Page B . When I click my button , It 'll add a new page to the navigation stack , Page C.May I ask how do I display Page C and remove Page B , or remove page B and display page C.I 've tried the followingThe issue i 'm having with this is that the page pops successfully , but the new page is n't visible . I immediately see page A . May I ask how do I pop the current page and immediately show another . await Navigation.PopAsync ( ) await Navigation.PushAsync ( new CustomPage ( ) )",How to pop then immediately push xamarin pages "C_sharp : If I compile this c # code to an EXE file and run in a Windows command shell it runs fine : outputting the prompt , waiting on the same line for some user input followed by enter , echoing that input . Running in a PowerShell v3 shell it also runs fine . If , however , I run this same EXE file in PowerShell ISE V3 , it never emits output from Write and it hangs on the ReadLine . ( As an aside , it will emit output from Write if it is later followed by a WriteLine . ) Is this an ISE bug or is there some property to adjust to make it work ... ? namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { System.Console.Write ( `` invisible prompt : `` ) ; var s = System.Console.ReadLine ( ) ; System.Console.WriteLine ( `` echo `` + s ) ; } } }",Why does PowerShell ISE hang on this C # program ? "C_sharp : I 'm creating an HTTPModule which can be reused a few times , but with different parameters . Think as an example , a request redirector module . I could use an HTTPHandler but it is not a task for it because my process needs to work at the request level , not at an extension/path level.Anyways , I 'd like to have my web.config this way : But most information I could find was this . I say , yeah , I can obtain the whole < modules > tag , but how do each instance of my HTTPModule knows which arguments to take ? If I could get the name ( tpl01 or tpl02 ) upon creation , I could look its arguments up by name afterwards , but I did not see any property in the HTTPModule class to get that.Any help would be really welcome . Thanks in advance ! : ) < system.webServer > < modules > < add name= '' tpl01 '' type= '' TemplateModule '' arg1= '' ~/ '' arg2= '' 500 '' / > < add name= '' tpl02 '' type= '' TemplateModule '' arg1= '' ~/ '' arg2= '' 100 '' / > < /modules > < /system.webServer >",Get HTTPModule 's own parameters in web.config ? "C_sharp : I have a struct e.g . : and would like to create it in my unit tests using autofixture . I tried using the following : But this throws an AutoFixture was unable to create an instance error . Is it possible to auto create a struct with autofixture ? How could this be done ? Please note , that I am working on legacy code and thus need to deal with structs . : ) EDIT : Changed ToSince it was n't relevant for the question . public struct Foo { public int Bar ; public string Baz ; } IFixture fixture = new Fixture ( ) ; var f = fixture.CreateAnonymous < Foo > ( ) ; IFixture fixture = new Fixture ( ) .Customize ( new AutoMoqCustomization ( ) ) ; IFixture fixture = new Fixture ( ) ;",Creating a struct with autofixture throws no public constructor error "C_sharp : I am using C # sockets to implement my own basic RTSP server ( for learning purposes ) . I am currently in the process of writing the logic for the server to perform the handshake with the client when negotiating media ports on a DESCRIBE request.The client application was not written by me and I have no access to update the software , it is a simple RTSP client which negotiates media ports on a Cisco router and then pipes audio to clients connected to it . The payload I want to send back is 1024 bytes and a 64 byte header , and from what I can see from inspecting my client app , only 400 bytes are transmitted back to the client.The response payload is defined in C # as : The responding method respondToClient is implemented as : With a SendCallback to determine when the packet has been sent to the client : Why is my client application only receiving 400 bytes , and if so how can I make sure my whole packet is sent ( I 'm using TCP ) ? Is this a hard limit set by C # ? I consulted MSDN and could not find any information to support this theory.If there are more details required regarding the implementation of my server , please ask.EDIT Here is some food for thought , and I do n't know why it would be happening so if somebody could enlighten me that would be great ... @ Gregory A Beamer suggested in the comments that EndSend could be firing prematurely , is this a possibility ? From my understanding I thought the async callback would only fire once , and only once all bytes had been sent from the server to the listening client socket.In order for me to tell that the packet was n't being fully recieved by the client , the following information states that only 400 bytes are received by the client application : Supported by a wireshark trace from S- > CUPDATE After speaking earlier with @ usr I did some further tests and can now confirm that the client application will only ever receive a 400 byte response back from the server . I h^ This is the log trace dumped by the client application when I dial in to the server , here we can see that it accept 1384 bytes back from the client , but its processing buffer is only capable of storing 400 bytes . I looked at a log for an existing application which handles streaming to the same device , and in the wireshark trace , instead of sending the header in one block , it sends several chunks back with the info [ TCP segment of a reassembled PDU ] I am not sure what this means ( new to network stuff ) but I assume its breaking down the server payload and sending it over in several chunks and then reassembling on the client to handle the request.How can I replicate this behaviour on my server application ? I tried the following in my respond method , with hopes that it would pipe back the packet and reassemble on the client , however I just continued to get the same error discussed above : // Build the RTSP Response stringvar body = `` v=0\n '' + `` o=- 575000 575000 IN IP4 `` + m_serverIP + `` \n '' + `` s= '' + stream + `` \n '' + `` i= < No author > < No copyright > \n '' + `` c= IN IP4 0.0.0.0\n '' + `` t=0 0\n '' + `` a=SdpplinVersion:1610641560\n '' + `` a=StreamCount : integer ; 1\n '' + `` a=control : *\n '' + `` a=Flags : integer ; 1\n '' + `` a=HasParam : integer ; 0\n '' + `` a=LatencyMode : integer ; 0\n '' + `` a=LiveStream : integer ; 1\n '' + `` a=mr : intgner ; 0\n '' + `` a=nr : integer ; 0\n '' + `` a=sr : integer ; 0\n '' + `` a=URL : string ; \ '' Streams/ '' + stream + `` \ '' \n '' + `` a=range : npt=0-\n '' + `` m=audio 0 RTP/AVP 8 '' + // 49170 is the RTP transport port and 8 is A-Law audio `` b=AS:90\n '' + `` b=TIAS:64000\n '' + `` b=RR:1280\n '' + `` b=RS:640\n '' + `` a=maxprate:50.000000\n '' + `` a=control : streamid=1\n '' + `` a=range : npt=0-\n '' + `` a=length : npt=0\n '' + `` a=rtpmap:8 pcma/8000/1\n '' + `` a=fmtp:8 '' + `` a=mimetype : string ; \ '' audio/pcma\ '' \n '' + `` a=ASMRuleBook : string ; \ '' marker=0 , Avera**MSG 00053 TRUNCATED**\n '' + `` **MSG 0053 CONTINUATION # 01**geBandwidth=64000 , Priority=9 , timestampdelivery=true ; \ '' \n '' + `` a=3GPP-Adaptation-Support:1\n '' + `` a=Helix-Adaptation-Support:1\n '' + `` a=AvgBitRate : integer ; 64000\n '' + `` a=AvgPacketSize : integer ; 160\n '' + `` a=BitsPerSample : integer ; 16\n '' + `` a=LiveStream : integer ; 1\n '' + `` a=MaxBitRate : integer ; 64000\n '' + `` a=MaxPacketSize : integer ; 160\n '' + `` a=Preroll : integer ; 2000\n '' + `` a=StartTime : integer ; 0\n '' + `` a=OpaqueData : buffer ; \ '' AAB2dwAGAAEAAB9AAAAfQAABABAAAA==\ '' '' ; var header = `` RTSP/1.0 200 OK\n '' + `` Content-Length : `` + body.Length + `` \n '' + `` x-real-usestrackid:1\n '' + `` Content-Type : application/sdp\n '' + `` Vary : User-Agent , ClientID\n '' + `` Content-Base : `` + requestURI + `` \n '' + `` vsrc : '' + m_serverIP + `` /viewsource/template.html\n '' + `` Set-Cookie : `` + Auth.getCookie ( ) + `` \n '' + `` Date : `` + System.DateTime.Now + `` \n '' + `` CSeq : 0\n '' ; var response = header + body ; var byteArray = System.Text.Encoding.UTF8.GetBytes ( response ) ; respondToClient ( byteArray , socket ) ; private static void respondToClient ( byte [ ] byteChunk , Socket socket ) { socket.BeginSend ( byteChunk , 0 , byteChunk.Length , SocketFlags.None , new AsyncCallback ( SendCallback ) , socket ) ; socket.BeginReceive ( m_dataBuffer , 0 , m_dataBuffer.Length , SocketFlags.None , new AsyncCallback ( ReceiveCallback ) , socket ) ; } private static void SendCallback ( IAsyncResult res ) { try { var socket = ( Socket ) res.AsyncState ; socket.EndSend ( res ) ; } catch ( Exception e ) { Console.Write ( e.Message ) ; } } Jul 1 13:28:29 : //-1//RTSP : /rtsp_read_svr_resp : Socket = 0Jul 1 13:28:29 : //-1//RTSP : /rtsp_read_svr_resp : NBYTES = 1384Jul 1 13:28:29 : //-1//RTSP : /rtsp_process_single_svr_resp : Jul 1 13:28:29 : rtsp_process_single_svr_resp : 400 bytes of data : RTSP/1.0 200 OKContent-Length : 1012x-real-usestrackid:1Content-Type : application/sdpVary : User-Agent , ClientIDContent-Base : rtsp : //10.96.134.50/streams/stream01.dcwvsrc:10.96.134.50/viewsource/template.htmlSet-Cookie : cbid=aabtvqjcldwjwjbatynprfpfltxaspyopoccbtewiddxuzhsesflnkzvkwibtikwfhuhhzzz ; path=/ ; expires=09/10/2015 14:28:38Date : 01/07/2015 14:28:38CSeq : 0 v=0o=- 575000 575000 IN IP4 private static void respondToClient ( byte [ ] byteChunk , Socket socket ) { // Divide the byte chunk into 300 byte chunks if ( byteChunk.Length > = 400 ) { Console.WriteLine ( `` Total bytes : `` + byteChunk.Length ) ; var totalBytes = byteChunk.Length ; var chunkSize = 400 ; var tmp = new byte [ chunkSize ] ; var packets = totalBytes / chunkSize ; var overflow = totalBytes % chunkSize ; Console.WriteLine ( `` Sending `` + totalBytes + `` in `` + packets + `` packets , with an overflow packets of `` + overflow + `` bytes . `` ) ; for ( var i = 0 ; i < packets * chunkSize ; i+=chunkSize ) { Console.WriteLine ( `` Sending chunk `` + i + `` to `` + ( i + chunkSize ) ) ; tmp = byteChunk.Skip ( i ) .Take ( chunkSize ) .ToArray ( ) ; socket.BeginSend ( tmp , 0 , tmp.Length , SocketFlags.None , new AsyncCallback ( SendCallback ) , socket ) ; } if ( overflow > 0 ) { Console.WriteLine ( `` Sending overflow chunk : `` + overflow + `` at index `` + ( totalBytes - overflow ) + `` to `` + ( totalBytes ) ) ; tmp = byteChunk.Skip ( byteChunk.Length - overflow ) .Take ( overflow ) .ToArray ( ) ; socket.BeginSend ( tmp , 0 , tmp.Length , SocketFlags.None , new AsyncCallback ( SendCallback ) , socket ) ; } } else { socket.BeginSend ( byteChunk , 0 , byteChunk.Length , SocketFlags.None , new AsyncCallback ( SendCallback ) , socket ) ; socket.BeginReceive ( m_dataBuffer , 0 , m_dataBuffer.Length , SocketFlags.None , new AsyncCallback ( ReceiveCallback ) , socket ) ; } }",Send more data than what can be stored in send buffer "C_sharp : I 'm looking for a way to filter out methods which have the unsafe modifier via reflection . It does n't seem to be a method attribute.Is there a way ? EDIT : it seems that this info is not in the metadata , at least I ca n't see it in the IL . However reflector shows the unsafe modifier in C # view . Any ideas on how it 's done ? EDIT 2 : For my needs I ended up with a check , that assumes that if one of the method 's parameters is a pointer , or a return type is a pointer , then the method is unsafe.This does n't handle , of course , a situation where an unsafe block is executed within a method , but again , all I am interested in is the method signature.Thanks ! public static bool IsUnsafe ( this MethodInfo methodInfo ) { if ( HasUnsafeParameters ( methodInfo ) ) { return true ; } return methodInfo.ReturnType.IsPointer ; } private static bool HasUnsafeParameters ( MethodBase methodBase ) { var parameters = methodBase.GetParameters ( ) ; bool hasUnsafe = parameters.Any ( p = > p.ParameterType.IsPointer ) ; return hasUnsafe ; }",Determine if method is unsafe via reflection "C_sharp : I have set an example of my code but I 'm not able to logs in kibana with authentication using serilog.Here , I have attached my code please correct it . Log.Logger = new LoggerConfiguration ( ) .WriteTo.Elasticsearch ( new ElasticsearchSinkOptions ( new Uri ( `` myurl:9200 '' ) ) { IndexFormat = `` ChargeMasterlog- { yyyy.MM.dd } '' , ModifyConnectionSettings = x = > x.BasicAuthentication ( `` username '' , `` password '' ) , } ) .CreateLogger ( ) ; Log.Information ( `` Hello , Serilog ! `` ) ;",How to set logs to ELK in kibana with authentication using serilog "C_sharp : We are using a base class for all of our Response DTO 's in our application . The class has the following signature : The Messages collection can be any of the following types : With concrete versions of : All DTO Response objects inherit from ResponseBase however even with the following ServiceKnownTypes on the WCF ContractWhen we load a Message into the ResponseBase Messages collection the following exception gets thrown : Error in line 1 position 906 . Element 'http : //schemas.datacontract.org/2004/07/CX.Framework.Common.BaseTypes : ResponseMessage ' contains data from a type that maps to the name 'http : //schemas.datacontract.org/2004/07/CX.Framework.Common.BaseTypes : WarnMessage ' . The deserializer has no knowledge of any type that maps to this name . Consider using a DataContractResolver or add the type corresponding to 'WarnMessage ' to the list of known types - for example , by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.We have done everything from ServiceKnownType to XMLInclude on the derived types . I 'm at a bit of a loss as to how to resolve this and would appreciate any assistance anyone can provide . [ Serializable ] public abstract class ResponseBase { public bool Successful { get ; set ; } public List < ResponseMessage > Messages { get ; set ; } // ... Other code ... } [ Serializable ] [ XmlInclude ( typeof ( DebugMessage ) ) ] [ XmlInclude ( typeof ( InfoMessage ) ) ] [ XmlInclude ( typeof ( ValidationMessage ) ) ] [ XmlInclude ( typeof ( WarnMessage ) ) ] [ XmlInclude ( typeof ( RecoverableFaultMessage ) ) ] [ XmlInclude ( typeof ( FatalFaultMessage ) ) ] public abstract class ResponseMessage { //..Other code ... } [ Serializable ] public class DebugMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Debug ; } } } [ Serializable ] public class InfoMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Info ; } } } [ Serializable ] public class ValidationMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Validation ; } } } [ Serializable ] public class WarnMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.Warn ; } } } [ Serializable ] public class RecoverableFaultMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.RecoverableFault ; } } } [ Serializable ] public class FatalFaultMessage : ResponseMessage { public override MessageType MessageType { get { return MessageType.FatalFault ; } } } [ ServiceKnownType ( typeof ( ResponseBase ) ) ] [ ServiceKnownType ( typeof ( ResponseMessage ) ) ] [ ServiceKnownType ( typeof ( List < ResponseMessage > ) ) ] [ ServiceKnownType ( typeof ( DebugMessage ) ) ] [ ServiceKnownType ( typeof ( InfoMessage ) ) ] [ ServiceKnownType ( typeof ( ValidationMessage ) ) ] [ ServiceKnownType ( typeof ( WarnMessage ) ) ] [ ServiceKnownType ( typeof ( RecoverableFaultMessage ) ) ] [ ServiceKnownType ( typeof ( FatalFaultMessage ) ) ] [ ServiceKnownType ( typeof ( List < DebugMessage > ) ) ] [ ServiceKnownType ( typeof ( List < InfoMessage > ) ) ] [ ServiceKnownType ( typeof ( List < ValidationMessage > ) ) ] [ ServiceKnownType ( typeof ( List < WarnMessage > ) ) ] [ ServiceKnownType ( typeof ( List < RecoverableFaultMessage > ) ) ] [ ServiceKnownType ( typeof ( List < FatalFaultMessage > ) ) ]",WCF Abstract base class with complex collection of abstract types not being included for deserialization in service response "C_sharp : I get an very strange behaviour when I change my Visual Studio 2010 config from Debug to Release : I have a BackgroundWorker : _bg , in the DoWork I have : in the ProgressChanged I have a MessageBox and after the user interaction , iswaiting will be set back to false and the _bg DoWork program will continue.All of these works very well when I run it from Visual Studio or build in Debug mode , but when I build it to Release , I never get out of the while ( iswaiting ) loop , although I can see from the log iswaiting is already set back to false.EDIT : Better way of doing this is more than welcome ! ! iswaiting = true ; _bg.ReportProgress ( 1 , filePath ) ; while ( iswaiting ) { ; } //My other part of code ( EDIT : something do to with the ` result ` I get from the user . ) void _bg_ProgressChanged ( object sender , ProgressChangedEventArgs e ) { //my other part of code ... ... .. result = Microsoft.Windows.Controls.MessageBox.Show ( `` Question '' , '' Title '' , MessageBoxButton.YesNoCancel , MessageBoxImage.Warning ) ; iswaiting=false ; log ( iswaiting.toString ( ) ) ; }",Difference between Release and Debug ? "C_sharp : I 'm having few RadioButtons and I do n't want to bind `` IsChecked '' property of each one of them to unique property in the code.I want to have a single property like `` CurrentSelected '' and accordingto that to set the `` IsChecked '' .In addition I do n't want to use converters.I tried to use the behavior `` ChangePropertyAction '' but it looks likeit 's working only in one way . here is my code : my view model is very simple : MainViewModel.csas you can see from the code , the `` Up '' RadioButton should be already checked ... What am I missing ? < RadioButton x : Name= '' UpRadioButton '' Margin= '' 5 '' Content= '' Up '' > < i : Interaction.Triggers > < ei : DataTrigger Binding= '' { Binding IsChecked , ElementName=UpRadioButton } '' Value= '' True '' > < ei : ChangePropertyAction TargetObject= '' { Binding Mode=OneWay } '' PropertyName= '' SelectedDirection '' Value= '' { x : Static Enums : DirectionEnum.Up } '' / > < /ei : DataTrigger > < /i : Interaction.Triggers > < /RadioButton > < RadioButton x : Name= '' DownRadioButton '' Margin= '' 5 '' Content= '' Down '' > < i : Interaction.Triggers > < ei : DataTrigger Binding= '' { Binding IsChecked , ElementName=DownRadioButton } '' Value= '' True '' > < ei : ChangePropertyAction TargetObject= '' { Binding Mode=OneWay } '' PropertyName= '' SelectedDirection '' Value= '' { x : Static Enums : DirectionEnum.Down } '' / > < /ei : DataTrigger > < /i : Interaction.Triggers > < /RadioButton > < RadioButton x : Name= '' LeftRadioButton '' Margin= '' 5 '' Content= '' Left '' > < i : Interaction.Triggers > < ei : DataTrigger Binding= '' { Binding IsChecked , ElementName=LeftRadioButton } '' Value= '' True '' > < ei : ChangePropertyAction TargetObject= '' { Binding Mode=OneWay } '' PropertyName= '' SelectedDirection '' Value= '' { x : Static Enums : DirectionEnum.Left } '' / > < /ei : DataTrigger > < /i : Interaction.Triggers > < /RadioButton > < RadioButton x : Name= '' RightRadioButton '' Margin= '' 5 '' Content= '' Right '' > < i : Interaction.Triggers > < ei : DataTrigger Binding= '' { Binding IsChecked , ElementName=RightRadioButton } '' Value= '' True '' > < ei : ChangePropertyAction TargetObject= '' { Binding Mode=OneWay } '' PropertyName= '' SelectedDirection '' Value= '' { x : Static Enums : DirectionEnum.Right } '' / > < /ei : DataTrigger > < /i : Interaction.Triggers > < /RadioButton > public class MainViewModel : ViewModelBase { private DirectionEnum _selectedDirection ; public DirectionEnum SelectedDirection { get { return _selectedDirection ; } set { if ( _selectedDirection ! = value ) { _selectedDirection = value ; RaisePropertyChanged ( ) ; } } } public MainViewModel ( ) { SelectedDirection = DirectionEnum.Up ; } }",Bind RadioButtons to single property ? "C_sharp : i 'm trying to find a good way to detect if a feature exists before P/Invoking . For example calling the native StrCmpLogicalW function : will crash on some systems that do not have this feature.i do n't want to perform version checking , as that is bad practice , and can sometimes just be wrong ( for example when functionality is back-ported , or when the functionality can be uninstalled ) .The correct way , is to check for the presence of the export from shlwapi.dll : The problem , of course , is that C # does n't support function pointers , i.e . : can not be done.So i 'm trying to find alternative syntax to perform the same logic in .NET . i have the following pseudo-code so far , but i 'm getting stymied : and i need some help.Another example of some exports that i want to detect presence of would be : dwmapi.dll : :DwmIsCompositionEnableddwmapi.dll : :DwmExtendFrameIntoClientAreadwmapi.dll : :DwmGetColorizationColordwmapi.dll : :DwmGetColorizationParameters ( undocumented1 , not yet exported by name , ordinal 127 ) dwmapi.dll : :127 ( undocumented1 , DwmGetColorizationParameters ) 1 as of Windows 7 SP1There must already be a design pattern in .NET for checking the presence of OS features . Can anyone point me to an example of the preferred way in .NET to perform feature detection ? [ SuppressUnmanagedCodeSecurity ] internal static class SafeNativeMethods { [ DllImport ( `` shlwapi.dll '' , CharSet = CharSet.Unicode ) ] public static extern int StrCmpLogicalW ( string psz1 , string psz2 ) ; } private static _StrCmpLogicalW : function ( String psz1 , String psz2 ) : Integer ; private Boolean _StrCmpLogicalWInitialized ; public int StrCmpLogicalW ( String psz1 , psz2 ) { if ( ! _StrCmpLogialInitialized ) { _StrCmpLogicalW = GetProcedure ( `` shlwapi.dll '' , `` StrCmpLogicalW '' ) ; _StrCmpLogicalWInitialized = true ; } if ( _StrCmpLogicalW ) return _StrCmpLogicalW ( psz1 , psz2 ) else return String.Compare ( psz1 , psz2 , StringComparison.CurrentCultureIgnoreCase ) ; } _StrCmpLogicalW = GetProcedure ( `` shlwapi.dll '' , `` StrCmpLogicalW '' ) ; [ SuppressUnmanagedCodeSecurity ] internal static class SafeNativeMethods { private Boolean IsSupported = false ; private Boolean IsInitialized = false ; [ DllImport ( `` shlwapi.dll '' , CharSet = CharSet.Unicode , Export= '' StrCmpLogicalW '' , CaseSensitivie=false , SetsLastError=true , IsNative=false , SupportsPeanutMandMs=true ) ] private static extern int UnsafeStrCmpLogicalW ( string psz1 , string psz2 ) ; public int StrCmpLogicalW ( string s1 , string s2 ) { if ( ! IsInitialized ) { //todo : figure out how to loadLibrary in .net //todo : figure out how to getProcedureAddress in .net IsSupported = ( result from getProcedureAddress is not null ) ; IsInitialized = true ; } if ( IsSupported ) return UnsafeStrCmpLogicalW ( s1 , s2 ) ; else return String.Compare ( s1 , s2 , StringComparison.CurrentCultureIgnoreCase ) ; } }",Feature detection when P/Invoking in C # and .NET "C_sharp : For performance optimization , I dynamically create new types per user request using the following code : Then I use that moduleBuilder to emit the type.This creates a new dynamic assembly per request . So I could end up with many of those during the lifetime of the app . So , I 'm worried that the resources will be freed . Therefore , I 'm using AssemblyBuilderAccess.RunAndCollect to make this possible . The msdn says : The dynamic assembly can be unloaded and its memory reclaimed , subject to the restrictions described in Collectible Assemblies for Dynamic Type Generation.I just did n't find how to unload the dynamic assembly and unfortunately the link to the Collectible Assemblies for Dynamic Type Generation topic is broken . A no-longer-maintained version of that page seems to indicated that the unloading happens automatically once the emitted type gets out of scope . Can I trust this ? var dynamicAssemblyName = new AssemblyName ( assemblyName ) ; AssemblyBuilder dynamicAssembly = AssemblyBuilder.DefineDynamicAssembly ( dynamicAssemblyName , AssemblyBuilderAccess.RunAndCollect ) ; ModuleBuilder moduleBuilder = dynamicAssembly.DefineDynamicModule ( assemblyName ) ;",How to unload a dynamic assembly created with RunAndCollect ? "C_sharp : I 'm indexing my query as follows : Now , how do I use the percolator capabilities of ES to match an incoming document with this query ? To say the NEST documentation is lacking in this area would be a huge understatement . I tried using client.Percolate call , but it 's deprecated now and they advise to use the search api , but do n't tell how to use it with percolator ... I 'm using ES v5 and the same version of NEST lib . client.Index ( new PercolatedQuery { Id = `` std_query '' , Query = new QueryContainer ( new MatchQuery { Field = Infer.Field < LogEntryModel > ( entry = > entry.Message ) , Query = `` just a text '' } ) } , d = > d.Index ( EsIndex ) ) ; client.Refresh ( EsIndex ) ;",Using NEST to percolate "C_sharp : I have seen the following exception case several times Is there a guideline for handling these cases ? And in general is there any guidelines describing `` exception style '' a bit more detailed than the MSDN documentation forExceptionArgumentException public SomeClass ( IEnumerable < T > someValues ) { if ( null == someValues ) { throw new ArgumentNullException ( `` someValues '' ) ; } int counter = 0 ; foreach ( T value in someValues ) { if ( null == value ) { string msg = counter + `` th value was null '' ; // What exception class to use ? throw new ArgumentException ( msg , `` someValues '' ) ; } counter++ ; } }",What exception class to use in when IEnumerable contains null "C_sharp : I have the following code : Because the compiler replaces the prefix variable with a closure `` NEW : brownie '' is printed to the console.Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression ? I would like a way of making my Func work identically to : The reason I need this is I would like to serialize the resulting delegate . If the prefix variable is in a non-serializable class the above function will not serialize . The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method : With helper class : This seems like a lot of extra work to get the compiler to be `` dumb '' . string prefix = `` OLD : '' ; Func < string , string > prependAction = ( x = > prefix + x ) ; prefix = `` NEW : '' ; Console.WriteLine ( prependAction ( `` brownie '' ) ) ; Func < string , string > prependAction = ( x = > `` OLD : '' + x ) ; string prefix = `` NEW : '' ; var prepender = new Prepender { Prefix = prefix } ; Func < string , string > prependAction = prepender.Prepend ; prefix = `` OLD : '' ; Console.WriteLine ( prependAction ( `` brownie '' ) ) ; [ Serializable ] public class Prepender { public string Prefix { get ; set ; } public string Prepend ( string str ) { return Prefix + str ; } }",Prevent .NET from `` lifting '' local variables "C_sharp : I am in need of your help.I am in the middle of arranging a script that can check various conditions before an ability can be executed in a RPG game.All these abilities are in individual classes ( Fireball , Heal , Poison ) all derived from another abstract class ( Ranged ability , Healing ability , DOT ability ) , which all are parented to an abstract class ( Ability ) .In order to avoid creating multiple functions , to handle every single ability : I am trying to create a single function call that can take all types of abilities.So far I have succeded in creating a Fireball object and pass it to the function.From here I can access all the public variables initialized in the Ability class , but I ca n't access the public variables initialized in the derived classes ( Ranged ability , Healing ability , DOT ability ) .Is it me who is forgetting something , or am I looking at this at a wrong perspective ? ( I am not great at utilizing inheritance and abstract classes . ) void condition ( Fireball f ) { //test } ; void condition ( Heal f ) { //test } ; void condition ( Poison f ) { //test } ; void condition ( Ability f ) { //test } Fireball _fire = new FireBall ( ) ; condition ( _fire ) ; void condition ( Ability f ) { //test }","C # , Unity - Single function taking multiple different objects" "C_sharp : This question is for educational purposes only and I can solve it easily by using for loop that returns false on first mismatch.I am implementing IEquatable < CustomerFeedbackViewModel > on CustomerFeedbackViewModel which has a collection of QuestionViewModel that I need to compare element by element.when implementing Equals instead of using for loop I mentioned above I wanted to use TrueForAll method it would look something like below.Ofc TrueForAll does not have index and above will never fly.How could I go around implementing comparison of two lists without using for loop but instead using linq 'oneliner ' ? public class CustomerFeedbackViewModel { public List < QuestionViewModel > Questions { get ; set ; } public string PageName { get ; set ; } public string SessionId { get ; set ; } } public bool Equals ( CustomerFeedbackViewModel other ) { if ( ReferenceEquals ( null , other ) ) return false ; if ( ReferenceEquals ( this , other ) ) return true ; return Questions.TrueForAll ( ( o , i ) = > o.Equals ( other.Questions.ElementAt ( i ) ) ) & & string.Equals ( PageName , other.PageName ) & & string.Equals ( SessionId , other.SessionId ) ; }",Comparing two collections with IEquatable while using only LINQ C_sharp : So we have ? ? to parse its right-hand value for when the left hand is null . What is the equivalent for a string [ ] .For exampleAbove example would still crash if we would try to get a third index or if string value = `` One '' . Because it is not null but IndexOutOfRangeException is thrown.https : //docs.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexceptionSo what is a one-line solution to tackle the above problem ? I 'd like to avoid the try-catch scenario because this gives ugly code . I want to get value out of a string [ ] with a string.Empty as a backup value so my string is never null . string value = `` One - Two '' string firstValue = value.Split ( '- ' ) [ 0 ] ? ? string.Empty ; string secondValue = value.Split ( '- ' ) [ 1 ] ? ? string.Empty ;,Get string from array or set default value in a one liner "C_sharp : First of all : I know how to work around this issue . I 'm not searching for a solution . I am interested in the reasoning behind the design choices that led to some implicit conversions and did n't lead to others.Today I came across a small but influential error in our code base , where an int constant was initialised with a char representation of that same number . This results in an ASCII conversion of the char to an int . Something like this : I was confused why C # would allow something like this . After searching around I found the following SO question with an answer by Eric Lippert himself : Implicit Type cast in C # An excerpt : However , we can make educated guesses as to why implicit char-to-ushort was considered a good idea . The key idea here is that the conversion from number to character is a `` possibly dodgy '' conversion . It 's taking something that you do not KNOW is intended to be a character , and choosing to treat it as one . That seems like the sort of thing you want to call out that you are doing explicitly , rather than accidentally allowing it . But the reverse is much less dodgy . There is a long tradition in C programming of treating characters as integers -- to obtain their underlying values , or to do mathematics on them.I can agree with the reasoning behind it , though an IDE hint would be awesome . However , I have another situation where the implicit conversion suddenly is not legal : This conversion is in my humble opinion , very logical . It can not lead to data loss and the intention of the writer is also very clear . Also after I read the rest of the answer on the char to int implicit conversion , I still do n't see any reason why this should not be legal.So that leads me to my actual question : What reasons could the C # design team have , to not implement the implicit conversion from char to a string , while it appears so obvious by the looks of it ( especially when comparing it to the char to int conversion ) . char a = ' a ' ; int z = a ; Console.WriteLine ( z ) ; // Result : 97 char a = ' a ' ; string z = a ; // CS0029 Can not implicitly convert type 'char ' to 'string '",Implicit conversion from char to single character string "C_sharp : Due to the existing framework I am using , a method call is returning a SortedList object . Because I wrote the other side of this call I know that it is in fact a SortedList . While I can continue to work with the SortedList , using the generic would convey my meaning better . So , how do you change the non-generic SortedList into an appropriately typed generic SortedList ? The background on this is that the call is a remote procedure call using the SoapFormatter . The SoapFormatter does not implement generics ( Thank you , Microsoft ) . I can not change the formatter since some non-.Net programs also use other method calls against the service.I would like my proxy call to look like the following : Where the interface for the GetList call is as follows due to the SoapFormatter requirements : public SortedList < string , long > GetList ( string parameter ) { return _service.GetList ( parameter ) ; } public SortedList GetList ( string parameter ) ;",How do you convert a SortedList into a SortedList < > "C_sharp : I recently came across an issue where I was able to change the IEnumerable object that I was iterating over in a foreach loop . It 's my understanding that in C # , you are n't supposed to be able to edit the list you 're iterating over , but after some frustration , I found that this is exactly what was happening . I basically looped through a LINQ query and used the object IDs to make changes in the database on those objects and those changes affected the values in the .Where ( ) statement.Does anybody have an explanation for this ? It seems like the LINQ query re-runs every time it 's iterated overNOTE : The fix for this is adding .ToList ( ) after the .Where ( ) , but my question is why this issue is happening at all i.e . if it 's a bug or something I 'm unaware ofThis code is just a reproducible mockup , but I 'd expect it to loop through 4 times and change all of the strings in aArray into b 's . However , it only loops through twice and turns the last two strings in aArray into b'sEDIT : After some feedback and to be more concise , my main question here is this : `` Why am I able to change what I 'm looping over as I 'm looping over it '' . Looks like the overwhelming answer is that LINQ does deferred execution , so it 's re-evaluating as I 'm looping through the LINQ IEnumerable.EDIT 2 : Actually looking through , it seems that everyone is concerned with the .Count ( ) function , thinking that is what the issue here is . However , you can comment out that line and I still have the issue of the LINQ object changing . I updated the code to reflect the main issue using System ; using System.Linq ; namespace MyTest { class Program { static void Main ( ) { var aArray = new string [ ] { `` a '' , `` a '' , `` a '' , `` a '' } ; var i = 3 ; var linqObj = aArray.Where ( x = > x == `` a '' ) ; foreach ( var item in linqObj ) { aArray [ i ] = `` b '' ; i -- ; } foreach ( var arrItem in aArray ) { Console.WriteLine ( arrItem ) ; //Why does this only print out 2 a 's and 2 b 's , rather than 4 b 's ? } Console.ReadKey ( ) ; } } }",Why am I able to edit a LINQ list while iterating over it ? "C_sharp : I 'm having yet another nasty moment with Reflection.Emit and type management.Say , I have a type named MyType which is defined in the dynamically generated assembly.Calling MyType.GetMethods ( ) results in a NotSupportedException , which has reduced me to writing my own set of wrappers and lookup tables . However , the same is happening when I 'm calling GetMethods ( ) or any other introspecting methods on standard generic types which use my own types as generic arguments : Tuple < int , string > = > works fineTuple < int , MyType > = > exceptionI can get the method list from the generic type definition : typeof ( Tuple < int , MyType ) .GetGenericTypeDefinition ( ) .GetMethods ( ) However , the methods have generic placeholders instead of actual values ( like T1 , TResult etc . ) and I do n't feel like writing yet another kludge that traces the generic arguments back to their original values.A sample of code : So the questions are : How do I detect if a type is safe to call GetMethods ( ) and similar methods on ? How do I get the actual list of methods and their generic argument values , if the type is not safe ? var asmName = new AssemblyName ( `` Test '' ) ; var access = AssemblyBuilderAccess.Run ; var asm = AppDomain.CurrentDomain.DefineDynamicAssembly ( asmName , access ) ; var module = asm.DefineDynamicModule ( `` Test '' ) ; var aType = module.DefineType ( `` A '' ) ; var tupleType = typeof ( Tuple < , > ) ; var tuple = tupleType.MakeGenericType ( new [ ] { typeof ( int ) , aType } ) ; tuple.GetProperty ( `` Item1 '' ) ; // < -- here 's the error",Reflection-generated and generic types "C_sharp : I 've installed Windows 8.1 recently to try , and my pet project is crashing on it ( same binary works fine on one Win7 and two Win8 machines ) .OutOfMemoryException is being thrown in BitmapImage.EndInit : Task manager readings for the process on crash : 27MB memory , 302 handles , 12 threads , 36 user objects , 34 GDI objects , 5.3 GB RAM availablePlatform target is x86 ( required because of native DLL usage ) Method is called many times for different ( random ) images ( there are ~250 bmp files in resources ) decodePixelWidth/Height are random , but within valid range exception happens on different resource paths and sizesexception happens only when DecodePixelWidth or DecodePixelHeight is not 0exception never happens if I comment out DecodePixelWidth and DecodePixelHeight setters and let it load to original sizeAs I understand from googling , it has something to do with GDI internals , but I ca n't find a fix or workaround . Any ideas ( besides using some other mechanism to decode and/or resize images - I only need raw pixel data ) ? Complete project source code can be found here ( link is to the file in question ) : https : //code.google.com/p/lander-net/source/browse/trunk/csharp/LanderNet/Util/BitmapUtils.csUPDATE : I 've tried to use TransformedBitmap for resizing , it fails with the same exception . public static BitmapImage GetResourceImage ( string resourcePath , int decodePixelWidth = 0 , int decodePixelHeight = 0 ) { var image = new BitmapImage ( ) ; var moduleName = Assembly.GetExecutingAssembly ( ) .GetName ( ) .Name ; var resourceLocation = string.Format ( `` pack : //application : , , ,/ { 0 } ; component/Resources/ { 1 } '' , moduleName , resourcePath ) ; image.BeginInit ( ) ; image.UriSource = new Uri ( resourceLocation ) ; image.DecodePixelWidth = decodePixelWidth ; image.DecodePixelHeight = decodePixelHeight ; image.EndInit ( ) ; image.Freeze ( ) ; return image ; }",BitmapImage OutOfMemoryException only in Windows 8.1 "C_sharp : Why does it display 1337,1,2,3 instead of 1,2,3 ? Is there a way/setting to make JSON.NET overwrite List instead of adding elements to it ? I need a solution that does n't modify the constructor . public class MyClass { public List < int > myList = new List < int > { 1337 } ; public MyClass ( ) { } } var myClass = JsonConvert.DeserializeObject < MyClass > ( `` { myList : [ 1,2,3 ] } '' ) ; Console.WriteLine ( string.Join ( `` , '' , myClass.myList.ToArray ( ) ) ) ; //1337,1,2,3",JSON.NET Why does it Add to List instead of Overwriting ? C_sharp : LINQ method syntaxLINQ query syntax var methodSyntax = VersionControls.Where ( x = > ! x.Removed ) .Max ( x = > x.VersionID ) ; var querySyntax = from x in VersionControls where ! x.Removed // how to do Max Aggregation in LINQ query syntax ? ? ? select x ;,how to do Max Aggregation in LINQ query syntax ? "C_sharp : I have the following XAML code that I want to perform in xaml.cs.Basically it binds the slider to the richtextbox and performs zooming.The following is what i have attempted : < RichTextBox.LayoutTransform > < ScaleTransform ScaleX= '' { Binding ElementName=mySlider , Path=Value } '' ScaleY= '' { Binding ElementName=mySlider , Path=Value } '' / > < /RichTextBox.LayoutTransform > RichTextBox newtext = new RichTextBox ( ) ; ScaleTransform mytran = new ScaleTransform ( ) ; mytran.ScaleX = mySlider.Value ; mytran.ScaleY = mySlider.Value ; newtext.LayoutTransform = mytran ;",Binding a RichTextBox to a Slider Control in C # "C_sharp : If I have an expression of a function delegate that takes a number of parameters like so : is there a way / how can I substitute one of the values ( say 5 for num1 ) and get the equivalent expression to : EDIT : Also needs to resolve complex types , e.g . : Expression < Func < int , int , int , bool > > test = ( num1 , num2 , num3 ) = > num1 + num2 == num3 ; Expression < Func < int , int , bool > > test = ( num2 , num3 ) = > 5 + num2 == num3 ; Expression < Func < Thing , int , int > > test = ( thing , num2 ) = > thing.AnIntProp + num2 ;",Reduce an expression by inputting a parameter "C_sharp : Is there a neat way to ignore exceptions in Linq ? I.e. , lets say I have a class ObjectA that takes a string parameter in its constructor , and within the constructor there is some validation going on - meaning that if the string does not have the correct format , the constructor will throw . By the following code I would get a List of ObjectA from a list of strings : So my question is : Is there a one line linq way , a la ( pseudocode coming up ... ) var result = new List < ObjectA > ( ) ; foreach ( string _s in ListOfFiles ) { try { ObjectA _A = new ObjectA ( _s ) ; result.Add ( _A ) ; } catch { } } var result = ListOfFiles.Select ( n = > try { new ObjectA ( n ) } ) .ToList ( ) ;",Try within Linq query "C_sharp : I have built a windows phone 7 app with a `` sign in with google '' function . Google library is not compatible with windows phone runtime so I choose RestSharp.The app has successfully received a authentication code from Google , and the next step is to exchange the code for an access token and a refresh token . Here I encountered some problem.I 'm not sure how to use the client.ExecuteAsync < T > method ( or any other would be helpful ) to get the response from Google . Is there any other code pre-requested for me to use such method ? Can anybody help me ? var request = new RestRequest ( this.TokenEndPoint , Method.POST ) ; request.AddParameter ( `` code '' , code ) ; request.AddParameter ( `` client_id '' , this.ClientId ) ; request.AddParameter ( `` client_secret '' , this.Secret ) ; request.AddParameter ( `` redirect_uri '' , `` http : //localhost '' ) ; request.AddParameter ( `` grant_type '' , `` authorization_code '' ) ; client.ExecuteAsync < ? ? ? > ( request , ( response ) = > { var passIn = response ; } ) ; // how to use this method ?",How to use RestSharp for Google Authentication ? "C_sharp : I have several similar methods , say eg . CalculatePoint ( ... ) and CalculateListOfPoints ( ... ) . Occasionally , they may not succeed , and need to indicate this to the caller . For CalculateListOfPoints , which returns a generic List , I could return an empty list and require the caller to check this ; however Point is a value type and so I ca n't return null there.Ideally I would like the methods to 'look ' similar ; one solution could be to define them as or alternatively to return a Point ? for CalculatePoint , and return null to indicate failure . That would mean having to cast back to the non-nullable type though , which seems excessive.Another route would be to return the Boolean boSuccess , have the result ( Point or List ) as an 'out ' parameter , and call them TryToCalculatePoint or something ... What is best practice ? Edit : I do not want to use Exceptions for flow control ! Failure is sometimes expected . public Point CalculatePoint ( ... out Boolean boSuccess ) ; public List < Point > CalculateListOfPoints ( ... out Boolean boSuccess ) ;",How to indicate that a method was unsuccessful "C_sharp : Given the following classes : I can create an index that allows client to query the view as follows : This certainly works and produces the desired result of a view with the data transformed to the structure required at the client application . However , it is unworkably verbose , will be a maintenance nightmare and is probably fairly inefficient with all the redundant object construction . Is there a simpler way of creating an index with the required structure ( ViewA ) given a collection of documents ( DocA ) ? FURTHER INFORMATIONThe issue appears to be that in order to have the index hold the data in the transformed structure ( ViewA ) , we have to do a Reduce . It appears that a Reduce must have both a GROUP ON and a SELECT in order to work as expected so the following are not valid : INVALID REDUCE CLAUSE 1 : This produces : System.InvalidOperationException : Variable initializer select must have a lambda expression with an object create expressionClearly we need to have the 'select new'.INVALID REDUCE CLAUSE 2 : This prduces : System.InvalidCastException : Unable to cast object of type 'ICSharpCode.NRefactory.Ast.IdentifierExpression ' to type 'ICSharpCode.NRefactory.Ast.InvocationExpression ' . Clearly , we also need to have the 'group on new'.Thanks for any assistance you can provide . ( Note : removing the type ( ViewA ) from the constructor calls has no effect on the above ) UPDATE WITH CORRECT APPROACHAs outlined in Daniel 's blog mentioned in the answer below , here is the correct way to do this for this example : public class Lookup { public string Code { get ; set ; } public string Name { get ; set ; } } public class DocA { public string Id { get ; set ; } public string Name { get ; set ; } public Lookup Currency { get ; set ; } } public class ViewA // Simply a flattened version of the doc { public string Id { get ; set ; } public string Name { get ; set ; } public string CurrencyName { get ; set ; } // View just gets the name of the currency } public class A_View : AbstractIndexCreationTask < DocA , ViewA > { public A_View ( ) { Map = docs = > from doc in docs select new ViewA { Id = doc.Id , Name = doc.Name , CurrencyName = doc.Currency.Name } ; Reduce = results = > from result in results group on new ViewA { Id = result.Id , Name = result.Name , CurrencyName = result.CurrencyName } into g select new ViewA { Id = g.Key.Id , Name = g.Key.Name , CurrencyName = g.Key.CurrencyName } ; } } Reduce = results = > from result in results group on new ViewA { Id = result.Id , Name = result.Name , CurrencyName = result.CurrencyName } into g select g.Key ; Reduce = results = > from result in results select new ViewA { Id = result.Id , Name = result.Name , CurrencyName = result.CurrencyName } ; public class A_View : AbstractIndexCreationTask < DocA , ViewA > { public A_View ( ) { Map = docs = > from doc in docs select new ViewA { Id = doc.Id , Name = doc.Name , CurrencyName = doc.Currency.Name } ; // Top-level properties on ViewA that match those on DocA // do not need to be stored in the index . Store ( x = > x.CurrencyName , FieldStorage.Yes ) ; } }",Simplest way to flatten document to a view in RavenDB "C_sharp : I 'm trying to use libgit2sharp to get a previous version of a file . I would prefer the working directory to remain as is , at the very least restored to previous condition.My initial approach was to try to stash , checkout path on the file I want , save that to a string variable , then stash pop . Is there a way to stash pop ? I ca n't find it easily . Here 's the code I have so far : If there 's an easier approach than using Stash , that would work great also . using ( var repo = new Repository ( DirectoryPath , null ) ) { var currentCommit = repo.Head.Tip.Sha ; var commit = repo.Commits.Where ( c = > c.Sha == commitHash ) .FirstOrDefault ( ) ; if ( commit == null ) return null ; var sn = `` Stash Name '' ; var now = new DateTimeOffset ( DateTime.Now ) ; var diffCount = repo.Diff.Compare ( ) .Count ( ) ; if ( diffCount > 0 ) repo.Stashes.Add ( new Signature ( sn , `` x @ y.com '' , now ) , options : StashModifiers.Default ) ; repo.CheckoutPaths ( commit.Sha , new List < string > { path } , CheckoutModifiers.None , null , null ) ; var fileText = File.ReadAllText ( path ) ; repo.CheckoutPaths ( currentCommit , new List < string > { path } , CheckoutModifiers.None , null , null ) ; if ( diffCount > 0 ) ; // stash Pop ? }",How do I get a previous version of a file with libgit2sharp "C_sharp : Here is the culmination of a Skeet posting for a random provider : I would like to use the same concept in a .NET 3.5 project , so ThreadLocal is not an option . How would you modify the code to have a thread safe random provider without the help of ThreadLocal ? UPDATEOk , am going with Simon 's [ ThreadStatic ] for now since I understand it the best . Lots of good info here to review and rethink as time allows . Thanks all ! public static class RandomProvider { private static int seed = Environment.TickCount ; private static ThreadLocal < Random > randomWrapper = new ThreadLocal < Random > ( ( ) = > new Random ( Interlocked.Increment ( ref seed ) ) ) ; public static Random GetThreadRandom ( ) { return randomWrapper.Value ; } } public static class RandomProvider { private static int _seed = Environment.TickCount ; [ ThreadStatic ] private static Random _random ; /// < summary > /// Gets the thread safe random . /// < /summary > /// < returns > < /returns > public static Random GetThreadRandom ( ) { return _random ? ? ( _random = new Random ( Interlocked.Increment ( ref _seed ) ) ) ; } }",Implementing a Random provider in .Net 3.5 "C_sharp : In C # , I have a method with the following signature : Inside Load ( ) method , i 'd like to dump full method name ( for debugging purposes ) , including the generic type . eg : calling Load < SomeRepository > ( ) ; would write `` Load < SomeRepository > '' What i have try so far : using MethodBase.GetCurrentMethod ( ) and GetGenericArguments ( ) to retrieve information.Retrieving method name works , but for generic parameter it always return me `` T '' . Method returns Load < T > instead of Load < SomeRepository > ( which is useless ) I have tried to call GetGenericArguments ( ) outside GetMethodName ( ) and provide it as argument but it does n't help . I could provide typeof ( T ) as a parameter of GetMethodName ( ) ( it will works ) but then it will be specific to number of generic types eg : with Load < T , U > it would not work anymore , unless I provide the other argument . List < T > Load < T > ( Repository < T > repository ) List < T > Load < T > ( Repository < T > repository ) { Debug.WriteLine ( GetMethodName ( MethodBase.GetCurrentMethod ( ) ) ) ; } string GetMethodName ( MethodBase method ) { Type [ ] arguments = method.GetGenericArguments ( ) ; if ( arguments.Length > 0 ) return string.Format ( `` { 0 } < { 1 } > '' , method.Name , string.Join ( `` , `` , arguments.Select ( x = > x.Name ) ) ) ; else return method.Name ; }","How to retrieve name of a generic method , including generic types names" "C_sharp : Is there an attribute I can use to tell the compiler that a method must always be optimized , even if the global /o+ compiler switch is not set ? The reason I ask is because I 'm toying with the idea of dynamically creating a method based on the IL code of an existing method ; the manipulation I want to do is reasonably easy when the code is optimized , but becomes significantly harder in non-optimized code , because of the extra instructions generated by the compiler.EDIT : more details about the non-optimizations that bother me ... Let 's consider the following implementation of the factorial function : ( Note : I know there are better ways to compute the factorial , this is just an example ) The IL generated with optimizations enabled is quite straightforward : But the unoptimized version is quite differentIt is designed to have only one exit point , at the end . The value to return is stored in a local variable.Why is this an issue ? I want to dynamically generate a method that includes tail call optimization . The optimized method can easily be modified by adding the tail . prefix before the recursive call , since there nothing after the call except ret . But with the unoptimized version , I 'm not so sure ... the result of the recursive call is stored in a local variable , then there 's a useless branch that just jumps to the next instruction , the the local variable is loaded and returned . So I have no easy way of checking that the recursive call really is the last instruction , so I ca n't be sure that tail call optimization can be applied . static long FactorialRec ( int n , long acc ) { if ( n == 0 ) return acc ; return FactorialRec ( n - 1 , acc * n ) ; } IL_0000 : ldarg.0 IL_0001 : brtrue.s IL_0005IL_0003 : ldarg.1 IL_0004 : ret IL_0005 : ldarg.0 IL_0006 : ldc.i4.1 IL_0007 : sub IL_0008 : ldarg.1 IL_0009 : ldarg.0 IL_000A : conv.i8 IL_000B : mul IL_000C : call UserQuery.FactorialRecIL_0011 : ret IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldc.i4.0 IL_0003 : ceq IL_0005 : ldc.i4.0 IL_0006 : ceq IL_0008 : stloc.1 IL_0009 : ldloc.1 IL_000A : brtrue.s IL_0010IL_000C : ldarg.1 IL_000D : stloc.0 IL_000E : br.s IL_001FIL_0010 : ldarg.0 IL_0011 : ldc.i4.1 IL_0012 : sub IL_0013 : ldarg.1 IL_0014 : ldarg.0 IL_0015 : conv.i8 IL_0016 : mul IL_0017 : call UserQuery.FactorialRecIL_001C : stloc.0 IL_001D : br.s IL_001FIL_001F : ldloc.0 IL_0020 : ret",Can I force the compiler to optimize a specific method ? "C_sharp : I 'm crafting this `` what you are listening to '' - plugin for learning purposes that displays the current Spotify or Winamp song as a message in an IM client.So far it 's really simple , I 'm merely getting the song played from the title like soand then just pick out the song part ( `` Spotify - < song title > '' ) However , most people do n't keep the main window open or minimized to the taskbar , but have it visible only as a tray icon . I 'd like to get the text from there ( the one displayed when hovering above it ) .Is there any easy way of doing this ? Thanks Process.GetProcessesByName ( `` spotify '' ) ; proc.MainWindowTitle.Substring ( 10 ) ;",C # Getting the text off notifyIcons ( tray icons ) "C_sharp : I would like to have some kind of catch-all exceptions mechanism in the root of my code , so when an app terminates unexpectedly I can still provide some useful logging.Something along the lines ofWhile this all works fine , my problem is when I want to attach the debugger after the exception has been raised.Since the exception escapes to the runtime , windows will prompt to attach visual studio , except , since it has been rethrown , all locals and parameters further up the stack have been lost.Is there anyway to log these exceptions , while still providing a way to attach the debugger and retain all useful information ? static void Main ( ) { if ( Debugger.IsAttached ) RunApp ( ) ; else { try { RunApp ( ) ; } catch ( Exception e ) { LogException ( e ) ; throw ; } } }",Attaching the .net debugger while still providing useful logging on death "C_sharp : I am making a height-adjustable and vertically alignable textbox with following code . The reason why I should do this is because although I can make winform textbox height-adjustable , I still ca n't vertically align the text in the textbox . So I decided I have to draw the text OnPaint event . The textbox is showing correct alignment now , but cursor is still located on top of textbox . Is there any way to control this position as well ? public class TextBoxHeightAdjustable : System.Windows.Forms.TextBox { public TextBoxHeightAdjustable ( ) { this.AutoSize = false ; this.TextAlign = System.Windows.Forms.HorizontalAlignment.Center ; this.SetStyle ( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw , true ) ; } protected override void OnPaint ( PaintEventArgs e ) { // This never runs no matter what I try ! base.OnPaint ( e ) ; // Create a StringFormat object with the each line of text , and the block // of text centered on the page . StringFormat stringFormat = new StringFormat ( ) ; stringFormat.Alignment = StringAlignment.Center ; stringFormat.LineAlignment = StringAlignment.Center ; e.Graphics.DrawString ( Text , Font , new SolidBrush ( ForeColor ) , ClientRectangle , stringFormat ) ; } }",How to set location of cursor in Textbox "C_sharp : The issue comes when you open a page with only one record . It fills the NavMenu with three links ; `` First '' , `` 1 '' and `` Last '' .For some reason , when you run a search query that will return more than one page , it still only displays `` First '' , `` 1 '' and `` Last '' . Similarly , if you start with four pages and your subsequent search query only returns two records , it still shows `` First '' , `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' and `` Last '' . So , for some reason , however many pages you start with , you 'll always get . How can you reset the page counter/display ? Here 's my C # code-behind : And on the aspx page : I did try NavMenu.Items.Clear ( ) , but it did n't like that because it also cleared out the hard-coded item on the aspx side . public void RunTheSearch ( ) { //Run the Stored Procedure first SqlConnection connection2 = new SqlConnection ( strCon1 ) ; SqlCommand cmd2 = new SqlCommand ( ) ; cmd2.CommandType = CommandType.StoredProcedure ; cmd2.CommandText = `` sp_Search '' ; cmd2.Connection = connection2 ; // -- - A bunch of code that returns a dataset . Lengthy and unnecessary to my issue connection2.Open ( ) ; SqlDataAdapter adp = new SqlDataAdapter ( cmd2 ) ; DataSet ds = new DataSet ( ) ; adp.Fill ( ds , `` OLDPages '' ) ; //Pagination code so only a set number of records loads at a time . // Done to speed up the loading , since this list gets really long . PagedDataSource pds = new PagedDataSource ( ) ; pds.DataSource = ds.Tables [ `` OLDPages '' ] .DefaultView ; pds.AllowPaging = true ; pds.PageSize = 10 ; //NavMenu.Items.Clear ( ) ; int currentPage ; if ( Request.QueryString [ `` page '' ] ! = null ) { currentPage = Int32.Parse ( Request.QueryString [ `` page '' ] ) ; } else { currentPage = 1 ; } pds.CurrentPageIndex = currentPage - 1 ; //Label1.Text = `` Page `` + currentPage + `` of `` + pds.PageCount ; if ( ! pds.IsFirstPage ) { MenuItem itemMessage = NavMenu.FindItem ( `` First '' ) ; itemMessage.NavigateUrl = Request.CurrentExecutionFilePath + `` ? page=1 '' ; } AcctRepeater.DataSource = pds ; AcctRepeater.DataBind ( ) ; CreatePagingControl ( pds.PageCount , pds.CurrentPageIndex ) ; // End of Pagination code connection2.Close ( ) ; } private void CreatePagingControl ( int PCount , int PIndex ) { int PIndex2 = 0 ; int SCounter = PIndex + 1 ; int RowCount = PCount ; //Allow the pagination menu to always start 5 less than the current page you 're on if ( PIndex < 5 ) { PIndex2 = 0 ; } else { PIndex2 = PIndex - 5 ; } // Show 10 total page numbers . You can increase or shrink that range by changing the 10 to whatever number you want for ( int i = PIndex2 ; i < PIndex2 + 10 & & i < PCount ; i++ ) { NavMenu.Items.Add ( new MenuItem { Text = ( i + 1 ) .ToString ( ) , NavigateUrl = Request.CurrentExecutionFilePath + `` ? page= '' + ( i + 1 ) .ToString ( ) } ) ; // Now determine the selected item so the proper CSS can be applied foreach ( MenuItem item in NavMenu.Items ) { item.Selected = item.Text.Equals ( SCounter.ToString ( ) ) ; } } NavMenu.Items.Add ( new MenuItem { Text = `` Last '' , NavigateUrl = Request.CurrentExecutionFilePath + `` ? page= '' + ( PCount ) } ) ; } < asp : Menu ID= '' NavMenu '' runat= '' server '' CssClass= '' menu '' IncludeStyleBlock= '' false '' Orientation= '' Horizontal '' width= '' 703px '' BackColor= '' # CC3300 '' EnableViewState= '' true '' > < Items > < asp : MenuItem NavigateUrl= '' ~/Default.aspx '' Text= '' First '' Selectable= '' true '' / > < /Items > < /asp : Menu >",Paging in ASP.NET ; the number of pages never changes after filtering "C_sharp : MSDN says : The styles parameter affects the interpretation of strings parsed using custom format strings . It determines whether input is interpreted as a negative time interval only if a negative sign is present ( TimeSpanStyles.None ) , or whether it is always interpreted as a negative time interval ( TimeSpanStyles.AssumeNegative ) . If TimeSpanStyles.AssumeNegative is not used , format must include a literal negative sign symbol ( such as `` - '' ) to successfully parse a negative time interval.I have try the following : However it returns 07:00:00 . And fails for `` 0700 '' .If I try : It fails too.Does not fail for both `` 0700 '' and `` -0700 '' , but always return the positive 07:00:00.How is it supposed to be used ? TimeSpan.ParseExact ( `` -0700 '' , @ '' \-hhmm '' , null , TimeSpanStyles.None ) TimeSpan.ParseExact ( `` -0700 '' , `` hhmm '' , null , TimeSpanStyles.None ) TimeSpan.ParseExact ( `` 0700 '' , new string [ ] { `` hhmm '' , @ '' \-hhmm '' } , null , TimeSpanStyles.None )",Parsing TimeSpan with optional minus sign "C_sharp : I have a WPF DataGrid and I want some columns to have different colors.I found posts about hard setting the background but I want something more smooth . It should fit in the mouse-over and selection actions and color accordingly but in a different color tone.I want to make the difference visual for `` default '' columns , important columns and `` readonly '' columns.Something like the above . Columns in different colors but still change colors a little bit if the row is selected for instance.But how ? < DataGrid > < DataGrid.Columns > < DataGridTextColumn Header= '' Name '' Binding= '' { Binding Name } '' / > < DataGridTemplateColumn Header= '' Weight '' > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < TextBlock Text= '' { Binding Path=Weight } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < TextBox Text= '' { Binding Path=Weight } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < /DataGridTemplateColumn > < DataGridTextColumn Header= '' Created At '' Binding= '' { Binding CreatedAt } '' / > < /DataGrid.Columns > < /DataGrid >",Having different color tones for DataGrid columns "C_sharp : Is not possible ( except use different name ) to have several generic methods with the same name but implementing different interface ? Thanks , public IList < T > List < T > ( ) where T : class , IMyInterface1 { return mylist } public IList < T > List < T > ( ) where T : class , IMyInterface2 { return mylist }",Two generic methods with the same name "C_sharp : The normal behavior for exceptions thrown from async Task methods is to stay dormant until they get observed later , or until the task gets garbage-collected . I can think of cases where I may want to throw immediately . Here is an example : I could use async void to get around this , which throws immediately : Now I can handle this exception right on the spot with Dispatcher.UnhandledException or AppDomain.CurrentDomain.UnhandledException , at least to bring it to the user attention immediately.Is there any other options for this scenario ? Is it perhaps a contrived problem ? public static async Task TestExAsync ( string filename ) { // the file is missing , but it may be there again // when the exception gets observed 5 seconds later , // hard to debug if ( ! System.IO.File.Exists ( filename ) ) throw new System.IO.FileNotFoundException ( filename ) ; await Task.Delay ( 1000 ) ; } public static void Main ( ) { var task = TestExAsync ( `` filename '' ) ; try { Thread.Sleep ( 5000 ) ; // do other work task.Wait ( ) ; // wait and observe } catch ( AggregateException ex ) { Console.WriteLine ( new { ex.InnerException.Message , task.IsCanceled } ) ; } Console.ReadLine ( ) ; } // disable the `` use await '' warning # pragma warning disable 1998public static async void ThrowNow ( Exception ex ) { throw ex ; } # pragma warning restore 1998public static async Task TestExAsync ( string filename ) { if ( ! System.IO.File.Exists ( filename ) ) ThrowNow ( new System.IO.FileNotFoundException ( filename ) ) ; await Task.Delay ( 1000 ) ; }",Throwing immediately from async method "C_sharp : I am writing a program that attempts to duplicate the algorithm discussed at the beginning of this article , http : //www-stat.stanford.edu/~cgates/PERSI/papers/MCMCRev.pdfF is a function from char to char . Assume that Pl ( f ) is a 'plausibility ' measure of that function . The algorithm is : Starting with a preliminary guess at the function , say f , and a then new function f* -- Compute Pl ( f ) .Change to f* by making a random transposition of the values f assigns to two symbols.Compute Pl ( f* ) ; if this is larger than Pl ( f ) , accept f*.If not , flip a Pl ( f ) /Pl ( f* ) coin ; if it comes up heads , accept f*.If the coin toss comes up tails , stay at f.I am implementing this using the following code . I 'm using c # but tried to make it somewhat more simplified for everyone . If there is a better forum for this please let me know . My question is basically whether this looks like the optimal approach to implementing that algorithm . IT seems like I may be getting stuck in some local maxima / local minima despite implementing this method . EDIT - Here is the essentially whats behind Transpose ( ) method . I use a dictionary / hash table of type < < char , char > > that the candidate function ( s ) use to look any given char - > char transformation . So the transpose method simply swaps two values in the dictionary that dictates the behavior of the function . Keep in mind that a candidate function that uses the underlying dictionary is basically just : And this is the function that computes Pl ( f ) : var current_f = Initial ( ) ; // current accepted function f var current_Pl_f = InitialPl ( ) ; // current plausibility of accepted function f for ( int i = 0 ; i < 10000 ; i++ ) { var candidate_f = Transpose ( current_f ) ; // create a candidate function var candidate_Pl_f = ComputePl ( candidate_f ) ; // compute its plausibility if ( candidate_Pl_f > current_Pl_f ) // candidate Pl has improved { current_f = candidate_f ; // accept the candidate current_Pl_f = candidate_Pl_f ; } else // otherwise flip a coin { int flip = Flip ( ) ; if ( flip == 1 ) // heads { current_f = candidate_f ; // accept it anyway current_Pl_f = candidate_Pl_f ; } else if ( flip == 0 ) // tails { // what to do here ? } } } private Dictionary < char , char > Transpose ( Dictionary < char , char > map , params int [ ] indices ) { foreach ( var index in indices ) { char target_val = map.ElementAt ( index ) .Value ; // get the value at the index char target_key = map.ElementAt ( index ) .Key ; // get the key at the index int _rand = _random.Next ( map.Count ) ; // get a random key ( char ) to swap with char rand_key = map.ElementAt ( _rand ) .Key ; char source_val = map [ rand_key ] ; // the value that currently is used by the source of the swap map [ target_key ] = source_val ; // make the swap map [ rand_key ] = target_val ; } return map ; } public char GetChar ( char in , Dictionary < char , char > theMap ) { return theMap [ char ] ; } public decimal ComputePl ( Func < char , char > candidate , string encrypted , decimal [ ] [ ] _matrix ) { decimal product = default ( decimal ) ; for ( int i = 0 ; i < encrypted.Length ; i++ ) { int j = i + 1 ; if ( j > = encrypted.Length ) { break ; } char a = candidate ( encrypted [ i ] ) ; char b = candidate ( encrypted [ j ] ) ; int _a = GetIndex ( _alphabet , a ) ; // _alphabet is just a string/char [ ] of all avl chars int _b = GetIndex ( _alphabet , b ) ; decimal _freq = _matrix [ _a ] [ _b ] ; if ( product == default ( decimal ) ) { product = _freq ; } else { product = product * _freq ; } } return product ; }",Algorithm for computing the plausibility of a function / Monte Carlo Method "C_sharp : I have the following interface and implementation : I 'm going to have multiple implementations that all return different data by Entity Framework . At some point I want to represent the user a list of classes that implement the IRepository interface . I do this with the following code . This works great for me.However , I would also like to create a factory method that given a specific string will return a concrete Repository type and allow me to call the 'GetAll ' method on it . In pseudo-code : ( I know this wo n't work because I have to specify a concrete type in the factory method ) .I desire this functionality because I want to give a user the ability to bind a report to a specific datasource . This way they can start a new report where the datasource of the report is bound to ( for example ) the TrendDataRepository.GetAll ( ) method.However , maybe because the end of the world is getting near ; - ) or it 's Friday afternoon and I just ca n't think clearly any more , I do n't know how to realise this . Some pointers would be really welcomed . public interface IRepository < T > { IList < T > GetAll ( ) ; } internal class TrendDataRepository : IRepository < TrendData > { public IList < TrendData > GetAll ( ) { //.. returns some specific data via Entity framework } } public static IEnumerable < string > GetAvailableRepositoryClasses ( ) { var repositories = from t in Assembly.GetExecutingAssembly ( ) .GetTypes ( ) where t.GetInterfaces ( ) .Any ( x = > x.IsGenericType & & x.GetGenericTypeDefinition ( ) == typeof ( IRepository < > ) ) select t.Name ; return repositories ; } someObject = Factory.CreateInstance ( `` TrendData '' ) ; someObject.GetAll ( ) ;",Factory method and generics C_sharp : Why ca n't open generic types be passed as parameters . I frequently have classes like : Lets say BaseClass is as follows ; I then want a method of say : I then have to write an interface just to pass this one class as a parameter as follows : The generic class then has to be modified to : That 's a lot of ceremony for what I would have thought the compiler could infer . Even if something ca n't be changed I find it psychologically very helpful if I know the reasons / justifications for the absence of Syntax short cuts . public class Example < T > where T : BaseClass { public int a { get ; set ; } public List < T > mylist { get ; set ; } } public BaseClass { public int num ; } public int MyArbitarySumMethod ( Example example ) //This wo n't compile Example not closed { int sum = 0 ; foreach ( BaseClass i in example.myList ) //myList being infered as an IEnumerable sum += i.num ; sum = sum * example.a ; return sum ; } public interface IExample { public int a { get ; set ; } public IEnumerable < BaseClass > myIEnum { get ; } } public class Example < T > : IExample where T : BaseClass { public int a { get ; set ; } public List < T > mylist { get ; set ; } public IEnumerable < BaseClass > myIEnum { get { return myList ; } } },c # Why ca n't open generic types be passed as parameters ? "C_sharp : I 've registered several types in Unity and given them type aliases as follows : Is it possible to resolve these types by from the container using the aliased name ( as opposed to by type ) , along the lines of : I ca n't see any way to do this , but wondered if I 've missed something . < typeAliases > < typeAlias alias= '' MyType '' type= '' foo.bar.MyType , foo.bar '' / > < /typeAliases > var myType = container.ResolveByTypeAlias ( `` MyType '' )","In Unity , is it possible to resolve a type from its type alias ?" "C_sharp : I 'm working on the UWP application . And I 'm using async/await a lot . Always when an exception occurs in my code the debugger set break in App.g.i.csBut I want to see the line when the exception occured . How to achieve that behavior ? # if DEBUG & & ! DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION UnhandledException += ( sender , e ) = > { if ( global : :System.Diagnostics.Debugger.IsAttached ) global : :System.Diagnostics.Debugger.Break ( ) ; } ; # endif",Exceptions debugging with async and UWP "C_sharp : In a typical .NET app , product and version information are stored in the AssemblyInfo.cs file under the 'Properties ' folder , like so ... In our case , we have a solution where we need to keep version information synced across eleven DLLs.To accomplish this , we first removed any shared values from each project 's AssemblyInfo.cs file , leaving only those values specific to that particular project.We then placed all of the shared values in a second file called AssemblyInfo_Shared.cs which we store in a sibling folder to those of the projects . We then add that file to each project 's 'Properties ' folder via a link ( that 's the little 'down ' arrow on the button when you 're adding it . ) By doing this , all related DLLs share the same version information while still retaining assembly-specific properties as well . It makes keeping a set of versioned DLLs in sync a piece of cake as we edit a single file and all eleven DLLs ' versions update at once.Here 's what it looks like ... The contents of AssemblyInfo.cs in Project A looks like this ... This is project B'sAnd here 's the shared ... With the above , both DLLs share the same version information since the common file is 'merged ' with the project-specific one when building . Hope this makes sense.However , in .NET Standard projects , it looks like the version information is baked right into the Project file under the < PropertyGroup > section , so I 'm not sure how we can achieve the same capability.Does .NET Standard have anything that supports this ? DLL Project - Properties Folder - AssemblyInfo.cs Common Folder - AssemblyInfo_Shared.cs ( Actual ) DLL Project A - Properties Folder - AssemblyInfo.cs // Only values specific to A - AssemblyInfo_Shared.cs ( Link ) DLL Project B - Properties Folder - AssemblyInfo.cs // Only values specific to B - AssemblyInfo_Shared.cs ( Link ) using System.Reflection ; [ assembly : AssemblyTitle ( `` SomeApp.LibA '' ) ] [ assembly : AssemblyDescription ( `` This is the code for A '' ) ] using System.Reflection ; [ assembly : AssemblyTitle ( `` SomeApp.LibB '' ) ] [ assembly : AssemblyDescription ( `` This is the code for Project B '' ) ] using System ; using System.Reflection ; using System.Resources ; using System.Runtime.InteropServices ; [ assembly : AssemblyProduct ( `` SomeApp '' ) ] [ assembly : AssemblyVersion ( `` 1.4.3.0 '' ) ] [ assembly : AssemblyFileVersion ( `` 1.4.3.0 '' ) ] [ assembly : AssemblyCompany ( `` MyCo '' ) ] [ assembly : AssemblyCopyright ( `` Copyright ( c ) 2010-2018 , MyCo '' ) ] [ assembly : ComVisible ( false ) ] [ assembly : NeutralResourcesLanguage ( `` en-US '' ) ] [ assembly : CLSCompliant ( true ) ]",Can you share version information between .NET Standard libraries ? "C_sharp : I am just curious , in Java , there is a @ Transactional attribute which can be placed above the method name and because almost every application service method use 's transaction , it may simplify the code.This is currently how it is done in .NETIs it possible to manage transaction 's via annotation attribute in .NET Core too ? // Java examplepublic class FooApplicationService { @ Transactional public void DoSomething ( ) { // do something ... } } // .NET examplepublic class FooApplicationService { public void DoSomething ( ) { using ( var transaction = new TransactionScope ( ) ) { // do something ... transaction.Complete ( ) ; } } }",Transactional annotation attribute in .NET Core "C_sharp : I 've been having some issues with static constructors with my project . I need to add a static constructor to the type `` '' in order to call my resource decryption method.Below in the gif you will see the issue I run into.I will also include the code snippet.Code for creating cctor : I have also tried changing the attributes to the exact same as Yano 's . It somehow never works . By `` works '' I mean detect it as a static constructor in DotNet Resolver.Here 's some more information about real outcome and expected result.I do not have an ResolveEventHandler attached to my entrypoint . I have it attached to the application , which is being obfuscated and it is located in the `` '' type 's static constructor which is executed before even the entrypoint is called.Application resources have been encrypted with AES and are not recognised as valid resources by dotnet resolver or other decompilers . I am simply asking why the event is not being triggered as it should be triggered when a resource is invalid or missing . As you can see in the example a messagebox should pop up before the application is launched but it never does ( string encryption encrypts the strings , so its a bit hard to see theres a string there ) .Any help is appreciated . MethodDefinition method = new MethodDefinition ( `` .cctor '' , Mono.Cecil.MethodAttributes.Private | Mono.Cecil.MethodAttributes.Static | Mono.Cecil.MethodAttributes.HideBySig | Mono.Cecil.MethodAttributes.SpecialName | Mono.Cecil.MethodAttributes.RTSpecialName , mod.Import ( typeof ( void ) ) ) ;",Static Constructor Creation [ Mono.Cecil ] "C_sharp : I have the following code which i 'd like to test : It is important that the EndSession Task only ends once the ` _keepAliveTask ' ended . However , I 'm struggling to find a way to test it reliably.Question : How do i unit test the EndSession method and verify that the Task returned by EndSession awaits the _keepAliveTask.For demonstration purposes , the unit test could look like that : Further criterias : - reliable test ( always passes when implementation is correct , always fails when implementation is wrong ) - can not take longer than a few milliseconds ( it 's a unit test , after all ) .I have already taken several alternatives into considerations which i 'm documenting below : non-async methodIf there would n't be the call to _logOutCommand.LogOutIfPossible ( ) it would be quite simple : i 'd just remove the async and return _keepAliveTask instead of awaiting it : The unit test would look ( simplified ) : However , there 's two arguments against this : i have multiple task which need awaiting ( i 'm considering Task.WhenAll further down ) doing so only moves the responsibility to await the task to the caller of EndSession . Still will have to test it there.non-async method , sync over asyncOf course , I could do something similar : But that is a no-go ( sync over async ) . Plus it still has the problems of the previous approach.non-async method using Task.WhenAll ( ... ) Is a ( valid ) performance improvement but introduces more complexity : - difficult to get right without hiding a second exception ( when both fail ) - allows parallel execution Since performance is n't key here i 'd like to avoid the extra complexity . Also , previously mentioned issue that it just moves the ( verification ) problem to the caller of the EndSession method applies here , too.observing effects instead of verifying callsNow of course instead of `` unit '' testing method calls etc . I could always observe effects . Which is : As long as _keepAliveTask has n't ended the EndSession Task must n't end either . But since I ca n't wait indefinite one has to settle for a timeout . The tests should be fast so a timeout like 5 seconds is a no go . So what I 've done is : But I really really dislike this approach : hard to understandunreliableor - when it 's quite reliable - it takes a long time ( which unit tests should n't ) . private Task _keepAliveTask ; // get 's assigned by object initializerpublic async Task EndSession ( ) { _cancellationTokenSource.Cancel ( ) ; // cancels the _keepAliveTask await _logOutCommand.LogOutIfPossible ( ) ; await _keepAliveTask ; } public async Task EndSession_MustWaitForKeepAliveTaskToEnd ( ) { var keepAliveTask = new Mock < Task > ( ) ; // for simplicity sake i slightly differ from the other examples // by passing the task as method parameter await EndSession ( keepAliveTask ) ; keepAliveTask.VerifyAwaited ( ) ; // this is what i want to achieve } public Task EndSession ( ) { _cancellationTokenSource.Cancel ( ) ; return _keepAliveTask ; } public void EndSession_MustWaitForKeepAliveTaskToEnd ( ) { var keepAliveTask = new Mock < Task > ( ) ; // for simplicity sake i slightly differ from the other examples // by passing the task as method parameter Task returnedTask = EndSession ( keepAliveTask ) ; returnedTask.Should ( ) .be ( keepAliveTask ) ; } public Task EndSession ( ) { _cancellationTokenSource.Cancel ( ) ; // cancels the _keepAliveTask _logOutCommand.LogOutIfPossible ( ) .Wait ( ) ; return _keepAliveTask ; } [ Test ] public void EndSession_MustWaitForKeepAliveTaskToEnd ( ) { var keepAlive = new TaskCompletionSource < bool > ( ) ; _cancelableLoopingTaskFactory .Setup ( x = > x.Start ( It.IsAny < ICancelableLoopStep > ( ) , It.IsAny < CancellationToken > ( ) ) ) .Returns ( keepAlive.Task ) ; _testee.StartSendingKeepAlive ( ) ; _testee.EndSession ( ) .Wait ( TimeSpan.FromMilliseconds ( 20 ) ) .Should ( ) .BeFalse ( ) ; }",Verify that task is being awaited "C_sharp : Let 's say I have this model : And whis this codes , I am trying to render input with check type : But , the results are different : How and why , the first one generates attributes for client-side validation , while the other did n't ? Update : After swapping the order of @ Html.CheckBoxFor and @ Html.CheckBox , the order of markup elements did n't change . public class Person { public bool IsApproved { get ; set ; } } @ Html.CheckBoxFor ( x = > x.IsApproved ) @ Html.CheckBox ( `` IsApproved '' ) // CheckBoxFor result < input data-val= '' true '' data-val-required= '' The IsApproved field is required . '' id= '' IsApproved '' name= '' IsApproved '' type= '' checkbox '' value= '' true '' > < input name= '' IsApproved '' type= '' hidden '' value= '' false '' > // CheckBox result < input id= '' IsApproved '' name= '' IsApproved '' type= '' checkbox '' value= '' true '' > < input name= '' IsApproved '' type= '' hidden '' value= '' false '' >","First html helper generates client-side validation attributes , while the second one does n't" "C_sharp : Is there any way in .net to bind a dictionary of properties to an instance at runtime , i.e. , as if the base object class had a property like : I have come up with a solution involving a static dictionary and extension methodbut this stops the objects from getting GC 'd as the the props collection holds a reference . In fact , this is just about ok for my particular use case , as I can clear the props down manually once I 've finished with the particular thing I 'm using them for , but I wonder , is there some cunning way to tie the ExpandoObject to the key while allowing garbage collection ? public IDictionary Items { get ; } void Main ( ) { var x = new object ( ) ; x.Props ( ) .y = `` hello '' ; } static class ExpandoExtension { static IDictionary < object , dynamic > props = new Dictionary < object , dynamic > ( ) ; public static dynamic Props ( this object key ) { dynamic o ; if ( ! props.TryGetValue ( key , out o ) ) { o = new ExpandoObject ( ) ; props [ key ] = o ; } return o ; } }",adding expando properties to a typed object at runtime in c # "C_sharp : According to MSDN : The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time . Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread . This ensures that the most up-to-date value is present in the field at all times.Please notice the last sentence : This ensures that the most up-to-date value is present in the field at all times.However , there 's a problem with this keyword.I 've read that it can change order of instructions : This means John sets a value to a volatile field , and later Paul wants to read the field , Paul is getting the old value ! What is going here ? Is n't that it 's main job ? I know there are other solutions , but my question is about the volatile keyword . Should I ( as a programmer ) need to prevent using this keyword - because of such weird behavior ? First instruction Second instruction Can they be swapped ? Read Read NoRead Write NoWrite Write No Write Read Yes ! < -- --",Volatile Violates its main job ? "C_sharp : Case 1 : I am Joined two different DB Context by ToList ( ) method in Both Context . Case 2 : And also tried Joining first Db Context with ToList ( ) and second with AsQueryable ( ) . Both worked for me . All I want to know is the difference between those Joinings regarding Performance and Functionality . Which one is better ? var users = ( from usr in dbContext.User.AsNoTracking ( ) select new { usr.UserId , usr.UserName } ) .ToList ( ) ; var logInfo= ( from log in dbContext1.LogInfo.AsNoTracking ( ) select new { log.UserId , log.LogInformation } ) .AsQueryable ( ) ; var finalQuery= ( from usr in users join log in logInfo on usr.UserId equals log.UserId select new { usr.UserName , log.LogInformation } .ToList ( ) ;",What is the difference between Joining two different DB Context using ToList ( ) and .AsQueryable ( ) ? "C_sharp : I 'm working on a bit of code which has an end purpose of letting you use a property expression to set the value of a property with similar syntax to passing a variable as an out or ref parameter.Something along the lines of : And Object.Property will be assigned the value of value.I 'm using the following code to get the owining object of the property : So this would , when used on a property expression like ( ) = > Object.Property , give back the instance of 'Object ' . I 'm somewhat new to using property expressions , and there seems to be many different ways to accomplish things , but I want to extend what I have so far , so that given an expression such as ( ) = > Foo.Bar.Baz it will give the Bar , not Foo . I always want the last containing object in the expression.Any ideas ? Thanks in advance . public static foo ( ( ) = > Object.property , value ) ; public static object GetOwningObject < T > ( this Expression < Func < T > > @ this ) { var memberExpression = @ this.Body as MemberExpression ; if ( memberExpression ! = null ) { var fieldExpression = memberExpression.Expression as MemberExpression ; if ( fieldExpression ! = null ) { var constExpression = fieldExpression.Expression as ConstantExpression ; var field = fieldExpression.Member as FieldInfo ; if ( constExpression ! = null ) if ( field ! = null ) return field.GetValue ( constExpression.Value ) ; } } return null ; }",Getting the owning object of a property from a Property Expression "C_sharp : In one of my classes I have a call to a repository which has some error handling on it . I would like to refactor the error handling code because it is quite repetitive and the only thing that really changes is the message.My code currently looks something like this : I could replace those lines in my catch block with a call to another method which takes an error message value and a logger message value . However I suppose I could also do this using an Action < > parameter but I am very inexperienced at using Func < > and Action < > and do n't really see what benefit I would have using one of those over a method.My question is really what is the best way to refactor this code and why does one way benefit over the other ( as per my example above ) .Thanks for any help . public IList < User > GetUser ( ) { try { return _repository.GetUsers ( ) ; } catch ( WebException ex ) { ErrorMessages.Add ( `` ... '' ) ; _logger.ErrorException ( `` ... '' , ex ) ; } catch ( SoapException ex ) { ErrorMessages.Add ( `` ... '' ) ; _logger.ErrorException ( `` ... '' , ex ) ; } ... etc }",Refactoring exception handling "C_sharp : What is the best way to check if only A is null or only B is null ? I have been trying many different ways to find something that feels clean , and this is how convoluted it has gotten : My best ( and the most obvious ) version is : But I do n't really like that either . ( Sure I could add parenthesis ... ) Is there a standard way of doing this that I never learned ? bool CheckForNull ( object a , object b ) { if ( a == null & & b == null ) { return false ; } if ( a == null || b == null ) { return true ; } return false ; } bool CheckForNull ( object a , object b ) { return a == null & & b ! = null || a ! = null & & b == null ; }",How can I best check if A xor B are null ? "C_sharp : I try to display the number of checked items in the checkedListBox : checkedListBox1.CheckedIndices.CountBut how can i update my count , if i want to display it on label ? I tried to write all in the ItemCheck event : But the count increases even if i uncheck the item : ( I 'd appreciate any help ! private void checkedListBox1_ItemCheck ( object sender , ItemCheckEventArgs e ) { label1.Text= checkedListBox1.CheckedIndices.Count ; }",How to track checks in checkedListBox C # ? C_sharp : I have a class and a method within that class . However this class method returns a string . When I call the class method I do n't get an error even though I 'm not catching the string value return . Is there a way that I can make C # and .net force me to capture the value when returning a value.Here is an example of what I mean.1- create a class test.2- call the class method from program or another classMy compiler while working in Visual Studio does not complain that I 'm not capturing the return value.Is this normal or I 'm missing something . Can I force the compiler to notify me that the function returns a value but I 'm not catching it ? Thanks in advance for any suggestions you may have . class test { public string mystring ( ) { return `` BLAH '' ; } } test mystring = new test ( ) ; mystring.mystring ( ) ;,Force function to return value and make compile error C # "C_sharp : I am trying to void an existing envelope using the updated version of the DocuSign C # Client ( DocuSign.eSign ) .The envelope is in the Sent status and has not been completed or voided already.Currently I have following code : When this code is called , it fails with an ApiException and the following ErrorContent : The message is `` The request contained at least one invalid parameter . Value for 'purgeState ' must be 'documents_queued ' or 'documents_and_metadata_queued ' '' , but according to the docs , I should n't need to supply those parameter if the status is `` voided '' and I have a voided reason.Is there a way to void an envelope using the DocuSign C # Client ? EnvelopesApi envelopesApi = new EnvelopesApi ( ) ; Envelope envelope = envelopesApi.GetEnvelope ( accountId , envelopeId ) ; envelope.Status = `` voided '' ; envelope.VoidedReason = `` This envelope was voided by `` + currentUserName ; // create the recipient view ( aka signing URL ) var updateSummary = envelopesApi.Update ( accountId , envelopeId , envelope ) ; return updateSummary ; { `` errorCode '' : `` INVALID_REQUEST_PARAMETER '' , `` message '' : `` The request contained at least one invalid parameter . Value for 'purgeState ' must be 'documents_queued ' or 'documents_and_metadata_queued ' . '' }",Voiding an envelope using the new DocuSign C # Client "C_sharp : Please , consider the following routes : And the following tests : TEST 1TEST 2This test emulates a situation when I already have route values in request context and try to generate an outgoing url with UrlHelper . The problem is that ( presented in test 2 ) , if I have values for all the segments from the expected route ( here route1 ) and try to replace some of them through routeValues parameter , the wanted route is omitted and the next suitable route is used.So test 1 works well , as the request context already has values for 3 of 5 segments of route 1 , and values for the missing two segments ( namely , year and month ) are passed through the routeValues parameter.Test 2 has values for all 5 segments in the request context . And I want to replace some of them ( namely , month and year ) with other values throught routeValues . But route 1 appears to be not suitable and route 2 is used.Why ? What is incorrect with my routes ? Am I expected to clear request context manually in such circumstances ? EDITThis test makes things more confused . Here I 'm testing route2 . And it works ! I have values for all 4 segments in the request context , pass other values through routeValues , and the generated outgoing url is OK.So , the problem is with route1 . What am I missing ? EDITFrom Sanderson S. Freeman A . - Pro ASP.NET MVC 3 Framework Third Edition : The routing system processes the routes in the order that they were added to the RouteCollection object passed to the RegisterRoutes method . Each route is inspected to see if it is a match , which requires three conditions to be met : A value must be available for every segment variable defined in the URL pattern . To find values for each segment variable , the routing system looks first at the values we have provided ( using the properties of anonymous type ) , then the variable values for the current request , and finally at the default values defined in the route . None of the values we provided for the segment variables may disagree with the default-only variables defined in the route . I do n't have default values in these routes The values for all of the segment variables must satisfy the route constraints . I do n't have constraints in these routes So , according to the first rule I 've specified values in an anonymous type , I do n't have default values . The variable values for the current request - I suppose this to be the values from the request context.What is wrong with these reasonings for route2 , while they work well for route1 ? EDITActually everything started not from unit tests , but from a real mvc application . There I used UrlHelper.Action Method ( String , Object ) to generate outgoing urls . Since this method is utilized in a layout view ( the parent one for the majority of all views ) , I 've taken it into my extension helper method ( to exclude extra logic from views ) , This extension method extracts the action name from the request context , passed to it as an argument . I know I could extract all the current route values through the request context and replace those year and month ( or could I create an anonymous route value collection , containing all the values from the context ) , but I thought it was superfluous , as mvc automatically took into account the values contained in the request context . So , I extracted only action name , as there were no UrlHelper.Action overload without action name ( or I 'd have liked even to `` not specify '' action name too ) , and added the new month and year through anonymous route value object . This is an extension method : As I described in the tests above , it worked for shorter routes ( when request context contained only controller , year and month , and action ) , but failed for a longer one ( when request context contained controller , year and month , action , and user ) .I 've posted a workaround I use to make the routing work the way I need . While indeed I would love to find out , why on earth do I have to make any workaround in such scenario and what is the key difference between these two routes that prevents route1 from working the way route2 does.EDITAnother remark . As far as the values in request context are of type string , I decided to try to set them into the context as strings to ensure there were no type confusion ( int vs string ) . I do not understand , what has changed in this respect , but some of the routes started generating correctly . But not all ... This makes yet less sense . I 've changed this in a real application , not tests , as the tests have int in context , not strings.Well , I 've found the condition under which route1 is used - it 's only used when the values of month and year in the context are equal to the ones given in the anonymous object . If they differ ( in the tests this is true both for int and string ) , route2 is used . But why ? This confirms what I have in my real application : I had strings in the context , but provided ints through the anonymous object , it somehow confused the mvc and it could n't use route1 . I changed ints in the anonymous object to strings , and the urls where month and year in context are equal to the ones in the anonymous object , started generating correctly ; whereas all others didn't.So , I see one rule : the properties of the anonymous object should be of type string to match the type of the route values in the request context.But this rule seems to be not compulsory , as in Test3 , I changed the types ( you may see it now above ) and it still works correctly . MVC manages to cast types itself correctly.Finally I found the explanation to all this behaviour . Please , see my answer below . routes.MapRoute ( `` route1 '' , `` { controller } / { month } - { year } / { action } / { user } '' ) ; routes.MapRoute ( `` route2 '' , `` { controller } / { month } - { year } / { action } '' ) ; [ TestMethod ] public void Test1 ( ) { RouteCollection routes = new RouteCollection ( ) ; MvcApplication.RegisterRoutes ( routes ) ; RequestContext context = new RequestContext ( CreateHttpContext ( ) , new RouteData ( ) ) ; DateTime now = DateTime.Now ; string result ; context.RouteData.Values.Add ( `` controller '' , `` Home '' ) ; context.RouteData.Values.Add ( `` action '' , `` Index '' ) ; context.RouteData.Values.Add ( `` user '' , `` user1 '' ) ; result = UrlHelper.GenerateUrl ( null , `` Index '' , null , new RouteValueDictionary ( new { month = now.Month , year = now.Year } ) , routes , context , true ) ; //OK , result == /Home/10-2012/Index/user1 Assert.AreEqual ( string.Format ( `` /Home/ { 0 } - { 1 } /Index/user1 '' , now.Month , now.Year ) , result ) ; } [ TestMethod ] public void Test2 ( ) { RouteCollection routes = new RouteCollection ( ) ; MvcApplication.RegisterRoutes ( routes ) ; RequestContext context = new RequestContext ( CreateHttpContext ( ) , new RouteData ( ) ) ; DateTime now = DateTime.Now ; string result ; context.RouteData.Values.Add ( `` controller '' , `` Home '' ) ; context.RouteData.Values.Add ( `` action '' , `` Index '' ) ; context.RouteData.Values.Add ( `` user '' , `` user1 '' ) ; context.RouteData.Values.Add ( `` month '' , now.Month + 1 ) ; context.RouteData.Values.Add ( `` year '' , now.Year ) ; result = UrlHelper.GenerateUrl ( null , `` Index '' , null , new RouteValueDictionary ( new { month = now.Month , year = now.Year } ) , routes , context , true ) ; //Error because result == /Home/10-2012/Index Assert.AreEqual ( string.Format ( `` /Home/ { 0 } - { 1 } /Index/user1 '' , now.Month , now.Year ) , result ) ; } [ TestMethod ] public void Test3 ( ) { RouteCollection routes = new RouteCollection ( ) ; MvcApplication.RegisterRoutes ( routes ) ; RequestContext context = new RequestContext ( CreateHttpContext ( ) , new RouteData ( ) ) ; DateTime now = DateTime.Now ; string result ; context.RouteData.Values.Add ( `` controller '' , `` Home '' ) ; context.RouteData.Values.Add ( `` action '' , `` Index '' ) ; context.RouteData.Values.Add ( `` month '' , now.Month.ToString ( ) ) ; context.RouteData.Values.Add ( `` year '' , now.Year.ToString ( ) ) ; result = UrlHelper.GenerateUrl ( null , `` Index '' , null , new RouteValueDictionary ( new { month = now.Month + 1 , year = now.Year + 1 } ) , routes , context , true ) ; Assert.AreEqual ( string.Format ( `` /Home/ { 0 } - { 1 } /Index '' , now.Month + 1 , now.Year + 1 ) , result ) ; } public static MvcHtmlString GetPeriodLink ( this HtmlHelper html , RequestContext context , DateTime date ) { UrlHelper urlHelper = new UrlHelper ( context ) ; return MvcHtmlString.Create ( urlHelper.Action ( ( string ) context.RouteData.Values [ `` action '' ] , new { year = date.Year , month = date.Month } ) ) ; }",Unexpected route chosen while generating an outgoing url "C_sharp : I have been tasked with porting data from a MongoDB database to a MySQL database . ( There are strong reasons for porting - so it has to be done ) .The MongoDB collection : Has approx 110 Million documentsWeighs 60 GB in sizeHas indexes for important propertiesIs running of a Windows 2008 standalone separate server which is not serving any production trafficThe Setup that we have tried : An Large Amazon EC2 Win2008 Server instance with 7.5 Gigs of RAM / 8 Gigs of Page FileA C # console app which converts the MongoDB data to a local MySQL databaseWe pick up 1K documents at a time in memory from the MongoDB , do the necessary processing and then save them to the MySQL db doing batch writes of 500 at a time.The problem that we are facing is that every 2.5 M docs , the server chokes up and Mongo responds very slowly - timing out the app 's data fetch operation ( Free RAM gets over by the time 1M documents are processed ) We are moving ahead slowly by killing the mongod process and starting it again every 2.5M records when it crashes - but I bet we 're doing something wrong.Question : Should I move the Mongo Server to a Linux based Large Instance and MySQL to the Amazon RDS for this and rewrite the conversion app in PHP ? Will it help ? The reason we decided to keep it all on one box was the latency issue of having different servers on different boxes - but I guess that is moot if the box is choking up.What other things can I try / tips I can use ? Thanks for reading this far ! -- Update 01 -- Its been approximate 6 hours since I restarted my app and have made the following change : Increased Mongo Read count from 1,000 to 10,000 records at a time . .skip ( 10K ) .limit ( 10K ) Removed all indexes from the MySQL target database.Increased the Windows page size from 4 Gigs to 8 GigsMy memory is at 100 % consumption but the app is running still . ( Last time it croaked in 52 mins ) . Mongo eating 6.8 Gigs of RAM , MySQL - 450 Megs and the converter app - 400 Megs ( approx values ) .Processed 11M records so far - but the speed has gone down to 370 records / sec from approx 500 records / sec.Next steps are going to be to isolate both the Mongo and MySQL servers to separate boxes and - keeping all of them in the same Amazon availability zone to minimize latency. -- Update 02 -- We made some changes in code to use the Mongo Cursor and letting it auto increment automatically as against doing a .skip ( ) .limt ( ) ourselves . This greatly sped up the process and we were doing 1250 records per second from 300 odd earlier . However , the application started consuming too much memory and would run out of RAM and crash and needed to be restarted after every 2M records.We used this code snippet : So what this does is fetch 'numOfResultsToFetchAtATime ' records at a time - but then progresses automatically in the loop and fetches the next set of records . Mongo takes care of this progression using a Cursor and hence it is a lot faster.However , we have still not been able to successfully port this.Will post my reply with code when that happens properly. -- Update 03 : Success -- We finally used @ scarpacci 's suggestion of doing a mongoexport.Do remember that it is essential that the mongodb is on a linux box and not a windows box . We first tried doing a mongoexport from Windows on the local MongoDB and no matter what we tried , it would fail at different places for one large collection ( 13Gigs+ ) Finally , I restored the DB on a Linux box and mongoexport worked like a charm.There is no Json - > MySQL converter - so that much we had to do.With a little tweaking , we were able to use our previous app and read the files and write to MySQL directly . It was quick and relatively error free.We had some issues with the large files , but breaking down the 13GB file to 500 Meg long files helped with that and we were able to migrate all data to MySQL successfully.Many thanks to everyone for spending time helping us out . Hope that this explanation helps someone in the future . var docs = db [ collectionName ] .Find ( query ) ; docs.SetBatchSize ( numOfResultsToFetchAtATime ) ; foreach ( var d in docs ) { // do processing }","Converting data from Mongo to MySQL ( 110M docs , 60Gigs ) - Tips and Suggestions ?" "C_sharp : I 've been confused over the past weeks now about events . I understand how delegates work , not how it works in detail but enough to know thatdelegate datatype is a single cast delegate.delegate void is a multicast delegate - a list of references to methods.I know a delegate type compiles to a class , but unfortunately I am still not sure how the method is referenced . For exampleQuestion 1 : I think myObject is the target , and SomeMethod is the method to reference , but I 'm only passing one input . So is myObject.SomeMethod compiled to a string and is the string split by the period ? Ridiculous I know . Question 2 : When you add to a multicast delegate Every method in the invocation list is called or notified ? If that 's true , why the hell do I need events or the event keyword ? Is it simply to tell the developers that Hey , this is acting as an event ? Because I 'm seriously confused , I just want to move on at this stage lol . This is a sample code I wrote to test it today whether I need event keyword or not.Adding the event keyword to the field public IsEvenNumberEventHandler IsEvenNumberEvent ; has no difference . Please can some explain so that a noob can understand thanks . delegate void TestDelegate ( ) ; TestDelegate testDelegate = new TestDelegate ( myObject.SomeMethod ) ; multicastdelegate+=newmethodtobereferencemulticastdelegate ( ) ; using System ; namespace LambdasETs { public delegate void IsEvenNumberEventHandler ( int numberThatIsEven ) ; public class IsEvenNumberFound { public IsEvenNumberEventHandler IsEvenNumberEvent ; private int number ; public void InputNumber ( int n ) { if ( number % 2 ==0 ) { if ( IsEvenNumberEvent ! = null ) { IsEvenNumberEvent ( n ) ; } } } public static void Main ( ) { IsEvenNumberFound isEvenNumberFound = new IsEvenNumberFound ( ) ; isEvenNumberFound.IsEvenNumberEvent += IsEvenNumberAction ; isEvenNumberFound.InputNumber ( 10 ) ; Console.ReadLine ( ) ; } public static void IsEvenNumberAction ( int number ) { Console.WriteLine ( `` { 0 } is an even number ! `` , number ) ; } } }",Why do Events need Delegates ? Why do we even Need Events ? "C_sharp : I want to build a method which accepts a string param , and an object which I would like to return a particular member of based on the param . So , the easiest method is to build a switch statement : This works fine , but I may wind up with a rather large list ... So I was curious if there 's a way , without writing a bunch of nested if-else structures , to accomplish this in an indexed way , so that the matching field is found by index instead of falling through a switch until a match is found . I considered using a Dictionary < string , something > to give fast access to the matching strings ( as the key member ) but since I 'm wanting to access a member of a passed-in object , I 'm not sure how this could be accomplished . I 'm specifically trying to avoid reflection etc in order to have a very fast implementation . I 'll likely use code generation , so the solution does n't need to be small/tight etc.I originally was building a dictionary of but each object was initializing it . So I began to move this to a single method that can look up the values based on the keys- a switch statement . But since I 'm no longer indexed , I 'm afraid the continuous lookups calling this method would be slow . SO : I am looking for a way to combine the performance of an indexed/hashed lookup ( like the Dictionary uses ) with returning particular properties of a passed-in object . I 'll likely put this in a static method within each class it is used for . public GetMemberByName ( MyObject myobj , string name ) { switch ( name ) { case `` PropOne '' : return myobj.prop1 ; case `` PropTwo '' : return myobj.prop2 ; } }","indexed switch statement , or equivalent ? .net , C #" "C_sharp : I 'm new to C # TPL and DataFlow and I 'm struggling to work out how to implement the TPL DataFlow TransformManyBlock . I 'm translating some other code into DataFlow . My ( simplified ) original code was something like this : And in another method I would call it like this : I 'm trying to create a TransformManyBlock to produce multiple little arrays ( actually data packets ) that come from the larger input array ( actually a binary stream ) , so both in and out are of type byte [ ] .I tried what I 've put below but I know I 've got it wrong . I want to construct this block using the same function as before and to just wrap the TransformManyBlock around it . I got an error `` The call is ambiguous ... '' private IEnumerable < byte [ ] > ExtractFromByteStream ( Byte [ ] byteStream ) { yield return byteStream ; // Plus operations on the array } foreach ( byte [ ] myByteArray in ExtractFromByteStream ( byteStream ) ) { // Do stuff with myByteArray } var streamTransformManyBlock = new TransformManyBlock < byte [ ] , byte [ ] > ( ExtractFromByteStream ) ;",How to construct a TransformManyBlock with a delegate C_sharp : In my code using reflections i wroteI have a class that has an implicit conversion to strings . However the if statement above doesnt catch it . How can i make reflection/the above if statement catch strings and classes with implicit string conversion ? instead of specifically strings and each class i know about ? if ( f.FieldType.IsAssignableFrom ( `` '' .GetType ( ) ) ),Implicit version of IsAssignableFrom ? "C_sharp : In my understanding ( I am not good in threading ) , Join ( ) blocks calling thread until thread on which Join ( ) is called returns.If that is true and Join ( ) is called from UI thread , creating the new thread for some long running operation does not make any sense . There are questions on SO those ask why Join ( ) hangs the application . It looks natural to me.By the way , even it looks natural , my application does not behave accordingly . It does not hang my application.Code without thread that hangs application : -Code with thread that DOES NOT hang application : -Above code works great without hanging application . Function call takes around 15-20 seconds . Why application does not hang ? This is not a problem for me ; actually it 's a good news . But I just do not understand what difference it made ? It does not match with what I read and learn.I am using DotNet Framework 4.0 if that matters . string retValue = `` '' ; retValue = LongRunningHeavyFunction ( ) ; txtResult.Text = retValue ; string retValue = `` '' ; Thread thread = new Thread ( ( ) = > { retValue = LongRunningHeavyFunction ( ) ; } ) ; thread.Start ( ) ; thread.Join ( ) ; txtResult.Text = retValue ;",Why Thread.Join ( ) DOES NOT hang my application when called on UI thread ? C_sharp : I 'm trying to build up a call graph of C # methods and properties . This essentially means that I search the project for MethodDeclarationSyntax and PropertyDeclarationSyntax nodes . I then build connections between these nodes by looking for method invocations via : Is there a similar method or recommended way to find all property `` invocations '' as well ? I believe the C # compiler breaks properties out into Getter and Setter functions on compilation.What 's the best way to detect the usage of properties with Roslyn ? SyntaxNode node = ... ; //Some syntax nodevar methodInvocations = node.DescendantNodesAndSelf ( ) .OfType < InvocationExpressionSyntax > ( ) ; //Process these method invocations,Find property `` invocations '' with Roslyn "C_sharp : Say I have an application resource that contains contact details resources , and contact details contains addresses resources.Eg.When doing a POST to Application , I am creating the root application.For all sub resources like Application Contacts , I do a POST to create Contact 1 etc ... My question is , Application = to submit somewhere for processing , but I do not want to submit it before everything is filled in , aka all children resources.Josh Application -- > Name -- > Application Amount -- > Application Contacts -- > -- > Contact 1 -- > -- > -- > Address -- > -- > Contact 2 -- > -- > -- > Address So the order of submission1 ) Create Application Resource -- > POST /Application -- > Get ID2 ) Create Contact 1 Resource -- > POST /Application/id/Contacts -- > Get ID3 ) Create Contact 1 Address Resource -- > POST /Application/id/Contacts/id/Addresses4 ) Create Contact 2 Resource -- > POST /Application/id/Contacts -- > Get ID 5 ) Create Contact 2 Address Resource -- > POST /Application/id/Contacts/id/Addresses6 ) DECIDE TO SUBMIT HERE < -- - ? ? HOW ?",How to Submit Deeply Nested Resource using Restful APIs ( HATEOAS ) "C_sharp : I 'm writing a class that represents an LED . Basically 3 uint values for r , g and b in the range of 0 to 255.I 'm new to C # and started with uint1 , which is bigger than 8 bit that I want . Before writing my own Clamp method I looked for one online and found this great looking answer suggesting an extension method . The problem is that it could not infer the type to be uint . Why is this ? This code has uint written all over it . I have to explicitly give the type to make it work.1 a mistake , using byte is the way to go of course . But I 'm still interested in the answer to the question . class Led { private uint _r = 0 , _g = 0 , _b = 0 ; public uint R { get { return _r ; } set { _r = value.Clamp ( 0 , 255 ) ; // nope _r = value.Clamp < uint > ( 0 , 255 ) ; // works } } } // https : //stackoverflow.com/a/2683487static class Clamp { public static T Clamp < T > ( this T val , T min , T max ) where T : IComparable < T > { if ( val.CompareTo ( min ) < 0 ) return min ; else if ( val.CompareTo ( max ) > 0 ) return max ; else return val ; } }",Why can the type not be inferred for this generic Clamp method ? "C_sharp : I 'm trying to is generate all possible syllable combinations for a given word . The process for identifying what 's a syllable is n't relevant here , but it 's the generating of all combinations that 's giving me a problem . I think this is probably possible to do recursively in a few lines I think ( though any other way is fine ) , but I 'm having trouble getting it working . Can anyone help ? // how to test a syllable , just for the purpose of this example bool IsSyllable ( string possibleSyllable ) { return Regex.IsMatch ( possibleSyllable , `` ^ ( mis|und|un|der|er|stand ) $ '' ) ; } List < string > BreakIntoSyllables ( string word ) { // the code here is what I 'm trying to write // if 'word ' is `` misunderstand '' , I 'd like this to return // = > { `` mis '' , '' und '' , '' er '' , '' stand '' } , { `` mis '' , '' un '' , '' der '' , '' stand '' } // and for any other combinations to be not included }",Generating combinations of substrings from a string "C_sharp : I have an MVC5 application that uses Castle Windsor ( http : //www.artisancode.co.uk/2014/04/integrating-windsor-castle-mvc/ ) . I recently tried to add an Async method an MVC Controller . When I do this I receive the following error message : The asynchronous action method 'test ' returns a Task , which can not be executed synchronously.I created a new MVC application in VS and did not receive the error , so I 'm guessing I ' v left something out of the Castle Windsor configuration ? However I 've no idea where to begin and I 've been unable to find any article when helps.Updating question with code : CastleWindsorActionInvoker.csWindsorDependencyMvcResolver.csCastleWindsorMvcFactory .csGlobal.asaxMVC Action public class CastleWindsorActionInvoker : ControllerActionInvoker { private readonly IKernel kernel ; public CastleWindsorActionInvoker ( IKernel kernel ) { this.kernel = kernel ; } protected override ActionExecutedContext InvokeActionMethodWithFilters ( ControllerContext controllerContext , IList < IActionFilter > filters , ActionDescriptor actionDescriptor , IDictionary < string , object > parameters ) { foreach ( IActionFilter filter in filters ) { kernel.InjectProperties ( null , filter ) ; } return base.InvokeActionMethodWithFilters ( controllerContext , filters , actionDescriptor , parameters ) ; } protected override AuthorizationContext InvokeAuthorizationFilters ( ControllerContext controllerContext , IList < IAuthorizationFilter > filters , ActionDescriptor actionDescriptor ) { foreach ( IAuthorizationFilter filter in filters ) { Type type = filter.GetType ( ) ; IEnumerable < INamedInstanceAttribute > namedInstanceAttributes = type.GetCustomAttributes ( typeof ( INamedInstanceAttribute ) , false ) as IEnumerable < INamedInstanceAttribute > ; if ( namedInstanceAttributes ! = null ) { this.kernel.InjectProperties ( namedInstanceAttributes , filter ) ; } else { this.kernel.InjectProperties ( null , filter ) ; } } return base.InvokeAuthorizationFilters ( controllerContext , filters , actionDescriptor ) ; } } public class WindsorDependencyMvcResolver : System.Web.Mvc.IDependencyResolver { public IWindsorContainer container { get ; protected set ; } public WindsorDependencyMvcResolver ( IWindsorContainer container ) { if ( container == null ) { throw new ArgumentNullException ( `` container '' ) ; } this.container = container ; } public object GetService ( Type serviceType ) { try { return container.Resolve ( serviceType ) ; } catch ( ComponentNotFoundException ) { return null ; } } public IEnumerable < object > GetServices ( Type serviceType ) { return container.ResolveAll ( serviceType ) .Cast < object > ( ) ; } } public class CastleWindsorMvcFactory : DefaultControllerFactory { private readonly IKernel kernel ; public CastleWindsorMvcFactory ( IKernel kernel ) { this.kernel = kernel ; } protected override IController GetControllerInstance ( RequestContext requestContext , Type controllerType ) { if ( controllerType == null ) { throw new HttpException ( 404 , string.Format ( `` The controller for path ' { 0 } ' could not be found . `` , requestContext.HttpContext.Request.Path ) ) ; } Controller controller = ( Controller ) kernel.Resolve ( controllerType ) ; if ( controller ! = null ) { controller.ActionInvoker = kernel.Resolve < IActionInvoker > ( ) ; } return controller ; } public override void ReleaseController ( IController controller ) { kernel.ReleaseComponent ( controller ) ; } } ControllerBuilder.Current.SetControllerFactory ( new CastleWindsorMvcFactory ( container.Kernel ) ) ; DependencyResolver.SetResolver ( new WindsorDependencyMvcResolver ( container ) ) ; public async Task < ActionResult > Index ( ) { return View ( ) ; }",Async MVC Action with Castle Windsor "C_sharp : I 'm trying to filter a collection of strings by a `` filter '' list ... a list of bad words . The string contains a word from the list I dont want it.I 've gotten so far , the bad Word here is `` frakk '' : But this aint working , why ? string [ ] filter = { `` bad '' , `` words '' , `` frakk '' } ; string [ ] foo = { `` this is a lol string that is allowed '' , `` this is another lol frakk string that is not allowed ! `` } ; var items = from item in foo where ( item.IndexOf ( ( from f in filter select f ) .ToString ( ) ) == 0 ) select item ;",How can I compare a string to a `` filter '' list in linq ? "C_sharp : Implementing Equals ( ) for reference types is harder than it seems . My current canonical implementation goes like this : I think that this covers all corner ( inheritance and such ) cases but I may be wrong . What do you guys think ? public bool Equals ( MyClass obj ) { // If both refer to the same reference they are equal . if ( ReferenceEquals ( obj , this ) ) return true ; // If the other object is null they are not equal because in C # this can not be null . if ( ReferenceEquals ( obj , null ) ) return false ; // Compare data to evaluate equality return _data.Equals ( obj._data ) ; } public override bool Equals ( object obj ) { // If both refer to the same reference they are equal . if ( ReferenceEquals ( obj , this ) ) return true ; // If the other object is null or is of a different types the objects are not equal . if ( ReferenceEquals ( obj , null ) || obj.GetType ( ) ! = GetType ( ) ) return false ; // Use type-safe equality comparison return Equals ( ( MyClass ) obj ) ; } public override int GetHashCode ( ) { // Use data 's hash code as our hashcode return _data.GetHashCode ( ) ; }",What is the `` best '' canonical implementation of Equals ( ) for reference types ? "C_sharp : I 've found a couple of Stack Overflow questions along with a couple of blog posts that already touch on this topic , but unfortunately none of them are meeting my needs . I 'll just start with some sample code to show what I 'd like to accomplish.This code works fine if , instead of using a DispatcherTimer , I use an ordinary Timer . But DispatcherTimer never fires . What am I missing ? What do I need to get it to fire ? using System ; using System.Security.Permissions ; using System.Threading.Tasks ; using System.Windows.Threading ; using Microsoft.VisualStudio.TestTools.UnitTesting ; namespace MyApp { [ TestClass ] public class MyTests { private int _value ; [ TestMethod ] public async Task TimerTest ( ) { _value = 0 ; var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds ( 10 ) } ; timer.Tick += IncrementValue ; timer.Start ( ) ; await Task.Delay ( 15 ) ; DispatcherUtils.DoEvents ( ) ; Assert.AreNotEqual ( 0 , _value ) ; } private void IncrementValue ( object sender , EventArgs e ) { _value++ ; } } internal class DispatcherUtils { [ SecurityPermission ( SecurityAction.Demand , Flags = SecurityPermissionFlag.UnmanagedCode ) ] public static void DoEvents ( ) { var frame = new DispatcherFrame ( ) ; Dispatcher.CurrentDispatcher.BeginInvoke ( DispatcherPriority.Background , new DispatcherOperationCallback ( ExitFrame ) , frame ) ; Dispatcher.PushFrame ( frame ) ; } private static object ExitFrame ( object frame ) { ( ( DispatcherFrame ) frame ) .Continue = false ; return null ; } } }",How can I test a class that uses DispatcherTimer ? "C_sharp : Actually , after clicking on each circle i want its color to be changed , for instance , i want it to turn into red , Overall , i wan na treat it as control.i know how to draw the circles that represent the nodes of the graph when i Double click on the picturebox . i 'm using the following code : public Form1 ( ) { InitializeComponent ( ) ; pictureBox1.Paint += new PaintEventHandler ( pic_Paint ) ; } public Point positionCursor { get ; set ; } private List < Point > points = new List < Point > ( ) ; public int circleNumber { get ; set ; } private void pictureBox1_DoubleClick ( object sender , EventArgs e ) { positionCursor = this.PointToClient ( new Point ( Cursor.Position.X - 25 , Cursor.Position.Y - 25 ) ) ; points.Add ( positionCursor ) ; Label lbl = new Label ( ) ; lbl.BackColor = Color.Transparent ; lbl.Font = new Font ( `` Arial '' , 7 ) ; lbl.Size = new Size ( 20 , 15 ) ; if ( circleNumber > = 10 ) { lbl.Location = new Point ( points [ circleNumber ] .X + 3 , points [ circleNumber ] .Y + 6 ) ; } else { lbl.Location = new Point ( points [ circleNumber ] .X + 7 , points [ circleNumber ] .Y + 7 ) ; } lbl.Text = circleNumber.ToString ( ) ; pictureBox1.Controls.Add ( lbl ) ; circleNumber++ ; pictureBox1.Invalidate ( ) ; } private void pic_Paint ( object sender , PaintEventArgs e ) { Graphics g = e.Graphics ; g.SmoothingMode = SmoothingMode.AntiAlias ; using ( var pen = new Pen ( Color.DimGray , 2 ) ) { foreach ( Point pt in points ) { g.FillEllipse ( Brushes.White , pt.X , pt.Y , 25 , 25 ) ; g.DrawEllipse ( pen , pt.X , pt.Y , 26 , 26 ) ; } } }",How can I treat the circle as a control after drawing it ? - Moving and selecting shapes "C_sharp : One of the handiest new features in C # 6 is nameof , which allows the programmer to effectively eliminate the use of magic strings.Per the documentation , nameof returns a string : Used to obtain the simple ( unqualified ) string name of a variable , type , or member.That works just fine with explicit typing in the following code example : However , when using implicit typing with the var keyword : the compiler throws an error : Can not use local variable 'magicString ' before it is declaredI then did some more experimenting with the C # Interactive window available in Visual Studio . Again , the first example worked fine , but the second example threw a different error this time : error CS7019 : Type of 'magicString ' can not be inferred since its initializer directly or indirectly refers to the definition.The nameof expression clearly returns a string , so why ca n't the compiler implicitly type it when being used with the initialized variable ? string magicString = nameof ( magicString ) ; var magicString = nameof ( magicString ) ;",Implicit and explicit typing with C # 6 nameof "C_sharp : My project require to keep all data encrypted , so MSMQ needs to be encrypted too . But as it is known from the article ( https : //msdn.microsoft.com/en-us/library/ms704178 ( v=vs.85 ) .aspx ) messages from private queues are stored by default in …\MSMQ\Storage\p000000x.mq file . When I configure a private queue , set its privacy level to `` Body '' , and when I send encrypted message to this queue , then I open the …\MSMQ\Storage\p000000x.mq file in text viewer ( I use Far Manager hex redactor ) , I see plain text of message . It is not encrypted . To send message I use next code : The message …\MSMQ\Storage\p000000x.mq stays plain , despite message encryption specified . See the picture below.So my question : Is there some built-in tool to keep message encrypted on drive in …\MSMQ\Storage\p000000x.mq file ? Or I need to encrypt message body before sending to queue , and then , when peek from the queue , I need to decrypt it ? Thanks a lot ! message.UseEncryption = true ; message.EncryptionAlgorithm = EncryptionAlgorithm.Rc2 ;",MSMQ . Keep message body encrypted while it is stored on drive "C_sharp : I am trying to test that a method is called , and that method exists in a base class of the class under test . When I run the below example with a simple string parameter it works but when there is a delegate parameter the test fails.I created the below sample to demonstrate the problem . If you take out the delegate parameter in SomeMethod and in the test , the test will pass . Failing Code : Passing Code : Error message for failing test : Whole error message : public abstract class BaseClass { public virtual void SomeMethod ( string someString , Func < bool > function ) { //do something } } public class DerivedClass : BaseClass { public void DoSomething ( ) { SomeMethod ( `` foo '' , ( ) = > true ) ; } } [ TestClass ] public class Tests { [ TestMethod ] public void TestMethod1 ( ) { var test = new Mock < DerivedClass > ( ) ; test.Object.DoSomething ( ) ; test.Verify ( x = > x.SomeMethod ( `` foo '' , ( ) = > true ) , Times.AtLeastOnce ) ; } } public abstract class BaseClass { public virtual void SomeMethod ( string someString ) { //do something } } public class DerivedClass : BaseClass { public void DoSomething ( ) { SomeMethod ( `` foo '' ) ; } } [ TestClass ] public class Tests { [ TestMethod ] public void TestMethod1 ( ) { var test = new Mock < DerivedClass > ( ) ; test.Object.DoSomething ( ) ; test.Verify ( x = > x.SomeMethod ( `` foo '' ) , Times.AtLeastOnce ) ; } } Expected invocation on the mock at least once , but was never performed : x = > x.SomeMethod ( `` foo '' , ( ) = > True ) No setups configured.Performed invocations : BaseClass.SomeMethod ( `` foo '' , System.Func1 [ System.Boolean ] ) ` Test method UnitTestProject1.Tests.TestMethod1 threw exception : Moq.MockException : Expected invocation on the mock at least once , but was never performed : x = > x.SomeMethod ( `` foo '' , ( ) = > True ) No setups configured.Performed invocations : BaseClass.SomeMethod ( `` foo '' , System.Func ` 1 [ System.Boolean ] ) at Moq.Mock.ThrowVerifyException ( MethodCall expected , IEnumerable ` 1 setups , IEnumerable ` 1 actualCalls , Expression expression , Times times , Int32 callCount ) at Moq.Mock.VerifyCalls ( Interceptor targetInterceptor , MethodCall expected , Expression expression , Times times ) at Moq.Mock.Verify ( Mock ` 1 mock , Expression ` 1 expression , Times times , String failMessage ) at Moq.Mock ` 1.Verify ( Expression ` 1 expression , Times times ) at Moq.Mock ` 1.Verify ( Expression ` 1 expression , Func ` 1 times ) at UnitTestProject1.Tests.TestMethod1 ( ) in UnitTest1.cs : line 16",Verifying a method call in a base class that takes a delegate parameter using Moq "C_sharp : I 've noticed in the tutorials for interception that you can target a method and intercept it . I.e.The documentation/tutorial does not cover what to do in the instance that the method you 're trying to intercept has parameters i.e if ThrowsAnError accepted a string as a parameter . At the time of binding I do not have access to the params so I was wondering whether I am going about this the wrong way ? EditWorking example Kernel.Bind < Foo > ( ) .ToSelf ( ) ; Kernel.InterceptReplace < Foo > ( foo = > foo.ThrowsAnError ( ) , invocation = > { } ) ; Kernel.Bind < Foo > ( ) .ToSelf ( ) ; Kernel.InterceptReplace < Foo > ( foo = > foo.ThrowsAnError ( **param goes here** ) , invocation = > { } ) ;",Ninject Method-level interception with params "C_sharp : When writing some unit tests for our application , I stumbled upon some weird behaviour in EF6 ( tested with 6.1 and 6.1.2 ) : apparently it is impossible to repeatedly create and delete databases ( same name/same connection string ) within the same application context.Test setup : RepeatedCreateDeleteDifferentName completes successfully , the other two fail . According to this , you can not create a database with the same name , already used once before . When trying to create the database for the second time , the test ( and application ) throws a SqlException , noting a failed login . Is this a bug in Entity Framework or is this behaviour intentional ( with what explanation ) ? I tested this on a Ms SqlServer 2012 and Express 2014 , not yet on Oracle.By the way : EF seems to have a problem with CompatibleWithModel being the very first call to the database.Update : Submitted an issue on the EF bug tracker ( link ) public class A { public int Id { get ; set ; } public string Name { get ; set ; } } class AMap : EntityTypeConfiguration < A > { public AMap ( ) { HasKey ( a = > a.Id ) ; Property ( a = > a.Name ) .IsRequired ( ) .IsMaxLength ( ) .HasColumnName ( `` Name '' ) ; Property ( a = > a.Id ) .HasColumnName ( `` ID '' ) ; } } public class SomeContext : DbContext { public SomeContext ( DbConnection connection , bool ownsConnection ) : base ( connection , ownsConnection ) { } public DbSet < A > As { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { base.OnModelCreating ( modelBuilder ) ; modelBuilder.Configurations.Add ( new AMap ( ) ) ; } } [ TestFixture ] public class BasicTest { private readonly HashSet < string > m_databases = new HashSet < string > ( ) ; # region SetUp/TearDown [ TestFixtureSetUp ] public void SetUp ( ) { System.Data.Entity.Database.SetInitializer ( new CreateDatabaseIfNotExists < SomeContext > ( ) ) ; } [ TestFixtureTearDown ] public void TearDown ( ) { foreach ( var database in m_databases ) { if ( ! string.IsNullOrWhiteSpace ( database ) ) DeleteDatabase ( database ) ; } } # endregion [ Test ] public void RepeatedCreateDeleteSameName ( ) { var dbName = Guid.NewGuid ( ) .ToString ( ) ; m_databases.Add ( dbName ) ; for ( int i = 0 ; i < 2 ; i++ ) { Assert.IsTrue ( CreateDatabase ( dbName ) , `` failed to create database '' ) ; Assert.IsTrue ( DeleteDatabase ( dbName ) , `` failed to delete database '' ) ; } Console.WriteLine ( ) ; } [ Test ] public void RepeatedCreateDeleteDifferentName ( ) { for ( int i = 0 ; i < 2 ; i++ ) { var dbName = Guid.NewGuid ( ) .ToString ( ) ; if ( m_databases.Add ( dbName ) ) { Assert.IsTrue ( CreateDatabase ( dbName ) , `` failed to create database '' ) ; Assert.IsTrue ( DeleteDatabase ( dbName ) , `` failed to delete database '' ) ; } } Console.WriteLine ( ) ; } [ Test ] public void RepeatedCreateDeleteReuseName ( ) { var testDatabases = new HashSet < string > ( ) ; for ( int i = 0 ; i < 3 ; i++ ) { var dbName = Guid.NewGuid ( ) .ToString ( ) ; if ( m_databases.Add ( dbName ) ) { testDatabases.Add ( dbName ) ; Assert.IsTrue ( CreateDatabase ( dbName ) , `` failed to create database '' ) ; Assert.IsTrue ( DeleteDatabase ( dbName ) , `` failed to delete database '' ) ; } } var repeatName = testDatabases.OrderBy ( n = > n ) .FirstOrDefault ( ) ; Assert.IsTrue ( CreateDatabase ( repeatName ) , `` failed to create database '' ) ; Assert.IsTrue ( DeleteDatabase ( repeatName ) , `` failed to delete database '' ) ; Console.WriteLine ( ) ; } # region Helpers private static bool CreateDatabase ( string databaseName ) { Console.Write ( `` creating database ' '' + databaseName + `` ' ... '' ) ; using ( var connection = CreateConnection ( CreateConnectionString ( databaseName ) ) ) { using ( var context = new SomeContext ( connection , false ) ) { var a = context.As.ToList ( ) ; // CompatibleWithModel must not be the first call var result = context.Database.CompatibleWithModel ( false ) ; Console.WriteLine ( result ? `` DONE '' : `` FAIL '' ) ; return result ; } } } private static bool DeleteDatabase ( string databaseName ) { using ( var connection = CreateConnection ( CreateConnectionString ( databaseName ) ) ) { if ( System.Data.Entity.Database.Exists ( connection ) ) { Console.Write ( `` deleting database ' '' + databaseName + `` ' ... '' ) ; var result = System.Data.Entity.Database.Delete ( connection ) ; Console.WriteLine ( result ? `` DONE '' : `` FAIL '' ) ; return result ; } return true ; } } private static DbConnection CreateConnection ( string connectionString ) { return new SqlConnection ( connectionString ) ; } private static string CreateConnectionString ( string databaseName ) { var builder = new SqlConnectionStringBuilder { DataSource = `` server '' , InitialCatalog = databaseName , IntegratedSecurity = false , MultipleActiveResultSets = false , PersistSecurityInfo = true , UserID = `` username '' , Password = `` password '' } ; return builder.ConnectionString ; } # endregion }",Repeatedly creating and deleting databases in Entity Framework "C_sharp : I 've been troubleshooting with this error for hours and I ca n't seem to understand why this happens . Consider the following code : When I compile the project , the line `` Contract.Requires ( Methods.TestMethod4 ( d , x = > x.TestData1 , x = > x.TestData2 ) ) ; '' causes the following compilation error : Malformed contract . Found Requires after assignment in method 'Contracts.Program.Method ( Contracts.Data ) '.How come `` Contract.Requires ( Methods.TestMethod2 ( `` test1 '' , `` test2 '' ) ) ; '' does n't cause an error but `` Contract.Requires ( Methods.TestMethod4 ( d , x = > x.TestData1 , x = > x.TestData2 ) ) ; '' does ? Please help ! : ( using System ; using System.Diagnostics.Contracts ; using System.Linq.Expressions ; namespace Contracts { class Data { public object TestData1 { get ; set ; } public object TestData2 { get ; set ; } } class Program { static void Main ( ) { Data d = new Data ( ) ; Method ( d ) ; } static void Method ( Data d ) { Contract.Requires ( Methods.TestMethod1 ( `` test '' ) ) ; Contract.Requires ( Methods.TestMethod2 ( `` test1 '' , `` test2 '' ) ) ; Contract.Requires ( Methods.TestMethod3 ( d , x = > x.TestData1 ) ) ; Contract.Requires ( Methods.TestMethod4 ( d , x = > x.TestData1 , x = > x.TestData2 ) ) ; } } static class Methods { [ Pure ] public static bool TestMethod1 ( string str ) { return true ; } [ Pure ] public static bool TestMethod2 ( params string [ ] strs ) { return true ; } [ Pure ] public static bool TestMethod3 < T > ( T obj , Expression < Func < T , object > > exp ) { return true ; } [ Pure ] public static bool TestMethod4 < T > ( T obj , params Expression < Func < T , object > > [ ] exps ) { return true ; } } }",Why does Code Contracts shows `` Malformed contract . Found Requires after assignment '' in method with params keywork ? "C_sharp : I am trying to work through a scenario I have n't seen before and am struggling to come up with an algorithm to implement this properly . Part of my problem is a hazy recollection of the proper terminology . I believe what I am needing is a variation of the standard `` combination '' problem , but I could well be off there.The ScenarioGiven an example string `` 100 '' ( let 's call it x ) , produce all combinations of x that swap out one of those 0 ( zero ) characters for a o ( lower-case o ) . So , for the simple example of `` 100 '' , I would expect this output : '' 100 '' '' 10o '' `` 1o0 '' '' 1oo '' This would need to support varying length strings with varying numbers of 0 characters , but assume there would never be more than 5 instances of 0.I have this very simple algorithm that works for my sample of `` 100 '' but falls apart for anything longer/more complicated : I have a nagging feeling that recursion could be my friend here , but I am struggling to figure out how to incorporate the conditional logic I need here . public IEnumerable < string > Combinations ( string input ) { char [ ] buffer = new char [ input.Length ] ; for ( int i = 0 ; i ! = buffer.Length ; ++i ) { buffer [ i ] = input [ i ] ; } //return the original input yield return new string ( buffer ) ; //look for 0 's and replace them for ( int i = 0 ; i ! = buffer.Length ; ++i ) { if ( input [ i ] == ' 0 ' ) { buffer [ i ] = ' o ' ; yield return new string ( buffer ) ; buffer [ i ] = ' 0 ' ; } } //handle the replace-all scenario yield return input.Replace ( `` 0 '' , `` o '' ) ; }",String Combinations With Character Replacement "C_sharp : I want to add some code into my masterpage . So I removed the namespace but when I want to test it it gives this error . No idea how to fix this . Error 2 The namespace 'Project ' in ' c : \Users\Test\AppData\Local\Temp\Temporary ASP.NET Files\project\fe95a550\6aff5a12\assembly\dl3\9f54421a\e011b011_23bccd01\Project.DLL ' conflicts with the type 'Project ' in ' c : \Users\Test\AppData\Local\Temp\Temporary ASP.NET Files\project\fe95a550\6aff5a12\App_Web_exfemb4u.dll ' c : \Users\Test\AppData\Local\Temp\Temporary ASP.NET Files\project\fe95a550\6aff5a12\App_Web_hrdlxq5l.4.cs 154 Masterpage.csMasterpage public partial class Project : System.Web.UI.MasterPage { protected void Page_Load ( object sender , EventArgs e ) { } } < % @ Master Language= '' C # '' AutoEventWireup= '' true '' CodeFile= '' Project.master.cs '' Inherits= '' Project '' % >","Error in Masterpage , namespace already exists" "C_sharp : We are currently going through the long process of writing some coding standards for C # .I 've written a method recently with the signatureGetUserSession ( ) returns null in the case that a session is not found for the user.in my calling code ... I say ... In a recent code review , the reviewer said `` you should never return null from a method as it puts more work on the calling method to check for nulls . `` Immediately I cried shenanigans , as if you return string.Empty you still have to perform some sort of check on the returned value.However , thinking about this further I would never return null in the case of a Collection/Array/List . I would return an empty list.The solution to this ( I think ) would be to refactor this in to 2 methods.andThis time , GetUserSessionID would throw a SessionNotFound exception ( as it should not return null ) now the code would look like ... This now means that there are no nulls , but to me this seems a bit more complicated . This is also a very simple example and I was wondering how this would impact more complicated methods.There is plenty of best-practice advise around about when to throw exceptions and how to handle them , but there seems to be less information regarding the use of null.Does anyone else have any solid guidelines ( or even better standards ) regarding the use of nulls , and what does this mean for nullable types ( should we be using them at all ? ) Thanks in advance , Chris.=====Thanks everyone ! LOTS of very interesting discussion there.I 've given the answer to egaga as I like thier suggestion of Get vs Find as a coding guideline , but all were interesting answers . string GetUserSessionID ( int UserID ) string sessionID = GetUserSessionID ( 1 ) if ( null == sessionID & & userIsAllowedToGetSession ) { session = GetNewUserSession ( 1 ) ; } if ( string.Empty == sessionID ) bool SessionExists ( int userID ) ; string GetUserSessionID ( int UserID ) ; if ( ! SessionExists ( 1 ) & & userIsAllowedToGetSession ) ) { session = GetNewUserSession ( 1 ) ; } else { session = GetUserSessionID ( 1 ) ; }",Never use Nulls ? "C_sharp : I have tasks that are put on a calendar : Now let me give this some context : Each day 'lasts ' 7.5 hours here . But I work with a variable called DayHours ( which right now is 7.5 ) . ( DayHours is also used in Locked Time which Ill describe below ) .The goal of this calendar is to schedule 7.5 hour work days for employees.What I need , is an algorithm that can correctly tell me how many hours are actually occupied in a day.This seems simple , but is actually quite recursive.First , a couple of notes . You will notice Case manager , at 14 hours , could be done in 2 days of 7.5 hours with 1 hour left over . It is stretched to 3 days because 1 . Schedule , is 5 hours long , and 2. can not start until the predecessor tasks of the day are complete.There is also the concept of Locked Time.In purple is Locked Time . This is a 10 hour block of locked time.This means , on the 12th , I can only do ( 7.5 - 7.5 ) hours of work , and Monday , only ( 7.5 - 2.5 ) aswell.I already have a function to calculate an actual day 's available hours to account for this : There is also the concept of carry hours.Here is an example : Now let us take Thursday the 18th ( The 18th has 1 . Case ) : To find the number of hours this day has for that employee , we need to first look at the tasks that start , end , or fall within that day.I do n't know how many hours I can do on the 18th because the task ending that day might have had carry hours.So I go look at Perform unit test 's start day . I cant figure that out either because NWDM finishes that day and it might have carry hours.So now I go evaluate NWDM . Ahh , this one has nothing ending that day , so I know Schedule will take 5 / 7.5 hours available.So I keep going , adding 7.5 hours each day that I pass . Then I get to NWDM 's last day.Up until then , I worked 5 + 7.5 + 7.5 + 7.5 hours on it , So I put in 27.5 hours , so I 'll put in ( 30 - 27.5 = 2.5h ) on the 22nd to finish it . So I have 5 hours left to work on Perform Unit Tests.This means that I will need 1.5h to finish it . Now Case is 1 hour long.Had case been 7.5 - 1.5 or more , we say the day is full and return DayHours.Therefore , we are done . The return value is 1.5 + 1 = 2.5.The function should look a bit like this one : To get the events that start , end , or fall within a given day , I use : The Schedule has the following relevant fields : The Schedule looks something like : Could anyone help me with developing an algorithm that can do this ? Edit : Steps : Start at target day . Then move backwards until no events are carried over from another day.From there , start counting hours , and keep track of carried over hours . Day can not last more than ActualDayLength ( ) Then , once you know that , work your way back to target and then calculate actual occupied hours . public decimal GetActualDayLength ( DateTime day , Schedule s ) { var e = Schedules.GetAllWithElement ( ) ; var t = Timeless ( day ) ; var locked = from p in e where p.EmployeID == s.EmployeID & & ( ( p.DateTo.Value.Date ) > = t & & Timeless ( p.DateFrom.Value ) < = t ) & & p.IsLocked select p ; decimal hrs = 0.0M ; foreach ( var c in locked ) { if ( c.Hours.Value < = DaysManager.GetDayHours ( ) ) hrs += c.Hours.Value ; else if ( Timeless ( c.DateTo.Value ) ! = t ) hrs += DaysManager.GetDayHours ( ) ; else { if ( c.Hours.Value % DaysManager.GetDayHours ( ) > 0 ) hrs += c.Hours.Value % DaysManager.GetDayHours ( ) ; else hrs += DaysManager.GetDayHours ( ) ; } } return DaysManager.GetDayHours ( ) - hrs ; } public decimal GetHours ( IEnumerable < Schedule > s , DateTime today ) { DateTime t = Timeless ( today ) ; decimal hrs = 0 ; foreach ( Schedule c in s ) { if ( c.Hours.Value < = DaysManager.GetDayHours ( ) ) hrs += c.Hours.Value ; else if ( Timeless ( c.DateTo.Value ) ! = t ) hrs += DaysManager.GetDayHours ( ) ; else { if ( c.Hours.Value % DaysManager.GetDayHours ( ) > 0 ) hrs += c.Hours.Value % DaysManager.GetDayHours ( ) ; else hrs += DaysManager.GetDayHours ( ) ; } } return hrs ; } public IEnumerable < Schedule > GetAllToday ( DateTime date , int employeeID , Schedule current ) { DateTime t = Timeless ( date ) ; int sid = current == null ? -1 : current.ScheduleID ; var e = Schedules.GetAllWithElement ( ) ; return from p in e where ( ( ( Timeless ( p.DateTo.Value ) > = t & & Timeless ( p.DateFrom.Value ) < = t & & p.EmployeID == employeeID ) & & ( p.IsLocked || ( Timeless ( p.DateFrom.Value ) < t & & ( sid == -1 ? true : Timeless ( p.DateFrom.Value ) < current.DateFrom.Value ) ) || bumpedList.Any ( d = > d.ScheduleID == p.ScheduleID ) ) & & p.ScheduleID ! = sid ) || ( ( Timeless ( p.DateTo.Value ) > = t & & ( Timeless ( p.DateFrom.Value ) == t || ( Timeless ( p.DateFrom.Value ) < t & & ( sid == -1 ? true : Timeless ( p.DateFrom.Value ) > current.DateFrom.Value ) ) ) & & p.EmployeID == employeeID ) & & ! p.IsLocked & & ! bumpedList.Any ( d = > d.ScheduleID == p.ScheduleID ) & & p.ScheduleID ! = sid ) ) & & p.ScheduleID ! = sid select p ; } DateFromDateToHoursEmployeeID [ global : :System.Data.Linq.Mapping.TableAttribute ( Name= '' dbo.Schedule '' ) ] public partial class Schedule : INotifyPropertyChanging , INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs ( String.Empty ) ; private int _ScheduleID ; private System.Nullable < System.DateTime > _DateFrom ; private System.Nullable < decimal > _Hours ; private System.Nullable < int > _EmployeID ; private System.Nullable < int > _RecurringID ; private System.Nullable < int > _Priority ; private System.Nullable < System.DateTime > _DateTo ; private bool _IsLocked ; private System.Nullable < int > _BumpPriority ; private EntitySet < Case > _Cases ; private EntitySet < Project > _Projects ; private EntitySet < Task > _Tasks ; private EntitySet < Task > _Tasks1 ; private EntityRef < Employee > _Employee ; private EntityRef < Recurring > _Recurring ; # region Extensibility Method Definitions partial void OnLoaded ( ) ; partial void OnValidate ( System.Data.Linq.ChangeAction action ) ; partial void OnCreated ( ) ; partial void OnScheduleIDChanging ( int value ) ; partial void OnScheduleIDChanged ( ) ; partial void OnDateFromChanging ( System.Nullable < System.DateTime > value ) ; partial void OnDateFromChanged ( ) ; partial void OnHoursChanging ( System.Nullable < decimal > value ) ; partial void OnHoursChanged ( ) ; partial void OnEmployeIDChanging ( System.Nullable < int > value ) ; partial void OnEmployeIDChanged ( ) ; partial void OnRecurringIDChanging ( System.Nullable < int > value ) ; partial void OnRecurringIDChanged ( ) ; partial void OnPriorityChanging ( System.Nullable < int > value ) ; partial void OnPriorityChanged ( ) ; partial void OnDateToChanging ( System.Nullable < System.DateTime > value ) ; partial void OnDateToChanged ( ) ; partial void OnIsLockedChanging ( bool value ) ; partial void OnIsLockedChanged ( ) ; partial void OnBumpPriorityChanging ( System.Nullable < int > value ) ; partial void OnBumpPriorityChanged ( ) ; # endregion public Schedule ( ) { this._Cases = new EntitySet < Case > ( new Action < Case > ( this.attach_Cases ) , new Action < Case > ( this.detach_Cases ) ) ; this._Projects = new EntitySet < Project > ( new Action < Project > ( this.attach_Projects ) , new Action < Project > ( this.detach_Projects ) ) ; this._Tasks = new EntitySet < Task > ( new Action < Task > ( this.attach_Tasks ) , new Action < Task > ( this.detach_Tasks ) ) ; this._Tasks1 = new EntitySet < Task > ( new Action < Task > ( this.attach_Tasks1 ) , new Action < Task > ( this.detach_Tasks1 ) ) ; this._Employee = default ( EntityRef < Employee > ) ; this._Recurring = default ( EntityRef < Recurring > ) ; OnCreated ( ) ; } }",Algorithm for hours occupied in day by tasks "C_sharp : Using System.Dynamic.Linq I have a group by statement that looks like this : Where c is just a string array of field names I need to have selected in my grouping . GroupBy in this case returns a IEnumerable ( note : not an IEnumerable < T > because we do n't know what T is ) . The regular GroupBy would return a System.Collections.Generic.IEnumerable < IGrouping < TKey , TElement > > Now my question is , how do I iterate through the groups such that I have access to the key ( Key is defined in IGrouping < TKey , TElement > but I do n't know TKey and TElement a priori ) ? I initially tried this : Which iterates , but I ca n't access row.Key ( row in this case is type object ) So I did this : Which , surprisingly , worked ... as long as the key was a string . If , however , the key happened to be numeric ( for example short ) , then I get this error : I need to be able to iterate through rowGrouped and get the Key for every row and then iterate through the collection in each group . var rowGrouped = data.GroupBy ( rGroup , string.Format ( `` new ( { 0 } ) '' , c ) ) ; foreach ( var row in rowGrouped ) foreach ( IGrouping < object , dynamic > row in rowGrouped ) Unable to cast object of type 'Grouping ` 2 [ System.Int16 , DynamicClass2 ] ' to type 'System.Linq.IGrouping ` 2 [ System.Object , System.Object ] ' .",Access key after grouping by with dynamic linq "C_sharp : I have a Logger.cs class : this logger class is used in multiple projects in a solution . Like shown below : With my above code . Now i can see only the first logging is written to the log file . Class A and Class A1 are using the same log file `` A '' , when my program executes i can see only Class A logging is present in the log but not class A1 logging messages.Same for Class B and Class B1 , only class B messages are visible.How can i use the same log file across multiple project in a solution ? public Logger ( string logtype=null ) { _logtype = logtype ; LogEventLevel level = LogEventLevel.Warning ; if ( File.Exists ( configPath ) ) { XDocument xdoc = XDocument.Load ( configPath ) ; string val = xdoc.Descendants ( `` logEnabled '' ) .First ( ) .Value ; // if ( clientConfig.LogEnabled == true ) if ( val == `` true '' ) { level = LogEventLevel.Debug ; } else if ( val == `` false '' ) { level = LogEventLevel.Warning ; } } else { level = LogEventLevel.Warning ; } _logger = new LoggerConfiguration ( ) .MinimumLevel.Debug ( ) .WriteTo.File ( _filepath , level ) .CreateLogger ( ) ; } Class A { Logger _logger = new Logger ( `` A '' ) ; } Class A1 { Logger _logger = new Logger ( `` A '' ) ; } Class B { Logger _logger = new Logger ( `` B '' ) ; } Class B1 { Logger _logger = new Logger ( `` A '' ) ; }",Same log file in multiple projects using serilog "C_sharp : I 'm have the strangest behavior with linq to entity / Json / MVC.net 4I have this bit of code , and for some odd reason , every other list 's property order is reversed.output looks like so : I 've managed to work around it by putting a toList ( ) between the Where , and Select , but I 'd still like to know why this behavior is happening.More info : EF 4.4 ( tt generated Context ) , SQL Server 2008r2 express .NET 4.0 , MVC 3.0 , Vanilla System.Web.Mvc.JsonResult , table consists of a int primary key , floats for values excluding last one which is a int var output = db.FooBar.Where ( a = > a.lookupFoo == bar ) .Select ( a = > new List < double > { //value 's are the same per row //for demonstration sake . a.fooBarA , //Always 12.34 a.fooBarB , //Always 12.34 a.fooBarC , //Always 0 a.fooBarD //Always 0 //lazy casting to double from int } ) ; return Json ( new { output } ) ; { `` output '' : [ [ 12.34 , 12.34 , 0 , 0 ] , [ 0 , 0 , 12.34 , 12.34 ] , [ 12.34 , 12.34 , 0 , 0 ] , [ 0 , 0 , 12.34 , 12.34 ] ] } ;",Why is Linq to Entity Select Method flip flopping projected lists properties ? "C_sharp : I 'm using EntityFramework as a DataLayer and DTO to transfer data between layer . I develop Windows Forms in N-Tier architecture and when I try to mapping from Entity to DTO in BLL : I 've got this error : http : //s810.photobucket.com/user/sky3913/media/AutoMapperError.png.htmlThe error said that I missing type map configuration or unsupported mapping . I have registered mapping using profile in this way at UI Layer : and AutoMapper configuration is in BLL : I 've got the same error too when mapping from DTO to Entity . How to solve this ? public IEnumerable < CategoryDTO > GetCategoriesPaged ( int skip , int take , string name ) { var categories = unitOfWork.CategoryRepository.GetCategoriesPaged ( skip , take , name ) ; var categoriesDTO = Mapper.Map < IEnumerable < Category > , List < CategoryDTO > > ( categories ) ; return categoriesDTO ; } [ STAThread ] static void Main ( ) { AutoMapperBusinessConfiguration.Configure ( ) ; AutoMapperWindowsConfiguration.Configure ( ) ; ... Application.Run ( new frmMain ( ) ) ; } public class AutoMapperBusinessConfiguration { public static void Configure ( ) { Mapper.Initialize ( cfg = > { cfg.AddProfile < EntityToDTOProfile > ( ) ; cfg.AddProfile < DTOToEntityProfile > ( ) ; } ) ; } } public class EntityToDTOProfile : Profile { public override string ProfileName { get { return `` EntityToDTOMappings '' ; } } protected override void Configure ( ) { Mapper.CreateMap < Category , CategoryDTO > ( ) ; } } public class DTOToEntityProfile : Profile { public override string ProfileName { get { return `` DTOToEntityMappings '' ; } } protected override void Configure ( ) { Mapper.CreateMap < CategoryDTO , Category > ( ) ; } } category = Mapper.Map < Category > ( categoryDTO ) ;",Error when mapping from Entity to DTO or DTO to Entity using AutoMapper "C_sharp : Thanks to suggestions from a previous question , I 'm busy trying out IronPython , IronRuby and Boo to create a DSL for my C # app . Step one is IronPython , due to the larger user and knowledge base . If I can get something to work well here , I can just stop.Here is my problem : I want my IronPython script to have access to the functions in a class called Lib . Right now I can add the assembly to the IronPython runtime and import the class by executing the statement in the scope I created : If I want to run Lib : :PrintHello , which is just a hello world style statement , my Python script contains : or ( if it 's not static ) : How can I change my environment so that I can just have basic statments in the Python script like this : I want these scripts to be simple for a non-programmer to write . I do n't want them to have to know what a class is or how it works . IronPython is really just there so that some basic operations like for , do , if , and a basic function definition do n't require my writing a compiler for my DSL . // load 'ScriptLib ' assemblyAssembly libraryAssembly = Assembly.LoadFile ( libraryPath ) ; _runtime.LoadAssembly ( libraryAssembly ) ; // import 'Lib ' class from 'ScriptLib'ScriptSource imports = _engine.CreateScriptSourceFromString ( `` from ScriptLib import Lib '' , SourceCodeKind.Statements ) ; imports.Execute ( _scope ) ; // run .py script : ScriptSource script = _engine.CreateScriptSourceFromFile ( scriptPath ) ; script.Execute ( _scope ) ; Lib.PrintHello ( ) library = new Lib ( ) library.PrintHello ( ) PrintHelloTurnOnPowerVerifyFrequencyTurnOffPoweretc ...",Simplfying DSL written for a C # app with IronPython "C_sharp : I have a method defined like this : Looking at the MethodInfo for this method , I findis false . I expected it to be true , because the second parameter has a type of T. ( On the other hand , methodInfo.GetParameters ( ) [ 1 ] .ParameterType.ContainsGenericParameters is true . ) Why is IsGenericParameter false in this case ? And what is the correct way to verify that the second parameter has a type of T. For instance , I 'm trying to find the correct method by filtering the results of Type.GetMethods ( ) . public bool TryGetProperty < T > ( string name , out T value ) methodInfo.GetParameters ( ) [ 1 ] .ParameterType.IsGenericParameter",Why is IsGenericParameter false for a generic parameter out T "C_sharp : I built a little program that calculates the average of 15 numbers or less . There are 15 text-boxes , each one 's default value is ' 0 ' . The program knows to get the sum of all typed numbers and divide it by numbers of text boxes that do n't return ' 0 ' . But if the user deletes in mistake one of the ' 0'os in one of the text boxs.. run-time error.Originally I solved this problam by writing this `` if statement '' 15 times ( one for each text-box ) : this code checks if there is n't a thing in text box ( for example , named t1 ) , if true , the program is giving the double 'tr1 ' ( do n't confuse with 't1 ' ) , the value of ' 0 ' , if false , the code gives the double 'tr1 ' the text of 't1'.i had to write this 'if ' 15 times . i wanted to know if i can write the same code with arrays and a for loop , and how ? here is the whole code ( sorry for var names are not similar to var 's use . ) : if ( t1.Text == `` '' ) { tr1 = 0 ; } else { tr1 = Double.Parse ( t1.Text ) ; } private void goyouidiot_Click ( object sender , EventArgs e ) { double tr1 ; double tr2 ; double tr3 ; double tr4 ; double tr5 ; double tr6 ; double tr7 ; double tr8 ; double tr9 ; double tr10 ; double tr11 ; double tr12 ; double tr13 ; double tr14 ; double tr15 ; if ( t1.Text == `` '' ) { tr1 = 0 ; } else { tr1 = Double.Parse ( t1.Text ) ; } if ( t2.Text == `` '' ) { tr2 = 0 ; } else { tr2 = Double.Parse ( t2.Text ) ; } if ( t3.Text == `` '' ) { tr3 = 0 ; } else { tr3 = Double.Parse ( t3.Text ) ; } if ( t4.Text == `` '' ) { tr4 = 0 ; } else { tr4 = Double.Parse ( t4.Text ) ; } if ( t5.Text == `` '' ) { tr5 = 0 ; } else { tr5 = Double.Parse ( t5.Text ) ; } if ( t6.Text == `` '' ) { tr6 = 0 ; } else { tr6 = Double.Parse ( t6.Text ) ; } if ( t7.Text == `` '' ) { tr7 = 0 ; } else { tr7 = Double.Parse ( t7.Text ) ; } if ( t8.Text == `` '' ) { tr8 = 0 ; } else { tr8 = Double.Parse ( t8.Text ) ; } if ( t9.Text == `` '' ) { tr9 = 0 ; } else { tr9 = Double.Parse ( t9.Text ) ; } if ( t10.Text == `` '' ) { tr10 = 0 ; } else { tr10 = Double.Parse ( t10.Text ) ; } if ( t11.Text == `` '' ) { tr11 = 0 ; } else { tr11 = Double.Parse ( t11.Text ) ; } if ( t12.Text == `` '' ) { tr12 = 0 ; } else { tr12 = Double.Parse ( t12.Text ) ; } if ( t13.Text == `` '' ) { tr13 = 0 ; } else { tr13 = Double.Parse ( t13.Text ) ; } if ( t14.Text == `` '' ) { tr14 = 0 ; } else { tr14 = Double.Parse ( t14.Text ) ; } if ( t15.Text == `` '' ) { tr15 = 0 ; } else { tr15 = Double.Parse ( t15.Text ) ; } double [ ] sch = { tr1 , tr2 , tr3 , tr4 , tr5 , tr6 , tr7 , tr8 , tr9 , tr10 , tr11 , tr12 , tr13 , tr14 , tr15 } ; double total = 0 ; double sorf = 0 ; for ( int i = 0 ; i ! = 14 ; i++ ) { sorf = sorf + sch [ i ] ; if ( sch [ i ] > 0 ) { total++ ; } } double totalic = sorf / total ; string glass = totalic.ToString ( ) ; result.Text = ( `` your score : `` + glass ) ; }",How to turn null to 0 "C_sharp : I have DownloadController.cs to Controllers/DownloadController with the following method : Also , in my Startup.cs I have configured the following endpoints : So how in a Blazor view can I navigate to the controller action ? I was looking for something similar to this : public async Task < ActionResult > DownloadFile ( string key ) { return File ( ... ) ; } app.UseEndpoints ( endpoints = > { endpoints.MapControllerRoute ( name : `` default '' . pattern : `` { controller } / { action } '' ) ; endpoints.MapControllers ( ) ; endpoints.MapBlazorHub ( ) ; endpoints.MapFallbackToPage ( `` /_Host '' ) ; } ) ; @ Html.ActionLink ( ... ) ;",How to navigate to an ASP.NET Core MVC controller in Blazor app ? "C_sharp : Imagine I am using a class to bring back items from a database , sayNow , what would happen to the performance of using this if there were just 2 methods ( as above ) or 100 methods , maybe some of them very large.Would instancing hundreds of these objects be worse if all the methods were on each object ? This is for c # /java type languages , but it would be good to know for all languages.Or is it good practice to have a seperate class , to perform all the actions on these objects , and leave the object as a pure data class ? class BankRecord { public int id ; public int balance ; public void GetOverdraft ( ) { ... } public void MakeBankrupt ( ) { ... } }",Does having lots of methods on a class increase the overhead of that class 's object ? "C_sharp : I am still confused about passing by ref.If I have a Cache object which I want to be accessed/available to a number of objects , and I inject it using constructor injection . I want it to affect the single cache object I have created . eg.Should I be using ref when I pass the Cache into the ObjectLoader constructor ? public class Cache { public void Remove ( string fileToRemove ) { ... } } public class ObjectLoader { private Cache _Cache ; public ObjectLoader ( Cache cache ) { } public RemoveFromCacheFIleThatHasBeenDeletedOrSimilarOperation ( string filename ) { _Cache.Remove ( fileName ) ; } }",Passing by ref ? "C_sharp : I 'm trying to get all Exception messages in English , no matter what language is the machine my program running on.I 've manage to get almost all exception messages in English using answers from the following posts : Exception messages in English ? and some other solution I 've found ( like using reflection to change the default CultureInfo ) . I have specific problem with SocketException , No matter what I 'm doing I 'm getting it in the default machine 's language.I 've created a test program to show the problem : This test program will print Exceptions in default language : This result on my machine the following text : On Japanese machine it write all exceptions in Japanese ( which I do n't understand ) : ( The Japanese '\ ' looks different in Japanese machine , but when copied to my machine it shown as '\ ' ) So from combining of the answers I 've found , I 've implemented the following solution , so now it looks like this : Now on Japanese machine it write the file exceptions in English but the Net.socket exceptions are still in Japanese : I 've also tested some other exceptions , some exceptions are now shown in English , but not all of them , the socket exceptions are persistent . As you can see , the file exception had been translated to English , but the socket exception is still in Japanese.I 've tested it in almost any .NET framework ( from 2.1 to 4.5 ) still the same.Is there a complete solution for all the exceptions ? Did I missed anything ? Should I do anything else ? Maybe there 's other way to run program on foreign machine , and set some environment variable , to get English output ? using System ; using System.Text ; using System.Threading ; using System.IO ; using System.Net.Sockets ; using System.Reflection ; using System.Globalization ; namespace TestApp { class Program { static void Main ( string [ ] args ) { try { //I 'm not listening on the following port : TcpClient s = new TcpClient ( `` localhost '' , 2121 ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Socket exception : `` + ex.Message ) ; } try { //the following file does n't exists : File.ReadAllText ( `` filenotexist.txt '' ) ; } catch ( Exception ex ) { Console.WriteLine ( `` File exception : `` + ex.Message ) ; } } } } H : \Shared > Test-def.exeSocket exception : No connection could be made because the target machine actively refused it 127.0.0.1:2121File exception : Could not find file ' H : \Shared\filenotexist.txt ' . Z : \ > Test-def.exeSocket exception : 対象のコンピューターによって拒否されたため、接続できませんでした。 127.0.0.1:2121File exception : ファイル ' Z : \filenotexist.txt ' が見つかりませんでした。 namespace TestApp { class Program { //will change CultureInfo to English , this should change all threads CultureInfo to English . public static void SetEnglishCulture ( ) { CultureInfo ci = new CultureInfo ( `` en-US '' ) ; //change CultureInfo for current thread : Thread.CurrentThread.CurrentUICulture = ci ; Thread.CurrentThread.CurrentCulture = ci ; //change CultureInfo for new threads : Type t = typeof ( CultureInfo ) ; try { t.InvokeMember ( `` s_userDefaultCulture '' , BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static , null , ci , new object [ ] { ci } ) ; t.InvokeMember ( `` s_userDefaultUICulture '' , BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static , null , ci , new object [ ] { ci } ) ; } catch { } try { t.InvokeMember ( `` m_userDefaultCulture '' , BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static , null , ci , new object [ ] { ci } ) ; t.InvokeMember ( `` m_userDefaultUICulture '' , BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Static , null , ci , new object [ ] { ci } ) ; } catch { } } static void Main ( string [ ] args ) { //first thing : set CultureInfo to English : SetEnglishCulture ( ) ; try { //I 'm not listening on the following port : TcpClient s = new TcpClient ( `` localhost '' , 2121 ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Socket exception : `` + ex.Message ) ; } try { //the following file does n't exists : File.ReadAllText ( `` filenotexist.txt '' ) ; } catch ( Exception ex ) { Console.WriteLine ( `` File exception : `` + ex.Message ) ; } } } } Z : \ > Test-en.exeSocket exception : 対象のコンピューターによって拒否されたため、接続できませんでした。 127.0.0.1:2121File exception : Could not find file ' Z : \filenotexist.txt ' .",How to get Win32Exception in English ? "C_sharp : The following nunit test compares performance between running a single thread versus running 2 threads on a dual core machine . Specifically , this is a VMWare dual core virtual Windows 7 machine running on a quad core Linux SLED host with is a Dell Inspiron 503.Each thread simply loops and increments 2 counters , addCounter and readCounter . This test was original testing a Queue implementation which was discovered to perform worse on a multi-core machine . So in narrowing down the problem to the small reproducible code , you have here no queue only incrementing variables and to shock and dismay , it 's far slower with 2 threads then one.When running the first test , the Task Manager shows 1 of the cores 100 % busy with the other core almost idle . Here 's the test output for the single thread test : You see over 360 Million increments ! Next the dual thread test shows 100 % busy on both cores for the whole 5 seconds duration of the test . However it 's output shows only : That 's only 223 Million read increments . What is god 's creation are those 2 CPU 's doing for those 5 seconds to get less work done ? Any possible clue ? And can you run the tests on your machine to see if you get different results ? One idea is that perhaps the VMWare dual core performance is n't what you would hope.Edit : I tested the above on a quad core laptop w/o vmware and got similar degraded performance . So I wrote another test similar to the above but which has each thread method in a separate class . My purpose in doing that was to test 4 cores.Well that test showed excelled results which improved almost linearly with 1 , 2 , 3 , or 4 cores . With some experimentation now on both machines it appears that the proper performance only happens if main thread methods are on different instances instead of the same instance.In other words , if multiple threads main entry method on on the same instance of a particular class , then the performance on a multi-core will be worse for each thread you add , instead of better as you might assume.It almost appears that the CLR is `` synchronizing '' so only one thread at a time can run on that method . However , my testing says that is n't the case . So it 's still unclear what 's happening.But my own problem seems to be solved simply by making separate instances of methods to run threads as their starting point.Sincerely , WayneEDIT : Here 's an updated unit test that tests 1 , 2 , 3 , & 4 threads with them all on the same instance of a class . Using arrays with variables uses in the thread loop at least 10 elements apart . And performance still degrades significantly for each thread added . readCounter 360687000readCounter2 0total readCounter 360687000addCounter 360687000addCounter2 0 readCounter 88687000readCounter2 134606500totoal readCounter 223293500addCounter 88687000addCounter2 67303250addFailure0 using System ; using System.Threading ; using NUnit.Framework ; namespace TickZoom.Utilities.TickZoom.Utilities { [ TestFixture ] public class ActiveMultiQueueTest { private volatile bool stopThread = false ; private Exception threadException ; private long addCounter ; private long readCounter ; private long addCounter2 ; private long readCounter2 ; private long addFailureCounter ; [ SetUp ] public void Setup ( ) { stopThread = false ; addCounter = 0 ; readCounter = 0 ; addCounter2 = 0 ; readCounter2 = 0 ; } [ Test ] public void TestSingleCoreSpeed ( ) { var speedThread = new Thread ( SpeedTestLoop ) ; speedThread.Name = `` 1st Core Speed Test '' ; speedThread.Start ( ) ; Thread.Sleep ( 5000 ) ; stopThread = true ; speedThread.Join ( ) ; if ( threadException ! = null ) { throw new Exception ( `` Thread failed : `` , threadException ) ; } Console.Out.WriteLine ( `` readCounter `` + readCounter ) ; Console.Out.WriteLine ( `` readCounter2 `` + readCounter2 ) ; Console.Out.WriteLine ( `` total readCounter `` + ( readCounter + readCounter2 ) ) ; Console.Out.WriteLine ( `` addCounter `` + addCounter ) ; Console.Out.WriteLine ( `` addCounter2 `` + addCounter2 ) ; } [ Test ] public void TestDualCoreSpeed ( ) { var speedThread1 = new Thread ( SpeedTestLoop ) ; speedThread1.Name = `` Speed Test 1 '' ; var speedThread2 = new Thread ( SpeedTestLoop2 ) ; speedThread2.Name = `` Speed Test 2 '' ; speedThread1.Start ( ) ; speedThread2.Start ( ) ; Thread.Sleep ( 5000 ) ; stopThread = true ; speedThread1.Join ( ) ; speedThread2.Join ( ) ; if ( threadException ! = null ) { throw new Exception ( `` Thread failed : `` , threadException ) ; } Console.Out.WriteLine ( `` readCounter `` + readCounter ) ; Console.Out.WriteLine ( `` readCounter2 `` + readCounter2 ) ; Console.Out.WriteLine ( `` totoal readCounter `` + ( readCounter + readCounter2 ) ) ; Console.Out.WriteLine ( `` addCounter `` + addCounter ) ; Console.Out.WriteLine ( `` addCounter2 `` + addCounter2 ) ; Console.Out.WriteLine ( `` addFailure '' + addFailureCounter ) ; } private void SpeedTestLoop ( ) { try { while ( ! stopThread ) { for ( var i = 0 ; i < 500 ; i++ ) { ++addCounter ; } for ( var i = 0 ; i < 500 ; i++ ) { readCounter++ ; } } } catch ( Exception ex ) { threadException = ex ; } } private void SpeedTestLoop2 ( ) { try { while ( ! stopThread ) { for ( var i = 0 ; i < 500 ; i++ ) { ++addCounter2 ; i++ ; } for ( var i = 0 ; i < 500 ; i++ ) { readCounter2++ ; } } } catch ( Exception ex ) { threadException = ex ; } } } } using System ; using System.Threading ; using NUnit.Framework ; namespace TickZoom.Utilities.TickZoom.Utilities { [ TestFixture ] public class MultiCoreSameClassTest { private ThreadTester threadTester ; public class ThreadTester { private Thread [ ] speedThread = new Thread [ 400 ] ; private long [ ] addCounter = new long [ 400 ] ; private long [ ] readCounter = new long [ 400 ] ; private bool [ ] stopThread = new bool [ 400 ] ; internal Exception threadException ; private int count ; public ThreadTester ( int count ) { for ( var i=0 ; i < speedThread.Length ; i+=10 ) { speedThread [ i ] = new Thread ( SpeedTestLoop ) ; } this.count = count ; } public void Run ( ) { for ( var i = 0 ; i < count*10 ; i+=10 ) { speedThread [ i ] .Start ( i ) ; } } public void Stop ( ) { for ( var i = 0 ; i < stopThread.Length ; i+=10 ) { stopThread [ i ] = true ; } for ( var i = 0 ; i < count * 10 ; i += 10 ) { speedThread [ i ] .Join ( ) ; } if ( threadException ! = null ) { throw new Exception ( `` Thread failed : `` , threadException ) ; } } public void Output ( ) { var readSum = 0L ; var addSum = 0L ; for ( var i = 0 ; i < count ; i++ ) { readSum += readCounter [ i ] ; addSum += addCounter [ i ] ; } Console.Out.WriteLine ( `` Thread readCounter `` + readSum + `` , addCounter `` + addSum ) ; } private void SpeedTestLoop ( object indexarg ) { var index = ( int ) indexarg ; try { while ( ! stopThread [ index*10 ] ) { for ( var i = 0 ; i < 500 ; i++ ) { ++addCounter [ index*10 ] ; } for ( var i = 0 ; i < 500 ; i++ ) { ++readCounter [ index*10 ] ; } } } catch ( Exception ex ) { threadException = ex ; } } } [ SetUp ] public void Setup ( ) { } [ Test ] public void SingleCoreTest ( ) { TestCores ( 1 ) ; } [ Test ] public void DualCoreTest ( ) { TestCores ( 2 ) ; } [ Test ] public void TriCoreTest ( ) { TestCores ( 3 ) ; } [ Test ] public void QuadCoreTest ( ) { TestCores ( 4 ) ; } public void TestCores ( int numCores ) { threadTester = new ThreadTester ( numCores ) ; threadTester.Run ( ) ; Thread.Sleep ( 5000 ) ; threadTester.Stop ( ) ; threadTester.Output ( ) ; } } }",Dual-core performance worse than single core ? "C_sharp : I have not used generics much and so can not figure out if it is possible to turn the following three methods into one using generics to reduce duplication . Actually my code currently has six methods but if you can solve it for the three then the rest should just work anyway with the same solution.I am building a simple expression parser that then needs to evaluate the simple binary operations such as addition/subtraction etc . I use the above methods to get the actual maths performed using the relevant types . But there has got to be a better answer ! private object EvaluateUInt64 ( UInt64 x , UInt64 y ) { switch ( Operation ) { case BinaryOp.Add : return x + y ; case BinaryOp.Subtract : return x - y ; case BinaryOp.Multiply : return x * y ; case BinaryOp.Divide : return x / y ; case BinaryOp.Remainder : return x % y ; default : throw new ApplicationException ( `` error '' ) ; } } private object EvaluateFloat ( float x , float y ) { switch ( Operation ) { case BinaryOp.Add : return x + y ; case BinaryOp.Subtract : return x - y ; case BinaryOp.Multiply : return x * y ; case BinaryOp.Divide : return x / y ; case BinaryOp.Remainder : return x % y ; default : throw new ApplicationException ( `` error '' ) ; } } private object EvaluateDouble ( double x , double y ) { switch ( Operation ) { case BinaryOp.Add : return x + y ; case BinaryOp.Subtract : return x - y ; case BinaryOp.Multiply : return x * y ; case BinaryOp.Divide : return x / y ; case BinaryOp.Remainder : return x % y ; default : throw new ApplicationException ( `` error '' ) ; } }",How to turn these 3 methods into one using C # generics ? "C_sharp : in xaml : After this code . Do n't show any text in TextBlock . I 'm changing Text binding like thisTextBlock Text shown like this System.Linq.Lookup^2+Grouping [ System.String , Model.Template ] I 'm debugging and checking Key property . this is not null . Why Key do n't bind in TextBlock ? How to show group title in Textblock ? list.ItemsSource=db.Templates.GroupBy ( t= > t.CategoryName ) ; < DataTemplate > < TextBlock Text= '' { Binding Key } '' / > < /DataTemplate > < DataTemplate > < TextBlock Text= '' { Binding } '' / > < /DataTemplate >",System.Linq.GroupBy Key not binding in silverlight "C_sharp : My question is pretty simple , but I did n't find a way to implement my code the way I want it to be . So I started wondering if the code I want to implement is not good . And if it is , what 's the best way to do it.Here it goes : This code wo n't compile , giving errors of this kind : The best overloaded method match for 'InputManager.Add ( ushort , Keys ) ' has some invalid arguments Argument ' 1 ' : can not convert from 'RegisteredInput ' to 'ushort'If I use a cast like in manager.Add ( ( ushort ) RegisteredInput.Up , Keys.Q ) ; it will work . But because the cast must be explicit , I was wondering if it is not recomended code in C # like it is in C++ and if there is a better way of doing it ( like using const ushort for every value , which I kinda do n't like much ) .The best answer I got so far was from this thread , but it sounds so much like a hack , I got worried.Thanks ! class InputManager { SortedDictionary < ushort , Keys > inputList = new SortedDictionary < ushort , Keys > ( ) ; public void Add ( ushort id , Keys key ) { ... } public bool IsPressed ( ushort id ) { ... } } class Main { private enum RegisteredInput : ushort { Up , Down , Confirm } public Main ( ) { InputManager manager = new InputManager ( ) ; manager.Add ( RegisteredInput.Up , Keys.Q ) ; manager.Add ( RegisteredInput.Down , Keys.A ) ; manager.Add ( RegisteredInput.Confirm , Keys.Enter ) ; } void update ( ) { if ( manager.IsPressed ( RegisteredInput.Up ) ) action ( ) ; } }",Using enum as integer constant in C # C_sharp : I want to create a single connectionString in my Web.config and then re-use it in the `` provider connection string '' attribute of all Modules declarations.example : Declare a connection string this way : and then share this connection between modules : Is this possible ? < add name= '' MyConnectionString '' connectionString= '' Data Source= . ; InitialCatalog=MyDB ; User ID=username ; Password=pwd ; '' / > < add name= '' Module1Context '' connectionString= '' metadata=res//*/Module1.csdl| ... | ... ; provider=System.Data.SqlClient ; provider connection string=MyConnectionString '' providerName= '' System.Data.EntityClient '' / >,Shared Connection Strings in Entity Framework "C_sharp : I have the following higher-order function : And trying to call it like that : Compiler gives me `` type arguments can not be inferred from the usage '' error.But the following works : I wonder what the difference is ? string.IsNullOrWhiteSpace is already a non-overloaded function with the exactly same signature.As mentioned in comments , the following also works and still does n't explain why type inference fails in this case : public static Func < T , bool > Not < T > ( Func < T , bool > otherFunc ) { return arg = > ! otherFunc ( arg ) ; } var isValidStr = LinqUtils.Not ( string.IsNullOrWhiteSpace ) ; var isValidStr = LinqUtils.Not ( ( string s ) = > string.IsNullOrWhiteSpace ( s ) ) ; var isValidStr = LinqUtils.Not < string > ( string.IsNullOrWhiteSpace ) ;",type arguments ca n't be inferred from the usage for higher-order function "C_sharp : I 'd really like a a generic numeric type as the second generic type parameter of the Func < TInput , THere , TResult > given below so I can provide either an integer or a double or a decimal as and when I like.Short of : making my own type ; or using object and boxing a value type and unboxing it ; orUsing the dynamic keyword , Is there a proper way to do that in C # ? I guess Java has a Number class that probably fits in my requirements but I was wondering if C # has anything similar.I guess there is n't any such thing in C # but I thought I 'll ask to be sure . var _resultSelectors = new Dictionary < string , Func < DateTime , /*here*/ double , DateTime > > ( ) ; // so I can do_resultSelector.Add ( `` foo '' , ( DateTime dt , int x ) = > ... ) ; _resultSelector.Add ( `` bar '' , ( DateTime dt , double d ) = > ... ) ; _resultSelector.Add ( `` gar '' , ( DateTime dt , float f ) = > ... ) ; _resultSelector.Add ( `` har '' , ( DateTime dt , decimal d ) = > ... ) ;",Is there a generic numeric type in C # ? "C_sharp : I have this generic class , which uses Entity Framework 6.x.And these interfaces : And entities that looks like this : My issue is that it does n't compile . I get this error : Can not apply operator '== ' to operands of type 'TId ' and 'TId ' I tried to change it to x = > Equals ( x.Id , id ) , but then EF can not translate it . Any way around it ? I know that I can use Find ( ) instead of FirstOrDefault . But I need this for more than the methods mentioned above . Is there any way I can let EF compare TId with TId ? TId is currently only guid and int . I 've already seen the questions below , but they do n't handle the issue regarding translation to SQL.Ca n't operator == be applied to generic types in C # ? How to solve Operator ' ! = ' can not be applied to operands of type 'T ' and 'T ' public class GenericRepository < TEntity , TId > where TEntity , class , IIdentifyable < TId > { public virtual TEntity GetById ( TId id ) { using ( var context = new DbContext ( ) ) { var dbSet = context.Set < TEntity > ( ) ; var currentItem = dbSet.FirstOrDefault ( x = > x.Id == id ) ; return currentItem ; } } public virtual bool Exists ( TId id ) { using ( var context = new DbContext ( ) ) { var dbSet = context.Set < TEntity > ( ) ; var exists = dbSet.Any ( x = > x.Id == id ) ; return exists ; } } } public interface IIdentifyable : IIdentifyable < int > { } public interface IIdentifyable < out TId > { TId Id { get ; } } public class CustomerEntity : IIdentifyable < int > { public string Name { get ; set ; } public int Id { get ; set ; } } public class ProductEntity : IIdentifyable < Guid > { public string Name { get ; set ; } public Guid Id { get ; set ; } }",EF - Can not apply operator '== ' to operands of type 'TId ' and 'TId ' "C_sharp : i 'm getting a list of items with following LINQ expression , i 'm getting the list as , ordered by Codenow , my expected result is as below , i know that i can get the expected result either by modifying the sql table containing these values or by adding an extra numeric column to the table specifying the sequence order.is it possible to get the results with the help of LINQ without modifying the table ? var list = ( from p in listData orderby p.Code ascending select new KeyValuePair < int , string > ( p.Code , p.DESC ) ) .Distinct < KeyValuePair < int , string > > ( ) .ToList < KeyValuePair < int , string > > ( ) ; 2 , MEDICAL5 , RETAIL6 , OTHER7 , GOVT 2 , MEDICAL5 , RETAIL7 , GOVT6 , OTHER",Change the order of List items conditionally with LINQ "C_sharp : I have a class library that i have built that consists of a number of classes that inherit from a single base class.there is a virtual method defined on the base class called Process which essentially will process the content of the class structure into the application.There is messaging going between different components ( servers ) of the application , and they are passing and receiving messages of the base class type , and then calling Process ( ) Where i have gotten stuck is that i need to be able to override the Process ( ) method in the other parts of the application , i.e . in different assemblies without deriving another type from it.From what i have read this seems not possible , so looking at if using interfaces would solve the issue ? EDIT : What i failed to mention in the question is the each derived class of the base class needs to have a different implementation of Process ( ) depending on the functionality required by that class.For example : the code in the override process methods need to be in different assemblies , due to the fact that this code will be referencing other external sources based on the class it belongs to that i do not want to propagate across the entire application.Just for clarification i do have access and can change the library class if required.I have been doing some further reading and it would appear using delegates could solve this issue.. thoughts ? class First : BaseClass { override void Process ( ) { //do something } } class Second : BaseClass { override void Process ( ) { //do something else } }",C # Define override method in different assembly "C_sharp : Edit : look at the bottom for a halfway reason why this is happeningI 've a very strange IndexOutOfRangeException ( as said in title ) . It happens when I use foreach to iterate over the controls of a control ( recursive FindControl ) .I then thought to add an additional check that makes sure root.Controls.Count > 0 . However I keep getting the exception , while the debugger clearly says Count == 0.The root in question is a FormView . If anyone has any ideas why a simple property check throws an IndexOutOfRangeException , please enlighten me ! Exception stackTrace ( yes it is complete ) : Code : EDIT : I 've tried to use the native FindControl function , this throws the same identical error.Specific question : How can foreach throw an IndexOutOfRangeException on a native collection.EDIT2 : Somehow this seems related to using a ObjectDataSource , I was n't filling in the inputparameters correctly , but I was n't getting any errors there . Perhaps this corrupted the FormView ( that was using that datasource ) somehow . I 'm still interested to know how this can happen without errors thrown before accessing the childcontrols . at System.ComponentModel.BaseNumberConverter.ConvertFrom ( ITypeDescriptorContext context , CultureInfo culture , Object value ) public static Control FindControlRecursive ( this Control root , string id ) { if ( root.ID == id ) { return root ; } if ( root.Controls.Count > 0 ) { foreach ( Control c in root.Controls ) { Control t = c.FindControlRecursive ( id ) ; if ( t ! = null ) { return t ; } } } return null ; }",IndexOutOfRangeException with foreach "C_sharp : I hava small windows app where user enter code and on button click event code is compiled at runtime . When i click button 1st time it works fine but if click same button more than once it gives error `` The process can not access the Exmaple.pdb file because it is being used by another process. '' . Below is the example sample codehow do i solve this issue so that if i click same button more than once.. it should work properly.thanks , using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; using Microsoft.CSharp ; using System.CodeDom.Compiler ; using System.Reflection ; using System.IO ; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } private void button1_Click ( object sender , EventArgs e ) { var csc = new CSharpCodeProvider ( new Dictionary < string , string > ( ) { { `` CompilerVersion '' , `` v3.5 '' } } ) ; var parameters = new CompilerParameters ( new [ ] { `` mscorlib.dll '' , `` System.Core.dll '' } , `` Example '' + `` .exe '' , true ) ; //iloop.ToString ( ) + parameters.GenerateExecutable = true ; CompilerResults results = csc.CompileAssemblyFromSource ( parameters , @ '' using System.Linq ; class Program { public static void Main ( string [ ] args ) { } public static string Main1 ( int abc ) { `` + textBox1.Text.ToString ( ) + @ '' } } '' ) ; results.Errors.Cast < CompilerError > ( ) .ToList ( ) .ForEach ( error = > Error = error.ErrorText.ToString ( ) ) ; var scriptClass = results.CompiledAssembly.GetType ( `` Program '' ) ; var scriptMethod1 = scriptClass.GetMethod ( `` Main1 '' , BindingFlags.Static | BindingFlags.Public ) ; StringBuilder st = new StringBuilder ( scriptMethod1.Invoke ( null , new object [ ] { 10 } ) .ToString ( ) ) ; result = Convert.ToBoolean ( st.ToString ( ) ) ; } } }",runtime code compilation gives error - process can not access the file "C_sharp : what is the best practice ? call a function then return if you test for something , or test for something then call ? i prefer the test inside of function because it makes an easier viewing of what functions are called.for example : andis this good : or should that test be done in Application_BeginRequest ? what is better ? thnx protected void Application_BeginRequest ( object sender , EventArgs e ) { this.FixURLCosmetics ( ) ; } private void FixURLCosmetics ( ) { HttpContext context = HttpContext.Current ; if ( ! context.Request.HttpMethod.ToString ( ) .Equals ( `` GET '' , StringComparison.OrdinalIgnoreCase ) ) { // if not a GET method cancel url cosmetics return ; } ; string url = context.Request.RawUrl.ToString ( ) ; bool doRedirect = false ; // remove > default.aspx if ( url.EndsWith ( `` /default.aspx '' , StringComparison.OrdinalIgnoreCase ) ) { url = url.Substring ( 0 , url.Length - 12 ) ; doRedirect = true ; } // remove > www if ( url.Contains ( `` //www '' ) ) { url = url.Replace ( `` //www '' , `` // '' ) ; doRedirect = true ; } // redirect if necessary if ( doRedirect ) { context.Response.Redirect ( url ) ; } } if ( ! context.Request.HttpMethod.ToString ( ) .Equals ( `` GET '' , StringComparison.OrdinalIgnoreCase ) ) { // if not a GET method cancel url cosmetics return ; } ;",is it better to test if a function is needed inside or outside of it ? "C_sharp : I read a couple of articles that say that with the introduction of named arguments in C # 3.0 , the name of parameters are now part of the public contract . Is this true , and what does it mean exactly ? I ran a simple test and changing a parameter name in MyLib.dll did not break MyApp.exe which called the method using a named argument with the original name , I think because the C # compiler did overload resolution at compile time , and the generated IL knows nothing about the parameter name . This is what the disassembled code looks on Reflector : ... and this is the original source code : private static void Main ( ) { bool CS $ 0 $ 0000 = true ; Class1.DoSomething ( CS $ 0 $ 0000 ) ; Console.ReadKey ( ) ; } static void Main ( ) { MyLib.Class1.DoSomething ( a : true ) ; Console.ReadKey ( ) ; }",Is a parameter name change in C # a runtime breaking change ? "C_sharp : In .NET , most of the standard strings used for formatting a DateTime value are culture-aware , for example the ShortDatePattern ( `` d '' ) format string switches the order of the year/month/day parts around depending on the current culture : I need something similar for a date format containing only month and day : Using e.g . the `` MM/dd '' custom format string does n't work ; it will incorrectly display `` 01.11 '' for Jan 11 in the German culture , when I want it to display `` 11.01 . `` How can I build a custom format string that takes the order of the date parts into account ? 6/15/2009 1:45:30 PM - > 6/15/2009 ( en-US ) 6/15/2009 1:45:30 PM - > 15/06/2009 ( fr-FR ) 6/15/2009 1:45:30 PM - > 15.06.2009 ( de-DE ) 6/15/2009 1:45:30 PM - > 6/15 ( en-US ) 6/15/2009 1:45:30 PM - > 15/06 ( fr-FR ) 6/15/2009 1:45:30 PM - > 15.06 . ( de-DE )",Custom culture aware date format in .NET "C_sharp : This is a severe problem in my application for some months with out finding any good solution.I noticed that C # manage the way Stream class is streaming in WCF , without considering my configuration.Firstly , I have a class that inherit from FileStream so I can watch how much was read until now from the client side at anytime : Secondly , below is my service method of reading the client 's stream that contain the file.My main problem is that FileStreamWatching.Read does not start for each time I summon it from this method below , instead FileStreamWatching.Read start one time for each X times I call it.. Strange . *Look at the out put laterThis is the output at the client side for each time FileStreamWatching.Read is activated : ( Remmber the buffer lenght is only 1000 ! ) Arr Lenght : 256 , Read : 256Arr Lenght : 4096 , Read : 4096Arr Lenght : 65536 , Read : 65536Arr Lenght : 65536 , Read : 65536Arr Lenght : 65536 , Read : 65536Arr Lenght : 65536 , Read : 65536 ... .Until the file transfare is complete.Problems : The Lenght of the buffer I brought to the read method isnt 256/4096/65536 . It is 1000.The Read from the FileStreamWatching class does not start each time I call it from the service.My goals : Controling on how much I reacive from the client for each read.The FileStreamWatching.Read will start each time I call it from the service.My Client configuration : My service configuration ( There is no configuration file here ) : public class FileStreamWatching : FileStream { /// < summary > /// how much was read until now /// < /summary > public long _ReadUntilNow { get ; private set ; } public FileStreamWatching ( string Path , FileMode FileMode , FileAccess FileAccess ) : base ( Path , FileMode , FileAccess ) { this._ReadUntilNow = 0 ; } public override int Read ( byte [ ] array , int offset , int count ) { int ReturnV = base.Read ( array , offset , count ) ; //int ReturnV = base.Read ( array , offset , count ) ; if ( ReturnV > 0 ) { _ReadUntilNow += ReturnV ; Console.WriteLine ( `` Arr Lenght : `` + array.Length ) ; Console.WriteLine ( `` Read : `` + ReturnV ) ; Console.WriteLine ( `` **************************** '' ) ; } return ReturnV ; } } public void Get_File_From_Client ( Stream MyStream ) { using ( FileStream fs = new FileStream ( @ '' C : \Upload\ '' + `` Chat.rar '' , FileMode.Create ) ) { byte [ ] buffer = new byte [ 1000 ] ; int bytes = 0 ; while ( ( bytes = MyStream.Read ( buffer , 0 , buffer.Length ) ) > 0 ) { fs.Write ( buffer , 0 , bytes ) ; fs.Flush ( ) ; } } } < configuration > < system.serviceModel > < bindings > < basicHttpBinding > < binding name= '' BasicHttpBinding_IJob '' transferMode= '' Streamed '' / > < /basicHttpBinding > < /bindings > < client > < endpoint address= '' http : //localhost:8080/Request2 '' binding= '' basicHttpBinding '' bindingConfiguration= '' BasicHttpBinding_IJob '' contract= '' ServiceReference1.IJob '' name= '' BasicHttpBinding_IJob '' / > < /client > < /system.serviceModel > < /configuration > BasicHttpBinding BasicHttpBinding1 = new BasicHttpBinding ( ) ; BasicHttpBinding1.TransferMode = TransferMode.Streamed ; // BasicHttpBinding1.MaxReceivedMessageSize = int.MaxValue ; BasicHttpBinding1.ReaderQuotas.MaxArrayLength = 1000 ; BasicHttpBinding1.ReaderQuotas.MaxBytesPerRead = 1000 ; BasicHttpBinding1.MaxBufferSize = 1000 ; // ServiceHost host = new ServiceHost ( typeof ( JobImplement ) , new Uri ( `` http : //localhost:8080 '' ) ) ; // ServiceMetadataBehavior behavior = new ServiceMetadataBehavior ( ) ; behavior.HttpGetEnabled = true ; // host.Description.Behaviors.Add ( behavior ) ; ServiceThrottlingBehavior throttle = new ServiceThrottlingBehavior ( ) ; throttle.MaxConcurrentCalls = 1 ; host.Description.Behaviors.Add ( throttle ) ; // // host.AddServiceEndpoint ( typeof ( IJob ) , BasicHttpBinding1 , `` Request2 '' ) ; host.Open ( ) ;",WCF Streaming - Limiting speed "C_sharp : Consider this code : We now want to refactor it to loosely couple it . We end up with this : Looks ok right ? Now any implementation can use the interface and all is good.What if I now say that the implementation is a WCF class and that the using statement before the refactoring was done was there for a reason . ie/to close the WCF connection.So now our interface has to implement a Dispose method call or we use a factory interface to get the implementation and put a using statement around that.To me ( although new to the subject ) this seems like a leaky abstraction . We are having to put method calls in our code just for the sake of the way the implementation is handling stuff.Could someone help me understand this and confirm whether I 'm right or wrong.Thanks public class MyClass ( ) { public MyClass ( ) { } public DoSomething ( ) { using ( var service = new CustomerCreditServiceClient ( ) ) { var creditLimit = service.GetCreditLimit ( customer.Firstname , customer.Surname , customer.DateOfBirth ) ; } } } public class MyClass ( ) { private readonly ICustomerCreditService service ; public MyClass ( ICustomerCreditService service ) { this.service= service ; } public DoSomething ( ) { var creditLimit = service.GetCreditLimit ( customer.Firstname , customer.Surname , customer.DateOfBirth ) ; } }",Is it a leaky abstraction if implementation of interface calls Dispose "C_sharp : Why `` my , string '' .Split ( ' , ' ) works in .NET C # ? The declaration of Split according to MSDN is Split ( Char [ ] ) .MSDN String.Split MethodI supposed that C # 5 converts the single char ' , ' to char [ ] { ' , ' } ; But I must be wrong because the following code does n't work : EDIT : Thanks to the Jon Skeet 's answer I changed the argument to params char [ ] and it works proving the concept . static void Main ( ) { GetChar ( ' , ' ) ; } static char GetChar ( char [ ] input ) { return input [ 0 ] ; } static char GetChar ( params char [ ] input ) { return input [ 0 ] ; }","Why `` my , string '' .Split ( ' , ' ) works in .NET C #" "C_sharp : So I am using WPF 3.5 with MVVM + DataTemplate method to load 2 views on the GUI . I have observed while memory profiling that items generated as part of items container of items controls are pinned into the memory and does n't get GCed even after the view is unloaded ! I just ran tests and found out it is reproducible even for the simplest of code ... You guys can check for yourself.XAML : Code Behind : I perform forced GC by Left Shift + Alt + Ctrl + G. All items for the Test1 or Test3 view and View Model gets dead after they are unloaded correctly . So that is as expected.But the collection generated in the Test1 model ( that has Test2 objects ) , remains pinned into the memory . And it indicates that the array is the one used by the items container of the listbox because it shows the number of de-virtualized items from the listbox ! This pinned array changes it 's size when we minimize or restore the view in Test1 view mode ! One time it was 16 items and next time it was 69 item when profiled.This means WPF performs pinning of items generated in items controls ! Can anyone explain this ? Does this have any signficant drawback ? Thx a lot . < Window x : Class= '' ContentControlVMTest.Window2 '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : ContentControlVMTest '' Title= '' Window2 '' Height= '' 300 '' Width= '' 300 '' > < DockPanel LastChildFill= '' True '' > < CheckBox Click= '' CheckBox_Click '' Content= '' Test1 ? '' DockPanel.Dock= '' Top '' Margin= '' 5 '' / > < ContentControl x : Name= '' contentControl '' > < ContentControl.Resources > < DataTemplate DataType= '' { x : Type local : Test3 } '' > < TextBlock Text= '' { Binding C } '' Margin= '' 5 '' / > < /DataTemplate > < DataTemplate DataType= '' { x : Type local : Test1 } '' > < DockPanel LastChildFill= '' True '' Margin= '' 5 '' > < TextBlock Text= '' { Binding A } '' DockPanel.Dock= '' Top '' Margin= '' 5 '' / > < ListBox ItemsSource= '' { Binding Bs } '' DisplayMemberPath= '' B '' Margin= '' 5 '' / > < /DockPanel > < /DataTemplate > < /ContentControl.Resources > < /ContentControl > < /DockPanel > < /Window > public class Test3 { public string C { get ; set ; } } public class Test2 { public string B { get ; set ; } } public class Test1 { public string A { get ; set ; } private List < Test2 > _Bs ; public List < Test2 > Bs { get { return _Bs ; } set { _Bs = value ; } } } public partial class Window2 : Window { public Window2 ( ) { InitializeComponent ( ) ; this.KeyDown += Window_KeyDown ; } private void Window_KeyDown ( object sender , System.Windows.Input.KeyEventArgs e ) { if ( Keyboard.IsKeyDown ( Key.LeftCtrl ) ) if ( Keyboard.IsKeyDown ( Key.LeftShift ) ) if ( Keyboard.IsKeyDown ( Key.LeftAlt ) ) if ( Keyboard.IsKeyDown ( Key.G ) ) { GC.Collect ( 2 , GCCollectionMode.Forced ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( 2 , GCCollectionMode.Forced ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( 3 , GCCollectionMode.Forced ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( 3 , GCCollectionMode.Forced ) ; } } private void CheckBox_Click ( object sender , RoutedEventArgs e ) { if ( ( ( CheckBox ) sender ) .IsChecked.GetValueOrDefault ( false ) ) { var x = new Test1 ( ) { A = `` Test1 A '' } ; x.Bs = new List < Test2 > ( ) ; for ( int i = 1 ; i < 10000 ; i++ ) { x.Bs.Add ( new Test2 ( ) { B = `` Test1 B `` + i } ) ; } contentControl.Content = x ; } else { contentControl.Content = new Test3 ( ) { C = `` Test3 C '' } ; } } }",Pinned Instances for GC - Not traceable from my managed code "C_sharp : This question is about best practices when using ContinueWith ( ) to handle a TPL datablock 's completion.The ITargetBlock < TInput > .Completion ( ) method allows you to asynchronously handle a datablock 's completion using ContinueWith ( ) .Consider the following Console app code which demonstrates a very basic use : The code has a very simple TransformBlock which divides integers by 2.0 and turns them into doubles . The transformed data is processed by an ActionBlock which just outputs the values to the console window.The output is : When the TransformBlock is completed , I want to also complete the ActionBlock . It is convenient to do this like so : And here lies the issue . Because this is inside an async method and I 'm ignoring the return value from ContinueWith ( ) , I get a compiler warning : warning CS4014 : Because this call is not awaited , execution of the current method continues before the call is completed . Consider applying the 'await ' operator to the result of the call.Clearly I ca n't await the call as advised by the warning - if I do so , the code hangs up because the CompleteWith ( ) task ca n't complete until transform.Complete ( ) is called.Now I do n't have a problem with dealing with the warning itself ( I can just suppress it or assign the task to a variable , or use a .Forget ( ) task extension and so on ) - but here 's my questions : Is it safe to handle linked DataBlock completion in this way ? Is there a better way ? Is there anything important here that I 've overlooked ? I think that if I was doing anything other than output.Complete ( ) inside the continuation , I 'd have to provide exception handling - but perhaps even just calling output.Complete ( ) is fraught with peril ? private static void Main ( ) { test ( ) .Wait ( ) ; } static async Task test ( ) { var transform = new TransformBlock < int , double > ( i = > i/2.0 ) ; var output = new ActionBlock < double > ( d = > Console.WriteLine ( d ) ) ; // Warning CS4014 here : transform.Completion.ContinueWith ( continuation = > output.Complete ( ) ) ; transform.LinkTo ( output ) ; for ( int i = 0 ; i < 10 ; ++i ) await transform.SendAsync ( i ) ; transform.Complete ( ) ; await output.Completion ; } 00.511.522.533.544.5 transform.Completion.ContinueWith ( continuation = > output.Complete ( ) ) ;",Best practice for ITargetBlock < TInput > .Completion.ContinueWith ( ) "C_sharp : C # noob here , coming from experience in other languages . ( Most notably Java ) .I 'm looking at this question 's code . It 's a standard WinForms C # project in VS 2013 : drop a button and a textbox on the form and use this code : Press the button , wait 2 seconds for the four DelayedAdd calls to complete , and the result ( 115 ) is displayed in the text box . How can I get the result displayed on the text box after every DelayedAdd call ? I tried to shove the final continuation between each call , but that fails , I 'm guessing because the continuations I inserted do n't return the integer result t. I 'm such a C # noob that I do n't even know how to fix that , let alone do this in an idiomatic way . private void button1_Click ( object sender , EventArgs e ) { Task.Factory.StartNew < int > ( ( ) = > DelayedAdd ( 5 , 10 ) ) .ContinueWith ( t = > DelayedAdd ( t.Result , 20 ) ) .ContinueWith ( t = > DelayedAdd ( t.Result , 30 ) ) .ContinueWith ( t = > DelayedAdd ( t.Result , 50 ) ) .ContinueWith ( t = > textBox1.Text = t.Result.ToString ( ) , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ; } private int DelayedAdd ( int a , int b ) { Thread.Sleep ( 500 ) ; return a + b ; } Task.Factory.StartNew < int > ( ( ) = > DelayedAdd ( 5 , 10 ) ) .ContinueWith ( t = > textBox1.Text = t.Result.ToString ( ) , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( t = > DelayedAdd ( t.Result , 20 ) ) .ContinueWith ( t = > textBox1.Text = t.Result.ToString ( ) , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( t = > DelayedAdd ( t.Result , 30 ) ) .ContinueWith ( t = > textBox1.Text = t.Result.ToString ( ) , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( t = > DelayedAdd ( t.Result , 50 ) ) .ContinueWith ( t = > textBox1.Text = t.Result.ToString ( ) , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ;",Update text box on continuation with Winforms and C # "C_sharp : I have a class called GenericPermutations that is both enumerable and an enumerator . Its job is to take an ordered list of objects and iterate through each permutation of them in order.Example , an integer implemenation of this class could iterate through the following : So its enumerable in the sense that it contains a 'list ' of things you can enumerate over . It 's also an enumerator , because its job involves finding the next permutation.THE ISSUE : I am currently trying to integrate IEnumerator and IEnumerable with this class , and it seems to me like it should be both ( rather than using a sub class as the IEnumerable ) . Thus far I have avoided the issue with trying to get two enumerators from it by passing a new GenericPermutation object in the GetEnumerator method.Is this a bad idea ? Anything else I should consider ? GenericPermutations < int > p = new GenericPermutations < int > ( { 1 , 2 , 3 } ) ; p.nextPermutation ( ) ; // 123p.nextPermutation ( ) ; // 132p.nextPermutation ( ) ; // 213// etc .",C # Class is IEnumerable AND an IEnumerator at the same time . What are the issues with this ? "C_sharp : I was thinking about arrays and lists and wondering if and how classes can get an implementation to be initializable like them . Let 's take this class as basis : What I would like to be able to do is to take the given values and internally fill my list.What would be normally possible is this : But I would like to have it for my own custom classes . The next question , which is optional , is if the same can be done for this syntax : I assume that is less likely to be possible . Note , these are different from this : These are direct and optional declarations of internal fields and properties.See also MSDN for more info . class TestClass { private List < int > Numbers = new List < int > ( ) ; // Insert code here } TestClass test = new TestClass ( ) { 2 , 4 , 7 , 10 } ; List < int > test = new List < int > ( ) { 2 , 4 , 7 , 10 } ; TestClass test = { 2 , 4 , 7 , 10 } ; Cat cat = new Cat ( ) { Name = `` Sylvester '' , Age=8 } ;",Initialize elements with brackets like Lists in c # "C_sharp : I discovered a strange behaviour of my program and after futher analysis , I was able to find that there is probably something wrong either in my C # knowledge or somewhere else . I beleive it 's my mistake but I can not find an answer anywhere ... The variable `` b '' in this code is evaluated to null . I do n't get why is it null.I googled and found a response in this question - Implicit casting of Null-Coalescing operator result - with the official specification.But following this specification , I ca n't find the reason why `` b '' is null : ( Maybe I 'm reading it wrong in which case I apologize for spamming . If A exists and is not a nullable type or a reference type , a compile-time error occurs ... .that 's not the case . If b is a dynamic expression , the result type is dynamic . At run-time , a is first evaluated . If a is not null , a is converted to dynamic , and this becomes the result . Otherwise , b is evaluated , and this becomes the result ... .that 's also not the case . Otherwise , if A exists and is a nullable type and an implicit conversion exists from b to A0 , the result type is A0 . At run-time , a is first evaluated . If a is not null , a is unwrapped to type A0 , and this becomes the result . Otherwise , b is evaluated and converted to type A0 , and this becomes the result ... .A exists , implicit conversion from b to A0 does not exist . Otherwise , if A exists and an implicit conversion exists from b to A , the result type is A . At run-time , a is first evaluated . If a is not null , a becomes the result . Otherwise , b is evaluated and converted to type A , and this becomes the result ... .A exists , implicit conversion from b to A does not exist . Otherwise , if b has a type B and an implicit conversion exists from a to B , the result type is B . At run-time , a is first evaluated . If a is not null , a is unwrapped to type A0 ( if A exists and is nullable ) and converted to type B , and this becomes the result . Otherwise , b is evaluated and becomes the result ... .b has a type B and implicit conversion exists from a to B. a is evaluated into null . Therefore , b should be evaluated and b should be the result . Otherwise , a and b are incompatible , and a compile-time error occurs . Does not happenAm I missing something please ? public class B { public static implicit operator B ( A values ) { return null ; } } public class A { } public class Program { static void Main ( string [ ] args ) { A a = new A ( ) ; B b = a ? ? new B ( ) ; //b = null ... is it wrong that I expect b to be B ( ) ? } }",Implicit conversion with null-coalescing operator "C_sharp : Note : Please note that the code below is essentially non-sense , and just for illustration purposes.Based on the fact that the right-hand side of an assignment must always be evaluated before it 's value is assigned to the left-hand side variable , and that increment operations such as ++ and -- are always performed right after evaluation , I would not expect the following code to work : Rather , I would expect newArray1 [ 0 ] to be assigned to newArray2 [ 1 ] , newArray1 [ 1 ] to newArray [ 2 ] and so on up to the point of throwing a System.IndexOutOfBoundsException . Instead , and to my great surprise , the version that throws the exception isSince , in my understanding , the compiler first evaluates the RHS , assigns it to the LHS and only then increments this is to me an unexpected behaviour . Or is it really expected and I am clearly missing something ? string [ ] newArray1 = new [ ] { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } ; string [ ] newArray2 = new string [ 4 ] ; int IndTmp = 0 ; foreach ( string TmpString in newArray1 ) { newArray2 [ IndTmp ] = newArray1 [ IndTmp++ ] ; } string [ ] newArray1 = new [ ] { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } ; string [ ] newArray2 = new string [ 4 ] ; int IndTmp = 0 ; foreach ( string TmpString in newArray1 ) { newArray2 [ IndTmp++ ] = newArray1 [ IndTmp ] ; }",Strange Increment Behaviour in C # "C_sharp : I 'm currently working on a C # WPF application which contains a fullscreen Grid with controls that are dynamically added to it at runtime . I have code in place to allow the user to move these controls across the Grid with mouse events . What I now want to do is allow the user to also resize the controls ( while keeping the aspect ratio ) , also at runtime . I have seen various tutorials describing how to do this using a Canvas ( and Thumb controls ) , but none on a Grid . As I can not use a Canvas in my application , is there an efficient way to implement this on a grid ? To give you an idea of what my code looks like , I placed my mouse events below : [ Edited below ] MainWindow.xaml.cs : MainWindow.xaml ( example ) : Edit : I have found that using TranslateTransform does not change a control 's margin . I need the margin to change appropriately in order for this to work.Edit 2 : Now I have added [ modified ] code for a resizing adorner ( found here ) . It almost actually works . The problem is that I 'm experiencing odd behavior with the adorners . On one of my controls ( in the top left corner ) , all 4 appear in their appropriate corners . But the rest of my controls only get 1-2 adorners and they 're not spaced correctly . The behavior with those is stranger as well . Yes , I realize this is a lot of code but I 'd suspect the problem would be in the ResizingAdorner class.Edit 3 : Added 'boilerplate ' code for those who want to copy & paste . It should compile with no problems . Let me know if you have any issues.Edit 4 ( 1/10/2018 ) : Still no good answer . It seems that the Thumb controls on the adorner only align themselves correctly if the control 's Margin is 0,0 . When moved from that position , the adorners space out from the element.Edit 5 ( 1/15/2018 ) : The adorner class was originally designed for a Canvas and running it on a Grid may contribute to the problem . My best guess is that the ArrangeOverride method was messed up because of it ( that 's where the thumbs are placed on their UIElement ) . public partial class MainWindow : Window { //Orientation variables : public static Point _anchorPoint ; public static Point _currentPoint ; private static double _originalTop ; private static double _originalLeft ; private static Point _startPoint ; private static bool _isDown = false ; private static bool _isInDrag = false ; private static bool _isDragging = false ; public static UIElement selectedElement = null ; public static bool elementIsSelected = false ; public static Dictionary < object , TranslateTransform > PointDict = new Dictionary < object , TranslateTransform > ( ) ; public static AdornerLayer aLayer ; public MainWindow ( ) { InitializeComponent ( ) ; } //Control events : public static void Control_MouseLeftButtonUp ( object sender , MouseButtonEventArgs e ) //HUD element left mouse button up { if ( _isInDrag ) { var element = sender as FrameworkElement ; element.ReleaseMouseCapture ( ) ; _isInDrag = false ; e.Handled = true ; aLayer = AdornerLayer.GetAdornerLayer ( selectedElement ) ; aLayer.Add ( new ResizingAdorner ( selectedElement ) ) ; } } public static void HUD_MouseDown ( object sender , MouseButtonEventArgs e ) { if ( elementIsSelected ) { elementIsSelected = false ; _isDown = false ; if ( selectedElement ! = null ) { aLayer.Remove ( aLayer.GetAdorners ( selectedElement ) [ 0 ] ) ; selectedElement = null ; } } if ( e.Source ! = mw.PACSGrid ) { _isDown = true ; _startPoint = e.GetPosition ( mw.PACSGrid ) ; selectedElement = e.Source as UIElement ; _originalLeft = VisualWorker.GetLeft ( selectedElement ) ; _originalTop = VisualWorker.GetTop ( selectedElement ) ; aLayer = AdornerLayer.GetAdornerLayer ( selectedElement ) ; aLayer.Add ( new ResizingAdorner ( selectedElement ) ) ; elementIsSelected = true ; e.Handled = true ; } } public static void Control_MouseLeftButtonDown ( object sender , MouseButtonEventArgs e ) //HUD element left mouse button down { if ( elementIsSelected ) { aLayer.Remove ( aLayer.GetAdorners ( selectedElement ) [ 0 ] ) ; selectedElement = sender as UIElement ; var element = sender as FrameworkElement ; _anchorPoint = e.GetPosition ( null ) ; element.CaptureMouse ( ) ; _isInDrag = true ; e.Handled = true ; } } public static void Control_MouseMove ( object sender , MouseEventArgs e ) //Drag & drop HUD element { if ( _isInDrag ) // The user is currently dragging the HUD element ... { _currentPoint = e.GetPosition ( null ) ; TranslateTransform tt = new TranslateTransform ( ) ; bool isMoved = false ; if ( PointDict.ContainsKey ( sender ) ) { tt = PointDict [ sender ] ; isMoved = true ; } tt.X += _currentPoint.X - _anchorPoint.X ; tt.Y += ( _currentPoint.Y - _anchorPoint.Y ) ; _anchorPoint = _currentPoint ; ( sender as UIElement ) .RenderTransform = tt ; if ( isMoved ) { PointDict.Remove ( sender ) ; } PointDict.Add ( sender , tt ) ; } } } // Adorner Class : public class ResizingAdorner : Adorner { Thumb topLeft , topRight , bottomLeft , bottomRight ; // To store and manage the adorner 's visual children . VisualCollection visualChildren ; // Initialize the ResizingAdorner . public ResizingAdorner ( UIElement adornedElement ) : base ( adornedElement ) { visualChildren = new VisualCollection ( this ) ; // Call a helper method to initialize the Thumbs // with a customized cursors . BuildAdornerCorner ( ref topLeft , Cursors.SizeNWSE ) ; BuildAdornerCorner ( ref topRight , Cursors.SizeNESW ) ; BuildAdornerCorner ( ref bottomLeft , Cursors.SizeNESW ) ; BuildAdornerCorner ( ref bottomRight , Cursors.SizeNWSE ) ; // Add handlers for resizing . bottomLeft.DragDelta += new DragDeltaEventHandler ( HandleBottomLeft ) ; bottomRight.DragDelta += new DragDeltaEventHandler ( HandleBottomRight ) ; topLeft.DragDelta += new DragDeltaEventHandler ( HandleTopLeft ) ; topRight.DragDelta += new DragDeltaEventHandler ( HandleTopRight ) ; } // Handler for resizing from the bottom-right . void HandleBottomRight ( object sender , DragDeltaEventArgs args ) { FrameworkElement adornedElement = this.AdornedElement as FrameworkElement ; Thumb hitThumb = sender as Thumb ; if ( adornedElement == null || hitThumb == null ) return ; FrameworkElement parentElement = adornedElement.Parent as FrameworkElement ; // Ensure that the Width and Height are properly initialized after the resize . EnforceSize ( adornedElement ) ; // Change the size by the amount the user drags the mouse , as long as it 's larger // than the width or height of an adorner , respectively . adornedElement.Width = Math.Max ( adornedElement.Width + args.HorizontalChange , hitThumb.DesiredSize.Width ) ; adornedElement.Height = Math.Max ( args.VerticalChange + adornedElement.Height , hitThumb.DesiredSize.Height ) ; } // Handler for resizing from the top-right . void HandleTopRight ( object sender , DragDeltaEventArgs args ) { FrameworkElement adornedElement = this.AdornedElement as FrameworkElement ; Thumb hitThumb = sender as Thumb ; if ( adornedElement == null || hitThumb == null ) return ; FrameworkElement parentElement = adornedElement.Parent as FrameworkElement ; // Ensure that the Width and Height are properly initialized after the resize . EnforceSize ( adornedElement ) ; // Change the size by the amount the user drags the mouse , as long as it 's larger // than the width or height of an adorner , respectively . adornedElement.Width = Math.Max ( adornedElement.Width + args.HorizontalChange , hitThumb.DesiredSize.Width ) ; //adornedElement.Height = Math.Max ( adornedElement.Height - args.VerticalChange , hitThumb.DesiredSize.Height ) ; double height_old = adornedElement.Height ; double height_new = Math.Max ( adornedElement.Height - args.VerticalChange , hitThumb.DesiredSize.Height ) ; double top_old = VisualWorker.GetTop ( adornedElement ) ; //double top_old = Canvas.GetTop ( adornedElement ) ; adornedElement.Height = height_new ; //Canvas.SetTop ( adornedElement , top_old - ( height_new - height_old ) ) ; VisualWorker.SetTop ( adornedElement , top_old - ( height_new - height_old ) ) ; } // Handler for resizing from the top-left . void HandleTopLeft ( object sender , DragDeltaEventArgs args ) { FrameworkElement adornedElement = AdornedElement as FrameworkElement ; Thumb hitThumb = sender as Thumb ; if ( adornedElement == null || hitThumb == null ) return ; // Ensure that the Width and Height are properly initialized after the resize . EnforceSize ( adornedElement ) ; // Change the size by the amount the user drags the mouse , as long as it 's larger // than the width or height of an adorner , respectively . //adornedElement.Width = Math.Max ( adornedElement.Width - args.HorizontalChange , hitThumb.DesiredSize.Width ) ; //adornedElement.Height = Math.Max ( adornedElement.Height - args.VerticalChange , hitThumb.DesiredSize.Height ) ; double width_old = adornedElement.Width ; double width_new = Math.Max ( adornedElement.Width - args.HorizontalChange , hitThumb.DesiredSize.Width ) ; double left_old = VisualWorker.GetLeft ( adornedElement ) ; //double left_old = Canvas.GetLeft ( adornedElement ) ; adornedElement.Width = width_new ; VisualWorker.SetLeft ( adornedElement , left_old - ( width_new - width_old ) ) ; double height_old = adornedElement.Height ; double height_new = Math.Max ( adornedElement.Height - args.VerticalChange , hitThumb.DesiredSize.Height ) ; double top_old = VisualWorker.GetTop ( adornedElement ) ; //double top_old = Canvas.GetTop ( adornedElement ) ; adornedElement.Height = height_new ; //Canvas.SetTop ( adornedElement , top_old - ( height_new - height_old ) ) ; VisualWorker.SetTop ( adornedElement , top_old - ( height_new - height_old ) ) ; } // Handler for resizing from the bottom-left . void HandleBottomLeft ( object sender , DragDeltaEventArgs args ) { FrameworkElement adornedElement = AdornedElement as FrameworkElement ; Thumb hitThumb = sender as Thumb ; if ( adornedElement == null || hitThumb == null ) return ; // Ensure that the Width and Height are properly initialized after the resize . EnforceSize ( adornedElement ) ; // Change the size by the amount the user drags the mouse , as long as it 's larger // than the width or height of an adorner , respectively . //adornedElement.Width = Math.Max ( adornedElement.Width - args.HorizontalChange , hitThumb.DesiredSize.Width ) ; adornedElement.Height = Math.Max ( args.VerticalChange + adornedElement.Height , hitThumb.DesiredSize.Height ) ; double width_old = adornedElement.Width ; double width_new = Math.Max ( adornedElement.Width - args.HorizontalChange , hitThumb.DesiredSize.Width ) ; double left_old = VisualWorker.GetLeft ( adornedElement ) ; //double left_old = Canvas.GetLeft ( adornedElement ) ; adornedElement.Width = width_new ; //Canvas.SetLeft ( adornedElement , left_old - ( width_new - width_old ) ) ; VisualWorker.SetLeft ( adornedElement , left_old - ( width_new - width_old ) ) ; } // Arrange the Adorners . protected override Size ArrangeOverride ( Size finalSize ) { // desiredWidth and desiredHeight are the width and height of the element that 's being adorned . // These will be used to place the ResizingAdorner at the corners of the adorned element . double desiredWidth = AdornedElement.DesiredSize.Width ; double desiredHeight = AdornedElement.DesiredSize.Height ; // adornerWidth & adornerHeight are used for placement as well . double adornerWidth = this.DesiredSize.Width ; double adornerHeight = this.DesiredSize.Height ; topLeft.Arrange ( new Rect ( -adornerWidth / 2 , -adornerHeight / 2 , adornerWidth , adornerHeight ) ) ; topRight.Arrange ( new Rect ( desiredWidth - adornerWidth / 2 , -adornerHeight / 2 , adornerWidth , adornerHeight ) ) ; bottomLeft.Arrange ( new Rect ( -adornerWidth / 2 , desiredHeight - adornerHeight / 2 , adornerWidth , adornerHeight ) ) ; bottomRight.Arrange ( new Rect ( desiredWidth - adornerWidth / 2 , desiredHeight - adornerHeight / 2 , adornerWidth , adornerHeight ) ) ; // Return the final size . return finalSize ; } // Helper method to instantiate the corner Thumbs , set the Cursor property , // set some appearance properties , and add the elements to the visual tree . void BuildAdornerCorner ( ref Thumb cornerThumb , Cursor customizedCursor ) { if ( cornerThumb ! = null ) return ; cornerThumb = new Thumb ( ) ; // Set some arbitrary visual characteristics . cornerThumb.Cursor = customizedCursor ; cornerThumb.Height = cornerThumb.Width = 10 ; cornerThumb.Opacity = 1 ; cornerThumb.Background = new ImageBrush ( new BitmapImage ( new Uri ( @ '' pack : //application : , , ,/Images/Thumb 1.jpg '' ) ) ) ; visualChildren.Add ( cornerThumb ) ; } // This method ensures that the Widths and Heights are initialized . Sizing to content produces // Width and Height values of Double.NaN . Because this Adorner explicitly resizes , the Width and Height // need to be set first . It also sets the maximum size of the adorned element . void EnforceSize ( FrameworkElement adornedElement ) { if ( adornedElement.Width.Equals ( Double.NaN ) ) adornedElement.Width = adornedElement.DesiredSize.Width ; if ( adornedElement.Height.Equals ( Double.NaN ) ) adornedElement.Height = adornedElement.DesiredSize.Height ; FrameworkElement parent = adornedElement.Parent as FrameworkElement ; if ( parent ! = null ) { adornedElement.MaxHeight = parent.ActualHeight ; adornedElement.MaxWidth = parent.ActualWidth ; } } // Override the VisualChildrenCount and GetVisualChild properties to interface with // the adorner 's visual collection . protected override int VisualChildrenCount { get { return visualChildren.Count ; } } protected override Visual GetVisualChild ( int index ) { return visualChildren [ index ] ; } } // Canvas alternative class : public class VisualWorker { public static void SetTop ( UIElement uie , double top ) { var frame = uie as FrameworkElement ; frame.Margin = new Thickness ( frame.Margin.Left , top , frame.Margin.Right , frame.Margin.Bottom ) ; } public static void SetLeft ( UIElement uie , double left ) { var frame = uie as FrameworkElement ; frame.Margin = new Thickness ( left , frame.Margin.Top , frame.Margin.Right , frame.Margin.Bottom ) ; } public static double GetTop ( UIElement uie ) { return ( uie as FrameworkElement ) .Margin.Top ; } public static double GetLeft ( UIElement uie ) { return ( uie as FrameworkElement ) .Margin.Left ; } } < Window x : Name= '' MW '' x : Class= '' MyProgram.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : MyProgram '' mc : Ignorable= '' d '' Title= '' MyProgram '' d : DesignHeight= '' 1080 '' d : DesignWidth= '' 1920 '' ResizeMode= '' NoResize '' WindowState= '' Maximized '' WindowStyle= '' None '' MouseLeave= '' HUD_MouseLeave '' > < Grid x : Name= '' MyGrid MouseDown= '' HUD_MouseDown '' / > < Image x : Name= '' Image1 '' Source= '' pic.png '' Margin= '' 880,862,0,0 '' Height= '' 164 '' Width= '' 162 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' MouseLeftButtonDown= '' Control_MouseLeftButtonDown '' MouseLeftButtonUp= '' Control_MouseLeftButtonUp '' MouseMove= '' Control_MouseMove '' / > < TextBox x : Name= '' Textbox1 '' Margin= '' 440,560,0,0 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' MouseLeftButtonDown= '' Control_MouseLeftButtonDown '' MouseLeftButtonUp= '' Control_MouseLeftButtonUp '' MouseMove= '' Control_MouseMove '' / >",How to resize WPF controls on a grid at runtime ( keeping aspect ratio ) "C_sharp : I 'm just started working on a project in MonoMac , which is pretty cool so far . But there 're still some things I 'm not sure of . For example : How do you use arrays ? Here 's what I found out : When I get an NSArray back from a method I 'm calling and I try to get one of the custom objects in that array I keep getting something like `` can not convert type System.IntPtr to MyType '' .That 's for arrays I get back . But what if I want to create an array on my own ? The implementation of NSArray does not allow me to instantiate it . So if I got the MonoMac website right , I should use an ordinary array like thisrespectively an strongly-typed array which I 'm not aware of how to use it in C # .So what 's the way to go here ? Thanks–f NSArray groupArray = ( NSArray ) groupDictionary.ObjectForKey ( key ) ; MyType myObject = ( MyType ) groupArray.ValueAt ( 0 ) ; int [ ] intArray = int [ 10 ] ;",Proper way to use arrays in MonoMac "C_sharp : I 'm trying to write an implementation of the parking lot test for random number generators . Here are the sources that I 'm getting my information about the test from : Intel math library documentation and Page 4 of this paper along with the phi function for probability density listed here.I wrote an implementation of the test in C # . It uses a 100x100 grid whose values are initially set to null . I then use the random number generator to generate random integers for x and y . If that index of the grid and it 's neighbors are empty , that index gets set to 1 . Otherwise , nothing happens because there was a `` crash '' . I ran it using C # System.Random generator . I do n't believe the results are correct because I always get very near 3079 points parked , which is about 500 short of the average I 'm supposed to get . It 's also yields a p-value of 2.21829146215425E-90 . My code is below . Does anyone have any experience with this or can anyone see something that I might be doing incorrectly in my implementation ? Any help would be greatly appreciated . edit - The problems with my original implementation wereI was plotting squares instead of disksI only plotted points at integer values . I should have used decimal values instead.As a result of the above two , I needed to change my distance checkThanks to Chris Sinclair and mine z for help in figuring this out . The final code is posted below . private void RunParkingLotTest ( ) { points = new int ? [ 100,100 ] ; int parked = 0 ; for ( int i = 0 ; i < 12000 ; i++ ) { int x = random.Next ( 100 ) ; int y = random.Next ( 100 ) ; if ( IsSafeToPark ( x , y ) ) { points [ x , y ] = 1 ; parked++ ; } } Console.WriteLine ( `` Parked : `` + parked + `` \nP value : `` + PhiFunction ( ( parked-3523 ) /21.9 ) ) ; } private bool IsSafeToPark ( int x , int y ) { return PointIsEmpty ( x , y ) & & LeftOfPointIsEmpty ( x , y ) & & RightOfPointIsEmpty ( x , y ) & & BelowPointIsEmpty ( x , y ) & & AbovePointIsEmpty ( x , y ) ; } private bool AbovePointIsEmpty ( int x , int y ) { if ( y == 99 ) { return true ; } else return points [ x , y + 1 ] == null ; } private bool BelowPointIsEmpty ( int x , int y ) { if ( y == 0 ) { return true ; } else return points [ x , y - 1 ] == null ; } private bool RightOfPointIsEmpty ( int x , int y ) { if ( x == 99 ) { return true ; } else return points [ x + 1 , y ] == null ; } private bool LeftOfPointIsEmpty ( int x , int y ) { if ( x == 0 ) { return true ; } else return points [ x - 1 , y ] == null ; } private bool PointIsEmpty ( int x , int y ) { return points [ x , y ] == null ; } private double PhiFunction ( double x ) { //ϕ ( x ) = ( 2π ) −½e−x2/2 return ( ( 1 / Math.Sqrt ( 2 * Math.PI ) ) * Math.Exp ( - ( Math.Pow ( x , 2 ) ) / 2 ) ) ; }",Why is my implementation of the parking lot test for random number generators producing bad results ? "C_sharp : Trying to understand async-await in C # , and a bit stuck in a `` chicken and egg '' problem , maybe.Does an async method need to call another async for it to be asynchronous ? As a high level example , I 'm trying to do a simple write to the file system , but not sure how I can make this task awaitable , if at all.That line of code is being called within a method that I 'm trying to make asynchronous . So while the file is being written , I 'd like to yield control to the application , but not quite sure how to do that.Can someone enlighten me with a very high-level example of how I could write a file to the file system in an async way ? public Task < FileActionStatus > SaveAsync ( path , data ) { // Do some stuff , then ... File.WriteAllBytes ( path , data ) ; // < -- Allow this to yield control ? // ... then return result }",Understanding async - can I await a synchronous method ? "C_sharp : I have a function which I thought I had fixed the CA2000 warning in Code Analysis for , but it just wo n't go away . The warning is on SqlCommand . Here 's the function : I have another function that to me looks no different but does not have a CA2000 warning associated to it . Here 's that function : I do n't understand what 's going on here and what I need to do to fix it . protected internal void LogUserSession ( int ? managerID ) { using ( var sqlCommand = new SqlCommand ( ) ) { sqlCommand.SetCommand ( `` usp_UserActivity_Create '' ) ; SqlParameter prmSessionID = new SqlParameter ( ) ; prmSessionID.ParameterName = `` @ sessionID '' ; prmSessionID.Direction = ParameterDirection.Input ; prmSessionID.SqlDbType = SqlDbType.VarChar ; prmSessionID.Size = 32 ; prmSessionID.SetValue ( SessionID ) ; SqlParameter prmUsername = new SqlParameter ( ) ; prmUsername.ParameterName = `` @ username '' ; prmUsername.Direction = ParameterDirection.Input ; prmUsername.SqlDbType = SqlDbType.VarChar ; prmUsername.Size = 32 ; prmUsername.SetValue ( Username ) ; SqlParameter prmLoginID = new SqlParameter ( ) ; prmLoginID.ParameterName = `` @ loginID '' ; prmLoginID.Direction = ParameterDirection.Output ; prmLoginID.SqlDbType = SqlDbType.Int ; sqlCommand.Parameters.Add ( prmSessionID ) ; sqlCommand.Parameters.Add ( prmUsername ) ; sqlCommand.Parameters.Add ( prmLoginID ) ; using ( sqlCommand.Connection = new SqlConnection ( ConnectionStrings.MainApp ) ) { sqlCommand.Connection.Open ( ) ; sqlCommand.ExecuteNonQueryTryCatch ( ) ; if ( prmLoginID.Value ! = DBNull.Value ) LoginID = Convert.ToInt32 ( prmLoginID.Value ) ; } } } public static bool IsAvailable ( string username ) { using ( var sqlCommand = new SqlCommand ( ) ) { sqlCommand.SetCommand ( `` usp_UsernameIsAvailable '' ) ; var prmUsername = new SqlParameter ( ) ; prmUsername.ParameterName = `` @ username '' ; prmUsername.Direction = ParameterDirection.Input ; prmUsername.SqlDbType = SqlDbType.VarChar ; prmUsername.Size = 32 ; prmUsername.SetValue ( username ) ; var prmReturnValue = new SqlParameter ( ) ; prmReturnValue.ParameterName = `` @ returnValue '' ; prmReturnValue.Direction = ParameterDirection.ReturnValue ; prmReturnValue.SqlDbType = SqlDbType.Bit ; sqlCommand.Parameters.Add ( prmUsername ) ; sqlCommand.Parameters.Add ( prmReturnValue ) ; using ( sqlCommand.Connection = new SqlConnection ( ConnectionStrings.ComplianceApps ) ) { sqlCommand.Connection.Open ( ) ; sqlCommand.ExecuteNonQueryTryCatch ( ) ; return Convert.ToBoolean ( prmReturnValue.Value ) ; } } }",C # Code Analysis CA2000 "C_sharp : I use the following code to take a screenshot : Now this works wonderfully and it 's easy to work with , however I always come across little 'white dots ' in some of the screenshots . This can be very annoying and distort the image when it occurs in larger quantities.I managed to narrow down the issue and when I try to take a screenshot of the following image the bug occurs : The output of the screenshot looks like this : How can you fix this ? And out of curiosity , how is this explained ? In my testing environment the screenshot is n't saved at all . I directly use it with the following code : tl ; dr I 'm trying to take screenshots and some of the pixels are replaced with white and distort the result.Thank you very much in advance.EDIT : It turns out that the bitmap makes the area transparent ( white comes from the background color of the form , thanks for spotting this spender ! ) But obviously as you can clearly see in the first picture ; I 'm not trying to capture any transparent content . Why does it do this ? EDIT2 : This is the whole class I 'm using to select my screenshot : On my form I then go : var rc = SystemInformation.VirtualScreen ; Bitmap bmp = new Bitmap ( rc.Width , rc.Height ) ; Graphics g = Graphics.FromImage ( bmp ) ; g.CopyFromScreen ( rc.Left , rc.Top , 0 , 0 , bmp.Size , CopyPixelOperation.SourceCopy ) ; pictureBox1.Image = bmp ; public partial class SnippingTool : Form { public static Image Snip ( ) { var rc = SystemInformation.VirtualScreen ; Bitmap bmp = new Bitmap ( rc.Width , rc.Height ) ; Graphics g = Graphics.FromImage ( bmp ) ; g.CopyFromScreen ( rc.Left , rc.Top , 0 , 0 , bmp.Size , CopyPixelOperation.SourceCopy ) ; var snipper = new SnippingTool ( bmp ) ; if ( snipper.ShowDialog ( ) == DialogResult.OK ) { return snipper.Image ; } return null ; } public SnippingTool ( Image screenShot ) { InitializeComponent ( ) ; this.BackgroundImage = screenShot ; this.ShowInTaskbar = false ; this.FormBorderStyle = FormBorderStyle.None ; this.StartPosition = FormStartPosition.Manual ; int screenLeft = SystemInformation.VirtualScreen.Left ; int screenTop = SystemInformation.VirtualScreen.Top ; int screenWidth = SystemInformation.VirtualScreen.Width ; int screenHeight = SystemInformation.VirtualScreen.Height ; this.Size = new System.Drawing.Size ( screenWidth , screenHeight ) ; this.Location = new System.Drawing.Point ( screenLeft , screenTop ) ; this.DoubleBuffered = true ; } public Image Image { get ; set ; } private Rectangle rcSelect = new Rectangle ( ) ; private Point pntStart ; protected override void OnMouseDown ( MouseEventArgs e ) { if ( e.Button ! = MouseButtons.Left ) return ; pntStart = e.Location ; rcSelect = new Rectangle ( e.Location , new Size ( 0 , 0 ) ) ; this.Invalidate ( ) ; } protected override void OnMouseMove ( MouseEventArgs e ) { if ( e.Button ! = MouseButtons.Left ) return ; int x1 = Math.Min ( e.X , pntStart.X ) ; int y1 = Math.Min ( e.Y , pntStart.Y ) ; int x2 = Math.Max ( e.X , pntStart.X ) ; int y2 = Math.Max ( e.Y , pntStart.Y ) ; rcSelect = new Rectangle ( x1 , y1 , x2 - x1 , y2 - y1 ) ; this.Invalidate ( ) ; } protected override void OnMouseUp ( MouseEventArgs e ) { if ( rcSelect.Width < = 0 || rcSelect.Height < = 0 ) return ; Image = new Bitmap ( rcSelect.Width , rcSelect.Height ) ; using ( Graphics gr = Graphics.FromImage ( Image ) ) { gr.DrawImage ( this.BackgroundImage , new Rectangle ( 0 , 0 , Image.Width , Image.Height ) , rcSelect , GraphicsUnit.Pixel ) ; } DialogResult = DialogResult.OK ; } protected override void OnPaint ( PaintEventArgs e ) { using ( Brush br = new SolidBrush ( Color.FromArgb ( 120 , Color.Black ) ) ) { int x1 = rcSelect.X ; int x2 = rcSelect.X + rcSelect.Width ; int y1 = rcSelect.Y ; int y2 = rcSelect.Y + rcSelect.Height ; e.Graphics.FillRectangle ( br , new Rectangle ( 0 , 0 , x1 , this.Height ) ) ; e.Graphics.FillRectangle ( br , new Rectangle ( x2 , 0 , this.Width - x2 , this.Height ) ) ; e.Graphics.FillRectangle ( br , new Rectangle ( x1 , 0 , x2 - x1 , y1 ) ) ; e.Graphics.FillRectangle ( br , new Rectangle ( x1 , y2 , x2 - x1 , this.Height - y2 ) ) ; } using ( Pen pen = new Pen ( Color.Red , 3 ) ) { e.Graphics.DrawRectangle ( pen , rcSelect ) ; } } protected override bool ProcessCmdKey ( ref Message msg , Keys keyData ) { if ( keyData == Keys.Escape ) this.DialogResult = DialogResult.Cancel ; return base.ProcessCmdKey ( ref msg , keyData ) ; } } pictureBox1.Image = SnippingTool.Snip ( ) ;",C # screenshot bug ? "C_sharp : I am trying to use the conditional operator , but I am getting hung up on the type it thinks the result should be.Below is an example that I have contrived to show the issue I am having : On the line indicated above , I get the following compile error : Type of conditional expression can not be determined because there is no implicit conversion between ' < null > ' and 'System.DateTime ' I am confused because the parameter is a nullable type ( DateTime ? ) . Why does it need to convert at all ? If it is null then use that , if it is a date time then use that.I was under the impression that : was the same as : Clearly this is not the case . What is the reasoning behind this ? ( NOTE : I know that if I make `` myDateTime '' a nullable DateTime then it will work . But why does it need it ? As I stated earlier this is a contrived example . In my real example `` myDateTime '' is a data mapped value that can not be made nullable . ) class Program { public static void OutputDateTime ( DateTime ? datetime ) { Console.WriteLine ( datetime ) ; } public static bool IsDateTimeHappy ( DateTime datetime ) { if ( DateTime.Compare ( datetime , DateTime.Parse ( `` 1/1 '' ) ) == 0 ) return true ; return false ; } static void Main ( string [ ] args ) { DateTime myDateTime = DateTime.Now ; OutputDateTime ( IsDateTimeHappy ( myDateTime ) ? null : myDateTime ) ; Console.ReadLine ( ) ; ^ } | } |// This line has the compile issue -- -- -- -- -- -- -- -+ condition ? first_expression : second_expression ; if ( condition ) first_expression ; else second_expression ;",Type result with conditional operator in C # "C_sharp : I am trying to define and retrieve custom attributes on a class in a Metro Style App portable library.Something likeThis works in ordinary 4.5 , but in a portable library targetting metro style apps it tells meThanks [ AttributeUsage ( AttributeTargets.Class ) ] public class FooAttribute : Attribute { } [ Foo ] public class Bar { } class Program { static void Main ( string [ ] args ) { var attrs = CustomAttributeExtensions.GetCustomAttribute < FooAttribute > ( typeof ( Bar ) ) ; } } Can not convert type 'System.Type ' to 'System.Reflection.MemberInfo '",Custom Class Attributes in Metro Style App "C_sharp : I have a collection of classes that inherit from an abstract class I created . I 'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class . Is there any way to hide a constructor from all code except a parent class.I 'd like to do this basicallyBut I want to prevent anyone from directly instantiating the 2 concrete classes . I want to ensure that only the MakeAbstractClass ( ) method can instantiate the base classes . Is there any way to do this ? UPDATEI do n't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class . I only need the public methods my Abstract class provides . I do n't really need to prevent the Concrete classes from being instantiated , I 'm just trying to avoid it since they provide no new public interfaces , just different implementations of some very specific things internal to the abstract class.To me , the simplest solution is to make child classes as samjudson mentioned . I 'd like to avoid this however since it would make my abstract class ' file a lot bigger than I 'd like it to be . I 'd rather keep classes split out over a few files for organization.I guess there 's no easy solution to this ... public abstract class AbstractClass { public static AbstractClass MakeAbstractClass ( string args ) { if ( args == `` a '' ) return new ConcreteClassA ( ) ; if ( args == `` b '' ) return new ConcreteClassB ( ) ; } } public class ConcreteClassA : AbstractClass { } public class ConcreteClassB : AbstractClass { }",Is there a way to make a constructor only visible to a parent class in C # ? "C_sharp : I have a List < ISomething > in a json file and I ca n't find an easy way to deserialize it without using TypeNameHandling.All ( which I do n't want / ca n't use because the JSON files are hand-written ) .Is there a way to apply the attribute [ JsonConverter ( typeof ( MyConverter ) ) ] to members of the list instead to the list ? In this case , Shapes is a List < IShape > where IShape is an interface with these two implementors : ShapeRect and ShapeDxf.I 've already created a JsonConverter subclass which loads the item as a JObject and then checks which real class to load given the presence or not of the property Path : How can I apply this JsonConverter to a list ? Thanks . { `` Size '' : { `` Width '' : 100 , `` Height '' : 50 } , `` Shapes '' : [ { `` Width '' : 10 , `` Height '' : 10 } , { `` Path '' : `` foo.bar '' } , { `` Width '' : 5 , `` Height '' : 2.5 } , { `` Width '' : 4 , `` Height '' : 3 } , ] } var jsonObject = JObject.Load ( reader ) ; bool isCustom = jsonObject .Properties ( ) .Any ( x = > x.Name == `` Path '' ) ; IShape sh ; if ( isCustom ) { sh = new ShapeDxf ( ) ; } else { sh = new ShapeRect ( ) ; } serializer.Populate ( jsonObject.CreateReader ( ) , sh ) ; return sh ;",Deserializing a list of interfaces with a custom JsonConverter ? "C_sharp : I have java code that uses SortedMap.tailMap . In my ported code , I have SortedMap = Dictionary < IComparable , value > . I need a way to copy / mimic tailMap in C # . I 've thought something like the following : myDictionary.Where ( p = > p.Key.CompareTo ( value ) > = 0 ) .ToDictionaryThis returns a Dictionary , and I need a SortedDictionary returned . I could create a SortedDictionary from the Dictionary , but I feel like there should be a more elegant and perfomant way to do this as it 's already sorted.Another thought was to do something like That should work , I 'm not sure how the adding of values in a sorted order will affect timing on the inserts as I build that list.Any other thoughts ? Java SortedMapC # SortedDictionary var newSD = new SortedDictionary < k , v > ( ) ; foreach ( var p in oldDictionary.Where ( p = > p.Key.CompareTo ( value ) > = 0 ) ) newSD.Add ( p.Key , p.Value ) ;",Equivalent of Java 's SortedMap.tailMap in C # SortedDictionary "C_sharp : I am trying to execute a stored procedure with this declaration : And I am calling in C # as follows : But I just get back this error : Procedure or function 'getByName ' expects parameter ' @ firstName ' which was not supplied.Update : and stating : for both parameters , yet it continues to throw the exception . ALTER PROCEDURE [ dbo ] . [ getByName ] @ firstName varchar , @ lastName varcharAS ... public List < Person > GetPersonByName ( string first , string last ) { var people = new List < Person > ( ) ; var connString = ConfigurationManager.ConnectionStrings [ `` MyDbConnString '' ] .ConnectionString ; using ( var conn = new SqlConnection ( connString ) ) { using ( var cmd = new SqlCommand ( `` dbo.getByName '' , conn ) ) { cmd.CommandType = CommandType.StoredProcedure ; cmd.Parameters.Add ( new SqlParameter ( `` @ firstName '' , SqlDbType.VarChar , 50 ) ) .Value = first ; cmd.Parameters.Add ( new SqlParameter ( `` @ lastName '' , SqlDbType.VarChar , 50 ) ) .Value = last ; conn.Open ( ) ; using ( var reader = cmd.ExecuteReader ( ) ) { people = ReadPeopleData ( reader ) ; } conn.Close ( ) ; } } return people ; } ALTER PROCEDURE [ dbo ] . [ getEmployeesByName ] @ firstName varchar ( 50 ) , @ lastName varchar ( 50 ) AS ... cmd.Parameters.Add ( new SqlParameter ( `` @ firstName '' , SqlDbType.VarChar , 50 ) ) .Value",Stored procedure expects a parameter I am already passing in C_sharp : I 've a question regarding enforcing a business rule via a specification pattern . Consider the following example : The business rule should enforce that there can not be a child in the collection which validity period intersects with another.For that I would like to implement a specification that is then be used to throw an exception if an invalid child is added AND as well can be used to check whether the rule will be violated BEFORE adding the child.Like : But in this example the child accesses the parent . And to me that doesnt seem that correct . That parent might not exist when the child has not been added to the parent yet . How would you implement it ? public class Parent { private ICollection < Child > children ; public ReadOnlyCollection Children { get ; } public void AddChild ( Child child ) { child.Parent = this ; children.Add ( child ) ; } } public class Child { internal Parent Parent { get ; set ; } public DateTime ValidFrom ; public DateTime ValidTo ; public Child ( ) { } } public class ChildValiditySpecification { bool IsSatisfiedBy ( Child child ) { return child.Parent.Children.Where ( < validityIntersectsCondition here > ) .Count > 0 ; } },Specification pattern implementation help "C_sharp : I have the following C # project targetting .NET 4.0 that takes a source code file , compiles it into an assembly on the fly and then executes a static method of a type contained in that assembly.This works as expected , as long as I do n't start the program with a debugger attached . In that case I get an exception on the call to xmlSerializer.Serialize ( sw , family ) ; , more precisely a System.NullReferenceException inside a System.TypeInitializationException inside a System.InvalidOperationException.If I take the same program , include the source code file in the project and compile it directly into the main program assembly , I will not get an exception regardless of whether or not a debugger is attached.Please note that I my project references the exact same assemblies as those listed when compiling on the fly.Why does it matter to the code compiled on the fly whether or not a debugger is attached ? What am I missing ? Main file Program.cs : File compiled into separate assembly SerializerTest.cs : This is the csproj file used to compile the project using Visual C # 2010 Express on Windows 7 : using System ; using System.CodeDom.Compiler ; using System.IO ; using System.Reflection ; using System.Linq ; namespace DebugSerializeCompiler { class Program { static void Main ( ) { if ( ! Environment.GetCommandLineArgs ( ) .Contains ( `` Compile '' ) ) { DebugSerializeCompiler.SerializerTest.Run ( ) ; } else { Assembly assembly ; if ( TryCompile ( `` ..\\..\\SerializerTest.cs '' , new [ ] { `` Microsoft.CSharp.dll '' , `` System.dll '' , `` System.Core.dll '' , `` System.Data.dll '' , `` System.Xml.dll '' } , out assembly ) ) { Type type = assembly.GetType ( `` DebugSerializeCompiler.SerializerTest '' ) ; MethodInfo methodInfo = type.GetMethod ( `` Run '' ) ; methodInfo.Invoke ( null , null ) ; } } Console.ReadKey ( ) ; } static bool TryCompile ( string fileName , string [ ] referencedAssemblies , out Assembly assembly ) { bool result ; CodeDomProvider compiler = CodeDomProvider.CreateProvider ( `` CSharp '' ) ; var compilerparams = new CompilerParameters { GenerateExecutable = false , GenerateInMemory = true } ; foreach ( var referencedAssembly in referencedAssemblies ) { compilerparams.ReferencedAssemblies.Add ( referencedAssembly ) ; } using ( var reader = new StreamReader ( fileName ) ) { CompilerResults compilerResults = compiler.CompileAssemblyFromSource ( compilerparams , reader.ReadToEnd ( ) ) ; assembly = compilerResults.CompiledAssembly ; result = ! compilerResults.Errors.HasErrors ; if ( ! result ) { Console.Out.WriteLine ( `` Compiler Errors : '' ) ; foreach ( CompilerError error in compilerResults.Errors ) { Console.Out.WriteLine ( `` Position { 0 } . { 1 } : { 2 } '' , error.Line , error.Column , error.ErrorText ) ; } } } return result ; } } } using System ; using System.Collections.Generic ; using System.IO ; using System.Xml.Serialization ; namespace DebugSerializeCompiler { public class SerializerTest { public static void Run ( ) { Console.WriteLine ( `` Executing Run ( ) '' ) ; var family = new Family ( ) ; var xmlSerializer = new XmlSerializer ( typeof ( Family ) ) ; TextWriter sw = new StringWriter ( ) ; try { if ( sw == null ) Console.WriteLine ( `` sw == null '' ) ; if ( family == null ) Console.WriteLine ( `` family == null '' ) ; if ( xmlSerializer == null ) Console.WriteLine ( `` xmlSerializer == null '' ) ; xmlSerializer.Serialize ( sw , family ) ; } catch ( Exception e ) { Console.WriteLine ( `` Exception caught : '' ) ; Console.WriteLine ( e ) ; } Console.WriteLine ( sw ) ; } } [ Serializable ] public class Family { public string LastName { get ; set ; } public List < FamilyMember > FamilyMembers { get ; set ; } } [ Serializable ] public class FamilyMember { public string FirstName { get ; set ; } } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Project ToolsVersion= '' 4.0 '' DefaultTargets= '' Build '' xmlns= '' http : //schemas.microsoft.com/developer/msbuild/2003 '' > < PropertyGroup > < Configuration Condition= '' ' $ ( Configuration ) ' == `` `` > Debug < /Configuration > < Platform Condition= '' ' $ ( Platform ) ' == `` `` > x86 < /Platform > < ProductVersion > 8.0.30703 < /ProductVersion > < SchemaVersion > 2.0 < /SchemaVersion > < ProjectGuid > { 7B8D2187-4C58-4310-AC69-9F87107C25AA } < /ProjectGuid > < OutputType > Exe < /OutputType > < AppDesignerFolder > Properties < /AppDesignerFolder > < RootNamespace > DebugSerializeCompiler < /RootNamespace > < AssemblyName > DebugSerializeCompiler < /AssemblyName > < TargetFrameworkVersion > v4.0 < /TargetFrameworkVersion > < TargetFrameworkProfile > Client < /TargetFrameworkProfile > < FileAlignment > 512 < /FileAlignment > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Debug|x86 ' `` > < PlatformTarget > x86 < /PlatformTarget > < DebugSymbols > true < /DebugSymbols > < DebugType > full < /DebugType > < Optimize > false < /Optimize > < OutputPath > bin\Debug\ < /OutputPath > < DefineConstants > DEBUG ; TRACE < /DefineConstants > < ErrorReport > prompt < /ErrorReport > < WarningLevel > 4 < /WarningLevel > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Release|x86 ' `` > < PlatformTarget > x86 < /PlatformTarget > < DebugType > pdbonly < /DebugType > < Optimize > true < /Optimize > < OutputPath > bin\Release\ < /OutputPath > < DefineConstants > TRACE < /DefineConstants > < ErrorReport > prompt < /ErrorReport > < WarningLevel > 4 < /WarningLevel > < /PropertyGroup > < ItemGroup > < Reference Include= '' System '' / > < Reference Include= '' System.Core '' / > < Reference Include= '' Microsoft.CSharp '' / > < Reference Include= '' System.Data '' / > < Reference Include= '' System.Xml '' / > < /ItemGroup > < ItemGroup > < Compile Include= '' Program.cs '' / > < Compile Include= '' Properties\AssemblyInfo.cs '' / > < Compile Include= '' SerializerTest.cs '' > < SubType > Code < /SubType > < /Compile > < /ItemGroup > < Import Project= '' $ ( MSBuildToolsPath ) \Microsoft.CSharp.targets '' / > < ! -- To modify your build process , add your task inside one of the targets below and uncomment it . Other similar extension points exist , see Microsoft.Common.targets . < Target Name= '' BeforeBuild '' > < /Target > < Target Name= '' AfterBuild '' > < /Target > -- > < /Project >",Why does C # code compiled on the fly not work when a debugger is attached ? "C_sharp : The LINQ Join ( ) method with Nullable < int > for TKey skips over null key matches . What am I missing in the documentation ? I know that I can switch to SelectMany ( ) , I 'm just curious why this equality operation works like SQL and not like C # since as near as I can tell , the EqualityComparer < int ? > .Default works exactly like I would expect it to for null values.http : //msdn.microsoft.com/en-us/library/bb534675.aspx using System ; using System.IO ; using System.Linq ; using System.Collections.Generic ; public class dt { public int ? Id ; public string Data ; } public class JoinTest { public static int Main ( string [ ] args ) { var a = new List < dt > { new dt { Id = null , Data = `` null '' } , new dt { Id = 1 , Data = `` 1 '' } , new dt { Id = 2 , Data = `` 2 '' } } ; var b = new List < dt > { new dt { Id = null , Data = `` NULL '' } , new dt { Id = 2 , Data = `` two '' } , new dt { Id = 3 , Data = `` three '' } } ; //Join with null elements var c = a.Join ( b , dtA = > dtA.Id , dtB = > dtB.Id , ( dtA , dtB ) = > new { aData = dtA.Data , bData = dtB.Data } ) .ToList ( ) ; // Output : // 2 two foreach ( var aC in c ) Console.WriteLine ( aC.aData + `` `` + aC.bData ) ; Console.WriteLine ( `` `` ) ; //Join with null elements converted to zero c = a.Join ( b , dtA = > dtA.Id.GetValueOrDefault ( ) , dtB = > dtB.Id.GetValueOrDefault ( ) , ( dtA , dtB ) = > new { aData = dtA.Data , bData = dtB.Data } ) .ToList ( ) ; // Output : // null NULL // 2 two foreach ( var aC in c ) Console.WriteLine ( aC.aData + `` `` + aC.bData ) ; Console.WriteLine ( EqualityComparer < int ? > .Default.Equals ( a [ 0 ] .Id , b [ 0 ] .Id ) ) ; Console.WriteLine ( EqualityComparer < object > .Default.Equals ( a [ 0 ] .Id , b [ 0 ] .Id ) ) ; Console.WriteLine ( a [ 0 ] .Id.Equals ( b [ 0 ] .Id ) ) ; return 0 ; } }",LINQ Join on a Nullable key "C_sharp : I 've found that I ca n't distinguish controlled/cooperative from `` uncontrolled '' cancellation of Tasks/delegates without checking the source behind the specific Task or delegate.Specifically , I 've always assumed that when catching an OperationCanceledException thrown from a `` lower level operation '' that if the referenced token can not be matched to the token for the current operation , then it should be interpreted as a failure/error . This is a statement from the `` lower level operation '' that it gave up ( quit ) , but not because you asked it to do so.Unfortunately , TaskCompletionSource can not associate a CancellationToken as the reason for cancellation . So any Task not backed by the built in schedulers can not communicate the reason for its cancellation and could misreport cooperative cancellation as an error.UPDATE : As of .NET 4.6 TaskCompletionSource can associate a CancellationToken if the new overloads for SetCanceled or TrySetCanceled are used.For instance the followingwill result in `` ERROR : Unexpected cancellation '' even though the cancellation was requested through a cancellation token distributed to all the components.The core problem is that the TaskCompletionSource does not know about the CancellationToken , butif THE `` go to '' mechanism for wrapping asynchronous operations in Tasks ca n't track thisthen I do n't think one can count on it ever being tracked across interface ( library ) boundaries.In fact TaskCompletionSource CAN handle this , but the necessary TrySetCanceled overload is internalso only mscorlib components can use it.So does anyone have a pattern that communicates that a cancellation has been `` handled '' acrossTask and Delegate boundaries ? public Task ShouldHaveBeenAsynchronous ( Action userDelegate , CancellationToken ct ) { var tcs = new TaskCompletionSource < object > ( ) ; try { userDelegate ( ) ; tcs.SetResult ( null ) ; // Indicate completion } catch ( OperationCanceledException ex ) { if ( ex.CancellationToken == ct ) tcs.SetCanceled ( ) ; // Need to pass ct here , but ca n't else tcs.SetException ( ex ) ; } catch ( Exception ex ) { tcs.SetException ( ex ) ; } return tcs.Task ; } private void OtherSide ( ) { var cts = new CancellationTokenSource ( ) ; var ct = cts.Token ; cts.Cancel ( ) ; Task wrappedOperation = ShouldHaveBeenAsynchronous ( ( ) = > { ct.ThrowIfCancellationRequested ( ) ; } , ct ) ; try { wrappedOperation.Wait ( ) ; } catch ( AggregateException aex ) { foreach ( var ex in aex.InnerExceptions .OfType < OperationCanceledException > ( ) ) { if ( ex.CancellationToken == ct ) Console.WriteLine ( `` OK : Normal Cancellation '' ) ; else Console.WriteLine ( `` ERROR : Unexpected cancellation '' ) ; } } }",Can one detect uncontrolled cancellation from .NET library code ? "C_sharp : I 'm parsing a piece of hmtl into a word document using the following codeThe above code sample produces something like this : I 'd like to `` shrink '' the image to something like this : Can I do this if I know the `` parent '' container size ? Thanks //Need the following packages// < package id= '' DocumentFormat.OpenXml '' version= '' 2.7.2 '' targetFramework= '' net471 '' / > // < package id = `` HtmlToOpenXml.dll '' version= '' 2.0.1 '' targetFramework= '' net471 '' / > using System.Linq ; using DocumentFormat.OpenXml ; using DocumentFormat.OpenXml.Packaging ; using DocumentFormat.OpenXml.Wordprocessing ; using HtmlToOpenXml ; namespace ConsoleAppHtmlParse { class Program { static void Main ( string [ ] args ) { string fileName = @ '' C : \temp\myDoc.docx '' ; using ( WordprocessingDocument document = WordprocessingDocument.Create ( fileName , WordprocessingDocumentType.Document ) ) { document.AddMainDocumentPart ( ) ; document.MainDocumentPart.Document = new Document ( new Body ( ) ) ; HtmlConverter conveter = new HtmlConverter ( document.MainDocumentPart ) ; var compositeElements = conveter.Parse ( Html ) ; Paragraph p = compositeElements [ 0 ] as Paragraph ; p.ParagraphProperties = new ParagraphProperties ( ) ; p.ParagraphProperties.FrameProperties = new FrameProperties ( ) ; p.ParagraphProperties.FrameProperties.Width = new StringValue ( `` 3200 '' ) ; document.MainDocumentPart.Document.Body.Append ( compositeElements ) ; } } const string Html = `` < p > SomeText < img src=\ '' data : image/png ; base64 , iVBORw0KGgoAAAANSUhEUgAAAUAAAAApCAYAAABEHPCMAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwgAADsIBFShKgAAADktJREFUeF7tXftTFVcSvv/JbtX6QoygwIUgvhV8ElGCoMaYTXaT1Wh2f9jaVEzFxM1uahMVxGhABXkKijzE9RHFR6qSUkwEXzFuhIuKb9foRTegxvR2nzln5sw4wLlXiJF7vqqupqfP6e7TPd0zFxA9oKGhoRGi0ANQQ0MjZKEHoIaGRshCD0ANDY2QhR6AGhoaIQs9ADU0NEIWegBqaGiELPQA1NDQCFnoAaihoRGyMAfgzz//rKmXKFi42dKkKdSoN+EhB2dv+mBpXTZMKn4Dxha8qqmHiPJJeaX8BlJIXRNNmoLvn0DgOXuzBSaXLYK5u9+FN7/8GJZ8tRLeQtL8yTnlk/JK+aU8qxTRGH66Jpprvgjv/XmsfxYq90+g8Cw9mA1zdi+F9H3vwNTdf4ZJO5fA5F1vwWTOtRy8TPmcjXml/FKeHz16xNPeOWjNOwd0TbSs5alI6XVLIWPXO8r9Eyg8kza/Dml734aknYvR8WLNe4FTfinPP/30U5dPMdLRmiRdE801N7lq/wQDz+iiBejkTUj89yJGEznXcs/JlF/K88OHD7sdgLRmlK6JlrVsUpJi/wQDz6iil9HhQpiwYyHnf9JyL8iUZ9UBOLJwvpJNLWs5VGSV/gkGnoTCl2D8jjdgfC2S5r3GKc+qAzChQNdEc81lrtI/wcAzApttXO3rSH9kfOx2gz+JPHbrAhhdpb4+FGTKs+oAjN80z9XGk8i6Jlp+lmWV/gkGnvhNc2HM9j/AmJrXeoSPLl0C79YfhPL9iyGhUn1fX+eUZ+UBmD9HyaYq1zXR/FnnKv0TDDzP52fA6JpXe4RGlS6GpScvQgdZfngN6va/CSO2ua8NNaI8qw5AXZNepIo5EP3hFIj4cDaMcNP/AjRiPfmfAtGFr7jqNT1OKv3TFW7daYNzF69A49lmG3ni8tJhVPXvYWT1K8hf4TxwOaF0kdVoAg+vQl3dQojf1v3++NzJMPTvkyGq4GVX/dOSEwpSWFzeUrX1ncmUZ9UBGJs3W8lmd3JfrYkRVwrEbe18/UheN4vSIJ70x09DG0vEJdghrX+SeAKVd9xmAUDb1TKHfi54bTFzyk5HXfD++oKs0j9uuP/gIZxtaX1s8AnyePPSIKF6ASRUIQXLty2BpScu2BtNABtu36ElMKIbO7XSTdHVul+aZ1++y+LyNbnrVTnlWXUAejfqmnTO50PtLYrqHnzd6KZfACM2zYAVLUbdLFyC2hLUmwOwFWpd7fc+7zyvB8FnqOxoPw4rcud2ai8UuEr/OEHD7+T3La6DT5AnZmMqNsJ8iK+cHzxvOA7/5U5dgQX8Zzd2zJviymYmx+YkwpDlyRCTPwt5IoQjDVmdBs9XZkC0kJfPgli+X6yPykl2rLf8xG9K5vtInwzeLcL/PIjJ4vaKhb8UiFqdCJU3jbiaGx+3FwinPKsOwOgNuibuNUmGYcvXw5F2iuouHNmL+twMR9zzIKtVPLTE9S/gmxvfwo7zKDeeMt8Aa/OtuIZtmsf3Z0CUGQ/nORnczjzw4j0RjjHFlczienFe+z7LnryP9MlQ48irtU4MQBru/LrvErsCtw5YeStPwzxY8UUVi/1Itnwil/Jj1EPss+pk2svCt2RmR9QTzynrMQ9xuQ67Zh4c17vMR+BcpX+c6OzNb3RKBiP62kPNFl/5EiZ3HpLBn0TezotL8DV1v17IYp//Sokk401+md8AhPZG+GR5HbRwEeACVOXPsa1vvn2PaRhofc5spo/Lnwaf2N4KqIGmQ3Q5+S+Fr9mr0gWobLzAtAB34OYD/qXAg28hW/E8TpnyrDoAozbMCspHZ3Lfqcn/cIUDbYcc8W/m++ihNRGbNt2uxwHoJyXGUXXFisvfUgBe0pcflM7CcXM3DhnaX+ISEw7SytnY7LuhmV8h+FvWw/BiI5/enFw+tAn3wHfLOAXl1Z7/A3wA3sUBaFyPqz9hxNtxmt17z5e/CBF7G41rHM2N0yCmHNcXpzjyifAfhDjcR8NPPMwN4BnwIe8lv+Kh0HEKfchxtMJ2WY95MG3cOcTqF27mgYPVo+t82OqhKKv0jwz6np9z8AmyDcDhG2ZC3La5EIvEeMWcJ5JrfuARIHxN3a8Xstjnv1Jsk+H2ASZbTYw3HMqrrxo3r/9Skev61df5zX2rDn1lQCZ/K2i7VoJ6bK77JGHDffUiyiVw1PlZsQ1vHOk6nYXsqp7HKVOeVQfgsPUpSjZV5b5VE2tIHG1wj7/WeMUzgE0b9v54GJw5C7ykb+ADENF2oxTXi7eui1BThvoTpVDbchCyuT3xFtz8XRrK7jHFFu7jzW7kIbbFeEA04Z64bWlQzYeG4U8MdsornVuO3zrbkc8nQNgHE+BjMdDID60RA/H+t7Aa5WyW07tQX58BsU2tpMEzfw5ReJZYPEs20uqKF80YfC3kTwx5fFjl4b6Gk3zInmI2Yyv2WwOQZKGX0NJi1Y8NWRY/r0eX+SD7avefLKv0jwy3H3i4kYeajRx4KzARSAYPXrY3m/p+udnc5KwrRrKF7D13kcnww37X9V5RtPYTkFVRBPX8Y9PRBu5f7Mdm9FYUWzf2HbzRSM/isq43n7PH64y/O5nyrD4AZyjZVJX7Vk328+YS+9zixzc159t7ewOs2DhbauZWqGHrhR/ZXipE4tAchGQOIDyTMybhL+Y/Rtz+lhw2bAe9vwua6ALlYXMdj1f4s+ph5EWOXwweB2gw8fNlXTLiaWo04gvb08DOQ7a8fNDQWY7sIf0UGL4Z7Zsx4JDn/laL2l0qtOrScRL9kF7EwddLA9CHg8+I16V+7Ho3+WD27etVZJX+keE27ATZ3gAjc1+AmK3pSLMZj+ZcRY7KSYKBy8bCoGXjkMbC4DUzoeYOjwDha5oJz31k6QctS4KIYnd71k1R5CpbzWbIMWaz1bmujzkm3ehbrSdr/THuX+zHomdtLZIGnRwfFtlxPZD8yDLlWXUARuQmu9pQkft+TUQzY+PxfV3lY7voXIT/UoEUAzY3WydqzO2VzoDwZTuNhpXBziTHZPnLusqHpBP+AxBzXLxxCn/pUO3IixWvfDa0e42/Md/cA5Glhj/x/UMn2q4XM718XrJz+NAMiDoun9nwJ2pHb+fRIics76SXBibJtpyJeF3qx8/RZT7M/dZ6FVmlf2Q4h55MtgEYkTsdHaRB1Ja0gHnRdfaZxcLtL+CD3DHYgGNgAFLKri+g1fYXbO7DmVPu9syb4nKhq5zJfxor5Cip2dzWR35pPBnh/imjmcTHq8OpqE+FoafP0wVWlOithdKgk+OSb3j3uFU55Vl1AA7N0TXpvCbWG2D9N+5xD1+PD4G1Kaa8kr81wR1qdv4REpu5mumFH27va6HHIY36VWIvnilqiz0m06/P+Ojp9+XBsMfiEYPiPFQVkJwKVeyn2FLezPXWAKw/hrL5AxscZF8a5xFDsel0Mgy3+SGeAhEbUplcYxyCDbXMLVIMhca6FT7jXG3Xi9APH3D4Zr6K7BTs5Q8AzBHJ30g5M/1Z9aPYmP8S9E28y3wEx1X6R4Zz6MlkG4DP5UzDRKbC8HKkAHkVv8EDQfP3j9shLmz5Lxe4yqvMZjPk4d+LZttnX39xPfRfNhoqbhhy2/VCps/k33/y+9ahfh0cZq/v9+BoI/kvsG5sR3ziRmpqGI37EmFosV2vyinPqgPwuc90TTqvSaHVeLupJlMgQo67ZDp8TM19cyf0f4/0ll+fD/VSM1exfcIPDUCUefOK/ZUin3Smcimmc9wf8ys+Mp6HCvQn/A7Oncn09ntoHRzhNsy8mXbE9854LHjdHGQYz5BNeE0MxfZj8BH3Q/6GFKRCxJqdcJhySdf3HDPO6d9vs8NieE+84dKQJz+O+M/wHFCOSC/nTIpX1A9uYK5o3+518NHK6TCsm3xY51XnKv0jwzn0ZLINwCGfTcWAZ0Fk+UyDl3GuIKs0W+vxv7Lf2xK8+Zy7vWpeoLbrBa7ySp5sIUeKG9Vfx2Sz2Tp4URDUaHK8q0TBGKjRhH/RVNgkzc746ngxCbinwalXkynPqgMwfN0UJZtuckjUpOEkfzMitEK1nA/zrckOn8+px33MnvBDvg074pyENn+rsR7PFIkD0IxJ2CO/zL98nxgw81Jm7SP40CbB0nM7pg2eB8d5fD6+znZ+AxSPHDfD/ZOwSrJv14vzG3pbHfCsxlpaI/vjspRve/0Q+Ha/stt8WPtVZZX+kdHVD0FsA3DwuskQUYavzoI2z1CWC29JVVXCffjujLr9QGTxpPZfznfVP22Z8qw6AAevneRqQ0XWNdFyX5RV+keG8q/BhK2bBEPLZsDQzS8gcf4MypXm91XyesReT8uUZ9UBGLY2qUd8Pm35114TLT87skr/OKH0i9CDPk2EIaXJSNOfaV7JX+/91/Jc9U+bU55VB+CgTye62njW+K+9Jpo/O1ylf5xQ+qdwAz+dAOGl0yC8BEnzXuOUZ9UBOHCNronmmstcpX/c0O0fQxiwZjwMLpkKYcVTIKwECbmWe16mPKsOwP7Z43rEp5a13Fdklf7pCp3+Oax+2GyDiidr6mWiPKsOQF0TTZrspNI/wcATvjYRBhYmwYCiJBiIpHkvcMwv5Vl1AA7WNdFcc4sr9k8w8Ly2/W3ov3EC9C+ciJTI+IAig2u5Z2TKL+VZdQC+WvM3XRMta5nL/TaMV+qfYOA51noKBnwyFn6TmQD98sfD7wrGQ7+CCZr3BMd8Ul4pv5Rn1f8YXddEc82R54+D32aOxF4Yo9Q/wcDz4MEDOHH+DPyl7EMY+a908P5jpqYeIson5ZXyS3l+9Mj2j3BdQWt0TTRpCq5/AoVHNFxHRwe0t7fDjz/+qKmHiPJJeRXFU3l60RpdE02aguufwADwf8lkaQ0EsRMIAAAAAElFTkSuQmCC\ '' alt=\ '' Screenshot_3\ '' / > moretext < /p > '' ; } }",OpenXml Force image fit in parent container "C_sharp : I just noticed that the following is possible in C # written in Visual Studio 2015 , but I 've never seen it before : My expectation was for Foo to have to be implemented like this : Note that there is no need to call new Y.Is this new in C # 6 ? I have n't seen any mention of this in the release notes , so maybe it 's always been there ? public class X { public int A { get ; set ; } public Y B { get ; set ; } } public class Y { public int C { get ; set ; } } public void Foo ( ) { var x = new X { A = 1 , B = { C = 3 } } ; } public void Foo ( ) { var x = new X { A = 1 , B = new Y { C = 3 } } ; }",New C # 6 object initializer syntax ? "C_sharp : I 'm using the .NET version of BouncyCastle , and I have to save a private RSA key to file , obviously encrypted with a password for security reasons.What I 'm trying right now is this : But BouncyCastle is thwrowing a NullReferenceException on the last instruction . Since the method is totally undocumented > : ( I wonder if any of you know how to use it correctly ... ( none of my parameters are NULL by the way , already checked that ) Dim rand As New SecureRandom Dim arr As Byte ( ) = New Byte ( 7 ) { } rand.NextBytes ( arr ) Dim privateKeyInfo As EncryptedPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo ( `` PBEwithHmacSHA-256 '' , Repository.Password.ToCharArray , arr , 1 , data.BouncyCastlePrivateKey )",Encrypting a private key with BouncyCastle "C_sharp : Consider this simple program which compiles fine in Visual Studio 2015 : ... which outputs as expected : However , Visual Studio 2015 keeps suggesting a `` Quick Action '' on this line specifically : It insists that the ( int ) `` cast is redundant '' , and suggests as a potential fix to `` Remove Unnecessary Cast '' , which of course is wrong , as it would change the result.Interestingly , it does n't give me any warning for the equivalent statement : Can someone provide a reasonable explanation for this false-positive when using an expression in an interpolated string ? public class Program { enum Direction { Up , Down , Left , Right } static void Main ( string [ ] args ) { // Old style Console.WriteLine ( string.Format ( `` The direction is { 0 } '' , Direction.Right ) ) ; Console.WriteLine ( string.Format ( `` The direction is { 0 } '' , ( int ) Direction.Right ) ) ; // New style Console.WriteLine ( $ '' The direction is { Direction.Right } '' ) ; Console.WriteLine ( $ '' The direction is { ( int ) Direction.Right } '' ) ; } } The direction is RightThe direction is 3The direction is RightThe direction is 3 // `` Cast is redundant '' warningConsole.WriteLine ( $ '' The direction is { ( int ) Direction.Right } '' ) ; // No warnings.Console.WriteLine ( string.Format ( `` The direction is { 0 } '' , ( int ) Direction.Right ) ) ;",Visual Studio 2015 : Invalid `` Cast is redundant '' warning in interpolated string expression "C_sharp : In a DbSet entity collection of Entity Framework ( 6.1.3 ) , when I add a new item , it is not returned from the collection afterwards . This is strange and unexpected . Here 's some gathered sample code : How can this be ? When I query dbContext.Entities in the immediate window in Visual Studio , it says something like `` Local : Count = 4 '' . Why does it hide the new item from me ? Update : If this collection does n't do the obvious thing – returning what was added before – what do I need to do instead ? It must return all records from the database when called first , and it must also include all changes ( add and remove ) when called later . SaveChanges is only called when the user has finished editing things . The collection is needed before that ! SaveChanges might also be called somewhere in between when the user is finished editing , but the code might return and the view be displayed again at a later time . dbContext.Entities.ToArray ( ) ; // contains 3 entriesdbContext.Entities.Add ( new Entity ( ) ) ; dbContext.Entities.ToArray ( ) ; // still contains 3 entries",DbSet : missing added item "C_sharp : I 'm trying to dynamically construct an expression similar to the one below , where I can use the same comparison function , but where the values being compared can be passed in , since the value is passed from a property 'higher-up ' in the query.I believe I 've constructed the query correctly , but the ExpressionExpander.VisitMethodCall ( .. ) method throws the following exception when I try to use it : `` Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN ' to type 'System.Linq.Expressions.LambdaExpression ' '' In real-world code , using Entity Framework and actual IQueryable < T > , I often get : `` Unable to cast object of type 'System.Linq.Expressions.MethodCallExpressionN ' to type 'System.Linq.Expressions.LambdaExpression ' '' as well.I 've constructed a LinqPad-friendly example of my problem , as simple as I could make it.If I 'm doing something obviously wrong , I 'd really appreciate a nudge in the right direction ! Thanks.Edit : I know that the following would work : However , I 'm trying to separate the comparison from the location of the parameters , since the comparison could be complex and I would like to re-use it for many different queries ( each with different locations for the two parameters ) . It is also intended that one of the parameters ( in the example , the 'min length ' ) would actually be calculated via another expression.Edit : Sorry , I 've just realised that some answers will work when attempted against my example code since my example is merely masquerading as an IQueryable < T > but is still a List < T > underneath . The reason I 'm using LinqKit in the first place is because an actual IQueryable < T > from an EntityFramework DbContext will invoke Linq-to-SQL and so must be able to be parsed by Linq-to-SQL itself . LinqKit enables this by expanding everything to expressions.Solution ! Thanks to Jean 's answer below , I think I 've realised where I 'm going wrong.If a value has come from somewhere in the query ( i.e . not a value that is known before-hand . ) then you must build the reference/expression/variable to it into the expression.In my original example , I was trying to pass the 'minLength ' value taken from within the expression and pass it to a method . That method call could not be done before-hand , since it used a value from the expression , and it could not be done within the expression , since you ca n't build an expression within an expression.So , how to get around this ? I chose to write my expressions so that they can be invoked with the additional parameters . Though this has the downside that the parameters are no longer 'named ' and I could end up with an Expression < Func < int , int , int , int , bool > > or something down the line . var people = People .Where ( p = > p.Cars .Any ( c = > c.Colour == p.FavouriteColour ) ) ; void Main ( ) { var tuples = new List < Tuple < String , int > > ( ) { new Tuple < String , int > ( `` Hello '' , 4 ) , new Tuple < String , int > ( `` World '' , 2 ) , new Tuple < String , int > ( `` Cheese '' , 20 ) } ; var queryableTuples = tuples.AsQueryable ( ) ; // For this example , I want to check which of these strings are longer than their accompanying number . // The expression I want to build needs to use one of the values of the item ( the int ) in order to construct the expression . // Basically just want to construct this : // .Where ( x = > x.Item1.Length > x.Item2 ) var expressionToCheckTuple = BuildExpressionToCheckTuple ( ) ; var result = queryableTuples .AsExpandable ( ) .Where ( t = > expressionToCheckTuple.Invoke ( t ) ) .ToList ( ) ; } public Expression < Func < string , bool > > BuildExpressionToCheckStringLength ( int minLength ) { return str = > str.Length > minLength ; } public Expression < Func < Tuple < string , int > , bool > > BuildExpressionToCheckTuple ( ) { // I 'm passed something ( eg . Tuple ) that contains : // * a value that I need to construct the expression ( eg . the 'min length ' ) // * the value that I will need to invoke the expression ( eg . the string ) return tuple = > BuildExpressionToCheckStringLength ( tuple.Item2 /* the length */ ) .Invoke ( tuple.Item1 /* string */ ) ; } Expression < Func < Tuple < string , int > , bool > > expr = x = > x.Item1.Length > x.Item2 ; var result = queryableTuples .AsExpandable ( ) .Where ( t = > expr.Invoke ( t ) ) .ToList ( ) ; // New signature.public Expression < Func < string , int , bool > > BuildExpressionToCheckStringLength ( ) { // Now takes two parameters . return ( str , minLength ) = > str.Length > minLength ; } public Expression < Func < Tuple < string , int > , bool > > BuildExpressionToCheckTuple ( ) { // Construct the expression before-hand . var expression = BuildExpressionToCheckStringLength ( ) ; // Invoke the expression using both values . return tuple = > expression.Invoke ( tuple.Item1 /* string */ , tuple.Item2 /* the length */ ) ; }",Trying to use parent property as parameter in child collection expression ; LinqKit throws `` Unable to cast MethodCallExpressionN to LambdaExpression '' "C_sharp : I had trouble coming up with a good way to word this question , so let me try to explain by example : Suppose I have some interface . For simplicity 's sake , I 'll say the interface is IRunnable , and it provides a single method , Run . ( This is not real ; it 's only an example . ) Now , suppose I have some pre-existing class , let 's call it Cheetah , that I ca n't change . It existed before IRunnable ; I ca n't make it implement my interface . But I want to use it as if it implements IRunnable -- presumably because it has a Run method , or something like it . In other words , I want to be able to have code that expects an IRunnable and will work with a Cheetah.OK , so I could always write a CheetahWrapper sort of deal . But humor me and let me write something a little more flexible -- how about a RunnableAdapter ? I envision the class definition as something like this : Straightforward enough , right ? So with this , I should be able to make a call like this : And now , voila : I have an object that implements IRunner and is , in its heart of hearts , a Cheetah.My question is : if this Cheetah of mine falls out of scope at some point , and gets to the point where it would normally be garbage collected ... will it ? Or does this RunnableAdapter object 's Runner property constitute a reference to the original Cheetah , so that it wo n't be collected ? I certainly want that reference to stay valid , so basically I 'm wondering if the above class definition is enough or if it would be necessary to maintain a reference to the underlying object ( like via some private UnderlyingObject property ) , just to prevent garbage collection . public class RunnableAdapter : IRunnable { public delegate void RunMethod ( ) ; private RunMethod Runner { get ; set ; } public RunnableAdapter ( RunMethod runner ) { this.Runner = runner ; } public void Run ( ) { Runner.Invoke ( ) ; } } Cheetah c = new Cheetah ( ) ; RunnableAdapter ra = new RunnableAdapter ( c.Run ) ;",Does a reference to a delegate constitute a reference to an object ( to prevent garbage collection ) ? "C_sharp : How do I pass in an enum inside a message action ? for instance , XAML : ViewModel : < UserControl.ContextMenu > < ContextMenu StaysOpen= '' True '' > < MenuItem Header= '' Arrow '' cal : Message.Attach= '' ChangeArrowType ( LogicArrowEnum.ARROW ) '' / > ... . public void ChangeArrowType ( LogicArrowEnum arrowType ) { MessageBox.Show ( arrowType ) ; //arrowType is empty ! } public enum LogicArrowEnum { ARROW = 1 , ASSIGN = 2 , IF = 3 , IF_ELSE = 4 }",Passing an enum as an argument in caliburn micro 's action "C_sharp : I am attempting to create a standard method to handle populating a view model based on stored values in a cookie , that are used as user defaults for search criteria.I am having issues when it comes to converting the string cookie values to the property type so the view model can be updated appropriately . Getting the following error : Here is what I have : Invalid cast from 'System.String ' to 'System.Reflection.RuntimePropertyInfo ' . public TViewModel GetUserSearchCriteriaDefaults < TViewModel > ( TViewModel viewModel ) where TViewModel : class { Type type = viewModel.GetType ( ) ; string className = viewModel.GetType ( ) .Name ; PropertyInfo [ ] properties = type.GetProperties ( ) ; if ( Request.Cookies [ className ] ! = null ) { string rawValue ; foreach ( PropertyInfo property in properties ) { if ( ! String.IsNullOrEmpty ( Request.Cookies [ className ] [ property.Name ] ) ) { rawValue = Server.HtmlEncode ( Request.Cookies [ className ] [ property.Name ] ) ; Type propertyType = property.GetType ( ) ; var convertedValue = Convert.ChangeType ( rawValue , propertyType ) ; < -- -- Error from this line property.SetValue ( viewModel , convertedValue ) ; } } } return viewModel ; }","Convert String to Type , where Type is a variable" "C_sharp : When in Linq To SQL I use user defined function like thisthe resulting query always contains varchar ( 8000 ) as a parameter type.So I have to change the parameter type of function to avoid SQL Server error.Can I force Linq To SQL not to ignore length that I pass ? P.S . There is the same issue with nvarchar ( 4000 ) . [ Function ( Name = `` udf_find_a '' , IsComposable = true ) ] public IQueryable < A > FindA ( [ Parameter ( DbType = `` varchar ( 100 ) '' ) ] string keywords ) { return CreateMethodCallQuery < A > ( this , ( ( MethodInfo ) ( MethodBase.GetCurrentMethod ( ) ) ) , keywords ) ; }",How can I force varchar length in Linq To SQL "C_sharp : I have the following situation : I want to mutualy exclude access to an object.So far I normaly would use a lock objectNow I have also a method which can be called from another thread . It should not be blocked for unknown time , instead it should give an answer in a defined time.In this case i would use a monitor , likeNow my question is : can lock and monitor be mixed in such a way if the lockobject is the same and mutually exclude each other , or would it be needed to change every lock to a monitor.So would both times the same token be `` locked '' , or would the monitor create another token for the object then the lock ? At a glimpse I can not see that the aplication runs in code of both at the same time . But I do n't know if any timing issues can exist , where CODE1 and CODE2 are executed in parallel . object lockObject = new object ( ) ; ... method1 : lock ( lockObject ) { CODE1 } method2 : try { Monitor.TryEnter ( lockObject , 20000 , ref lockTaken ) ; if ( lockTaken ) { CODE2 } } catch ( ... ) { ... } finally { if ( lockTaken ) Monitor.Exit ( timerLock ) ; }",Can lock and monitor be used on same object safely ? "C_sharp : In C # 7 you can have named tuples : If I pass this to a MVC model using : Then what syntax should be used in the cshtml file to declare the model ? Although this does n't work , something like ... var foo = ( Name : `` Joe '' , Age : 42 ) ; return View ( foo ) ; @ model ( string Name , int Age ) ;",Can a C # named Tuple be used as an MVC page model type ? C_sharp : Here is a sample code of using the SqlDataReader : EDIT : I mean I want to understand whether there is the same mechanism when retrieving data from database in a while-loop ( in case of SqlDataReader ) as it does when working with the SQLite . // Working with SQLServer and C # // Retrieve all rowscmd.CommandText = `` SELECT some_field FROM data '' ; using ( var reader = cmd.ExecuteReader ( ) ) { while ( reader.Read ( ) ) { Console.WriteLine ( reader.GetString ( 0 ) ) ; } } // working with SQLite and Javaif ( cursor.moveToFirst ( ) ) { do { String data = cursor.getString ( cursor.getColumnIndex ( `` data '' ) ) ; // do what ever you want here } while ( cursor.moveToNext ( ) ) ; } cursor.close ( ) ;,"Does a .NET SqlDataReader object use a database cursor , or the whole result set is loaded into RAM ?" "C_sharp : This is my first time using StackOverflow myself . I have found many answers to many of my question here before , and so I thought I would try asking something myself.I 'm working on a small project and I am a bit stuck right now . I know ways to solve my problem - just not the way I want it to be solved.The project includes an NBT parser which I have decided to write myself since it will be used for a more or less custom variation of NBT files , though the core principle is the same : a stream of binary data with predefined `` keywords '' for specific kinds of tags . I have decided to try and make one class only for all the different types of tags since the structure of the tags are very similar - they all contain a type and a payload . And this is where I am stuck . I want the payload to have a specific type that , when an explicit conversion is done implicitly , throws an error.The best I could come up with is to make the payload of type Object or dynamic but that will allow all conversions done implicitly : Is there any way of doing this ? I would like to solve it by somehow telling C # that from now on , even though Payload is dynamic , it will throw an exception if the assigned value can not be implicitly converted to the type of the current value - unless , of course , it is done explicitly.I am open to other ways of accomplishing this , but I would like to avoid something like this : Int64 L = 90000 ; Int16 S = 90 ; dynamic Payload ; // Whatever is assigned to this next will be acceptedPayload = L ; // This finePayload = S ; // Still fine , a short can be implicitly converted to a longPayload = `` test '' ; // I want it to throw an exception here because the value assigned to Payload can not be implicitly cast to Int64 ( explicit casting is ok ) public dynamic Payload { set { if ( value is ... & & Payload is ... ) { // Using value.GetType ( ) and Payload.GetType ( ) does n't make any difference for me , it 's still ugly ... // this is ok } else if ( ... ) { ... // this is not ok , throw an exception } ... ... ... } }",C # : run-time datatype conversion "C_sharp : Consider the following : Is there any way that FindBoxBySize ( ) can be compacted using LINQ ? Also : comments on my code are welcome . I do n't do much recursion , so I might have missed something in my implementation . public class Box { public BoxSize Size { get ; set ; } public IEnumerable < Box > Contents { get ; set ; } } Box FindBoxBySize ( Box box , BoxSize size ) { Box _foundBox = null ; Action < IEnumerable < Box > > _recurse = null ; _recurse = new Action < IEnumerable < Box > > ( boxes = > { foreach ( var _box in boxes ) { if ( _box.Size == size ) { _foundBox = _box ; return ; } if ( _box.Contents ! = null ) _recurse ( _box.Contents ) ; } } ) ; _recurse ( box.Contents ) ; return _foundBox ; }",LINQ and recursion "C_sharp : Why ca n't an int that 's been boxed be directly cast to double ? That throw an invalid cast exception . Instead it seems it has to first be cast as an int , and then on to double . I 'm sure the simple answer is `` because that 's how boxing works '' but I 'm hoping someone might shed a bit of light here . object o = 12 ; double d = ( double ) o ; object o = 12 ; double d = ( double ) ( int ) o ;",Casting a boxed value "C_sharp : Recently I was studying the operating system , and came across this question . Is the thread created in C # user level or kernel level , like : As far as I know , the process with cpu-intensive thread on kernel level could run faster than those on user level . Because the book Modern operating system says `` The schedule of user-level thread will not trap into kernel , that 's why they are more lightweight compared with kernl-level thread '' .So I think user-level thread could not run on different cpu , which requires trapping into kernel.And in linux , the thread created by pthread_create is kernel level . So I 'm curious about the feature of .Net C # . Thread mythread=new Thread ( ThreadStart ( something ) ) ;",Is the thread created in C # user level or kernel level ? "C_sharp : I am using a LINQ statement that selects from various tables information I need to fill some Post / Post Comment style records . I 'm getting a funny exception saying that the object must implement IConvertible when I try to iterate the record set . The funny part about it is that it seems to only occur when the anonymous type I 'm using to hold the data contains more than 2 generic collections . ( Note : I am using MYSQL Connector/Net so things like Take and FirstOrDefault and things like that are not supported within the LINQ statements themselves , I have opted to use those methods during iteration as it does not raise an exception there ) The problem is , when all 3 fields ( Game , Recipient , and Comments ) are present . I get the exception `` Object must implement IConvertible '' . BUT if I remove ANY one of the 3 field assignments ( does n't matter which one ) , it works just fine . Anybody know what 's going on here ? Thanks in advance ! Ryan . //select friend timeline posts postsvar pquery = from friend in fquery join post in db.game_timeline on friend.id equals post.user_id //join user in db.users on post.friend_id equals user.id into userGroup //join game in db.games on post.game_id equals game.game_id into gameGroup select new { Friend = friend , Post = post , Game = from game in db.games where game.game_id == post.game_id select game , Recipient = from user in db.users where user.id == post.user_id select user , Comments = from comment in db.timeline_comments where comment.post_id == post.id join users in db.users on comment.user_id equals users.id select new { User = users , Comment = comment } } ;",Strange LINQ To Entities Exception "C_sharp : I 'm rewriting some of my extension methods using the new Span < T > type and I 'm having trouble finding a way to properly pin a generic instance to be able to use parallel code to work on it.As an example , consider this extension method : Here I just want to fill an input Span < T > using some values provider , and since these vectors could be quite large I 'd like to populate them in parallel . This is just an example , so even if using parallel code here is n't 100 % necessary , the question still stands , as I 'd need to use parallel code again sooner or later anyways.Now , this code does work , but since I 'm never actually pinning the input span and given the fact that it could very well be pointing to some managed T [ ] vector , which can be moved around all the time by the GC , I think I might have just been lucky to see it working fine in my tests.So , my question is : Is there any way to pin a generic Span < T > instance and get a simple void* pointer to it , so that I can pass it around in closures to work on the Span < T > instance in parallel code ? Thanks ! public static unsafe void Fill < T > ( this Span < T > span , [ NotNull ] Func < T > provider ) where T : struct { int cores = Environment.ProcessorCount , batch = span.Length / cores , mod = span.Length % cores , sizeT = Unsafe.SizeOf < T > ( ) ; //fixed ( void* p0 = & span.DangerousGetPinnableReference ( ) ) // This does n't work , ca n't pin a T object void* p0 = Unsafe.AsPointer ( ref span.DangerousGetPinnableReference ( ) ) ; { byte* p = ( byte* ) p0 ; // Local copy for the closure Parallel.For ( 0 , cores , i = > { byte* start = p + i * batch * sizeT ; for ( int j = 0 ; j < batch ; j++ ) Unsafe.Write ( start + sizeT * j , provider ( ) ) ; } ) ; // Remaining values if ( mod == 0 ) return ; for ( int i = span.Length - mod ; i < span.Length ; i++ ) span [ i ] = provider ( ) ; } }",How to pin a generic Span < T > instance to work on it with Parallel.For ? C_sharp : Where should I create an instance ? which way is better and why ? 1 ) In the constructor ? 2 ) as a private class member ? public class UserController : Controller { private UnitOfWork unitofwork ; public UserController ( ) { unitofwork = new UnitofWork ( ) ; } public ActionResult DoStuff ( ) { ... public class UserController : Controller { private UnitOfWork unitofwork = new UnitofWork ( ) ; public ActionResult DoStuff ( ) { ...,"Asp.net MVC4 , C # Create object instance" "C_sharp : Normally , one would expect , and hope , that two casts are needed to first unbox a value type and then perform some kind of value type conversion into another value type . Here 's an example where this holds : As you can see from my smileys , I 'm happy that these conversions will fail if I use only one cast . After all , it 's probably a coding mistake to try to unbox a value type into a different value type in one operation . ( There 's nothing special with the IFormattable interface ; you could also use the object class if you prefer . ) However , today I realized that this is different with enums ( when ( and only when ) the enums have the same underlying type ) . Here 's an example : I think this behavior is unfortunate . It should really be compulsory to say ( DateTimeKind ) ( DayOfWeek ) box . Reading the C # specification , I see no justification of this difference between numeric conversions and enum conversions . It feels like the type safety is lost in this situation.Do you think this is `` unspecified behavior '' that could be improved ( without spec changes ) in a future .NET version ? It would be a breaking change.Also , if the supplier of either of the enum types ( either DayOfWeek or DateTimeKind in my example ) decides to change the underlying type of one of the enum types from int to something else ( could be long , short , ... ) , then all of a sudden the above one-cast code would stop working , which seems silly.Of course , the enums DayOfWeek and DateTimeKind are not special . These could be any enum types , including user-defined ones.Somewhat related : Why does unboxing enums yield odd results ? ( unboxes an int directly into an enum ) ADDITION : OK , so many answers and comments have focused on how enums are treated `` under the hood '' . While this is interesting in itself , I want to concentrate more on whether the observed behavior is covered by the C # specification.Suppose I wrote the type : and then said : then , does the C # spec say anything about whether this will succeed at runtime ? For all I care , .NET might treat a YellowInteger as just an Int32 with different type metadata ( or whatever it 's called ) , but can anyone guarantee that .NET does not `` confuse '' a YellowInteger and an Int32 when unboxing ? So where in the C # spec can I see if ( int ) box will succeed ( calling my explicit operator method ) ? // create boxed int IFormattable box = 42 ; // box.GetType ( ) == typeof ( int ) // unbox and narrow short x1 = ( short ) box ; // fails runtime : - ) short x2 = ( short ) ( int ) box ; // OK // unbox and make unsigned uint y1 = ( uint ) box ; // fails runtime : - ) uint y2 = ( uint ) ( int ) box ; // OK // unbox and widen long z1 = ( long ) box ; // fails runtime : - ) long z2 = ( long ) ( int ) box ; // OK ( cast to long could be made implicit ) // create boxed DayOfWeek IFormattable box = DayOfWeek.Monday ; // box.GetType ( ) == typeof ( DayOfWeek ) // unbox and convert to other // enum type in one cast DateTimeKind dtk = ( DateTimeKind ) box ; // succeeds runtime : - ( Console.WriteLine ( box ) ; // writes Monday Console.WriteLine ( dtk ) ; // writes Utc struct YellowInteger { public readonly int Value ; public YellowInteger ( int value ) { Value = value ; } // Clearly a yellow integer is completely different // from an integer without any particular color , // so it is important that this conversion is // explicit public static explicit operator int ( YellowInteger yi ) { return yi.Value ; } } object box = new YellowInteger ( 1 ) ; int x = ( int ) box ;","In C # , why can a single cast perform both an unboxing and an enum conversion ?" "C_sharp : I 'm getting System.OutOfMemoryException when trying to generate 6 letter permutations . 5 letter permutations still work.Here is the code I 'm using to generate ALL permutations : after which I am using this piece of code to filter them based on regex : so since I do n't really need ALL those permutations , is there a way to regex filter while generating permutations , or should I use a more efficient piece of code to generate permutations ? Here is a picture to better demonstrate what I 'm trying to achieve : The vertical alphabet string is the one I 'm telling the code to use . private static List < string > getPermutations ( int n , string source ) { IEnumerable < string > q = source.Select ( x = > x.ToString ( ) ) ; for ( int i = 0 ; i < n - 1 ; i++ ) { q = q.SelectMany ( x = > source , ( x , y ) = > x + y ) ; } return q.ToList ( ) ; // THIS IS WHERE THE ERROR HAPPENS } private static List < string > filterListByRegex ( List < string > list , string regex ) { List < string > newList = list.ToList ( ) ; for ( int i = newList.Count - 1 ; i > = 0 ; i -- ) { Match match = Regex.Match ( `` '' +newList [ i ] , regex , RegexOptions.IgnoreCase ) ; if ( ! match.Success ) { newList.RemoveAt ( i ) ; } } return newList ; }",System.OutOfMemoryException when generating permutations C_sharp : I am wondering why the output of the given code ( execute it in LinqPad ) is always : I have naively expected it to be True in both cases . void Main ( ) { Compare1 ( ( Action ) Main ) .Dump ( ) ; Compare2 ( Main ) .Dump ( ) ; } bool Compare1 ( Delegate x ) { return x == ( Action ) Main ; } bool Compare2 ( Action x ) { return x == Main ; } False True,Implicit method group conversion gotcha "C_sharp : I 've got this code which fails : When Stuff/Stuff2 has the same value I get this exception : An item with the same key has already been added.If they have different values everything works . I use AutoMapper 2.2.0.Have I done something wrong or is it a bug ? How can I solve it ? internal class Program { private static void Main ( ) { Mapper.CreateMap < SourceFoo , TargetFoo > ( ) ; Mapper.CreateMap < string , Stuff > ( ) .ForMember ( dest = > dest.Value , opt = > opt.MapFrom ( src = > src ) ) .ForMember ( dest = > dest.IgnoreMe , opt = > opt.Ignore ( ) ) ; var source = new SourceFoo { Stuff = `` a '' , Stuff2 = `` a '' } ; var target = new TargetFoo { Stuff = new Stuff ( ) , Stuff2 = new Stuff ( ) } ; Mapper.Map ( source , target ) ; Console.WriteLine ( target.Stuff.Value ) ; Console.WriteLine ( target.Stuff2.Value ) ; Console.ReadLine ( ) ; } } public class SourceFoo { public string Stuff { get ; set ; } public string Stuff2 { get ; set ; } } public class TargetFoo { public Stuff Stuff { get ; set ; } public Stuff Stuff2 { get ; set ; } } public class Stuff { public string Value { get ; set ; } public bool IgnoreMe { get ; set ; } }",Error when mapping same value with AutoMapper "C_sharp : At work , we 're using EFCore on our data layer and graphql-dotnet to manage APIs requests , I 'm having a problem updating some of our big objects using GraphQL mutations . When the user sends a partial update on the model , we would like to update on our database only the fields that actually were changed by the mutation . The problem we 're having is that as we directly map the input to the entity , wheather some field was purposefully passed as null , or the field was not specified on the mutation at all , we get the property value as null . This way we ca n't send the changes to the database otherwise we would incorrectly update a bunch of fields to null.So , we need a way to identify which fields are sent in a mutation and only update those . In JS this is achieved by checking if the property value is undefined , if the value is null we know that it was passed as null on purpose.Some workarounds we 've been thinking were using reflection on a Dictionary to update only the specified fields . But we would need to spread reflection to every single mutation . Another solution was to have a isChanged property to every nullable property on our model and change ir on the refered property setter , but ... cmon ... I 'm providing some code as example of this situation bellow : Human class : GraphQL Type : Input Type : Human Mutation : public class Human { public Id { get ; set ; } public string Name { get ; set ; } public string HomePlanet { get ; set ; } } public class HumanType : ObjectGraphType < Human > { public HumanType ( ) { Name = `` Human '' ; Field ( h = > h.Id ) .Description ( `` The id of the human . `` ) ; Field ( h = > h.Name , nullable : true ) .Description ( `` The name of the human . `` ) ; Field ( h = > h.HomePlanet , nullable : true ) .Description ( `` The home planet of the human . `` ) ; } } public class HumanInputType : InputObjectGraphType { public HumanInputType ( ) { Name = `` HumanInput '' ; Field < NonNullGraphType < StringGraphType > > ( `` name '' ) ; //The problematic field Field < StringGraphType > ( `` homePlanet '' ) ; } } /// Example JSON request for an update mutation without HomePlanet /// { /// `` query '' : `` mutation ( $ human : HumanInput ! ) { createHuman ( human : $ human ) { id name } } '' , /// `` variables '' : { /// `` human '' : { /// `` name '' : `` Boba Fett '' /// } /// } /// } ///public class StarWarsMutation : ObjectGraphType < object > { public StarWarsMutation ( StarWarsRepository data ) { Name = `` Mutation '' ; Field < HumanType > ( `` createOrUpdateHuman '' , arguments : new QueryArguments ( new QueryArgument < NonNullGraphType < HumanInputType > > { Name = `` human '' } ) , resolve : context = > { //After conversion human.HomePlanet is null . But it was not informed , we should keep what is on the database at the moment var human = context.GetArgument < Human > ( `` human '' ) ; //On EFCore the Update method is equivalent to an InsertOrUpdate method return data.Update ( human ) ; } ) ; } }",Null fields on a partial update mutation on GraphQL .NET "C_sharp : I 'd like to write a simple unit of work class that would behave like this : This is what I have so far ( any comments will be welcome if you think my design is wrong ) : What I would like to do is to roll back the transaction in case the data acess code threw some exception . So the Dispose ( ) method would look something like : Does it make sense ? And if so , how can it be done ? using ( var unitOfWork = new UnitOfWork ( ) ) { // Call the data access module and do n't worry about transactions . // Let the Unit of Work open a session , begin a transaction and then commit it . } class UnitOfWork : IDisposable { ISession _session ; ITransation _transaction ; . . . void Dispose ( ) { _transaction.Commit ( ) ; _session.Dispose ( ) ; } } void Dispose ( ) { if ( Dispose was called because an exception was thrown ) { _transaction.Commit ( ) ; } else { _transaction.RollBack ( ) ; } _session.Dispose ( ) ; }",How can Dispose ( ) know it was called because of an exception ? "C_sharp : I was troubleshooting a ( de ) serialization issue with the following class using Json.Net : The problem is that the constructor argument `` withdrawDate '' is named differently than the property name `` WithDrawlDate '' . Making the names match ( even ignoring case ) fixed the issue.However , I wanted to understand this a little better , so I reverted the code and tested after making both the setters public . This also fixed the problem.Finally , I switched from auto-properties to properties with backing fields so that I could fully debug and see what was actually going on : I tried this with and without a default constructor ( code shown omits the default constructor ) .With the default constructor : default constructor is called , then both property setters are called.Without the default constructor : non-default constructor is called , then WithDrawlDate setter is called . NumberOfCoinsByType setter is never called.My best guess is that the deserializer is keeping track of which properties can be set via the constructor ( by some convention , since casing seems to be ignored ) , and then uses property setters where possible to fill in the gaps.Is this the way it works ? Are the order of operations/rules for deserialization documented somewhere ? public class CoinsWithdrawn { public DateTimeOffset WithdrawlDate { get ; private set ; } public Dictionary < CoinType , int > NumberOfCoinsByType { get ; private set ; } public CoinsWithdrawn ( DateTimeOffset withdrawDate , Dictionary < CoinType , int > numberOfCoinsByType ) { WithdrawlDate = withdrawDate ; NumberOfCoinsByType = numberOfCoinsByType ; } } public class CoinsWithdrawn { private DateTimeOffset _withdrawlDate ; private Dictionary < CoinType , int > _numberOfCoinsByType ; public DateTimeOffset WithdrawlDate { get { return _withdrawlDate ; } set { _withdrawlDate = value ; } } public Dictionary < CoinType , int > NumberOfCoinsByType { get { return _numberOfCoinsByType ; } set { _numberOfCoinsByType = value ; } } public CoinsWithdrawn ( DateTimeOffset withdrawDate , Dictionary < CoinType , int > numberOfCoinsByType ) { WithdrawlDate = withdrawDate ; NumberOfCoinsByType = numberOfCoinsByType ; } }",Json.Net Deserialization Constructor vs. Property Rules "C_sharp : I 'm in c # for quite a long time , but I never got this kind of error . First of all , do you see anything wrong ( possibly wrong ) about this single code block ( except it 's logic of course , I know it always return 0 ) ? Release project settings : DEBUG constant = false ; TRACE constant = true ; Optimize Code = true ; Output/Advanced/Debug info = none ; IIS = version 7.5This method , having specified release settings throws `` System.AccessViolationException : Attempted to read or write protected memory . This is often an indication that other memory is corrupt . `` And here is the funny part . These are cases , when it does not throw this exception : Run it on IIS ( Express and not-Express ) 8.5 ( no project edit needed ) .Set Optimize code = false ; and Output/Advanced/Debug info = false ; Wrapp the method inside to try/catch block ( tried also log the exception using log4net in catch block - empty log ) Replace inner of the method with some different code . Things to note : The exception had to be catched using win debugger on the server ( no regular .NET exception handler was called ) Application crashes after the exception.This code block was functioning several months ago ( no release for a long time ) . The error started probably with some update.Tested on two different servers with IIS 7.5 and one machine having IIS 8.5 and IIS Express ( VS2012 ) . Same results.I have tried a lot of different combinations of projects settings . Basicaly if I do n't set the settings like in point 2. , it throws theexception on IIS 7.5.My working ( and build ) machine is running Windows 8.1 with latest updates.The code block is situated in separate project ( class library ) .I know how to fix this . But I do n't like closing issues , while not knowing the cause . Also , I want to avoid this in future . Do you think you could help me with that ? If it is some null reference exception , why is this happening ? And why it is debug/release specific or IIS version specific ? *Note2 : Recently I had problem with missing dll 's ( System.Net.Http.Formatting.dll , System.Web.Http.dll , System.Web.Http.WebHost.dll ) while publishing . It was because of some Microsoft security update . Maybe this is something similiar . *Edit 1Adding structure of the enum declaration.Also , I just tried adding [ MethodImpl ( MethodImplOptions.NoInlining ) ] , but no help . public static int GetDecimals ( MySimpleEnum val ) { int result = 0 ; switch ( val ) { case MySimpleEnum.Base : case MySimpleEnum.Slow : case MySimpleEnum.Normal : case MySimpleEnum.Quick : case MySimpleEnum.Fastest : result = 0 ; break ; } return result ; } public enum MySimpleEnum { Base = 0 , Slow = 1 , Normal = 2 , Quick = 3 , Fastest = 4 }",AccessViolationException thrown in strange situation "C_sharp : I 'd like to pass Bar 's name to Type.GetMethod ( string ) . I can do this as someType.GetMethod ( nameof ( Foo < int > .Bar ) ) , but that int is wholly arbitrary here ; is there any way I can omit it ? Sadly , nameof ( Foo < > .Bar ) does n't work.It 's not such a big deal in this toy case , but if there are multiple type parameters and especially if they have where constraints attached to them , spelling them all out can become a task . class Foo < T > { public T Bar ( ) { /* ... */ } }",Use nameof on a member of a generic class without specifying type arguments "C_sharp : I 'm building an MVVM Light WPF app using Visual Studio 2015 Update 1 . I have the following two search fields : cmbSearchColumn and txtSearchValue . Neither can be blank when the user clicks the Search button . Note that I 've got ValidationRules set for both fields . Here 's the relevant XAML : When the app loads , it immediately displays the error next to the fields , saying that they can not be blank . However , I need to trigger the validation on them only when the user clicks the Search button . How do I do this ? Thanks . < TextBlock Grid.Row= '' 1 '' Grid.Column= '' 0 '' Style= '' { StaticResource FieldLabel } '' > Search Column < /TextBlock > < StackPanel Grid.Row= '' 1 '' Grid.Column= '' 1 '' Style= '' { StaticResource ValidationStackPanel } '' > < ComboBox x : Name= '' cmbSearchColumn '' DisplayMemberPath= '' MemberName '' IsEditable= '' True '' ItemsSource= '' { Binding SearchColumns } '' SelectedValuePath= '' MemberValue '' Style= '' { StaticResource ComboBoxStyle } '' > < ComboBox.SelectedItem > < Binding Mode= '' TwoWay '' Path= '' SelectedColumn } '' UpdateSourceTrigger= '' Explicit '' > < Binding.ValidationRules > < helpers : NotEmptyStringValidationRule Message= '' Search Column can not be blank . '' ValidatesOnTargetUpdated= '' True '' / > < /Binding.ValidationRules > < /Binding > < /ComboBox.SelectedItem > < /ComboBox > < TextBlock Style= '' { StaticResource FieldLabelError } '' Text= '' { Binding ( Validation.Errors ) [ 0 ] .ErrorContent , ElementName=cmbSearchColumn } '' / > < /StackPanel > < TextBlock Grid.Row= '' 2 '' Grid.Column= '' 0 '' Padding= '' 0 0 9 9 '' Style= '' { StaticResource FieldLabel } '' > Search Value < /TextBlock > < StackPanel Grid.Row= '' 1 '' Grid.Column= '' 1 '' Style= '' { StaticResource ValidationStackPanel } '' > < TextBox x : Name= '' txtSearchValue '' Style= '' { StaticResource FieldTextBox } '' > < TextBox.Text > < Binding Mode= '' TwoWay '' Path= '' SearchValue '' UpdateSourceTrigger= '' Explicit '' > < Binding.ValidationRules > < helpers : NotEmptyStringValidationRule Message= '' Search Value can not be blank . '' ValidatesOnTargetUpdated= '' True '' / > < /Binding.ValidationRules > < /Binding > < /TextBox.Text > < /TextBox > < TextBlock Style= '' { StaticResource FieldLabelError } '' Text= '' { Binding ( Validation.Errors ) [ 0 ] .ErrorContent , ElementName=txtSearchValue } '' / > < /StackPanel > < Button Grid.Row= '' 4 '' Grid.Column= '' 1 '' Command= '' { Binding SearchEmployeesRelayCommand } '' Content= '' Search '' Style= '' { StaticResource FieldButton } '' / >",Trigger validation on click of Search button "C_sharp : I have a system that takes Samples . I have multiple client threads in the application that are interested in these Samples , but the actual process of taking a Sample can only occur in one context . It 's fast enough that it 's okay for it to block the calling process until Sampling is done , but slow enough that I do n't want multiple threads piling up requests . I came up with this design ( stripped down to minimal details ) : Is this safe for use in the scenario I described ? public class Sample { private static Sample _lastSample ; private static int _isSampling ; public static Sample TakeSample ( AutomationManager automation ) { //Only start sampling if not already sampling in some other context if ( Interlocked.CompareExchange ( ref _isSampling , 0 , 1 ) == 0 ) { try { Sample sample = new Sample ( ) ; sample.PerformSampling ( automation ) ; _lastSample = sample ; } finally { //We 're done sampling _isSampling = 0 ; } } return _lastSample ; } private void PerformSampling ( AutomationManager automation ) { //Lots of stuff going on that should n't be run in more than one context at the same time } }",Is this a correct Interlocked synchronization design ? "C_sharp : First , please allow me to explain what I 've got and then I 'll go over what I 'm trying to figure out next . What I 've gotI 've got a textured custom mesh with some edges that exactly align with integer world coordinates in Unity . To the mesh I 've added my own crude yet effective custom surface shader that looks like this : Into the shader I feed a float that simply oscilates between 2 and 3 over time using some maths , this is done from a simple update function in Unity : I also feed the shader an array of Vector4 called _ColorizationArray that stores 0 to 600 coordinates , each representing a tile to be colored at runtime . These tiles may or may not be highlighted depending on their selectionMode value at runtime . Here 's the method I 'm using to do that : And the result is this blue glowy set of tiles that are set and changed dynamically at runtime : My goal with all of this is to highlight squares ( or tiles , if you will ) on a mesh as part of a grid-based tactical game where units can move to any tile within the highlighted area . After each unit moves it can then undergo an attack where tiles are highlighted red , and then the next unit takes it 's turn and so on . Since I expect AI , and movement calculations , and particle effects to take up the majority of processing time I need to highlight the tiles both dynamically and very efficiently at runtime.What I 'd like to do nextWhew , ok. Now , if you know anything about shaders ( which I certainly do n't , I only started looking at cg code yesterday ) you 're probably thinking `` Oh dear god what an inefficient mess . What are you doing ? ! If statements ? ! In a shader ? '' And I would n't blame you . What I 'd really like to do is pretty much the same thing , only much more efficiently . Using specific tile indices I 'd like to tell the shader `` color the surface blue inside of these tiles , and these tiles only '' and do it in a way that is efficient for both the GPU and the CPU.How can I achieve this ? I 'm already computing tile world coordinates in C # code and providing the coordinates to the shader , but beyond that I 'm at a loss . I realize I should maybe switch to a vertex/frag shader , but I 'd also like to avoid losing any of the default dynamic lighting on the mesh if possible . Also , is there a type of variable that would allow the shader to color the mesh blue using the local mesh coordinates rather than world coordinates ? Would be nice to be able to move the mesh around without having to worry about shader code.Edit : In the 2 weeks since posting this question I 've edited the shader by passing in an array of Vector4s and a half to represent how much of the array to actually process , _ColorizationArrayLength , it works well , but is hardly more efficient - this is producing GPU spikes that take about 17ms to process on a fairly modern graphics card . I 've updated the shader code above as well as portions of the original question . Shader `` Custom/GridHighlightShader '' { Properties { [ HideInInspector ] _SelectionColor ( `` SelectionColor '' , Color ) = ( 0.1,0.1,0.1,1 ) [ HideInInspector ] _MovementColor ( `` MovementColor '' , Color ) = ( 0,0.205,1,1 ) [ HideInInspector ] _AttackColor ( `` AttackColor '' , Color ) = ( 1,0,0,1 ) [ HideInInspector ] _GlowInterval ( `` _GlowInterval '' , float ) = 1 _MainTex ( `` Albedo ( RGB ) '' , 2D ) = `` white '' { } _Glossiness ( `` Smoothness '' , Range ( 0,1 ) ) = 0.5 _Metallic ( `` Metallic '' , Range ( 0,1 ) ) = 0.0 } SubShader { Tags { `` RenderType '' = `` Opaque '' } LOD 200 CGPROGRAM // Physically based Standard lighting model , and enable shadows on all light types # pragma surface surf Standard fullforwardshadows // Use shader model 3.0 target , to get nicer looking lighting # pragma target 3.0 struct Input { float2 uv_MainTex ; float3 worldNormal ; float3 worldPos ; } ; sampler2D _MainTex ; half _Glossiness ; half _Metallic ; fixed4 _SelectionColor ; fixed4 _MovementColor ; fixed4 _AttackColor ; half _GlowInterval ; half _ColorizationArrayLength = 0 ; float4 _ColorizationArray [ 600 ] ; half _isPixelInColorizationArray = 0 ; // Add instancing support for this shader . You need to check 'Enable Instancing ' on materials that use the shader . // See https : //docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing . // # pragma instancing_options assumeuniformscaling UNITY_INSTANCING_BUFFER_START ( Props ) // put more per-instance properties here UNITY_INSTANCING_BUFFER_END ( Props ) void surf ( Input IN , inout SurfaceOutputStandard o ) { fixed4 c = tex2D ( _MainTex , IN.uv_MainTex ) ; // Update only the normals facing up and down if ( abs ( IN.worldNormal.x ) < = 0.5 & & ( abs ( IN.worldNormal.z ) < = 0.5 ) ) { // If no colors were passed in , reset all of the colors if ( _ColorizationArray [ 0 ] .w == 0 ) { _isPixelInColorizationArray = 0 ; } else { for ( int i = 0 ; i < _ColorizationArrayLength ; i++ ) { if ( abs ( IN.worldPos.x ) > = _ColorizationArray [ i ] .x & & abs ( IN.worldPos.x ) < _ColorizationArray [ i ] .x + 1 & & abs ( IN.worldPos.z ) > = _ColorizationArray [ i ] .z & & abs ( IN.worldPos.z ) < _ColorizationArray [ i ] .z + 1 ) { _isPixelInColorizationArray = _ColorizationArray [ i ] .w ; } } } if ( _isPixelInColorizationArray > 0 ) { if ( _isPixelInColorizationArray == 1 ) { c = tex2D ( _MainTex , IN.uv_MainTex ) + ( _SelectionColor * _GlowInterval ) - 1 ; } else if ( _isPixelInColorizationArray == 2 ) { c = tex2D ( _MainTex , IN.uv_MainTex ) + ( _MovementColor * _GlowInterval ) ; } else if ( _isPixelInColorizationArray == 3 ) { c = tex2D ( _MainTex , IN.uv_MainTex ) + ( _AttackColor * _GlowInterval ) ; } } } o.Albedo = c.rgb ; o.Metallic = _Metallic ; o.Smoothness = _Glossiness ; o.Alpha = c.a ; } ENDCG } FallBack `` Diffuse '' } private void Update ( ) { var t = ( 2 + ( ( Mathf.Sin ( Time.time ) ) ) ) ; meshRenderer.material.SetFloat ( `` _GlowInterval '' , t ) ; } public void SetColorizationCollectionForShader ( ) { var coloredTilesArray = Battlemap.Instance.tiles.Where ( x = > x.selectionMode ! = TileSelectionMode.None ) .ToArray ( ) ; // https : //docs.unity3d.com/ScriptReference/Material.SetVectorArray.html // Set the tile count in the shader 's own integer variable meshRenderer.material.SetInt ( `` _ColorizationArrayLength '' , coloredTilesArray.Length ) ; // Loop through the tiles to be colored only and grab their world coordinates for ( int i = 0 ; i < coloredTilesArray.Length ; i++ ) { // Also grab the selection mode as the w value of a float4 colorizationArray [ i ] = new Vector4 ( coloredTilesArray [ i ] .x - Battlemap.HALF_TILE_SIZE , coloredTilesArray [ i ] .y , coloredTilesArray [ i ] .z - Battlemap.HALF_TILE_SIZE , ( float ) coloredTilesArray [ i ] .selectionMode ) ; } // Feed the overwritten array into the shader meshRenderer.material.SetVectorArray ( `` _ColorizationArray '' , colorizationArray ) ; }",Unity Shader - How to efficiently recolor specific coordinates ? "C_sharp : There is a class , called circle . It contains circleID , circleGeometry and circlePath propertities.Now , I 'm trying to set ZIndex value for a circle . For example it 'll be 2.But I have such kind of warning : `` static method invoked via derived type '' Can somebody explain me what does that mean ? public class Circle { public string ID { get ; set ; } public EllipseGeometry circleGeometry { get ; set ; } public Path circlePath { get ; set ; } } Canvas.SetZIndex ( someCircleID.circlePath,2 ) ;",static method invoked via derived type "C_sharp : Is it possible to avoid list property tags when serializing ? Serializing Foo gives ( except the comment ) : Wanted output : // [ Serializable ( ) ] - removed , unnecessarypublic class Foo { protected List < FooBar > fooBars = new List < FooBar > ( ) ; public virtual List < FooBar > FooBars { get { return fooBars ; } set { fooBars = value ; } } } // [ Serializable ( ) ] - removed , unnecessarypublic class FooBar { public int MyProperty { get ; set ; } } < Foo xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < FooBars > < ! -- Unwanted tag -- > < FooBar > < MyProperty > 7 < /MyProperty > < /FooBar > < FooBar > < MyProperty > 9 < /MyProperty > < /FooBar > < /FooBars > < /Foo > < Foo xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < FooBar > < MyProperty > 7 < /MyProperty > < /FooBar > < FooBar > < MyProperty > 9 < /MyProperty > < /FooBar >",How to suppress XML tag for list property "C_sharp : I have an interface IMyInterface that I am mocking in a unit test using moq.The unit under test has a register method that looks like this : public void RegisterHandler ( Type type , IHandler handler ) and then a handle method : public void Handle ( IMyInterface objectToHandle ) What I am trying to test is that I can regiester 2 handlers for 2 different implementations of IMyInterface and that the Handle method correctly selects which one to use : The problem is both mocked objects are of the same type . Is there some way to force Moq to generate 2 mocks of the same interface as different types ? Mock < IMyInterface > firstMockedObject = new Mock < IMyInterface > ( ) ; Mock < IMyInterface > secondMockedObject = new Mock < IMyInterface > ( ) ; UnitUnderTest.RegisterHAndler ( firstMockedObject.Object.GetType ( ) , handler1 ) ; UnitUnderTest.RegisterHAndler ( seconMockedObject.Object.GetType ( ) , handler2 ) ;",Mock same interface as 2 different types "C_sharp : I am trying to set-up a remote validation similar to the one in this example : ExampleMy application has a twist however , my form elements are dynamically generated , therefore this tag : is not set in stone , I need to vary the ErrorMessage for example and preferably vary the action . Is it possible , or would you suggest taking the long-way , meaning to implement the whole ajax validation on my own . Any suggestions are appreciated . [ Remote ( `` doesUserNameExist '' , `` Account '' , HttpMethod = `` POST '' , ErrorMessage = `` User name already exists . Please enter a different user name . '' ) ]",Passing a variable to validator "C_sharp : I have a web method , which is called from jquery 's ajax method , like this : And this is my web method : If myClass in javascript is serialized to correct format , then DoSomething methods executes and saves the raw json to database.But if myClass is in wrong then the method does n't execute at all and I ca n't log the problematic json ... What is the best way to always somehow get and log the raw json , that my web method receives , even if the serialization fails ? $ .ajax ( { type : `` POST '' , url : `` MyWebService.aspx/DoSomething '' , data : ' { `` myClass '' : ' + JSON.stringify ( myClass ) + ' } ' , contentType : `` application/json ; charset=utf-8 '' , dataType : `` json '' , async : false , success : function ( result ) { alert ( `` success '' ) ; } , error : function ( ) { alert ( `` error '' ) ; } } ) ; [ WebMethod ( EnableSession = true ) ] public static object DoSomething ( MyClass myClass ) { HttpContext.Current.Request.InputStream.Position = 0 ; using ( var reader = new StreamReader ( HttpContext.Current.Request.InputStream ) ) { Logger.Log ( reader.ReadToEnd ( ) ) ; } }",How to log JSON requests of web services C_sharp : How can i prevent from MEF to load duplicates Modules in the case of the presence of 2 copies of the same Assembly ( maybe by mistake ) Assembly1.dllAssembly2.dll ( copy of Assembly1 ) [ ImportMany ] public IList < IModule > Modules { get ; private set ; } public void BuildUp ( ) { Modules = new List < IModule > ( ) ; var catalog = new DirectoryCatalog ( @ '' .\Modules '' ) ; var container = new CompositionContainer ( catalog ) ; container.ComposeParts ( this ) ; },How-To Prevent Module Duplicates with MEF ? C_sharp : I 'm dealing with pointer in C # using fixed { } phrases.I placed my code inside the brackets of the fixed statement and want to know if the Garbage collection will handle the pointer freeing after the fixed statementif not how can I free it ? fixed { int * p= & x } { // i work with x . },Freeing a pointer from memory in c # "C_sharp : I have a string resource that I 'm using to set as the x : uid for a textblockI 'm trying to write a Unit test to check if the text is correct . However I ca n't get a handle on the `` Expected '' string because it has a .text at the end so that it can be displayed in the TextBlockThis code fails because var expected is blank < data name= '' Expected.Text '' xml : space= '' preserve '' > < value > Expected Text < /value > < /data > < TextBlock x : Name= '' control '' x : uid= '' Expected / > ResourceLoader loader = ResourceLoader.GetForCurrentView ( ) ; var expected = loader.GetString ( `` Expected '' ) ; Assert.AreEqual ( expected , control.Text ) ;",Load string resource for textblock x : Uid in code behind "C_sharp : I have the Situation that I have an object which I want to check for equality with another object.A Problem occurs when a = 1 ( integer ) and b = 1 ( ushort ( or basically not integer ) ) . I wondered whether this should n't yield true , but it does return false ... EditWhat makes it even worse is this : I think that the value ' 1 ' should only be allowed once . public static bool Equals ( object a , object b ) { return a.Equals ( b ) ; } Hashtable ht = new Hashtable ( ) ; ht.Add ( ( int ) 1 , `` SOME STRING '' ) ; ht.Add ( ( short ) 1 , `` SOME STRING '' ) ; ht.Add ( ( long ) 1 , `` SOME STRING '' ) ;",Why does ( ( object ) ( int ) 1 ) .Equals ( ( ( object ) ( ushort ) 1 ) ) yield false ? C_sharp : Umanaged C++ : How do I marshall this to C # ? int foo ( int ** New_Message_Pointer ) ; [ DllImport ( `` example.dll '' ) ] static extern int foo ( ? ? ? ) ;,How do I marshal a pointer to a pointer to an int ? "C_sharp : Second day fighting this issue.To reproduce , create new WPF application , xamland codeMouseover button to open popup , click elsewhere to close . Click button to have bug : popup is IsOpen == true ( can be seen on checkbox or with breakpoint in handler ) , while it is invisible.WTF ? And my original problem is , it seems , what setting IsOpen is not instant . To example , when I try to set it to false in Popup 's MouseMove event , then I get MouseEnter and MouseMove events of Button fired right during thatSame with setting it to true , there are 2 ( ! ) MouseMove events occurs , put this line into event handler to see itThere will be 2 M in the Output window of VS , while Popup ( when StayOpen=false ) suppose to capture mouse events and it does , but not immediately.Can someone explain me what it going on ? I want no events to occurs during ( or shortly after ? how to check if this is true ? ) setting IsOpen . Tried already dozens of things : Dispatcher.InvokeAsync , variables , timers , etc . < StackPanel Orientation= '' Horizontal '' VerticalAlignment= '' Top '' > < Button Width= '' 100 '' Height= '' 100 '' MouseMove= '' Button_MouseMove '' / > < Popup x : Name= '' popup '' StaysOpen= '' False '' AllowsTransparency= '' True '' Placement= '' Center '' > < TextBlock > Some random text < /TextBlock > < /Popup > < CheckBox IsChecked= '' { Binding ( Popup.IsOpen ) , ElementName=popup } '' > Popup < /CheckBox > < /StackPanel > private void Button_MouseMove ( object sender , MouseEventArgs e ) { popup.IsOpen = true ; } IsOpen = true ; System.Diagnostics.Trace.WriteLine ( `` M '' ) ;",Invisible opened popup "C_sharp : The C # language specification describes type inference in Section §7.5.2 . There is a detail in it that I don ’ t understand . Consider the following case : Both the Microsoft and Mono C # compilers correctly infer T = object , but my understanding of the algorithm in the specification would yield T = string and then fail . Here is how I understand it : The first phaseIf Ei is an anonymous function , an explicit parameter type inference ( §7.5.2.7 ) is made from Ei to Ti⇒ has no effect , because the lambda expression has no explicit parameter types . Right ? Otherwise , if Ei has a type U and xi is a value parameter then a lower-bound inference is made from U to Ti.⇒ the first parameter is of static type string , so this adds string to the lower bounds for T , right ? The second phaseAll unfixed type variables Xi which do not depend on ( §7.5.2.5 ) any Xj are fixed ( §7.5.2.10 ) .⇒ T is unfixed ; T doesn ’ t depend on anything ... so T should be fixed , right ? §7.5.2.11 FixingThe set of candidate types Uj starts out as the set of all types in the set of bounds for Xi.⇒ { string ( lower bound ) } We then examine each bound for Xi in turn : [ ... ] For each lower bound U of Xi all types Uj to which there is not an implicit conversion from U are removed from the candidate set . [ ... ] ⇒ doesn ’ t remove anything from the candidate set , right ? If among the remaining candidate types Uj there is a unique type V from which there is an implicit conversion to all the other candidate types , then Xi is fixed to V.⇒ Since there is only one candidate type , this is vacuously true , so Xi is fixed to string . Right ? So where am I going wrong ? // declarationvoid Method < T > ( T obj , Func < string , T > func ) ; // callMethod ( `` obj '' , s = > ( object ) s ) ;",Problem understanding C # type inference as described in the language specification "C_sharp : How can I replace \r 's with \r\n when the \r is n't followed by a \n using Regex ? The problemI 'm having problems with a text editor on Windows I 'm creating in that line breaks are being added as \r . As a result they are not being read as line breaks when I open the file in Notepad.What I triedI 've tried looking everywhere ( google , stackoverflow , etc ) for this , but have been unable to find something that is specifically for what I 'm after.Everything I 've tried so far does what I 'm after the first time but it then keeps unnecessarily replacing \r 's even if they 're followed by a \n.For reference , this is the expression : `` \r ( ? ! ^\n ) '' , `` \r\n ''",Regex to replace all instances of \r not followed by \n with \r\n "C_sharp : Preamble : I was changing a bit of code ( manual Max search in an array ) to some Linq.Max ( ) super sexy written line , which brings me to questions about performance ( I often deal with big arrays ) . So I made a little program to test , because I only trust what I see and got this results : In short , Linq is almost 10 times slower , which bothered me a bit , so I took a look to the implementation of Max ( ) : As the title already ask , what in this implementation make it 10 times slower ? ( And it 's not about the ForEach , I 've checked ) Edit : Of course , I test in Release mode.Here 's my test code ( without output ) : The size is now of 1 elementsWith the loop it took : 00:00:00.0000015 With Linq it took : 00:00:00.0000288 The loop is faster : 94,79 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 10 elementsWith the loop it took : 00:00:00 With Linq it took : 00:00:00.0000007 The loop is faster : 100,00 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 100 elementsWith the loop it took : 00:00:00 With Linq it took : 00:00:00.0000011 The loop is faster : 100,00 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 1 000 elementsWith the loop it took : 00:00:00.0000003 With Linq it took : 00:00:00.0000078 The loop is faster : 96,15 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 10 000 elementsWith the loop it took : 00:00:00.0000063 With Linq it took : 00:00:00.0000765 The loop is faster : 91,76 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 100 000 elementsWith the loop it took : 00:00:00.0000714 With Linq it took : 00:00:00.0007602 The loop is faster : 90,61 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 1 000 000 elementsWith the loop it took : 00:00:00.0007669 With Linq it took : 00:00:00.0081737 The loop is faster : 90,62 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 10 000 000 elementsWith the loop it took : 00:00:00.0070811 With Linq it took : 00:00:00.0754348 The loop is faster : 90,61 % -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -The size is now of 100 000 000 elementsWith the loop it took : 00:00:00.0788133 With Linq it took : 00:00:00.7758791 The loop is faster : 89,84 % public static int Max ( this IEnumerable < int > source ) { if ( source == null ) throw Error.ArgumentNull ( `` source '' ) ; int value = 0 ; bool hasValue = false ; foreach ( int x in source ) { if ( hasValue ) { if ( x > value ) value = x ; } else { value = x ; hasValue = true ; } } if ( hasValue ) return value ; throw Error.NoElements ( ) ; } // -- -- -- -- -- -- -- -- private int [ ] arrDoubles ; // -- -- -- -- -- -- -- -- Stopwatch watch = new Stopwatch ( ) ; //Stop a 100 Millions to avoid memory overflow on my laptopfor ( int i = 1 ; i < = 100000000 ; i = i * 10 ) { fillArray ( i ) ; watch.Restart ( ) ; int max = Int32.MinValue ; // Reset for ( int j = 0 ; j < arrDoubles.Length ; j++ ) { max = Math.Max ( arrDoubles [ j ] , max ) ; } watch.Stop ( ) ; TimeSpan loopSpan = watch.Elapsed ; watch.Restart ( ) ; max = Int32.MinValue ; // Reset max = arrDoubles.Max ( ) ; watch.Stop ( ) ; TimeSpan linqSpan = watch.Elapsed ; } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -private void fillArray ( int nbValues ) { int Min = Int32.MinValue ; int Max = Int32.MaxValue ; Random randNum = new Random ( ) ; arrDoubles = Enumerable.Repeat ( 0 , nbValues ) .Select ( i = > randNum.Next ( Min , Max ) ) .ToArray ( ) ; }",What in Linq.Max implementation is the bottleneck ? "C_sharp : I want to implement an interface that automatically clears all local fields , so far I have : How do I set the last step to save the default value over the field ? // Implement IClearabledynamicType.AddInterfaceImplementation ( typeof ( IClearable ) ) ; MethodBuilder clearnMethodBuilder = dynamicType.DefineMethod ( `` Clear '' , MethodAttributes.Public | MethodAttributes.Virtual , CallingConventions.Standard ) ; ILGenerator clearMethodILGen = clearnMethodBuilder.GetILGenerator ( ) ; foreach ( FieldBuilder localField in fields ) { clearMethodILGen.Emit ( OpCodes.Ldarg_0 ) ; clearMethodILGen.Emit ( OpCodes.Ldfld , localField ) ; clearMethodILGen.Emit ( OpCodes. ? ? , Profit ? ? ) ; } clearMethodILGen.Emit ( OpCodes.Ret ) ;",How would you emit the default value of a type ? "C_sharp : I 'm trying to write a simple program that will compare the files in separate folders . I 'm currently using LINQ to Objects to parse the folder and would like to included information extracted from the string in my result set as well.Here 's what I have so far : This produces : I would like to modify the LINQ query so that : It only includes actual `` backup '' files ( you can tell the backup files because of the _C_Drive038 in the examples above , though 038 and possibly the drive letter could change ) .I want to include a field if the file is the `` main '' backup file ( i.e. , it does n't have _i0XX at the end of the file name ) .I want to include the `` image number '' of the file ( e.g . in this case it 's 038 ) .I want to include the increment number if it 's an incrememnt of a base file ( e.g . 001 would be an increment number ) I believe the basic layout of the query would look like the following , but I 'm not sure how best to complete it ( I 've got some ideas for how some of this might be done , but I 'm interested to heard how others might do it ) : When looking for the ImageNumber and IncrementNumber , I would like to assume that the location of this data is not always fixed , meaning , I 'd like to know of a good way to parse this ( If this requires RegEx , please explain how I might use it ) .NOTE : Most of my past experience in parsing text involved using location-based string functions , such as LEFT , RIGHT , or MID . I 'd rather not fall back on those if there is a better way . FileInfo [ ] fileList = new DirectoryInfo ( @ '' G : \Norton Backups '' ) .GetFiles ( ) ; var results = from file in fileList orderby file.CreationTime select new { file.Name , file.CreationTime , file.Length } ; foreach ( var x in results ) Console.WriteLine ( x.Name ) ; AWS025.sv2iAWS025_C_Drive038.v2iAWS025_C_Drive038_i001.iv2iAWS025_C_Drive038_i002.iv2iAWS025_C_Drive038_i003.iv2iAWS025_C_Drive038_i004.iv2iAWS025_C_Drive038_i005.iv2i ... var results = from file in fileList let IsMainBackup = \\ ? ? let ImageNumber = \\ ? ? let IncrementNumber = \\ ? ? where \\ it is a backup file . orderby file.CreationTime select new { file.Name , file.CreationTime , file.Length , IsMainBackup , ImageNumber , IncrementNumber } ;",How might I complete this example using LINQ and string parsing ? "C_sharp : Suppose I have some code that looks like this : I can not combine things into one big for loop like this : Doing so would change the order . Any commentary on the best ways to make the code simpler in C # ? I imagine I could solve this problem by creating a function like this , though I 'd rather leave it the way it is than force future readers of my code to understand yield : foreach ( type x in list y ) { //dostuff1 ( x ) } foreach ( type x in list y ) { //dostuff2 ( x ) } foreach ( type x in list y ) { //dostuff3 ( x ) } foreach ( type x in list y ) { //dostuff4 ( x ) } foreach ( type x in list y ) { //dostuff5 ( x ) } foreach ( type x in list y ) { //dostuff1 ( x ) //dostuff2 ( x ) //dostuff3 ( x ) //dostuff4 ( x ) //dostuff5 ( x ) } void func ( type x ) { dostuff1 ( x ) yield 0 ; dostuff2 ( x ) yield 0 ; dostuff3 ( x ) yield 0 ; dostuff4 ( x ) yield 0 ; dostuff5 ( x ) yield break ; } for ( int i = 0 ; i < 5 ; ++i ) { foreach ( type x in list y ) { //Call func ( x ) using yield semantics , which I 'm not going to look up right now } }",C # Code Simplification Query : The Sequential Foreach Loops "C_sharp : How to access VIP in the proxy_OpenReadCompleted method ? void method1 ( ) { String VIP = `` test '' ; WebClient proxy = new WebClient ( ) ; proxy.OpenReadCompleted += new OpenReadCompletedEventHandler ( proxy_OpenReadCompleted ) ; String urlStr = `` someurl/lookup ? q= '' + keyEntityName + `` & fme=1 & edo=1 & edi=1 '' ; } void proxy_OpenReadCompleted ( object sender , OpenReadCompletedEventArgs e ) { }",Silverlight : How to pass data from the request to the response using Webclient Asynchronous mode ? "C_sharp : I want to pass either string or List < string > as a parameter , like the way I could do in JavaScript , and then evaluate what type is it and do the appropriate actions . Now I can do it like this : What the code inside these methods do , is basically Parsing with some programs either one file or list of files , depends what type is given.If I will have lots of code , should I duplicate it , or should I create sub method which will contain the code , or is there another cool way I can do this in c # ? public static class TestParser { static void Parse ( string inputFile ) { // Lots of code goes in here } static void Parse ( List < string > inputFileList ) { // Lots of code goes in here too } }",Best practice with dynamic string/List < string > parameters "C_sharp : I just had a very interesting experience with AOP in C # . I have a function with a return type List which is being intercepted and that 's all well and good . However the interceptor function is a validator style function and can prevent the real function by being called and returning the boolean false.So the code looks a little bit like this : The Method Interceptor looks like the followingNow after validation fails the value of updates is actually a boolean not a List , I thought there would be some kind of runtime error here but there was not , so : But : So save will still accept its mutated list of updates and will complain later on when you try to use it.So how is this possible in a type safe language like C # ? btw it 's spring-aop.Edit : Also this does compile and it does work i 've stepped through it a few times now . List < Update > updates = Manager.ValidateAndCreate ( ) ; // protected void Save ( List < Update > updates ) { ... .Save ( updates ) ; public class ExceptionAdvice : AopAlliance.Intercept.IMethodInterceptor { public object Invoke ( AopAlliance.Intercept.IMethodInvocation invocation ) { if ( isValid ( invocation ) ) { return invocation.Proceed ( ) ; } else { return false ; } } private bool isValid ( ... } updates.GetType ( ) .Name == `` Boolean '' updates is bool == false",C # and AOP - AOPAlliance ( Aspect-oriented programming ) how does this work "C_sharp : I 'm trying to create URIs that look a little something like this : http : //hostname/mobile/en/controller/action for mobiles OR http : //hostname/en/controller/action for desktop ( non mobiles ) .My Route table currently looks like this ( Global.asax.cs ) The problem occurs when I try to do a return RedirectToAction ( `` Add '' , `` User '' ) ; It always redirects the desktop browser from /en/User/List to /mobile/en/User/Add when I want it to go to /en/User/Add.The Mobile version works correctly but I believe this is because the first `` Mobile '' route is always been seen to be the route that matches even if it does n't have /mobile/ at the start.I 'm trying to use the same Controller for both versions but am stuck at it always redirecting to the Mobile route . This means RedirectToRoute is n't prefect as I want dynamic routes.Thanks for your help . routes.IgnoreRoute ( `` { resource } .axd/ { *pathInfo } '' ) ; routes.MapRoute ( `` Mobile '' , // Route name `` mobile/ { language } / { controller } / { action } / { id } '' , // URL with parameters new { language = `` en '' , controller = `` Route '' , action = `` Index '' , id = UrlParameter.Optional } , // Parameter defaults new { language = @ '' en|us '' } // validation ) ; routes.MapRoute ( `` Default '' , // Route name `` { language } / { controller } / { action } / { id } '' , // URL with parameters new { language = `` en '' , controller = `` Route '' , action = `` Index '' , id = UrlParameter.Optional } , // Parameter defaults new { language = @ '' en|us '' } // validation ) ;",Route always goes to the first maproute "C_sharp : I 'm making a game using XNA framework , so I use a lot functions that operate on vectors . ( especially Vector2 ( 64bit struct ) ) . What bothers me is that most of the methods are defined with ref and out parameters . Here is an example : which looks a bit strange too me . There is also another Min which is more obviousBasically , almost all the functions have overloads with refs and outs . Similar , other APIs.What is the benefit of this design ? XNA is optimized for performance , could it be a result ? Say , Quaternion requires 128b where passing by ref less . EDIT : Here is a test code : The results : refOut1 2200 refOut2 1400Win 7 64bit , .Net 4 . XNA 4.0Also IL code andSeems overhead is caused by temp Vector . Also I tried 1GHz WP 7.5 device:19791677Number of ticks for an order of magnitude smaller number of iterations . void Min ( ref Vector2 value1 , ref Vector2 value2 , out Vector2 result ) public static Vector2 Min ( Vector2 value1 , Vector2 value2 ) ; public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics ; SpriteBatch spriteBatch ; private Vector2 vec1 = new Vector2 ( 1 , 2 ) ; private Vector2 vec2 = new Vector2 ( 2 , 3 ) ; private Vector2 min ; private string timeRefOut1 ; private string timeRefOut2 ; private SpriteFont font ; public Game1 ( ) { graphics = new GraphicsDeviceManager ( this ) ; Content.RootDirectory = `` Content '' ; refOut1 ( ) ; refOut2 ( ) ; } private Vector2 refOut1 ( ) { Vector2 min = Vector2.Min ( vec1 , vec2 ) ; return min ; } private Vector2 refOut2 ( ) { Vector2.Min ( ref vec1 , ref vec2 , out min ) ; return min ; } protected override void Initialize ( ) { const int len = 100000000 ; Stopwatch stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; for ( int i = 0 ; i < len ; i++ ) { refOut1 ( ) ; } stopWatch.Stop ( ) ; timeRefOut1 = stopWatch.ElapsedMilliseconds.ToString ( ) ; stopWatch.Reset ( ) ; stopWatch.Start ( ) ; for ( int i = 0 ; i < len ; i++ ) { refOut2 ( ) ; } stopWatch.Stop ( ) ; timeRefOut2 = stopWatch.ElapsedMilliseconds.ToString ( ) ; base.Initialize ( ) ; } protected override void LoadContent ( ) { spriteBatch = new SpriteBatch ( GraphicsDevice ) ; font = Content.Load < SpriteFont > ( `` SpriteFont1 '' ) ; } protected override void Update ( GameTime gameTime ) { if ( GamePad.GetState ( PlayerIndex.One ) .Buttons.Back == ButtonState.Pressed ) this.Exit ( ) ; base.Update ( gameTime ) ; } protected override void Draw ( GameTime gameTime ) { GraphicsDevice.Clear ( Color.CornflowerBlue ) ; spriteBatch.Begin ( ) ; spriteBatch.DrawString ( font , timeRefOut1 , new Vector2 ( 200 , 200 ) , Color.White ) ; spriteBatch.DrawString ( font , timeRefOut2 , new Vector2 ( 200 , 300 ) , Color.White ) ; spriteBatch.End ( ) ; // TODO : Add your drawing code here base.Draw ( gameTime ) ; } } .method public hidebysig static void Min ( valuetype Microsoft.Xna.Framework.Vector2 & value1 , valuetype Microsoft.Xna.Framework.Vector2 & value2 , [ out ] valuetype Microsoft.Xna.Framework.Vector2 & result ) cil managed { // Code size 69 ( 0x45 ) .maxstack 3 IL_0000 : ldarg.2 IL_0001 : ldarg.0 IL_0002 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0007 : ldarg.1 IL_0008 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_000d : blt.s IL_0017 IL_000f : ldarg.1 IL_0010 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0015 : br.s IL_001d IL_0017 : ldarg.0 IL_0018 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_001d : stfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0022 : ldarg.2 IL_0023 : ldarg.0 IL_0024 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_0029 : ldarg.1 IL_002a : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_002f : blt.s IL_0039 IL_0031 : ldarg.1 IL_0032 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_0037 : br.s IL_003f IL_0039 : ldarg.0 IL_003a : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_003f : stfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_0044 : ret } // end of method Vector2 : :Min .method public hidebysig static valuetype Microsoft.Xna.Framework.Vector2 Min ( valuetype Microsoft.Xna.Framework.Vector2 value1 , valuetype Microsoft.Xna.Framework.Vector2 value2 ) cil managed { // Code size 80 ( 0x50 ) .maxstack 3 .locals init ( valuetype Microsoft.Xna.Framework.Vector2 V_0 ) IL_0000 : ldloca.s V_0 IL_0002 : ldarga.s value1 IL_0004 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0009 : ldarga.s value2 IL_000b : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0010 : blt.s IL_001b IL_0012 : ldarga.s value2 IL_0014 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0019 : br.s IL_0022 IL_001b : ldarga.s value1 IL_001d : ldfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0022 : stfld float32 Microsoft.Xna.Framework.Vector2 : :X IL_0027 : ldloca.s V_0 IL_0029 : ldarga.s value1 IL_002b : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_0030 : ldarga.s value2 IL_0032 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_0037 : blt.s IL_0042 IL_0039 : ldarga.s value2 IL_003b : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_0040 : br.s IL_0049 IL_0042 : ldarga.s value1 IL_0044 : ldfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_0049 : stfld float32 Microsoft.Xna.Framework.Vector2 : :Y IL_004e : ldloc.0 IL_004f : ret } // end of method Vector2 : :Min",What is the benefit of using out/ref versus returning ? "C_sharp : Im having a little trouble understanding delegates.I have a delegate that i will invoke when a y character is entered : i have a subscribe method in order that calling code can ask to be notified when the delegate is invoked : As far as i can see , to register with this delegate , i need to provide something of the type respondToY . Yet when calling the subscribe method , i can supply either a new instance of the delegate or simply the name of the method . Does this mean that any method matching the delegate signature can be used and will automatically be converted to the correct delegate type ? ** Edit ** So on this assumption it would also be valid to supply only a method name to things like click event handlers for buttons ( provided the method took the sender , and the relevant event object ) , it would be converted to the required delegate ? public delegate void respondToY ( string msgToSend ) ; private respondToY yHandler ; public void Subscribe ( respondToY methodName ) { yHandler += methodName ; }",Are method names implicitly cast to delegate types ? "C_sharp : I have a form which is used to generate a Report . We are using RDLC reports and the Report is loaded in an aspx page.So this is the code for the Form , form target is set to _blank , and opens in new Tab.This is the Controller action which redirects to the Report aspx page , where the Report is processed and displayed.The Reports take 3,4 minutes to generate in some cases . and during this time the UI is blocked , We want the report to generate on a separate thread so that user can use the UI while the report is generated.Is there a way in MVC C # to Execute this Action in a separate Thread ? I have tried using the following , but the Context and Session are then NULLand also : EDITCode to generate the Report in - This is the code that takes 3 to 4 minutes ExcessiveIdleReport.aspxI have also tried using Ajax.BeginFormJS : I load all other Pages using Ajax : Here is an image of the Asset Reports page 'Show Report ' button which executes the action : But once this button is clicked other UI Elements are Blocked . e.g . I ca n't load View with Group Reports until the Report has been generated . @ using ( Html.BeginForm ( `` AssetReports '' , `` AssetReports '' , FormMethod.Post , new { target = `` _blank '' } ) ) { < div class= '' row mt-15 '' > < div class= '' col-md-12 text-center '' > < input type= '' submit '' class= '' btn btn-primary '' value= '' Show Report '' / > < /div > < /div > } [ HttpPost ] public void AssetReports ( AssetReportsDTO model , AssetReportParametersDTO reportParameters ) { SessionHandler.AssetReport = model ; SessionHandler.AssetReportParameters = reportParameters ; switch ( model.SelectedReportType ) { case AssetReportTypesEnum.ExcessiveIdleReport : Response.Redirect ( `` ~/Reports/AssetReports/ExcessiveIdleReport/ExcessiveIdleReport.aspx '' ) ; break ; } } Task.Factory.StartNew ( ( ) = > { switch ( model.SelectedReportType ) { case AssetReportTypesEnum.ExcessiveIdleReport : Response.Redirect ( `` ~/Reports/AssetReports/ExcessiveIdleReport/ExcessiveIdleReport.aspx '' ) ; break ; } } ) ; new Thread ( ( ) = > { switch ( model.SelectedReportType ) { case AssetReportTypesEnum.ExcessiveIdleReport : Response.Redirect ( `` ~/Reports/AssetReports/ExcessiveIdleReport/ExcessiveIdleReport.aspx '' ) ; break ; } } ) .Start ( ) ; public partial class ExcessiveIdleReport1 : Page { private IReportsProvider _reportsProvider ; protected void Page_Load ( object sender , EventArgs e ) { _reportsProvider = new ReportsProvider ( ) ; if ( ! IsPostBack ) { try { var reportDetails = SessionHandler.AssetReport ; var reportParams = SessionHandler.AssetReportParameters ; var sPath = Server.MapPath ( `` ../ExcessiveIdleReport/ExcessiveIdleReport.rdlc '' ) ; var dsExcessiveReport = _reportsProvider.GetExcessiveIdleReport ( reportDetails.CompanyId , reportDetails.AssetId , reportDetails.StartDate , reportDetails.EndDate , reportParams.SelectedIdleTime * 60 ) ; ExcessiveIdleReportViewer.ProcessingMode = ProcessingMode.Local ; ExcessiveIdleReportViewer.LocalReport.EnableHyperlinks = true ; ExcessiveIdleReportViewer.HyperlinkTarget = `` _blank '' ; ExcessiveIdleReportViewer.LocalReport.DataSources.Add ( new ReportDataSource ( `` ExcessiveIdleReport '' , dsExcessiveReport.Tables [ 0 ] ) ) ; ExcessiveIdleReportViewer.LocalReport.DataSources.Add ( new ReportDataSource ( `` ReportHeaderDetails '' , dsExcessiveReport.Tables [ 1 ] ) ) ; ExcessiveIdleReportViewer.LocalReport.DataSources.Add ( new ReportDataSource ( `` ReportSummary '' , dsExcessiveReport.Tables [ 2 ] ) ) ; ExcessiveIdleReportViewer.LocalReport.ReportPath = sPath ; ExcessiveIdleReportViewer.LocalReport.EnableExternalImages = true ; ExcessiveIdleReportViewer.LocalReport.SetParameters ( param ) ; ExcessiveIdleReportViewer.LocalReport.Refresh ( ) ; } catch ( Exception ex ) { ErrorDiv.InnerText = string.Format ( `` An error occured while generating the ExcessiveIdleReport , Please contact Support with following Message : [ { 0 } ] - [ { 1 } ] '' , ex.Message , ex.StackTrace ) ; ReportContentDiv.Visible = false ; ErrorDiv.Visible = true ; } } } } @ using ( Ajax.BeginForm ( `` AssetReports '' , `` AssetReports '' , new AjaxOptions ( ) { HttpMethod = `` POST '' , OnSuccess = `` OpenReport '' } , new { target = `` _blank '' } ) ) { < div class= '' row mt-15 '' > < div class= '' col-md-12 text-center '' > < input type= '' submit '' class= '' btn btn-primary '' value= '' Show Report '' / > < /div > < /div > } function OpenReport ( response ) { var popup = window.open ( `` about : blank '' , `` _blank '' ) ; // the about : blank is to please Chrome , and _blank to please Firefox popup.location = '/TBReports/AssetReports/ExcessiveIdleReport/ExcessiveIdleReport.aspx ' ; }",Execute an Action in separate thread to unblock the UI "C_sharp : Let me sketch the situation first : I have a basic controller which looks like this : Using the following routingI can easly use the functions as followsNow i wanted to add the following controllerBut the following GET does n't workIt works however when I change my function as follows : Question : Could someone explain the origin of this behavior ? Have I done something wrong or is there something wrong with my routing ? public class SearchRequestController : ApiController { public IEnumerable < ObjectA > GetAllRequests ( ) { ... } { } public IEnumerable < ObjectA > GetLatestRequest ( ) { ... } { } } public static void RegisterRoutes ( RouteCollection routes ) { routes.IgnoreRoute ( `` { resource } .axd/ { *pathInfo } '' ) ; routes.MapRoute ( name : `` Default '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; } Http : //myServer/myvirtualdirectory/api/SearchRequest/GetAllRequests Http : //myServer/myvirtualdirectory/api/SearchRequest/GetLatestRequest public class UserController : ApiController { public IEnumerable < UserObject > SearchUsersByInput ( ) { ... } } Http : //myServer/myvirtualdirectory/api/User/SearchUsersByInput I 'm getting a 405 : { `` Message '' : '' The requested resource does not support http method 'GET ' . '' } public class UserController : ApiController { [ HttpGet ] public IEnumerable < UserObject > SearchUsersByInput ( ) { ... } }",Why is HttpGet required only for some actions ? "C_sharp : I came across a very funny situation where comparing a nullable type to null inside a generic method is 234x slower than comparing an value type or a reference type . The code is as follows : The execution code is : The output for the code above is:00:00:00.187982700:00:00.000877900:00:00.0008532As you can see , comparing an nullable int to null is 234x slower than comparing an int or a string . If I add a second overload with the right constraints , the results change dramatically : Now the results are:00:00:00.000604000:00:00.000601700:00:00.0006014Why is that ? I did n't check the byte code because I 'm not fluent on it , but even if the byte code was a little bit different , I would expect the JIT to optimize this , and it is not ( I 'm running with optimizations ) . static bool IsNull < T > ( T instance ) { return instance == null ; } int ? a = 0 ; string b = `` A '' ; int c = 0 ; var watch = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { var r1 = IsNull ( a ) ; } Console.WriteLine ( watch.Elapsed.ToString ( ) ) ; watch.Restart ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { var r2 = IsNull ( b ) ; } Console.WriteLine ( watch.Elapsed.ToString ( ) ) ; watch.Restart ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) { var r3 = IsNull ( c ) ; } watch.Stop ( ) ; Console.WriteLine ( watch.Elapsed.ToString ( ) ) ; Console.ReadKey ( ) ; static bool IsNull < T > ( T ? instance ) where T : struct { return instance == null ; }",Why is it slower to compare a nullable value type to null on a generic method with no constraints ? "C_sharp : I have a class : The docs say : [ ... ] The parser will pass null to master class GetUsage ( string ) also if the user requested the help index with : $ git help or the verb command if the user requested explicitly instructions on how to use a particular verb : $ git help commit [ ... ] Then , I typed MyApp.exe help verb1 , but I could see only the base help ( that looked like I typed the wrong verb , or help verb , or something ) . Rather , I expect it to show the help message related to specified verb . Why is n't it working properly ? class Options { // Remainder omitted ( verb1 , verb2 , verb3 ) [ HelpVerbOption ] public string GetUsage ( string verb ) { return HelpText.AutoBuild ( this , verb ) ; } }",HelpVerbOption is not working - Command Line Parser C # "C_sharp : What I am showing below , is rather a theoretical question . But I am interested in how the new C # 7 compiler works and resolves local functions.In C # 7 I can use local functions . For example ( you can try these examples in LinqPad beta ) : Example 1 : Nested Main ( ) DotNetFiddle for Example 1Rather than calling Main ( ) in a recursive way , the local function Main ( ) is being called once , so the output of this is : Hello ! The compiler accepts this without warnings and errors.Example 2 : Here , I am going one level deeper , like : DotNetFiddle for Example 2In this case , I would also expect the same output , because the innermost local function is called , then one level up , Main ( ) is just another local function with a local scope , so it should be not much different from the first example.But here , to my surprise , I am getting an error : CS0136 A local or parameter named 'Main ' can not be declared in this scope because that name is used in an enclosing local scope to define a local or parameterQuestion : Can you explain why this error happens in Example 2 , but not in Example 1 ? I thought , each inner Main ( ) would have a local scope and is hidden outside.Update : Thank you to all who have made contibutions so far ( either answers or comments ) , it is very worthwile what you wrote to understand the behavior of the C # compiler . From what I read , and after considering the possibilities , what I found out with your help is that it can be either a compiler bug or behavior by design.Recall that C # had some design goals which differentiate it from languages like C++.If you 're interested what I have done to investigate it further : I have renamed the innermost function to MainL like : Example 2b : This modified example compiles and runs successfully.Now when you compile this with LinqPad and then switch to the IL tab you can see what the compiler did : It created the innermost MainL function as g__MainL0_1 , the enclosing Main function has the label g__Main0_0 . That means , if you remove the L from MainL you will notice that the compiler already renames it in a unique way , because then the code looks like : which would still resolve correctly . Since the code does n't look like this in Example 2 , because the compiler stops with an error , I do now assume that the behavior is by design , it is not likely a compiler bug.Conclusion : Some of you wrote that in C++ recursive resolution of local functions can lead to refactoring issues , and others wrote that this kind of behavior in C # is what the compiler does with local variables ( note that the error message is the same ) - all that even confirms me thinking it was done like this by design and is no bug . void Main ( ) { void Main ( ) { Console.WriteLine ( `` Hello ! `` ) ; } Main ( ) ; } void Main ( ) { void Main ( ) { void MainL ( ) { Console.WriteLine ( `` Hello ! `` ) ; } MainL ( ) ; } Main ( ) ; } IL_0000 : call UserQuery. < Main > g__Main0_0IL_0005 : ret < Main > g__Main0_0 : IL_0000 : call UserQuery. < Main > g__Main0_1IL_0005 : ret < Main > g__Main0_1 : IL_0000 : ldstr `` Hello ! `` IL_0005 : call System.Console.WriteLineIL_000A : ret",Why is a local function not always hidden in C # 7 ? "C_sharp : When I try this on a large xml file ( that is also very slow to download ) , my azure web app throws a blank page after a couple of minutes.I saw this on Azure 's Failed Request Tracing Logs : ModuleName : DynamicCompressionModuleNotification : SEND_RESPONSEHttpStatus : 500HttpReason : Internal Server ErrorHttpSubStatus : 19ErrorCode : An operation was attempted on a nonexistent network connection . ( 0x800704cd ) As you can see , I have been `` playing around '' with the timeout settings.Also tried catching all exceptions but it does n't catch any.Also , this works without problems when debugging the web app locally on my computer . It could be that the internet connection at my office is better than Azure 's , resulting on the xml file being read fast without any problems.Any possible workarounds ? Edit : I want to keep streaming the XML file ( I 'm avoiding downloading the whole file because the user has an option to read only the first N entries of the feed ) . In case the problem described above ca n't be avoided , I will be happy if someone can help me displaying a meaningful message to the user at least , instead of blank page . string url = `` http : //www.example.com/feed.xml '' ; var settings = new XmlReaderSettings ( ) ; settings.IgnoreComments = true ; settings.IgnoreProcessingInstructions = true ; settings.IgnoreWhitespace = true ; settings.XmlResolver = null ; settings.DtdProcessing = DtdProcessing.Parse ; settings.CheckCharacters = false ; var request = ( HttpWebRequest ) WebRequest.Create ( url ) ; request.Timeout = 900000 ; request.KeepAlive = true ; request.IfModifiedSince = lastModified ; var response = ( HttpWebResponse ) request.GetResponse ( ) ; Stream stream ; stream = response.GetResponseStream ( ) ; stream.ReadTimeout = 600000 ; var xmlReader = XmlReader.Create ( stream , settings ) ; while ( ! xmlReader.EOF ) { ...","ASP.Net when trying to read xml file , `` An operation was attempted on a nonexistent network connection ''" "C_sharp : I have defined to following structures to emulate a C++ union ( which will eventually be used for C++ Interop ) : I have written the following test code which assigns a value to Struct1.guid and tests for equality to Struct2.guid : Why does Struct2.guid not equal Struct1.guid and instead a segment of Struct2.guid 's value seems to shift into Struct2.integer ? All structure members , IMO , seem to be aligned . [ StructLayout ( LayoutKind.Sequential ) ] internal struct STRUCT1 { public Guid guid ; public String str1 ; public String str2 ; } [ StructLayout ( LayoutKind.Sequential ) ] internal struct STRUCT2 { public Guid guid ; public String str1 ; public String str2 ; public Int32 i1 ; } [ StructLayout ( LayoutKind.Explicit ) ] internal struct MASTER_STRUCT_UNION { [ FieldOffset ( 0 ) ] public STRUCT1 Struct1 ; [ FieldOffset ( 0 ) ] public STRUCT2 Struct2 ; } [ StructLayout ( LayoutKind.Sequential ) ] internal struct MASTER_STRUCT { public MASTER_STRUCT_UNION Union ; } class Class1 { public static void Test ( ) { MASTER_STRUCT ms = new MASTER_STRUCT ( ) ; bool match ; ms.Union.Struct1.guid = new Guid ( 0xffeeddcc , 0xbbaa , 0x9988 , 0x77 , 0x66 , 0x55 , 0x44 , 0x33 , 0x22 , 0x11 , 0 ) ; Console.WriteLine ( `` Struct1.guid : \t\t { 0 } \n '' , ms.Union.Struct1.guid.ToString ( ) ) ; Console.WriteLine ( `` Struct2.integer : \t { 0 : x } '' , ms.Union.Struct2.i1 ) ; Console.WriteLine ( `` Struct2.guid : \t\t { 0 } '' , ms.Union.Struct2.guid.ToString ( ) ) ; match = ms.Union.Struct1.guid == ms.Union.Struct2.guid ? true : false ; } }",Unions in C # : Structure Members Do Not Seem to be Aligned "C_sharp : Answering the question : Task.Yield - real usages ? I proposed to use Task.Yield allowing a pool thread to be reused by other tasks . In such pattern : But one user wrote I do n't think using Task.Yield to overcome ThreadPool starvation while implementing producer/consumer pattern is a good idea . I suggest you ask a separate question if you want to go into details as to why.Anybody knows , why is not a good idea ? CancellationTokenSource cts ; void Start ( ) { cts = new CancellationTokenSource ( ) ; // run async operation var task = Task.Run ( ( ) = > SomeWork ( cts.Token ) , cts.Token ) ; // wait for completion // after the completion handle the result/ cancellation/ errors } async Task < int > SomeWork ( CancellationToken cancellationToken ) { int result = 0 ; bool loopAgain = true ; while ( loopAgain ) { // do something ... means a substantial work or a micro batch here - not processing a single byte loopAgain = /* check for loop end & & */ cancellationToken.IsCancellationRequested ; if ( loopAgain ) { // reschedule the task to the threadpool and free this thread for other waiting tasks await Task.Yield ( ) ; } } cancellationToken.ThrowIfCancellationRequested ( ) ; return result ; } void Cancel ( ) { // request cancelation cts.Cancel ( ) ; }",Using Task.Yield to overcome ThreadPool starvation while implementing producer/consumer pattern "C_sharp : How do I use c # similar Math.Round with MidpointRounding.AwayFromZero in Delphi ? What will be the equivalent of : Output : 2.13In Delphi ? double d = 2.125 ; Console.WriteLine ( Math.Round ( d , 2 , MidpointRounding.AwayFromZero ) ) ;",What is the equivalent of Math.Round ( ) with MidpointRounding.AwayFromZero in Delphi ? "C_sharp : ① In following C # code , CS1729 occurs but I understand that CS0122 would be more appropriate.CS1729 : ' A.Test ' does not contain a constructor that takes 1 argumentsCS0122 : ' A.Test.Test ( int ) is inaccessible due to its protection level ' ② In following C # code , CS0122 occurs but I understand that CS1729 would be more appropriate CS0122 : ' A.Test.Test ( int ) is inaccessible due to its protection level'CS1729 : ' A.Test ' does not contain a constructor that takes 0 argumentsQuestion : Is there any reason why CS0122 and CS1729 are swapped in ① and ② or is this C # compiler bug ? P.S . : Errors in ① and ② can be reproduced with Microsoft Visual C # 2010 Compiler version 4.030319.1 . namespace A { class Program { static void Main ( ) { Test test = new Test ( 1 ) ; } } class Test { Test ( int i ) { } } } namespace A { class Program { static void Main ( ) { Test test = new Test ( ) ; } } class Test { Test ( int i ) { } } }",Constructor accessibility C # compiler error CS0122 vs CS1729 "C_sharp : I am trying to upload an image and POST form data ( although ideally I 'd like it to be json ) to an endpoint in my Azure Mobile Services application.I have the ApiController method : This only works when I remove the [ FromBody ] string metadata , but then it works great . When [ FromBody ] string metadata is included ( as above ) , I get the error : However , I would like to POST additional metadata ( which can be long , so I do n't want to put it in the Uri ) .How can I keep the file upload logic , and also POST additional string data to my controller ? I am using Azure Mobile Services , so this code is inside an System.Web.Http.ApiController ( if that matters ) . [ HttpPost ] [ Route ( `` api/upload/ { databaseId } / { searchingEnabled } / { trackingEnabled } '' ) ] public async Task < IHttpActionResult > Upload ( string databaseId , string searchingEnabled , string trackingEnabled , [ FromBody ] string metadata ) { if ( ! Request.Content.IsMimeMultipartContent ( ) ) { return BadRequest ( `` No image is uploaded . `` ) ; } else { var provider = new MultipartMemoryStreamProvider ( ) ; await Request.Content.ReadAsMultipartAsync ( provider ) ; foreach ( var file in provider.Contents ) { // Process each image uploaded } } } The request entity 's media type 'multipart/form-data ' is not supported for this resource .",How can I upload an image and POST data to an Azure Mobile Services ApiController endpoint ? "C_sharp : I 'm trying to use an attached property to trigger a style change on a UIElement when an event has fired.Here is the case scenario : A user sees a TextBox , and focuses then unfocuses it . Somewhere in an attached property it notices this LostFocus event and sets a property ( somewhere ? ) to say that it HadFocus.The style on the TextBox then knows that it should style itself differently based on this HadFocus property.Here 's how I imagine the markup to look ... I 've tried a few combinations of the attached properties to get this working , my latest attempt throws a XamlParseException stating `` Property can not be null on Trigger . `` Anyone able to direct me ? < TextBox Behaviors : UIElementBehaviors.ObserveFocus= '' True '' > < TextBox.Style > < Style TargetType= '' TextBox '' > < Style.Triggers > < Trigger Property= '' Behaviors : UIElementBehaviors.HadFocus '' Value= '' True '' > < Setter Property= '' Background '' Value= '' Pink '' / > < /Trigger > < /Style.Triggers > < /Style > < /TextBox.Style > public class UIElementBehaviors { public static readonly DependencyProperty ObserveFocusProperty = DependencyProperty.RegisterAttached ( `` ObserveFocus '' , typeof ( bool ) , typeof ( UIElementBehaviors ) , new UIPropertyMetadata ( false , OnObserveFocusChanged ) ) ; public static bool GetObserveFocus ( DependencyObject obj ) { return ( bool ) obj.GetValue ( ObserveFocusProperty ) ; } public static void SetObserveFocus ( DependencyObject obj , bool value ) { obj.SetValue ( ObserveFocusProperty , value ) ; } private static void OnObserveFocusChanged ( DependencyObject d , DependencyPropertyChangedEventArgs e ) { var element = d as UIElement ; if ( element == null ) return ; element.LostFocus += OnElementLostFocus ; } static void OnElementLostFocus ( object sender , RoutedEventArgs e ) { var element = sender as UIElement ; if ( element == null ) return ; SetHadFocus ( sender as DependencyObject , true ) ; element.LostFocus -= OnElementLostFocus ; } private static readonly DependencyPropertyKey HadFocusPropertyKey = DependencyProperty.RegisterAttachedReadOnly ( `` HadFocusKey '' , typeof ( bool ) , typeof ( UIElementBehaviors ) , new FrameworkPropertyMetadata ( false ) ) ; public static readonly DependencyProperty HadFocusProperty = HadFocusPropertyKey.DependencyProperty ; public static bool GetHadFocus ( DependencyObject obj ) { return ( bool ) obj.GetValue ( HadFocusProperty ) ; } private static void SetHadFocus ( DependencyObject obj , bool value ) { obj.SetValue ( HadFocusPropertyKey , value ) ; } }",Attached property to update style trigger on event "C_sharp : I will have literally tens of millions of instances of some class MyClass and want to minimize its memory size . The question of measuring how much space an object takes in the memory was discussed in Find out the size of a .net objectI decided to follow Jon Skeet 's suggestion , and this is my code : I run the program on 64 bit Windows , Choose `` release '' , platform target : `` any cpu '' , and choose `` optimize code '' ( The options only matter if I explicitly target x86 ) The result is , sadly , 48 bytes per instance . My calculation would be 8 bytes per reference , plus 1 byte for bool plus some ~8byte overhead . What is going on ? Is this a conspiracy to keep RAM prices high and/or let non-Microsoft code bloat ? Well , ok , I guess my real question is : what am I doing wrong , or how can I minimize the size of MyClass ? Edit : I apologize for being sloppy in my question , I edited a couple of identifier names . My concrete and immediate concern was to build a `` 2-dim linked-list '' as a sparse boolean matrice implementation , where I can get an enumeration of set values in a given row/column easily . [ Of course that means I have to also store the x , y coordinates on the class , which makes my idea even less feasible ] // Edit : This line is `` dangerous and foolish '' : - ) // ( However , commenting it does not change the result ) // [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public class MyClass { public bool isit ; public MyClass nextRight ; public MyClass nextDown ; } class Program { static void Main ( string [ ] args ) { var a1 = new MyClass ( ) ; //to prevent JIT code mangling the result ( Skeet ) var before = GC.GetTotalMemory ( true ) ; MyClass [ ] arr = new MyClass [ 10000 ] ; for ( int i = 0 ; i < 10000 ; i++ ) arr [ i ] = new MyClass ( ) ; var after = GC.GetTotalMemory ( true ) ; var per = ( after - before ) / 10000.0 ; Console.WriteLine ( `` Before : { 0 } After : { 1 } Per : { 2 } '' , before , after , per ) ; Console.ReadLine ( ) ; } }",How come my class take so much space in memory ? "C_sharp : I provided following query ( simplified version ) to return an IQueryable from my service : And also I have following codes in my service class according to my query : And I have seen this following errors : Generated error corresponding to solution ( 1 ) : The LINQ expression node type 'Invoke ' is not supported in LINQ to Entities.Generated error corresponding to solution ( 2 ) : Its a compilation error : Methods , delegate or event is expectedThanks a lot for any advanced help . var query = ( from item in _entityRepository.DbSet ( ) where MyCondition orderby Entity.EntityID descending select new DTOModel { Id = Entity.EntityID , ... , //My problem is here , when I trying to call a function into linq query : //Size = Entity.IsPersian ? ( Entity.EntitySize.ConvertNumbersToPersian ( ) ) : ( Entity.EntitySize ) //Solution ( 1 ) : //Size = ConvertMethod1 ( Entity ) //Solution ( 2 ) : //Size = ConvertMethod2 ( Entity ) } ) ; //Corresponding to solution ( 1 ) : Func < Entity , string > ConvertMethod1 = p = > ( p.IsPersian ? p.EntitySize.ConvertNumbersToPersian ( ) : p.EntitySize ) ; //Corresponding to solution ( 2 ) : Expression < Func < Entity , string > > ConvertMethod2 = ( p ) = > ( p.IsPersian ? p.EntitySize.ConvertNumbersToPersian ( ) : p.EntitySize ) ;",How to use Func in a linq query that provide an IQueryable output C_sharp : When I declare a method like this : And call it with this : What DoWork method will it call and why ? I ca n't seem to find it in any MSDN documentation . void DoWork < T > ( T a ) { } void DoWork ( int a ) { } int a = 1 ; DoWork ( a ) ;,Generic vs Non-Generic Overload Calling "C_sharp : I am trying to configure a multi-tenancy application using Identity Framework Core.I have successfully created a custom ApplicationUser to override IdentityUser with TenantId using instructions here : https : //www.scottbrady91.com/ASPNET-Identity/Quick-and-Easy-ASPNET-Identity-Multitenancy ( these are instructions are not for Identity Framework Core but they helped ) .I am stuck at the point when I am creating the database tables.My intention with this is to replace the UserNameIndex which is defined in base.OnModelCreating ( ) so that it is an index on two columns rather than just NormalizedUsername . But this just results in the error : The indexes { 'NormalizedUserName ' , 'TenantId ' } on 'User ' and { 'NormalizedUserName ' } on 'User ' are both mapped to 'Security.AspNetUser.UserNameIndex ' but with different columns ( { 'NormalizedUserName ' , 'TenantId ' } and { 'NormalizedUserName ' } ) .Obviously I want to undo the Index that is created in the base.OnModelCreating ( ) call before I add it in my code , but ca n't find a method to do that.Is there a way to remove an Index from ModelBuilder that has been created further up the model creation chain ? protected override void OnModelCreating ( ModelBuilder builder ) { base.OnModelCreating ( builder ) ; builder.Entity < Models.User > ( entity = > { entity.HasIndex ( a = > new { a.NormalizedUserName , a.TenantId } ) .HasName ( `` UserNameIndex '' ) .IsUnique ( ) ; } ) ; }",Undo HasIndex in OnModelCreating "C_sharp : I 'm facing a problem with AutoMapper 2.1.267.0 when working with objects containing collections of derived classes.I 've isolated my problem in a simpler scenario with the following classes : and these mappingsHere is the initializationand a diagram summarizing everything ( Red arrows represent AutoMapper mappings ) I 've mapped a ContainerA instance to ContainerB . This first scenario works properly . The destination object is fully filled as shown in the image bellow : But if I add this mappingthe result isThe `` Text '' properties of all elements of the collection become null . As you can see in the image , the `` Text '' property of the containerB.ClassB object is still mapped correctly . This only occurs with collections . I do n't know what 's happening . Any clues ? Thanks public class ClassABase { public string Name { get ; set ; } } public class ClassA : ClassABase { public string Description { get ; set ; } } public class ClassBBase { public string Title { get ; set ; } } public class ClassB : ClassBBase { public string Text { get ; set ; } } public class ContainerA { public IList < ClassA > ClassAList { get ; set ; } public ClassA ClassA { get ; set ; } } public class ContainerB { public IList < ClassB > ClassBList { get ; set ; } public ClassB ClassB { get ; set ; } } public class ClassABaseToClassBBase : Profile { protected override void Configure ( ) { CreateMap < ClassABase , ClassBBase > ( ) .Include < ClassA , ClassB > ( ) .ForMember ( dest = > dest.Title , opt = > opt.MapFrom ( src = > src.Name ) ) ; Mapper.AssertConfigurationIsValid ( ) ; } } public class ClassAToClassB : Profile { protected override void Configure ( ) { CreateMap < ClassA , ClassB > ( ) .ForMember ( dest = > dest.Text , opt = > opt.MapFrom ( src = > src.Description ) ) ; Mapper.AssertConfigurationIsValid ( ) ; } } public class ContainerAToContainerB : Profile { protected override void Configure ( ) { CreateMap < ContainerA , ContainerB > ( ) .ForMember ( dest = > dest.ClassBList , opt = > opt.MapFrom ( src = > Mapper.Map < IList < ClassA > , IList < ClassB > > ( src.ClassAList ) ) ) .ForMember ( dest = > dest.ClassB , opt = > opt.MapFrom ( src = > src.ClassA ) ) ; } } Mapper.Initialize ( x = > { x.AddProfile < ClassABaseToClassBBase > ( ) ; x.AddProfile < ClassAToClassB > ( ) ; x.AddProfile < ContainerAToContainerB > ( ) ; } ) ; public class ClassBBaseToClassB : Profile { protected override void Configure ( ) { CreateMap < ClassBBase , ClassB > ( ) .ForMember ( dest = > dest.Text , opt = > opt.Ignore ( ) ) ; Mapper.AssertConfigurationIsValid ( ) ; } } Mapper.Initialize ( x = > { x.AddProfile < ClassABaseToClassBBase > ( ) ; x.AddProfile < ClassAToClassB > ( ) ; x.AddProfile < ClassBBaseToClassB > ( ) ; x.AddProfile < ContainerAToContainerB > ( ) ; } ) ;",AutoMapper not working with collection of derived classes "C_sharp : Being a new user of MassTransit and RabbitMQ I 'm currently trying to make my ASP.NET core service to work with MassTransit.Taking this documentation section to configure MassTransit and ASP.NET Core I 'm unable to get it working . Currently ( part of ) the Startup.cs looks like The exchange is created automatically in RabbitMQ on startup , but no queue is bind to the exchange which I would expect . After invoking my API endpoint I can see activity on the exchange , but of course the consumers doing nothing as there is no queue . What ( obvious ) part am I missing ? services.AddMassTransit ( x = > { x.AddConsumer < MailConsumer > ( ) ; x.AddConsumer < MailFailedConsumer > ( ) ; x.AddBus ( provider = > ConfigureBus ( provider , rabbitMqConfigurations ) ) ; } ) ; private IBusControl ConfigureBus ( IServiceProvider provider , RabbitMqConfigSection rabbitMqConfigurations ) = > Bus.Factory.CreateUsingRabbitMq ( cfg = > { var host = cfg.Host ( rabbitMqConfigurations.Host , `` / '' , hst = > { hst.Username ( rabbitMqConfigurations.Username ) ; hst.Password ( rabbitMqConfigurations.Password ) ; } ) ; cfg.ReceiveEndpoint ( host , $ '' { typeof ( MailSent ) .Namespace } . { typeof ( MailSent ) .Name } '' , endpoint = > { endpoint.Consumer < MailConsumer > ( provider ) ; } ) ; cfg.ReceiveEndpoint ( host , $ '' { typeof ( MailSentFailed ) .Namespace } . { typeof ( MailSentFailed ) .Name } '' , endpoint = > { endpoint.Consumer < MailFailedConsumer > ( provider ) ; } ) ; } ) ;",ASP.NET Core service not creating RabbitMQ queue C_sharp : Is it possible to create some extension method in C # 5.0 to give the same results as the C # 6.0 Elvis ( ? . ) operator ? For example : //C # 6.0 wayvar g1 = parent ? .child ? .child ? .child ; if ( g1 ! = null ) // TODO//C # 5.0 wayvar g1 = parent.elvisExtension ( ) .child.elvisExtension ( ) .child.elvisExtension ( ) .child ; if ( g1 ! = null ) // TODO,Elvis ( ? . ) Extension Method in C # 5.0 "C_sharp : I have small application which calls phone numbers in Skype and allows to record conversations.But it does n't work with Skype versions after 7.5 . I tried both Skype4COM and direct API : For Skype4COM call always gets status clsCancelled , FailureReason is cfrMiscError . Below example code : For direct API call status is MISSED . I 'm using following command to start a call CALL +17606604690 . It is possible to start call with somebody from your contact list by starting IM with him and bringing Skype client in focus , but this approach does n't work for mobile numbers.I guess Skype API changed after version 7.5 , because I see that other applications still able to place calls . I 'm also aware about Skype URLs , but they have big delays and wo n't let you know if call fails . Skype skype = new SKYPE4COMLib.Skype ( ) ; if ( ! skype.Client.IsRunning ) { skype.Client.Start ( true , true ) ; } skype.Attach ( skype.Protocol , true ) ; Call call = skype.PlaceCall ( `` +17606604690 '' ) ;",Skype API call always cancelled "C_sharp : Is it possible to project every property of an object and add more , without specifically listing them all . For instance , instead of doing this : Can we do something like this : Where it will take every property from e with the same name , and add the `` NumberOfItems '' property onto that ? var projection = from e in context.entities select new QuestionnaireVersionExtended { Id = e.Id , Version = e.Version , CreationDate = e.CreationDate , ... many more properties ... NumberOfItems = ( e.Children.Count ( ) ) } ; var projection = from e in context.entities select new QuestionnaireVersionExtended { e , NumberOfItems = ( e.Children.Count ( ) ) } ;",Full object projection with additional values in LINQ "C_sharp : We have a webservice function that runs a list of tasks in the background . When all tasks are complete , it returns . I 've revisited the function for C # 5 . I 've managed to get the following snippet working : The task.Result waits for the individual task to be done . I 've tested this by adding a three second delay to the DoWork method and verifying that it finishes in less than 5 seconds , for a list of 10 tasks.Now I 've tried to rewrite the function using the new async / await syntax . But I ca n't seem to get it to work . If it compiles , it runs synchronously , as verified by adding a wait.Any ideas on how you can rewrite the above snippet using async / await ? var result = new List < int > ( ) ; var tasks = new List < Task < int > > ( ) ; foreach ( var row in rowlist ) tasks.Add ( Task.Factory.StartNew ( ( ) = > DoWork ( row ) ) ) ; foreach ( var task in tasks ) result.Add ( task.Result ) ;",Rewrite multi-thread wait using async/await "C_sharp : This operation returns a 0 : But this operation returns a 1 : Because the convertedValue is a float , and it is in parenthesis *100f should n't it still be treated as float operation ? string value = “ 0.01 ” ; float convertedValue = float.Parse ( value ) ; return ( int ) ( convertedValue * 100.0f ) ; string value = “ 0.01 ” ; float convertedValue = float.Parse ( value ) * 100.0f ; return ( int ) ( convertedValue ) ;",Is this a bug ? Float operation being treated as integer "C_sharp : I am trying to get OpenHardwareMonitor to read temperature data out of the Winbond W83793 chip on my Supermicro X7DWA motherboard . The problem is that I do n't have any low-level programming experience , and the available docs online do not seem to be sufficient in explaining how to access the temperatures . However , over the month that I 've been working on this problem , I have discovered a few values and low-level methods that may be the key to solving my problem . I just need to figure out how to use them to get what I want . That 's where I turn to you , because you might understand what this information means , and how to apply it , unlike me . I 've already done my fair share of poking around , resulting in many blue screens and computer restarts . Enough guessing , I need to piece these clues together . Here is what I know so far : To read from the chip , I will somehow need to access the SMBus , because that is the way monitoring programs , such as CPUID HWMonitor , are getting the information . OpenHardwareMonitor , as far as I know , does not have any code in it to access the SMBus , which is why it may not be reading from the chip . However , OpenHardwareMonitor has the following methods included in its Ring0 class , which it uses to access information from other chips . I may be able to use these methods to my advantage : Among other information , HWMonitor reports the following information about the Winbond W83793 chip to me when I save a report : Register Space : SMBus , base address = 0x01100 SMBus request : channel 0x0 , address 0x2FIt looks like these are important values , but I do n't know exactly what they mean , and how I can use them in conjunction with the Ring0 methods above . Hmm ... so many clues . The other values HWMonitor shows me are the actual voltages , temperatures , and fan speeds , and an array of hexadecimal values that represents data from somewhere on the chip , which I will reproduce here if you want to look at it.Finally , in the W83793 data sheet , on page 53 ( if you have the document open ) , here are the addresses in hex of the temperatures I would like to read ( I believe ) : TD1 Readout - Bank 0 Address 1C TD2 Readout - Bank 0 Address 1D TD3 Readout - Bank 0 Address 1E TD4 Readout - Bank 0 Address 1F Low bit Readout - Bank 0 Address 22 TR1 Readout - Bank 0 Address 20 TR2 Readout - Bank 0 Address 21That is all I know so far . The OpenHardwareMonitor , W83793 chip , and Ring0 code are available via the links provided above . As I said earlier , I 've been at it for a month , and I just have n't been able to solve this mystery yet . I hope you can help me . All this information may seem a bit intimidating , but I 'm sure it will make sense to someone with some low-level programming experience.To summarize my question , use the clues provided above to figure out how to get OpenHardwareMonitor to read temperatures out of the W83793 chip . I do n't need details on creating a chip in OpenHardwareMonitor . I already have a class ready . I just need the sequence and format to write Ring0 commands in , if that 's what I need to do.EDIT : I found some more information . I printed an SMBus device report from HWMonitor , and among other things , I got this line , included here because it says 0x2F : SMB device : I/O = 0x1100 , address 0x2F , channel = 0This must mean I need to somehow combine the addresses of the I/O with the address of the chip , which seems to be 0x2F . I tried adding them together but then I get all temperature readings to be 255 , so that was n't the right guess . void Ring0.WriteIOPort ( uint port , byte value ) ; byte Ring0.ReadIOPort ( uint port ) ;",Can you piece together the following clues to help me read temperatures out of the Winbond W83793 chip ? "C_sharp : I 'm learning to use Ninject and Interceptor pattern.I have the following interceptor.And have a class named MyClass which got nothing but 2 simple methods , virtual to allow the interceptors to work on them . ( Two methods are Echo and double , which does what their name says . ) I added Ninject , Ninject.Extensions.Interception and Ninject.Extensions.Interception.DynamicProxy to my project via NuGet.Added following using statements.My Main method , which does the bootstrapping looks like this.I 'm getting the following error at the specified line.Can anyone tell me what I 'm doing wrong ? public class MyInterceptor : IInterceptor { public void Intercept ( IInvocation invocation ) { Console.WriteLine ( `` Pre Execute : `` + invocation.Request.Method.Name ) ; foreach ( var param in invocation.Request.Arguments ) { Console.WriteLine ( `` param : `` + param ) ; } invocation.Proceed ( ) ; Console.WriteLine ( `` Post Execute : `` + invocation.Request.Method.Name ) ; Console.WriteLine ( `` Returned : `` + invocation.ReturnValue ) ; } } using Ninject ; using Ninject.Extensions.Interception.Infrastructure.Language ; using Ninject.Extensions.Interception ; static void Main ( string [ ] args ) { MyClass o = null ; using ( IKernel kernel = new StandardKernel ( ) ) { kernel.Bind < MyClass > ( ) .ToSelf ( ) .Intercept ( ) .With ( new MyInterceptor ( ) ) ; o = kernel.Get < MyClass > ( ) ; } o.Echo ( `` Hello World ! `` ) ; // Error o.Double ( 5 ) ; } Error loading Ninject component IProxyRequestFactoryNo such component has been registered in the kernel 's component container.Suggestions : 1 ) If you have created a custom subclass for KernelBase , ensure that you have properly implemented the AddComponents ( ) method . 2 ) Ensure that you have not removed the component from the container via a call to RemoveAll ( ) . 3 ) Ensure you have not accidentally created more than one kernel..",Interception with Ninject . Fails to load IProxyRequestFactory "C_sharp : I 'm trying to make a filter for a page in serenity.I have a page called Companies , and one button to open another page , CompanyUsers , users from this company.It 's already opening the new page , but it 's giving me all the users , I want to filter by the row I have clicked.I have tried changing the Controller of CompanyUsers adding a parameter , but after this I do n't know how to set the filter in CompanyUsers.My Onclick in CompaniesGrid.tsHow can I do that with serenity ? Is there an easy way to do that ? Thanks ! ! protected onClick ( e : JQueryEventObject , row : number , cell : number ) : void { super.onClick ( e , row , cell ) ; let item = this.itemAt ( row ) ; if ( $ ( e.target ) .hasClass ( 'usuario-row ' ) ) { window.location.href = '/Cadastros/EmpresasUsuarios ? empresaId= ' + item.EmpresaId ; } }",How to add a filter to a page in serenity ? "C_sharp : Does not work : Error is no implicit conversion between method group and method groupWorks : I 'm just curious why ? Am I missing something ? Func < string , byte [ ] > getFileContents = ( Mode ! = null & & Mode.ToUpper ( ) == `` TEXT '' ) ? TextFileContents : BinaryFileContents ; private static byte [ ] BinaryFileContents ( string file ) { return System.IO.File.ReadAllBytes ( file ) ; } private static byte [ ] TextFileContents ( string file ) { using ( var sourceStream = new StreamReader ( file ) ) { return Encoding.UTF8.GetBytes ( sourceStream.ReadToEnd ( ) ) ; } } Func < string , byte [ ] > getFileContents2 ; if ( Mode ! = null & & Mode.ToUpper ( ) == `` TEXT '' ) { getFileContents2 = TextFileContents ; } else { getFileContents2 = BinaryFileContents ; }","In C # , why does n't ? : operator work with lambda or method groups ?" "C_sharp : In C # UWP how to make inner shadow effect ? Like this : I have created one grid with just a border , but shadow is populating the whole grid.How to make inner shadow effect with this control ? < controls : DropShadowPanel BlurRadius= '' 5 '' ShadowOpacity= '' 0.5 '' OffsetX= '' 0 '' OffsetY= '' 0 '' Color= '' Black '' > < Grid BorderBrush= '' White '' BorderThickness= '' 5 '' / > < /controls : DropShadowPanel >",C # UWP Toolkit DropShadowPanel inner shadow "C_sharp : I 'm trying to convert a nested json to simple json by recursively traversing . ( Structure of input json is unknown ) for example , I want json like thisto be converted something like thiseach fields in nested object will be changed to key which represents its actual path.this is what I have done so far.and getting wrong resultwill appreciate any help on correcting my code , or any other approach to archive this . { `` FirstName '' : `` Rahul '' , `` LastName '' : `` B '' , `` EmpType '' : { `` RID '' : 2 , `` Title '' : `` Full Time '' } , `` CTC '' : `` 3.5 '' , `` Exp '' : `` 1 '' , `` ComplexObj '' : { `` RID '' : 3 , `` Title '' : { `` Test '' : `` RID '' , `` TWO '' : { `` Test '' : 12 } } } } { `` FirstName '' : `` Rahul '' , `` LastName '' : `` B '' , `` EmpType__RID '' : 2 , `` EmpType__Title '' : `` Full Time '' , `` CTC '' : `` 3.5 '' , `` Exp '' : `` 1 '' , `` ComplexObj__RID '' : 3 , `` ComplexObj__Title__Test '' : `` RID '' , `` ComplexObj__Title__TWO__Test '' : 12 } public static void ConvertNestedJsonToSimpleJson ( JObject jobject , ref JObject jobjectRef , string currentNodeName = `` '' , string rootPath = `` '' ) { string propName = `` '' ; if ( currentNodeName.Equals ( rootPath ) ) { propName = currentNodeName ; } else { propName = ( rootPath == `` '' & & currentNodeName == `` '' ) ? rootPath + `` '' + currentNodeName : rootPath + `` __ '' + currentNodeName ; } foreach ( JProperty jprop in jobject.Properties ( ) ) { if ( jprop.Children < JObject > ( ) .Count ( ) == 0 ) { jobjectRef.Add ( propName == `` '' ? jprop.Name : propName + `` __ '' + jprop.Name , jprop.Value ) ; } else { currentNodeName = jprop.Name ; rootPath = rootPath == `` '' ? jprop.Name : rootPath ; ConvertNestedJsonToSimpleJson ( JObject.Parse ( jprop.Value.ToString ( ) ) , ref jobjectRef , currentNodeName , rootPath ) ; } } } { `` FirstName '' : `` Rahul '' , `` LastName '' : `` B '' , `` EmpType__RID '' : 2 , `` EmpType__Title '' : `` Full Time '' , `` CTC '' : `` 3.5 '' , `` Exp '' : `` 1 '' , `` EmpType__ComplexObj__RID '' : 3 , `` EmpType__Title__Test '' : `` RID '' , `` EmpType__two__Test '' : 12 }",Convert nested JSON to simple JSON "C_sharp : I was updating one of our projects to C # 6.0 when I found a method that was literally doing nothing : Now I was wondering if there is any possibility to rewrite it as an expression-bodied method as it just contains return.Try 1 : Exceptions : ; expectedInvalid token 'return ' in class , struct , or interface member declarationInvalid expression term 'return'Try 2 : Exception : Invalid expression term ' ; 'Is there any possibility to achieve this ( although this method does n't really make sense ) ? private void SomeMethod ( ) { return ; } private void SomeMethod ( ) = > return ; private void SomeMethod ( ) = > ;",Expression-bodied method : Return nothing "C_sharp : In razor views I can access model state object : How can i inject and access ViewData or ModelState objects in razor TagHelper ? I tried the following , however the ViewData and ModelState are always null : @ ViewData.ModelState public class ModelStateTagHelper : TagHelper { public ViewDataDictionary ViewData { get ; set ; } public ModelStateDictionary ModelState { get ; set ; } public override void Process ( TagHelperContext context , TagHelperOutput output ) { } }",How can I inject ViewDataDictionary or ModelStateDictionary into TagHelper ? "C_sharp : I have created a custom water mark text box which is extended from text box . control template for the same is shown below.but while typing the textbox enters to a condition where it is having no cursor but we can type into it occurs with a probability of 1/2 chars.I wonder how it happens . Anyone is having idea how it is happening ? < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type controls : WaterMarkTextBox } '' > < ControlTemplate.Resources > < Storyboard x : Key= '' Storyboard1 '' > < ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty= '' ( FrameworkElement.Margin ) '' Storyboard.TargetName= '' PART_FieldTextBlock '' > < SplineThicknessKeyFrame KeyTime= '' 0:0:0.15 '' Value= '' 0,0,10,0 '' / > < /ThicknessAnimationUsingKeyFrames > < /Storyboard > < Storyboard x : Key= '' Storyboard2 '' > < ThicknessAnimationUsingKeyFrames Storyboard.TargetProperty= '' ( FrameworkElement.Margin ) '' Storyboard.TargetName= '' PART_FieldTextBlock '' > < SplineThicknessKeyFrame KeyTime= '' 0:0:0.25 '' Value= '' 0,0 , -500,0 '' / > < /ThicknessAnimationUsingKeyFrames > < /Storyboard > < /ControlTemplate.Resources > < Grid x : Name= '' PART_GridControl '' ClipToBounds= '' True '' Height= '' { TemplateBinding Height } '' Width= '' { TemplateBinding Width } '' > < TextBlock x : Name= '' PART_PlaceHolderTextBlock '' Style= '' { StaticResource SWMLightTextBlockStyle } '' Foreground= '' # BDBBBB '' FontSize= '' { StaticResource SmallFontSize } '' Text= '' { TemplateBinding PlaceHolderText } '' VerticalAlignment= '' Center '' Margin= '' 20,0,10,0 '' / > < Border Name= '' border '' CornerRadius= '' 0 '' Padding= '' 2 '' BorderThickness= '' 1 '' BorderBrush= '' DeepSkyBlue '' > < ScrollViewer x : Name= '' PART_ContentHost '' / > < /Border > < TextBlock x : Name= '' PART_FieldTextBlock '' HorizontalAlignment= '' Right '' Foreground= '' # BDBBBB '' Margin= '' 0,0 , -500,0 '' Style= '' { StaticResource SWMLightTextBlockStyle } '' FontSize= '' { StaticResource SmallFontSize } '' TextWrapping= '' Wrap '' Text= '' { TemplateBinding FieldText } '' VerticalAlignment= '' Center '' / > < /Grid > < /ControlTemplate > < /Setter.Value > < /Setter >",Text Box sometimes cursor is missing "C_sharp : I have 2 classes like thisI serialize A instance with type name handlingWhat would be the easiest way to get B instance from this ? Before you ask why , it 's about importing A as B ( they have base properties and those what names are matching as you see , so this operation is reasonable ) .Trying to deserialize given json as B will throwI could think of following : Deserialize json as A , create instance of B and copy all values ( bad ) ; Substitute ( maybe even remove ? ) $ type in json and try to deserialize it as B ( better , still bad ) ; Use SerializationBinder and deserialize json as B ( good ) : Is there better way ? In my scenario there are many such types and having hundereds of such binders ( as well as reading json first as A to determine which binder to apply ) is very tedious.I am looking for a simple way to ignore $ type and specify wanted type directly ( generic method ) , because I know type I need , but I do n't know which type is in json and I want to ignore it . class A : Base { public string CommonField ; public int IntField ; } class B : Base { public string CommonField ; public double DoubleField ; } { `` $ type '' : `` MyApp.A , MyApp '' , `` CommonField '' : `` SomeValue '' , `` IntField '' : 123 , `` SomeBaseField '' : 321 } Newtonsoft.Json.JsonSerializationException : Type specified in JSON 'MyApp.A , MyApp , Version=0.0.1.1 , Culture=neutral , PublicKeyToken=null ' is not compatible with 'MyApp.B , MyApp , Version=0.0.1.1 , Culture=neutral , PublicKeyToken=null ' . Path ' $ type ' , line 2 , position 42. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolveTypeName ( JsonReader reader , Type & objectType , JsonContract & contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , String qualifiedTypeName ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadMetadataProperties ( JsonReader reader , Type & objectType , JsonContract & contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue , Object & newValue , String & id ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize ( JsonReader reader , Type objectType , Boolean checkAdditionalContent ) public class JsonABBinder : DefaultSerializationBinder { public override Type BindToType ( string assemblyName , string typeName ) { if ( typeName == `` MyApp.A '' ) return typeof ( B ) ; return base.BindToType ( assemblyName , typeName ) ; } }",How to ignore $ type during deserialization "C_sharp : I know this has several canonical answers ( that I 've used successfully in the past ! ) See https : //stackoverflow.com/a/1778410/1675729 and https : //stackoverflow.com/a/1565766/1675729 . For reference , these methods involve using the SetValue method on the PropertyInfo of the property , or otherwise invoking the setter method with reflection , or in extreme cases , setting the backing field directly . However , none of these methods seem to be working for me now , and I 'm curious if something has changed that has broken this functionality.Consider the following : The Foo property has a setter , it 's just private . It also fails if I change the setter to protected , which seems even more bizarre , since it 's no longer the C # 6 initializer-only setter . This fails with both .NET 4.5 and .NET Core 2 as the runtime . What am I missing ? using System ; using System.Reflection ; public class Program { public static void Main ( ) { var exampleInstance = new Example ( ) ; var exampleType = typeof ( Example ) ; var fooProperty = exampleType.GetProperty ( `` Foo '' ) ; // this works fine - the `` GetSetMethod '' method returns null , however // fails with the following : // [ System.MethodAccessException : Attempt by method 'Program.Main ( ) ' to access method 'Example.set_Foo ( Int32 ) ' failed . ] //fooProperty.SetValue ( exampleInstance , 24 ) ; // same error here : //Run-time exception ( line 14 ) : Attempt by method 'Program.Main ( ) ' to access method 'Example.set_Foo ( Int32 ) ' failed . //exampleType.InvokeMember ( fooProperty.Name , BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance , null , exampleInstance , new object [ ] { 24 } ) ; } } public class Example { public int Foo { get ; private set ; } }",Set private setter on property via reflection "C_sharp : I have a BaseClass , which is abstract , and has many abstract properties.I have a dozen or so ( it will probably grow ) entities that are part of the Entity Framework that each derive from BaseClass.I 'm trying to avoid having to do : for each property and each entity , since that seems very wasteful and creates a lot of code duplication . I experimented with getting all the Entities in a namespace that derive from the BaseClass by : However , the next logical steps seems to be : but will not compile , because `` entity is a variable , but is used like a type '' . modelBuilder.Entity < Entity1 > ( ) .HasKey ( t = > t.Id ) ; modelBuilder.Entity < Entity2 > ( ) .HasKey ( t = > t.Id ) ; modelBuilder.Entity < Entity3 > ( ) .HasKey ( t = > t.Id ) ; ... var derivedEntities = Assembly.GetExecutingAssembly ( ) .GetTypes ( ) . Where ( t = > t.Namespace == `` My.Entities '' & & t.IsAssignableFrom ( typeof ( BaseClass ) ) ) ; foreach ( var entity in derivedEntities ) { modelBuilder.Entity < entity > ( ) .HasKey ( t = > t.Id ) ; }",EF Fluent API : Set property for each entity derived from a base abstract class "C_sharp : I 'm trying to print an image ( QR code ) from Silverlight 4 app , however the image is antialised when printed ( I have tried both XPS file printer and hardware printer ) image is blury , and is not readable by barcode reader.Image from printed XPS document http : //img805.imageshack.us/img805/7677/qraliasing.pngI 'm using this simple code to print it : WriteableBitmap bitmap = new WriteableBitmap ( width , height ) ; //write bitmap pixelsImage image = new Image ( ) { Stretch = Stretch.None } ; image.Source = bitmap ; image.Width = bitmap.PixelWidth ; image.Height = bitmap.PixelHeight ; //PrintPrintDocument printDocument = new PrintDocument ( ) ; printDocument.PrintPage += ( sender , args ) = > { args.PageVisual = image ; } ; printDocument.Print ( `` QrCode '' ) ;",Silverlight printing anti-aliasing "C_sharp : In a large WPF application , we have the possibility to change the language at runtime . We use WPF Localize Extension and resx-files for localization and it works great , except for converters used in UI . If in a binding a ValueConverter is culture-specific , the resulting text is not updated on the language change.How can I make WPF update all converted bindings application-wide ? EDIT : At the moment we have experimented by making the ValueConverters MultiValueConverters and adding the locale as an extra value . This way the value source values change , and the result is updated . But this is cumbersome and ugly.Related : Run-time culture change and IValueConverter in a binding ( I do n't have the option to raise propertychanged for every field manually ) < MultiBinding Converter= '' { StaticResource _codeMultiConverter } '' ConverterParameter= '' ZSLOOPAKT '' > < Binding Path= '' ActivityCode '' / > < Binding Source= '' { x : Static lex : LocalizeDictionary.Instance } '' Path= '' Culture '' / > < Binding Source= '' { x : Static RIEnums : CodeTypeInfo+CodeDisplayMode.Both } '' / > < /MultiBinding >","WPF Runtime Locale Change , reevaluate ValueConverters UI" "C_sharp : when will t1 ( reference variable ) will get memory , at compile time or run time.I think it should be run time . But when I put a breakpoint at Main Method and Put a Watch for t1 , it was null . So it means t1 was in memory.Please correct me If I am wrong.Edit : I heard Static Member Variables are assigned at compile time . public static void Main ( ) { Test t1 = new Test ( ) ; }",Memory Allocation Question ? "C_sharp : I have an asp.net MVC application that has a controller action that takes a string as input and sends a response wav file of the synthesized speech . Here is a simplified example : The application ( and this action method in particular ) is running fine in a server environment on 2008 R2 servers , 2012 ( non-R2 ) servers , and my 8.1 dev PC . It is also running fine on a standard Azure 2012 R2 virtual machine . However , when I deploy it to three 2012 R2 servers ( its eventual permanent home ) , the action method never produces an HTTP response -- the IIS Worker process maxes one of the CPU cores indefinitely . There is nothing in the event viewer and nothing jumps out at me when watching the server with Procmon . I 've attached to the process with remote debugging , and the synth.Speak ( text ) never returns . When the synth.Speak ( text ) call is executed I immediately see the runaway w3wp.exe process in the server 's task manager.My first inclination was to believe some process was interfering with speech synthesis in general on the servers , but the Windows Narrator works correctly , and a simple console app like this also works correctly : So obviously I ca n't blame the server 's speech synthesis in general . So maybe there is a problem in my code , or something strange in IIS configuration ? How can I make this controller action work correctly on these servers ? This is a simple way to test the action method ( just have to get the url value right for the routing ) : public async Task < ActionResult > Speak ( string text ) { Task < FileContentResult > task = Task.Run ( ( ) = > { using ( var synth = new System.Speech.Synthesis.SpeechSynthesizer ( ) ) using ( var stream = new MemoryStream ( ) ) { synth.SetOutputToWaveStream ( stream ) ; synth.Speak ( text ) ; var bytes = stream.GetBuffer ( ) ; return File ( bytes , `` audio/x-wav '' ) ; } } ) ; return await task ; } static void Main ( string [ ] args ) { var synth = new System.Speech.Synthesis.SpeechSynthesizer ( ) ; synth.Speak ( `` hello '' ) ; } < div > < input type= '' text '' id= '' txt '' autofocus / > < button type= '' button '' id= '' btn '' > Speak < /button > < /div > < script > document.getElementById ( 'btn ' ) .addEventListener ( 'click ' , function ( ) { var text = document.getElementById ( 'txt ' ) .value ; var url = window.location.href + '/speak ? text= ' + encodeURIComponent ( text ) ; var audio = document.createElement ( 'audio ' ) ; var canPlayWavFileInAudioElement = audio.canPlayType ( 'audio/wav ' ) ; var bgSound = document.createElement ( 'bgsound ' ) ; bgSound.src = url ; var canPlayBgSoundElement = bgSound.getAttribute ( 'src ' ) ; if ( canPlayWavFileInAudioElement ) { // probably Firefox and Chrome audio.setAttribute ( 'src ' , url ) ; audio.setAttribute ( 'autoplay ' , `` ) ; document.getElementsByTagName ( 'body ' ) [ 0 ] .appendChild ( audio ) ; } else if ( canPlayBgSoundElement ) { // internet explorer document.getElementsByTagName ( 'body ' ) [ 0 ] .appendChild ( bgSound ) ; } else { alert ( 'This browser probably can\'t play a wav file ' ) ; } } ) ; < /script >",System.Speech.Synthesis hangs with high CPU on 2012 R2 "C_sharp : I discover a very strange behavior of WindowsFormsHost in WPF . I find that if a WPF control does n't have WindowsFormsHost as a child control , then IsKeyboardFocusWithinChanged fires properly -- it is fired whenever the WPF control gains or loses focuses , and the variable IsKeyboardFocusWithin is toggled as expected ( true when the control gains focus , false when loses focus ) .But , if I host a WindowsFormHost in WPF , then after a short while , the IsKeyboardFocusWithinChanged event is no longer fired for both the WPF mother control and the WindowsFormHost child control . I ca n't find in MSDN documentation or SO why so , any reason ? This is my code : MainWindow.xamlMainWindow.xaml.csWhen the lines involving WindowsFormHost are commented out , then IsKeyboardFocusWithin is true whenever the control gains focus , and false when the control loses focus.When the lines involving WindowsFormHost are there , then IsKeyboardFocusWithin is true , until I click on the control , and then host.IsKeyboardFocusWithin becomes false , and IsKeyboardFocusWithin also becomes false , and then , no matter what I do , IsKeyboardFocusWithinChanged event will never be fired again . < Window x : Class= '' WpfApplication1.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : WpfApplication1 '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' IsKeyboardFocusWithinChanged= '' Window_IsKeyboardFocusWithinChanged '' > < Grid Name= '' grid1 '' > < /Grid > < /Window > public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; host = new System.Windows.Forms.Integration.WindowsFormsHost ( ) ; var mtbDate = new System.Windows.Forms.MaskedTextBox ( `` 00/00/0000 '' ) ; host.Child = mtbDate ; host.IsKeyboardFocusWithinChanged += Host_IsKeyboardFocusWithinChanged ; grid1.Children.Add ( host ) ; } private void Host_IsKeyboardFocusWithinChanged ( object sender , DependencyPropertyChangedEventArgs e ) { Console.WriteLine ( host.IsKeyboardFocusWithin.ToString ( ) + '' blah '' ) ; } private System.Windows.Forms.Integration.WindowsFormsHost host ; private void Window_IsKeyboardFocusWithinChanged ( object sender , DependencyPropertyChangedEventArgs e ) { Console.WriteLine ( IsKeyboardFocusWithin.ToString ( ) ) ; } }",The presence of WindowsFormsHost causes the IsKeyboardFocusWithinChanged to be fired at most twice and not more "C_sharp : I defined a DataObject as : And used fluent API to make CompanyId and ServiceId a composite key : Even though a Primary Key has been set Entity Framework creates a column named Id when I run Add-Migration : How do I prevent EF from adding this column ? public class SensorType : EntityData { //PKs public string CompanyId { get ; set ; } public string ServiceId { get ; set ; } public string Type { get ; set ; } } modelBuilder.Entity < SensorType > ( ) .HasKey ( t = > new { t.CompanyId , t.ServiceId } ) ; //No autogeneration of PKsmodelBuilder.Entity < SensorType > ( ) .Property ( t = > t.ServiceId ) .HasDatabaseGeneratedOption ( System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None ) ; modelBuilder.Entity < SensorType > ( ) .Property ( t = > t.CompanyId ) .HasDatabaseGeneratedOption ( System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None ) ; CreateTable ( `` dbo.SensorTypes '' , c = > new { CompanyId = c.String ( nullable : false , maxLength : 128 ) , ServiceId = c.String ( nullable : false , maxLength : 128 ) , Type = c.String ( ) , Id = c.String ( annotations : new Dictionary < string , AnnotationValues > { { `` ServiceTableColumn '' , new AnnotationValues ( oldValue : null , newValue : `` Id '' ) ... } ) .PrimaryKey ( t = > new { t.CompanyId , t.ServiceId } ) .Index ( t = > t.CreatedAt , clustered : true ) ; }",Entity Framework 6 creates Id column even though other primary key is defined "C_sharp : I recently inherited an ASP.NET MVC project . In that project , the developer is using async everywhere . I 'm trying to assess if its a good idea or not . Specifically , I 'm reviewing the controller code at the moment.In the controllers , the developer wrote the stuff like the following : Is there any advantage to this instead of the traditional version : I could understand using async if await was used in the controller code . A lot of times , its not being used though . Is there any justification for this approach ? public async Task < ActionResult > Index ( ) { return View ( ) ; } public ActionResult Index ( ) { return View ( ) ; }",Always using Async in an ASP.NET MVC Controller "C_sharp : I want to walk over all the documents in every project in a given solution using Roslyn.This is the code I have now : The problem here is that as Roslyn is largely immutable.After the first `` msWorkspace.TryApplyChanges '' , the solution and the document are now replaced with new versions.So the next iteration will still walk over the old versions.Is there any way to do this in a Roslyn idiomatic way ? Or do I have to resort to some for ( int projectIndex = 0 ; projectIndex < solution.Projects.count ) { kind of hackery ? var msWorkspace = MSBuildWorkspace.Create ( ) ; var solution = await msWorkspace.OpenSolutionAsync ( solutionPath ) ; foreach ( var project in solution.Projects ) { foreach ( var document in project.Documents ) { if ( document.SourceCodeKind ! = SourceCodeKind.Regular ) continue ; var doc = document ; foreach ( var rewriter in rewriters ) { doc = await rewriter.Rewrite ( doc ) ; } if ( doc ! = document ) { Console.WriteLine ( `` changed { 0 } '' , doc.Name ) ; //save result //the solution is now changed and the next document to be processed will belong to the old solution msWorkspace.TryApplyChanges ( doc.Project.Solution ) ; } } }",Visit and modify all documents in a solution using Roslyn "C_sharp : Imagine a set of Entity Framework entities : Imagine as well a DOTNET 5 api GETIf there are no markets attached to the entity the data returns without issue , but as soon as I have a few linked items attached I get an error : HTTP Error 502.3 - Bad Gateway The specified CGI application encountered an error and the server terminated the process.I vaguely recall a previous application where every complex EF object had a `` primitives only '' type object to send and receive this object to and from the client , but I wonder if there is a way to communicate without intermediary objects ? eg : My concern is the coding overhead of translating every complex object back and forth from the client ( which , I 'll admit , I 'm not sure is even a bad thing , maybe it has to be done anyways ) .Since the scaffolded APIs seem to take and return entities directly I find myself wondering if there is a way to handle the complex part of the object directlyEdit # 1 : Per Noel 's comment below , if I change the code which is causing the error to the stack trace is Correctly thrown . If I remove the exception , the 500 gateway error appears . I agree that it looks like it 's probably a serialization error , but it 's tough to say.EDIT 2 - per a comment from Oleg below : The solution to a bad gateway is to first explicitly update a more recent version of NewtonSoft.Json in the dependencies in the project.json file : next you must alter the Startup.cs filewith those two settings in place , the bad gateway no longer occurs and an api call successfully returns the complex object as expected . public class Country { public string CountryCode { get ; set ; } public string Name { get ; set ; } public string Flag { get ; set ; } } public class Market { public string CountryCode { get ; set ; } public virtual Country Country { get ; set ; } public int ProductID { get ; set ; } public virtual Product Product { get ; set ; } } public class Product { public int ProductID { get ; set ; } public string Name { get ; set ; } public virtual ICollection < Market > Markets { get ; set ; } } // GET api/product [ HttpGet ] public async Task < IActionResult > GetProduct ( [ FromRoute ] int id ) { return Ok ( await _context.Products .Include ( p = > p.Markets ) .SingleAsync ( m = > m.ProductID == id ) ) ; } public class ProductViewModel { public int ProductID { get ; set ; } public string Name { get ; set ; } public List < MarketViewModel > Markets { get ; set ; } } public class MarketViewModel { public int ProductID { get ; set ; } public Country Country { get ; set ; } } [ HttpGet ( `` { id } '' , Name = `` GetProduct '' ) ] public async Task < IActionResult > GetProduct ( [ FromRoute ] int id ) { Product product = await _context.Products .Include ( t = > t.Markets ) .SingleAsync ( m = > m.ProductID == id ) ; throw new System.Exception ( `` error sample '' ) ; return Ok ( product ) ; } `` dependencies '' : { `` Newtonsoft.Json '' : `` 8.0.1-beta3 '' , public void ConfigureServices ( IServiceCollection services ) { services.AddMvc ( ) .AddJsonOptions ( options = > { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ; } ) ;",Is it possible to get complex Entity Framework objects from a REST api in .NET without creating ViewModel objects ? "C_sharp : I 'm working with an old C # LightSwitch HTML project that connects to SharePoint and I need to make a few changes . Unfortunately not enough to justify migrating to another technology/platform , but anyways ... I fire up my Visual Studio 2015 and the project wo n't build . I 've of course googled for and tried everything I can think of and long story short even if I create a new C # LightSwitch HTML project and try to build it , it fails . Here 's the error I get : An exception occurred when building the database for the application . An error occurred during deployment plan generation . Deployment can not continue . Error SQL0 : Required contributor with id 'Microsoft.LightSwitch.DataRetentionDeploymentPlanModifier.v5.0 ' could not be loaded . Error SQL0 : Required contributor with id 'Microsoft.LightSwitch.LocalDbLocationModifier.v5.0 ' could not be loaded . GraphicsApp C : \Program Files ( x86 ) \MSBuild\Microsoft\VisualStudio\v14.0\LightSwitch\v5.0\Microsoft.LightSwitch.targets 160If I go to line 160 ( double-clicking on the error ) I see this ( Starting at line 160 ) : I 've tried searching everything I can think of but I 'm not finding anything that even sounds remotely the same except this link . But it 's talking about V4 and only says that the solution was to : `` right clicking on the project in solution explorer ... [ and ] upgrade the project '' But that does n't help me at all because I do n't see any option to upgrade anything and again I have the same exact problem on the brand new project I create . < BuildSchema Inputs= '' @ ( ServerMetadataFiles ) '' ServerGeneratedMetadataFiles= '' @ ( ServerGeneratedMetadataFiles ) '' Collation= '' $ ( DatabaseCollation ) '' DatabaseProject= '' @ ( _DatabaseProject ) '' ProjectPath= '' $ ( MSBuildProjectFullPath ) '' OutputDirectory= '' Bin\Data '' SqlExpressInstanceName= '' $ ( SqlExpressInstanceName ) '' ExternalDataSources= '' @ ( ServerExternalDataSources ) '' Condition= '' ' $ ( SkipBuildSchema ) ' == `` '' / >",Visual Studio LightSwitch will not Build "C_sharp : I 've written a regular expression that automatically detects URLs in free text that users enter . This is not such a simple task as it may seem at first . Jeff Atwood writes about it in his post.His regular expression works , but needs extra code after detection is done.I 've managed to write a regular expression that does everything in a single go . This is how it looks like ( I 've broken it down into separate lines to make it more understandable what it does ) : As you may see , I 'm using named capture groups ( used later in Regex.Replace ( ) ) and I 've also included some local characters ( čšžćđ ) , that allow our localised URLs to be parsed as well . You can easily omit them if you 'd like.Anyway . Here 's what it does ( referring to line numbers ) :1 - detects if URL starts with open braces ( is contained inside braces ) and stores it in `` outer '' named capture group2 - checks if it starts with URL scheme also detecting whether scheme is SSL or not3 - start parsing URL itself ( will store it in `` url '' named capture group ) 4-8 - if statement that says : if `` sheme '' was present then www . part is optional , otherwise mandatory for a string to be a link ( so this regular expression detects all strings that start with either http or www ) 9 - first character after http : // or www . should be either a letter or a number ( this can be extended if you 'd like to cover even more links , but I 've decided not to because I ca n't think of a link that would start with some obscure character ) 10-14 - if statement that says : if `` outer '' ( braces ) was present capture everything up to the last closing braces otherwise capture all15 - closes the named capture group for URL16 - if open braces were present , capture closing braces as well and store it in `` ending '' named capture groupFirst and last line used to have \s* in them as well , so user could also write open braces and put a space inside before pasting link.Anyway . My code that does link replacement with actual anchor HTML elements looks exactly like this : As you can see I 'm using named capture groups to replace link with an Anchor tag : I could as well omit the http ( s ) part in anchor display to make links look friendlier , but for now I decided not to.QuestionI would like my links to be replaced with shortenings as well . So when user copies a very long link ( for instance if they would copy a link from google maps that usually generates long links ) I would like to shorten the visible part of the anchor tag . Link would work , but visible part of an anchor tag would be shortened to some number of characters . I could as well append ellipsis at the end of at all possible ( and make things even more perfect ) .Does Regex.Replace ( ) method support replacement notations so that I can still use a single call ? Something similar as string.Format ( ) method does when you 'd like to format values in string format ( decimals , dates etc ... ) . 1 ( ? < outer > \ ( ) ? 2 ( ? < scheme > http ( ? < secure > s ) ? : // ) ? 3 ( ? < url > 4 ( ? ( scheme ) 5 ( ? : www\ . ) ? 6 |7 www\.8 ) 9 [ a-z0-9 ] 10 ( ? ( outer ) 11 [ -a-z0-9/+ & @ # / % ? =~_ ( ) | ! : , . ; čšžćđ ] + ( ? =\ ) ) 12 |13 [ -a-z0-9/+ & @ # / % ? =~_ ( ) | ! : , . ; čšžćđ ] +14 ) 15 ) 16 ( ? < ending > ( ? ( outer ) \ ) ) ) value = Regex.Replace ( value , @ '' ( ? < outer > \ ( ) ? ( ? < scheme > http ( ? < secure > s ) ? : // ) ? ( ? < url > ( ? ( scheme ) ( ? : www\. ) ? |www\. ) [ a-z0-9 ] ( ? ( outer ) [ -a-z0-9/+ & @ # / % ? =~_ ( ) | ! : ,. ; čšžćđ ] + ( ? =\ ) ) | [ -a-z0-9/+ & @ # / % ? =~_ ( ) | ! : ,. ; čšžćđ ] + ) ) ( ? < ending > ( ? ( outer ) \ ) ) ) '' , `` $ { outer } < a href=\ '' http $ { secure } : // $ { url } \ '' > http $ { secure } : // $ { url } < /a > $ { ending } '' , RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase ) ; `` $ { outer } < a href=\ '' http $ { secure } : // $ { url } \ '' > http $ { secure } : // $ { url } < /a > $ { ending } ''",Advanced Regex : Smart auto detect and replace URLs with anchor tags C_sharp : I have a controller with many actions . All should be accessible to certain users only except one action : Even [ Authorize ( Roles = null ) ] does n't work . The method attribute will be ignored ! How could I get the exception for just one action ? Like AllowAnonymous allows it but visible to logged in users ? [ Authorize ( Roles = `` Admin '' ) ] public class SecretsController : Controller { [ Authorize ] public ActionResult Index ( ) { return View ( ... ) ; } ... },Make an exception on AuthorizeAttribute "C_sharp : Sometimes the exception type is unique enough to indicate the exact issue , such as an ArgumentOutOfRangeException . Othertimes , the exception is more general and could be thrown for several reasons . In this scenario , it seems the only additional information is found in the exception message property.In my current circumstance , I am getting a CommunicationException which throws the error message : The maximum message size quota for incoming messages ( 65536 ) has been exceededAs multiple different errors may be thrown via the CommunicationException , is it bad practice to use the message property to determine the cause , like so : Will these messages be constant and reliable on all systems ? Are there any other considerations , such as localization ? Conclusion : My scenario with the 'CommunicationException ' was a bad example , as I later realized that there was a QuotaExceededException in the InnerException property . Thanks to the responses , I knew to look for any data that existed in the exception to indicate the exact cause . In this case , it was the InnerException property.In terms of the question regarding whether or not the message property should be used to determine the cause , it seems to be the general consensus that it should be avoided unless there is no alternative . The message property value may not remain constant over varying systems due to localization . catch ( CommunicationException ex ) { if ( Regex.IsMatch ( ex.Message , `` The maximum message size quota for incoming messages . * has been exceeded '' ) ) { // handle thrown exception } throw ; }",Is it bad practice to use an exception message property to check for particular error ? "C_sharp : Possible Duplicate : What is the difference between new Thread ( void Target ( ) ) and new Thread ( new ThreadStart ( void Target ( ) ) ) ? I have a small question about Thread class . This class has 4 constructors : I use the 2nd constructor to create a Thread object : However , I can use a way to create this object without using any constructors I talk above.In this case , ScanDirectory is a void method , it is n't ThreadStart or ParameterizedThreadStart but Thread class still accepts this constructor . Why ? I think this is a .NET feature but I do n't know how it 's implemented . Note : ScanDirectory is a void method . public Thread ( ParameterizedThreadStart start ) ; public Thread ( ThreadStart start ) ; public Thread ( ParameterizedThreadStart start , int maxStackSize ) ; public Thread ( ThreadStart start , int maxStackSize ) ; Thread thread = new Thread ( new ThreadStart ( ScanDirectory ) ) ; Thread thread = new Thread ( ScanDirectory ) ;","Why does new Thread ( ) accept a method name , even though none of the constructor overloads seem to allow this ?" "C_sharp : Printing the stack trace is not so difficult when using System.Diagnostics . I am wondering if it is possible to print the VALUES of the parameters passed to each method up the stack trace , and if not why not.Here is my preliminary code : Thanks in advance . public static class CallStackTracker { public static void Print ( ) { var st = new StackTrace ( ) ; for ( int i = 0 ; i < st.FrameCount ; i++ ) { var frame = st.GetFrame ( i ) ; var mb = frame.GetMethod ( ) ; var parameters = mb.GetParameters ( ) ; foreach ( var p in parameters ) { // Stuff probably goes here , but is there another way ? } } } }",Print the values of the parameters up the stack trace "C_sharp : I am building some update statements with the MongoDB C # driver . The C # API includes both Wrapped and `` Un-Wrapped '' methods in the Builder namespace . On the surface , it appears that these differ by generics and not having to use a BSON wrapper . However , both method types allow me to pass in a non-Bson-Wrapped parameter . Is there a functional difference between the two ? For example ( using driver v1.2 ) , here are two uses of Update.Set : What is the difference between these two calls ? If only syntactic sugar - why the need for a Wrapped version ? var myCollection = database.GetCollection < MyObject > ( typeof ( MyObject ) .Name ) ; myCollection.Update ( Query.EQ ( `` _id '' , myId ) , Update.Set ( `` Message '' , `` My message text '' ) ) ; // And now the same call with `` Wrapped '' methodmyCollection.Update ( Query.EQ ( `` _id '' , myId ) , Update.SetWrapped ( `` Message '' , `` My message text '' ) ) ;",Using the MongoDB C # Driver : Wrapped or Un-Wrapped ? "C_sharp : I have a service interface with a method that has a parameter of type Stream . Should i close the stream after i have read all data from this stream or is this done by the WCF Runtime when the method call is completed ? The most examples i have seen , do only read the data from the stream , but do not call Close or Dispose on the Stream.Normally i would say i do not have to close the stream cause the class is not the owner of the stream , but the reason is why is ask this question is that we are currently investigating a problem in our system , that some Android Clients , that use HTTP-Post to send data to this service sometimes have open connections that aren´t closed ( Analyzed with netstat which list ESTABLISHED Tcp connections ) .Configuration of the Service/Binding [ ServiceContract ] public interface IStreamedService { [ OperationContract ] [ WebInvoke ] Stream PullMessage ( Stream incomingStream ) ; } [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.PerCall , UseSynchronizationContext = false ) ] public class MyService : IStreamedService { public System.IO.Stream PullMessage ( System.IO.Stream incomingStream ) { // using ( incomingStream ) { // Read data from stream // } Stream outgoingStream = // assigned by omitted code ; return outgoingStream ; } < webHttpBinding > < binding name= '' WebHttpBindingConfiguration '' transferMode= '' Streamed '' maxReceivedMessageSize= '' 1048576 '' receiveTimeout= '' 00:10:00 '' sendTimeout= '' 00:10:00 '' closeTimeout= '' 00:10:00 '' / > < /webHttpBinding >",Is it necessary to close the Stream of WebInvoke method "C_sharp : In our application we work a lot with async / await and Tasks . Therefore it does use Task.Run a lot , sometimes with cancellation support using the built in CancellationToken.If i do now cancel the execution using the CancellationToken the execution does stop at the beginning of the next loop , or if the Task did not start at all it throws an exception ( TaskCanceledException inside Task.Run ) . The question is now why does Task.Run use an Exception to control successful cancellation instead of just returning a completed Task . Is there any specific reason MS did not stick to the `` Do NOT use exceptions to control execution flow '' rule ? .And how can i avoid Boxing every method that supports cancellation ( which are a lot ) in an completely useless try catch ( TaskCancelledException ) block ? public Task DoSomethingAsync ( CancellationToken cancellationToken ) { return Task.Run ( ( ) = > { while ( true ) { if ( cancellationToken.IsCancellationRequested ) break ; //do some work } } , cancellationToken ) ; }",TaskCancellationException how to avoid the exception on success control flow ? "C_sharp : I am trying to create a derived class from a generic class , and I was wondering what the differences are betweenandInside class A there probably will be no code , since ( for now ) it will not behave different from class B. I only want to distinguish the two classes.Thanks in advance . public class A < T > : B < T > where T : C { } public class A : B < C > { }",What is the difference between `` class A : B < C > '' and `` class A < T > : B < T > where T : C '' ? "C_sharp : I 'm trying to send an IP packet using c # .The content of builtPacket is shown below . It 's an IP packet containing a TCP SYN packet ( That 's what I think I created anyway ) .45 00 00 28 00 00 00 00 02 06 36 6E C0 A8 00 8CC0 A8 00 C6 14 1E 00 50 00 00 00 00 00 00 00 0005 02 FF FF E6 4F 00 00The output is : The problem is I do n't see anything in the Wireshark trace . It 's like the data is not getting far enough down the stack for Wireshark to see it ? If I use a browser to connect to 192.168.0.198 , Wireshark shows all the packets , but shows nothing when I try to send a packet using the above code and data . My config : I am running as admin so it 's not a permissions problem . Windows7 ( Not running in a VM ) Wireless connection only ( IP config reports its IP as 192.168.0.140 ) What am I doing wrong ? I 'm sure Occam 's Razor applies here , but I 've been looking at this for hours and ca n't figure out what 's wrong . destAddress = IPAddress.Parse ( `` 192.168.0.198 '' ) , destPort = 80 ; // Create a raw socket to send this packet rawSocket = new Socket ( AddressFamily.InterNetwork , SocketType.Raw , ProtocolType.IP ) ; // Bind the socket to the interface specified IPEndPoint iep = new IPEndPoint ( IPAddress.Parse ( `` 192.168.0.140 '' ) ,0 ) ; rawSocket.Bind ( iep ) ; // Set the HeaderIncluded option since we include the IP header rawSocket.SetSocketOption ( socketLevel , SocketOptionName.HeaderIncluded , 1 ) ; // Send the packet ! int rc = rawSocket.SendTo ( builtPacket , new IPEndPoint ( destAddress , destPort ) ) ; Console.WriteLine ( `` sent { 0 } bytes to { 1 } '' , rc , destAddress.ToString ( ) ) ; sent 40 bytes to 192.168.0.198",Why ca n't I send this IP packet ? "C_sharp : Recently I 've been working on a Space Invaders like game , to help me boost my programming Skills . I 've fallen into a few problems . I 've been researching for a few days now , in how you would go about making a laser fire , on keyUp . This is my attempt so far ; I can get the laser to fire , but it has stumbled me why the laser does n't carry on moving up ... Help or advice would be much appreciated thanks . using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; using System.IO ; namespace SpaceInvaders { public partial class Form1 : Form { public int spriteX = 226 ; public int spriteY = 383 ; bool bulletFire = false ; int fireTimer = 8 ; int laserFired ; public Form1 ( ) { InitializeComponent ( ) ; } private void exitToolStripMenuItem_Click ( object sender , EventArgs e ) { this.Close ( ) ; } public void laserFire ( ) { //on laser fire i wont the bulle to move up while bullet timer is enabled //moving up slowly with set intervals while ( bulletTimer.Enabled == true ) { PictureBox laser = new PictureBox ( ) ; laser.BackColor = Color.Chartreuse ; laser.Width = 5 ; laser.Height = 30 ; laserFired = spriteY ; laserFired = laserFired - 10 ; this.Controls.Add ( laser ) ; laser.Location = new Point ( spriteX , laserFired ) ; } } private void Form1_KeyDown ( object sender , KeyEventArgs e ) { //Fire bullet if ( e.KeyCode == Keys.Up ) { bulletFire = true ; if ( bulletFire == true ) { laserFire ( ) ; bulletTimer.Enabled = true ; } } //Controls Right movement if ( spriteX < 448 ) { if ( e.KeyCode == Keys.Right ) { spriteX = spriteX + 20 ; } } //Controls Left Movement if ( spriteX > 0 ) { if ( e.KeyCode == Keys.Left ) { spriteX = spriteX - 20 ; } } //Points sprite to new location pctSprite.Location = new Point ( spriteX , spriteY ) ; } private void bulletTimer_Tick ( object sender , EventArgs e ) { if ( fireTimer == 0 ) { bulletTimer.Enabled = false ; } else { fireTimer = fireTimer - 1 ; } } } }",Can not get laser to fire in 2D space invaders like game "C_sharp : The result of the following Code differs If it is started with the debugger in the background or without . The difference is only there , if optimization is switched on.This is the result : - > with optimazation:100020083016100120093007 ... - > without optimization ( as expected ) 100010081016100110091017 ... Code : The behavior of the error depends on the number of iterations of the inner loop ( x < 5 everything works fine ) . Very interesting is that the does not occure when I use instead of I am working with Visual Studio 2010 SP1 and tried it with .NET Framework from 2.0 to 4.0.3 . I 've always seen the same result.Does anybody know about this bug or can reproduce ? using System ; using System.Diagnostics ; using System.Runtime.CompilerServices ; namespace OptimizerTest { public class Test { int dummy ; public void TestFunction ( int stepWidth ) // stepWidth must be a parameter { for ( int step = 0 ; step < stepWidth ; step++ ) { dummy = step + 1000 ; // addition with constant ( same value as later ! ) for ( int x = 0 ; x < 20 ; x += stepWidth ) { int index = x + 1000 + step ; // constant must be same as above and ? ! ? ! // int index = x + step + 1000 ; works ! ! ! ! ! Console.Write ( `` \n\r '' + index ) ; } } } [ MethodImpl ( MethodImplOptions.NoOptimization ) ] public void TestFunctionNoOptimization ( int stepWidth ) { for ( int step = 0 ; step < stepWidth ; step++ ) { dummy = step + 1000 ; for ( int x = 0 ; x < 20 ; x += stepWidth ) { int index = x + 1000 + step ; Console.Write ( `` \n\r '' + index ) ; } } } } class Program { /// < summary > /// Result differs from Start with F5 to Ctrl-F5 /// < /summary > /// < param name= '' args '' > < /param > static void Main ( string [ ] args ) { Test test = new Test ( ) ; Console.Write ( `` \n\r -- -- -- -- -\n\roptimized result\n\r -- -- -- -- -- -- - '' ) ; test.TestFunction ( 8 ) ; Console.Write ( `` \n\r -- -- -- -- -\n\rnot optimized result\n\r -- -- -- -- -- -- - '' ) ; test.TestFunctionNoOptimization ( 8 ) ; Console.Write ( `` \n\r -- -- -- -- -\n\rpress any key '' ) ; Console.ReadKey ( ) ; } } } int index = x + step + 1000 ; int index = x + 1000 + step ;",JIT .Net compiler bug ? "C_sharp : Now I am using something simmilar to this constructionAnd not very happy with it . Is there a better , more cleaner way to do such kind of sequent/concurrent action execution ? I have a look at Rx framework , but it is designed for other tasks and looks like way overkill for my problem . A.Completed += ( ) = > { B.Completed += ( ) = > { C.Completed += ( ) = > { // } C ( ) ; } B ( ) ; } A ( ) ;",How to execute async operations sequentially ? "C_sharp : I have just come across the following code ( .NET 3.5 ) , which does n't look like it should compile to me , but it does , and works fine : Table.IsChildOf is actually a method with following signature : Am I right in thinking this is equivalent to : and if so , what is the proper term for this ? bool b = selectedTables.Any ( table1.IsChildOf ) ) ; public bool IsChildOf ( Table otherTable ) bool b = selectedTables.Any ( a = > table1.IsChildOf ( a ) ) ;",Lambda expression syntactic sugar ? "C_sharp : In code similar to each of the following examples , I would like to be able to statically analyze code to determine the list of possible values that are passed into SpecialFunction ( ) .I can already parse the C # into an abstract syntax tree and I can already handle cases like A , and I guess I could keep track of initial assignments of values to guess case B , but cases as easy as C seem to get complicated quickly.I 'm almost certain that we wo n't be able to solve for x in all cases statically and that 's OK . I would like to know strategies for attempting it , ways to recognize when it ca n't be done . What if we need to include class-level fields and multi-threading ? Closures ? Would it help if we know that for the set X of all possible values for x , |X| < 50 ? From @ Vladimir Perevalov 's suggestion , how could the concepts in Pex be applied to finding possible values for targeted code points ( rather than what Pex seems to do which is to discover code paths and values that lead to unchecked ( ? ) exceptional cases ) ? SpecialFunction ( 5 ) ; // Aint x = 5 ; SpecialFunction ( x ) ; // Bint x = 5 ; x = condition ? 3 : 19 ; SpecialFunction ( x ) ; // C","C # Static Analysis , possible values for a variable/parameter" "C_sharp : I have an ASP.NET Core API ( .Net Core 2.1 ) and I implemented an Action Filter using this article https : //docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters ? view=aspnetcore-2.1 # action-filtersIn my Model , I use Data Annotations to validate the model , and I added the ValidateModel attribute for the Action in my Controller.I used Postman to test this , and my Action Filter gets called only if the Model is valid . If my request is missing a required field or some value is out of range , Action Filter does n't get called . Instead I receive a 400 bad request with the model state in the response.I implemented the Action Filter because I want to customize my model validation error . My understanding is that Action Filters get called at the time of model binding . Can someone help me figure out why this is happening and how to get the Action Filter to work ? UPDATE : I found the solution 2 seconds after posting the question , and the link @ Silvermind posted below is great info too.I added the following line to my Startup.cs It 's well documented here on the Microsoft site.https : //docs.microsoft.com/en-us/aspnet/core/web-api/index ? view=aspnetcore-2.1 # automatic-http-400-responses [ HttpPost ( `` CreateShipment '' ) ] [ ValidateModel ] public IActionResult CreateShipment ( [ FromBody ] CreateShipmentRequest request ) { if ( ModelState.IsValid ) { //Do something } return Ok ( ) ; } services.Configure < ApiBehaviorOptions > ( options = > { options.SuppressModelStateInvalidFilter = true ; } ) ;",ASP.NET Core Action Filter Does n't Get Called "C_sharp : having this code , I do n't understand why if assigning a variable in a finally block does n't understand it will ALWAYS be assigned . I think I missing a valid option where currency wo n't be assigned . If you know , will be great to understand why . much appreciate it ! Thanks ! the error happens on the finally block . If i take it out of the finally block like this : it works fine . CurrencyVO currency ; try { if ( idConnection.HasValue & & idConnection ! = 0 ) { currencyConnection = client.GetConnection ( idConnection.Value ) ; model.Connection = currencyConnection ; } else { int providerUserKey = ( int ) Models.UserModel.GetUser ( ) .ProviderUserKey ; currencyConnection = client.GetConnection ( providerUserKey ) ; } currency = model.Currencies.SingleOrDefault ( c = > c.IdCountry == currencyConnection.idcountry ) ? ? new CurrencyVO ( ) ; } catch { currency = new CurrencyVO ( ) ; } finally { model.PublishedContainer.Currency = currency ; } } catch { currency = new CurrencyVO ( ) ; } model.PublishedContainer.Currency = currency ;",Use of unassigned local variable . But always falls into assignment "C_sharp : I would like to better understand how a controler method knows when a parameter it recives should be retrived from the post data or the url.Take the following example : The controller would look something like this : Now , somehow the method is smart enough to look for the first parameter , the id , in the site URL and the Object in the HTTPPost.Whilst this works , I do n't know why , and as a result I sometimes run into unpredictable and erratic behaviour . For example , I seem to have found ( although I am not 100 % sure ) that removing the ? from int ? id makes the controller method inmediately assume it should look for the id in the HTTPPost and not the URL.So I would like to clarify the following points : What exactly is it that tells the method where to look for the data ? ( The [ HttpPost ] attribute preciding the method ? ) Do naming conventions come into play ? ( for example removint the ? or not using id as the variable name ? ) Does the order in which the variables are placed have an inpact ? ( ie placing the Object before the id ) I know I can more or less figure out some of this stuff by trial and error , but I would like a qualified explanation rather than to continiue to work of assumption based on observation.Thank youChopo URL : /ModelController/Method/itemID // Where itemID is the id ( int ) of the item in the databasePOST : objectOrArray : { JSON Object/Array } [ HttpPost ] public ActionResult InputResources ( int ? id , Object objectOrArray )",ASP.NET MVC : How does a controller distingush between parameters in the URL and sent by POST "C_sharp : I am adding an entity to my DataContext . After this , I have to send this entity back on view ( show result to end user ) .DbSet has Add method that returns back new entity . But I need my entity with included navigation properties.In the current moment , I make one more call to DataContext and passing newEntity 's Id to find the entity.Is it possible to include navigation property during adding operation ? My code works but I am looking for way to do it more gracefully . public async Task < Entity > AddAsync ( Entity entity ) { var savedEntity = m_DataContext.Entities.Add ( entity ) ; await m_DataContext.SaveChangesAsync ( ) ; return await m_DataContext.Entities .Include ( p= > p.SubEntity ) .FirstAsync ( p= > p.Id==savedEntity.Id ) ; }",EF : Include navigation property to result of adding entity in DbSet "C_sharp : I created a blank Universal Windows App project in Visual Studio 2015.I add something like : I get a stack trace like : i.e. , No line numbers.How do I get line numbers to show up ? try { string foo = null ; int len = foo.Length ; } catch ( Exception ex ) { System.Diagnostics.Debug.WriteLine ( ex ) ; } Exception thrown : 'System.NullReferenceException ' in TestStackTraces.exeSystem.NullReferenceException : Object reference not set to an instance of an object.at TestStackTraces.App.OnLaunched ( LaunchActivatedEventArgs e )",Line numbers in stack traces for UWP apps "C_sharp : This is in a Windows Phone 8.1 Store app . My MainPage has a CaptureElement to display the preview stream from my MediaCapture object . For navigation within the app ( between pages ) , this works well : I can navigate to other pages and come back , and the preview runs reliably . I 'm running into problems for the following scenarios though : User presses the Windows button , then the back buttonUser presses the Windows button , then uses the task switcher to come back to my appUser presses the search button , then the back buttonUser presses the power button , then presses it again and swipes up to unlock the deviceUser holds down the back button to enter the task switcher , then taps on my app againAfter each of the above actions ( and/or combinations of them ) , when my app comes back the preview is frozen at the last frame that was displayed.If the user then navigates to a different page and then back to the MainPage , the preview starts running again without an issue , so this leads me to believe I just need to stop/start the preview after coming back from one of the above scenarios.I tried subscribing to the App.Suspending and App.Resuming events , but these do n't trigger on these occasions . What am I missing ? MediaCapture mc ; protected override async void OnNavigatedTo ( NavigationEventArgs e ) { mc = new MediaCapture ( ) ; await mc.InitializeAsync ( ) ; preview.Source = mc ; await mc.StartPreviewAsync ( ) ; } protected override async void OnNavigatedFrom ( NavigationEventArgs e ) { await mc.StopPreviewAsync ( ) ; }",MediaCapture + CaptureElement lifecycle/navigation management "C_sharp : I have a few lines of code that have worked fine for months , and now suddenly they do not work and I get a very strange error . Here is the function in question : Naturally , this gets called in response to the SettingsPane.GetForCurrentView ( ) .CommandsRequested event . The error happens on the second line and is as follows : A first chance exception of type 'System.FormatException ' occurred in mscorlib.dllAdditional information : Guid should contain 32 digits with 4 dashes ( xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ) .If I continue the app , then another exception comes : A first chance exception of type 'System.InvalidCastException ' occurred in mscorlib.dllAdditional information : Object in an IPropertyValue is of type 'String ' , which can not be converted to a 'Guid'.What is going on here ? As you can see I 'm not using any GUID values anywhere . public void OnCommandsRequested ( SettingsPane settingsPane , SettingsPaneCommandsRequestedEventArgs eventArgs ) { UICommandInvokedHandler handler = new UICommandInvokedHandler ( OnSettingsCommand ) ; SettingsCommand appSettings = new SettingsCommand ( `` appSettings '' , `` アプリ内設定 '' , handler ) ; eventArgs.Request.ApplicationCommands.Add ( appSettings ) ; }",Why does this unrelated error happen when I try to setup Windows 8 settings ? "C_sharp : UPDATE : As of C # 7.3 , this should no longer be an issue . From the release notes : When a method group contains some generic methods whose type arguments do not satisfy their constraints , these members are removed from the candidate set.Pre C # 7.3 : So I read Eric Lippert 's 'Constraints are not part of the signature ' , and now I understand that the spec specifies that type constraints are checked AFTER overload resolution , but I 'm still not clear on why this MUST be the case . Below is Eric 's example : This does n't compile because overload resolution for : Foo ( new Giraffe ( ) ) infers that Foo < Giraffe > is the best overload match but then the type constraints fail and a compile-time error is thrown . In Eric 's words : The principle here is overload resolution ( and method type inference ) find the best possible match between a list of arguments and each candidate method ’ s list of formal parameters . That is , they look at the signature of the candidate method . Type constraints are NOT part of the signature , but why ca n't they be ? What are some scenarios where it is a bad idea to consider type constraints part of the signature ? Is it just difficult or impossible to implement ? I 'm not advocating that if the best chosen overload is for whatever reason impossible to call then silently fallback to the second best ; I would hate that . I 'm just trying to understand why type constraints ca n't be used to influence the choosing of the best overload.I 'm imagining that internally in the C # compiler , for overload resolution purposes only ( it does n't permanently rewrite the method ) , the following : gets transformed to : Why ca n't you sort of `` pull in '' the type constraints into the formal parameter list ? How does this change the signature in any bad way ? I feel like it only strengthens the signature . Then Foo < Reptile > will never be considered as an overload candidate.Edit 2 : No wonder my question was so confusing . I did n't properly read Eric 's blog and I quoted the wrong example . I 've edited in the example I think more appropriate . I 've also changed the title to be more specific . This question does n't seem as simple as I first imagined , perhaps I 'm missing some important concept . I 'm less sure that this is stackoverflow material , it may be best for this question/discussion to be moved elsewhere . static void Foo < T > ( T t ) where T : Reptile { } static void Foo ( Animal animal ) { } static void Main ( ) { Foo ( new Giraffe ( ) ) ; } static void Foo < T > ( T t ) where T : Reptile { } static void Foo ( Reptile t ) { }",Why are n't type constraints part of the method signature ? "C_sharp : I 've often seen and used enums with attached attributes to do some basic things such as providing a display name or description : And have had a set of extension methods to support the attributes : Following this pattern , additional existing or custom attributes could be applied to the fields to do other things . It is almost as if the enum can work as the simple enumerated value type it is and as a more rich immutable value object with a number of fields : In this way , it can `` travel '' as a simple field during serialization , be quickly compared , etc . yet behavior can be `` internalized '' ( ala OOP ) .That said , I recognize this may be considered an anti-pattern . At the same time part of me considers this useful enough that the anti might be too strict . public enum Movement { [ DisplayName ( `` Turned Right '' ) ] TurnedRight , [ DisplayName ( `` Turned Left '' ) ] [ Description ( `` Execute 90 degree turn to the left '' ) ] TurnedLeft , // ... } public static string GetDisplayName ( this Movement movement ) { ... } public static Movement GetNextTurn ( this Movement movement , ... ) { ... } public class Movement { public int Value { get ; set ; } // i.e . the type backing the enum public string DisplayName { get ; set ; } public string Description { get ; set ; } public Movement GetNextTurn ( ... ) { ... } // ... }",The `` Enum as immutable rich-object '' : is this an anti-pattern ? "C_sharp : In the following code : My assumption is that bag is threadsafe and list is not . Is this the right way to deal with a dictionary of lists in a multithreaded app ? Edited to add : Only 1 thread would be adding to the bag/list and another thread would remove , but many threads could access . public class SomeItem { } public class SomeItemsBag : ConcurrentBag < SomeItem > { } public class SomeItemsList : List < SomeItem > { } public static class Program { private static ConcurrentDictionary < string , SomeItemsBag > _SomeItemsBag ; private static ConcurrentDictionary < string , SomeItemsList > _SomeItemsList ; private static void GetItem ( string key ) { var bag = _SomeItemsBag [ key ] ; var list= _SomeItemsList [ key ] ; ... } }","Is it correct ok to use ConcurrentBag < T > as object of ConcurrentDictionary < key , object >" "C_sharp : Suppose I have the following expressions : I 'd like to be able to compile these into a method/delegate equivalent to the following : What is the best way to approach this ? I 'd like it to perform well , ideally with performance equivalent to the above method.UPDATESo , whilst it appears that there is no way to do this directly in C # 3 is there a way to convert an expression to IL so that I can use it with System.Reflection.Emit ? Expression < Action < T , StringBuilder > > expr1 = ( t , sb ) = > sb.Append ( t.Name ) ; Expression < Action < T , StringBuilder > > expr2 = ( t , sb ) = > sb.Append ( `` , `` ) ; Expression < Action < T , StringBuilder > > expr3 = ( t , sb ) = > sb.Append ( t.Description ) ; void Method ( T t , StringBuilder sb ) { sb.Append ( t.Name ) ; sb.Append ( `` , `` ) ; sb.Append ( t.Description ) ; }",How can I combine several Expressions into a fast method ? "C_sharp : Which way is better practice : return a value from a method inside an using statement or declare a variable before , set it inside and return it after ? or public int Foo ( ) { using ( .. ) { return bar ; } } public int Foo ( ) { var b = null ; using ( .. ) { b = bar ; } return b ; }",Best practice regarding returning from using blocks "C_sharp : I have just started using and am falling in love with MVC design pattern.My only pet peeve with it is that it seems to produce a lot of repetitive code . For example.I have a standard MVC App with my DB ( models ) in one project , separated from my controllers / views / viewmodels in another , again separated from my test methods in another . All working great.Models : Now , I have a bunch of nice EF4 classes in my DB project , which I have to use ViewModels for in my real project to access my data . No problem here.Controllers : However , every controller I have , essentially does the very same thing . It gets and sets the data from the ViewModels so while each controller is different in that it gets only different data , they are all essentially doing the very same job , in the very same way . ( I currently have 9 , but this could easily explode to well over 50 ) .For example : Views : Every view generated from the contollers work great . Execpt , that only thing that changes is the data ( fields with labels and text boxes ) . Once again , they all do the very same job ( but with different datasets ) .Problem : I want to make a single controller , and make it dynamic . So that it can read data from different view models . ( Why have 9 or 50 controllers esentially doing the same job ) Then I want to do likewise with the views . So that different fields can be dynamically generated . ( Why have 9 or 50 views all doing the same job ) . If the view is based on the controller , the view should be able to change based on its properties.Essentially all I want to do is find a way to tell the controller to read from viewmodel X or VM - Y or VM - Z ect and it should be able to generate the properties , retreive the associated data , and pass it to the view , which upon receiving , will generate the fields with labels and text boxes.I guess I want to know if there is any way to do this using reflection . As the view models are basic classes with simple properties . One could potentially create a base controller class that has a method to read in a specified viewmodel object , get its properties , read in also an associated table and match up the fields in that table with the properties in the class . Finally one can pass in the record from the table to display . The view then can be generated automatically based on this using some kind of razor , c # or javascript.Any taughts on if this is possible or not would be welcome . public class Dummy1Controller : Controller { private MyProj.Data.Entities _entities = new Data.Entities ( ) ; private MyProj.Data.Entities2 _coreEntities = new Data.Entities2 ( ) ; //GET : /Customers/ public ActionResult Index ( ) { if ( _entities.table1.Count ( ) == 0 ) return View ( ) ; var pastObj = _entities.table1.First ( ) ; return View ( new Table1ViewModel ( ) { Id = pastObj.Id , FirstName = pastObj.FirstName , LastName = pastObj.LastName , . . . . } ) ; } } public class Dummy2Controller : Controller { private MyProj.Data.Entities _entities = new Data.Entities ( ) ; private MyProj.Data.Entities2 _coreEntities = new Data.Entities2 ( ) ; //GET : /Vehicles/ public ActionResult Index ( ) { if ( _entities.table2.Count ( ) == 0 ) return View ( ) ; var pastObj = _entities.table2.First ( ) ; return View ( new Table1ViewModel ( ) { RegNo = pastObj.RegNo , Make = pastObj.Make , Model = pastObj.Model , . . . . } ) ; } } public class Dummy3Controller : Controller { private MyProj.Data.Entities _entities = new Data.Entities ( ) ; private MyProj.Data.Entities2 _coreEntities = new Data.Entities2 ( ) ; //GET : /Invoices/ public ActionResult Index ( ) { if ( _entities.table3.Count ( ) == 0 ) return View ( ) ; var pastObj = _entities.table3.First ( ) ; return View ( new Table1ViewModel ( ) { InvNo = pastObj.InvNo , Amount = pastObj.Amount , Tax = pastObj.Tax , . . . . } ) ; } } @ model MyProject.Web.ViewModels.Table1ViewModel @ { ViewBag.Title = `` Index '' ; } < link href= '' @ Url.Content ( `` ~/Content/CSS/GenericDetailStyles.css '' ) '' rel= '' stylesheet '' type= '' text/css '' / > < section id= '' content '' > < div id= '' table '' > < div > < h2 > Customer < /h2 > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.Id ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.Id ) < /div > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.FirstName ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.FirstName ) < /div > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.LastName ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.LastName ) < /div > < /div > . . . . < /div > < /section > @ { Html.RenderAction ( `` Index '' , `` FooterPartial '' ) ; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @ model MyProject.Web.ViewModels.Table2ViewModel @ { ViewBag.Title = `` Index '' ; } < link href= '' @ Url.Content ( `` ~/Content/CSS/GenericDetailStyles.css '' ) '' rel= '' stylesheet '' type= '' text/css '' / > < section id= '' content '' > < div id= '' table '' > < div > < h2 > Vehicle < /h2 > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.RegNo ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.RegNo ) < /div > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.Make ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.Make ) < /div > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.PatientID ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.Model ) < /div > < /div > . . . . < /div > < /section > @ { Html.RenderAction ( `` Index '' , `` FooterPartial '' ) ; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @ model MyProject.Web.ViewModels.Table3ViewModel @ { ViewBag.Title = `` Index '' ; } < link href= '' @ Url.Content ( `` ~/Content/CSS/GenericDetailStyles.css '' ) '' rel= '' stylesheet '' type= '' text/css '' / > < section id= '' content '' > < div id= '' table '' > < div > < h2 > Invoice < /h2 > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.InvNo ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.InvNo ) < /div > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.Amount ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.Amount ) < /div > < /div > < div class= '' row '' > < div class= '' left '' > @ Html.LabelFor ( x= > x.Tax ) < /div > < div class= '' right '' > @ Html.TextBoxFor ( model = > model.Tax ) < /div > < /div > . . . . < /div > < /section > @ { Html.RenderAction ( `` Index '' , `` FooterPartial '' ) ; }",MVC Reducing repetitive code "C_sharp : I 'm running a PLINQ query as follows : The GetNextCombo method is just returning the next combination of letters and numbers , with possibilities up to the billions/trillions.Now this is throwing the exception when I choose a range of combinations greater than the allowed size of an Int32 , it always throws when the counter of combos it 's run is 2147483584.I 've made sure it 's nothing in the GetNextCombo by creating a fake combo to return every time ( doing a yield return `` 234gf24fa23 ... '' etc . ) The exception is being thrown by LINQ : I 'm wondering if there 's anything I can do to change this query to not overflow , any order in which I do things , etc . Maybe not have the linq query do a where and select , although I 've tried this : still the same overflow . ParallelQuery < string > winningCombos = from n in nextComboMaker.GetNextCombo ( ) .AsParallel ( ) .WithCancellation ( _cancelSource.Token ) where ComboWasAWinner ( n ) select n ; ConcurrentBag < string > wins = new ConcurrentBag < string > ( ) ; foreach ( var winningCombo in winningCombos ) { wins.Add ( winningCombo ) ; if ( wins.Count == _maxWinsAllowed ) break ; } System.AggregateException was unhandled by user code Message=One or more errors occurred . Source=System.Core StackTrace : at System.Linq.Parallel.QueryTaskGroupState.QueryEnd ( Boolean userInitiatedDispose ) at System.Linq.Parallel.MergeExecutor ` 1.Execute [ TKey ] ( PartitionedStream ` 2 partitions , Boolean ignoreOutput , ParallelMergeOptions options , TaskScheduler taskScheduler , Boolean isOrdered , CancellationState cancellationState , Int32 queryId ) at System.Linq.Parallel.PartitionedStreamMerger ` 1.Receive [ TKey ] ( PartitionedStream ` 2 partitionedStream ) at System.Linq.Parallel.ForAllOperator ` 1.WrapPartitionedStream [ TKey ] ( PartitionedStream ` 2 inputStream , IPartitionedStreamRecipient ` 1 recipient , Boolean preferStriping , QuerySettings settings ) at System.Linq.Parallel.UnaryQueryOperator ` 2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive [ TKey ] ( PartitionedStream ` 2 inputStream ) at System.Linq.Parallel.WhereQueryOperator ` 1.WrapPartitionedStream [ TKey ] ( PartitionedStream ` 2 inputStream , IPartitionedStreamRecipient ` 1 recipient , Boolean preferStriping , QuerySettings settings ) at System.Linq.Parallel.UnaryQueryOperator ` 2.UnaryQueryOperatorResults.ChildResultsRecipient.Receive [ TKey ] ( PartitionedStream ` 2 inputStream ) at System.Linq.Parallel.ScanQueryOperator ` 1.ScanEnumerableQueryOperatorResults.GivePartitionedStream ( IPartitionedStreamRecipient ` 1 recipient ) at System.Linq.Parallel.UnaryQueryOperator ` 2.UnaryQueryOperatorResults.GivePartitionedStream ( IPartitionedStreamRecipient ` 1 recipient ) at System.Linq.Parallel.UnaryQueryOperator ` 2.UnaryQueryOperatorResults.GivePartitionedStream ( IPartitionedStreamRecipient ` 1 recipient ) at System.Linq.Parallel.QueryOperator ` 1.GetOpenedEnumerator ( Nullable ` 1 mergeOptions , Boolean suppressOrder , Boolean forEffect , QuerySettings querySettings ) at System.Linq.Parallel.ForAllOperator ` 1.RunSynchronously ( ) at StockWiz.Library.PLINQArrayProcessor.DoProcessing ( ) in C : \Users\dad\Documents\BitBucket\stockwiz_clone\stockwiz\StockWiz.Library\PLINQArrayProcessor.cs : line 50 at System.Threading.Tasks.Task.Execute ( ) InnerException : System.OverflowException Message=Arithmetic operation resulted in an overflow . Source=System.Core StackTrace : at System.Linq.Parallel.PartitionedDataSource ` 1.ContiguousChunkLazyEnumerator.MoveNext ( T & currentElement , Int32 & currentKey ) at System.Linq.Parallel.WhereQueryOperator ` 1.WhereQueryOperatorEnumerator ` 1.MoveNext ( TInputOutput & currentElement , TKey & currentKey ) at System.Linq.Parallel.ForAllOperator ` 1.ForAllEnumerator ` 1.MoveNext ( TInput & currentElement , Int32 & currentKey ) at System.Linq.Parallel.ForAllSpoolingTask ` 2.SpoolingWork ( ) at System.Linq.Parallel.SpoolingTaskBase.Work ( ) at System.Linq.Parallel.QueryTask.BaseWork ( Object unused ) at System.Threading.Tasks.Task.Execute ( ) InnerException : var query = nextComboMaker.GetNextCombo ( ) .AsParallel ( ) ; query.ForAll ( x = > if ( ComboWasAWinner ( x ) wins.Add ( x ) ) ;",PLINQ query giving overflow exception "C_sharp : Sorry to ask all , but I 'm an old hand Vb.net guy who 's transferring to c # . I have the following piece of code that seems to activate when the ( in this case ) postAsync method is fired . I just don ; t understand what the code is doing ( as follows ) : -if anyone could explain what the += ( o , args ) = > is actually acheiving I 'd be so greatful ... .many thanks in advance.Tim app.PostCompleted += ( o , args ) = > { if ( args.Error == null ) { MessageBox.Show ( `` Picture posted to wall successfully . `` ) ; } else { MessageBox.Show ( args.Error.Message ) ; } } ;","what is += ( o , arg ) = > actually achieving ?" "C_sharp : I have this JSON which I am trying to read on Windows Phone . I 've been playing with DataContractJsonSerializer and Json.NET but had not much luck , especially reading each 'entry ' : All I care about is the entries in the people section . Basically I need to read and iterate through the entries ( containing the ID , Name , Age values ) and add them to a Collection or class . ( I am populating a listbox afterwards . ) Any pointers appreciated . { `` lastUpdated '' : '' 16:12 '' , '' filterOut '' : [ ] , '' people '' : [ { `` ID '' : '' x '' , '' Name '' : '' x '' , '' Age '' : '' x '' } , { `` ID '' : '' x '' , '' Name '' : '' x '' , '' Age '' : '' x '' } , { `` ID '' : '' x '' , '' Name '' : '' x '' , '' Age '' : '' x '' } ] , `` serviceDisruptions '' : { `` infoMessages '' : [ `` blah blah text '' ] , `` importantMessages '' : [ ] , `` criticalMessages '' : [ ] } }",Deserializing JSON in WP7 "C_sharp : Is it possible to place an AES key and IV into a KeyContainer using ASPNET_REGIIS ? If yes , how ? Context : I have created AesProtectedConfigurationProvider to encrypt web.config data using AES as opposed to Triple DES ( i.e. , 3DES ) . I have also created a console application that uses the AesProtectedConfigurationProvider in order to generate both the AES key and initialization vector ( IV ) . I can save the key to a text file and then reference the text file in the provider of the web.config . From there , I am able to encrypt the web.config file . But , I would like to protect the keys.txt file by moving them into a KeyContainer , if that is possible.So , under the provider tag , the section for keyContainerName would be : as opposed toMy understanding is the current encryption offering that is available out of the box in ASPNET_REGIIS uses 3DES to encrypt the contents of the web.config file while the RsaProtectedConfigurationProvider is used to encrypt the 3DES keys ( please correct me if I am wrong on this ) . So , if it is possible to use the RsaProtectedConfigurationProvider to encrypt the AES keys into a KeyContainer then that would be helpful . I have reviewed the following sites and I am not sure if this is possible : https : //msdn.microsoft.com/en-us/library/33ws57y0.aspxHow to encrypt web.config with AES instead of 3DESEDIT : Does anyone know why Microsoft took out the AesProtectedConfigurationProvider in subsequent releases of .NET ? This seems like a step backwards as AES is the current standard while 3DES is no longer recommended . In speaking with a colleague , they mentioned that it may have been removed due to a security flaw , such as ; elevation of privileges . Microsoft is known for making unannounced changes with respect to security . But , I would like to know if anyone knows for sure . If , indeed , a flaw was found in the AesProtectedConfigurationProvider , then I might be inclined to stay with 3DES . keyContainerName= '' AesKeyContainer '' keyContainerName= '' C : \AesKey.txt ''",ASPNET_REGIIS : Place AES key and IV into a KeyContainer "C_sharp : The canonical answer on where to put Database.SetInitializer calls is in Global.asax for web projects . I 'm looking for another option.We 're using Entity Framework 4.3.1 with Code First . We write web services and WinForms applications , and typically put data access code ( such as DbContexts ) in shared libraries.Currently , the constructors of our DbContext descendants look like this:95 % of the time , that 's the right default . 5 % of the time ( some integration tests , greenfield development , etc . ) it 's not.If we move that code into the initialization ( or configuration ) of our services and applications , adding a new DbContext to a library involves Shotgun Surgery . All of these projects have to be updated , even if the library does n't expose the context directly.Optional arguments are one possibility : Overriding the default strategy might involve passing the initializer through multiple layers , though.We 've also considered creating a reflection-based initializer that would set all contexts to a specific strategy.What 's the best practice ? public PricingContext ( string connectionString ) : base ( connectionString ) { Database.SetInitializer < PricingContext > ( null ) ; } public PricingContext ( string connectionString , IDatabaseInitializer < PricingContext > databaseInitializer = null ) : base ( connectionString ) { Database.SetInitializer < PricingContext > ( databaseInitializer ) ; }",Avoiding Shotgun Surgery with Database.SetInitializer "C_sharp : The problem of single dispatch is mostly familiar to people engaged in coding with statically typed languages like Java and C # . The basic idea is : While the runtime polymorphism allows us to dispatch to the right method call according to the type ( runtime type ) of receiver , for example : The method call will be performed according to the runtime type of mything , namely Cat.This is the single dispatch capability ( which is present in Java/C # ) .Now , if you need to dispatch not only on the runtime type of receiver , but on the types of ( multiple ) arguments either , you face a little problem : The second method never gets called , because in our 'consumer ' code we just tend to treat different types of objects ( visitors in my example ) by their common supertype or interface.That 's why I ask - because dynamic typing allows the multiple dispatch polymorphism and C # 4.0 has that dynamic keyword ; ) IAnimal mything = new Cat ( ) ; mything.chop ( ) ; public class MyAcceptor { public void accept ( IVisitor vst ) { ... } public void accept ( EnhancedConcreteVisitor vst ) { ... } }",Does new 'dynamic ' variable type in .NET 4.0 solve the single/multiple method dispatch issue in CLR ? "C_sharp : I am trying to post data from Xamarin android app to Netsuite RESTlet api . Below code is working fine from asp.net web form c # using rest sharp library and also work on Postman Desktop app . But when i try to post data xamarin android app it throw below errors . Response Error : name resolution error and sometime it throw following error request time out var client = new RestClient ( `` testclient.com '' ) ; var request = new RestRequest ( Method.POST ) ; request.AddHeader ( `` postman-token '' , `` 123-456-789-123-3654 '' ) ; request.AddHeader ( `` cache-control '' , `` no-cache '' ) ; request.AddHeader ( `` content-type '' , `` application/json '' ) ; request.AddHeader ( `` authorization '' , `` NLAuth nlauth_account= 12345678 , nlauth_email=test @ test.com , nlauth_signature=test123 , nlauth_role=correctrole '' ) ; request.AddParameter ( `` application/json '' , `` [ { \ '' id\ '' : \ '' 123\ '' , \t\ '' myid\ '' : \ '' 111\ '' , \t\ '' qty\ '' : \ '' 4\ '' } , { \ '' id\ '' : \ '' 123\ '' , \t\ '' myid\ '' : \ '' 618\ '' , \t\ '' qty\ '' : \ '' 6\ '' } \n , { \ '' id\ '' : \ '' 123\ '' , \t\ '' 1234\ '' : \ '' 2037\ '' , \t\ '' qty\ '' : \ '' 3\ '' } , { \ '' id\ '' : \ '' 123\ '' , \t\ '' 1243\ '' : \ '' 126\ '' , \t\ '' qty\ '' : \ '' 2\ '' } ] '' , ParameterType.RequestBody ) ; IRestResponse response = client.Execute ( request ) ;",Xamarin RestSharp POST method throwing request timeout error and name resolution error "C_sharp : I 'm trying to access KeyVault from an .net Core console application , using a Service Principle ( I have the App Id and App Secret ) . Here 's my code : Which calls back to this function : Calling GetSecretAsync returns an `` AccessDenied '' exception . Modifying the code to use this callback yeilds an `` Unauthorized '' exception : I setup the Service Principle by going to Azure > AAD > App Registrations , noted the App Id and password ( App Secret ) when I setup the Principle.Then in KeyVault , I added the principle to Access Control ( IAM ) , with contributor rights , but still no joy ! Has anyone come across this scenario before ? Thanks ! : ) var client = new KeyVaultClient ( GetAccessToken ) ; var secret = client.GetSecretAsync ( `` https : // { keyvaultName } .vault.azure.net '' , `` MySecret '' ) .Result ; private static async Task < string > GetAccessToken ( string authority , string resource , string scope ) { var context = new AuthenticationContext ( authority , TokenCache.DefaultShared ) ; var credential = new ClientCredential ( clientId : appId , clientSecret : appSecret ) ; var authResult = await context.AcquireTokenAsync ( resource , credential ) ; return authResult.AccessToken ; } private static async Task < string > GetAccessToken ( string authority , string resource , string scope ) { var context = new AuthenticationContext ( authority , TokenCache.DefaultShared ) ; var credential = new ClientCredential ( clientId : appId , clientSecret : appSecret ) ; **var authResult = await context.AcquireTokenAsync ( `` https : //management.core.windows.net/ '' , credential ) ; ** return authResult.AccessToken ; }",Azure - authenticating to KeyVault using Service Principle returns an Unauthorized exception "C_sharp : I was wondering what the best implementation for a global error ( does n't have to be errors , can also be success messages ) handler would be ? Let me break it down for you with an example : User tries to delete a record Deletion fails and an error is loggedUser redirects to another pageDisplay error message for user ( using a HtmlHelper or something , do n't want it to be a specific error page ) I 'm just curious what you guys think . I 've been considering TempData , ViewData and Session but they all have their pros and cons.TIA ! UPDATE : I 'll show an example what I exactly mean , maybe I was n't clear enough.This is an example of a method that adds a message when user deletes a record . If user succeeds , user redirects to another pageAnd in the view `` RecordsList '' , it would be kinda cool to show all messages ( both error and success messages ) in a HtmlHelper or something.This can be achieved in many ways , I 'm just curious what you guys would do . UPDATE 2 : I have created a custom error ( message ) handler . You can see the code if you scroll down . public ActionResult DeleteRecord ( Record recordToDelete ) { // If user succeeds deleting the record if ( _service.DeleteRecord ( recordToDelete ) { // Add success message MessageHandler.AddMessage ( Status.SUCCESS , `` A message to user '' ) ; // And redirect to list view return RedirectToAction ( `` RecordsList '' ) ; } else { // Else return records details view return View ( `` RecordDetails '' , recordToDelete ) ; } } < % = Html.RenderAllMessages % >",ASP.NET MVC - Approach for global error handling ? "C_sharp : This example is in C # but the question really applies to any OO language . I 'd like to create a generic , immutable class which implements IReadOnlyList . Additionally , this class should have an underlying generic IList which is unable to be modified . Initially , the class was written as follows : However , this is n't immutable . As you can likely tell , changing the initial IList 'obj ' changes Datum 's 'objects ' . This writes `` two '' to the console . As the point of Datum is immutability , that 's not okay . In order to resolve this , I 've rewritten the constructor of Datum : Given the same test as before , `` one '' appears on the console . Great . But , what if Datum contains a collection of non-immutable collection and one of the non-immutable collections is modified ? And , as expected , `` two '' is printed out on the console . So , my question is , how do I make this class truly immutable ? public class Datum < T > : IReadOnlyList < T > { private IList < T > objects ; public int Count { get ; private set ; } public T this [ int i ] { get { return objects [ i ] ; } private set { this.objects [ i ] = value ; } } public Datum ( IList < T > obj ) { this.objects = obj ; this.Count = obj.Count ; } IEnumerator IEnumerable.GetEnumerator ( ) { return this.GetEnumerator ( ) ; } public IEnumerator < T > GetEnumerator ( ) { return this.objects.GetEnumerator ( ) ; } } static void Main ( string [ ] args ) { List < object > list = new List < object > ( ) ; list.Add ( `` one '' ) ; Datum < object > datum = new Datum < object > ( list ) ; list [ 0 ] = `` two '' ; Console.WriteLine ( datum [ 0 ] ) ; } public Datum ( IList < T > obj ) { this.objects = new List < T > ( ) ; foreach ( T t in obj ) { this.objects.Add ( t ) ; } this.Count = obj.Count ; } static void Main ( string [ ] args ) { List < object > list = new List < object > ( ) ; List < List < object > > containingList = new List < List < object > > ( ) ; list.Add ( `` one '' ) ; containingList.Add ( list ) ; Datum < List < object > > d = new Datum < List < object > > ( containingList ) ; list [ 0 ] = `` two '' ; Console.WriteLine ( d [ 0 ] [ 0 ] ) ; }",How to Ensure Immutability of a Generic "C_sharp : I need to allow image upload in my AngularJS + WebAPI project . to achieve this I am using ng-file-upload according to this sample code : http : //monox.mono-software.com/blog/post/Mono/233/Async-upload-using-angular-file-upload-directive-and-net-WebAPI-service/with a few adjustments to the post code to look like this : I have quite a few web API controllers already and I added a new one according to the code sample in the link above ( that inherits from System.web.http.ApiController instead of the `` regular '' Microsoft.AspNet.Mvc.Controller class ) : The problem is , i keep getting `` 404 not found '' when posting.I tried : all stack overflow answersonline answersremoving the content of the `` Upload '' function , and changing to MVC 's Controller base class - > still same result.changing the name of `` Upload '' method to `` Post '' and posting to `` /api/uploads '' - > same 404.Please help ! thanks ! EDITthis is the browser `` Network '' tab : I am using HTTPSthis was tested `` live '' ( without localhost ) = same result.EDIT2my routes : these are the only routes that are declared.EDIT3I am 100 % sure the problem is me using `` ApiController '' as base class instead of `` Controller '' . i added a new controller and i can access it no problem . now just making it work as i do n't have `` Request.Content `` in `` Controller '' - any ideas ? I see 2 possibilities to make it work : pass HttpRequestMessage as a parameter to the method : public async Task Post ( [ FromBody ] HttpRequestMessage request ) but i am getting HTTP 500 as i do n't know how to pass from angular 's POST.or : get Request.Content to resolve under Controller ( no idea how ) .has someone managed to do this ? thanks ! $ scope.onFileSelect = function ( $ files ) { console.log ( `` on file select is running ! `` ) ; // $ files : an array of files selected , each file has name , size , and type . for ( var i = 0 ; i < $ files.length ; i++ ) { var $ file = $ files [ i ] ; ( function ( index ) { Upload.upload ( { url : `` /api/Uploads/Upload '' , // webapi url method : `` POST '' , file : $ file } ) .progress ( function ( evt ) { // get upload percentage console.log ( 'percent : ' + parseInt ( 100.0 * evt.loaded / evt.total ) ) ; } ) .success ( function ( data , status , headers , config ) { // file is uploaded successfully console.log ( data ) ; } ) .error ( function ( data , status , headers , config ) { // file failed to upload console.log ( data ) ; } ) ; } ) ( i ) ; } } [ Route ( `` api/ [ controller ] '' ) ] public class UploadsController : ApiController { [ HttpPost ] // This is from System.Web.Http , and not from System.Web.Mvc public async Task < HttpResponseMessage > Upload ( ) { if ( ! Request.Content.IsMimeMultipartContent ( ) ) { this.Request.CreateResponse ( HttpStatusCode.UnsupportedMediaType ) ; } var provider = GetMultipartProvider ( ) ; var result = await Request.Content.ReadAsMultipartAsync ( provider ) ; // On upload , files are given a generic name like `` BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5 '' // so this is how you can get the original file name var originalFileName = GetDeserializedFileName ( result.FileData.First ( ) ) ; // uploadedFileInfo object will give you some additional stuff like file length , // creation time , directory name , a few filesystem methods etc.. var uploadedFileInfo = new FileInfo ( result.FileData.First ( ) .LocalFileName ) ; // Through the request response you can return an object to the Angular controller // You will be able to access this in the .success callback through its data attribute // If you want to send something to the .error callback , use the HttpStatusCode.BadRequest instead var returnData = `` ReturnTest '' ; return this.Request.CreateResponse ( HttpStatusCode.OK , new { returnData } ) ; } app.UseMvc ( routes = > { routes.MapRoute ( name : `` default '' , template : `` { controller=Home } / { action=Index } / { id ? } '' ) ; } ) ;",Ng-File-Upload with MVC & Web API - keep getting `` 404 Not Found '' "C_sharp : I 'm trying to use Cecil to find instances of calls to a generic method using an interface for a convention test . I 'm having trouble identifying the generic type from the MethodReference.I 've set up a basic test : So I want to find the call to farm.Add < IAnimal > ( ) , which wo n't give a compile time error or even a run-time error , until the farm conceivable tried to create an instance of the type through reflection . My actual use case is a convention test for a DI container.Cecil comes in to it in the FindErrors ( ) method : The callsInError part is where I am failing to identify the generic type used when calling Farm : :Add . Specifically , the GenericParameters property of the MethodReference is empty , so GenericParameters [ 0 ] gives an ArgumentOutOfRangeException . I 've explored the MethodReference , and I 'm definitely getting the calls to Farm : :Add , but I ca n't see anywhere that relates to the generic type being used except for the FullName property , which is n't useful.How can I get Cecil to identify the generic type used in the call ? private interface IAnimal { } private class Duck : IAnimal { } private class Farm { private readonly ICollection < string > _animals = new List < string > ( ) ; public void Add < T > ( ) { _animals.Add ( typeof ( T ) .Name ) ; } public override string ToString ( ) { return string.Join ( `` , `` , _animals ) ; } } static Farm FarmFactory ( ) { var farm = new Farm ( ) ; farm.Add < Duck > ( ) ; farm.Add < Duck > ( ) ; farm.Add < IAnimal > ( ) ; // whoops farm.Add < Duck > ( ) ; return farm ; } private static void Main ( string [ ] args ) { var farm = FarmFactory ( ) ; Console.WriteLine ( `` Farm : '' ) ; Console.WriteLine ( farm ) ; // Use Cecil to find the call to farm.Add < IAnimal > ( ) : Console.WriteLine ( `` Errors : '' ) ; FindErrors ( ) ; Console.Read ( ) ; } private static void FindErrors ( ) { var methods = AssemblyDefinition.ReadAssembly ( typeof ( Farm ) .Assembly.Location ) .Modules .SelectMany ( module = > module.Types ) .SelectMany ( type = > type.Methods ) .Where ( method = > method.HasBody ) .ToArray ( ) ; var callsToFarmDotAdd = methods .Select ( method = > new { Name = method.Name , MethodReferences = GetCallsToFarmDotAdd ( method ) } ) .Where ( x = > x.MethodReferences.Any ( ) ) .ToArray ( ) ; var testCases = callsToFarmDotAdd .SelectMany ( x = > x.MethodReferences ) ; var callsInError = testCases .Where ( test = > ! test.GenericParameters [ 0 ] .Resolve ( ) .IsClass ) ; foreach ( var error in callsInError ) { Console.WriteLine ( error.FullName ) ; } } private static IEnumerable < MethodReference > GetCallsToFarmDotAdd ( MethodDefinition method ) { return method.Body.Instructions .Where ( instruction = > instruction.OpCode == OpCodes.Callvirt ) .Select ( instruction = > ( MethodReference ) instruction.Operand ) .Where ( methodReference = > methodReference.FullName.Contains ( `` Farm : :Add '' ) ) ; }",How can I use Cecil to find the type passed to a generic method ? "C_sharp : Using the async/await model , I have a method which makes 3 different calls to a web service and then returns the union of the results.Using typical await , these 3 calls will execute synchronously wrt each other . How would I go about letting them execute concurrently and join the results as they complete ? var result1 = await myService.GetData ( source1 ) ; var result2 = await myService.GetData ( source2 ) ; var result3 = await myService.GetData ( source3 ) ; allResults = Union ( result1 , result2 , result3 ) ;",Concurrent execution of async methods "C_sharp : I am trying out Visual Studio 2019 on a code base written in Visual Studio 2017 , and am immediately finding a build issue . I have a switch case statement in which the case is selected on a constant string . This does n't have a default case , which is fine in Visual Studio 2017 , but throws a build error in Visual Studio 2019.I can resolve the issue by adding a default case , but I would like to avoid a code change and just change a compiler setting if possible , to avoid the need for a pull request . In any case it would be good to understand the reason for the issue.A github repository containing the example solution can be found athttps : //github.com/martineyles/NoDefaultCaseThis includes an archive of the example solution in the state before it was added to github.In Visual Studio 2017 , the output of the build is : In Visual Studio 2019 , the output of the build is : I am targeting .net framework 4.7.2 and the default language version . I have also tried reducing the language version to C # 6.0 and setting the language version manually to C # 7.3 with the same results.The specific version of Visual Studio I am using are : andThe issue is resolved in : public class Program { public const string Database = `` MongoDB '' ; public static string GetDb ( ) { switch ( Database ) { case `` MongoDB '' : return Database ; } } } 1 > -- -- -- Rebuild All started : Project : NoDefaultCase , Configuration : Debug Any CPU -- -- -- 1 > NoDefaultCase - > C : \Users\MartinEyles\source\repos\NoDefaultCase\NoDefaultCase\bin\Debug\NoDefaultCase.exe========== Rebuild All : 1 succeeded , 0 failed , 0 skipped ========== 1 > -- -- -- Rebuild All started : Project : NoDefaultCase , Configuration : Debug Any CPU -- -- -- 1 > C : \Users\MartinEyles\source\repos\NoDefaultCase\NoDefaultCase\Program.cs ( 9,30,9,35 ) : error CS0161 : 'Program.GetDb ( ) ' : not all code paths return a value========== Rebuild All : 0 succeeded , 1 failed , 0 skipped ========== Microsoft Visual Studio Enterprise 2017 Version 15.9.11VisualStudio.15.Release/15.9.11+28307.586Microsoft .NET Framework Version 4.7.03056 Microsoft Visual Studio Enterprise 2019 Version 16.0.0VisualStudio.16.Release/16.0.0+28729.10Microsoft .NET Framework Version 4.7.03056 Microsoft Visual Studio Enterprise 2019Version 16.0.3VisualStudio.16.Release/16.0.3+28803.352Microsoft .NET Framework Version 4.7.03056",Why does a switch-case statement on a string constant require a default in Visual Studio 2019 ( prior to 16.0.3 ) but not in Visual Studio 2017 ? "C_sharp : I want to migrate a library project which targeted .NET Framework 4.6.1 to a new one targeting both , .NET Framework 4.6.1 and .NET Standard 2.0.In my current code I use , for example : System.Web.Hosting.HostingEnvironment.MapPath ( ) method ; so , I already added a condition in my .csproj file : Now in my code , I know that I could have something like this : My question : If later I change my project to target .NET Framework 4.7 , will the above code be executed or it will be strictly targeted for .NET Framework 4.6.1 only ? What condition to use for 4.6.1 and up ? < PropertyGroup Condition= '' ' $ ( OS ) ' == 'Windows_NT ' `` > < TargetFrameworks > netstandard2.0 ; net461 < /TargetFrameworks > < /PropertyGroup > < ItemGroup Condition= '' ' $ ( TargetFramework ) ' == 'net461 ' `` > < Reference Include= '' System.Web '' / > < /ItemGroup > # if NET461 if ( someFolderVar.StartsWith ( `` ~/ '' ) ) someFolderVar = System.Web.Hosting.HostingEnvironment.MapPath ( someFolderVar ) ; # endif",How to use conditional symbols when targeting multiple frameworks correctly ( VS2017 ) "C_sharp : The base of the problem : Pun intended.The problem starts with a very old dBase database where the textual information is encoded directly into DOS Cyrillic ( CP-866 ) , and because that 's not enough of a problem , it 's also being transferred to a MySQL database every evening , to which I have access.I 've installed the MySQL Providers and connected to the database with Entity Framework , which was my main data access method , and then for experimental reasons with pure ADO.NET as well.Everything was going better than expected until I attempted to convert the supposedly CP-866 values from the database to UTF-8 , like so : I 've read it once with EntityFramework and once with ADO.NET with the same result.For unknown at the time and less-unknown now reasons , it did n't work . After reading some important articles about encoding and string values I 've determined that it is not possible to apply such conversions to the string equivalent of the varchar field in the database because of the nature of the string variable itself.Few keyboard bangs later , I 've finally made it happen by using ADO.NET MySQL Provider and customizing my query by adding CONVERT ( varcharColumn , Binary ) to the column I was testing with.From then on , I used the above code with the only difference that I already had the cp866 byte array from the convert . I originally intended to do something similar but the MySQL provider was n't able to directly read bytes from a varchar field , neither I found a way to do it with Entity Framework.Yes , it works , but it does n't feel right even to my unexperienced self.Questions:1 : Can I specify how Entity Framework should select specific fields ? I would like to somehow explain my beloved ORM that it should be converting specific varchar fields to binary during the read , without returning the string representation at all , because it messes everything up.2 : Is there a way to make the ADO.NET MySQL provider to get the bytes of a varchar field , without pulling it as a string first ? The GetBytes method throws an exception when used with varchar , and the GetSqlBytes method that is normally present in ADO.NET provider is missing in the MySQL version . I do n't really want to write Binary Convert on every field which I need to read properly.3 : Bonus Question : Is it possible to read the CP-866 encoded varchar field as a string as I did , but this time properly changing the encoding to UTF-8 ? There is still a lot of chaos in my head on the encoding topic after today 's reading . I still believe there might be something I am missing and that is possible to read a string from the cp-866 encoded varchar fields , like : ..and then convert it to UTF-8 , while having in mind the field in the database was encoded with CP-866 . From what I 've read , as soon as it 's in a string , it 's unicode and the string is immutable . I 've tried getting it 's byre array representation , changing it to cp866 , then to utf8 , I tried using it as it is cp866 itself , but without success . var cp866 = Encoding.GetEncoding ( 866 ) ; var utf8 = Encoding.UTF8 ; string source = `` some unreadable set of characters from the database '' ; byte [ ] cp866bytes = cp866.GetBytes ( source ) ; byte [ ] utf8bytes = Encoding.Convert ( cp866 , utf8 , cp866bytes ) ; string result = utf8.GetString ( utf8bytes ) ; string cp866EncodedValue = `` Œ€ „ ‹… Œ‹€ „ …Ž‚€ Šš…‚€ '' ; //actual copy-pasted value",Accessing VARCHAR as BINARY during read with Entity Framework and MySQL ? "C_sharp : I 've tried to write a method which returns the permutation of a given enumerable as simple as possible . The code : As the code has simplified within the iterator block , I 'm trying to make it simply a single query expression of LINQ . There 's a recursion in the nested foreach with this code , even another possibly yield outside the foreach ; and which is the difficult part for me to rewrite it in query syntax . I 've read this answer : C # String permutationBut I guess it 's not the solution for me .. I tried various ways , and think it 's not so easy to do . How can I get it done ? ( The Exchange method is another problem , and I 've asked a question : How to exchange the items of enumeration by interating only once ? But I guess it 's not the matter here .. ) using System.Collections.Generic ; public static partial class Permutable { static IEnumerable < IEnumerable < T > > PermuteIterator < T > ( IEnumerable < T > source , int offset ) { var count=0 ; foreach ( var dummy in source ) if ( ++count > offset ) foreach ( var sequence in Permutable.PermuteIterator ( source.Exchange ( offset , count-1 ) , 1+offset ) ) yield return sequence ; if ( offset==count-1 ) yield return source ; } public static IEnumerable < IEnumerable < T > > AsPermutable < T > ( this IEnumerable < T > source ) { return Permutable.PermuteIterator ( source , 0 ) ; } public static IEnumerable < T > Exchange < T > ( this IEnumerable < T > source , int index1 , int index2 ) { // exchange elements at index1 and index2 } }",How to use query syntax to create permutations ? "C_sharp : I have two XML files with same base format , but some of the tags and attributes in Master.XML are n't contained in the Child.XML.I need to Merge the XML files into new one XML file with missing tags and attributes present.If the values in the Master.XML and Child.XML differs , then values from Child.XML should be used.I tried using Union and Concat with nodes , But it 's not working.Any suggestion will be helpful.Master.XMLChild.XMLExpected Output master.DescendantNodes ( ) .Union ( child.DescendantNodes ( ) ) ; < SysConfig IsRuntime= '' False '' BarcodeEnabled= '' false '' version= '' 1.2.0.0 '' > < DbPath > C : \Agilent_i1000\ICPT_DB.sqlite < /DbPath > < CardDiagonsticsDelayTime > 10 < /CardDiagonsticsDelayTime > < ScreenSpecs NameID= '' CoreID '' XrelativeID= '' X '' YrelativeID= '' Y '' > < ScreenSpec Name= '' MainCtrlPanel '' Xrelative= '' 0 '' Yrelative= '' 0 '' > < /ScreenSpec > < ScreenSpec Name= '' 1 '' Xrelative= '' 75 '' Yrelative= '' 0 '' NotToUse= '' 1 '' > < /ScreenSpec > < ScreenSpec Name= '' 2 '' Xrelative= '' 75 '' Yrelative= '' 25 '' NotToUse= '' 1 '' > < /ScreenSpec > < /ScreenSpecs > < /SysConfig > < SysConfig IsRuntime= '' False '' BarcodeEnabled= '' false '' version= '' 1.2.0.0 '' > < CardDiagonsticsDelayTime > 20 < /CardDiagonsticsDelayTime > < ScreenSpecs NameID= '' CoreID '' XrelativeID= '' X '' YrelativeID= '' Y '' > < ScreenSpec Name= '' MainCtrlPanel '' Xrelative= '' 0 '' Yrelative= '' 0 '' > < /ScreenSpec > < ScreenSpec Name= '' 1 '' Xrelative= '' 100 '' Yrelative= '' 0 '' > < /ScreenSpec > < ScreenSpec Name= '' 2 '' Xrelative= '' 75 '' Yrelative= '' 25 '' > < /ScreenSpec > < ScreenSpec Name= '' 3 '' Xrelative= '' 175 '' Yrelative= '' 25 '' > < /ScreenSpec > < /ScreenSpecs > < /SysConfig > < SysConfig IsRuntime= '' False '' BarcodeEnabled= '' false '' version= '' 1.2.0.0 '' > < DbPath > C : \Agilent_i1000\ICPT_DB.sqlite < /DbPath > < CardDiagonsticsDelayTime > 20 < /CardDiagonsticsDelayTime > < ScreenSpecs NameID= '' CoreID '' XrelativeID= '' X '' YrelativeID= '' Y '' > < ScreenSpec Name= '' MainCtrlPanel '' Xrelative= '' 0 '' Yrelative= '' 0 '' > < /ScreenSpec > < ScreenSpec Name= '' 1 '' Xrelative= '' 100 '' Yrelative= '' 0 '' NotToUse= '' 1 '' > < /ScreenSpec > < ScreenSpec Name= '' 2 '' Xrelative= '' 75 '' Yrelative= '' 25 '' NotToUse= '' 1 '' > < /ScreenSpec > < ScreenSpec Name= '' 3 '' Xrelative= '' 175 '' Yrelative= '' 25 '' > < /ScreenSpec > < /ScreenSpecs > < /SysConfig >",Merge two XML files and add missing tags and attributes "C_sharp : Here are the errors : I can see the console using ctrl + f5 which I found out through another stack overflow question , but it runs and disappears when just using Start.Visual Studio terminates my console application too fastThis is my first program written in C # for event driven programming . I was wondering if I should be worried about future programs or can I bypass it everytime ? I also enabled Symbols through Debug > Options > Debugging > Symbols , which changed my error from file not found to symbol loaded . Is there a better fix ? I uninstalled , reinstalled , repaired , got rid of redistributables , and added older redistributables but could n't find another solution . Any help is appreciated.Here is the code . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities.Sync\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.Sync.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \Users\Chris James\Documents\Visual Studio 2015\Projects\ConsoleApplication3\ConsoleApplication3\bin\Debug\ConsoleApplication3.vshost.exe ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.Linq.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_4.0.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_64\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_4.0.0.0__b77a5c561934e089\System.Xml.dll ' . Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled.The thread 0x3344 has exited with code 0 ( 0x0 ) .The thread 0x369c has exited with code 0 ( 0x0 ) .The thread 0x4498 has exited with code 0 ( 0x0 ) . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' c : \users\chris james\documents\visual studio 2015\Projects\ConsoleApplication3\ConsoleApplication3\bin\Debug\ConsoleApplication3.exe ' . Symbols loaded . 'ConsoleApplication3.vshost.exe ' ( CLR v4.0.30319 : ConsoleApplication3.vshost.exe ) : Loaded ' C : \WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll ' . Symbols loaded.The thread 0x2b58 has exited with code 0 ( 0x0 ) .The thread 0x3994 has exited with code 0 ( 0x0 ) .The program ' [ 11144 ] ConsoleApplication3.vshost.exe ' has exited with code 0 ( 0x0 ) . using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace DelegateTutorial1 { public class MediaStorage { public delegate int PlayMedia ( ) ; public void ReportResult ( PlayMedia playerDelegate ) { if ( playerDelegate ( ) == 0 ) { Console.WriteLine ( `` Media played successfully '' ) ; } else { Console.WriteLine ( `` Media did not play successfully '' ) ; } } } public class AudioPlayer { private int audioPlayerStatus ; public int PlayAudioFile ( ) { Console.WriteLine ( `` Simulating playing an audio file '' ) ; audioPlayerStatus = 0 ; return audioPlayerStatus ; } } public class VideoPlayer { private int videoPlayerStatus ; public int PlayVideoFile ( ) { Console.WriteLine ( `` Simulating a failed video file '' ) ; videoPlayerStatus = -1 ; return videoPlayerStatus ; } } public class Tester { public void Run ( ) { MediaStorage myMediaStorage = new MediaStorage ( ) ; AudioPlayer myAudioPlayer = new AudioPlayer ( ) ; VideoPlayer myVideoPlayer = new VideoPlayer ( ) ; MediaStorage.PlayMedia audioPlayerDelegate = new MediaStorage.PlayMedia ( myAudioPlayer.PlayAudioFile ) ; MediaStorage.PlayMedia videoPlayerDelegate = new MediaStorage.PlayMedia ( myVideoPlayer.PlayVideoFile ) ; myMediaStorage.ReportResult ( audioPlayerDelegate ) ; myMediaStorage.ReportResult ( videoPlayerDelegate ) ; } } class Program { static void Main ( string [ ] args ) { Tester t = new Tester ( ) ; t.Run ( ) ; } } }",Visual Studio Community 2015 Console Application Error on Start "C_sharp : How do you send an email to a yahoo account , I can only send to gmail ? I 'd like to know why because MY ISP does n't offer me a POP3 or SMTP address . I do n't know anything about mine , if you could tell me a way to investigate then I 'll be delightedly thankful . SmtpClient smtp = new SmtpClient ( `` smtp.gmail.com '' , 587 ) ; smtp.UseDefaultCredentials = false ; smtp.Credentials = new NetworkCredential ( `` pevus55 @ gmail.com '' , `` mypassword '' ) ; smtp.EnableSsl = true ; MailAddress mailFrom = new MailAddress ( `` parris797877 @ yahoo.com '' ) ; MailAddress mailTo = new MailAddress ( `` pevus55 @ gmail.com '' ) ; MailMessage msg = new MailMessage ( mailFrom , mailTo ) ; msg.Subject = `` Test '' ; msg.Body = textBox1.Text ; smtp.Send ( msg ) ;",Sending email to yahoo account "C_sharp : I have create a little engineering app for some network debugging . It takes a list of IP addresses and pings them , with user set timeout and rate . It logs the average round-trip time and every time one of the sends fails it logs it 's duration of failure and a timestamp of when it happened ... That 's the idea . I developed it on a Win7 machine with .Net4 and have had to put the thing on a set of XP laptops.The problem is the duration values on my box during testing show nice ms durations , on the XP boxes when I look they show 0 or 15.625 ( magic number ? ) ... and have the funny square , box symbol in the string ? That 's the bit that does the log . The _ipStatus is the ping failure reason ( typically timeout ) .That 's the bit that does the print ... Can anyone shed any light on this apparent difference ? The question has been answered but I will include an edit here for some more info.EDIT : It seems that the difference was down not to the Win7 and WinXP difference but 32bit and 64bit.In a 32 bit windows systems as Henk points out , the granularity of the system clock is 15-16ms , this is what gave me the value of 15.625 for every value less than 16ms for the timespan . In a 64 bit system the system call is to a different set of methods that have a much finer granularity . So on my dev machine in x64 I had ms accuracy from my system clock ! Now , the stopwatch uses a hardware interface via the processor instrumentation to record a much finer granularity ( probably not every processor tick , but I imagine something obscenely accurate in-line with this thinking ) . If the hardware underlying the OS does not have this level of instrumentation , it will however use the system time . So beware ! But I would guess most modern desktops/laptops have this instrumentation ... Embedded devices or things of that nature might not , but then the stopwatch class is not in the Compact Framework as far as I can see ( here you have to use QueryPerformanceCounter ( ) ) .Hope all this helps . It 's helped me a lot . Somewhere around the _spanStopWatch initialiser : The nuts and bolts : public void LinkUp ( ) { if ( _isLinkUp ) return ; _upTime = DateTime.Now ; var span = _upTime.Subtract ( _downTime ) ; _downTimeLog.Add ( new LinkDown ( ) { _span = span , _status = _ipStatus , _time = _downTime } ) ; _isLinkUp = true ; } _downEventLog.AppendLine ( `` Duration- > `` + linkDownLogEvent._span.TotalMilliseconds + `` ms\n '' ) ; if ( ! _spanStopWatch.IsHighResolution ) { throw new ThisMachineIsNotAccurateEnoughForMyLikingException ( `` Find a better machine . `` ) ; } public void LinkUp ( ) { if ( _isLinkUp ) return ; _spanStopWatch.Stop ( ) ; var span = _spanStopWatch.Elapsed ; _downTimeLog.Add ( new LinkDown ( ) { _span = span , _status = _ipStatus , _time = _downTime } ) ; _isLinkUp = true ; }",Datetime Granularity between 32bit and 64bit Windows "C_sharp : I am learning the Entity Framework and using it in an MVVM app where each ViewModel works with the DbContext for Data Access . Disclaimer : In a real application I know the ViewModel should n't interact directly with the Data Access Layer.Given that each ViewModel is there to monitor and manipulate the state of the View by maintaining relationships with the Models themselves , I began to wonder about the implications of spinning up multiple DbContext objects , and if something like a DBContext is best left as a singleton - to which I quickly found the answer was `` NO '' . So if the consensus is to have an instance for each use ( as in the case with multiple ViewModels , or what-have-you ) I still havent seen where any one mentions the potential issues with having this.To elaborate , lets say I have two ViewModels and in each I create a Context ( TestContext inherits from DbContext ) to maintain the Data Access activities during the lifetime of each ViewModel : Are there any pitfalls with having a context in each class that can consume it ? One such thought that taunts me is if it 's possible to have either context be out of sync with the other , such that one ViewModel has more recent data than the other by way of its context being more `` up-to-date '' . Things like this I am interested in knowing.Thanks.EDITI dont hope to discover / cover every situation as that would be unique TO the situation against which one is coding . I just want to know if there are any `` up-front '' or obvious perils that I am unaware of being new to the subject . public class MainWindowViewModel : ViewModelBase { private TestContext db = new TestContext ( ) ; ... other code follows ( properties methods etc ... ) ... } public class TestViewModel : ViewModelBase { private TestContext db = new TestContext ( ) ; ... other code follows ( properties methods etc ... ) ... }",Exploring the pitfalls ( if any ) of having a DbContext for each ViewModel/Class that uses it "C_sharp : I have translated the code from javascript to c # which can be found by going to this excellent demo at http : //fractal.qfox.nl/dragon.js My translation is intended to produce just a single dragon upon clicking the button but I think I have missed something in my version.See the Wikipedia article : Dragon Curve for more information.Incomplete dragon fractal output : Code : public partial class MainPage : UserControl { PointCollection pc ; Int32 [ ] pattern = new Int32 [ ] { 1 , 1 , 0 , 2 , 1 , 0 , 0 , 3 } ; Int32 [ ] position = new Int32 [ ] { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; Boolean toggle ; Char r = default ( Char ) ; Int32 distance = 10 ; // line length Int32 step = 100 ; // paints per step Int32 skip = 10 ; // folds per paint Double x = 0 ; Double y = 0 ; Int32 a = 90 ; public MainPage ( ) { InitializeComponent ( ) ; } private void btnFire_Click ( object sender , RoutedEventArgs e ) { x = canvas.ActualWidth / 3 ; y = canvas.ActualHeight / 1.5 ; pc = new PointCollection ( ) ; var n = step ; while ( -- n > 0 ) { List < Char > s = getS ( skip ) ; draw ( s ) ; } Polyline p = new Polyline ( ) ; p.Stroke = new SolidColorBrush ( Colors.Red ) ; p.StrokeThickness = 0.5 ; p.Points = pc ; canvas.Children.Add ( p ) ; } List < Char > getS ( Int32 n ) { List < Char > s1 = new List < Char > ( ) ; while ( n -- > 0 ) s1.Add ( getNext ( 0 ) ) ; return s1 ; } void draw ( List < Char > s ) { pc.Add ( new Point ( x , y ) ) ; for ( Int32 i = 0 , n = s.Count ; i < n ; i++ ) { pc.Add ( new Point ( x , y ) ) ; Int32 j ; if ( int.TryParse ( s [ i ] .ToString ( ) , out j ) & & j ! = 0 ) { if ( ( a + 90 ) % 360 ! = 0 ) { a = ( a + 90 ) % 360 ; } else { a = 360 ; // Right } } else { if ( a - 90 ! = 0 ) { a = a - 90 ; } else { a = 360 ; // Right } } // new target if ( a == 0 || a == 360 ) { y -= distance ; } else if ( a == 90 ) { x += distance ; } else if ( a == 180 ) { y += distance ; } else if ( a == 270 ) { x -= distance ; } // move pc.Add ( new Point ( x , y ) ) ; } } Char getNext ( Int32 n ) { if ( position [ n ] == 7 ) { r = getNext ( n + 1 ) ; position [ n ] = 0 ; } else { var x = position [ n ] > 0 ? pattern [ position [ n ] ] : pattern [ 0 ] ; switch ( x ) { case 0 : r = ' 0 ' ; break ; case 1 : r = ' 1 ' ; break ; case 2 : if ( ! toggle ) { r = ' 1 ' ; } else { r = ' 0 ' ; } toggle = ! toggle ; break ; } position [ n ] = position [ n ] + 1 ; } return r ; } }",Why is my dragon fractal incomplete "C_sharp : I have a user control where I have bounded a string to the xaml path . This makes it possible for me to choose colors like `` Black '' `` Blue '' and also use hexa numbers as a string to choose the color . But I am not able to use the same string in the C # code . Which is shown in the example below : So the last string shieldGearModelRec.Gear.Color is what I use as a binding in XAML . And it can convert strings to color either in color names or hexa description . But how can I do this in the code behind , that is in c # ? My searches found stuff likeConvert string to Color in C # but this was not possible in windows phone . Is there anyway to accomplish this ? An IdeaDo I need to create a converter that reads the string , looks for # to determine if it is hexa or a color name and then using a hexa converter to find rgb , and a switch for the names ? This does not seem like the smartest solution SolidColorBrush blackBrush = new SolidColorBrush ( ) ; SolidColorBrush mySolidColorBrush = new SolidColorBrush ( ) ; mySolidColorBrush.Color = shieldGearModelRec.Gear.Color ;",How to convert a string into a Color ? For windows phone c # "C_sharp : I 'm trying to load a type from a different assembly ( not known at build time ) as 'dynamic ' and execute a method on that type . My goal is to completely disconnect the 'plugin ' from the parent application such that there is no requirement for any shared code or common interface type . The interface is implied by way of an expected method signature on the loaded type.This works : However this will load the type into the current AppDomain along with all its dependent assemblies.I want to modify this to allow me to do that same thing in a separate AppDomain.This works but does n't make use of the dynamic keyword , I need to know the explicit type that I am instantiating to be able to call the Execute method : This is essentially my target case and I have been trying to get something like this working : I keep ending up with a RuntimeBinderException with the message `` 'System.MarshalByRefObject ' does not contain a definition for 'Execute ' '' . This message makes sense , sure it does n't contain a definition for 'Execute ' , but I know the type that I am instantiating does indeed contain an 'Execute ' method . I imagine there 's something going on here with the transparent proxy that is preventing this from working but I 'm not sure what.My actual class that I am trying to instantiate looks like this : I have also tried this with a shared interface ( not my primary goal , but I 'm trying to figure this out first ) so it would look like : Where IPlugin is a known type in the parent application and the plugin has the appropriate reference at build time but this does n't seem to work either.I 'm guessing at this point that it 's not possible to load a type as dynamic across the AppDomain boundary.Is there a way to actually get this to work ? dynamic myObj = Assembly.Load ( `` MyAssembly '' ) .CreateInstance ( `` MyType '' ) ; myObj.Execute ( ) ; var appDomain = AppDomain.CreateDomain ( domainName , evidence , setup ) ; var myObj = appDomain.CreateInstanceAndUnwrap ( assembly , type ) ; typeof ( IMyInterface ) .InvokeMember ( `` Execute '' , BindingFlags.InvokeMethod , null , myObj ) ; dynamic myObj = ad.CreateInstanceAndUnwrap ( assembly , type ) ; myObj.Execute ( ) ; [ Serializable ] public class MyClass : MarshalByRefObject { public void Execute ( ) { // do something } } [ Serializable ] public class MyClass : MarshalByRefObject , IPlugin { public void Execute ( ) { // do something } }",Can I instantiate a type as 'dynamic ' from another AppDomain ? "C_sharp : I 'm using WebGrid to display data on client side , canSort : true is set.The view code is : I 'm able to sort data by clicking column headers.Problem : How can someone asynchronously sort the WebGrid using Ajax ? @ model UI.Models.TestModel @ if ( Model.listTestModel ! = null ) { var grid = new WebGrid ( Model.listTestModel , null , defaultSort : `` ColumnA '' , rowsPerPage : 25 , canPage : true , canSort : true ) ; @ grid.GetHtml ( mode : WebGridPagerModes.All , columns : grid.Columns ( grid.Column ( columnName : `` ColumnA '' , header : `` ColumnA '' ) , grid.Column ( columnName : `` ColumnB '' , header : `` ColumnB '' ) ) ) }",Asynchronously sort GridView in ASP.NET MVC using Ajax "C_sharp : I have a combo box which I need to mirror in another tab page in a C # winforms based application.I have perfectly working code for when you select a different item from the drop down list . Unfortunately , however , when I change the Text of a tab that has not been clicked on yet nothing actually happens.If I first click each tab then everything works as expected.Now I 'm putting this down to some form of lack of initialisation happening first . So I 've tried to select each tab in my constructor.But this does n't work.I 've also tried calling tabControlDataSource.SelectTab ( 1 ) and still it does n't work.Does anyone know how I can force the tab to `` initialise '' ? tabControlDataSource.SelectedIndex = 0 ; tabControlDataSource.SelectedIndex = 1 ; // etc",Changing text of a combobox in a different tab "C_sharp : I have a piece of code for some validation logic , which in generalized for goes like this : This works , is pretty easy to understand , and has early-out optimization . It is , however , pretty verbose . The main purpose of this question is what is considered readable and good style . I 'm also interested in the performance ; I 'm a firm believer that premature { optimization , pessimization } is the root of all evil , and try to avoid micro-optimizing as well as introducing bottlenecks.I 'm pretty new to LINQ , so I 'd like some comments on the two alternative versions I 've come up with , as well as any other suggestions wrt . readability . I do n't believe that V2 offers much over V1 in terms of readability , even if shorter . I find V3 to be clear & concise , but I 'm not too fond of the Method ( ) .Property part ; of course I could turn the lambda into a full delegate , but then it loses it 's one-line elegance.What I 'd like comments on are : Style - ever so subjective , but what do you feel is readable ? Performance - are any of these a definite no-no ? As far as I understand , all three methods should early-out.Debuggability - anything to consider ? Alternatives - anything goes.Thanks in advance : ) private bool AllItemsAreSatisfactoryV1 ( IEnumerable < Source > collection ) { foreach ( var foo in collection ) { Target target = SomeFancyLookup ( foo ) ; if ( ! target.Satisfactory ) { return false ; } } return true ; } private bool AllItemsAreSatisfactoryV2 ( IEnumerable < Source > collection ) { return null == ( from foo in collection where ! ( SomeFancyLookup ( foo ) .Satisfactory ) select foo ) .First ( ) ; } private bool AllItemsAreSatisfactoryV3 ( IEnumerable < Source > collection ) { return ! collection.Any ( foo = > ! SomeFancyLookup ( foo ) .Satisfactory ) ; }",LINQ or foreach - style/readability and speed "C_sharp : Consider this scenario : Which does n't compile : error CS1667 : Attribute 'Obsolete ' is not valid on property or event accessors . It is only valid on 'class , struct , enum , constructor , method , property , indexer , field , event , interface , delegate ' declarations.Applying attributes to specifically the accessors is perfectly fine for any other attribute ( provided that AttributeTargets.Method is set up in its usages , which is true for ObsoleteAttribute ) . public class C { private int _foo ; public int Foo { get { return _foo ; } [ Obsolete ( `` Modifying Foo through the setter may corrupt hash tables. `` + `` Consider using the method 'ModifyFoo ' instead . '' ) ] set { _foo = value ; } } public C ModifyFoo ( int foo ) { // return a new instance of C } }",How and why is ObsoleteAttribute disallowed for property accessors ? "C_sharp : I have this situation : If I use this mapping code : only A table is created ( with ABase and A properties ) . If I delete IncludeBase ( ) then A1 and A2 are created ( with all properties ) . How to write mapping to have tables for classes A ( with all A and ABase properties ) , A1 and A2 ( with specific properties ) in my database but not for the class ABase ? public namespace ANamespace { public abstract class ABase : IABase { //properties } public abstract class A : ABase { //properties } public class A1 : A { //properties } public class A2 : A { //properties } } AutoMap .AssemblyOf < ABase > ( ) .Where ( e = > e.Namespace == `` ANamespace '' ) .IncludeBase < A > ( ) .IgnoreBase < ABase > ( ) ; AutoMap .AssemblyOf < ABase > ( ) .Where ( e = > e.Namespace == `` ANamespace '' ) .IgnoreBase < ABase > ( ) ;",Automapping inheritance with Fluent nhibernate "C_sharp : I have Visual Studio Professional 2013 and I am debugging an application which uses async/await extensively . But when I stop at breakpoint and open Debug/Windows/Tasks window , it always says `` No tasks to display . `` I 've made two test , in one I can see task , in another I ca n't ( I run program , and pause it ) . Or I can breakpoint at waiting fro task line.Can anybody explain why I can see tasks in one case but not in another ? using System ; using System.Threading ; using System.Threading.Tasks ; namespace TasksDebugWindowTest { class Program { static void Main ( string [ ] args ) { DoesNotWork ( ) ; } static void Works ( ) { Console.WriteLine ( `` Starting '' ) ; var t = Task.Factory.StartNew ( ( ) = > { Task.Delay ( 100 * 1000 ) .Wait ( ) ; Console.WriteLine ( `` Task complete '' ) ; } ) ; Console.WriteLine ( `` Status : { 0 } '' , t.Status ) ; Thread.Sleep ( 500 ) ; Console.WriteLine ( `` Status : { 0 } '' , t.Status ) ; t.Wait ( ) ; Console.WriteLine ( `` Done '' ) ; } static void DoesNotWork ( ) { Console.WriteLine ( `` Starting '' ) ; var t = Task.Delay ( 100 * 1000 ) ; t.Wait ( ) ; // **** Breakpoint here Console.WriteLine ( `` Task complete '' ) ; } } }",VS2013 Debug/Windows/Tasks : `` No tasks to display '' "C_sharp : I have a c # enumeration that looks like this : I added a leading underscore to each value to make the compiler happy . Is there a standard naming convention for enumerations like this ? The underscore I 've used does n't seem like the best choice . public enum EthernetLinkSpeed { [ Description ( `` 10BASE-T '' ) ] _10BaseT , [ Description ( `` 100BASE-T '' ) ] _100BaseT , [ Description ( `` 1000BASE-T '' ) ] _1000BaseT , [ Description ( `` Disconnected '' ) ] Disconnected }",Is there a naming convention for enum values that have a leading digit ? "C_sharp : I have an XML file that already contains a reference to an XSLT file.I 'm looking at converting this XML file , according to the referenced transformation rules , so that I can then create a nice PDF file.It appears that I can perform the actual transform via System.Xml.Xsl.XslCompiledTransform , but it requires that I manually associate an XSLT before I perform the transform.Based on what I 've seen , I must now manually pull the XSLT reference from the XDocument ( rough start below ) : However , since the XSLT is already referenced within the XML file itself , I assume I 'm doing too much work , and there 's a more efficient way to apply the transform.Is there , or is this what one has to do ? xmlDocument.Document.Nodes ( ) .Where ( n = > n.NodeType == System.Xml.XmlNodeType.ProcessingInstruction )",Is there a more efficient way to transform an XDocument that already contains a reference to an XSLT ? "C_sharp : I am trying to resize images in a batch job . When I use the .Net provided classes , memory is not properly released so OutOfMemoryException is thrown . I think I use using statements properly . The code is below : Alternative to this code is to use FreeImage library . When I use FreeImage , there is no memory issue . Code with FreeImage : What is missing in my first code ? private static byte [ ] Resize ( byte [ ] imageBytes , int width , int height ) { using ( var img = Image.FromStream ( new MemoryStream ( imageBytes ) ) ) { using ( var outStream = new MemoryStream ( ) ) { double y = img.Height ; double x = img.Width ; double factor = 1 ; if ( width > 0 ) factor = width / x ; else if ( height > 0 ) factor = height / y ; var imgOut = new Bitmap ( ( int ) ( x * factor ) , ( int ) ( y * factor ) ) ; var g = Graphics.FromImage ( imgOut ) ; g.Clear ( Color.White ) ; g.DrawImage ( img , new Rectangle ( 0 , 0 , ( int ) ( factor * x ) , ( int ) ( factor * y ) ) , new Rectangle ( 0 , 0 , ( int ) x , ( int ) y ) , GraphicsUnit.Pixel ) ; imgOut.Save ( outStream , ImageFormat.Jpeg ) ; return outStream.ToArray ( ) ; } } } private static byte [ ] Resize ( byte [ ] imageBytes , int width , int height ) { var img = new FIBITMAP ( ) ; var rescaled = new FIBITMAP ( ) ; try { using ( var inStream = new MemoryStream ( imageBytes ) ) { img = FreeImage.LoadFromStream ( inStream ) ; rescaled = FreeImage.Rescale ( img , width , height , FREE_IMAGE_FILTER.FILTER_BICUBIC ) ; using ( var outStream = new MemoryStream ( ) ) { FreeImage.SaveToStream ( rescaled , outStream , FREE_IMAGE_FORMAT.FIF_JPEG ) ; return outStream.ToArray ( ) ; } } } finally { if ( ! img.IsNull ) FreeImage.Unload ( img ) ; img.SetNull ( ) ; if ( ! rescaled.IsNull ) FreeImage.Unload ( rescaled ) ; rescaled.SetNull ( ) ; } }",.Net Image resizing memory leak "C_sharp : Considering the following code : I was surprised to see the following result : My first expectation was that because I was passing an int , the default indexer should be used , and the first call should have succeeded.Instead , it seems that the overload expecting an enum is always called ( even when casting 0 as int ) , and the test fails.Can someone explain this behavior to me ? And give a workaround to maintain two indexers : one by index , and one for the enum ? EDIT : A workaround seems to be casting the collection as Collection , see this answer.So : Why does the compiler choose the most `` complex '' overload instead of the most obvious one ( despite the fact it 's an inherited one ) ? Is the indexer considered a native int method ? ( but without a warning on the fact that you hide the parent indexer ) ExplanationWith this code we are facing two problems : The 0 value is always convertible to any enum.The runtime always starts by checking the bottom class before digging in inheritance , so the enum indexer is chosen.For more precise ( and better formulated ) answers , see the following links : original answer by James Michael Haresum up by Eric Lippert namespace MyApp { using System ; using System.Collections.ObjectModel ; class Program { static void Main ( string [ ] args ) { var col = new MyCollection ( ) ; col.Add ( new MyItem { Enum = MyEnum.Second } ) ; col.Add ( new MyItem { Enum = MyEnum.First } ) ; var item = col [ 0 ] ; Console.WriteLine ( `` 1 ) Null ? { 0 } '' , item == null ) ; item = col [ MyEnum.Second ] ; Console.WriteLine ( `` 2 ) Null ? { 0 } '' , item == null ) ; Console.ReadKey ( ) ; } } class MyItem { public MyEnum Enum { get ; set ; } } class MyCollection : Collection < MyItem > { public MyItem this [ MyEnum val ] { get { foreach ( var item in this ) { if ( item.Enum == val ) return item ; } return null ; } } } enum MyEnum { Default = 0 , First , Second } } 1 ) Null ? True2 ) Null ? False",Overloaded indexer with enum : impossible to use default indexer "C_sharp : Why ca n't a dynamic object invoke these methods on the NameTranslate COM object when reflection can ? Failing example using dynamic : The third line fails with a NotImplementedException and the message The method or operation is not implemented.A similar attempt that works using a different COM object ( WScript.Shell and SendKeys ) : Getting back to the first sample . If I use reflection and invoke the methods using the InvokeMethod method things work fine . Working example using reflection : I believe this must have something to do with how the COM object is created or marked - but for the life of me I ca n't see anything in the docs , object browser or registry that indicates these COM objects and their subs/functions are marked private or something else that would normally throw off the dynamic keyword.NameTranslate documentation on MSDN : http : //msdn.microsoft.com/en-us/library/windows/desktop/aa706046.aspx Type ntt = Type.GetTypeFromProgID ( `` NameTranslate '' ) ; dynamic nto = Activator.CreateInstance ( ntt ) ; nto.Init ( 3 , null ) Type shellType = Type.GetTypeFromProgID ( `` WScript.Shell '' ) ; dynamic shell = Activator.CreateInstance ( shellType ) ; shell.SendKeys ( `` abc '' ) ; Type ntt = Type.GetTypeFromProgID ( `` NameTranslate '' ) ; object nto = Activator.CreateInstance ( ntt ) ; object [ ] initParams = new object [ ] { 3 , null } ; ntt.InvokeMember ( `` Init '' , BindingFlags.InvokeMethod , null , nto , initParams ) ;",Why does dynamic method invoke fail when reflection still works ? "C_sharp : I 'm trying to make a crossplatform C # application using C # , mono/GTK # on Linux and .NET/GTK # on Windows , however the startup sequence seems to need to be slightly different under the two platforms : Under Linux : Under Windows : Both require it to be done that way : Windows complains about g_thread_init ( ) not being called with the linux code , and linux complains about it already being called with the Windows code . Other than this , it all works wonderfully.My first attempt at a `` solution '' looked like : But even this messy solution does n't work ; the error is coming from GTK+ , unmanaged code , so it ca n't be caught . Does anyone have any bright ideas about the cause of the problem , and how to fix it ? Or , failing that , have bright ideas on how to detect which one should be called at runtime ? public static void Main ( string [ ] args ) { Gdk.Threads.Init ( ) ; // etc ... public static void Main ( string [ ] args ) { Glib.Thread.Init ( ) ; Gdk.Threads.Init ( ) ; // etc ... public static void Main ( string [ ] args ) { try { Gdk.Threads.Init ( ) ; } catch ( Exception ) { GLib.Thread.Init ( ) ; Gdk.Threads.Init ( ) ; } // etc ...","Crossplatform threading and GTK # , not working ( properly ) ?" "C_sharp : When porting an application that uses a settings file to an Azure Function , is it necessary to remove reliance on the file ? I want to write a function app to import data from Xero into an Azure sql database.The Xero SDK I am using is expecting an appsettings.json file.Consequently when the function runs I get the errorI tried putting the relevant settings in via the Manage Application Settings link on the VS2017 Project Publish Tab . Clearly this fails . Is there another way I can use ? Here is the relevant code in the api . I would prefer not to have to modify it , so that I can use the official nuget package.When I add to the function I getwhen running in the portal System.Private.CoreLib : Exception while executing function : FunctionXeroSync . Xero.Api : The type initializer for 'Xero.Api.Infrastructure.Applications.Private.Core ' threw an exception . Microsoft.Extensions.Configuration.FileExtensions : The configuration file 'appsettings.json ' was not found and is not optional . The physical path is ' C : \Users\kirst\AppData\Local\AzureFunctionsTools\Releases\2.6.0\cli\appsettings.json ' . namespace Xero.Api { public class XeroApiSettings : IXeroApiSettings { public IConfigurationSection ApiSettings { get ; set ; } public XeroApiSettings ( string settingspath ) { var builder = new ConfigurationBuilder ( ) .AddJsonFile ( settingspath ) .Build ( ) ; ApiSettings = builder.GetSection ( `` XeroApi '' ) ; } public XeroApiSettings ( ) : this ( `` appsettings.json '' ) { } public string BaseUrl = > ApiSettings [ `` BaseUrl '' ] ; public string CallbackUrl = > ApiSettings [ `` CallbackUrl '' ] ; public string ConsumerKey = > ApiSettings [ `` ConsumerKey '' ] ; public string ConsumerSecret = > ApiSettings [ `` ConsumerSecret '' ] ; public string SigningCertificatePath = > ApiSettings [ `` SigningCertPath '' ] ; public string SigningCertificatePassword = > ApiSettings [ `` SigningCertPassword '' ] ; public string AppType = > ApiSettings [ `` AppType '' ] ; public bool IsPartnerApp = > AppType ? .Equals ( `` partner '' , StringComparison.OrdinalIgnoreCase ) ? ? false ; } } log.LogInformation ( `` base directory : `` +AppDomain.CurrentDomain.BaseDirectory ) ; D : \Program Files ( x86 ) \SiteExtensions\Functions\2.0.12095-alpha\32bit\","Can I , how do I , supply a settings file to an Azure Function ?" "C_sharp : I have some code generating expressions to pass as the `` where '' statement in a database read , and I 'm trying to speed things up a bit.This example below makes a where statement to match the PK of a table with a passed in value : The above is a simplification for the question - the real thing includes code to take the table to query on and find its PK etc . It is effectively doing the same thing as you might do in code usually : This works ok , but , while doing to testing to optimize things a bit I 've found its rather slow - doing the above 1000000 times takes around 25 secs . Its better if I omit the last line above ( but obviously then it 's useless ! ) , so it appears to be Expression.Lamba that taking around 2/3rds of the time , but the rest is n't great either.If all the queries were going to happen at once I could turn it into an IN style expression and generate once , but unfortunately that 's not possible , so what I 'm hoping for is to save on most of the generation above , and just reuse the generated expression , but passing in a different value of id.Note that , as this is going to be passed to Linq , I ca n't compile the expression to have an integer parameter that I can pass in on invocation - it must remain as the expression tree.So the following might be an simple version for the purposes of doing the timing exercise : How might I re-use the expression , just with a different value of id ? private Expression MakeWhereForPK ( int id ) { var paramExp = Expression.Parameter ( typeof ( Brand ) , '' b '' ) ; //Expression to get value from the entity var leftExp = Expression.Property ( paramExp , '' ID '' ) ; //Expression to state the value to match ( from the passed in variable ) var rightExp = Expression.Constant ( id , typeof ( int ) ) ; //Expression to compare the two var whereExp = Expression.Equal ( leftExp , rightExp ) ; return Expression.Lambda < Func < Brand , bool > > ( whereExp , paramExp ) ; } ctx.Brands.Where ( b = > b.ID = id ) ; Expression < Func < Brand , bool > > savedExp ; private Expression MakeWhereForPKWithCache ( int id ) { if ( savedExp == null ) { savedExp = MakeWhereForPK ( id ) ; } else { var body = ( BinaryExpression ) savedExp.Body ; var rightExp = ( ConstantExpression ) body.Right ; //At this point , value is readonly , so is there some otherway to `` inject '' id , //and save on compilation ? rightExp.Value = id ; } return savedExp ; }",Changing the value of a ConstantExpression in a pre-existing BinaryExpression "C_sharp : I have a Dictionary : where TCHEMISTRY and TDRILLSPAN are classes . Then I want to get rows from one of this classes like this : All this code works correctly . After that I need to get some rows like this : But this line causes error : `` Could not find an implementation of the query pattern for source type 'object ' . 'Where ' not found . `` What 's wrong with this code line ? Dictionary < int , Type > AllDrillTypes = new Dictionary < int , Type > ( ) { { 13 , typeof ( TCHEMISTRY ) } , { 14 , typeof ( TDRILLSPAN ) } } ; Type T = AllDrillTypes [ 13 ] ; var LC = Activator.CreateInstance ( typeof ( List < > ) .MakeGenericType ( T ) ) ; MethodInfo M = T.GetMethod ( `` FindAll '' , BindingFlags.Public | BindingFlags.Static , null , new Type [ ] { } , null ) ; LC = M.Invoke ( null , new object [ ] { } ) ; var LingLC = from obj in LC where obj.RunID == 1001 select obj ;",how to get values from var-source with linq "C_sharp : When I first started to program in C # last year , I immediately looked for the equivalent to STL 's map , and learned about Dictionary.UPDATE crossed out this garbage below , I was completely wrong . My experience with STL 's map was that I hated when I requested it for a value , and if the key was n't in the map , it would automatically create the value type ( whatever its default constructor did ) and add it to the map . I would have to then check for this condition in code and throw an exception.Dictionary < > gets the whole shebang correct -- if the key is n't there , it throws the exception if you 're requesting the value , or automatically adds it if it 's not and you want to set the value.But you all already knew that . I should have written my unit tests before posting here and embarrassing myself . : ) They 're written now ! Now I love Dictionary and all , but the thing that bugs me the most about it right now is that if the key is n't in the Dictionary , it throws a KeyNotFoundException . Therefore , I always need to write code like this : Why does n't Dictionary automatically add the key value pair if the key does n't exist , like STL 's map ? Now the funny thing is that in a previous life , I used to get annoyed because I 'd often have to try to prevent map from doing just that . I guess my use cases right now are a little different . Dictionary < string , string > _mydic ; public string this [ string key ] { get { return _mydic [ key ] ; // could throw KeyNotFoundException } set { if ( _mydic.ContainsKey ( key ) ) _mydic [ key ] = value ; else _mydic.Add ( key , value ) ; } }","Can anyone explain why Dictionary < > in C # does n't work like map < T , U > in STL ?" "C_sharp : I 'm implementing a Diffie-Hellman key exchange algorithm between an embedded device which uses OpenSSL libraries for BIGNUM operations and a C # software which uses System.Numerics.BigInteger methods to calculate the secret shared key generation . But after Alice and Bob exchange keys , they calculate different shared secrets.The keys are printed out on each side ( PubA , PrivA , PubB , PrivB , DHPrime , DHGenerator ) and I can see that they are the same.I suspect there is an issue about little/big endianness , or maybe openssl does n't care about negative numbers for the exponent , and I do n't know how to debug those operations . I do n't have the code with me right now , but all the operations are kept simple , like this . C # sideC sideSome additional info for C methods of OpenSSL : > BN_bin2bn sets |*ret| to the value of |len| bytes from |in| , interpreted as a big-endian number , and returns |ret| . If |ret| is NULL then a fresh |BIGNUM| is allocated and returned . It returns NULL on allocation failure . BN_mod_exp sets |r| equal to |a|^ { |p| } mod |m| . It does so with the best algorithm for the values provided and can run in constant time if |BN_FLG_CONSTTIME| is set for |p| . It returns one on success or zero otherwise.And they produce different results . What should I do about this ? What would be your next thing to check ? Thanks in advance . BigInteger bintA = new BigInteger ( baByteArrayReceived ) ; BigInteger bintb = new BigInteger ( baRandomBobSecret ) ; BigInteger bintDHPrime = new BigInteger ( baDHPrime2048 ) ; BigInteger bintSharedSecret = bintA.ModPow ( bintb , bintDHPrime ) ; BIGNUM *bnB = BN_new ( ) ; BIGNUM *bna = BN_new ( ) ; BIGNUM *bnDHPrime = BN_new ( ) ; BIGNUM *bnResult = BN_new ( ) ; BN_CTX *bnctx = BN_CTX_new ( ) ; BN_bin2bn ( baBReceived , 256 , bnB ) ; BN_bin2bn ( baRandomAliceSecret , 256 , bna ) ; BN_bin2bn ( baDHPrime2048 , 256 , bnDHPrime ) ; BN_mod_exp ( bnResult , bnB , bna , bnDHPrime , bnctx ) ; BIGNUM *BN_bin2bn ( const uint8_t *in , size_t len , BIGNUM *ret ) ; int BN_mod_exp ( BIGNUM *r , const BIGNUM *a , const BIGNUM *p , const BIGNUM *m , BN_CTX *ctx ) ;",Diffie-Hellman with BIGNUM ( OpenSSL ) vs. BigInteger ( C # ) "C_sharp : My issue is actually close to this one : Umbraco V6 404 not handled properly according to cultureI have 2 directories with different culture : When I go from a FR page to a 404 , the culture is back in english.It looks like it 's url-based , and probably with a 404 the engine ca n't find a link so it sets the culture as default but I would like to maintain this culture when the user meets a 404 page.my config : How can I do that ? I use one-level path in domains.Example of urls : site/en/page1 site/en/page2site/fr/page1I use umbraco 7.2.5 Content EN page1 page2 404 FR page1 404 < error404 > < errorPage culture= '' en-US '' > 1187 < /errorPage > < errorPage culture= '' fr-FR '' > 1189 < /errorPage > < /error404 >",Umbraco 404 with different culture not working "C_sharp : I made the following linq statementC # That returns But I am trying to make it into this formatHow could I modify the statement to get the result I 'm looking for ? Non linq answers are acceptable too.EDIT : Region is the parent of SubRegion , SubRegion is the parent of Country and Count is the unique number of items that belongs to Country var list = from row in repository.GetAllEntities ( ) group row by new { row.RegionString , row.SubRegionString , row.CountryString } into g select new { g.Key.RegionString , g.Key.SubRegionString , g.Key.CountryString , Count = g.Count ( ) } ; return Json ( list , JsonRequestBehavior.AllowGet ) ; [ { `` RegionString '' : '' Americas '' , `` SubRegionString '' : '' '' , `` CountryString '' : '' '' , `` Count '' :2 } , { `` RegionString '' : '' Americas '' , `` SubRegionString '' : '' NorthAmerica '' , `` CountryString '' : '' Canada '' , `` Count '' :5 } , { `` RegionString '' : '' Americas '' , `` SubRegionString '' : '' NorthAmerica '' , `` CountryString '' : '' US '' , `` Count '' :3 } , { `` RegionString '' : '' Americas '' , `` SubRegionString '' : '' SouthAmerica '' , `` CountryString '' : '' Chile '' , `` Count '' :3 } , { `` RegionString '' : '' EMEA '' , `` SubRegionString '' : '' AsiaPacific '' , `` CountryString '' : '' Australia '' , `` Count '' :2 } , { `` RegionString '' : '' EMEA '' , `` SubRegionString '' : '' AsiaPacific '' , `` CountryString '' : '' Japan '' , `` Count '' :1 } , { `` RegionString '' : '' EMEA '' , `` SubRegionString '' : '' SouthernEurope '' , `` CountryString '' : '' Turkey '' , `` Count '' :1 } , { `` RegionString '' : '' EMEA '' , `` SubRegionString '' : '' WesternEurope '' , `` CountryString '' : '' '' , `` Count '' :1 } ] [ { name : `` Americas '' , children : [ { name : `` NorthAmerica '' , children : [ { `` name '' : `` Canada '' , `` count '' : 5 } , { `` name '' : `` US '' , `` count '' : 3 } ] } , { name : `` SouthAmerica '' , children : [ { `` name '' : `` Chile '' , `` count '' : 1 } ] } , ] , } , { name : `` EMA '' , children : [ { name : `` AsiaPacific '' , children : [ { `` name '' : `` Australia '' , `` count '' : 2 } , { `` name '' : `` Japan '' , `` count '' : 1 } ] } , { name : `` SouthernEurope '' , children : [ { `` name '' : `` Turkey '' , `` count '' : 1 } ] } , ] , } ]",C # + EntityFramework : Convert multiple group by query to nested JSON "C_sharp : I 'm primarily a C++ developer , but recently I 've been working on a project in C # . Today I encountered some behavior that was unexpected , at least to me , while using object initializers . I 'm hoping someone here can explain what 's going on.Example AExample BExample A works as I 'd expect . The object passed into PassInFoo has Bar set to true . However , in Example B , foo.Bar is set to true , despite being assigned false in the object initializer . What would be causing the object initializer in Example B to be seemingly ignored ? public class Foo { public bool Bar = false ; } PassInFoo ( new Foo { Bar = true } ) ; public class Foo { public bool Bar = true ; } PassInFoo ( new Foo { Bar = false } ) ;","In C # , how do field initializers and object initializers interact ?" "C_sharp : I 'm having some inheritance issues as I 've got a group of inter-related abstract classes that need to all be overridden together to create a client implementation . Ideally I would like to do something like the following : This would allow anyone using the Dog class to automatically get DogLegs and anyone using the Animal class to get Legs . The problem is that the overridden function has to have the same type as the base class so this will not compile . I do n't see why it should n't though , since DogLeg is implicitly castable to Leg . I know there are plenty of ways around this , but I 'm more curious why this is n't possible/implemented in C # .EDIT : I modified this somewhat , since I 'm actually using properties instead of functions in my code . EDIT : I changed it back to functions , because the answer only applies to that situation ( covariance on the value parameter of a property 's set function should n't work ) . Sorry for the fluctuations ! I realize it makes a lot of the answers seem irrelevant . abstract class Animal { public Leg GetLeg ( ) { ... } } abstract class Leg { } class Dog : Animal { public override DogLeg Leg ( ) { ... } } class DogLeg : Leg { }",Why does n't inheritance work the way I think it should work ? C_sharp : If I wrote this code : Would it use reflection ? How much different from : is it ? typeof ( myType ) .TypeHandle Type.GetType ( string ) .TypeHandle,Does typeof ( myType ) .TypeHandle use reflection ? "C_sharp : I have some custom wrapper types defined with an explicit cast operation : The following works just fine : This does not : ... what 's going on here ? I 'm constrained to have the cast to object first - the actual cast is being performed elsewhere in generic library code ( so it 's of the form return ( TOutput ) ( object ) input ; , and dynamic is not an option ) private class A { private readonly int _value ; public A ( int value ) { _value = value ; } public int Value { get { return _value ; } } } private class B { private readonly int _value ; private B ( int value ) { _value = value ; } public int Value { get { return _value ; } } public static explicit operator B ( A value ) { return new B ( value.Value ) ; } } B n = ( B ) new A ( 5 ) ; B n = ( B ) ( object ) new A ( 5 ) ; // Throws System.InvalidCastException : // Unable to cast object of type ' A ' to type ' B '",Explicit cast to defined type throws ` InvalidCastException ` "C_sharp : I have this function : which I want to document.I want the < return > tag to say string.Join ( separator , strings.ToArray ( ) ) since to anyone able to read C # code this says more than a thousand words . However , when I use then string.Join ( separator , strings.ToArray ( ) ) will be formatted as plain text , which makes it almost unreadable . So I tried but this always creates a new paragraph ... So here 's my question : Is there a way to format a piece of text so that it appears as if it were code ? I 'd be satisfied with a fixed-width font . public static string Join ( this IEnumerable < string > strings , string separator ) { return string.Join ( separator , strings.ToArray ( ) ) ; } < return > string.Join ( separator , strings.ToArray ( ) ) < /return > < return > < code > string.Join ( separator , strings.ToArray ( ) ) < /code > < /return >",How to tag code in C # XML documentation "C_sharp : I want to know is there anyway to put contentpresenter in itemtemplate of an itemscontrol to display my data . I do n't want hard code binding like Text= '' { Binding username } '' cause I am building a custom control , I think ContentPresenter is what I want . But after I tried using contentpresenter , it give me stackoverflowexception.That 's my code . If without those seperator and itemtemplate , I able to display my data by just using the displaymemberpath , but it stack all the name together . I still finding any solution to solve it . I hope you can provide some ideas to do this . < ItemsControl ItemsSource= '' { Binding SelectedItems , ElementName=listbox } '' DisplayMemberPath= { Binding DisplayMemberPath } '' > < ItemsControl.ItemPanel > < ItemsPanelTemplate > < StackPanel Orientation= '' Horizontal '' IsItemsHost= '' True '' / > < /ItemsPanelTemplate > < /ItemsControl.ItemPanel > < ItemsControl.ItemTemplate > < DataTemplate > < StackPanel Orientation= '' Horizontal '' > < TextBlock x : Name= '' Separator '' Text= '' , `` / > < ContentPresenter/ > < ! -- < TextBlock Text= '' { Binding username } '' / > -- > < /StackPanel > < /DataTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl >",ContentPresenter in ItemControl.ItemTemplate to show displaymemberpath of itemscontrol C_sharp : I´m using EF6 and trying to eager fetch the whole structure of an object . The problem is that i´m using inheritance.Let´s say that i have this classes.DbContextExample classesThe error i get is : Why doesn´t it work with the following ? New exampleEDIT : Added a new example that seems to work . DbSet < A > A { get ; set ; } public class A { public string Id { get ; set ; } public IList < Base > Bases { get ; set ; } } public abstract class Base { public int Id { get ; set ; } public string Name { get ; set ; } } public abstract class Base1 : Base { public SomeClass SomeClass { get ; set ; } } public class Base2 : Base1 { } public class Base3 : Base1 { public SomeOtherClass SomeOtherClass { get ; set ; } } The Include path expression must refer to a navigation property defined on the type . Use dotted paths for reference navigation properties and the Select operator for collection navigation properties . public IEnumerable < A > GetAll ( string id ) { return _ctx.A .Include ( x = > x.Bases.OfType < Base1 > ( ) .Select ( y= > y.SomeClass ) ) .Where ( x = > x.Id.Equals ( id ) ) .ToList ( ) ; } public IEnumerable < A > GetAll ( string id ) { var lists = _dbContext.A.Where ( x = > x.Id == id ) ; lists.SelectMany ( a = > a.Bases ) .OfType < Base1 > ( ) .Include ( e= > e.SomeClass ) .Load ( ) ; lists.SelectMany ( b = > b.Bases ) .OfType < Base3 > ( ) .Include ( e = > e.SomeOtherClass ) .Load ( ) ; return lists ; },EF Eager fetching derived class "C_sharp : I want to get the names of all properties that changed for matching objects . I have these ( simplified ) classes : Now I want to get the objects where the Property values differ : In the end I would like to have a list of Differences like this : The ChangedProperties should contain the name of the changed properties . public enum PersonType { Student , Professor , Employee } class Person { public string Name { get ; set ; } public PersonType Type { get ; set ; } } class Student : Person { public string MatriculationNumber { get ; set ; } } class Subject { public string Name { get ; set ; } public int WeeklyHours { get ; set ; } } class Professor : Person { public List < Subject > Subjects { get ; set ; } } List < Person > oldPersonList = ... List < Person > newPersonList = ... List < Difference > = GetDifferences ( oldPersonList , newPersonList ) ; public List < Difference > GetDifferences ( List < Person > oldP , List < Person > newP ) { //how to check the properties without casting and checking //for each type and individual property ? ? //can this be done with Reflection even in Lists ? ? } class Difference { public List < string > ChangedProperties { get ; set ; } public Person NewPerson { get ; set ; } public Person OldPerson { get ; set ; } }",Compare Properties automatically "C_sharp : I have the following block of code that retrieves a document node in kentico and deletes it . It does delete the kentico node , but not the underlying document type which stays in the datase . Help ? ! CMS.TreeEngine.TreeProvider provider = new CMS.TreeEngine.TreeProvider ( CMS.CMSHelper.CMSContext.CurrentUser ) ; CMS.TreeEngine.TreeNode image = provider.SelectSingleNode ( new Guid ( imageID ) , `` en-US '' , CMS.CMSHelper.CMSContext.CurrentSite.SiteName ) ; if ( image ! = null ) { CMS.TreeEngine.TreeNode school = provider.SelectSingleNode ( image.Parent.NodeID , `` en-US '' , true , true ) ; if ( school ! = null ) { string CMSUserID = school.GetValue ( `` CMSUserID '' ) .ToString ( ) ; if ( CMSUserID == ui.UserID.ToString ( ) ) { image.Delete ( false ) ; } } }",Kentico TreeNode Delete method not deleting dependencies "C_sharp : Let me elaborate . By `` items '' I mean all the items you see one the desktop ( Windows ) which includes `` My Computer '' , `` Recycle Bin '' , all the shortcuts etc . If I select all the items on the desktop I get the count in the properties displayed . It is this count I want , programmatically.The problem I face : The desktop as we see has items from my account , also the All Users 's desktop items and also other shortcuts like `` My Computer '' , `` Recycle Bin '' . In total , 3 things . So I ca n't just get the item count from the physical path to Desktop directory . So this fails : I know SpecialFolder.Desktop stands for the logical desktop as we see . But this fails again since GetFolderPath ( ) again gets the physical path of user 's desktop : What is the right way to get total count on the user 's desktop ? int count = Directory.GetFiles ( Environment.GetFolderPath ( Environment.SpecialFolder .DesktopDirectory ) ) .Length ; int count = Directory.GetFiles ( Environment.GetFolderPath ( Environment.SpecialFolder .Desktop ) ) .Length ;",How to get the total number of items on the ( logical ) desktop ( C # ) "C_sharp : In my application I previously used regular C # attributes to `` annotate '' a method . E.g . : What SpecialAttributeLogicHere ( ) did , was to reflectively look at all the Foo-attributes that annotated this particular method . It would then ( on its own ) , create its own dictionary for all the keys and values.I 'm now trying to move to PostSharp , because the SpecialAttributeLogic could be put into an aspect ( and removed from the method body which is much cleaner ! ) , within OnEntry . Foo will be replaced by an aspect that extends OnMethodBoundaryAspect.I would still like to use it the following way : But if Foo has an OnEntry , that means that the `` SpecialAttributeLogic '' will be executed twice . I basically need to `` gather '' all the keys and values from each Foo ( ) , into a dictionary , which I then apply some logic to.How to do this ( or best practices ) with PostSharp ? Thanks ! [ Foo ( SomeKey= '' A '' , SomeValue= '' 3 '' ) ] [ Foo ( SomeKey= '' B '' , SomeValue= '' 4 '' ) ] public void TheMethod ( ) { SpecialAttributeLogicHere ( ) ; } [ Foo ( SomeKey= '' A '' , SomeValue= '' 3 '' ) ] [ Foo ( SomeKey= '' B '' , SomeValue= '' 4 '' ) ]",Multiple aspects on one method C_sharp : A couple of times I have came across this code where a local variable in a class ( its NOT a static variable ) has been used in a lock.Is there any point of locking given that its an instance variables ? public class SomeClass { private object obj = new object ( ) ; ... . ... . lock ( obj ) { } },What is the point of using a non-static local variable in a lock ? "C_sharp : I 'm trying to downgrade some .NET 4.6 code to .NET 4.5 . This is the code block im working with at the moment : data is byte* type so I do n't know if Buffer.BlockCopy ( ) is a reasonable replacement since it takes in Arrays.Any ideas ? fixed ( byte* destination = dataBytes ) { Buffer.MemoryCopy ( data , destination , dataLength , dataLength ) ; }",Best alternative to Buffer.MemoryCopy pre .NET 4.6 "C_sharp : When my app starts , I see that following lines are written to the output window : I like to add these lines to my log file ( and assign timestamp ) for some performance measurements . I 've tried to do that with the following class I created.But this does n't work . The Write ( ) method is never called . Any ideas ? 'MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\PresentationFramework.Luna\3.0.0.0__31bf3856ad364e35\PresentationFramework.Luna.dll ' , Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\PresentationFramework.Aero\3.0.0.0__31bf3856ad364e35\PresentationFramework.Aero.dll ' , Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\PresentationFramework.resources\3.0.0.0_nl_31bf3856ad364e35\PresentationFramework.resources.dll '' MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\System.Data.SqlServerCe\3.5.1.0__89845dcd8080cc91\System.Data.SqlServerCe.dll ' , Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_32\System.Transactions\2.0.0.0__b77a5c561934e089\System.Transactions.dll ' , Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_32\System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll ' , Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\System.Data.resources\2.0.0.0_nl_b77a5c561934e089\System.Data.resources.dll '' MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded ' C : \WINDOWS\assembly\GAC_MSIL\System.Xml.Linq\3.5.0.0__b77a5c561934e089\System.Xml.Linq.dll ' , Skipped loading symbols . Module is optimized and the debugger option 'Just My Code ' is enabled . 'MyApp.exe ' ( Managed ( v2.0.50727 ) ) : Loaded 'Anonymously Hosted DynamicMethods Assembly ' public static class ConsoleLogger { public class LogWriter : TextWriter { public LogWriter ( ) { } public override Encoding Encoding { get { return Encoding.UTF8 ; } } public override void Write ( string value ) { Logger.Info ( value ) ; } } public static void RedirectConsoleLog ( ) { Console.SetOut ( new LogWriter ( ) ) ; } }",Redirect output window to log file "C_sharp : Consider an ASP.NET page with this code : The application should be highly performance-tuned and handle thousands on concurrent requests and the main purpose is transferring huge binary file to clients over high speed connections . I can do the job with an ASP.NET page , with HTTP Handler , IHttpAsyncHandler , ISAPI filter and ... The question is what is the best choice for this purpose ? while ( read ) { Response.OutputStream.Write ( buffer , 0 , buffer.Length ) ; Response.Flush ( ) ; }",What 's the best practice for transferring huge binary files with ASP.NET ? "C_sharp : Using AutoFixture as a SutFactory , I can see that if I register or freeze a value for a type , that value will then be used for all subsequent usages of that type . However , if I have a class with two parameters that are the same type on the constructor such as : What strategies exist for using autofixture to inject unique pre-defined values for parameterA and parameterB with a view to testing the Calculated value ? *Unfortunately I ca n't share my exact scenario here , however its using the command pattern to operate on another object , so the only way of setting parameterA and parameterB maintaining the design is to inject them both in , and the constructor is the neatest way to do this in this case . public class ClassA { public double ParameterA { get ; private set ; } public double ParameterB { get ; private set ; } public ClassA ( double parameterA , double parameterB ) { ParameterA = parameterA ; ParameterB = parameterB ; } public void Execute ( ClassB object ) { object.Value = ( object.Value * ParameterA ) /ParameterB ; } }",Defining/managing > 1 constructor parameters of the same type with independent values when using AutoFixture as a SutFactory "C_sharp : I essentially define IFoo twice in the Inherited class . Does that cause some unforeseen consequences ? The reason I want to make IBar inherit from IFoo is so I can work on Derived as it was IFoo without having to cast it.If it does n't inherit I have to cast it . Which makes use more complicated , and users of the class might not understand that IBar just is a specialization of IFoo.Is this bad practice ? What other solutions are there to this problem ? interface IFoo { ... } interface IBar : IFoo { ... } class Base : IFoo { ... } class Derived : Base , IBar { ... } if ( Derived is IBar ) // Do work if ( Derived is IBar ) Derived as IFoo // Do work",Defining interface multiple times on inherited class "C_sharp : I 'm using this solution to delete all empty folders and subdirectories in a certain path : It works perfectly . But I want to delete all empty folders and also folders which are not empty but also does n't contain files with the .dvr extension.For example , my folder has the files : a.logb.logc.dvrd.datSo this folder ca n't be deleted , for it contains a file with the dvr extension.How can I filter it ? ( I 'm using GTK # but I believe C # code will work , since this solution is a C # code ) static void Main ( string [ ] args ) { processDirectory ( @ '' c : \temp '' ) ; } private static void processDirectory ( string startLocation ) { foreach ( var directory in Directory.GetDirectories ( startLocation ) ) { processDirectory ( directory ) ; if ( Directory.GetFiles ( directory ) .Length == 0 & & Directory.GetDirectories ( directory ) .Length == 0 ) { Directory.Delete ( directory , false ) ; } } }",Delete all folders and subdirectories that does n't have a file of certain extension "C_sharp : It 's a well known fact that the .NET garbage collector does n't just 'delete ' the objects on the heap , but also fights memory fragmentation using memory compaction . From what I understand , basically memory is copied to a new place , and the old place is at some point deleted . My question is : how does this work ? What I 'm mostly curious about is the fact that the GC runs in a separate thread , which means that the object we 're working on can be moved by the GC while we 're executing our code . Technical details of the questionTo illustrate , let me explain my question in more detail : In this small example , we create an object and set a simple variable on an object . The point '*** ' is all that matters for the question : if the address of 'tmp ' moves , 'foo ' will reference something incorrect and everything will break.The garbage collector runs in a separate thread . So as far as I know , 'tmp ' can be moved during this instruction and 'foo ' can end up with the incorrect value . But somehow , magic happens and it doesn't.As for the disassembler , I noticed that the compiled program really takes the address of 'foo ' and moves in the value '12 : I more or less expected to see an indirect pointer here , which can be updated- but apparently the GC works smarter than that.Further , I do n't see any thread synchronization that checks if the object has been moved . So how does the GC update the state in the executing thread ? So , how does this work ? And if the GC does n't move these objects , what is the 'rule ' that defines wether or not to move the objects ? class Program { private int foo ; public static void Main ( string [ ] args ) { var tmp = new Program ( ) ; // make an object if ( args.Length == 2 ) // depend the outcome on a runtime check { tmp.foo = 12 ; // set value *** } Console.WriteLine ( tmp.foo ) ; } } 000000ae 48 8B 85 10 01 00 00 mov rax , qword ptr [ rbp+00000110h ] 000000b5 C7 40 08 0C 00 00 00 mov dword ptr [ rax+8 ] ,0Ch",How does the .NET runtime move memory ? "C_sharp : I 've got a complex class in my C # project on which I want to be able to do equality tests . It is not a trivial class ; it contains a variety of scalar properties as well as references to other objects and collections ( e.g . IDictionary ) . For what it 's worth , my class is sealed.To enable a performance optimization elsewhere in my system ( an optimization that avoids a costly network round-trip ) , I need to be able to compare instances of these objects to each other for equality – other than the built-in reference equality – and so I 'm overriding the Object.Equals ( ) instance method . However , now that I 've done that , Visual Studio 2008 's Code Analysis a.k.a . FxCop , which I keep enabled by default , is raising the following warning : warning : CA2218 : Microsoft.Usage : Since 'MySuperDuperClass ' redefines Equals , it should also redefine GetHashCode.I think I understand the rationale for this warning : If I am going to be using such objects as the key in a collection , the hash code is important . i.e . see this question . However , I am not going to be using these objects as the key in a collection . Ever.Feeling justified to suppress the warning , I looked up code CA2218 in the MSDN documentation to get the full name of the warning so I could apply a SuppressMessage attribute to my class as follows : However , while reading further , I noticed the following : How to Fix Violations To fix a violation of this rule , provide an implementation of GetHashCode . For a pair of objects of the same type , you must ensure that the implementation returns the same value if your implementation of Equals returns true for the pair . When to Suppress Warnings -- -- - > Do not suppress a warning from this rule . [ arrow & emphasis mine ] So , I 'd like to know : Why should n't I suppress this warning as I was planning to ? Does n't my case warrant suppression ? I do n't want to code up an implementation of GetHashCode ( ) for this object that will never get called , since my object will never be the key in a collection . If I wanted to be pedantic , instead of suppressing , would it be more reasonable for me to override GetHashCode ( ) with an implementation that throws a NotImplementedException ? Update : I just looked this subject up again in Bill Wagner 's good book Effective C # , and he states in `` Item 10 : Understand the Pitfalls of GetHashCode ( ) '' : If you 're defining a type that wo n't ever be used as the key in a container , this wo n't matter . Types that represent window controls , web page controls , or database connections are unlikely to be used as keys in a collection . In those cases , do nothing . All reference types will have a hash code that is correct , even if it is very inefficient . [ ... ] In most types that you create , the best approach is to avoid the existence of GetHashCode ( ) entirely ... . that 's where I originally got this idea that I need not be concerned about GetHashCode ( ) always . [ SuppressMessage ( `` Microsoft.Naming '' , `` CA2218 : OverrideGetHashCodeOnOverridingEquals '' , Justification= '' This class is not to be used as key in a hashtable . '' ) ]",Overriding Object.Equals ( ) instance method in C # ; now Code Analysis/FxCop warning CA2218 : `` should also redefine GetHashCode '' . Should I suppress this ? C_sharp : I have a method like : This method is used as follows : I also want to log exceptions that were caught inside Foo ( ) . I can not use throw in catch inside of Foo.How can I catch such exceptions ? Example : public TResult DoSomethingWithLogging < TResult > ( Func < TResult > someAction ) { try { return someAction.Invoke ( ) ; } catch ( Exception ex ) { LogException ( ex ) throw ; } var result = DoSomethingWithLogging ( ( ) = > Foo ( ) ) ; public static string Foo ( ) { try { return `` Foo '' ; } catch ( Exception ) { // I have to log this exception too without adding anything to Foo return `` Exception caught '' ; } },Log caught exceptions from outside the method in which they were caught "C_sharp : Given that you have in your AssemblyInfo.cs file , when is Log4Net configured ? Is it at the application start or when you use a logger for the first time ? [ assembly : log4net.Config.XmlConfigurator ( ConfigFile = `` Log4Net.config '' , Watch = true ) ]",When is Log4Net configured ? "C_sharp : Trying to figure out whether or not I should use async methods or not such as : TcpListener.BeginAcceptTcpClientTcpListener.EndcceptTcpClientandNetworkStream.BeginReadNetworkStream.EndReadas opposed to their synchronous TcpListener.AcceptTcpClient and NetworkStream.Read versions . I 've been looking at related threads but I 'm still a bit unsure about one thing : Question : The main advantage of using an asynchronous method is that the GUI is not locked up . However , these methods will be called on separate Task threads as it is so there is no threat of that . Also , TcpListener.AcceptTcpClient blocks the thread until a connection is made so there is no wasted CPU cycles . Since this is the case , then why do so many always recommend using the async versions ? It seems like in this case the synchronous versions would be superior ? Also , another disadvantage of using asynchronous methods is the increased complexity and constant casting of objects . For example , having to do this : As opposed to this : TcpClient client = listener.AcceptTcpClient ( ) ; Also it seems like the async versions would have much more overhead due to having to create another thread . ( Basically , every connection would have a thread and then when reading that thread would also have another thread . Threadception ! ) Also , there is the boxing and unboxing of the TcpListener and the overhead associated with creating , managing , and closing these additional threads.Basically , where normally there would just be individual threads for handling individual client connections , now there is that and then an additional thread for each type of operation performed ( reading/writing stream data and listening for new connections on the server 's end ) Please correct me if I am wrong . I am still new to threading and I 'm trying to understand this all . However , in this case it seems like using the normal synchronous methods and just blocking the thread would be the optimal solution ? private void SomeMethod ( ) { // ... listener.BeginAcceptTcpClient ( OnAcceptConnection , listener ) ; } private void OnAcceptConnection ( IAsyncResult asyn ) { TcpListener listener = ( TcpListener ) asyn.AsyncState ; TcpClient client = listener.EndAcceptTcpClient ( asyn ) ; }",Is it necessary to use the async Begin/End methods if already on a separate thread ? "C_sharp : I have a number of classes that derive from a class BaseClass where BaseClass just has an ` Id property.I now need to do distinct on a collections of some of these objects . I have the following code over and over for each of the child classes : Given the logic is just based on Id , I wanted to created a single comparer to reduce duplication : But this does n't seem to compile : ... as it says it ca n't convert from BaseClass to Position . Why does the comparer force the return value of this Distinct ( ) call ? public class PositionComparer : IEqualityComparer < Position > { public bool Equals ( Position x , Position y ) { return ( x.Id == y.Id ) ; } public int GetHashCode ( Position obj ) { return obj.Id.GetHashCode ( ) ; } } public class BaseClassComparer : IEqualityComparer < BaseClass > { public bool Equals ( BaseClass x , BaseClass y ) { return ( x.Id == y.Id ) ; } public int GetHashCode ( BaseClass obj ) { return obj.Id.GetHashCode ( ) ; } } IEnumerable < Position > positions = GetAllPositions ( ) ; positions = allPositions.Distinct ( new BaseClassComparer ( ) )","Doing Distinct ( ) using base class IEqualityComparer , and still return the child class type ?" "C_sharp : So I have a Generic class ( it 's mostly a container class ) with implicit casting , like this : So in runtime I would like to cast an instance of Container < int > to int using reflection but can not seem to find a way , I 've tried the `` Cast '' method invoking mentioned in a couple of places but I 'm getting an Specified cast is not valid . exception . Any help will be appreciated . public class Container < T > { public T Value { get ; set ; } public static implicit operator T ( Container < T > t ) { return t.Value ; } public static implicit operator Container < T > ( T t ) { return new Container < T > ( ) { Value = t } ; } }",Execute implicit cast at runtime "C_sharp : What I want to accomplish is to convert a DateTime ( parsed from a string assumed to be in EST/EDT ) to UTC . I am using NodaTime because I need to use Olson timezones.Converting an invalid ( skipped ) DateTime to UTC using NodaTime 's ZoneLocalMappingResolver is not converting minute and seconds part of the input because I have configured the CustomResolver to return the start of interval after the gap . NodaTime does not seem to have an equivalent of TimeZoneInfo.IsInvalidTime.How do I use NodaTime to convert skipped datetime values to UTC and match the result of GetUtc ( ) method in the Utils class below ? ( Utils.GetUtc method uses System.TimeZoneInfo not NodaTime ) This is the test case : This is what I am getting : Assert.AreEqual failed . Expected : < 2013-03-10 07:15:45.000000 > . Actual : < 2013-03-10 07:00:00.000000 > . Here is the Utils class ( also on github ) : [ TestMethod ] public void Test_Invalid_Date ( ) { var ts = new DateTime ( 2013 , 3 , 10 , 2 , 15 , 45 ) ; // Convert to UTC using System.TimeZoneInfo var utc = Utils.GetUtc ( ts ) .ToString ( Utils.Format ) ; // Convert to UTC using NodaTime ( Tzdb/Olson dataabase ) var utcNodaTime = Utils.GetUtcTz ( ts ) .ToString ( Utils.Format ) ; Assert.AreEqual ( utc , utcNodaTime ) ; } using System ; using NodaTime ; using NodaTime.TimeZones ; /// < summary > /// Functions to Convert To and From UTC/// < /summary > public class Utils { /// < summary > /// The date format for display/compare /// < /summary > public const string Format = `` yyyy-MM-dd HH : mm : ss.ffffff '' ; /// < summary > /// The eastern U.S. time zone /// < /summary > private static readonly NodaTime.DateTimeZone BclEast = NodaTime.DateTimeZoneProviders.Bcl.GetZoneOrNull ( `` Eastern Standard Time '' ) ; private static readonly TimeZoneInfo EasternTimeZone = TimeZoneInfo.FindSystemTimeZoneById ( `` Eastern Standard Time '' ) ; private static readonly NodaTime.DateTimeZone TzEast = NodaTime.DateTimeZoneProviders.Tzdb.GetZoneOrNull ( `` America/New_York '' ) ; private static readonly ZoneLocalMappingResolver CustomResolver = Resolvers.CreateMappingResolver ( Resolvers.ReturnLater , Resolvers.ReturnStartOfIntervalAfter ) ; public static DateTime GetUtc ( DateTime ts ) { return TimeZoneInfo.ConvertTimeToUtc ( EasternTimeZone.IsInvalidTime ( ts ) ? ts.AddHours ( 1.0 ) : ts , EasternTimeZone ) ; } public static DateTime GetUtcTz ( DateTime ts ) { var local = LocalDateTime.FromDateTime ( ts ) ; var zdt = TzEast.ResolveLocal ( local , CustomResolver ) ; return zdt.ToDateTimeUtc ( ) ; } public static DateTime GetUtcBcl ( DateTime ts ) { var local = LocalDateTime.FromDateTime ( ts ) ; var zdt = BclEast.ResolveLocal ( local , CustomResolver ) ; return zdt.ToDateTimeUtc ( ) ; } }",Using NodaTime to convert invalid ( skipped ) datetime values to UTC "C_sharp : I 've been wondering recently how lock ( or more specific : Monitor ) works internally in .NET with regards to the objects that are locked . Specifically , I 'm wondering what the overhead is , if there are 'global ' ( Process ) locks used , if it 's possible to create more of those global locks if that 's the case ( for groups of monitors ) and what happens to the objects that are passed to lock ( they do n't seem to introduce an extra memory overhead ) .To clarify what I 'm not asking about : I 'm not asking here about what a Monitor is ( I made one myself at University some time ago ) . I 'm also not asking how to use lock , Monitor , how they compile to a try/finally , etc ; I 'm pretty well aware of that ( and there are other SO questions related to that ) . This is about the inner workings of Monitor.Enter and Monitor.Exit.For example , consider this code executed by ten threads : Is it bad to lock a thousand objects instead of one ? What is impact in terms of performance / memory pressure ? The underlying monitor creates a wait queue . Is it possible to have more than one wait queue and how would I create that ? for ( int i=0 ; i < 1000 ; ++i ) { lock ( myArray [ i ] ) { // ... } }",How does ` lock ` ( Monitor ) work in .NET ? "C_sharp : Long story short , I started a new project using MVC 5.2.3 ( with all updated JS frameworks ) expecting that many of the issues I had with validations from MVC 2 were solved , how wrong was I.Basically I am driving myself crazy trying to provide validation to DateTime and Decimal.With the decimal field , using browsers in EN and DE ( cultures ) I am getting problems with comma and point ( decimal division ) and with the range that I am setting.With the DateTime I even tried a DisplayFormat just to display the Date and not the time , and anyway the order of day/month/year with separations with . or / or - are simply failing.Examples : In DE - Type : 999,999 -- > Result : ERROR `` Das Feld `` D1 DE '' muss zwischen 0 und 999,9999 liegen. `` - should be accepted.In EN - Type : 999.999 -- > Result : is accepted as it should be ( correct ) The same applies to the datetime display format and similar JS validations ... .I share with you guys what I have at the moment : TestObjectview.cshtml_layout.cshtmlDecimalModelBinder } Global.asaxweb.config public class TestObject { ... . [ Display ( Name = `` D2 '' , ResourceType = typeof ( WebApplication1.Models.Res.TestObject ) ) ] [ Range ( 0 , 999.9999 ) ] public decimal ? D1 { get ; set ; } // On DBContext I have defined the range/precision // modelBuilder.Entity < TestObject > ( ) .Property ( x = > x.D2 ) .HasPrecision ( 7 , 4 ) ; [ Display ( Name = `` Date1 '' , ResourceType = typeof ( WebApplication1.Models.Res.TestObject ) ) ] // [ DisplayFormat ( ApplyFormatInEditMode = true , DataFormatString = @ '' { 0 : dd\/MM\/yyyy } '' ) ] public DateTime Date1 { get ; set ; } ... . } < div class= '' form-group '' > @ Html.LabelFor ( model = > model.D2 , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.EditorFor ( model = > model.D2 , new { htmlAttributes = new { @ class = `` form-control '' } } ) @ Html.ValidationMessageFor ( model = > model.D2 , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < div class= '' form-group '' > @ Html.LabelFor ( model = > model.Date1 , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > @ Html.EditorFor ( model = > model.Date1 , new { htmlAttributes = new { @ class = `` form-control '' } } ) @ Html.ValidationMessageFor ( model = > model.Date1 , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < script src= '' ~/Scripts/globalize/globalize.js '' type= '' text/javascript '' > < /script > < /script > < script src= '' ~/Scripts/globalize/cultures/globalize.culture.de.js '' type= '' text/javascript '' > < /script > < script src= '' ~/Scripts/globalize/cultures/globalize.culture.en-US.js '' type= '' text/javascript '' > < /script > < script > $ .validator.methods.number = function ( value , element ) { return this.optional ( element ) || ! isNaN ( Globalize.parseFloat ( value ) ) ; } $ .validator.methods.date = function ( value , element ) { return this.optional ( element ) || Globalize.parseDate ( value ) ; } $ ( document ) .ready ( function ( ) { Globalize.culture ( ' @ System.Threading.Thread.CurrentThread.CurrentCulture ' ) ; } ) ; < /script > public class DecimalModelBinder : DefaultModelBinder { public override object BindModel ( ControllerContext controllerContext , ModelBindingContext bindingContext ) { object result = null ; // Do n't do this here ! // It might do bindingContext.ModelState.AddModelError // and there is no RemoveModelError ! // // result = base.BindModel ( controllerContext , bindingContext ) ; string modelName = bindingContext.ModelName ; string attemptedValue = bindingContext.ValueProvider.GetValue ( modelName ) .AttemptedValue ; // Depending on CultureInfo , the NumberDecimalSeparator can be `` , '' or `` . '' // Both `` . '' and `` , '' should be accepted , but are n't . string wantedSeperator = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator ; string alternateSeperator = ( wantedSeperator == `` , '' ? `` . '' : `` , '' ) ; if ( attemptedValue.IndexOf ( wantedSeperator ) == -1 & & attemptedValue.IndexOf ( alternateSeperator ) ! = -1 ) { attemptedValue = attemptedValue.Replace ( alternateSeperator , wantedSeperator ) ; } try { if ( bindingContext.ModelMetadata.IsNullableValueType & & string.IsNullOrWhiteSpace ( attemptedValue ) ) { return null ; } result = decimal.Parse ( attemptedValue , NumberStyles.Any ) ; } catch ( FormatException e ) { bindingContext.ModelState.AddModelError ( modelName , e ) ; } return result ; } public class MvcApplication : System.Web.HttpApplication { protected void Application_Start ( ) { ... ModelBinders.Binders.Add ( typeof ( decimal ) , new DecimalModelBinder ( ) ) ; ModelBinders.Binders.Add ( typeof ( decimal ? ) , new DecimalModelBinder ( ) ) ; ... } private void Application_BeginRequest ( Object source , EventArgs e ) { HttpApplication application = ( HttpApplication ) source ; HttpContext context = application.Context ; string culture = null ; if ( context.Request.UserLanguages ! = null & & Request.UserLanguages.Length > 0 ) { culture = Request.UserLanguages [ 0 ] ; Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo ( culture ) ; Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture ; } } } < globalization culture= '' auto '' uiCulture= '' auto '' enableClientBasedCulture= '' true '' / >",MVC 5.2.3 - Globalization - DateTime & Decimal with Range "C_sharp : When I use preprocessor directives like it causes that at runtime the line numbers in the log ( eg . stack trace ) are incorrect - in the above example line 9 would become 4 because the rest would be parsed by the preprocessor.It makes log analysis quite difficult . Is there a way to solve this issue without creating methods with ConditionalAttribute ? I 'm aware of Debugger.IsAttached ( and I 'm using this solution now ) but I would prefer to run code based on the build mode ( debug/release ) not on whether the debugger is attached . 1 # if ( DEBUG ) 2 // 13 // 24 # else5 // 16 // 27 # endif89 logger.Debug ( `` Log exception , etc . `` ) ;",# if ( DEBUG ) and log4net line number source/runtime mismatch "C_sharp : I got here after reading this and I did n't find a relevant answer - So please do n't mark this as a duplicate until you read the whole question.I 've been using a reflector and looked into Object.Equals.What I saw is : And RuntimeHelpers.Equals looks like this : Now I ca n't see the implementation of RuntimeHelpers.Equals but by the description , if both objects are n't the same instance and are n't null it will call the object.Equals method again and I 'd get into a loop ( I 'm talking about pure objects ) .When I say pure objects I mean something like this : By documentation this should call Object.Equals and get a recusive stackoverflow . I guess maybe the documentation is wrong and this checks reference equality for basic objects - but I wanted to be sure.Bottom line : When comparing two pure objects ( e.g . not casting a string into on object ) via an Equals call - how does it determine if they are equal ? - What happens if I do n't override the Equals method and I call Equals on two objects ? P.s . is there anyway that I can see the RuntimeHelpers.Equals source code ? [ __DynamicallyInvokable , TargetedPatchingOptOut ( `` Performance critical to inline across NGen image boundaries '' ) ] public virtual bool Equals ( object obj ) { return RuntimeHelpers.Equals ( this , obj ) ; } // System.Runtime.CompilerServices.RuntimeHelpers/// < summary > Determines whether the specified < see cref= '' T : System.Object '' / > instances are considered equal. < /summary > /// < returns > true if the < paramref name= '' o1 '' / > parameter is the same instance as the < paramref name= '' o2 '' / > parameter , or if both are null , or if o1.Equals ( o2 ) returns true ; otherwise , false. < /returns > /// < param name= '' o1 '' > The first object to compare . < /param > /// < param name= '' o2 '' > The second object to compare . < /param > [ SecuritySafeCritical ] [ MethodImpl ( MethodImplOptions.InternalCall ) ] public new static extern bool Equals ( object o1 , object o2 ) ; object pureObj1 = new object ( ) ; object pureObj2 = new object ( ) ; bool areEql = pureObj1.Equals ( pureObj2 ) ;",Object Equals - whats the basic logic for pure objects or reference types that do n't override Equals ? "C_sharp : I 'm retrieving json from a public api and converting it into a dynamic object using JsonFx . The json contains a property named return . e.g.JsonFx creates the dynamic object fine and I can also debug into it and see the values . The problem is when I try to reference the property in my code the compiler complains : How can I reference the return property without the compiler complaining ? JsonFx.Json.JsonReader reader = new JsonFx.Json.JsonReader ( ) ; dynamic response = reader.Read ( jsonAsString ) ; { `` result '' : '' success '' , '' return '' : { `` high '' : { `` value '' : '' 3.85001 '' , '' value_int '' : '' 385001 '' , '' display '' : '' 3.85001\u00a0\u20ac '' , '' currency '' : '' EUR '' } } response.return.high.currencyIdentifier expected ; 'return ' is a keyword",.Net 4 : How to reference a dynamic object with property named `` return '' "C_sharp : I 've created two entities ( simplified ) in C # : I am using the following code to initialize the objects : The method below is used to get the date logs : The result of the above LINQ query is : My question is , what is the best way to rewrite the LINQ query above to include the results from the second object I created ( Log2 ) , since it has an empty list . In the other words , I would like to display all dates even if they do n't have time values.The expected result would be : class Log { entries = new List < Entry > ( ) ; DateTime Date { get ; set ; } IList < Entry > entries { get ; set ; } } class Entry { DateTime ClockIn { get ; set ; } DateTime ClockOut { get ; set ; } } Log log1 = new Log ( ) { Date = new DateTime ( 2010 , 1 , 1 ) , } ; log1.Entries.Add ( new Entry ( ) { ClockIn = new DateTime ( 0001 , 1 , 1 , 9 , 0 , 0 ) , ClockOut = new DateTime ( 0001 , 1 , 1 , 12 , 0 , 0 ) } ) ; Log log2 = new Log ( ) { Date = new DateTime ( 2010 , 2 , 1 ) , } ; var query = from l in DB.GetLogs ( ) from e in l.Entries orderby l.Date ascending select new { Date = l.Date , ClockIn = e.ClockIn , ClockOut = e.ClockOut , } ; /* Date | Clock In | Clock Out 01/01/2010 | 09:00 | 12:00 */ /* Date | Clock In | Clock Out 01/01/2010 | 09:00 | 12:00 02/01/2010 | | */",LINQ : display results from empty lists C_sharp : I 've made the following declaration for interfaces : The compiler says that IChangeable.Data hides IBasic.Data . It 's reasonable . The alternative I 've found is : There is any way to define setter and getters for the same property on different hierarchy on interfaces ? Or there are any alternatives to this approach ? public interface IBasic { int Data { get ; } } public interface IChangeable : IBasic { int Data { set ; } } public interface IBasic { int Data { get ; } } public interface IChangeable : IBasic { void ChangeData ( int value ) ; },Interfaces with different getter and setter for the same propertie "C_sharp : Consider the following program : That will have the following output : What is odd to me is that .464737 was rounded to .463 . Should n't that have rounded to .464 ? I assume I have not found a bug in .NET code , so the question is : Why did it round to what it did ? and how can I get client side rounding that will do what SqlServer is going to do ? As a side note , I saved this date time to a SQL Server database ( in a DateTime column ) and pulled it out again and it came out as 10:21:54.4670000 . So I am really confused . ( I thought SqlDateTime would match up with what SQL Server was going to do . ) Note : Because I am using OData I can not use DateTime2 in SQL Server . DateTime dateTime = new DateTime ( 634546165144647370 ) ; SqlDateTime sqlDateTime = new SqlDateTime ( dateTime ) ; Console.WriteLine ( `` dateTime.TimeOfDay = `` + dateTime.TimeOfDay ) ; Console.WriteLine ( `` sqlDateTime.TimeOfDay = `` + sqlDateTime.Value.TimeOfDay ) ; Console.ReadLine ( ) ; dateTime.TimeOfDay = 10:21:54.4647370 sqlDateTime.TimeOfDay = 10:21:54.4630000",How does SqlDateTime do its precision reduction "C_sharp : Is it safe to store an instance of HttpContext in a middleware ? Example : I would like to use it in other private methods to work on it , so I can either pass it around as parameter to those function or use it as shown in the example.But is it thread safe ? public class TestMiddleware { private readonly RequestDelegate next ; private HttpContext context ; public TestMiddleware ( RequestDelegate next ) { this.next = next ; } public async Task Invoke ( HttpContext context ) { try { this.context = context ;",HttpContext .NET core saving instance in Middleware "C_sharp : I am confused on how XmlSerializer works behind the scenes . I have a class that deserializes XML into an object . What I am seeing is for the following two elements that are NOT part of the Xml being deserialized.Let 's take the following XML as an example : You notice that Tests and Comments are NOT part of the XML.When this XML gets deserialized Comments is null ( which is expected ) and Tests is an empty list with a count of 0 . If someone could explain this to me it would be much appreciated . What I would prefer is that if < Tests > is missing from the XML then the list should remain null , but if a ( possibly empty ) node < Tests / > is present then the list should get allocated . [ XmlRootAttribute ( `` MyClass '' , Namespace = `` '' , IsNullable = false ) ] public class MyClass { private string comments ; public string Comments { set { comments = value ; } get { return comments ; } } private System.Collections.Generic.List < string > tests = null ; public System.Collections.Generic.List < string > Tests { get { return tests ; } set { tests = value ; } } } < MyClass > < SomeNode > value < /SomeNode > < /MyClass >",C # Xml Serializer deserializes list to count of 0 instead of null "C_sharp : I have created a custom exception InvalidSessionException . However when trying to catch or evaluate if the exception raised is of that type , it does n't work . Meaning that it both EX is and Catch Ex , do n't evaluate to InvalidSessionExceptionI have also tried ( without any difference in results ) From what I can tell the exception being thrown is of the correct type.More Information : ex.GetType ( ) .FullName = `` System.ServiceModel.FaultException1 [ [ System.ServiceModel.ExceptionDetail , System.ServiceModel , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ] '' Reuse Types is enabled on the service ? try { acc = this.fda.GetAccountHeader ( this.selectedTicket.AccountId ) ; } catch ( Exception ex ) { if ( ex is Enterprise.Data.InformationModel.CustomExceptions.InvalidSessionException ) { this.lblError.Text = Resources.Resource.error_sessionedTimedOut ; this.MPError.Show ( ) ; } return ; } catch ( Enterprise.Data.InformationModel.CustomExceptions.InvalidSessionException ex ) { this.lblError.Text = Resources.Resource.error_sessionedTimedOut ; this.MPError.Show ( ) ; return ; } catch ( Exception ex ) { return ; }",Custom Exception Thrown by a Web Service not seen as same type by the Client ( using shared assemblies ) "C_sharp : is producing the following code : How can I get CodeDom to drop the `` { } '' , which will resolve the compiler error I 'm getting trying to compile ? I thought of just using a CodeSnippetStatement ( which I would rather not do , since this defeats the purpose of using CodeDom in the first place ) , but I ca n't find a place in the CodeTypeDeclaration class to add snippets.So : I need to eitherAdd an implementation-less method to a classAdd a random snippet to a classMystery 3rd option internal List < CodeMemberMethod > createEventHooks ( ) { string [ ] eventNames = new string [ ] { `` OnUpdate '' , `` OnInsert '' , `` OnDelete '' , `` OnSelect '' , `` OnSelectAll '' } ; List < CodeMemberMethod > eventHooks = new List < CodeMemberMethod > ( ) ; foreach ( string eventName in eventNames ) { CodeMemberMethod eventHook = new CodeMemberMethod ( ) ; eventHook.Name = eventName ; eventHook.Attributes = MemberAttributes.ScopeMask ; eventHook.ReturnType = new CodeTypeReference ( `` partial void '' ) ; } return eventHooks ; } partial void OnUpdate ( ) { } partial void OnInsert ( ) { } partial void OnDelete ( ) { } partial void OnSelect ( ) { } partial void OnSelectAll ( ) { }",How to add a partial method without an implementation using CodeDom "C_sharp : I have my DirectX11 Engine written in C++ , a wrapper in C++ with CLR , and an interface in C # . 1 ) I am curious about where the bottleneck is in this structure , and I 'm wondering if there is a more efficient way to let me host the DirectX11 rendering in a WinForms Control.2 ) Is there a way to render on a thread other than the owner of the WinForms control ? I doubt it but figured I 'd ask.3 ) Is there a way to render multiple frames without going through the wrapper layer on each frame but keep the application responsive ? I have compared this setup to SlimDX and am actually getting slightly slower FPS when simply clearing the screen and not doing any other API calls . SlimDX ~ 3000 FPS , My Engine ~ 2000 FPS . This is n't a big deal but I am wondering where this 33 % difference is coming from as it will probably make a difference later when comparing 20 fps to 30.I will walk through the current setup and describe as much as I can . I am sure along the way people will ask for more info and I 'll update as needed.My WinForms GraphicsPanel Control is below . It passes the system messages to the wrapper layer.Within the Engine Wrapper I have this function to pass the message from the WinForms control to the native C++ layer.Finally , the Native C++ Engine processes the messages as such : public class GraphicsPanel : Control { EngineWrapper Engine ; public GraphicsPanel ( ) { this.SetStyle ( ControlStyles.Selectable , true ) ; this.SetStyle ( ControlStyles.UserMouse , true ) ; this.SetStyle ( ControlStyles.UserPaint , true ) ; this.TabStop = true ; } public void SetEngine ( EngineWrapper Engine ) { this.Engine = Engine ; Application.Idle += OnApplicationIdle ; } ~GraphicsPanel ( ) { System.Windows.Forms.Application.Idle -= OnApplicationIdle ; } void PassMessage ( Message m ) { Engine.ProcessWindowMessage ( m.Msg , m.WParam , m.LParam ) ; } protected override void WndProc ( ref Message m ) { base.WndProc ( ref m ) ; PassMessage ( m ) ; } private void OnApplicationIdle ( object sender , EventArgs e ) { while ( AppStillIdle ) if ( Engine ! = null ) Engine.ProcessWindowMessage ( 0 , IntPtr.Zero , IntPtr.Zero ) ; } public bool AppStillIdle { get { NativeMethods.PeekMsg msg ; return ! NativeMethods.PeekMessage ( out msg , IntPtr.Zero , 0 , 0 , 0 ) ; } } internal class NativeMethods { private NativeMethods ( ) { } [ StructLayout ( LayoutKind.Sequential ) ] public struct PeekMsg { public IntPtr hWnd ; public Message msg ; public IntPtr wParam ; public IntPtr lParam ; public uint time ; public System.Drawing.Point p ; } [ System.Security.SuppressUnmanagedCodeSecurity ] [ DllImport ( `` User32.dll '' , CharSet = CharSet.Auto ) ] public static extern bool PeekMessage ( out PeekMsg msg , IntPtr hWnd , uint messageFilterMin , uint messageFilterMax , uint flags ) ; } } void EngineWrapper : :ProcessWindowMessage ( int msg , System : :IntPtr wParam , System : :IntPtr lParam ) { m_Engine- > ProcessWindowMessage ( msg , ( void* ) wParam , ( void* ) lParam ) ; } void Input : :ProcessWindowMessage ( int msg , void* wParam , void* lParam ) { if ( msg == 0 || msg == WM_PAINT ) { DrawFrame ( ) ; } else if ( msg == WM_SIZING || msg == WM_SIZE ) { DoResize ( ) ; DrawFrame ( ) ; } else if ( msg > = WM_MOUSEFIRST & & msg < = WM_MOUSEWHEEL ) { ProcessMouseMessage ( msg , wParam , lParam ) ; } }",DirectX11 Engine in C++ and Interface in C # "C_sharp : I 'm building a selenium test framework based on .Net Core and the team decided to go with xUnit . All 's well and good everything has been going ok but for a while now , we 've been trying to replicate the functionality of Java TestNG listeners without much luck.I 've been digging around the xunit git repo and found a few instances where some interfaces such ITestListener have been used . After digging deeper , I found that these listeners are from a package called TestDriven.Framework and I wanted to know exactly how would I use a test listener created using those interfaces ? So far this is my simple test listener that should write something when the test fails : Now , I know you can do this inside a tear down hook but remember , this is just a simple example and what I have in mind is something more complex . So to be precise , where/how exactly would I register the test to use this listener ? In Java TestNg I would have @ Listeners but in C # I 'm not too sure.Edit 1 so the example worked and managed to add it to my own project structure but when I try to use thisI 'm having trouble registering this one , or if i 'm even registering it right . As far as the examples go , I have found the actual message sinks but also found the actual test status data which i 'm not exactly sure how to use . public class Listener { readonly int totalTests ; public Listener ( ITestListener listener , int totalTests ) { this.totalTests = totalTests ; TestListener = listener ; TestRunState = TestRunState.NoTests ; } public ITestListener TestListener { get ; private set ; } public TestRunState TestRunState { get ; set ; } public void onTestFail ( ITestFailed args ) { Console.WriteLine ( args.Messages ) ; } } class TestPassed : TestResultMessage , ITestPassed { /// < summary > /// Initializes a new instance of the < see cref= '' TestPassed '' / > class . /// < /summary > public TestPassed ( ITest test , decimal executionTime , string output ) : base ( test , executionTime , output ) { Console.WriteLine ( `` Execution time was an awesome `` + executionTime ) ; } }",C # xUnit Test listeners "C_sharp : So what I really want is somewhat usable tab completion in a PS module.ValidateSet seems to be the way to go here.Unfortunately my data is dynamic , so I can not annotate the parameter with all valid values upfront.DynamicParameters/IDynamicParameters seems to be the solution for that problem.Putting these things together ( and reducing my failure to a simple test case ) we end up with : Unfortunately this tiny snippet causes a lot of issues already . Ordered descending : I fail to see how I can create a connection between the parameters . If you pick an author , you should only be able to pick a book that matches the author . So far GetDynamicParameters ( ) always seems stateless though : I see no way to access the value of a different/earlier dynamic parameter . Tried keeping it in a field , tried searching MyInvocation - no luck . Is that even possible ? How do you define a default value for mandatory parameter ? Does n't fit the silly example , but let 's say you can store your favorite author . From now on I want to default to that author , but having a pointer to an author is still mandatory . Either you gave me a default ( and can still specify something else ) or you need to be explicit.Tab completion for strings with spaces seems weird/broken/limited - because it does n't enclose the value with quotes ( like cmd.exe would do , for example , if you type dir C : \Program < tab > ) . So tab completion actually breaks the invocation ( if the issues above would be resolved , Get-BookDetails Ter < tab > would/will expand to Get-BookDetails Terry Pratchett which puts the last name in parameter position 1 aka 'book'.Should n't be so hard , surely someone did something similar already ? Update : After another good day of tinkering and fooling around I do n't see a way to make this work . The commandlet is stateless and will be instantiated over and over again . At the point in time when I can define dynamic parameters ( GetDynamicParameters ) I can not access their ( current ) values/see what they 'd be bound to - e.g . MyInvocation.BoundParameters is zero . I 'll leave the question open , but it seems as if this just is n't supported . All the examples I see add a dynamic parameter based on the value of a static one - and that 's not relevant here . Bugger . using System ; using System.Collections.Generic ; using System.Collections.ObjectModel ; using System.Linq ; using System.Management.Automation ; using System.Text ; using System.Threading.Tasks ; namespace PSDummy { [ Cmdlet ( VerbsCommon.Get , `` BookDetails '' ) ] public class GetBookDetails : Cmdlet , IDynamicParameters { IDictionary < string , string [ ] > m_dummyData = new Dictionary < string , string [ ] > { { `` Terry Pratchett '' , new [ ] { `` Small Gods '' , `` Mort '' , `` Eric '' } } , { `` Douglas Adams '' , new [ ] { `` Hitchhiker 's Guide '' , `` The Meaning of Liff '' } } } ; private RuntimeDefinedParameter m_authorParameter ; private RuntimeDefinedParameter m_bookParameter ; protected override void ProcessRecord ( ) { // Do stuff here.. } public object GetDynamicParameters ( ) { var parameters = new RuntimeDefinedParameterDictionary ( ) ; m_authorParameter = CreateAuthorParameter ( ) ; m_bookParameter = CreateBookParameter ( ) ; parameters.Add ( m_authorParameter.Name , m_authorParameter ) ; parameters.Add ( m_bookParameter.Name , m_bookParameter ) ; return parameters ; } private RuntimeDefinedParameter CreateAuthorParameter ( ) { var p = new RuntimeDefinedParameter ( `` Author '' , typeof ( string ) , new Collection < Attribute > { new ParameterAttribute { ParameterSetName = `` BookStuff '' , Position = 0 , Mandatory = true } , new ValidateSetAttribute ( m_dummyData.Keys.ToArray ( ) ) , new ValidateNotNullOrEmptyAttribute ( ) } ) ; // Actually this is always mandatory , but sometimes I can fall back to a default // value . How ? p.Value = mydefault ? return p ; } private RuntimeDefinedParameter CreateBookParameter ( ) { // How to define a ValidateSet based on the parameter value for // author ? var p = new RuntimeDefinedParameter ( `` Book '' , typeof ( string ) , new Collection < Attribute > { new ParameterAttribute { ParameterSetName = `` BookStuff '' , Position = 1 , Mandatory = true } , new ValidateSetAttribute ( new string [ 1 ] { string.Empty } /* can not fill this , because I can not access the author */ ) , new ValidateNotNullOrEmptyAttribute ( ) } ) ; return p ; } } }",Powershell module : Dynamic mandatory hierarchical parameters "C_sharp : See line of code below : In this lines of code I have _tables reference and trying to access its system define functions GetType ( ) and Count ( ) , both throw exception but why .Count ( ) throws System.ArgumentNullException , since we have same value for reference which is null ? DataTable [ ] _tables = null ; // Throws System.NullReferenceException_tables.GetType ( ) ; // Throws System.ArgumentNullException_tables.Count ( ) ;",Why ArgumentNullException ? Why not System.NullReferenceException ? "C_sharp : Consider the following class written in c # .net 4.0 ( typically found in a nhibernate class ) : This line gets a well founded warning `` virtual member call in the constructor '' .Where shall I initialize this collection ? Regards , public class CandidateEntity : EntityBase { public virtual IList < GradeEntity > Grades { get ; set ; } public CandidateEntity ( ) { Grades = new List < GradeEntity > ( ) ; } }",Syntax for virtual members C_sharp : I have 2 tables enquiry and details.On save button click I have writtenfbsave ( ) save the data in enquiry table and fbsavedetails ( ) saves data in details table.now if error occur in fbsavedetails ( ) then both steps should be rollback.is it possible ? fbsave ( ) ; fbsavedetails ( ) ;,Roll back in c # "C_sharp : I am using .Net Core 2.0 for my project , and Moq v4.7.145 as my mocking framework.I have this protected virtual method , which normally uploads bytes to a cloud service . To be able to unit test this , I wanted to mock this method which works fine for all other scenarios.The problem occurred when I want to make this method return null . This to simulate the service being down or it actually returns null . I have checked a few questions on SO , but none seems to work.I have mocked my picture provider like this . The mockProvider is a mock of the cloud service , and the LoggerMock is a mock of well ... the logger.I have set up my mocked method like this : I have tried casting the return object in every way , but none has worked so far.The method which I 'm mocking looks like this : The method that calls the mocked method above , looks like this : Every time it reaches the protected ( Mocked ) method in my public UploadImageAsync method , it throws a NullReferenceException : I assume I 'm missing something in my setup of the mocked method , I just ca n't figure out what it is . If I missed to mention/show something , please let me know ! PictureProvider = new Mock < CloudinaryPictureProvider > ( mockProvider.Object , LoggerMock.Object ) { // CallBase true so it will only overwrite the method I want to be mocked . CallBase = true } ; PictureProvider.Protected ( ) .Setup < Task < ReturnObject > > ( `` UploadAsync '' , ItExpr.IsAny < ImageUploadParams > ( ) ) .Returns ( null as Task < ReturnObject > ) ; protected virtual async Task < ReturnObject > UploadAsync ( ImageUploadParams uploadParams ) { var result = await _cloudService.UploadAsync ( uploadParams ) ; return result == null ? null : new ReturnObject { // Setting values from the result object } ; } public async Task < ReturnObject > UploadImageAsync ( byte [ ] imageBytes , string uploadFolder ) { if ( imageBytes == null ) { // Exception thrown } var imageStream = new MemoryStream ( imageBytes ) ; // It throws the NullReferenceException here . var uploadResult = await UploadAsync ( new ImageUploadParams { File = new FileDescription ( Guid.NewGuid ( ) .ToString ( ) , imageStream ) , EagerAsync = true , Folder = uploadFolder } ) ; if ( uploadResult ? .Error == null ) { // This is basically the if statement I wanted to test . return uploadResult ; } { // Exception thrown } } Message : Test method { MethodName } threw exception : System.NullReferenceException : Object reference not set to an instance of an object .",Mocked method with moq to return null throws NullReferenceException "C_sharp : TL ; DR I 'm looking for a way to obtain IEqualityComparer < T > from IComparer < T > , no matter which datatype is T , including case-insensitive options if T is string . Or I need a different solution for this problem.Here 's full story : I 'm implementing simple , generic cache with LFU policy . Requirement is that it must be possible to select whether the cache will be case sensitive or case insensitive -- if string happens to be the datatype for cache keys ( which is not necessary ) . In the solution I primarily develop the cache for , I expect hundreds of billions of cache lookups , and cache sizes of max 100.000 entries . Because of that numbers I immediately resigned from using any string manipulation that causes allocations ( such as .ToLower ( ) .GetHashCode ( ) etc . ) and instead opted to use IComparer and IEqualityComparer , as they are standard BCL features . User of this cache can pass the comparers to constructor . Here are relevant fragments of the code : The keyEqualityComparer is used to manage cache entries ( so e.g . the key `` ABC '' and `` abc '' are equal if user wants to ) . The keyComparer is used to manage cache entries sorted by UseCount so that it 's easy to select the least frequently used one ( implemented in CacheItemComparer class ) .Example correct usage with custom comparison : ( That looks stupid , but StringComparer implements both IComparer < string > and IEqualityComparer < string > . ) The problem is that if user gives incompatible comparers ( i.e . case insensitive keyEqualityComparer and case sensitive keyComparer ) , then the most likely outcome is invalid LFU statistics , and thus lower cache hits at best . The other scenario is also less than desired . Also if the key is more sophisticated ( I 'll have something resembling Tuple < string , DateTime , DateTime > ) , it 's possible to mess it up more severely.That 's why I 'd like to only have a single comparer argument in constructor , but that does n't seem to work . I 'm able to create IEqualityComparer < T > .Equals ( ) with help of IComparer < T > .Compare ( ) , but I 'm stuck at IEqualityComparer < T > .GetHashCode ( ) -- which is very important , as you know . If I had got access to private properties of the comparer to check if it 's case sensitive or not , I would have used CompareInfo to get hash code.I like this approach with 2 different data structures , because it gives me acceptable performance and controllable memory consumption -- on my laptop around 500.000 cache additions/sec with cache size 10.000 elements . Dictionary < TKey , TValue > is just used to find data in O ( 1 ) , and SortedSet < CacheItem > inserts data in O ( log n ) , find element to remove by calling lfuList.Min in O ( log n ) , and find the entry to increment use count also in O ( log n ) .Any suggestions on how to solve this are welcome . I 'll appreciate any ideas , including different designs . public class LFUCache < TKey , TValue > { private readonly Dictionary < TKey , CacheItem > entries ; private readonly SortedSet < CacheItem > lfuList ; private class CacheItem { public TKey Key ; public TValue Value ; public int UseCount ; } private class CacheItemComparer : IComparer < CacheItem > { private readonly IComparer < TKey > cacheKeyComparer ; public CacheItemComparer ( IComparer < TKey > cacheKeyComparer ) { this.cacheKeyComparer = cacheKeyComparer ; if ( cacheKeyComparer == null ) this.cacheKeyComparer = Comparer < TKey > .Default ; } public int Compare ( CacheItem x , CacheItem y ) { int UseCount = x.UseCount - y.UseCount ; if ( UseCount ! = 0 ) return UseCount ; return cacheKeyComparer.Compare ( x.Key , y.Key ) ; } } public LFUCache ( int capacity , IEqualityComparer < TKey > keyEqualityComparer , IComparer < TKey > keyComparer ) // < - here 's my problem { // ... entries = new Dictionary < TKey , CacheItem > ( keyEqualityComparer ) ; lfuList = new SortedSet < CacheItem > ( new CacheItemComparer ( keyComparer ) ) ; } // ... } var cache = new LFUCache < string , int > ( 10000 , StringComparer.InvariantCultureIgnoreCase , StringComparer.InvariantCultureIgnoreCase ) ;",Is there a way to derive IEqualityComparer from IComparer ? "C_sharp : I am working on custom media player and trying to reproduce same behavior as in Movies & TV app ( Windows 10 CU ) .Space is used to Play & Pause video no matter what . Space is not used to click buttons when they are focused ( but Enter is ) . This behavior breaks some rules about keyboard accessibility , but I think it is OK. Space for Play & Pause is something that user expect.Question is : How they did it ? I found some half-solutions : Solution 1 Window.Current.CoreWindow.KeyDown and if in Click Event HandlerPage.xaml.cs : Page.xaml : Why not : Need to add if in every Click HandlerThere is button click animation ... Solution 2 Disable focused Button in Window.Current.CoreWindow.KeyDown and enable it in KeyUpSomething like : Why notIt change focus from disabled button . Need to change it back after enable . Focus is jumping..Disable and enable animation appearit is too hackie Solution 3 button.ClickMode = ClickMode.HoverWhen ClickMode is set to Hover it is not possible to Click it with keyboard . When I change it in KeyDown handler of Window ( like solution 2 ) it still bubble to Click event for the first time . Solution could be set all buttons to Hover , but in that case Enter will not cause the Click and I need to change all buttons ... Are there any better solutions on your mind ? protected override void OnNavigatedTo ( NavigationEventArgs e ) { Window.Current.CoreWindow.KeyDown += CoreWindowOnKeyDown ; // ... } bool isItSpace ; private void CoreWindowOnKeyDown ( CoreWindow sender , KeyEventArgs args ) { if ( args.VirtualKey == VirtualKey.Space ) isItSpace = true ; } private void ButtonBase_OnClick ( object sender , RoutedEventArgs e ) { if ( isItSpace ) { isItSpace = false ; return ; } // ... } < Button Click= '' ButtonBase_OnClick '' > Button Text < /Button > if ( FocusManager.GetFocusedElement ( ) is Button ) { var bu = ( Button ) FocusManager.GetFocusedElement ( ) ; bu.IsEnabled = false ; }",UWP - Do n't fire Click event when pressing space ( like in Movies & TV app ) "C_sharp : My app uses views , which implement IViewFor < T > interface . The views are registered with the dependency resolver in AppBootstrapper . The app displays the views using ViewModelViewHost control by assigning a corresponding view model to control 's ViewModel property . All the view models implement ISupportsActivation interface.I noticed that WhenActivated is called twice . First it 's called when a view and view model get activated . Then on deactivation all disposables are disposed and WhenActivated is called again immediately followed by disposing the disposables.I am testing with the following code both in view and view model : As a result the output looks like this : The view is hidden by setting ViewModel property of ViewModelViewHost control to null.Am I doing something wrong ? Edit : here 's the complete source code : https : //gist.github.com/dmakaroff/e7d84e06e0a48d7f5298eb6b7d6187d0Pressing first Show and then Hide buttons produces the following output : this.WhenActivated ( disposables = > { Debug.WriteLine ( `` ViewModel activated . `` ) ; Disposable .Create ( ( ) = > { Debug.WriteLine ( `` ViewModel deactivated . `` ) ; } ) .AddTo ( disposables ) ; } ) ; // App displays the view : ViewModel activated.View activated.// App hides the view : ViewModel deactivated.View deactivated.ViewModel activated.View activated.ViewModel deactivated.View deactivated . SubViewModel activated.SubView activated.SubViewModel deactivated.SubView deactivated.SubViewModel activated.SubView activated.SubViewModel deactivated.SubView deactivated .",WhenActivated is called twice when used in Views and ViewModels hosted in ViewModelViewHost control "C_sharp : I am using the code belowat the end of a while loop . To try and get a 5ms delay between iterations.Sometimes it sleeps for 16ms . This I understand and accept , since it depends on when the CPU gets around to servicing the thread . However once it has woken the next iteration it seems to wake immediately after the sleep call ( I am logging with timestamps ) . Is there a problem with using such a short sleep interval that it is treated as zero ? Thread.Sleep ( 5 ) ;",C # Thread.Sleep waking immediately "C_sharp : My colleague and I have dispute . We are writing a .NET application that processes massive amounts of data . It receives data elements , groups subsets of them them into blocks according to some criterion and processes those blocks.Let 's say we have data items of type Foo arriving some source ( from the network , for example ) one by one . We wish to gather subsets of related objects of type Foo , construct an object of type Bar from each such subset and process objects of type Bar.One of us suggested the following design . Its main theme is exposing IObservable < T > objects directly from the interfaces of our components.The other suggested another design that its main theme is using our own publisher/subscriber interfaces and using Rx inside the implementations only when needed.Which one do you think is better ? Exposing IObservable < T > and making our components create new event streams from Rx operators , or defining our own publisher/subscriber interfaces and using Rx internally if needed ? Here are some things to consider about the designs : In the first design the consumer of our interfaces has the whole power of Rx at his/her fingertips and can perform any Rx operators . One of us claims this is an advantage and the other claims that this is a drawback.The second design allows us to use any publisher/subscriber architecture under the hood . The first design ties us to Rx.If we wish to use the power of Rx , it requires more work in the second design because we need to translate the custom publisher/subscriber implementation to Rx and back . It requires writing glue code for every class that wishes to do some event processing . // ********* Interfaces **********interface IFooSource { // this is the event-stream of objects of type Foo IObservable < Foo > FooArrivals { get ; } } interface IBarSource { // this is the event-stream of objects of type Bar IObservable < Bar > BarArrivals { get ; } } / ********* Implementations *********class FooSource : IFooSource { // Here we put logic that receives Foo objects from the network and publishes them to the FooArrivals event stream . } class FooSubsetsToBarConverter : IBarSource { IFooSource fooSource ; IObservable < Bar > BarArrivals { get { // Do some fancy Rx operators on fooSource.FooArrivals , like Buffer , Window , Join and others and return IObservable < Bar > } } } // this class will subscribe to the bar source and do processingclass BarsProcessor { BarsProcessor ( IBarSource barSource ) ; void Subscribe ( ) ; } // ******************* Main ************************class Program { public static void Main ( string [ ] args ) { var fooSource = FooSourceFactory.Create ( ) ; var barsProcessor = BarsProcessorFactory.Create ( fooSource ) // this will create FooSubsetToBarConverter and BarsProcessor barsProcessor.Subscribe ( ) ; fooSource.Run ( ) ; // this enters a loop of listening for Foo objects from the network and notifying about their arrival . } } //********** interfaces *********interface IPublisher < T > { void Subscribe ( ISubscriber < T > subscriber ) ; } interface ISubscriber < T > { Action < T > Callback { get ; } } //********** implementations *********class FooSource : IPublisher < Foo > { public void Subscribe ( ISubscriber < Foo > subscriber ) { /* ... */ } // here we put logic that receives Foo objects from some source ( the network ? ) publishes them to the registered subscribers } class FooSubsetsToBarConverter : ISubscriber < Foo > , IPublisher < Bar > { void Callback ( Foo foo ) { // here we put logic that aggregates Foo objects and publishes Bars when we have received a subset of Foos that match our criteria // maybe we use Rx here internally . } public void Subscribe ( ISubscriber < Bar > subscriber ) { /* ... */ } } class BarsProcessor : ISubscriber < Bar > { void Callback ( Bar bar ) { // here we put code that processes Bar objects } } //********** program *********class Program { public static void Main ( string [ ] args ) { var fooSource = fooSourceFactory.Create ( ) ; var barsProcessor = barsProcessorFactory.Create ( fooSource ) // this will create BarsProcessor and perform all the necessary subscriptions fooSource.Run ( ) ; // this enters a loop of listening for Foo objects from the network and notifying about their arrival . } }",Should I expose IObservable < T > on my interfaces ? "C_sharp : In WPF , I 'm programmatically adding a context menu to a control.CopyImage is defined in my application resource . At runtime , only the last menu item shows the icon . The other three menu items do not . Does anyone have an explanation for this behavior ? var contextMenu = new ContextMenu ( ) ; contextMenu.Items.Add ( new MenuItem { Header = `` Copy All '' , Icon = FindResource ( `` CopyImage '' ) } ) ; contextMenu.Items.Add ( new MenuItem { Header = `` Copy All with Headers '' , Icon = FindResource ( `` CopyImage '' ) } ) ; contextMenu.Items.Add ( new MenuItem { Header = `` Copy Selected '' , Icon = FindResource ( `` CopyImage '' ) } ) ; contextMenu.Items.Add ( new MenuItem { Header = `` Copy Selected with Headers '' , Icon = FindResource ( `` CopyImage '' ) } ) ; < Image x : Key= '' CopyImage '' Source= '' ../Images/copy.png '' / >",Why only the last menu item has icon ? "C_sharp : Let 's have a following simplified example : Compiler says : The type 'System.Collections.Generic.IEnumerable ' can not be used as type parameter ' C ' in the generic type or method 'UserQuery.Foo ( C , T ) ' . There is no implicit reference conversion from 'System.Collections.Generic.IEnumerable ' to 'System.Collections.Generic.ICollection'.If I change Main to : It will work ok. Why compiler does not choose the right overload ? void Foo < T > ( IEnumerable < T > collection , params T [ ] items ) { // ... } void Foo < C , T > ( C collection , T item ) where C : ICollection < T > { // ... } void Main ( ) { Foo ( ( IEnumerable < int > ) new [ ] { 1 } , 2 ) ; } void Main ( ) { Foo < int > ( ( IEnumerable < int > ) new [ ] { 1 } , 2 ) ; }",C # overloading with generics : bug or feature ? "C_sharp : Suppose I have enum , which underlying type is byte : Can I cast some int literal to underlying type of this enum ( byte in this case ) ? Something like this does n't work ( Error : `` ; expected '' ) : Can I cast to underlying type without explicitly writing ( byte ) 15 ? Thanks . enum EmpType : byte { Manager = 1 , Worker = 2 , } byte x = ( Enum.GetUnderlyingType ( typeof ( EmpType ) ) ) 15 ;","C # , cast variable to Enum.GetUnderlyingType" "C_sharp : I am using the C # management API of Azure to create my resources in the cloud . I am stuck creating a container in the blob storage . I did create a storage account following these instructions : But I do not know how to go on from there . From the Microsoft documentation it seems that I have to retrieve a Microsoft.WindowsAzure.Storage.CloudStorageAccount instance , but the storageAccount instance I obtain with the above code lives in the namespace Microsoft.Azure.Management.Storage.Fluent , and I have not found any way to get the CloudStorageAccount from there . Is it possible to create containers directly with the API in the fluent namespace ? If not , how do I get the CloudStorageAccount instance from my IStorageAccount one ? This answer in SO is not helpful because it does use the Microsoft.WindowsAzure namespace directly . // storageAccount here is a Microsoft.Azure.Management.Storage.Fluent.IStorageAccount instancevar storageAccount = _azure.StorageAccounts .Define ( name ) .WithRegion ( region ) .WithExistingResourceGroup ( resourceGroup ) .WithBlobEncryption ( ) .WithOnlyHttpsTraffic ( ) .WithBlobStorageAccountKind ( ) .WithAccessTier ( AccessTier.Hot ) .Create ( ) ;",Create blob storage container in c # using fluent API "C_sharp : As I was looking the difference between Count and Count ( ) , I thought to glance at the source code of Count ( ) . I saw the following code snippet in which I wonder why the checked keyword is necessary/needed : The source code : int num = 0 ; using ( IEnumerator < TSource > enumerator = source.GetEnumerator ( ) ) { while ( enumerator.MoveNext ( ) ) { num = checked ( num + 1 ) ; } return num ; } // System.Linq.Enumerableusing System.Collections ; using System.Collections.Generic ; public static int Count < TSource > ( this IEnumerable < TSource > source ) { if ( source == null ) { ThrowHelper.ThrowArgumentNullException ( ExceptionArgument.source ) ; } ICollection < TSource > collection = source as ICollection < TSource > ; if ( collection ! = null ) { return collection.Count ; } IIListProvider < TSource > iIListProvider = source as IIListProvider < TSource > ; if ( iIListProvider ! = null ) { return iIListProvider.GetCount ( onlyIfCheap : false ) ; } ICollection collection2 = source as ICollection ; if ( collection2 ! = null ) { return collection2.Count ; } int num = 0 ; using ( IEnumerator < TSource > enumerator = source.GetEnumerator ( ) ) { while ( enumerator.MoveNext ( ) ) { num = checked ( num + 1 ) ; } return num ; } }",Why does the Count ( ) method use the `` checked '' keyword ? "C_sharp : Say I have a class with some properties and some methods for manipulating those properties : Typical usage would be : I think it would be cool to make the methods chainable : Then usage would be : But I am not returning a modified `` clone '' of the passed-in PersonModel object in each of these chainable methods . They are just modifying the original object and returning it ( for convenience ) . To me , this creates an ambiguity because someone calling these methods may assume that they are immutable ( i.e . they leave the original object intact but return a modified object ) .Does that violate any sort of best practice regarding fluent/chainable interfaces ? public class PersonModel { public string Name { get ; set ; } public string PrimaryPhoneNumber { get ; set ; } public void LoadAccountInfo ( AccountInfo accountInfo ) { this.Name = accountInfo.Name ; } public void LoadPhoneInfo ( PhoneInfo phoneInfo ) { this.PrimaryPhoneNumber = phoneInfo.PhoneNumber ; } } var model = new PersonModel ( ) ; model.LoadAccountInfo ( accountInfo ) ; model.LoadPhoneInfo ( phoneInfo ) ; public PersonModel LoadAccountInfo ( AccountInfo accountInfo ) { this.Name = accountInfo.Name ; return this ; } public PersonModel LoadPhoneInfo ( PhoneInfo phoneInfo ) { this.PrimaryPhoneNumber = phoneInfo.PhoneNumber ; return this ; } var model = new PersonModel ( ) .LoadAccountInfo ( accountInfo ) .LoadPhoneInfo ( phoneInfo ) ;",Must a `` fluent '' ( or chainable ) method be immutable ? "C_sharp : I have a series of unit tests that connect to an Azure Storage emulator . In Setup my code checks if there is something listening on the emulator 's port , and if not sets a flag StorageNotAvailable.In each of my tests I have some code ... As expected , when the test returns void this reports correctly in the Test Explorer as `` Inconclusive '' .When the test is exercising some async methods , and the [ TestMethod ] signature returns Task then the test is reported in the TestExplorer as `` Failed '' instead of `` Inconclusive '' .How can I get an async method to report as Inconclusive ? EDITSome additional detail may be in order . Here are some sample tests I rigged up to demonstrate the problem I am seeing.Some environment details may be in order as well : Windows 10 x64 1703 Build 15063.608Visual Studio Enterprise 2017 15.3.5.NET 4.7.02046VS Extensions that might be relevantMicrosoft Visual Studio Test PlatformMSTest V2 Create Unit Test ExtensionMSTest V2 IntelliTest ExtensionMSTest V2 TemplatesProject references that might be relevantMicrosoft.VisualStudio.TestPlatform.TestFramework v14.0.0.0Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions v14.0.0.0Project nuGet packages that might be relevantMSTest.TestAdapter v1.1.18MSTest.TestFramework v1.1.18Project build target is .NET Framework v4.7 if ( StorageNotAvailable ) Assert.Inconclusive ( `` Storage emulator is not available '' ) // where storage emulator is available , continue as normal [ TestMethod ] public void MyTestMethod ( ) { Assert.Inconclusive ( `` I am inconclusive '' ) ; } [ TestMethod ] public async Task MyTestMethodAsync ( ) { Assert.Inconclusive ( `` I am an error '' ) ; }",Calling Assert.Inconclusive ( ) in an async unit test is reported as a fail "C_sharp : I have a situation in a project I am currently working on at work that has left my mind restless the entire weekend . First , I need to explain my scenario , and the possible solutions I have considered.I am writing a composite WCF service that will be aggregating a large amount of external API 's . These API 's are arbitrary and their existence is all that is needed for this explanation . These services can be added and removed throughout the period of development . My WCF service should be able to consume the services using several methods ( REST , SOAP , etc ) . For this example , I am focusing on communicating with the external APIS by manually creating the requests in code.For example , we might have two API 's ServiceX and ServiceY . ServiceX is consumed by POST ing a web request with the data in the request body specifically.ServiceY is consumed by POST ing a web request with the data appended to the URL ( Yes ... I know this should be a GET , but I did n't write the external API , so do n't lecture me about it . ) In order to avoid redundant , duplicate code , I have wrapped the web requests using the command pattern , and am using a factory to build the requests . For ServiceX , the data needs to be encoded and put into the request body , as oppose to ServiceY where the data needs to be iterated over and placed on the Post string.I have a class structure like the following : This allows me to cleanly separate the way that I am binding data to the request when they need to be send out , and essentially , I can also add additional classes to handle GET requests . I am not sure if this is a good use of these patterns . I am thinking an alternative might be using the Strategy pattern and specifying strategy objects for the different Request methods I might need to use . Such as the following : I am starting to think the Strategy pattern may be the cleaner solution.Any thoughts ? public abstract class PostCommandFactory { public ICommand CreateCommand ( ) ; } public class UrlPostCommandFactory : PostCommandFactory { public ICommand CreateCommand ( ) { //Initialize Command Object Here } } public class BodyPostCommandFactory : PostCommandFactory { public ICommand CreateCommand ( ) { //Initialize Command Object Here } } public interface ICommand { string Invoke ( ) ; } public class UrlPostCommand : ICommand { public string Invoke ( ) { //Make URL Post Request } } public class BodyPostCommand : ICommand { public string Invoke ( ) { //Make Request Body Post Request } } public class RequestBodyPostStrategy : IPostStrategy { public string Invoke ( ) { //Make Request Body POST here } } public class UrlPostStrategy : IPostStrategy { public string Invoke ( ) { //Make URL POST here } } public interface IPostStrategy { string Invoke ( ) ; } public class PostContext { pubic List < IPostStrategy > _strategies ; public IPostStrategy _strategy ; public PostContext ( ) { _strategies = new List < IPostStrategy > ( ) ; } public void AddStrategy ( IPostStrategy strategy ) { _strategies.Add ( strategy ) ; } public void SetStrategy ( IPostStrategy strategy ) { _strategy = strategy ; } public void Execute ( ) { _strategy.Invoke ( ) ; } }",Design Pattern Scenario - Which should I use ? "C_sharp : I 'm designing the User Settings for my MVC application , and right now I have ~20 boolean settings that the user can toggle . Since every user will always have every setting , I was thinking about storing each setting as a boolean on the User table . Though this would become unwieldy as the application requirements grow . First question - is there anything wrong with having a ton of columns on your table in this situation ? I then considered using Flags , and storing the settings as one bit each in an array : And then each user will have a single `` Settings '' column in their User row , that stores a value of 2^20 , if there are 20 settings . I 'd use this to guide my efforts : What does the [ Flags ] Enum Attribute mean in C # ? Is this better than the former approach ? Any suggestions are welcome . [ Flags ] public enum Settings { WantsEmail = 1 , WantsNotifications = 2 , SharesProfile = 4 , EatsLasagna = 8 }",Storing User Settings - anything wrong with using `` Flags '' or `` Bits '' instead of a bunch of bools ? "C_sharp : I need generate typescript files from some of my C # classes after build.I created dotnet cli tool and added post-build eventwhere $ ( TargetPath ) is macros pointing , for example , D : \Test\bin\Release\netcoreapp2.0\my.dllNext , i tried to load assembly next way : But i got ReflectionTypeLoadException that says Could not load file or assembly for some references assemblies ( for example , Microsoft.AspNetCore.Antiforgery ) .How i can load assembly for .NET Core applications ? dotnet tsgenerator `` $ ( TargetPath ) '' public static void Main ( string [ ] args ) { var dllPath = args [ 0 ] ; // `` D : \Test\bin\Release\netcoreapp2.0\my.dll '' var assembly = Assembly.LoadFile ( dllPath ) ; var types = assembly.GetExportedTypes ( ) ; // Throws exception }",.NET Core Assembly.LoadFile at PostBuild event "C_sharp : Switch expressions were introduced in C # 8 . There 's plenty of places in codebases , which may be rewritten in this new style.For example , I have some code , which is used for parsing packets from a stream of bytes : The problem is - it ca n't be converted to a switch expression likeThe first thing that got in my mind was to use a Func < > , which compiles : F # already allows code with multiple statements in each branch : Now I 'm stuck using switch-statements , but is there any option to write this as a switch-expression without any weird hacks ? switch ( command ) { case Command.C1 : return new P1 ( ) ; case Command.C2 : return new P2 ( ) ; default : stream.Position++ ; return null ; } return command switch { Command.C1 = > new P1 ( ) , Command.C3 = > new P2 ( ) , _ = > { stream.Position++ ; return null ; } } ; return command switch { Command.C1 = > new P1 ( ) , Command.C3 = > new P2 ( ) , _ = > new Func < AbstractPacket > ( ( ) = > { stream.Position++ ; return null ; } ) ( ) } ; match command with| Command.C1 - > Some ( P1 ( ) : > AbstractPacket ) | Command.C2 - > Some ( P2 ( ) : > AbstractPacket ) | _ - > stream.Position < - stream.Position + 1 None",Multiple statements in a switch expression : C # 8 "C_sharp : How do variables captured by a closure interact with different threads ? In the following example code I would want to declare totalEvents as volatile , but C # does not allow this . ( Yes I know this is bad code , it 's just an example ) EDIT : People seem to be missing the point of my question a bit . I know I ca n't use volatile on local vars . I also know that the example code code is bad and could be implemented in other ways , hence my `` bad code '' disclaimer . It was just to illustrate the problem.Anyway , it would appear that there is no way to force volatile semantics onto captured local variables , so I will implement a different way . Thanks for the answers though , I have learned a couple of useful things anyway . : ) private void WaitFor10Events ( ) { volatile int totalEvents = 0 ; // error CS0106 : _someEventGenerator.SomeEvent += ( s , e ) = > totalEvents++ ; while ( totalEvents < 10 ) Thread.Sleep ( 100 ) ; }",Making variables captured by a closure volatile "C_sharp : I have a model like below : I 'm rendering the Engineer property in a View < CreateStockcheckJobModel > using Html.EditorFor ( m = > m.Engineer , `` EngineerEditor '' ) .How do I access the value in the Engineer attribute ( in this case true ) from within the code in my partial view ( EngineerEditor.ascx ) ? Below is my editor codeI 'm aware of reflection , however i 'm unsure how to use it as the attribute is n't added to the EngineerModel class it 's added to the Engineer property of the CreateStockcheckJobModel class . If i could get the PropertyInfo that I 'm rendering from the editor code then I 'd be sorted , but I do n't know how to get that information . If I go down the route of enumerate all properties in the CreateStockcheckJobModel class then I 'm going to get issues if I have more than one EngineerModel property ( one might have the attribute with True , another might have False ) . public class CreateStockcheckJobModel { [ Engineer ( true ) ] public EngineerModel Engineer { get ; set ; } } < % @ Control Language= '' C # '' Inherits= '' ViewUserControl < EngineerModel > '' % > < % if ( PropertyImRenderingHasAttributeWithTrueBooleanValue ) // What goes here ? { % > < p > Render one thing < /p > < % } else { % > < p > Render another thing < /p > < % } % >",How to access C # model attribute within EditorFor "C_sharp : I noticed that the C # compiler generates a ret instruction at the end of void methods : I 've written a compiler for .NET and it works regardless if I emit a ret statement or not ( I 've checked the generated IL and it 's indeed not in there ) .I just wonder : Is ret on methods returning void required for anything ? It does n't seem to do anything with the stack , so I believe it 's completely unnecessary for void methods , but I 'd like to hear from someone who knows a bit more about the CLR ? .method private hidebysig static void Main ( string [ ] args ) cil managed { // method body L_0030 : ret }",Is a ret instruction required in .NET applications ? "C_sharp : Ok , this is working : ... and this does not ... So , what 's the difference ? I 'm missing something . A call to `` DisposeValueProxy ( ) gives the following error : '' Can not marshal 'parameter # 1 ' : Pointers can not reference marshaled structures . Use ByRef instead . `` ( and yes , I can simply use IntPtr/void* instead of `` ValueProxy* '' but that 's not my point ) .A call to `` DisposeHandleProxy ( ) '' works fine.Let 's see if someone can figure this one out . ; ) [ StructLayout ( LayoutKind.Explicit , Size = 28 ) ] public unsafe struct HandleProxy { [ FieldOffset ( 0 ) , MarshalAs ( UnmanagedType.I4 ) ] public JSValueType _ValueType ; // JSValueType is an enum [ FieldOffset ( 4 ) , MarshalAs ( UnmanagedType.I4 ) ] public Int32 _ManagedObjectID ; [ FieldOffset ( 8 ) ] public void* _NativeEngineProxy ; [ FieldOffset ( 16 ) , MarshalAs ( UnmanagedType.I4 ) ] public Int32 _EngineID ; [ FieldOffset ( 20 ) ] public void* _Handle ; } [ DllImport ( `` Proxy '' ) ] public static extern void DisposeHandleProxy ( HandleProxy* handle ) ; [ StructLayout ( LayoutKind.Explicit , Size = 20 ) ] public unsafe struct ValueProxy { [ FieldOffset ( 0 ) , MarshalAs ( UnmanagedType.I4 ) ] public JSValueType _ValueType ; // 32-bit type value . [ FieldOffset ( 4 ) , MarshalAs ( UnmanagedType.Bool ) ] public bool _Boolean ; [ FieldOffset ( 4 ) , MarshalAs ( UnmanagedType.I4 ) ] public Int32 _Integer ; [ FieldOffset ( 4 ) ] public double _Number ; [ FieldOffset ( 12 ) ] public void* _String ; } [ DllImport ( `` Proxy '' ) ] public static extern void DisposeValueProxy ( ValueProxy* valueProxy ) ;",What is the difference between C # marshaled struct pointers ? "C_sharp : While uploading a big file via Postman ( from a frontend with form written in php I have the same issue ) I am getting a 502 bad gateway error message back from the Azure Web App : 502 - Web server received an invalid response while acting as a gateway or proxy server . There is a problem with the page you are looking for , and it can not be displayed . When the Web server ( while acting as a gateway or proxy ) contacted the upstream content server , it received an invalid response from the content server.The error I see in Azure application insights : Microsoft.AspNetCore.Connections.ConnectionResetException : The client has disconnected < -- - An operation was attempted on a nonexistent network connection . ( Exception from HRESULT : 0x800704CD ) This is happening while trying to upload a 2GB test file . With a 1GB file it is working fine but it needs to work up to ~5GB.I have optimized the part which is writing the file streams to azure blob storage by using a block write approach ( credits to : https : //www.red-gate.com/simple-talk/cloud/platform-as-a-service/azure-blob-storage-part-4-uploading-large-blobs/ ) but for me it looks like that the connection is being closed to the client ( to postman in this case ) as this seems to be a single HTTP POST request and underlying Azure network stack ( e.g . load balancer ) is closing the connection as it takes to long until my API provides back the HTTP 200 OK for the HTTP POST request.Is my assumption correct ? If yes , how can achieve that the upload from my frontend ( or postman ) is happening in chunks ( e.g . 15MB ) which then can be acknowledged by the API in a faster way than the whole 2GB ? Even creating a SAS URL for uploading to azure blob and returning the URL back to the browser would be fine but not sure how I can integrate that easily - also there are max block sizes afaik , so for a 2GB I would probably need to create multiple blocks . If this is the suggestion it would be great to get a good sample here BUT also other ideas are welcome ! This is the relevant part in my API controller endpoint in C # .Net Core 2.2 : And this is a sample HTTP POST via Postman : I set maxAllowedContentLength & requestTimeout in web.config for testing already : requestLimits maxAllowedContentLength= '' 4294967295 '' and aspNetCore processPath= '' % LAUNCHER_PATH % '' arguments= '' % LAUNCHER_ARGS % '' stdoutLogEnabled= '' false '' stdoutLogFile= '' .\logs\stdout '' requestTimeout= '' 00:59:59 '' hostingModel= '' InProcess '' [ AllowAnonymous ] [ HttpPost ( `` DoPost '' ) ] public async Task < IActionResult > InsertFile ( [ FromForm ] List < IFormFile > files , [ FromForm ] string msgTxt ) { ... // use generated container name CloudBlobContainer container = blobClient.GetContainerReference ( SqlInsertId ) ; // create container within blob if ( await container.CreateIfNotExistsAsync ( ) ) { await container.SetPermissionsAsync ( new BlobContainerPermissions { // PublicAccess = BlobContainerPublicAccessType.Blob PublicAccess = BlobContainerPublicAccessType.Off } ) ; } // loop through all files for upload foreach ( var asset in files ) { if ( asset.Length > 0 ) { // replace invalid chars in filename CleanFileName = String.Empty ; CleanFileName = Utils.ReplaceInvalidChars ( asset.FileName ) ; // get name and upload file CloudBlockBlob blockBlob = container.GetBlockBlobReference ( CleanFileName ) ; // START of block write approach //int blockSize = 256 * 1024 ; //256 kb //int blockSize = 4096 * 1024 ; //4MB int blockSize = 15360 * 1024 ; //15MB using ( Stream inputStream = asset.OpenReadStream ( ) ) { long fileSize = inputStream.Length ; //block count is the number of blocks + 1 for the last one int blockCount = ( int ) ( ( float ) fileSize / ( float ) blockSize ) + 1 ; //List of block ids ; the blocks will be committed in the order of this list List < string > blockIDs = new List < string > ( ) ; //starting block number - 1 int blockNumber = 0 ; try { int bytesRead = 0 ; //number of bytes read so far long bytesLeft = fileSize ; //number of bytes left to read and upload //do until all of the bytes are uploaded while ( bytesLeft > 0 ) { blockNumber++ ; int bytesToRead ; if ( bytesLeft > = blockSize ) { //more than one block left , so put up another whole block bytesToRead = blockSize ; } else { //less than one block left , read the rest of it bytesToRead = ( int ) bytesLeft ; } //create a blockID from the block number , add it to the block ID list //the block ID is a base64 string string blockId = Convert.ToBase64String ( ASCIIEncoding.ASCII.GetBytes ( string.Format ( `` BlockId { 0 } '' , blockNumber.ToString ( `` 0000000 '' ) ) ) ) ; blockIDs.Add ( blockId ) ; //set up new buffer with the right size , and read that many bytes into it byte [ ] bytes = new byte [ bytesToRead ] ; inputStream.Read ( bytes , 0 , bytesToRead ) ; //calculate the MD5 hash of the byte array string blockHash = Utils.GetMD5HashFromStream ( bytes ) ; //upload the block , provide the hash so Azure can verify it blockBlob.PutBlock ( blockId , new MemoryStream ( bytes ) , blockHash ) ; //increment/decrement counters bytesRead += bytesToRead ; bytesLeft -= bytesToRead ; } //commit the blocks blockBlob.PutBlockList ( blockIDs ) ; } catch ( Exception ex ) { System.Diagnostics.Debug.Print ( `` Exception thrown = { 0 } '' , ex ) ; // return BadRequest ( ex.StackTrace ) ; } } // END of block write approach ...",Howto upload big files 2GB+ to .NET Core API controller from a form ? C_sharp : I 'm trying to swtich some code I have to use Owned Instances instead of passing around the container.Now I want to Moq the Func < Owned > and inject it but the calls to _syncProcessor ( ) do n't resolve anything So I tried this . but that gives me a run time error that it ca n't cast object of type System.Linq.Expressions.InstanceMethodCallExpressionN to type System.Linq.InvocationExpression public class SyncManager { private Func < Owned < ISynchProcessor > > _syncProcessor = null ; public SyncManager ( Func < Owned < ISynchProcessor > > syncProcessor ) { _syncProcessor = syncProcessor ; } private void Handle ( ) { using ( var service = _syncProcessor ( ) ) { service.Value.Process ( ) ; } } } Mock < ITimer > timer = new Mock < ITimer > ( ) ; Mock < Func < Owned < ISynchProcessor > > > syncProcessor = new Mock < Func < Owned < ISynchProcessor > > > ( ) ; Mock < Owned < ISynchProcessor > > proc = new Mock < Owned < ISynchProcessor > > ( ) ; [ TestInitialize ] public void TestInitialize ( ) { timer = new Mock < ITimer > ( ) ; syncProcessor = new Mock < Func < Owned < ISynchProcessor > > > ( ) ; syncProcessor.Setup ( item = > item.Invoke ( ) ) .Returns ( ( ) = > proc.Object ) ; },Moq with Autofac Func < Owned < IClass > > "C_sharp : Myself and a colleague are having a difference of opinion on when an object can be garbage collected in .NET . Take the following code : My colleague claims that when a release build is run using the server garbage collector that it is valid for the request object to be garbage collected after the call to request.Stream . He asserts that this only happens with the server garbage collector , and never with the workstation garbage collector.The reason this is that the Request class had a finalizer that was closing the Stream given to the request . As a result , when DoStuff2 went to use the stream it got an `` object disposed '' exception . Since the finalizer can only be run by the garbage collector my colleague says that a garbage collection must have taken place before the end of the finally block , but after the last use of requestHowever , it 's my belief that since the above code is just shorthand for something like this : Then request can not be garbage collected after the call to request.Stream at it is still reachable from the finally block . Also , if it were possible for the garbage collector to collect the object then the finally block would potentially exhibit undefined behavior as Dispose would be called on a GC 'd object , which does n't make sense . Likewise , it is n't possible to optimize away the finally block as an exception could be thrown within the try/using block before any garbage collection had taken place , which would require the finally block to execute.Ignoring the issue of closing the stream in the finalizer , is it ever possible for the garbage collector to collect the object before the end of the finally block , and in effect optimize away the logic in the finally block ? Stream stream=getStream ( ) ; using ( var request=new Request ( stream ) ) { Stream copy=request.Stream ; // From here on can `` request '' be garbage collected ? DoStuff1 ( ) ; DoStuff2 ( copy ) ; } Stream stream=getStream ( ) ; Request request=null ; try { Stream copy=request.Stream ; // From here on can `` request '' be garbage collected ? DoStuff1 ( ) ; DoStuff2 ( copy ) ; } finally { if ( request ! =null ) request.Dispose ( ) ; }",.NET server garbage collection and object lifetime "C_sharp : everyone ! I searched the best I could and did not find exactly the help I was looking for.ProblemAutoCompleteTextbox FREEZES and `` eats '' characters while query is performedAsking forMimic Google Instant functionalityBackgroundFirst things first : C # , WPF , .NET 4.0Ok , now that 's out of the way , I 'm trying to find the best way to implement a dynamic AutoComplete Textbox , which queries a database for results after each letter typed . The following code gets executed when the AutoCompleteTextBox 's TextChanged event is fired : Now , let 's say that SearchUnderlyings ( e.SearchText ) takes an average of 600-1100ms - during that time , the textbox is frozen and it `` eats '' any keys pressed . This is an annoying problem I 've been having . For some reason , the LINQ in SearchUnderlyings ( e.SearchText ) is running in the GUI thread . I tried delegating this to a background thread , but still same result.Ideally , I would like the textbox to work the way Google Instant does - but I do n't want to be `` killing '' threads before the server/query can return a result.Anyone have experience or can offer some guidance which will allow me to query as I type without freezing the GUI or killing the server ? Thank you guys ! public void Execute ( object sender , object parameter ) { //removed some unnecessary code for the sake of being concise var autoCompleteBox = sender as AutoCompleteTextBox ; var e = parameter as SearchTextEventArgs ; var result = SearchUnderlyings ( e.SearchText ) ; autoCompleteBox.ItemsSource = result ; }",Autocomplete textbox freezes while executing query . Must be a better way ! "C_sharp : I 've been reading a lot about threading but ca n't figure out how to find a solution to my issue.First let me introduce the problem . I have files which need to be processed . The hostname and filepath are located in two arrays.Now I want to setup several threads to process the files . The number of threads to create is based on three factors : A ) The maximum thread count can not exceed the number of unique hostnames in all scenarios.B ) Files with the same hostname MUST be processed sequentially . I.E We can not process host1_file1 and host1_file2 at the same time . ( Data integrity will be put at risk and this is beyond my control.C ) The user may throttle the number of threads available for processing . The number of threads is still limited by condition A from above . This is purely due to the fact that if we had an large number of hosts let 's say 50.. we might not want 50 threads processing at the same time.In the example above a maximum of 6 threads can be created . The optimal processing routine is shown below.I guess what I 'm after is a guide on how to code the threaded processing routines that are in accordance with the specs above . public class file_prep_obj { public string [ ] file_paths ; public string [ ] hostname ; public Dictionary < string , int > my_dictionary ; public void get_files ( ) { hostname = new string [ ] { `` host1 '' , `` host1 '' , `` host1 '' , `` host2 '' , `` host2 '' , `` host3 '' , `` host4 '' , '' host4 '' , '' host5 '' , '' host6 '' } ; file_paths=new string [ ] { `` C : \\host1_file1 '' , '' C : \\host1_file2 '' , '' C : \\host1_file3 '' , '' C : \\host2_file1 '' , '' C : \\host2_file2 '' , '' C : \\host2_file2 '' , `` C : \\host3_file1 '' , '' C : \\host4_file1 '' , '' C : \\host4_file2 '' , '' C : \\host5_file1 '' , '' C : \\host6_file1 '' } ; //The dictionary provides a count on the number of files that need to be processed for a particular host . my_dictionary = hostname.GroupBy ( x = > x ) .ToDictionary ( g = > g.Key , g = > g.Count ( ) ) ; } } //This class contains a list of file_paths associated with the same host.//The group_file_host_name will be the same for a host.class host_file_thread { public string [ ] group_file_paths ; public string [ ] group_file_host_name ; public void process_file ( string file_path_in ) { var time_delay_random=new Random ( ) ; Console.WriteLine ( `` Started processing File : `` + file_path_in ) ; Task.Delay ( time_delay_random.Next ( 3000 ) +1000 ) ; Console.WriteLine ( `` Completed processing File : `` + file_path_in ) ; } } class Program { static void Main ( string [ ] args ) { file_prep_obj my_files=new file_prep_obj ( ) ; my_files.get_files ( ) ; //Create our host objects ... my_files.my_dictionary.Count represents the max number of threads host_file_thread [ ] host_thread=new host_file_thread [ my_files.my_dictionary.Count ] ; int key_pair_count=0 ; int file_path_position=0 ; foreach ( KeyValuePair < string , int > pair in my_files.my_dictionary ) { host_thread [ key_pair_count ] = new host_file_thread ( ) ; //Initialise the host_file_thread object . Because we have an array of a customised object host_thread [ key_pair_count ] .group_file_paths=new string [ pair.Value ] ; //Initialise the group_file_paths host_thread [ key_pair_count ] .group_file_host_name=new string [ pair.Value ] ; //Initialise the group_file_host_name for ( int j=0 ; j < pair.Value ; j++ ) { host_thread [ key_pair_count ] .group_file_host_name [ j ] =pair.Key.ToString ( ) ; //Group the hosts host_thread [ key_pair_count ] .group_file_paths [ j ] =my_files.file_paths [ file_path_position ] ; //Group the file_paths file_path_position++ ; } key_pair_count++ ; } //Close foreach ( KeyValuePair < string , int > pair in my_files.my_dictionary ) //TODO PROCESS FILES USING host_thread objects . } //Close static void Main ( string [ ] args ) } //Close Class Program",Multithreading task to process files in c # "C_sharp : I 'm facing a problem I do n't even know what to search in Google/Stack Overflow.So comment if you feel the need for further explanation , questions.Basically I want to intersect two lists and return the similarity with the preserved order of the original first string value.Example : I have two strings , that I convert to a CharArray.I want to Intersect these two arrays and return the values that are similar , including/with the order of the first string ( s1 ) .As you can see the first string contains E15 ( in that specific order ) , and so does the seconds one.So these two strings will return : { ' E ' , ' 1 ' , ' 5 ' } The problem I am facing is that if i replace `` s2 '' with : My operation will return : { ' Q ' , ' E ' , ' 1 ' } The result should be : { ' E ' , ' 1 ' } because Q do n't follow the letter 1 Currently my operation is not the greatest effort , because i do n't know which methods to use in .NET to be able to do this.Current code : Feel free to help me out , pointers in the right direction is acceptable as well as a full solution . string s1 = `` E15QD ( A ) '' ; string s2 = `` NHE15H '' ; string s2 = `` NQE18H '' // Will return { ' Q ' , ' E ' , ' 1 ' } List < char > cA1 = s1.ToList ( ) ; List < char > cA2 = s2.ToList ( ) ; var result = cA1.Where ( x = > cA2.Contains ( x ) ) .ToList ( ) ;",Intersect two lists with preserved order in the first one "C_sharp : I have some strings containing code for emoji icons , like : grinning : , : kissing_heart : , or : bouquet : . I 'd like to process them to remove the emoji codes.For example , given : Hello : grinning : , how are you ? : kissing_heart : Are you fine ? : bouquet : I want to get this : Hello , how are you ? Are you fine ? I know I can use this code : However , there are 856 different emoji icons I have to remove ( which , using this method , would take 856 calls to Replace ( ) ) . Is there any other way to accomplish this ? richTextBox2.Text = richTextBox1.Text.Replace ( `` : kissing_heart : '' , `` '' ) .Replace ( `` : bouquet : '' , `` '' ) .Replace ( `` : grinning : '' , `` '' ) .ToString ( ) ;",How remove some special words from a string content ? "C_sharp : I have probably missed something very basic but this has me stumped.When using String.Split ( ) I get different results between and Given this code : Why do I get different results : .Split ( ' ' ) .Split ( new char [ ' ' ] ) using ( System.IO.StreamWriter sw = new StreamWriter ( @ '' C : \consoleapp1.log '' , true ) ) { string anystring = `` pagelength=60 pagewidth=170 cpi=16 lpi=8 landscape=1 lm=2 '' ; sw.WriteLine ( `` .Split ( ' ' ) '' ) ; string [ ] anystrings1 = anystring.Split ( ' ' ) ; for ( int i = 0 ; i < anystrings1.Length ; i++ ) { sw.WriteLine ( $ @ '' { i,2 } : { anystrings1 [ i ] } '' ) ; } sw.WriteLine ( `` .Split ( new char [ ' ' ] ) '' ) ; string [ ] anystrings2 = anystring.Split ( new char [ ' ' ] ) ; for ( int i = 0 ; i < anystrings2.Length ; i++ ) { sw.WriteLine ( $ @ '' { i,2 } : { anystrings2 [ i ] } '' ) ; } } .Split ( ' ' ) 0 : pagelength=60 1 : pagewidth=170 2 : cpi=16 3 : lpi=8 4 : landscape=1 5 : lm=2.Split ( new char [ ' ' ] ) 0 : pagelength=60 pagewidth=170 cpi=16 lpi=8 landscape=1 lm=2",C # string.split variances "C_sharp : I 'm using ASP.NET Core 2.1 ActionResult < T > to return a file from controller : But it returns incomplete json instead of starting file download : Chrome devtools indicates request status as `` ( failed ) '' with tooltip `` net : :ERR_SPDY_PROTOCOL_ERROR '' If I change the code so it returns a FileContentResult then status turns to `` 200 ok '' but still json is written instead of file download : If I change method signature to Or toThen file download starts with both FileResult implementations.How could I use ActionResult < T > to download file ? Am I missing something or is it really some kind of bug ? [ HttpGet ] public ActionResult < FileResult > Download ( ) { var someBinaryFile = `` somebinaryfilepath '' ; return File ( new FileStream ( firstExe , FileMode.Open , FileAccess.Read , FileShare.Read ) , System.Net.Mime.MediaTypeNames.Application.Octet , true ) ; } { `` fileStream '' : { `` handle '' : { `` value '' :2676 } , '' canRead '' : true , '' canWrite '' : false , '' safeFileHandle '' : { `` isInvalid '' : false , '' isClosed '' : false } , '' name '' : '' somebinaryfilepath '' , '' isAsync '' : false , '' length '' :952320 , '' position '' :0 , '' canSeek '' : true , '' canTimeout '' : false { `` fileContents '' : `` somebinaryfilecontent '' , '' contentType '' : '' application/octet-stream '' , '' fileDownloadName '' : '' '' , '' lastModified '' : null , '' entityTag '' : null , '' enableRangeProcessing '' : true } public FileResult Download ( ) public IActionResult Download ( )",ActionResult < FileResult > does n't work as expected "C_sharp : I have downloaded the Roslyn CTP and have run across the following error.A CompilationErrorException is thrown when executing the line session.Execute ( @ '' using System.Linq ; '' ) ; with the following message : ( 1,14 ) : error CS0234 : The type or namespace name 'Linq ' does not exist in the namespace 'System ' ( are you missing an assembly reference ? ) My code is : I 'm especially confused as to why the System.Linq line throws an error while System.Collections is fine . namespace RoslynError { using System ; using Roslyn.Scripting ; using Roslyn.Scripting.CSharp ; internal class RoslynError { static void Main ( string [ ] args ) { var engine = new ScriptEngine ( ) ; Session session = engine.CreateSession ( ) ; session.Execute ( @ '' using System.Collections ; '' ) ; session.Execute ( @ '' using System.Linq ; '' ) ; Console.ReadKey ( ) ; } } }",CompilationErrorException when including System.Linq in Roslyn CP2 "C_sharp : I have following two classes ( models ) , one is base class and other is sub class : In application I am calling ChildClass dynamically using genericsHere , in propertyNames list , I am getting property for BaseClass as well . I want only those properties which are in child class . Is this possible ? What I tried ? Tried excluding it as mentioned in this questionTried determining whether the class is sub class or base class as mentioned here but that does not help either . public class BaseClass { public string BaseProperty { get ; set ; } } public class ChildClass : BaseClass { public string ChildProperty { get ; set ; } } List < string > propertyNames=new List < string > ( ) ; foreach ( PropertyInfo info in typeof ( T ) .GetProperties ( ) ) { propertyNames.Add ( info.Name ) ; }",How to determine if the property belongs to Base class or sub class dynamically in generic type using reflection ? "C_sharp : I have a char [ 26 ] of the letters a-z and via nested for statements I 'm producing a list of sequences like : Currently , the software is written to generate the list of all possible values from aaa-zzz and then maintains an index , and goes through each of them performing an operation on them.The list is obviously large , it 's not ridiculously large , but it 's gotten to the point where the memory footprint is too large ( there are also other areas being looked at , but this is one that I 've got ) .I 'm trying to produce a formula where I can keep the index , but do away with the list of sequences and calculate the current sequence based on the current index ( as the time between operations between sequences is long ) .Eg : I 've tried working out a small example using a subset ( abc ) and trying to index into that using modulo division , but I 'm having trouble thinking today and I 'm stumped.I 'm not asking for an answer , just any kind of help . Maybe a kick in the right direction ? aaa , aaz ... aba , abb , abz , ... zzy , zzz . char [ ] characters = { a , b , c ... z } ; int currentIndex = 29 ; // abdpublic string CurrentSequence ( int currentIndex ) { int ndx1 = getIndex1 ( currentIndex ) ; // = 0 int ndx2 = getIndex2 ( currentIndex ) ; // = 1 int ndx3 = getIndex3 ( currentIndex ) ; // = 3 return string.Format ( `` { 0 } { 1 } { 2 } '' , characters [ ndx1 ] , characters [ ndx2 ] , characters [ ndx3 ] ) ; // abd }",Calculating Nth permutation step ? "C_sharp : I have an abstract class : and a couple of classes that implement this class for specific purposes , e.g.Now using Ninject i want to do Dependency Injection like the following ( this particular code is NOT working ) : So what I want to achieve is thatShould be bound to the Class `` NewsValidator '' , but if any other not-bound version of this class is requested , saythat should be bound to a default Class ( NullValidator ) . Using the code used above throws an Exception , though , because it binds the Validator < News > both to the NewsValidator as well as to the NullValidator.How could I implement this ? Particular types of the generic class should be bound to individual classes . All other types of the generic class that were not explicitly bound should be bound to a default class.Would be really glad about a couple of suggestions ! Thanks ! public abstract class Validator < T > : IValidator public sealed class NewsValidator : Validator < News > Bind < Validator < News > > ( ) .To < NewsValidator > ( ) ; Bind ( typeof ( Validator < > ) ) .To ( typeof ( NullValidator < > ) ) ; Validator < News > Validator < Article > Validator < SomethingElse >",Ninject : Default & specific bindings for a Generic class "C_sharp : I have a couple of .exe files that I run as follows : This code works , but there 's still some flickering being caused from the exe-s being ran multiple times . Is there ANY way to remove the flickering because it 's really annoying for the users to experience it since it happens for a few second ( there are quite a few exe 's being ran ) .I tried using a task to do it on a different thread but since each exe depends on the work on the previous ( it writes to a file ) I get an IO exception.It also seems that the exe files only work if their ProcessPriority is set to Realtime.Edit : Afew more details about what I tried recently : As @ Jack Hughes suggested I tried using a background worker to solve this problem : Here 's what I did : I call RunWorkerAsync ( ) function on the background worker which on it 's turn calls the RunCalculator function for each of the calculators in order.The flickering still persists.Edit2 : I have created a detailed repository which contains my way of running the exe files , the exe files and the ProcessHelper class which Old Fox suggested.You can find instructions on how to use the repository inside the README file.Link to repository : https : //github.com/interdrift/epiwin-flick public void RunCalculator ( Calculator calculator ) { var query = Path.Combine ( EpiPath , calculator.ExeName + `` .exe '' ) ; if ( File.Exists ( Path.Combine ( EpiPath , `` ffs.exe '' ) ) ) { var p = new Process ( ) ; p.StartInfo.FileName = query ; p.StartInfo.WorkingDirectory = EpiPath ; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden ; p.StartInfo.UseShellExecute = false ; p.StartInfo.CreateNoWindow = true ; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden ; p.StartInfo.Arguments = String.Join ( `` `` , calculator.Arguments ) ; p.Start ( ) ; p.WaitForExit ( ) ; } else throw new InvalidOperationException ( ) ; }",Remove flickering from running consecutive exe files "C_sharp : I am profiling my simple 2D XNA game . I found that 4 % of entire running time is taken by simple operarion of adding together two Colors , one of them multiplied first by float.I need to call this method rogulthy 2000 times per frame ( for each tile on map ) , which gave me 120000 times per second for XNA 's 60 fps . Even minimal boosting of single call whould give huge speed impact . Yet I simple do not know how can I make this more effectiveEDIT : As suggested by Michael Stum : This lowered time usage from 4 % to 2.5 % private void DoColorCalcs ( float factor , Color color ) { int mul = ( int ) Math.Max ( Math.Min ( factor * 255.0 , 255.0 ) , 0.0 ) ; tile.Color = new Color ( ( byte ) Math.Min ( tile.Color.R + ( color.R * mul / 255 ) , 255 ) , ( byte ) Math.Min ( tile.Color.G + ( color.G * mul / 255 ) , 255 ) , ( byte ) Math.Min ( tile.Color.B + ( color.B * mul / 255 ) , 255 ) ) ; } private void DoColorCalcs ( float factor , Color color ) { factor= ( float ) Math.Max ( factor , 0.0 ) ; tile.Color = new Color ( ( byte ) Math.Min ( tile.Color.R + ( color.R * factor ) , 255 ) , ( byte ) Math.Min ( tile.Color.G + ( color.G * factor ) , 255 ) , ( byte ) Math.Min ( tile.Color.B + ( color.B * factor ) , 255 ) ) ; }",Optimize color manipulation on XNA "C_sharp : I have a LINQ statement which pulls the top N record IDs from a collection and then another query which pulls all records which have those IDs . It feels very clunky and inefficient and i was wondering if there might be a more succinct , LINQy way to get the same resultsFYI - there will be multiple records with the same ID , which is why there is the Distinct ( ) and why i ca n't use a simple Take ( ) in the first place.Thanks ! var records = cache.Select ( rec = > rec.Id ) .Distinct ( ) .Take ( n ) ; var results = cache.Where ( rec = > records.Contains ( rec.Id ) ) ;",Using LINQ to get the results from another LINQ collection "C_sharp : I 'll try to be as explicit as possible , in case there is a better solution for my problem than answering my question.I 'm working in C # .I have a report template that can include any number of 'features ' turned on . A feature might be a table of information , a pie/bar chart , a list , etc . I am generating the report as a text file , or a PDF ( possibly other options in the future ) .So far I have an IFeature interface , and some feature types implementing it : ChartFeature , ListFeature , etc.I read the list of features enabled from the database and pass each one to a method along with the data id and the method returns a populated IFeature of the proper type.I also have an IReportWriter interface that TextReportWriter and PdfReportWriter implement . That interface has a method : AddFeature ( IFeature ) .The problem is that AddFeature in each writer ends up looking like : In the PDF writer the above would be modified to generate PDF table cells , text boxes , and so forth.This feels ugly . I like it somewhat better as AddFeature ( ListFeature ) { ... } , AddFeature ( ChartFeature ) because at least then it 's compile time checked , but in practice it just moves the problem so now outside if the IReportWriter I 'm calling if ( feature is ... ) .Moving the display code into the feature just reverses the problem because it would need to know whether it should be writing plain text or a PDF.Any suggestions , or am I best just using what I have and ignoring my feelings ? Edit : Filled in some of the conditions to give people a better idea of what is happening . Do n't worry too much about the exact code in those examples , I just wrote it off the top of my head . public void AddFeature ( IFeature ) { InsertSectionBreakIfNeeded ( ) ; if ( IFeature is TableFeature ) { TableFeature tf = ( TableFeature ) feature ; streamWriter.WriteLine ( tf.Title ) ; for ( int row=0 ; row < tf.Data.First.Length ; row++ ) { for ( int column=0 ; i < tf.Data.Length ; i++ ) { if ( i ! = 0 ) { streamWriter.Write ( `` | '' ) ; } streamWriter.Write ( feature.Data [ column ] [ row ] ) ; } } } else if ( IFeature is ListFeature ) { ListFeature lf = ( ListFeature ) feature ; streamWriter.Write ( lf.Title + `` : `` ) ; bool first = true ; foreach ( var v in lf.Data ) { if ( ! first ) { streamWriter.Write ( `` , `` ) ; } else { first = false ; } streamWriter.Write ( v ) ; } } ... else { throw new NotImplementedException ( ) ; } sectionBreakNeeded = true ; }",Is there a design pattern to handle when code depends on the subtype of two objects "C_sharp : I have a bunch of regular , closed and opened types in my assembly . I have a query that I 'm trying to rule out the open types from itUpon debugging the generic arguments of an open type , I found that their FullName is null ( as well as other things like the DeclaringMethod ) - So this could be one way : Is there a built-in way to know if a type is open ? if not , is there a better way to do it ? Thanks . class Foo { } // a regular typeclass Bar < T , U > { } // an open typeclass Moo : Bar < int , string > { } // a closed typevar types = Assembly.GetExecutingAssembly ( ) .GetTypes ( ) .Where ( t = > ? ? ? ) ; types.Foreach ( t = > ConsoleWriteLine ( t.Name ) ) ; // should *not* output `` Bar ` 2 '' bool IsOpenType ( Type type ) { if ( ! type.IsGenericType ) return false ; var args = type.GetGenericArguments ( ) ; return args [ 0 ] .FullName == null ; } Console.WriteLine ( IsOpenType ( typeof ( Bar < , > ) ) ) ; // true Console.WriteLine ( IsOpenType ( typeof ( Bar < int , string > ) ) ) ; // false",Detect if a generic type is open ? "C_sharp : If I build a query say : ( the query is build using XDocument class from System.Xml.Linq ) and then I call elements.Last ( ) SEVERAL times . Will each call return the most up to date Last ( ) element ? For example if I doIs it actually getting the latest element each time and added a new one to the end or is elements.Last ( ) the same element each time ? var elements = from e in calendarDocument.Root.Elements ( `` elementName '' ) select e ; elements.Last ( ) .AddAfterSelf ( new XElement ( `` elementName '' , `` someValue1 '' ) ) ; elements.Last ( ) .AddAfterSelf ( new XElement ( `` elementName '' , `` someValue2 '' ) ) ; elements.Last ( ) .AddAfterSelf ( new XElement ( `` elementName '' , `` someValue3 '' ) ) ; elements.Last ( ) .AddAfterSelf ( new XElement ( `` elementName '' , `` someValue4 '' ) ) ;",C # Linq - Delayed Execution "C_sharp : I use this code to copy files to Clipboard : Unfortunately , this does n't work if the disk is a TrueCrypt mounted volume . What is the way to do this on a TrueCrypt volume ? IDataObject data = new DataObject ( ) ; data.SetData ( DataFormats.FileDrop , new string [ ] { @ '' X : \test.doc '' } ) ; MemoryStream memo = new MemoryStream ( 4 ) ; byte [ ] bytes = new byte [ ] { ( byte ) ( 5 ) , 0 , 0 , 0 } ; memo.Write ( bytes , 0 , bytes.Length ) ; data.SetData ( `` Preferred DropEffect '' , memo ) ; Clipboard.SetDataObject ( data ) ;",Copy file from TrueCrypt volume to clipboard ? "C_sharp : I have the following XAML excerpt : Basically , this splitview is compacted until the user presses a button which then sets the IsPaneOpen to true , which in turn shows my application menu.The problem is , the very first thing i have in the menu is the search box and it seems to be getting focused automatically no matter what i do . The fact that it has focus then brings up the touch keyboard on phones , which is very annoying and hides most of the menu on small phones.I tried playing with the TabIndex property to either give it a huge number or even put a lower index for something else.I also tried setting the IsTabStop to false but that did n't seem to do anything.Is there a clean way to prevent the box from gaining focus automatically ? ( Besides disabling / hiding the element and then enabling / showing it again ) < SplitView Name= '' Menu '' DisplayMode= '' CompactOverlay '' OpenPaneLength= '' 200 '' CompactPaneLength= '' 0 '' Grid.RowSpan= '' 2 '' > < SplitView.Pane > < StackPanel > < AutoSuggestBox Margin= '' 0,20,0,20 '' Width= '' 170 '' PlaceholderText= '' Search '' QueryIcon= '' Find '' > < /AutoSuggestBox > < ListBox > < ListBoxItem Tapped= '' Projects_Tapped '' > < StackPanel Orientation= '' Horizontal '' > < SymbolIcon Symbol= '' Library '' / > < TextBlock Margin= '' 10,0,0,0 '' > Projects < /TextBlock > < /StackPanel > < /ListBoxItem > [ ... . ] < /ListBox > < /StackPanel > < /SplitView.Pane > < /SplitView >",How to prevent TextBlock from getting automatic focus "C_sharp : I try to create a TagHelper that checks for the existence of an image and if it is not there replaces the path to a default image . Unfortunately I have problems to map the `` ~ '' symbol in my tag helper.For example . My src of the image contains `` ~\images\image1.png '' . Now I want to check for existence of this file and if not replace it by another one from an attribute of the tag . I am stuck at mapping the `` ~ '' to wwwroot of my application.This is what I have actually : [ HtmlTargetElement ( `` img '' , TagStructure = TagStructure.WithoutEndTag ) ] public class ImageTagHelper : TagHelper { public ImageTagHelper ( IHostingEnvironment environment ) { this._env = environment ; } private IHostingEnvironment _env ; public string DefaultImageSrc { get ; set ; } public override void Process ( TagHelperContext context , TagHelperOutput output ) { // urlHelper.ActionContext.HttpContext . //var env = ViewContext.HttpContext.ApplicationServices.GetService ( typeof ( IHostingEnvironment ) ) as IHostingEnvironment ; string imgPath = context.AllAttributes [ `` src '' ] .Value.ToString ( ) ; if ( ! File.Exists ( _env.WebRootPath + imgPath ) ) { output.Attributes.SetAttribute ( `` src '' , _env.WebRootPath + DefaultImageSrc ) ; } } }",AspNetCore get path to wwwroot in TagHelper "C_sharp : I have a WebAPI server that has a Hub that replies to Subscribe requests by publishing an Dictionary < long , List < SpecialParam > > object.The list of SpecialParam contains items of type SpecialParamA & SpecialParamB which both inherit SpecialParam.When I try to capture the publish on the client : The DoStuff ( ) method is n't called . If I change the publish return value to string , and change the proxy to receive a string value , the DoStuff ( ) method is called . Therefore , the problem is with the deserialization of the SpecialParam Item.I tried configuring on the server-side : But it did n't help.I also tried adding to the client : And it also did n't help.In other solutions I found that people defined a new IParameterResolver , but it is only called when the server receives the input to the hub method , and not when the output is published from the hub.Please help ! UPDATEHere is what I caught with fidler : This is what the server replies to the client.UPDATE 2I 'm still trying to figure out how to receive it already deserialized as Dictionary < long , List < SpecialParam > > . hubProxy.On < Dictionary < long , List < SpecialParam > > > ( hubMethod , res = > { DoStuff ( ) ; } ) ; var serializer = JsonSerializer.Create ( ) ; serializer.TypeNameHandling = TypeNameHandling.All ; var hubConfig = new HubConfiguration ( ) ; hubConfig.Resolver.Register ( typeof ( JsonSerializer ) , ( ) = > serializer ) ; GlobalHost.DependencyResolver.Register ( typeof ( JsonSerializer ) , ( ) = > serializer ) ; HubConnection hubConnection = new HubConnection ( hubPath ) ; hubConnection.JsonSerializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto ; hubProxy = hubConnection.CreateHubProxy ( hubName ) ; hubProxy.JsonSerializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto ; { `` $ type '' : '' Microsoft.AspNet.SignalR.Hubs.HubResponse , Microsoft.AspNet.SignalR.Core '' , '' I '' : '' 0 '' }",Deserialize object passed as abstract class by SignalR "C_sharp : I have an asp.net C # MVC website . It uses SimpleAuthentication and forms authentication . Everything works fine , requiring people to log in to go to pages . However , I have one controller called `` ReportsController '' . Whenever you go to the URL 's of the actions within this controller it always pops up with `` Authentication Required '' in the browser window.It is only doing it for this controller and not any others . The URL will be `` www.domain.com/reports '' . This URL works fine when I run from IIS and from my development server , but not on my live server . This is running IIS7.I have checked my web.config and it is definately set to Forms authentication and not Windows.Anyone have any ideas why any urls beginning with `` /Reports '' would not work . I am guessing it is something specific to the server , such as an IIS setting or web.config change , but I can not figure out what this would be.Web.config : namespace ProjectName.Controllers { public class ReportsController : Controller { public ActionResult Index ( ) { throw new SystemException ( `` here '' ) ; return View ( ) ; } } } < authentication mode= '' Forms '' > < forms loginUrl= '' ~/ '' timeout= '' 2880 '' / > < /authentication >","Website asks for `` Authentication Required '' on an MVC controller , but not others" "C_sharp : I have an interface here named IFish . I want to derive it with an abstract class ( WalkingFishCommon ) which provides an incomplete implementation , so that classes derived from WalkingFishCommon do not have to implement the CanWalk property : I 've not yet discovered how to make the compiler happy , while still achieving the goal of forcing classes derived from WalkingFishCommon to implement the Swim ( ) method . Particularly baffling is the delta between ( 1 ) and ( 2 ) , where the compiler alternates between complaining that Swim ( ) is n't marked abstract , and in the next breath complains that it ca n't be marked abstract . Interesting error ! Any help ? interface IFish { bool Swim ( ) ; bool CanWalk { get ; } } abstract class WalkingFishCommon : IFish { bool IFish.CanWalk { get { return true ; } } // ( 1 ) Error : must declare a body , because it is not marked // abstract , extern , or partial // bool IFish.Swim ( ) ; // ( 2 ) Error : the modifier 'abstract ' is not valid for this item // abstract bool IFish.Swim ( ) ; // ( 3 ) : If no declaration is provided , compiler says // `` WalkingFishCommon does not implement member IFish.Swim ( ) '' // { no declaration } // ( 4 ) Error : the modifier 'virtual ' is not valid for this item // virtual bool IFish.Swim ( ) ; // ( 5 ) Compiles , but fails to force derived class to implement Swim ( ) bool IFish.Swim ( ) { return true ; } }",How to satisfy the compiler when only partially implementing an interface with an abstract class ? C_sharp : It seems when I 'm in exception handler like this : Or like this : The stack was already unwind to call my custom unhandled exception handler . Seems it does n't make sense to write a minidump at this point cause the stack was already unwind . Without unwinding the stack application ca n't understand whether this exception was unhandled or not.Even if I can see stack in UnhandledExceptionEventArgs.ExceptionObject I ca n't get minidump at exact place where application crashed.Is there another way ? I know I can ask system to write a dump but I should be Administrator for that.UPDATE : Ok . I 've got an idea ) Would be nice if in FirstChanceException handler I can walk stack back and see if this exception is unhandled or not . But this should be fast enough to work in production . AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException ; Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException ;,Does it makes sense to write minidump on Unhandled Exception in .NET ? "C_sharp : I would like to make some LINQ extensions for generic types . I know how to extend LINQ without using delegates , I have several as-yet-defined types that will have properties which I will need to enumerate and things like variance out of . How can I define my Variance extension method so it takes a delegate ? public static class LinqExtensions { public static double Variance ( this IList < double > data ) { double sumSquares=0 ; double avg = data.Average ( ) ; foreach ( var num in data ) { sumSquares += ( num - avg * num - avg ) ; } return sumSquares / ( data.Count - 1 ) ; } public static decimal ? Variance < TSource > ( this IEnumerable < TSource > source , Func < TSource , decimal ? > selector ) { //where to start for implementing ? } }",Generic extension methods in LINQ "C_sharp : I am using iTextSharp 5.5.1 in order to sign PDF files digitally with a detached signature ( obtained from a third party authority ) . Everything seems to work fine , the file is valid and e.g . Adobe Reader reports no problems , displays the signatures as valid etc.The problem is that the Java Clients have apparently some problems with those files - the file can be neither opened nor parsed.The files have a byte order mark in the header which seems to cause the behavior ( \x00EF\x00BB\x00BF ) .I could identify the BOM like this : How can I either remove the BOM ( without losing the validity of the signature ) , or force the iTextSharp library not to append these bytes into the files ? PdfReader reader = new PdfReader ( path ) ; byte [ ] metadata = reader.Metadata ; // metadata [ 0 ] , metadata [ 1 ] , metadata [ 2 ] contain the BOM",Remove Byte Order Mark from signed PDF file ? "C_sharp : I want to inject some email configuration data from database to config class named AuthMessageSenderOptions , this class has following properties : For injecting configuration detail in appsettings.json to AuthMessageSenderOptions class , I use this piece of code in Startup.cs : Now my question is : How can read this data from database instead of appsettings.json and inject them to my AuthMessageSenderOptions class for future use ? public class AuthMessageSenderOptions { public int PortNumber { get ; set ; } public string SmtpServer { get ; set ; } public string UserName { get ; set ; } public string Password { get ; set ; } } services.Configure < AuthMessageSenderOptions > ( Configuration.GetSection ( `` SMTP '' ) ) ;",Inject data from database to a class with ASP.NET MVC Core "C_sharp : I have two classes , a base class and a child class . In the base class i define a generic virtual method : Then in my child class i try to do this : Visual studio gives this weird error : Repeating the where clause on the child 's override also gives an error : So what am i doing wrong here ? protected virtual ReturnType Create < T > ( ) where T : ReturnType { } protected override ReturnTypeChild Create < T > ( ) // ReturnTypeChild inherits ReturnType { return base.Create < T > as ReturnTypeChild ; } The type 'T ' can not be used as type parameter 'T ' in the generic type or method 'Create ( ) ' . There is no boxing conversion or type parameter conversion from 'T ' to 'ReturnType ' . Constraints for override and explicit interface implementation methods are inherited from the base method , so they can not be specified directly",Weird generics compile error "C_sharp : I was going through Edulinq by Jon Skeet , and I came across the following code , Page 23 , in which he implements cache mechanism for Empty ( ) operator of LinqMy question is , how does this actually cache the Array variable ? Optionally , How does it work in CLR ? Edit : Also following that , he mentions there was a revolt against returning an array . Why should anybody not return an array ( even if it is 0 sized ? ) ? private static class EmptyHolder < T > { internal static readonly T [ ] Array = new T [ 0 ] ; }",Jon Skeet 's Edulinq - Empty Array Caching "C_sharp : Background : i have a 1 to 0..1 relationship between User and UserSettings.The important part of the model is as follows : When i do an INSERT : Everything is cool , when i check the trace , User is added first , then the UserSettings - as you would expect , since UserSettings needs the IDENTITY from User.But when i UPDATE that `` SpecialField '' : I see that the trace shows EF updating the UserSettings first , then the User.Why ? This is important for me , because i have trigger logic that needs to execute only when SpecialField is changed , and it needs to reference data on User.Can anyone explain this behaviour ? Is there a workaround ( other than a hack - which would involve me manually `` touching '' special field again , which is really bad ) . public class User { public int UserId { get ; set ; } public string Name { get ; set ; } public UserSettings Settings { get ; set ; } } public class UserSettings { public int UserId { get ; set ; } // PK/FK public sting SpecialField { get ; set ; } } var user = new User { Settings = new UserSettings { SpecialField = `` Foo '' } } ; ctx.Users.Add ( user ) ; ctx.SaveChanges ( ) ; var user = ctx.Users.Include ( `` Settings '' ) .Single ( ) ; user.Name = `` Joe '' ; user.Settings.SpecialField = `` Bar '' ; ctx.SaveChanges ( ) ;",Entity Framework UPDATE Operation - Why is child record updated first ? "C_sharp : I 'm trying to write a debugger type proxy/surrogate for matrices and vectors in Math.NET Numerics , so the debugger shows more useful information ( also in F # FSI ) . The type hierarchy is as follows : Generic.Matrix < T > Double.Matrix : Generic.Matrix < double > Double.DenseMatrix : Double.MatrixWhat worksNon-generic proxy with closed , generic type . It also works the same way if instead of Matrix < double > the constructor would accept a Double.Matrix or a Double.DenseMatrix.Then , decorate Double.DenseMatrix with : What I 'd like to workI 'd prefer not having to implement a separate proxy for every type , so let 's make it generic : Then , decorate Double.DenseMatrix with : Or maybe closed with : And/or maybe also add that attribute to the base classes if needed.None of these work e.g . when debugging Unit Tests , even though the documentation says it is supposed to work when declaring the attribute with an open generic type ( i.e . MatrixSummary < > ) . After all it also works fine with List < T > etc.Any ideas ? Related : Diagnosing why DebuggerTypeProxy attributes are not workingHow can I have my DebuggerTypeProxy target class inherit from base proxies ? http : //msdn.microsoft.com/en-us/library/d8eyd8zc.aspx public class MatrixSummary { public MatrixSummary ( Matrix < double > matrix ) { } // ... } [ DebuggerTypeProxy ( typeof ( MatrixSummary ) ) ] public class MatrixSummary < T > where T : ... { public MatrixSummary ( Matrix < T > matrix ) { } // ... } [ DebuggerTypeProxy ( typeof ( MatrixSummary < > ) ) ] [ DebuggerTypeProxy ( typeof ( MatrixSummary < double > ) ) ]",DebuggerTypeProxy for generic type hierarchy "C_sharp : I have the interesting idea . I want to redefine the keywords in C # , like replace the if keyword to the MyIf or something else . Do someone have any idea about how to do it ? As I think it have to look something like this : Added : Maybe there is the way how to make the C++ or C library which will redefine the part of standard core of C # ? **Notice . I know that it is the bad programming practice and I ask all the programmers to not use the answer in your enterprise code . ** namespace { # define MyIf = if ; # define MyElse = else ; ... public someclass { public void someMethod ( ) { MyIf ( true ) { ... } MyElse { ... } } } }",How to redefine the names for the standard keywords in C # "C_sharp : this is my web service code I am using for the first time webservice in my project . I do n't know how to solve this error . If I am running aspx.cs this is perfectly running and values bind in combo box . But when I am binding values to combobox by using web service , its gives an error : The type Telerik.Web.UI.RadComboBoxContext is not supported because it implements IDictionary . private const int ItemsPerRequest = 10 ; [ WebMethod ] public RadComboBoxItemData [ ] GetAccount ( object context ) { RadComboBoxContext obj = ( RadComboBoxContext ) context ; DataTable data = GetDataAccount ( obj.Text ) ; RadComboBoxData comboData = new RadComboBoxData ( ) ; int itemOffset = obj.NumberOfItems ; int endOffset = Math.Min ( itemOffset + ItemsPerRequest , data.Rows.Count ) ; comboData.EndOfItems = endOffset == data.Rows.Count ; List result = new List ( endOffset - itemOffset ) ; for ( int i = itemOffset ; i < endOffset ; i++ ) { RadComboBoxItemData itemData = new RadComboBoxItemData ( ) ; itemData.Value = data.Rows [ i ] [ `` AccountLevelNo '' ] .ToString ( ) ; itemData.Text = data.Rows [ i ] [ `` AccountDesc3 '' ] .ToString ( ) ; itemData.Attributes.Add ( `` Level6 '' , data.Rows [ i ] [ `` AccountDesc2 '' ] .ToString ( ) ) ; itemData.Attributes.Add ( `` Level1 '' , data.Rows [ i ] [ `` AccountDesc1 '' ] .ToString ( ) ) ; result.Add ( itemData ) ; } comboData.Items = result.ToArray ( ) ; // comboData.Message = GetStatusMessage ( endOffset , data.Rows.Count ) ; return comboData.Items.ToArray ( ) ; } private static DataTable GetDataAccount ( string text ) { int accCode = 0 ; string query = `` select COA.LevelAccountNo , COA.AccountDesc as AccountDesc3 , Level1.AccountDesc as AccountDesc1 , Level2.AccountDesc as AccountDesc2 from COA COA , ( select LevelAccountNo , AccountDesc `` + `` from COA where len ( LevelAccountNo ) =2 ) as Level1 , ( select LevelAccountNo , AccountDesc from COA where len ( LevelAccountNo ) =5 ) as Level2 `` + `` where Level1.LevelAccountNo=left ( COA.LevelAccountNo,2 ) and Level2.LevelAccountNo=left ( COA.LevelAccountNo,5 ) and len ( COA.LevelAccountNo ) > 6 '' ; try { accCode = Convert.ToInt32 ( text ) ; query = query + `` COA.LevelAccountNo like ' '' + text + `` % ' '' ; } catch ( Exception ex ) { query = query + `` COA.AccountDesc3 like ' % '' + text + `` % ' '' ; } SqlConnection con = new SqlConnection ( ConfigurationSettings.AppSettings [ `` ConnectionString '' ] .ToString ( ) ) ; // string constr=ConfigurationManager.ConnectionStrings [ `` ConnectionString '' ] .ConnectionString ; SqlDataAdapter adapter = new SqlDataAdapter ( query , con ) ; // adapter.SelectCommand.Parameters.AddWithValue ( `` @ text '' , text ) ; DataTable data = new DataTable ( ) ; adapter.Fill ( data ) ; con.Close ( ) ; return data ; } Collapse | Copy Code < telerik : RadComboBox ID= '' cboAccount '' runat= '' server '' Height= '' 200 '' Width= '' 200 '' EmptyMessage= '' Select an Account '' EnableLoadOnDemand= '' true '' ShowMoreResultsBox= '' true '' EnableVirtualScrolling= '' true '' > < HeaderTemplate > < h3 > Accounts < /h3 > < /HeaderTemplate > < ClientItemTemplate > < div > < ul > < li > < span > < b > Name : # = Text # < /b > < /span > < /li > < li > < span > Level6 # = Attributes.Level6 # < /span > < /li > < li > < span > Level1 : # = Attributes.Level4 # < /span > < /li > < li > < span > Level4 # = Attributes.Level1 # < /span > < /li > < /ul > < /div > < br > < /br > < /ClientItemTemplate > < WebServiceSettings Method= '' GetAccount '' Path= '' InvestmentDropDownWebService.asmx '' / > < /telerik : RadComboBox >",Telerik.Web.UI.RadComboBoxContext is not supported because it implements IDictionary "C_sharp : I 'm trying to send a JSON request from a javascript application , and create this object ( HourRegistration ) in my SQL DB , but for some reason , I ca n't parse the date from json , to a valid DateTime.JSON date from JSSo dd/MM/yyyyI 'm trying to parse like so : Entire methodScreenshotToCharArray ( ) I do n't really know why this does n't work . As far as I recall , this should work ? hourRegistration.Date = `` 12/08/2015 '' ; Date = DateTime.ParseExact ( hourRegistration.Date , `` dd/MM/yyyy '' , CultureInfo.InvariantCulture ) public void CreateHours ( HourRegistrationDTO hourRegistration ) { DAO.Instance.HourRegistration.Add ( new HourRegistration ( ) { Date = DateTime.ParseExact ( hourRegistration.Date , `` dd/MM/yyyy '' , CultureInfo.InvariantCulture ) , Cust_ID = hourRegistration.Cust_id , Login_ID = hourRegistration.Login_id , Hours = hourRegistration.Hours , Comment = hourRegistration.Comment } ) ; DAO.Instance.SaveChanges ( ) ; }",DateTime.ParseExact : `` String not recognised as a valid DateTime '' "C_sharp : I 'm looking at Task.Delay ( int ) decompiled in ILSpy : This method is used like await Task.Delay ( 5000 ) ; , and the intellisense even says `` ( awaitable ) '' : So how is it that Task.Delay ( int ) is n't marked async ( public static async Task Delay ( int millisecondsDelay ) ) ? // System.Threading.Tasks.Task [ __DynamicallyInvokable ] public static Task Delay ( int millisecondsDelay ) { return Task.Delay ( millisecondsDelay , default ( CancellationToken ) ) ; }",How is Task.Delay awaitable if it 's not marked async ? "C_sharp : So I 'm trying to get into .NET Core MVC using Visual Studio 2019 Enterprise.I tried to follow a fairly simple example from Microsofts own documentation . After setting up the code , I have the template project that they give you with MVC . So on the `` About '' page I have the following controller class AboutController.cs with the method found on Microsofts website : The only `` big '' difference is that I return the view , not an `` Ok '' because I 'm not really interested in that . I want to modify the view I 'm looking at not go to a completely new view ( maybe I 'm misunderstanding how MVC works ? ) .Now my HTML looks like this : This produces the form , also as seen in their documentation linked earlier . When I click the `` Browse '' button to find a picture , it works fine and when I click `` Open '' so I can upload it , the Visual Studio debugger stops running immediately . No error anywhere that I can see.Any idea what causes this behaviour ? Update 1It appears that just calling return View ( ) ; exhibits the same behaviour and Nuget says it 's AspNetCore.Mvc 2.1.1Update 2Turns out the debugger does not work in this particular instance with the browser called `` Brave '' which is a chromium browser that I use ( which If forgot to mention ) [ HttpPost ( `` UploadFiles '' ) ] public async Task < IActionResult > Post ( List < IFormFile > files ) { long size = files.Sum ( f = > f.Length ) ; string filePath = Path.GetTempFileName ( ) ; if ( files.Count > 0 ) { IFormFile file = files [ 0 ] ; if ( file.Length > 0 ) { using ( FileStream stream = new FileStream ( filePath , FileMode.Create ) ) { await file.CopyToAsync ( stream ) ; } } } return View ( ) ; } < form method= '' post '' enctype= '' multipart/form-data '' asp-controller= '' About '' asp-action= '' Post '' > < div class= '' form-group '' > < div class= '' col-md-10 '' > < p > Upload one image using this form : < /p > < input type= '' file '' name= '' files '' > < /div > < /div > < div class= '' form-group '' > < div class= '' col-md-10 '' > < input type= '' submit '' value= '' Upload '' > < /div > < /div > < /form >",Visual Studio debugging stop immediately on file upload in mvc ? "C_sharp : I need to make the following code work on WP8 , the problem is that there is no X509Certificate2 class on WP8 , I have tried using bouncy castle apis but I have n't really managed to figure it out.Is there a way to make this code work on WP8 ? private string InitAuth ( X509Certificate2 certificate , string systemId , string username , string password ) { byte [ ] plainBytes = Encoding.UTF8.GetBytes ( password ) ; var cipherB64 = string.Empty ; using ( var rsa = ( RSACryptoServiceProvider ) certificate.PublicKey.Key ) cipherB64 = systemId + `` ^ '' + username + `` ^ '' + Convert.ToBase64String ( rsa.Encrypt ( plainBytes , true ) ) ; return cipherB64 ; }",X509Certificate2 to X509Certificate on Windows Phone 8 "C_sharp : I am looking to expose a service to a selection of clients over the internet . At this stage the api is very small , and I only want known clients to be able to access the service . I do n't need to be able to identify the clients now , however I envisage that in future I will need to be able to identify clients , as the api grows.I 'm wondering what the best way to secure the service is in the short term , with a view to the longer term where I may want to be able to authorise client access to specific methods on the service ? I was thinking of using Transport security - i.e . SSL . Should I also look at using Message security with in which clase each client will have their own certificate that will authenticate them with the service ? Or should I simply provide each client an API key which will provide a similar level of client differentiation ? Any other suggestions welcome . Note that this is a service to service interface - i.e . not a client application . The number of users of the service will be limited , and I do n't foresee needing to apply security at the data level , moreso at the method access level . clientCredentialType= '' certificate ''",Best way to secure a WCF service on the internet with few clients "C_sharp : We have a webapp that routes many requests through a .NET IHttpHandler ( called proxy.ashx ) for CORS and security purposes . Some resources load fast , others load slow based on the large amount of computation required for those resources . This is expected.During heavy load , proxy.ashx slows to a crawl , and ALL resources take forever to load . During these peak load times , if you bypass the proxy and load the resource directly , it loads immediately which means that the proxy is the bottleneck. ( i.e . http : //server/proxy.ashx ? url=http : //some_resource loads slow , but http : //some_resource loads fast on its own ) .I had a hypothesis that the reduced responsiveness was because the IHttpHandler was coded synchronously , and when too many long-running requests are active , the IIS request threads are all busy . I created a quick A/B testing app to verify my hypothesis , and my test results are showing that this is not the case.This article is where I am basing understanding of the request thread pool . On the Web server , the .NET Framework maintains a pool of threads that are used to service ASP.NET requests . When a request arrives , a thread from the pool is dispatched to process that request . If the request is processed synchronously , the thread that processes the request is blocked while the request is being processed , and that thread can not service another request . ... However , during an asynchronous call , the server is not blocked from responding to other requests while it waits for the first request to complete . Therefore , asynchronous requests prevent request queuing when there are many requests that invoke long-running operations.In my example below , in theory , the synchronous handler should hog request threads after a certain threshold , preventing more new requests from starting . The async handler should allow MANY more requests to queue up , because every request almost immediately yields its request thread back to the thread pool while it awaits Task.Delay , allowing that request thread to process a new request while the previous request is still awaiting.Synchronous HttpHandlerAsynchronous HandlerBenchmarkingI ran some benchmarks using the apache benchmark utility . Here 's the command I 'm using ( changing the numbers for the results below , obviously ) .ab -n 1000 -c 10 http : //localhost/AsyncProxyTest/Sync.ashxab -n 1000 -c 10 http : //localhost/AsyncProxyTest/Async.ashxResults1,000 requests , 10 at a timesync : 30.10 requests/secondasync : 32.05 request/second10,000 requests , 100 at a timesync : 33.02 requests/secondasync : 32.05 requests/second10,000 requests , 1,000 at a timesync : 32.55 requests/secondasync : 32.05 requests/secondAs you can see , sync versus async seems to have almost no effect ( at least not enough to make it worth the switch ) . My question is : Did I mess something up in my tests that is not accurately modeling this concept ? < % @ WebHandler Language= '' C # '' Class= '' SyncHandler '' % > using System.Web ; using System.Threading ; public class SyncHandler : IHttpHandler { public void ProcessRequest ( HttpContext context ) { //BLOCKING artifical pause to simulate network activity Thread.Sleep ( 300 ) ; var Response = context.Response ; Response.Write ( `` sync response '' ) ; } public bool IsReusable { get { return true ; } } } < % @ WebHandler Language= '' C # '' Class= '' AsyncHandler '' % > using System.Web ; using System.Threading.Tasks ; public class AsyncHandler : HttpTaskAsyncHandler { public override async Task ProcessRequestAsync ( HttpContext context ) { //NON-BLOCKING artificial pause to simulate network activity await Task.Delay ( 300 ) ; var Response = context.Response ; Response.Write ( `` async response '' ) ; } public override bool IsReusable { get { return true ; } } }",IHttpHandler versus HttpTaskAsyncHandler performance "C_sharp : I have old project which used ADO.NET to access the persistent store . Currently , I want to migrate it to EF ( 6.1.3 , if it matters ) , in order to support several DB providers with minimal code duplicate.There is an entity , which contains Hashtable property : With ADO.NET , the BinaryFormatter was used to convert this data property to the BLOB , and vice versa : Now I need to tell EF how it should store and retrieve that property.What have I triedI could store one more property in the entity : But this solution is prone to errors , and special workflow with that property must be followed.P.S . Actually this question is not about the Hashtable only , but about every custom class which must be stored and retrived in a special way . public class Record { ... public Hashtable data { get ; set ; } } using ( MemoryStream stream = new MemoryStream ( ) ) { BinaryFormatter formatter = new BinaryFormatter ( ) ; formatter.Serialize ( stream , data ) ; result = stream.GetBuffer ( ) ; } // -- -- -- -- -- using ( MemoryStream serializationStream = new MemoryStream ( ( byte [ ] ) value ) ) { BinaryFormatter formatter = new BinaryFormatter ( ) ; result = ( Hashtable ) formatter.Deserialize ( serializationStream ) ; } public class Record { public byte [ ] dataRaw { get ; set ; } [ NotMapped ] public Hashtable data { get { /*deserialize dataRaw */ } set { /*Serialize to dataRaw*/ } } }",How to deal with Hashtable property of entity in database using EntityFramework "C_sharp : I would like to - for obscure reasons thou shall not question - start a lock in a method , and end it in another . Somehow like : Would have the same behaviour as : The problem is that the lock keyword works in a block syntax , of course . I 'm aware that locks are not meant to be used like this , but I 'm more than open to the creative and hacky solutions of S/O . : ) object mutex = new object ( ) ; void Main ( string [ ] args ) { lock ( mutex ) { doThings ( ) ; } } object mutex = new object ( ) ; void Main ( string [ ] args ) { Foo ( ) ; doThings ( ) ; Bar ( ) ; } void Foo ( ) { startLock ( mutex ) ; } void Bar ( ) { endlock ( mutex ) ; }",Start and finish lock in different methods "C_sharp : I have JWT-based claims authentication/ authorization set up in my .NET Core application , which authenticates as expected , but my policy enforcement is not acting as I would expect.I have a requirements implementation and handler set up as follows : I have a helper set up like so : ... off of my Startup.cs , I have the policy defined : ... and on my controller , it 's written as such : If I run this with the AuthorizeAttribute commented out , I can take a look at the user 's claims , and the `` cim : true '' is in the claims enumeration , but if I run it with the AuthorizeAttribute enabled , I get a 403 Forbidden error.I tried putting a breakpoint on the line in the ImpersonationHandler : ... but the debugger never stops here , so I do n't know what the problem is . Can someone educate me as to what I 'm doing wrong ? public class ImpersonationRequirement : IAuthorizationRequirement { } public class ImpersonationHandler : AuthorizationHandler < ImpersonationRequirement > { protected override Task HandleRequirementAsync ( AuthorizationHandlerContext context , ImpersonationRequirement requirement ) { if ( context.User.CanImpersonate ( ) ) context.Succeed ( requirement ) ; return Task.CompletedTask ; } } public static bool CanImpersonate ( this ClaimsPrincipal principal ) { var val = principal ? .FindFirst ( MyClaimTypes.CAN_IMPERSONATE ) ? .Value ; return bool.TryParse ( val , out var value ) & & value ; } public class MyClaimTypes { /// < summary > /// Boolean value indicating this user is authorized to impersonate other customer accounts . /// < /summary > public const string CAN_IMPERSONATE = `` cim '' ; ... /// < summary > /// Actual name of the user impersonating the current user . /// < /summary > public const string IMPERSONATING_USER = `` imp '' ; } services.AddAuthorization ( options = > { options.AddPolicy ( `` Impersonator '' , policy = > policy.Requirements.Add ( new ImpersonationRequirement ( ) ) ) ; } ) ; [ Produces ( `` application/json '' ) ] [ Authorize ( Policy = `` Impersonator '' ) ] public class ImpersonationController : Controller { private readonly ILogger _logger ; private readonly ITokenManagementService _tokenManagementService ; private readonly UserManager < MyUser > _userManager ; public ImpersonationController ( ITokenManagementService tokenManagementService , ILoggerFactory loggerFactory , UserManager < MyUser > userManager ) { _tokenManagementService = tokenManagementService ; _userManager = userManager ; _logger = loggerFactory.CreateLogger < ImpersonationController > ( ) ; } [ HttpPost ] [ Route ( `` ~/api/impersonation/token '' ) ] [ ProducesResponseType ( typeof ( AuthenticationResponse ) , 200 ) ] [ ProducesResponseType ( typeof ( Exception ) , 500 ) ] public async Task < IActionResult > Impersonate ( [ FromBody ] string userNameToImpersonate ) { try { var impersonated = await _userManager.FindByNameAsync ( userNameToImpersonate ) ; if ( impersonated == null ) throw new EntityNotFoundException ( $ '' Unable to find user ' { userNameToImpersonate } ' in the data store . `` ) ; var actualUserId = User.UserId ( ) ; var token = await _tokenManagementService.GenerateJwt ( impersonated.Id , actualUserId ) ; var refresh = await _tokenManagementService.GenerateRefreshToken ( impersonated.Id , actualUserId ) ; var response = new AuthenticationResponse { AuthenticationToken = token , RefreshToken = refresh } ; return Ok ( response ) ; } catch ( Exception ex ) { return new OopsResult ( ex ) ; } } } if ( context.User.CanImpersonate ( ) ) context.Succeed ( requirement ) ;",ASP.NET Core Authorization Policies : Ca n't step into the handler ? "C_sharp : I am running the HelloMvc sample application from the command line using k web . I have tried to run it using the different environments available to me using kvm use -runtime . When I change the controller and hit F5 ( or Ctrl+F5 ) in the browser , the code is not recompiled automatically and the page does not change . What am I doing wrong ? Active Version Runtime Architecture -- -- -- -- -- -- - -- -- -- - -- -- -- -- -- -- 1.0.0-alpha3 svr50 x86 1.0.0-alpha3 svrc50 x86 1.0.0-alpha4 CLR x86 * 1.0.0-alpha4 CoreCLR x86","In ASP.NET vNext , why is code not recompiled on the fly ?" "C_sharp : In my code , I used to load a related entity using await FindAsync , hoping that i better conform to c # async guidelines.and it ran slow , was slow in sql server profiler , the query text was fast in SSMS . It took 5 seconds to fetch this line.The alternative : is much faster.By all means , the problem does not seem to be parameter sniffing , as the number of reads in the fast and slow queries are the same.One possibly irrelevant point is that the fetched object contains a string property containing ~1MB text . The application is asp.net mvc , running on the same computer as the sql server , connecting using ( local ) .What is the cause of the observed slowness ? EDIT : After @ jbl 's comment , I did some more experiments : var activeTemplate = await exec.DbContext.FormTemplates.FindAsync ( exec.Form.ActiveTemplateId ) ; var activeTemplate = exec.Form.ActiveTemplate ; var activeTemplate = await exec.DbContext.FormTemplates.FirstOrDefaultAsync ( x = > x.Id == exec.Form.ActiveTemplateId ) ; // slowvar activeTemplate = exec.DbContext.FormTemplates.FirstOrDefault ( x = > x.Id == exec.Form.ActiveTemplateId ) ; // fast","FindAsync is Slow , but lazy loading is fast" "C_sharp : I 've got a suite of Selenium tests that work perfectly in my local environment and using Browserstack Automate , but fail on Azure DevOps . There are no configuration or setting changes when running on Azure Devops.We 've followed all the documentation here : https : //docs.microsoft.com/en-us/azure/devops/pipelines/test/continuous-test-selenium ? view=vstsRandom tests fail , never the same ones . The tests always fail because of timeouts . I wait for the pages to load for 5 minutes so it 's not a case of the timeouts being too low . There are no firewalls in place , the application is public.Authentication always succeeds so the tests are able to load the application.Not sure what to try next.Below is a copy of the Azure DevOps log . 4 tests passed but all the other 's failed . Usually , only 4-5 tests fail.This tests works perfectly using BrowserStack Automate ( remote selenium ) and locally . 2018-11-17T05:40:28.6300135Z Failed StripeAdmin_WhenOnTab_DefaultSortIsByIdDescending2018-11-17T05:40:28.6300461Z Error Message:2018-11-17T05:40:28.6304198Z Test method CS.Portal.E2e.Tests.Admin.StripeAdmin.StripeAdminTests.StripeAdmin_WhenOnTab_DefaultSortIsByIdDescending threw exception : 2018-11-17T05:40:28.6305677Z OpenQA.Selenium.WebDriverTimeoutException : Timed out after 300 seconds2018-11-17T05:40:28.6307041Z Stack Trace:2018-11-17T05:40:28.6307166Z at OpenQA.Selenium.Support.UI.DefaultWait ` 1.ThrowTimeoutException ( String exceptionMessage , Exception lastException ) 2018-11-17T05:40:28.6307999Z at OpenQA.Selenium.Support.UI.DefaultWait ` 1.Until [ TResult ] ( Func ` 2 condition ) 2018-11-17T05:40:28.6308188Z at CS.Portal.E2e.Tests.Utility.WebDriverUtilities.WaitForElement ( IWebDriver driver , By by , Boolean mustBeDisplayed ) in D : \a\1\s\CS.Portal.E2e.Tests\Utility\WebDriverUtilities.cs : line 262018-11-17T05:40:28.6319651Z at CS.Portal.E2e.Tests.Admin.StripeAdmin.StripeAdminTests.StripeAdmin_WhenOnTab_DefaultSortIsByIdDescending ( ) in D : \a\1\s\CS.Portal.E2e.Tests\Admin\StripeAdmin\StripeAdminTests.cs : line 512018-11-17T05:40:28.6319982Z 2018-11-17T05:40:34.4671568Z Results File : D : \a\1\s\TestResults\VssAdministrator_factoryvm-az416_2018-11-17_03_08_24.trx2018-11-17T05:40:34.4692222Z 2018-11-17T05:40:34.4695222Z Attachments:2018-11-17T05:40:34.4697610Z D : \a\1\s\TestResults\672f4d28-5082-42e9-a7e7-f5645aadcfd8\VssAdministrator_factoryvm-az416 2018-11-17 03_02_43.coverage2018-11-17T05:40:34.4697943Z 2018-11-17T05:40:34.4698278Z Total tests : 34 . Passed : 4 . Failed : 30 . Skipped : 0 .",Random Selenium E2e Tests Fail because of timeouts on Azure DevOps but work locally and with remote Selenium ( BrowserStack Automate ) "C_sharp : I am using WCF Async calls in my project and i am using Client side asynchronous methods . I have a scenario like below -So as shown in the above code snippet it does not throw the exception from business layer to web layer as it will be suppressed here in business layer itself.I checked in some of the blogs and sites they are suggesting to go for async and await approach , as i have .NET 4.0 framework and i am seeing `` Generate task-based Operations '' option disabled . So if there are any options using `` IAsyncResult '' ( Begin & End in client side ) please let me know . If there are any other approaches also welcome . Kindly someone help me.Thanks . //Code in Business Layer and this method is called from Web layer private void GetGeneralNews ( ) { client.BeginGetGeneralNewsFeed ( GeneralNewsCallback , null ) ; } //Call Back Method private static void GeneralNewsCallback ( IAsyncResult asyncResult ) { string response = string.Empty ; try { response = client.EndGetGeneralNewsFeed ( asyncResult ) ; } catch ( Exception ex ) { throw ex ; // Here is the problem . It does not throw the exception to the web layer instead it will suppress the error . } }",How to throw an exception from callback in WCF Async using IAsyncResult "C_sharp : Currently code contracts do not allow preconditions on members in derived classes where the member already has a precondition set in the base class ( I actually currently get a warning and not an error ) . I do not understand the logic behind this . I understand that it has to do with Liskov 's substitution rule stating that a derived class should always be able to be used in places where the parent is expected . Of course `` used '' means work as expected . This seems okay to me for interfaces as the different types implementing an interface do n't add state and hence can oblige the contract exactly . However , when you inherit from a base class , you are doing so to add state and special functionality and more often than not the overriding method would have extra requirements . Why ca n't preconditions be ANDed together just like post conditions and object invariants ? Take a look below : You may argue that this class hierarchy breaks Liskov 's rule because the wireless speaker may not be able to beep when passed to methods that expect a Speaker . But is n't that why we use code contracts ? to make sure that the requirements are met ? class Speaker { public bool IsPlugged { get ; set ; } protected virtual void Beep ( ) { Contract.Requires ( IsPlugged ) ; Console.WriteLine ( `` Beep '' ) ; } } class WirelessSpeaker : Speaker { public bool TransmitterIsOn { get ; set ; } protected override void Beep ( ) { Contract.Requires ( TransmitterIsOn ) ; base.Beep ( ) ; } }",Code Contracts and Inheritance ( Precondition on overridden method ) "C_sharp : I 'm trying to Inject a dependency into a controller which inherits from Umbraco 's RenderMvcController and getting the error No registration for type RenderMvcController could be found and an implicit registration could not be made . For the container to be able to create RenderMvcController it should have only one public constructor : it has 3 . See https : //simpleinjector.org/one-constructor for more information.Below is my code to wire up the DIThis is an example of a class receiving the dependency , it inherits from a base class I wroteThe base class extends RenderMvcController which is an Umbraco ControllerAs you can see the base Umbraco controller does in fact have 3 different constructorsI 'm not sure how to get SimpleInjector to place nicely with this controller inherited from Umbraco.Thanks in advance ! var container = new Container ( ) ; container.Options.DefaultScopedLifestyle = new WebRequestLifestyle ( ) ; InitializeContainer ( container ) ; container.RegisterMvcControllers ( Assembly.GetExecutingAssembly ( ) ) ; container.Verify ( ) ; DependencyResolver.SetResolver ( new SimpleInjectorDependencyResolver ( container ) ) ; private static void InitializeContainer ( Container container ) { container.Register < ICacheProvider , CacheProvider > ( Lifestyle.Transient ) ; container.Register < ICacheService , CacheService > ( Lifestyle.Transient ) ; } public class NewsroomController : BaseRenderMvcController { public NewsroomController ( ICacheService cacheService ) : base ( cacheService ) { } public class BaseRenderMvcController : RenderMvcController { public ICacheService CacheService { get ; set ; } public BaseRenderMvcController ( ICacheService cacheService ) { CacheService = cacheService ; } } public class RenderMvcController : UmbracoController , IRenderMvcController , IRenderController , IController { public RenderMvcController ( ) ; public RenderMvcController ( UmbracoContext umbracoContext ) ; public RenderMvcController ( UmbracoContext umbracoContext , UmbracoHelper umbracoHelper ) ;",Using Simple Injector with Umbraco Controller "C_sharp : The following code is in Haskell . How would I write similar function in C # ? Just to clarify ... above code is a function , that takes as input a list containing radius of circles . The expression calculates area of each of the circle in the input list.I know that in C # , I can achieve same result , by looping thru a list and calculate area of each circle in the list and return a list containing area of circles . My question is ... Can the above code be written in similar fashion in C # , perhaps using lambda expressions or LINQ ? squareArea xs = [ pi * r^2 | r < - xs ]",Learning Haskell : list comprehensions in C # C_sharp : Testing code that uses WeakReference failed for me using Mono 2.11.3 ( SGen ) as well as the stable 2.10.8 version . In a simple code like thisthe second assert will fail . Adding GC.WaitForPendingFinalizers does n't help . Is this a bug in Mono or in my head ? Thanks object obj = new object ( ) ; WeakReference wr = new WeakReference ( obj ) ; Assert.IsTrue ( wr.IsAlive ) ; obj = null ; GC.Collect ( ) ; Assert.IsFalse ( wr.IsAlive ) ;,strange WeakReference behavior on Mono "C_sharp : I have the following code in my code behind : I would like to follow the MVVM pattern and have this code moved to my ViewModel which at the moment has only few properties . I have read a lot of answer here and outside of StackOverflow on the topic , I 've downloaded some github projects to check out how experienced programmers handle specific situations , but none of that seem to clear out the confusion for me . I 'd like to see how can my case be refactored to follow the MVVM pattern.Those are the extra extension methods and also the ViewModel itself : I have tried to make the code copy/paste ready as requested in the comments , all of the Controls in the View 's code behind are created in the XAML , if you want to fully replicate it . public partial class MainWindow { private Track _movieSkipSliderTrack ; private Slider sMovieSkipSlider = null ; private Label lbTimeTooltip = null ; private MediaElement Player = null ; public VideoPlayerViewModel ViewModel { get { return DataContext as VideoPlayerViewModel ; } } public MainWindow ( ) { InitializeComponent ( ) ; } private void SMovieSkipSlider_OnLoaded ( object sender , RoutedEventArgs e ) { _movieSkipSliderTrack = ( Track ) sMovieSkipSlider.Template.FindName ( `` PART_Track '' , sMovieSkipSlider ) ; _movieSkipSliderTrack.Thumb.DragDelta += Thumb_DragDelta ; _movieSkipSliderTrack.Thumb.MouseEnter += Thumb_MouseEnter ; } private void Thumb_MouseEnter ( object sender , MouseEventArgs e ) { if ( e.LeftButton == MouseButtonState.Pressed & & e.MouseDevice.Captured == null ) { var args = new MouseButtonEventArgs ( e.MouseDevice , e.Timestamp , MouseButton.Left ) { RoutedEvent = MouseLeftButtonDownEvent } ; SetPlayerPositionToCursor ( ) ; _movieSkipSliderTrack.Thumb.RaiseEvent ( args ) ; } } private void Thumb_DragDelta ( object sender , DragDeltaEventArgs e ) { SetPlayerPositionToCursor ( ) ; } private void SMovieSkipSlider_OnMouseEnter ( object sender , MouseEventArgs e ) { lbTimeTooltip.Visibility = Visibility.Visible ; lbTimeTooltip.SetLeftMargin ( Mouse.GetPosition ( sMovieSkipSlider ) .X ) ; } private void SMovieSkipSlider_OnPreviewMouseMove ( object sender , MouseEventArgs e ) { double simulatedPosition = SimulateTrackPosition ( e.GetPosition ( sMovieSkipSlider ) , _movieSkipSliderTrack ) ; lbTimeTooltip.AddToLeftMargin ( Mouse.GetPosition ( sMovieSkipSlider ) .X - lbTimeTooltip.Margin.Left + 35 ) ; lbTimeTooltip.Content = TimeSpan.FromSeconds ( simulatedPosition ) ; } private void SMovieSkipSlider_OnMouseLeave ( object sender , MouseEventArgs e ) { lbTimeTooltip.Visibility = Visibility.Hidden ; } private void SetPlayerPositionToCursor ( ) { Point mousePosition = new Point ( Mouse.GetPosition ( sMovieSkipSlider ) .X , 0 ) ; double simulatedValue = SimulateTrackPosition ( mousePosition , _movieSkipSliderTrack ) ; SetNewPlayerPosition ( TimeSpan.FromSeconds ( simulatedValue ) ) ; } private double CalculateTrackDensity ( Track track ) { double effectivePoints = Math.Max ( 0 , track.Maximum - track.Minimum ) ; double effectiveLength = track.Orientation == Orientation.Horizontal ? track.ActualWidth - track.Thumb.DesiredSize.Width : track.ActualHeight - track.Thumb.DesiredSize.Height ; return effectivePoints / effectiveLength ; } private double SimulateTrackPosition ( Point point , Track track ) { var simulatedPosition = ( point.X - track.Thumb.DesiredSize.Width / 2 ) * CalculateTrackDensity ( track ) ; return Math.Min ( Math.Max ( simulatedPosition , 0 ) , sMovieSkipSlider.Maximum ) ; } private void SetNewPlayerPosition ( TimeSpan newPosition ) { Player.Position = newPosition ; ViewModel.AlignTimersWithSource ( Player.Position , Player ) ; } } static class Extensions { public static void SetLeftMargin ( this FrameworkElement target , double value ) { target.Margin = new Thickness ( value , target.Margin.Top , target.Margin.Right , target.Margin.Bottom ) ; } public static void AddToLeftMargin ( this FrameworkElement target , double valueToAdd ) { SetLeftMargin ( target , target.Margin.Left + valueToAdd ) ; } } public class VideoPlayerViewModel : ViewModelBase { private TimeSpan _movieElapsedTime = default ( TimeSpan ) ; public TimeSpan MovieElapsedTime { get { return _movieElapsedTime ; } set { if ( value ! = _movieElapsedTime ) { _movieElapsedTime = value ; OnPropertyChanged ( ) ; } } } private TimeSpan _movieLeftTime = default ( TimeSpan ) ; public TimeSpan MovieLeftTime { get { return _movieLeftTime ; } set { if ( value ! = _movieLeftTime ) { _movieLeftTime = value ; OnPropertyChanged ( ) ; } } } public void AlignTimersWithSource ( TimeSpan currentPosition , MediaElement media ) { MovieLeftTime = media.NaturalDuration.TimeSpan - currentPosition ; MovieElapsedTime = currentPosition ; } } public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged ; [ NotifyPropertyChangedInvocator ] protected virtual void OnPropertyChanged ( [ System.Runtime.CompilerServices.CallerMemberName ] string propName = null ) { PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( propName ) ) ; } }",Moving methods from view to viewmodel - WPF MVVM "C_sharp : I have an MVC app where I override my base controller 's OnActionExecuting ( ) method to set my thread culture : As I have started to program asynchronously more , I 'm curious about how culture is persisted if we return the thread whose culture we 've modified to the thread pool , and a new thread is dispatched when the async task completes ? Any gotchas I should be aware of ? protected override void OnActionExecuting ( ActionExecutingContext filterContext ) { var langCode = GetLangCode ( ) ; Thread.CurrentThread.CurrentUICulture = new CultureInfo ( langCode ) ; Thread.CurrentThread.CurrentCulture = new CultureInfo ( langCode ) ; }",Asynchrony and thread culture "C_sharp : Well , I have the following problem and I hope that you can help me : I would like to create a WPF application with a background worker for updating richtextboxes and other UI elements . This background worker should process some data , e.g . handle the content of a folder , do some parsing and much more . Since I would like to move as much code as possible outside the Main class , I created a class called MyProcess.cs as you can see below ( in fact , this class does not make much sense so far , it will be filled with much more processing elements if this problem has been solved ) . The general functionality should be : MainWindow : An array of strings will be created ( named this.folderContent ) MainWindow : A background worker is started taking this array as argumentMainWindow : The DoWork ( ) method will be called ( I know , this one now runs in a new thread ) MyProcess : Generates a ( so far unformatted ) Paragraph based on the given string arrayMainWindow : If the background worker is finished , the RunWorkerCompleted ( ) method is called ( running in UI thread ) which should update a WPF RichTextBox via the method 's return argumentThis last step causes an InvalidOperationsException with the note , that `` The calling thread can not access this object because a different thread owns it . '' I read a bit about the background worker class and its functionality . So I think that it has something to do with the this.formatedFilenames.Inlines.Add ( new Run ( ... ) ) call in the Execute ( ) method of MyProcess . If I replace the Paragraph attribute by a list of strings or something similar ( without additional new ( ) calls ) I can access this member without any problems by a get method . All examples related to the background worker I have found return only basic types or simple classes.MainWindow.xaml.csEdit : Since this has been asked : the RunWorkerAsync is called e.g . on a button click event or after a folder has been selected via a dialog , so within the UI thread.MyProcess.cs public MainWindow ( ) { InitializeComponent ( ) ; this.process = new MyProcess ( ) ; this.worker = new BackgroundWorker ( ) ; this.worker.DoWork += worker_DoWork ; this.worker.RunWorkerCompleted += worker_RunWorkerCompleted ; } private void worker_DoWork ( object sender , DoWorkEventArgs e ) { this.process.Execute ( ( string [ ] ) e.Argument ) ; e.Result = this.process.Paragraph ( ) ; } private void worker_RunWorkerCompleted ( object sender , RunWorkerCompletedEventArgs e ) { this.rtbFolderContent.Document.Blocks.Clear ( ) ; // the next line causes InvalidOperationsException : // The calling thread can not access this object because a different thread owns it . this.rtbFolderContent.Document.Blocks.Add ( ( Paragraph ) e.Result ) ; } ... // folderContent of type string [ ] this.worker.RunWorkerAsync ( this.folderContent ) ; ... class MyProcess { Paragraph formatedFilenames ; public MyProcess ( ) { this.formatedFilenames = new Paragraph ( ) ; } public void Execute ( string [ ] folderContent ) { this.formatedFilenames = new Paragraph ( ) ; if ( folderContent.Length > 0 ) { for ( int f = 0 ; f < folderContent.Length ; ++f ) { this.formatedFilenames.Inlines.Add ( new Run ( folderContent [ f ] + Environment.NewLine ) ) ; // some dummy waiting time Thread.Sleep ( 500 ) ; } } } public Paragraph Paragraph ( ) { return this.formatedFilenames ; } }",Backgroundworker processing in own class "C_sharp : Sometimes I have this situation when it 's quite easier to wrap whole piece of code in try-catch block rather than do a lot of checking which violently reduce code readability.For example , thisI really prefer to do like this But after code review I often hear from my mentor that I should avoid try-catch blocks when it 's possible to make simple checking . Is it really so critical and each try-catch block eating a lot of system resources ( relatively ) ? Is this resources used only when error raised or each case ( successfull or not ) is equally `` heavy '' ? var result = string.Empty ; if ( rootObject ! = null ) { if ( rootObject.FirstProperty ! = null ) { if ( rootObject.FirstProperty.SecondProperty ! = null ) { if ( ! string.IsNullOrEmpty ( rootObject.FirstProperty.SecondProperty.InterestingString ) ) { result = rootObject.FirstProperty.SecondProperty.InterestingString ; } } } } var result = string.Empty ; try { result = rootObject.FirstProperty.SecondProperty.InterestingString ; } catch { }",How heavy .NET exception handling is ? "C_sharp : Hei , In my application i 'm using DataGrid to show some data . To get everything working with threading i 'm using AsyncObservableCollection as DataContext of DataGrid . When my application starts it looks for files in some folders and updates AsyncObservableCollection . Finding files is done on a separate thread : Where all the loading logic is in InitAllOrdersCollection ( ) method.Now here 's where things go bad , when i start the application for some reason i get 2 rows with same data in DataGrid even if there is one item in collection and only one file in folders . If i add a delay ( Thread.Sleep ( ) 50ms minimum ) before loading files then DataGrid show everything correctly ( no extra row ) . Delay has to be added to the Thread what is loading the files ( The one created with Task.Factory.StartNew ( ) ) .Have anybody encountered something similar or is there something else i should try ? Thanks in advance ! EDIT : Adding some code as requested : FilesToOrders ( ) method is the one what adds the new orders to the AsyncObservableCollection.Hope this helps . Task.Factory.StartNew ( ( ) = > _cardType.InitAllOrdersCollection ( ) ) .ContinueWith ( ( t ) = > ThrowEvent ( ) , TaskContinuationOptions.None ) ; public AsyncObservableCollection < IGridItem > OrdersCollection = new AsyncObservableCollection < IGridItem > ( ) ; public void InitAllOrdersCollection ( ) { // Thread.Sleep ( 50 ) ; < -- this sleep here fixes the problem ! foreach ( var convention in FileNameConventions ) { var namePatterns = convention.NameConvention.Split ( ' , ' ) ; foreach ( var pattern in namePatterns ) { var validFiles = CardTypeExtensions.GetFiles ( this.InputFolder , pattern , convention ) ; if ( validFiles.Any ( ) ) { this.FilesToOrders ( validFiles , convention ) ; } } } } public static List < string > GetFiles ( string inputFolder , string pattern , FileNameConvention convention ) { var files = Directory.GetFiles ( inputFolder , pattern ) ; return files.Where ( file = > IsCorrect ( file , convention ) ) .AsParallel ( ) .ToList ( ) ; } // Adds new order to OrdersCollection if its not there already ! private void FilesToOrders ( List < string > dirFiles , FileNameConvention convention ) { foreach ( var dirFile in dirFiles.AsParallel ( ) ) { var order = new Order ( dirFile , this , convention ) ; if ( ! this.OrdersCollection.ContainsOrder ( order ) ) { this.OrdersCollection.Add ( order ) ; } } } public static bool ContainsOrder ( this ObservableCollection < IGridItem > collection , Order order ) { return collection.Cast < Order > ( ) .Any ( c= > c.Filepath == order.Filepath ) ; }",WPF DataGrid is adding extra `` ghost '' row "C_sharp : I have text box with text wrapping enabled in my Windows Phone 7 app , how do I get the line count at the character selected by the user ? For example , if a text box it looked like this : , with `` | '' representing the selected character , the line count would be 3 . I need to do this at any point in time , most specifically when the text is changed . I could count the number of newlines in a text box without text wrapping , but this is clearly a different scenario . testtextbo|xishere",How to get the selected line in a Text Box ? "C_sharp : I have a WPF DataGrid represented in XAML . I 'm using a RowStyle for my grid 's TableView but also need to set some properties for specific cells . I need those cells to have the properties of the row style and apply the extra properties from the cell style on top of those.What I would need is something like this , although this does n't work as it 's saying : Target type 'CellContentPresenter ' is not convertible to base type 'GridRowContent ' I 've also tried not specifying the BasedOn property for MyCellStyle but that does n't work either.I use the MyCellStyle like this : and MyGridRowStyle like this on the TableView : How can I make the cell style only change the properties specified in MyCellStyle and use the values specified in MyGridRowStyle for the other properties ? < Style x : Key= '' MyGridRowStyle '' BasedOn= '' { StaticResource { themes : GridRowThemeKey ResourceKey=RowStyle } } '' TargetType= '' { x : Type dxg : GridRowContent } '' > < Setter Property= '' Height '' Value= '' 25 '' / > < Style.Triggers > ... < /Style.Triggers > < /Style > < Style x : Key= '' MyCellStyle '' BasedOn= '' { StaticResource MyGridRowStyle } '' TargetType= '' { x : Type dxg : CellContentPresenter } '' > < Style.Triggers > ... < /Style.Triggers > < /Style > < dxg : GridColumn Header= '' My Header '' FieldName= '' MyFieldName '' Width= '' 100 '' CellStyle= '' { StaticResource MyCellStyle } '' / > RowStyle= '' { StaticResource MyGridRowStyle } ''",CellStyle based on RowStyle in WPF "C_sharp : I have developed a web dashboard which has a structure of controls embedded inside of controls . In many scenarios I have the ID of a control and need to be working on the actual control object . As such , I use a utility method , a recursive FindControl implementation , which searches Page ( or any other provided object , but I always use Page ) , for the ID of the control.This function has the ability to become quite slow . I realize just how slow once I put log4net logging into it . I am now trying to move away from it where I can , but I am not sure what other options I have , if any.For instance , the user drag-and-drops a control onto my web page . The event handler looks like this : There is no guarantee that this control will be the direct child of Page , and I do not ( as far as I know ! ) , have the ability to determine where in my controls this ID could be except by searching from Page downward . The only thing I can think up is keeping a lookup table of every object on Page , but that seems like the wrong idea.Has anyone else experienced this issue ? /// < summary > /// Page.FindControl is not recursive by default./// < /summary > /// < param name= '' root '' > Page < /param > /// < param name= '' id '' > ID of control looking for . < /param > /// < returns > The control if found , else null . < /returns > public static Control FindControlRecursive ( Control root , string id ) { if ( int.Equals ( root.ID , id ) ) { return root ; } foreach ( Control control in root.Controls ) { Control foundControl = FindControlRecursive ( control , id ) ; if ( ! object.Equals ( foundControl , null ) ) { return foundControl ; } } return null ; } protected void RadListBox_Dropped ( object sender , RadListBoxDroppedEventArgs e ) { //e.HtmlElementID is the UniqueID of the control I want to work upon . RadDockZone activeControlDockZone = Utilities.FindControlRecursive ( Page , e.HtmlElementID ) as RadDockZone ; }",Struggling to move away from recursive Page.FindControl "C_sharp : There is a specific WSDL for which the ServiceContractGenerator keeps on generating message contracts ( request/response wrapper objects ) , which I do not want ( I want straight parameters ) . Other WSDL 's work fine.When I use Visual Studio to create a WCF client ( `` Add Service Reference '' ) and I click on `` Advanced ... '' , the checkbox which says `` Always generate message contracts '' does properly control whether the message contract objects are generated.However , when I use the ServiceContractGenerator class to generate a WCF client programmatically , it keeps generating message contracts . I tried setting the ServiceContractGenerator 's Options to ServiceContractGenerationOptions.None , but the result is the same.Here is the code that I use : What should I do so that ServiceContractGenerator generates the web methods with straight parameters ? MetadataSet metadataSet = new MetadataSet ( ) ; metadataSet.MetadataSections.Add ( MetadataSection.CreateFromServiceDescription ( System.Web.Services.Description.ServiceDescription.Read ( wsdlStream ) ) ) ; WsdlImporter importer = new WsdlImporter ( metadataSet ) ; if ( serviceDescription ! = null ) importer.WsdlDocuments.Add ( serviceDescription ) ; foreach ( XmlSchema nextSchema in schemas ) importer.XmlSchemas.Add ( nextSchema ) ; ServiceContractGenerator generator = new ServiceContractGenerator ( ) ; generator.Options = ServiceContractGenerationOptions.None ; foreach ( ContractDescription nextContract in importer.ImportAllContracts ( ) ) generator.GenerateServiceContractType ( nextContract ) ; if ( generator.Errors.Count ! = 0 ) throw new Exception ( `` Service assembly compile error : \r\n - `` + string.Join ( `` \r\n - `` , generator.Errors.Select ( e = > e.Message ) ) ) ; // Use generator.TargetCompileUnit to generate the code ...",Prevent ServiceContractGenerator from generating message contracts ( request/response wrappers ) "C_sharp : I am using Newtonsoft JSON to deserialize an object that contains interfaces . Newtonsoft was having trouble `` figuring out '' how to map the interfaces to their concrete types on deserialization , so I was following the directions in this answer to fix the issue.I am doing the following to deserialize : I 'm using the DeviceCalibrationConverter object to try to map my interface to its concrete type : I 'm currently getting an `` ArgumentOutOfRangeException . '' Full exception details are below : This occurs , by the way , on the line where I try to call Deserialize.Edit : The entire JSON is pretty lengthy but it turns out that the offending line is as follows : In particular , in `` Version '' deserializes to : This deserializes to the System.Version class and this is invalid , thus producing the exception I listed above.CDIDriver , by the way , creates the Version object as follows : This is perfectly valid , and the document does , in fact , say that using this constructor as described will set the build and revision to -1 ( as shown in the JSON ) . My question , then , is if this is a perfectly valid , document state of the object , why does it produce this exception when I try to deserialize it ? I am aware that trying to do something like new Version ( 1 , 0 , -1 , -1 ) will produce an exception and that this is the documented behavior . ( This seems like very odd behavior given that that would result in a valid object state , but that 's just my opinion ) . Is there some way around having to do : just for the sake of making the deserialization work ? var converter = new JsonSerializer ( ) ; converter.Converters.Add ( new DeviceCalibrationConverter ( ) ) ; // Obviously parameter.value and typeObj being the JSON and Type respectively// I can see stepping through this that these are , in fact , the correct valuesobject deserialized = converter.Deserialize ( new StringReader ( parameter.Value ) , typeObj ) ; public class DeviceCalibrationConverter : JsonConverter { public override bool CanConvert ( Type objectType ) { // I am trying to map the IDeviceCalibration interface to its concrete type ( DeviceCalibration ) return objectType.Equals ( typeof ( IDeviceCalibration ) ) ; } public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer ) { return serializer.Deserialize ( reader , typeof ( DeviceCalibration ) ) ; } public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { serializer.Serialize ( writer , value ) ; } } System.ArgumentOutOfRangeException was unhandled HResult=-2146233086 Message=Version 's parameters must be greater than or equal to zero.Parameter name : build Source=mscorlib ParamName=build StackTrace : at System.Version..ctor ( Int32 major , Int32 minor , Int32 build , Int32 revision ) at Void .ctor ( Int32 , Int32 , Int32 , Int32 ) ( Object [ ] ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObjectUsingCreatorWithParameters ( JsonReader reader , JsonObjectContract contract , JsonProperty containerProperty , ObjectConstructor ` 1 creator , String id ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject ( JsonReader reader , JsonObjectContract objectContract , JsonProperty containerMember , JsonProperty containerProperty , String id , Boolean & createdFromNonDefaultCreator ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue ( JsonProperty property , JsonConverter propertyConverter , JsonContainerContract containerContract , JsonProperty containerProperty , JsonReader reader , Object target ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject ( Object newObject , JsonReader reader , JsonObjectContract contract , JsonProperty member , String id ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue ( JsonProperty property , JsonConverter propertyConverter , JsonContainerContract containerContract , JsonProperty containerProperty , JsonReader reader , Object target ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject ( Object newObject , JsonReader reader , JsonObjectContract contract , JsonProperty member , String id ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize ( JsonReader reader , Type objectType , Boolean checkAdditionalContent ) at Newtonsoft.Json.JsonSerializer.DeserializeInternal ( JsonReader reader , Type objectType ) at Newtonsoft.Json.JsonSerializer.Deserialize ( TextReader reader , Type objectType ) at FunctionalTesting.ExecuteXMLScript.Execute ( ) in [ folder ] \ExecuteXMLScript.cs : line 141 at FunctionalTesting.TestRunner.RunTests ( ) in [ folder ] \TestRunner.cs : line 102 at FunctionalTesting.Program.Main ( String [ ] args ) in [ folder ] \Program.cs : line 43 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) InnerException : { `` State '' : '' needs-translation '' , '' OriginalString '' : '' LP '' , '' StringID '' : [ id ] , '' StringValue '' : '' LP '' } } ] , '' MarketingFeatures '' : null , `` CDIDriver '' { `` Name '' : '' [ Product Name ] '' , `` Version '' : { `` Major '' :1 , '' Minor '' :0 , '' Build '' : -1 , '' Revision '' : -1 , '' MajorRevision '' : -1 , '' MinorRevision '' : -1 } } { `` Major '' :1 , '' Minor '' :0 , '' Build '' : -1 , '' Revision '' : -1 , '' MajorRevision '' : -1 , '' MinorRevision '' : -1 } Version = new Version ( ( int ) major , ( int ) minor ) ; new Version ( 1 , 0 , 0 , 0 )",System.ArgumentOutOfRangeException while deserializing using Newtonsoft.Json "C_sharp : When I tested the above code with CLRProfiler , it told me that the code allocates roughly 40 MB . Around 20 MB is allocated to String , 9 MB to Char [ ] , 5 MB to StringBuilder and 3 MB to Int32.This one allocates around 5 MB . 4 MB is allocated to Char [ ] . The only thing I get is that array a should require 1 MB ( 250,000 * 4 ) .Why is there such a massive difference ? Why are all those objects required for the first code and how do I reduce the memory allocation ? public static void Main ( ) { int size = 250000 ; var a = new int [ size ] ; for ( int i = 0 ; i < size ; i++ ) Console.WriteLine ( `` { 0 } '' , a [ i ] ) ; } public static void Main ( ) { int size = 250000 ; var a = new int [ size ] ; for ( int i = 0 ; i < size ; i++ ) Console.WriteLine ( `` 0 '' ) ; }",High memory usage with Console.WriteLine ( ) "C_sharp : I have a Windows Phone 8.1 XAML app with a ListView nad WrapGrid as its ItemsPanel to display items in two columnsThe cache mode of the page is set to NavigationCacheMode.Required . I scoll in the list , tap an item and navigate to another screen . When I navigate back to the page with the ListView , the ListView remebers the scoll position ( NavigationCacheMode.Required ) but gets `` broken '' , when I tap on items , they just jump strangely . Here is a complete simple solution to reproduce the problem : https : //dl.dropboxusercontent.com/u/73642/listview.zip.Here is a video showing the problem : https : //dl.dropboxusercontent.com/u/73642/listview.wmvAnyone else experienced this ? Is there a way around this issue ? < ListView x : Name= '' ListV '' ItemClick= '' ListV_ItemClick '' IsItemClickEnabled= '' True '' > < ListView.ItemsPanel > < ItemsPanelTemplate > < WrapGrid Orientation= '' Horizontal '' ItemWidth= '' 160 '' ItemHeight= '' 280 '' MaximumRowsOrColumns= '' 2 '' / > < /ItemsPanelTemplate > < /ListView.ItemsPanel > < ListView.ItemTemplate > < DataTemplate > < Grid Background= '' Red '' Margin= '' 12 '' Width= '' 100 '' Height= '' 100 '' > < /Grid > < /DataTemplate > < /ListView.ItemTemplate > < /ListView >",Strange behavior of ListView with WrapGrid in Windows Phone 8.1 XAML "C_sharp : I have a method which synchronizes two folders , that looks like this : What would be the best way to test if the files were synchronized properly , or in general , test methods that manipulate the file system ? Is there a way to set up virtual folders ? void Synchronize ( string folderAPath , string folderBPath ) { //Code to synchronize the folders }",How to test file system operations "C_sharp : Just recently I found out you can do this in C # : instead of i.e . : This might be a bad example that can be solved in a lot of other manners . Are there any patterns where the 'scope without statement ' feature is a good practice ? { // google string url = `` # '' ; if ( value > 5 ) url = `` http : //google.com '' ; menu.Add ( new MenuItem ( url ) ) ; } { // cheese string url = `` # '' ; // url has to be redefined again , // so it ca n't accidently leak into the new menu item if ( value > 45 ) url = `` http : //cheese.com '' ; menu.Add ( new MenuItem ( url ) ) ; } string url = `` # '' ; // google if ( value > 5 ) url = `` http : //google.com '' ; menu.Add ( new MenuItem ( url ) ) ; // cheese url = `` # '' ; // now I need to remember to reset the url if ( value > 45 ) url = `` http : //cheese.com '' ; menu.Add ( new MenuItem ( url ) ) ;",When do you use scope without a statement in C # ? "C_sharp : I created a simple SFX application which works on Compressing / Packing files . When someone click the output file he will be prompted for a password , if password entered correctly the file decrypt it self following a specific routines . A customer said that my file was a virus , so i scanned the file online on VirusTotal.com and i seen that the file was detected by avira in the SCAN RESULT . I reexamined the source code Line by Line , and i found that the following Lines of code are detected . What i want to do now is to find a solution which let me encrypt the class above , so instead of writing it as it is in my C # propgram i will write the encrypted string . and use a function which decrypt and execute the encrypted string at Run-time . So instead of writing the above class i will write the following Then simply i call a function like : Is this possible , and how can I achieve this in the case it is . public class SimplerAES { private static byte [ ] key = { 88 , 54 , 54 , 147 , 99 , 201 , 41 , 80 , 58 , 100 , 5 , 64 , 213 , 99 , 14 , 15 , 154 , 35 , 110 , 36 , 124 , 25 , 115 , 23 , 56 , 44 , 65 , 7 , 45 , 254 , 1 , 54 } ; private static byte [ ] vector = { 33 , 8 , 121 , 196 , 223 , 45 , 63 , 100 , 1 , 32 , 18 , 87 , 1 , 158 , 119 , 111 } ; private ICryptoTransform encryptor , decryptor ; private UTF8Encoding encoder ; public SimplerAES ( ) { RijndaelManaged rm = new RijndaelManaged ( ) ; encryptor = rm.CreateEncryptor ( key , vector ) ; decryptor = rm.CreateDecryptor ( key , vector ) ; encoder = new UTF8Encoding ( ) ; } public string Encrypt ( string unencrypted ) { return Convert.ToBase64String ( Encrypt ( encoder.GetBytes ( unencrypted ) ) ) ; } public string Decrypt ( string encrypted ) { return encoder.GetString ( Decrypt ( Convert.FromBase64String ( encrypted ) ) ) ; } public byte [ ] Encrypt ( byte [ ] buffer ) { MemoryStream encryptStream = new MemoryStream ( ) ; using ( CryptoStream cs = new CryptoStream ( encryptStream , encryptor , CryptoStreamMode.Write ) ) { cs.Write ( buffer , 0 , buffer.Length ) ; } return encryptStream.ToArray ( ) ; } public byte [ ] Decrypt ( byte [ ] buffer ) { MemoryStream decryptStream = new MemoryStream ( ) ; using ( CryptoStream cs = new CryptoStream ( decryptStream , decryptor , CryptoStreamMode.Write ) ) { cs.Write ( buffer , 0 , buffer.Length ) ; } return decryptStream.ToArray ( ) ; } } String MYCODE = `` 687b1ddf28e8d9d3141c3b5d8d4d1863964a614c74317e88a18a10c1c4723bed18d53c99eeb5f05b6646b10b63ae14166c81b06dd487103d133a06896ed9a125e8e2a9c54a2fec82ddd8abe4ef9bbe1b99664a8bc761db2ce70cd1dd9d6898e72490ccea73d7dab056e86cec23f39328b9eb3ef3ef7942db4122178b8a319971c6de2a5cb7e23dd5ba382525a7993122bf068d9d7ac189e701e1b2120b6f5747123e320f892a51df0ff38d7fef5c24d8914a9974d36183c4885582d2ce37023cbde2c23896e608754e81cf9faf70cd64fea5e930340e185fcfe1f457710a2e8b7c977b4c851f8fb4dd49ea53216dc8242ec6ac17e5256ab16170ac49a124a3972477e6bbfefbf1e1c1f84290e023fa2d7813e7761c9e2872c2d57e8d69be34c2cbb41fd75b81604ebf57dece4c9fd6b5bce441350cc4e2ca1bc78105ee554629ff6201745088a177859d168ffffb356fb2bb327de7495db77e07d9fcc9787fc4313a5118037f5828eb2ac7a006126b21b207eb22a369b3182d1f613b43a097d214650c6fd0af057f7836586b4f55342351e93fbb03f726982f4356c801342b6efe7a9fe29ba6770a61d29656725ed21c77a17fe61ffb6d9dea55bbd1ab9e70c1ce44fc82ed710550483ae3b6049aa7d24cc142f5d521bc8beaa36d2839fb82efe59aafa713659c3e902a65c27e8fa9712cd9d232ac65fbf20bef047371317bd60331f8b8b2971cc1ba2b5e854c3d0b072ad786deb40811dcdb335d2937a1ef86a5d0923294ed9eed758670856bbd89471e4940d6dbdae6d8e4cb10235645c2e23be442a4739d0a24a56b666828269704984621ba9761d47512e0804a3a20b0f7c15ff10036dedb4ad8f1149c028de5d726f9e62244fc22b45a5096736d6dd65e9afddd05234982818f7eccd35555805169cf1ef887bf06bc4cee729513c255ff3e41de5397e45212ca921e394bfd059f30cd3404a3a7e989e374239c22aca956e39d576838bed69551040095a4e070fdecd369b7be51ae30ad0a8c4d3c23c7678a7bb661a720e88d396218b0f37bea4f7959df498b7f2e59460b32735685b551f0fe74786a119ce9343ebd4c3f2efea11f02741a067300fe836ad7943577c56b22cf54964b6bf8be4b0a61c353be7fffe90166c5a1c667938878eace2046eb254fc65ef7a3c98c7877651e1cc735bb006d5ba9fdf5f5555345570a43adbe6a49ed714d79990f408f667ac2a624511b0fc1674bdff0cd02b11a2666cb76b39c84d5aeb2b32c3777f7f577495bdef2ac7cf8a119487c8a97a6c1ec8f5b775cd7059f7edd3d8da1764467058991d6a6c5b061fdbbc255103798d5d2e2d75eff80316b65abff2b9d1514f55e2db114e207ba6d41419924e9397404750a7822daa93c5055dbd3448f8d25550cae7daf8fea9d6ab51eff5f11e88dabe81a0030a775480bb694acf95ce4cf48497fd24272853a62e1af55c5ab4e2d058ebd04f053a01b86b7d87e0c1c8bae2ed3f3e5f2096d83569aef940331f29ed27656968880433b6a892b97239acef888afb9b4f4e3dcb4bb67823ce1e80f2068805145daacea016267dadbb78f437aaed32711dcc436f9a4997cc19eb797c10ca3c8c432b4fdf9c886bdc566f233400e202630925eb837c812c9ba95957ca7035056831d93ab16cd5c9095090e64b3f90d6ff709f732237dd41a3cebe371f7328b7bd3cbb6cf695f98c69b45e1999a3595bd12cc23f5f3cfcf13e355b7a3ea5b0bbc5c60142ae85829915f48d4ae0fc896ed8113e6062a7c6e54ac8470d0c8cc5b5e5e91d702a7b19af4a9b647e84db3ad1c5c65f2f450f99cdce1be4b3a3404070de4f45f36eb0acec358452c72c475ee69615614889737b698afab9472ab2cd12a543555dbe31199b8c188232a85bbbff925a6e8bac9e0c98fd8156b34b849dcbbcb9077018c5a1d5ca7b76fa5ba3e5fa5070c47d4a4e1723503500f1b63395d60fcf8eb551fb3aaac2a52763d89584951e6adcec46cde1e0e7dc0c511fc38a9cb92413c4f4eb54a803ff18e759a9aac56760ab97f1a25f7474561964e541fac9ae4c53d1728565bfe8007c2a015d9e7a2877891a829db9a3b70e91507f060362efe6f7d51573feadb7cedfab390a6a53e171e28b4c0582c2dd944d2b227b0d79f7484795bdbe15da65c3a60d859b10cc3b20614c827eff8d78bf5a64d86d5404c14b96bbd46c2ae176064feb5ef80b5147dae06faa34982b5835fe0562ce210c27abce2e15235cd530550f1927dc2b73f732b159391fbe186a670284a81a3e22d182b0587dda31429d296b486683d3b74205ce6a15102334c43c610c44841fad92ab9456340ef55fde6814ba11a0d069dd680b7b2c63aaa5b6a7d1ab119ebbfb2c5322ee950f94f9780652e258650b2991a62f9964a6534a16104de5463f1fb278b82690999c6ff48a3eed75ca7a619ab5ae4c3c2a66b4bc7d450f597aba119cfcb292f1a91032cc0a8f11f9baabd491fff0bcea62c72f8e30c87e58b769c5a5e1f6c7aca403ace859f199fb60381412d75703966c8adcef9a6938bde96d09376692a9bffe6ab4c31d7f71c8d959feadb0e532a3e6dd8f84d9e0f114d81bb3122ba2cbb9f59b636118a0d7a3c5f177329ccb50a049a60d6 '' xor_get_and_execute_original_code ( MYCODE , mykey ) ;",Coding with an encrypted Source Code . Possible or Not ? "C_sharp : This is the scenario which has been working for years . I have a parent asp.net web application at ( say ) www.MySite.co.uk and under it I have multiple child ( client ) sites in virtual directories e.g . www.MySite.co.uk/Client1 etc . All sites ( parent and child virtual directories ) are traditional asp.net web forms applications using .NET 4.5 and all working fine.Yesterday , I updated my parent site to be an asp.net MVC 5 web application ( developed for me by a freelancer ) . I only updated the parent site and it broke all my child sites . As an emergency fix for this I have renamed the web.config file in my parent MVC site , obviously this has broken my parent site , but at least the client ( child ) sites are working again.There is obviously a setting in the root application ( the MVC one ) which the webforms sites are inheriting and they don ’ t like it.In my research I came across this : http : //forums.iis.net/t/1200821.aspx ? Creating+virtual+directory+for+ASP+NET+website+under+MVC+application and so I wonder if the setting in question is to do with my MVC RouteConfig.cs file . My freelancer set it up so that old links to my aspx paths would still work ( i.e . map to my new views ) . I 'm not familiar with the code yet , but here is a snippet : I have done a lot of searching , but so far have been unable to find out the solution . So my question is this : Is it possible to have traditional asp.net site in virtual directory under MVC site ? If so , what settings should I be looking at ? How can I stop the child sites inheriting the wrong settings ? I have a feeling the settings are either in web.config or something to do with RouteConfig.cs above.I would be very grateful if anyone could point me in the right direction , thanks in advance.UpdateHaving also looked at this post Virtual Directory App within a Asp.net MVC app I have tried editing web.config in the root application and wrapping < location inheritInChildApplications= '' false '' > around everything that would allow it . But it did not work , the client sites still did n't work.Update 2I have a response from my freelancer who says it is about routing and URL because MVC expects something to be at /Client1 etc . So we need to write a route which sends such requests ( route plus one word ) to a controller which then needs to see whether this is a page in the MVC ( e.g . /help ) or a client site ( e.g . /Client1 ) and display appropriate page.Personally I do n't know enough about routing to do this myself , but my freelancer is on the case . If he comes up with a solution I will post it . I would still appreciate any other input or alternative solutions.Update 3Now solved ! Please note , it was nothing to do with MVC , that was a red herring . Thanks to Greg Burghardt for pointing me in the right direction with his comment `` Apparently IIS tries matching a virtual directory first , then an MVC controller '' . This is true , there are no routing issues with having ASP.NET Web Forms sites in virtual directories under an MVC parent site . It was to do with web.config Entity Framework inheritance issues . I will post the answer . public class RouteConfig { public static void RegisterRoutes ( RouteCollection routes ) { routes.IgnoreRoute ( `` { resource } .axd/ { *pathInfo } '' ) ; routes.MapRoute ( name : `` HelpRedirect '' , url : `` Help/ { *route } '' , defaults : new { controller = `` Help '' , action = `` ViewRedirect '' } ) ; routes.MapRoute ( name : `` AspxRoute '' , url : `` { controller } / { action } .aspx '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; routes.MapRoute ( name : `` ContactRoute '' , url : `` Contact.aspx '' , defaults : new { controller = `` Contact '' , action = `` Index '' , id = UrlParameter.Optional } ) ; routes.MapRoute ( name : `` Default '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; } }",Can I have traditional ASP.NET Web Applications in Virtual Directories under MVC Site ? "C_sharp : Is there an way to disable WPF 's very annoying exception wrapping when debugging ? An example would be a window that owns a text box , the text box is bound to a property , the getter on that property throws an exception that ca n't be handled by the presentation framework ( throw new StackOverflowException ( ) for example ) . What I 'm should be seeing is Instead what I 'm seeing is ... Because of WPF 's exception wrapping this exception is also sometimes caught and dispatched then is either rethrown or hidden deep within MS.Internals and impossible to return to the actual site of exception . This results in us seeing a gigantic callstack of PresentationFramework.dll , PresentationCore.dll , and WindowsBase.dll but NO user code except for App.Main ( ) .This occurs during binding , events called during creation , and other completely random situations without rhyme or reason ( exception during button click sometimes does this to me ) . Now yes I can look at stack trace inside of the exception but that stack trace is also pretty much meaningless because I can not return to that frame to see what the variables are that at the time of throw . get { throw new StackOverflowException ( ) ; // < Exception happened here } No Source Available Call Stack Location : PresentationFramework.dll ! MS.Internal.Data.PropertyPathWorker.RawValue ( int k ) + 0x64 bytes",Disable WPF exception wrapping for debugging "C_sharp : I have my own implementation of TaskScheduler . The main reason for its existence is that it will set processor core affinity to the thread running my task.When I use it in the following manner : the affinity works fine , the task will run only on the specified core.How can I change Task.Factory or Task.Factory.Scheduler so my scheduler will be the default one whenever is being called ? var myTaskSceduler = new MyTaskScheduler ( 4 ) ; var taskFactory = new TaskFactory ( myTaskSceduler ) ; taskFactory.StartNew ( DoSomething ) ; Task.Factory.StartNew ( )",How to make my custom TaskScheduler the default one C_sharp : I have a template for items control shown below . I need separate instances of colorProvider for each item in the template . Each item in the items control requires a seperate instance of the Color Provider depending on the item it is bound to.How do i create multiple copies of staticresource so that the staticresource is only available for that item . < ItemsControl x : Name= '' itemsControl '' ItemsSource= '' { Binding DataList } '' > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < StackPanel Orientation= '' Vertical '' / > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel > < ItemsControl.ItemTemplate > < DataTemplate > < Grid MinHeight= '' 250 '' > < ContentPresenter Content= '' { Binding } '' ContentTemplateSelector= '' { StaticResource chartSelector } '' > < ContentPresenter.Resources > < v : ColorProvider x : Key= '' colorProvider '' / > < /ContentPresenter.Resources > < /ContentPresenter > < /Grid > < /DataTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl >,create multiple copies of staticresource "C_sharp : I 'm trying to use the Reactive Extensions ( Rx ) to buffer an enumeration of Tasks as they complete . Does anyone know if there is a clean built-in way of doing this ? The ToObservable extension method will just make an IObservable < Task < T > > , which is not what I want , I want an IObservable < T > , that I can then use Buffer on.Contrived example : //Method designed to be awaitablepublic static Task < int > makeInt ( ) { return Task.Run ( ( ) = > 5 ) ; } //In practice , however , I do n't want to await each individual task//I want to await chunks of them at a time , which *should* be easy with Observable.Buffer public static void Main ( ) { //Make a bunch of tasks IEnumerable < Task < int > > futureInts = Enumerable.Range ( 1 , 100 ) .Select ( t = > makeInt ( ) ) ; //Is there a built in way to turn this into an Observable that I can then buffer ? IObservable < int > buffered = futureInts.TasksToObservable ( ) .Buffer ( 15 ) ; // ? ? ? ? buffered.Subscribe ( ints = > { Console.WriteLine ( ints.Count ( ) ) ; //Should be 15 } ) ; }",Convert IEnumerable < Task < T > > to IObservable < T > "C_sharp : I 'm reading Async in C # 5.0 , and the section on the compiler transform contains this snippet : There are two pieces of notation that are new to me . The first is < AlexsMethod > d__0 . The second is stateMachine. < > 4__this . Neither works when I try them myself , so I suspect it 's for use by the compiler only . But I 'm having trouble searching for more information on what is intended by this notation . public Task < int > AlexsMethod ( ) { < AlexsMethod > d__0 stateMachine = new < AlexsMethod > d__0 ( ) ; stateMachine. < > 4__this = this ; stateMachine. < > t__builder = AsyncTaskMethodBuilder < int > .Create ( ) ; stateMachine. < > 1__state = -1 ; stateMachine. < > t__builder.Start < < AlexsMethod > d__0 > ( ref stateMachine ) ; return stateMachine. < > t__builder.Task ; }",What does this notation involving angle brackets mean ? "C_sharp : For example , I have registered class C1 with one parameter in constructor of type System.Type . I have another class ( C2 ) with injected parameter of type C1 . And I want receive typeof ( C2 ) automatically in C1 constructor . Is it possible in some way ? Example code : public class C1 { public C1 ( Type type ) { } // ... } public class C2 { public C2 ( C1 c1 ) { } // ... } // RegistrationcontainerBuilder.Register ( ? ? ? ) ; containerBuilder.Register < C2 > ( ) ;",Is it possible to get container type in AutoFac "C_sharp : I 'm trying to add share functionality to my Windows Phone App . The code behaves in an unpredictable way . Sometimes it works , but mostly it does n't and I have n't been able to get any details about what 's causing the crash . Could someone please go through the code below and let me know if I 've missed something ? Thanks ! UPDATEThe code always works while I 'm debugging from visual studio but pretty much never otherwise . I made a release build thinking there might be some code in the debug build which is causing the problem but that did n't make any difference . public ArticlePage ( ) { this.InitializeComponent ( ) ; //.. RegisterForShare ( ) ; } private void RegisterForShare ( ) { DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView ( ) ; dataTransferManager.DataRequested += new TypedEventHandler < DataTransferManager , DataRequestedEventArgs > ( this.ShareLinkHandler ) ; } private void ShareLinkHandler ( DataTransferManager sender , DataRequestedEventArgs e ) { DataRequest request = e.Request ; DataRequestDeferral defferal = request.GetDeferral ( ) ; request.Data.Properties.Title = this.article.Title ; request.Data.Properties.Description = this.article.Summary ; request.Data.SetWebLink ( new Uri ( this.article.UrlDomain ) ) ; defferal.Complete ( ) ; } private void ShareCommand_Click ( object sender , RoutedEventArgs e ) { DataTransferManager.ShowShareUI ( ) ; }",Windows Phone 8.1 App crashes on ShowShareUI ( ) "C_sharp : I have a simple C # Application containing this line : When running this code on Windows ( .NET ) , the image is loaded correctly.When running the same code on OS X ( Mono ) , the application just hangs . The debugger stays in that call forever . No exception no nothing.The callstack shows the application hangs at : System.Drawing.GDIPlus.GdiplusStartup ( ) What could go wrong here ? PS : I have the latest versions of Xamarin Studio and Mono installed . var mImage = System.Drawing.Image.FromFile ( filename ) ;",Image.FromFile ( ) or FromStream ( ) hangs on GdiplusStartup "C_sharp : I 'm trying to make a service that returns a catalog based on the filters.I 've seen a few results on the internet , but not quite my issue . I hope you can help me with mine.The issue is that this query build can not be translated into a store expression : 'LINQ to Entities does not recognize the method 'System.Linq.IQueryable ' 1 [ App.Data.Models.Subgroup ] HasProductsWithState [ Subgroup ] ( System.Linq.IQueryable ' 1 [ App.Data.Models.Subgroup ] , System.Nullable ` 1 [ System.Boolean ] ) ' method , and this method can not be translated into a store expression . 'How can I make it so the query can be translated into a store expression.Please do n't suggest .ToList ( ) as a answer as I do n't want this to run in memory.So what I have is : In the code below you can see that I recursively call the extension to try and stack the expression . But when I walk through my code at runtime it does not enter the function again whenis called.UPDATEMissing classes : bool ? isActive = null ; string search = null ; DbSet < Maingroup > query = context.Set < Maingroup > ( ) ; var result = query.AsQueryable ( ) .HasProductsWithState ( isActive ) .HasChildrenWithName ( search ) .OrderBy ( x = > x.SortOrder ) .Select ( x = > new CatalogViewModel.MaingroupViewModel ( ) { Maingroup = x , Subgroups = x.Subgroups.AsQueryable ( ) .HasProductsWithState ( isActive ) .HasChildrenWithName ( search ) .OrderBy ( y = > y.SortOrder ) .Select ( y = > new CatalogViewModel.SubgroupViewModel ( ) { Subgroup = y , Products = y.Products.AsQueryable ( ) .HasProductsWithState ( isActive ) .HasChildrenWithName ( search ) .OrderBy ( z = > z.SortOrder ) .Select ( z = > new CatalogViewModel.ProductViewModel ( ) { Product = z } ) } ) } ) ; return new CatalogViewModel ( ) { Maingroups = await result.ToListAsync ( ) } ; return maingroups.Where ( x = > x.Subgroups.AsQueryable ( ) .HasProductsWithState ( state ) .Any ( ) ) as IQueryable < TEntity > ; public static class ProductServiceExtensions { public static IQueryable < TEntity > HasProductsWithState < TEntity > ( this IQueryable < TEntity > source , bool ? state ) { if ( source is IQueryable < Maingroup > maingroups ) { return maingroups.Where ( x = > x.Subgroups.AsQueryable ( ) .HasProductsWithState ( state ) .Any ( ) ) as IQueryable < TEntity > ; } else if ( source is IQueryable < Subgroup > subgroups ) { return subgroups.Where ( x = > x.Products.AsQueryable ( ) .HasProductsWithState ( state ) .Any ( ) ) as IQueryable < TEntity > ; } else if ( source is IQueryable < Product > products ) { return products.Where ( x = > x.IsActive == state ) as IQueryable < TEntity > ; } return source ; } public static IQueryable < TEntity > HasChildrenWithName < TEntity > ( this IQueryable < TEntity > source , string search ) { if ( source is IQueryable < Maingroup > maingroups ) { return maingroups.Where ( x = > search == null || x.Name.ToLower ( ) .Contains ( search ) || x.Subgroups.AsQueryable ( ) .HasChildrenWithName ( search ) .Any ( ) ) as IQueryable < TEntity > ; } else if ( source is IQueryable < Subgroup > subgroups ) { return subgroups.Where ( x = > search == null || x.Name.ToLower ( ) .Contains ( search ) || x.Products.AsQueryable ( ) .HasChildrenWithName ( search ) .Any ( ) ) as IQueryable < TEntity > ; } else if ( source is IQueryable < Product > products ) { return products.Where ( x = > search == null || x.Name.ToLower ( ) .Contains ( search ) ) as IQueryable < TEntity > ; } return source ; } } public class Maingroup { public long Id { get ; set ; } public string Name { get ; set ; } ... public virtual ICollection < Subgroup > Subgroups { get ; set ; } } public class Subgroup { public long Id { get ; set ; } public string Name { get ; set ; } public long MaingroupId { get ; set ; } public virtual Maingroup Maingroup { get ; set ; } ... public virtual ICollection < Product > Products { get ; set ; } } public class Product { public long Id { get ; set ; } public string Name { get ; set ; } public long SubgroupId { get ; set ; } public virtual Subgroup Subgroup { get ; set ; } ... public bool IsActive { get ; set ; } }",Nested expression building with linq and Entity Framework C_sharp : I have several classes defining the DebuggerDisplay attribute . I want to know if there is a way to define one DebuggerDisplay attribute based on another one . If I have the following classes : I would like to see on instances of B the A class as it is defined on the class A DebuggerDisplay attribute . Instead of that I 'm getting the class A ToString ( ) method onto the debugger while viewing class B objects . [ DebuggerDisplay ( `` Text = { Text } '' ) ] class A { public string Text { get ; set ; } } [ DebuggerDisplay ( `` Property = { Property } '' ) ] class B { public A Property { get ; set ; } },Chaining DebuggerDisplay on complex types "C_sharp : tl ; dr : What 's wrong with my Cur ( currency ) structure ? tl ; dr 2 : Read the rest of the question please , before giving an example with float or double . : - ) I 'm aware that this question has come up numerous times before all around the internet , but I have not yet seen a convincing answer , so I thought I 'd ask again.I fail to understand why using a non-decimal data type is bad for handling money . ( That refers to data types that store binary digits instead of decimal digits . ) True , it 's not wise to compare two doubles with a == b . But you can easily say a - b < = EPSILON or something like that.What is wrong with this approach ? For instance , I just made a struct in C # that I believe handles money correctly , without using any decimal-based data formats : ( Sorry for changing the name Currency to Cur , for the poor variable names , for omitting the public , and for the bad layout ; I tried to fit it all onto the screen so that you could read it without scrolling . ) : ) You can use it like : Of course , C # has the decimal data type , but that 's beside the point here -- the question is about why the above is dangerous , not why we should n't use decimal.So would someone mind providing me with a real-world counterexample of a dangerous statement that would fail for this in C # ? I ca n't think of any.Thanks ! Note : I am not debating whether decimal is a good choice . I 'm asking why a binary-based system is said to be inappropriate . struct Cur { private const double EPS = 0.00005 ; private double val ; Cur ( double val ) { this.val = Math.Round ( val , 4 ) ; } static Cur operator + ( Cur a , Cur b ) { return new Cur ( a.val + b.val ) ; } static Cur operator - ( Cur a , Cur b ) { return new Cur ( a.val - b.val ) ; } static Cur operator * ( Cur a , double factor ) { return new Cur ( a.val * factor ) ; } static Cur operator * ( double factor , Cur a ) { return new Cur ( a.val * factor ) ; } static Cur operator / ( Cur a , double factor ) { return new Cur ( a.val / factor ) ; } static explicit operator double ( Cur c ) { return Math.Round ( c.val , 4 ) ; } static implicit operator Cur ( double d ) { return new Cur ( d ) ; } static bool operator < ( Cur a , Cur b ) { return ( a.val - b.val ) < -EPS ; } static bool operator > ( Cur a , Cur b ) { return ( a.val - b.val ) > +EPS ; } static bool operator < = ( Cur a , Cur b ) { return ( a.val - b.val ) < = +EPS ; } static bool operator > = ( Cur a , Cur b ) { return ( a.val - b.val ) > = -EPS ; } static bool operator ! = ( Cur a , Cur b ) { return Math.Abs ( a.val - b.val ) < EPS ; } static bool operator == ( Cur a , Cur b ) { return Math.Abs ( a.val - b.val ) > EPS ; } bool Equals ( Cur other ) { return this == other ; } override int GetHashCode ( ) { return ( ( double ) this ) .GetHashCode ( ) ; } override bool Equals ( object o ) { return o is Cur & & this.Equals ( ( Cur ) o ) ; } override string ToString ( ) { return this.val.ToString ( `` C4 '' ) ; } } Currency a = 2.50 ; Console.WriteLine ( a * 2 ) ;",Why is using a NON-decimal data type bad for money ? "C_sharp : An empty try has some value as explained elsewhereHowever , is there any use for an empty finally such as : EDIT : Note I have Not actually checked to see if the CLR has any code generated for the empty finally { } try { } finally { ..some code here } try { ... some code here } finally { }",Empty finally { } of any use ? "C_sharp : I have a class that is effectively a object based enum . There is a static set of objects exposed by the class , and everything uses these same instances . eg ( Note the private constructor ) This works great until I have to serialise across WCF . The DataContractSerializer creates new objects by bypassing the constructor . This results in a valid FieldType object , but it is a new instance that is not one of my static instances . This makes reference comparisons against the known static values fail.Is there any way to override the serialisation behaviour for a class so that I create the object instance instead of populating an instance supplied to me ? [ DataContract ] public class FieldType { public static readonly FieldType Default = new FieldType ( 1 , `` Default '' ) ; public static readonly FieldType Name = new FieldType ( 2 , `` Name '' ) ; public static readonly FieldType Etc = new FieldType ( 3 , `` Etc '' ) ; private FieldType ( uint id , string name ) { Id = id ; Name = name ; } [ DataMember ] public uint Id { get ; private set ; } [ DataMember ] public string Name { get ; private set ; } //snip other properties }",DataContractSerializer and immutable types . Deserialising to a known object instance "C_sharp : I have a dictionary of type Dictionary < string , IEnumerable < string > > and a list of string values . For some reason , every time I do an Add , every value in the dictionary is overwritten . I 'm completely stumped as to why this is happening . I made sure it 's not a reference problem be declaring and initializing the IEnumberable object within the loop so that it 's scope does not go outside one iteration , and it still does it . Here is my code : where typelist is an IEnumerable < string > , root is an XElement , and serialLists is my Dictionary . foreach ( string type in typelist ) { IEnumerable < string > lst = from row in root.Descendants ( ) where row.Attribute ( `` serial '' ) .Value.Substring ( 0 , 3 ) .Equals ( type ) select row.Attribute ( `` serial '' ) .Value.Substring ( 3 ) .ToLower ( ) ; serialLists.Add ( type , lst ) ; }",Why is Dictionary.Add overwriting all items in my dictionary ? "C_sharp : Retargetable assembly references have been introduced for the .NET Compact Framework and are now used to support Portable Class Libraries.Basically , the compiler emits the following MSIL : How does the C # compiler understand it has to emit a retargetable reference , and how to force the C # compiler to emit such reference even outside of a portable class library ? .assembly extern retargetable mscorlib { .publickeytoken = ( 7C EC 85 D7 BE A7 79 8E ) .ver 2:0:5:0 }",How does the C # compiler decide to emit retargetable assembly references ? "C_sharp : I 'm working with Db ( via SQLite.NET PCL , not async version ) . At current moment i have a listview with some data ( taken from db ) , also i got a searchbar/entry ( its nvm ) , where user can input some values and then , via LINQ i 'm going to make a query and update SourceItems of my List . So the problems comes with performance , because my DB got million records and simple LINQ query working very slow.In other words , when user enter too fast some data , application gets huge lags and sometimes can Crash.To resolve this problem , some things come in my mind ( theoretically solution ) : 1 ) Need to put method ( which i make query into db ) on Task ( to unlock my main UI thread ) 2 ) Initialize timer , then turn on and : if 1 second passed , then = > run my method ( query ) on Task ( similiar to background thread ) if 1 second does n't passed , then exit from anonymous method . Something like that ( similar ) or any suggestions.Thanks ! UPD : So to be honest , i tried too much and didnt get a good resultBTW , my current code ( Snippets ) :1 ) My SearchMethod 2 ) Searchbar.TextChanged ( anonymous method ) The main problem is how to implement this part ( with these case 's ) , where 1 second passed and only then i 'm going to make query to update my sourceItems of list ( everytime , when user inputs some value into searchbar , this trigger ( timer ) must refresh again to zero ) . Any help will be appreciated , thanks ! PS Sorry for my eng . skills ! public void QueryToDB ( string filter ) { this.BeginRefresh ( ) ; if ( string.IsNullOrWhiteSpace ( filter ) ) { this.ItemsSource = SourceData.Select ( x = > x.name ) ; // Source data is my default List of items } else { var t = App.DB_Instance.FilterWords < Words > ( filter ) ; //FilterWords it 's a method , where i make direct requests to the database this.ItemsSource = t.Select ( x = > x.name ) ; } this.EndRefresh ( ) ; } searchBar.TextChanged +=async ( sender , e ) = > { ViewModel.isBusy = true ; //also i got a indicator , to show progress , while query working await Task.Run ( ( ) = > //my background , works fine { listview.QueryToDB ( searchBar.Text ) ; } ) ; ViewModel.isBusy = false ; // after method is finished , indicator turn off } ;","Dynamically search with interrupts , via Tasks C #" "C_sharp : Fails : Succeeds : The error in the first statement is : Type of conditional expression can not be determined because there is no implicit conversion between 'int ' and 'string'.Why does there need to be though , I 'm assigning those values to a variable of type object.Edit : The example above is trivial , yes , but there are examples where this would be quite helpful : object o = ( ( 1==2 ) ? 1 : `` test '' ) ; object o ; if ( 1 == 2 ) { o = 1 ; } else { o = `` test '' ; } int ? subscriptionID ; // comes in as a parameterEntityParameter p1 = new EntityParameter ( `` SubscriptionID '' , DbType.Int32 ) { Value = ( ( subscriptionID == null ) ? DBNull.Value : subscriptionID ) , }",Are there any good reasons why ternaries in C # are limited ? C_sharp : I tried to check matches facebook url and get profile in one regular expression : I have : http : //www.facebook.com/profile.php ? id=123456789 https : //facebook.com/someusernameI need : using this regular expression : I get : Whats wrong ? 123456789someusername ( ? < = ( https ? : // ( www. ) ? facebook.com/ ( profile.php ? id= ) ? ) ) ( [ ^/ # ? ] + ) profile.phpsomeusername,Regular expression to get facebook profile "C_sharp : I have been looking in to subscribing to an event using a weak event pattern . With the .NET 4.5 framework , we have a slick looking WeakEventManager class . Weakly subscribing to an event is as simple asI 'm not a big fan of 'stringly-typed ' code however . I have been trying to find a way around using the string name of the event to subscribe to . The only way I have found to obtain the name of the event is using a lambda expression in the class that defines the event . In my scenario , I own the class defining the event so I can change it however I like . I have been trying to find a clean way to subscribe and unsubscribe to my event and here is what I disliked the least.Using custom event accessors I was able to avoid clunky ( in my opinion ) methods like LoggingOn_Subscribe ( EventHandler ) or adding name properties for each event . Unfortunately it is not so intuitive in that people subscribing to the event are doing so in the classic manner but have no idea other than the `` _Weak '' part of the name that indicates it is being subscribed to weakly.As for my questions..1 ) I have never used weak events or custom event accessors before . The code above appears to work , however , I would just like to make sure there is nothing technically wrong with it . Is there anything I 'm doing here to shoot myself in the foot ? 2 ) From a design perspective , is this a terrible idea ? Are there any major design concerns I should consider ? Is there better alternative ? Should i just suck it up and subscribe from my subscriber using a stringly-typed event name ? Thoughts ? WeakEventManager < EventSource , SomeEventEventArgs > .AddHandler ( source , `` SomeEvent '' , source_SomeEvent ) ; public event EventHandler < EventArgs > LoggingOn ; public event EventHandler < EventArgs > LoggingOn_Weak { add { var eventName = this.GetEventName ( ( ) = > this.LoggingOn ) ; WeakEventManager < CurrentUser , EventArgs > .AddHandler ( this , eventName , value ) ; } remove { var eventName = this.GetEventName ( ( ) = > this.LoggingOn ) ; WeakEventManager < CurrentUser , EventArgs > .RemoveHandler ( this , eventName , value ) ; } } // In a base class view model in my scenarioprivate string GetEventName < T > ( System.Linq.Expressions.Expression < Func < T > > expression ) { return ( expression.Body as System.Linq.Expressions.MemberExpression ) .Member.Name ; } protected void OnLoggingOn ( object sender , EventArgs e ) { var handler = this.LoggingOn ; if ( handler ! = null ) { handler ( sender , e ) ; } }",WeakEventManager with event name lambda expression and custom event accessors "C_sharp : Had a search and ca n't find this.I 'm looking for the VB.Net equivalent of C # 7 inline out variable declaration , e.g : Does such a thing exist in the equivalent VB.Net versions ? * the duplicate proposed is n't quite right I 'm afraid , but I 've marked Heinzi 's answer correct . MethodCall ( arg1 , out string arg2 ) ;",Equivalent of inline out parameter declaration ? "C_sharp : I need to use Sql Server 's `` datetime2 '' type on all the DateTime and DateTime ? properties of all my entity objects . This is normally done with the fluent API like this : However , I would prefer NOT to do this manually for each and every DateTime field in each and every entity type . ( I do not have a common base type where all the DateTime properties can be placed , because the DateTime properties are specific to the entity types where they are defined ) .The short question : What are my options ? The long question : I was considering using reflection and made an atttempt , but it got very messy as is seems like the fluent API is not really suited for this kind of work because I had to call the generic fluent API methods via reflection . Here is my messy attempt : This fails in this line : with this error ( Entities.Order is one of my entity objects having a DateTime property ) : Can anyone help me out with this reflection approach or better , show me a simpler way to avoid having to manually write a lot of fluent api stuff ? modelBuilder.Entity < Mail > ( ) .Property ( c = > c.SendTime ) .HasColumnType ( `` datetime2 '' ) ; protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { var genericEntityMethod = modelBuilder.GetType ( ) .GetMethod ( `` Entity '' ) ; var entityTypes = Assembly.GetExecutingAssembly ( ) .GetTypes ( ) .Where ( t = > t.IsClass & & ! t.IsAbstract & & t.GetInterface ( `` IEntity '' ) ! = null ) ; foreach ( var t in entityTypes ) { var props = t.GetProperties ( ) .Where ( p = > p.GetSetMethod ( ) ! = null & & p.GetGetMethod ( ) ! = null & & ( p.PropertyType == typeof ( DateTime ) || p.PropertyType == typeof ( DateTime ? ) ) ) ; foreach ( var propertyInfo in props ) { var entityMethod = genericEntityMethod.MakeGenericMethod ( t.GetType ( ) ) ; var entityTypeConfiguration = entityMethod.Invoke ( modelBuilder , null ) ; var lambdaExpression = Expression.Lambda ( Expression.MakeMemberAccess ( Expression.Parameter ( t ) , propertyInfo ) , Expression.Parameter ( t ) ) ; //var propertyMethod = entityTypeConfiguration.GetType ( ) .GetMethod ( `` Property '' ) ; // Cant get this to work var propertyMethods = entityTypeConfiguration.GetType ( ) .GetMethods ( ) .Where ( m = > m.ReturnType == typeof ( DateTimePropertyConfiguration ) ) .ToList ( ) ; var propertyMethod = propertyInfo.PropertyType == typeof ( DateTime ) ? propertyMethods [ 0 ] : propertyMethods [ 1 ] ; var dateTimePropertyConfiguration = propertyMethod.Invoke ( entityTypeConfiguration , new object [ ] { lambdaExpression } ) ; var hasColumnTypeMethod = entityTypeConfiguration.GetType ( ) .GetMethod ( `` HasColumnType '' ) ; hasColumnTypeMethod.Invoke ( dateTimePropertyConfiguration , new object [ ] { `` datetime2 '' } ) ; } } base.OnModelCreating ( modelBuilder ) ; } var dateTimePropertyConfiguration = propertyMethod.Invoke ( entityTypeConfiguration , new object [ ] { lambdaExpression } ) ; Object of type 'System.Linq.Expressions.Expression ` 1 [ System.Func ` 2 [ Entities.Order , System.Nullable ` 1 [ System.DateTime ] ] ] ' can not be converted to type 'System.Linq.Expressions.Expression ` 1 [ System.Func ` 2 [ System.RuntimeType , System.Nullable ` 1 [ System.DateTime ] ] ]",A smarter Entity Framework Codefirst fluent API C_sharp : I have an app.config file where i have the same value many many times in the file and would like to be able to change it in one place.Something like : and then consume it for my Data Souce value in my connectionstring like below for exampleCan i do this somehow ? < appSettings > < add key= '' dbHostAddress '' value= '' localhost '' / > < /appSettings > < connectionStrings > < add name= '' ConnectionString '' connectionString= '' Data Source=I WOULD LIKE TO ACCESS THE VALUE HERE ; Initial Catalog=Database ; Integrated Security=True ; Connect Timeout=15 '' / > < /connectionStrings >,Declare variables in app.config for consuming inside app.config "C_sharp : Im developing an image skin detection app.But there is a problem with my camera , that try to compensate the light and the result image is bad , in most of cases i have a cold or warm effect on the image.When i use photoshop there is the AutoTone function that normalize an image and reduce this problem.With aforge i want to use HistogramEqualization ( ) filter but the result is very bad : So my question is : There is a function in Accord or Aforge to have the same result of the autotone of Photoshop ? If not , there is some library or script that let to do this ? Thank you all . // create filterHistogramEqualization filter = new HistogramEqualization ( ) ; // process imagefilter.ApplyInPlace ( sourceImage ) ;",Do something similar to Auto Tone of Photoshop with Aforge.net or c # "C_sharp : I 'm having some trouble with an event . The problem is that sometimes the event just is n't raised.We 've got a camera from an company which we 've implemented in our software . In the software we register an event which is triggered every time an image is taken on the camera.I 've noticed that with an increase of need in processing power ( e.g . calculating average mean on images and working with bigger images ) will sometimes result in the event not being raised . Furthermore I can make this happen even more often by increasing the frame-rate of the camera . I know a frame is missing because they are marked with ID's.In their own demo software I 'm able to run at the same speed with no problems . Their software does n't perform any calculations or anything , it just receives and displays the image.I 'm baffled because this is the closest connection to the camera I have ; all I can do is wait for the event to rise . I 'd like to ask you if you know of any situation where an event would be ignored.To me it looks like the camera is firing an image but for some reason the eve n't is n't picking up ( overload ? ) .Here is some of the related code : As you can see I take the frame , add it to a queue , and then tell my outside classes that there 's something for them to fetch . I 'm releasing the event thread as quickly as possible.Summary : My event is sometimes not raised . I think it 's because the main thread is working too hard.Do you have any experience with events sometimes not being raised ? private void Camera_OnFrameReceived ( AVT.VmbAPINET.Frame frame ) { if ( frame.ReceiveStatus == VmbFrameStatusType.VmbFrameStatusComplete ) { if ( lastID ! = 0 & & lastID ! = 1 ) { if ( frame.FrameID - lastID > 1 ) Debug.WriteLine ( `` HEEEEYYY SKIPPED A FRAME , ID : `` + frame.FrameID.ToString ( ) + `` TOTAL LOST : `` + ( frame.FrameID - lastID - 1 ) .ToString ( ) ) ; } lastID = frame.FrameID ; //Debug.WriteLine ( `` Frame received from camera '' ) ; //if the camera is in single mode , dont raise the event ( frame already taken ) if ( Mode == CaptureMode.Single ) return ; //set the last frame _frameQueue.Enqueue ( frame ) ; if ( FilmFrameReady ! = null ) { DateTime dateTime = Accurate.DtNow ; frameTaken = false ; FilmFrameReady ( this , new FilmFrameReadyArgs ( this , dateTime ) ) ; } } }",C # Event not raised and Threads "C_sharp : I have a Message class where a user could leave a message for more than one person . I have a getter for it , however , is returning a ConcurrentBag < > the way I 've done proper practice ? If not , how do i return the ConcurrentBag < > so I can loop through it and display it ? using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Collections.Concurrent ; namespace Crystal_Message { class Message { private int messageID ; private string message ; private ConcurrentBag < Employee > messageFor ; private Person messageFrom ; private string calltype ; public Message ( int iden , string message , Person messageFrom , string calltype , string telephone ) { this.messageID = iden ; this.messageFor = new ConcurrentBag < Employee > ( ) ; this.Note = message ; this.MessageFrom = messageFrom ; this.CallType = calltype ; } public ConcurrentBag < Employee > ReturnMessageFor { get { return messageFor ; } } public int MessageIdentification { get { return this.messageID ; } private set { if ( value == 0 ) { throw new ArgumentNullException ( `` Must have Message ID '' ) ; } this.messageID = value ; } } public string Note { get { return message ; } private set { if ( string.IsNullOrWhiteSpace ( value ) ) { throw new ArgumentException ( `` Must Have a Message '' ) ; } this.message = value ; } } public Person MessageFrom { get { return messageFrom ; } private set { this.messageFrom = value ; } } public string CallType { get { return this.calltype ; } private set { if ( string.IsNullOrWhiteSpace ( value ) ) { throw new ArgumentNullException ( `` Please specify call type '' ) ; } this.calltype = value ; } } public void addEmployee ( Employee add ) { messageFor.Add ( add ) ; } public override string ToString ( ) { return `` Message : `` + this.message + `` From : `` + this.messageFrom + `` Call Type : `` + this.calltype + `` For : `` + this.returnMessagefor ( ) ; } private string returnMessagefor ( ) { string generate= '' '' ; foreach ( Employee view in messageFor ) { generate += view.ToString ( ) + `` `` ; } return generate ; } public override bool Equals ( object obj ) { if ( obj == null ) { return false ; } Message testEquals = obj as Message ; if ( ( System.Object ) testEquals == null ) { return false ; } return ( this.messageID == testEquals.messageID ) & & ( this.message == testEquals.message ) & & ( this.messageFor == testEquals.messageFor ) & & ( this.messageFrom == testEquals.messageFrom ) & & ( this.calltype == testEquals.calltype ) ; } public bool Equals ( Message p ) { if ( ( Object ) p == null ) { return false ; } return ( this.messageID == p.messageID ) & & ( this.message == p.message ) & & ( this.messageFor == p.messageFor ) & & ( this.messageFrom == p.messageFrom ) & & ( this.calltype == p.calltype ) ; } public override int GetHashCode ( ) { unchecked { return this.messageID.GetHashCode ( ) * 33 ^ this.message.GetHashCode ( ) * 33 ^ this.messageFor.GetHashCode ( ) * 33 ^ this.messageFrom.GetHashCode ( ) * 33 ^ this.calltype.GetHashCode ( ) ; } } } }",C # Return a Copy of ConcurrentBag "C_sharp : I get that it ca n't access Method here , because Method is required to be static . Why is this ? Prop is not static.Update : Here 's the actual signature : And this is how the method used to be : This was n't an issue because I did n't need to reference this , so when I added this and it did n't compile anymore , ( the field was n't mine to begin with , someone else had done it like that , so do n't hate me for that ) . I changed it to the following : But then the ajaxData private field would always be null , which makes the data table be instanced again every time ( this is appended into a concurrent dictionary , which causes an Exception on a duplicate key ) . I want to know how assigning to a field that does n't reference this works . Does that create something that is reused across all instances of an object ? public T Prop = new Ctor ( Method ) ; private K Method ( U controller , V request ) ; public DataSource ( Func < ControllerBase , AjaxDataTable.Request , Result > dataSelector ) public AjaxDataTable < SourcesViewModel.Source.Channel > .DataSource AjaxData = new AjaxDataTable < SourcesViewModel.Source.Channel > .DataSource ( OnSelectData ) ; private AjaxDataTable < SourcesViewModel.Source.Channel > .DataSource ajaxData ; public AjaxDataTable < SourcesViewModel.Source.Channel > .DataSource AjaxData { get { if ( ajaxData == null ) { ajaxData = new AjaxDataTable < SourcesViewModel.Source.Channel > .DataSource ( OnDataSelector ) ; } return ajaxData ; } }",Why is this in static context ? "C_sharp : I was digging around in .NET 's implementation of Dictionaries , and found one function that I 'm curious about : HashHelpers.GetPrime.Most of what it does is quite straightforward , it looks for a prime number above some minimum which is passed to it as a parameter , apparently for the specific purpose of being used as a number of buckets in a hashtable-like structure . But there 's one mysterious part : What is the purpose of the ( j - 1 ) % 101 ! = 0 check ? i.e . Why do we apparently want to avoid having a number of buckets which is 1 more than a multiple of 101 ? if ( HashHelpers.IsPrime ( j ) & & ( j - 1 ) % 101 ! = 0 ) { return j ; }",What is the purpose of this line in HashHelpers.GetPrime ? "C_sharp : I want to collect/run tasks , and then do Task.WhenAll on them.Is it correct to use Task.Run here or should I doOr something else entirely ? var tasks = new List < Task > ( ) ; foreach ( var thing in things ) { tasks.Add ( Task.Run ( async ( ) = > { // async stuff using thing } ) ) ; } var stuffs = await Task.WhenAll ( tasks ) ; tasks.Add ( new Func < Task > ( async ( ) = > { async stuff } ) ( ) ) ;","When running a async lambda , use Task.Run ( func ) or new Func < Task > ( func ) ( ) ?" "C_sharp : Given this class : Suppose I have the following List < Article > where some of the articles contain a comma separated name : Is there a way , in one Linq statement , to get a list where each comma separated name becomes a separate article ? public class Article { public string Name { get ; set ; } public string Colour { get ; set ; } } var list = new List < Article > { new Article { Name = `` Article1 , Article2 , Article3 '' , Colour = `` Red '' } , new Article { Name = `` Article4 , Article5 , Article6 '' , Colour = `` Blue '' } , } var list = new List < Article > { new Article { Name = `` Article1 '' , Colour = `` Red '' } , new Article { Name = `` Article2 '' , Colour = `` Red '' } , new Article { Name = `` Article3 '' , Colour = `` Red '' } , new Article { Name = `` Article4 '' , Colour = `` Blue '' } , new Article { Name = `` Article5 '' , Colour = `` Blue '' } , new Article { Name = `` Article6 '' , Colour = `` Blue '' } , }",Splitting List < T > based on comma separated property value using Linq "C_sharp : In C # , using reflection , is it possible to define method in the base class that returns its own name ( in the form of a string ) and have subclasses inherit this behavior in a polymorphic way ? For example : public class Base { public string getClassName ( ) { //using reflection , but I do n't want to have to type the word `` Base '' here . //in other words , DO NOT WANT get { return typeof ( Base ) .FullName ; } return className ; //which is the string `` Base '' } } public class Subclass : Base { //inherits getClassName ( ) , do not want to override } Subclass subclass = new Subclass ( ) ; string className = subclass.getClassName ( ) ; //className should be assigned `` Subclass ''",Define a method in base class that returns the name of itself ( using reflection ) - subclasses inherit this behavior "C_sharp : How to create or use ready Shims for .net framework 4.6.1 elements to port them ( from .net framework 4.6.1 ) to .net core 2.0 / .net standard 2.0 ? Some classes of interest : , it would be nice to have shims for classes like : System.Windows.Threading.Dispatcheror System.ComponentModel.ItemPropertyInfo.DescriptorevenSystem.Windows.Controls.MenuItemand many more ... Context : The application ( the code ) is not 100 % well organized . Business logic is not 100 % separated from UI logic . The answer `` do refactoring first '' is definitely a good answer . But in my case things are not 100 % how they should ideally be.Approximate example , a try to do it mannually : System.Windows.Threading.Dispatcher is not implemented in Core 2.0.One could try to add : Followed by two implementations of this interface : andFollowed by a a class ( let 's call it Shims ) in a multitargeted project : The result is the shim , which could be used in different APIs.Is this a correct approach ? Actually , creating such shims requires much routine work . I have a feeling that this work is not necessary to be performed . I have a feeling that there is a ready solution for this problem ... I 'm aware of Microsoft.Windows.Compatibility package . The question is rather related to porting when WPF is involved with many wpf-specific elements . Those elements are not in Microsoft.Windows.Compatibility package , but , unfortunately , they are used across my assemblies , which are candidates for retargeting to .Net Core 2.0 . I mean shimming those classes , which are not in Microsoft.Windows.Compatibility . Ok , we have this Microsoft.Windows.Compatibility.Shims , but i 'm not sure that it is useful in my case ; especially after reading the following text : Microsoft.Windows.Compatibility.Shims : This package provides infrastructure services and should n't be referenced directly from your code ... .Upd : emphasizing that the final target is .net core 2.0Upd2 : the whole task is to port the major part of a WPF app to .net core ( leaving working WPF app ) for potential web-client . The major part contains .net framework elements which are not implemented for .net core.Upd3 : Couple of words about complete strategy : The more complete strategy is Shared projects , first approach in this article ( # if ) . There are 2 major steps in my strategy : one is to gradually port code , starting from base libraries and finnishing at top libraries , But with intense use of stubs and PlatformNotSupportedExceptions . The second step is to move from top libraries to base libraries substituting stubs and exceptions by .net core implementations , On demand ( ! ) - no need to subsitute all stubs and exceptions.Upd4 We have already split portable tests from non-portable tests ( into two libs ) . It is very important that we run the tests during the porting process . public enum DispatcherShimPriority { Background // ... } public interface DispaicherShim { void Invoke ( Action action , DispatcherShimPriority prio ) ; void BeginInvoke ( Action action , DispatcherShimPriority , prio ) ; } public class DispatcherCore : DispaicherShim ; public class DispatcherFramework : DispaicherShim ; public static DispaicherShim CreateDispatcher ( ) { # if NETCOREAPP2_0 return new DispatcherCore ( ) ; # else return new DispatcherFramework ( ) ; # endif }",How to create or use ready Shims for porting from .net framework to .net core / standard ? "C_sharp : I use the fallowing code to export a Windows-Event-Log : This is generally working . But on one machine , I get the fallowing Exception : '' Der Verzeichnisname ist ungültig '' means on english : `` The pathname is invalid '' The Application-EventLog is existing and tempEventLogPath is also valid.Does someone know , what there can be wrong ? var els = new EventLogSession ( ) ; els.ExportLogAndMessages ( `` Application '' , PathType.LogName , `` * [ System [ Provider [ @ Name='Prayon.Client ' ] ] ] '' , tempEventLogPath , false , CultureInfo.CurrentCulture ) ; System.Diagnostics.Eventing.Reader.EventLogException : Der Verzeichnisname ist ungültigbei System.Diagnostics.Eventing.Reader.EventLogException.Throw ( Int32 errorCode ) bei System.Diagnostics.Eventing.Reader.NativeWrapper.EvtArchiveExportedLog ( EventLogHandle session , String logFilePath , Int32 locale , Int32 flags ) bei System.Diagnostics.Eventing.Reader.EventLogSession.ExportLogAndMessages ( String path , PathType pathType , String query , String targetFilePath , Boolean tolerateQueryErrors , CultureInfo targetCultureInfo )",Exception at Exporting EventLog C_sharp : I 'd like the aspect to exit a method invocation based on a condition like the following : Any help much appreciated . [ AttributeUsage ( AttributeTargets.Method ) ] public class IgnoreIfInactiveAttribute : OnMethodBoundaryAspect { public override void OnEntry ( MethodExecutionEventArgs eventArgs ) { if ( condition ) { **// How can I make the method return here ? ** } } },How to exit a method in the OnEntry method of a PostSharp aspect based on condition "C_sharp : I updated my ASP.NET MVC project to include form validation - Abide ( foundation.abide.js ) , but when I go to include data-abide in the form , it throws up an error . I added it to a foundation folder that is part of a script bundle which is referenced on my layout view.Can someone explain what I am missing ? Is it due to the fact that I only added the javascript file and nothing else ? @ using ( Html.BeginForm ( `` CreateJourney '' , `` Home '' , FormMethod.Post , new { @ class = `` custom '' , id= '' postJourneyForm '' , name= '' postJourneyForm '' , data-abide } ) )",Can not get Foundation 's Abide to work with Html Helper form "C_sharp : I use a BackgroundWorker and do this : And now the two methods.I do n't understand why UnsafeThreadMethod does n't throw the following exception but EvenUnsaferThreadMethod does . Cross-thread operation not valid : Control 'panelLoading ' accessed from a thread other than the > thread it was created on.According to the message it 's because toolStripLabelRssFeedData was created on the same thread but it wasn't.I thought that I ca n't call controls created by the main thread and have to use the ProgressChanged event . What 's going on ? And I have a second question . What is the advantage of doing it like this when I can use ProgressChanged ? What should I do ? private void loadNewAsyncToolStripMenuItem_Click ( object sender , EventArgs e ) { this.Text = `` RunWorkerAsync ( ) '' ; backgroundWorkerLoading.RunWorkerAsync ( ) ; } private void backgroundWorkerLoading_DoWork ( object sender , DoWorkEventArgs e ) { UnsafeThreadMethod ( `` hello '' ) ; EvenUnsaferThreadMethod ( ) ; } private void UnsafeThreadMethod ( string text ) { toolStripLabelRssFeedData.Text = text ; } private void EvenUnsaferThreadMethod ( ) { panelLoading.Visible = true ; } private void EvenUnsaferThreadMethod ( ) { if ( panelLoading.InvokeRequired ) { panelLoading.Invoke ( new MethodInvoker ( ( ) = > { EvenUnsaferThreadMethod ( ) ; } ) ) ; } else { panelLoading.Visible = true ; } }",Why do I not get the `` Cross-thread operation not valid '' error "C_sharp : I have a windows service that downloads a script and then runs it.I 've been trying to make my windows service more secure , making it accept only signed power-shell scripts.I have ran the Set-ExecutionPolicy AllSigned command on the server , and this works in the windows power shell command prompt.However , my code still runs both signed and unsigned scripts , even if the set-executionpolicy is set to restricted.I have tried two approaches : RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create ( ) ; And another approach : In both situations the code runs unsigned scripts as well.Have I missed something ? Runspace runspace = RunspaceFactory.CreateRunspace ( runspaceConfiguration ) ; runspace.Open ( ) ; RunspaceInvoke scriptInvoker = new RunspaceInvoke ( runspace ) ; Pipeline pipeline = runspace.CreatePipeline ( ) ; pipeline.Commands.AddScript ( @ '' Set-ExecutionPolicy AllSigned '' ) ; pipeline.Commands.AddScript ( @ '' Get-ExecutionPolicy '' ) ; pipeline.Commands.AddScript ( script ) ; Collection < PSObject > results = pipeline.Invoke ( ) ; using ( PowerShell ps = PowerShell.Create ( ) ) { ps.AddCommand ( `` Set-ExecutionPolicy '' ) .AddArgument ( `` Restricted '' ) ; ps.AddScript ( `` Set-ExecutionPolicy Restricted '' ) ; ps.AddScript ( script ) ; Collection < PSObject > results = ps.Invoke ( ) ; }",Run Only signed powershell scripts from c # "C_sharp : Using ReSharper 8.2 on local computer and NUnit 2.6.3 on build server found there were some test which passed in ReSharper and failed in NUnit . Installed NUnit locally and same results so it is not a difference between computers . Two of my colleagues ran the same tests and had same results so does n't seem something messing my computer.A simplified version of the tests : ReSharper output is all green . The output from NUnit : ReSharper seems to be using the same version of NUnit ( Built-in NUnit 2.6.3 ) Does anyone knows what how to fix that ? Is it a bug in ReSharper or NUnit ? [ Test ] public void Test_UrlQueryString ( ) { var urlInput = `` http : //www.domain.com/page-with-querystring ? url=https : //www.domain2.com/page % 3Fp % 3DPEPE '' ; var uri = new Uri ( urlInput ) ; Assert.AreEqual ( urlInput , uri.ToString ( ) ) ; } [ Test ] public void Test_Dot ( ) { var urlInput = `` http : //www.domain.com/page-with-dot . ? p=google '' ; var uri = new Uri ( urlInput ) ; Assert.AreEqual ( urlInput , uri.ToString ( ) ) ; } Runtime Environment - OS Version : Microsoft Windows NT 6.1.7601 Service Pack 1 CLR Version : 4.0.30319.18444 ( Net 4.5 ) ProcessModel : Default DomainUsage : SingleExecution Runtime : net-4.5 ... ... ... ... ... ... .F.F ... ... ... Tests run : 29 , Errors : 0 , Failures : 2 , Inconclusive : 0 , Time : 0.576769973208475 seconds Not run : 0 , Invalid : 0 , Ignored : 0 , Skipped : 0Errors and Failures : 1 ) Test Failure : Test.OrganicTest.Test_Dot Expected string length 45 but was 44 . Strings differ at index 35 . Expected : `` http : //www.domain.com/page-with-dot . ? p=google '' But was : `` http : //www.domain.com/page-with-dot ? p=google '' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ^ 2 ) Test Failure : Test.OrganicTest.Test_UrlQueryString Expected string length 87 but was 83 . Strings differ at index 76 . Expected : `` ... -with-querystring ? url=https : //www.domain2.com/page % 3Fp % 3DPEPE '' But was : `` ... -with-querystring ? url=https : //www.domain2.com/page ? p=PEPE '' -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ^",Unit test ReSharper and NUnit give different results "C_sharp : I 've specified type in a variable : Type hiddenType . I need to create a Func < T > delegate where T is of type specified in mentioned variable and assign an method : It does n't works - because funcImplementation is returns object instead of desired . At runtime , it will surely be an instance of type specified in hiddenType.GetInstance returns object and signaure can not be changed . var funcType = typeof ( Func < > ) .MakeGenericType ( hiddenType ) ; Func < object > funcImplementation = ( ) = > GetInstance ( hiddenType ) ; var myFunc= Delegate.CreateDelegate ( funcType , valueGenerator.Method ) ;",Create generic Func from reflection "C_sharp : I 'm trying to connect to the Windows Azure Service Management API . I have to provide a certificate which I previously uploaded to my azure portal . In .NET , this is very easy , as detailed here . In Metro however , you can not attach a Certificate to the request manually . On the Microsoft forum I found this : Together with giving the app the capability to use shared certificates , this should select a certificate or present the user an option to select the certificate . The certificate is in my Personal store , and I have even tried to include the certificate in the package manifest , but nothing works . It appears it just does n't include the certificate in the request.What is the correct way to call a REST-based API which needs a certiticate within a Metro app ? HttpClientHandler aHandler = new HttpClientHandler ( ) ; aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic ; HttpClient aClient = new HttpClient ( aHandler ) ; HttpResponseMessage aResp = await aClient.GetAsync ( `` https : // [ azure service management uri ] '' ) ;",Client-side certificate in a Metro app for Windows Azure Service Management "C_sharp : I have recently seen some production code to the effect of : Does this make any sense ? Intuitively , if the process has exited then no code can be running inside it.If not , what would be a good way to tell if the current process is terminating ? If it can be of any relevance , the use case for this was to avoid popping assertions such as objects not disposed when the process is being killed . if ( Process.GetCurrentProcess ( ) .HasExited ) { // do something }",Can Process.HasExited be true for the current process ? "C_sharp : I want to make my class immutable . Obvious way would be to declare all fields as get ; private set ; and to initialize all fields in constructor . So clients must provide everything in constructor . The problem is that when there are ~10 or more fields passing them in constructor become very unreadable , because there are no labels for each field.For example this is pretty readable : compare to this : And now imaging that I have 10 or more parameters.So how can I make class immutable saving readability ? I can suggest only use the same formatting when using constructor : Can you suggest something better ? info = new StockInfo { Name = data [ 0 ] as string , Status = s , LotSize = ( int ) data [ 1 ] , ISIN = data [ 2 ] as string , MinStep = ( decimal ) data [ 3 ] } ; new StockInfo ( data [ 0 ] as string , s , ( int ) data [ 1 ] , data [ 2 ] as string , ( decimal ) data [ 3 ] ) info = new StockInfo ( data [ 0 ] as string , // Name s , // Status ( int ) data [ 1 ] , // LotSize data [ 2 ] as string , // ISIN ( decimal ) data [ 3 ] // MinStep ) ;",is it possible to create immutable object without passing everything in constructor ? "C_sharp : Why do I get a heigh and Width of 0 with the below : Here is my definition of GetWindowRect : This is my definition for RECT : Thanks all for any help . static void Main ( string [ ] args ) { Process notePad = new Process ( ) ; notePad.StartInfo.FileName = `` notepad.exe '' ; notePad.Start ( ) ; IntPtr handle = notePad.Handle ; RECT windowRect = new RECT ( ) ; GetWindowRect ( handle , ref windowRect ) ; int width = windowRect.Right - windowRect.Left ; int height = windowRect.Bottom - windowRect.Top ; Console.WriteLine ( `` Height : `` + height + `` , Width : `` + width ) ; Console.ReadLine ( ) ; } [ DllImport ( `` user32.dll '' ) ] [ return : MarshalAs ( UnmanagedType.Bool ) ] static extern bool GetWindowRect ( IntPtr hWnd , ref RECT lpRect ) ; [ StructLayout ( LayoutKind.Sequential ) ] public struct RECT { public int Left ; // x position of upper-left corner public int Top ; // y position of upper-left corner public int Right ; // x position of lower-right corner public int Bottom ; // y position of lower-right corner }",Why do I get a height and Width of 0 ? "C_sharp : In my web application I 'm using System.Web.HttpContext.Current and it represents the current hit context , I was wondering how its accessible from everywhere until i noticed that its a static member ! While its a static member how it keeps its value while if two requests received in almost the same time.like the following : did I miss-understand something or there is a trick in it or what ? # Req1 -- -- > | set the value of the static field to req1 # Req2 -- -- > | set the value of the static field to req2 # Req1 | use that static its supposed to be req2 while its req1",System.Web.HttpContext.Current is static between requests "C_sharp : This question came to my mind while I am reading the post Why does n't C # support multiple inheritance ? from MSDN Blog.At first look at the following code : Object class is the ultimate base class of all classes . So it is the base class of A and B both in my program and also make A as a base class of B . So B has now two base class , one is A and another is Object . I override one method GetHashCode ( ) of Object Class in class A and B both . But in class B , base.GetHashCode ( ) method returns the return value of GetHashCode ( ) method of class A . But I want this value from Object class . How can I get that ? using System ; using System.Collections.Generic ; using System.Text ; namespace ConsoleApplication1 { class A { int num ; public A ( ) { num = 0 ; } public A ( int x ) { num = x ; } public override int GetHashCode ( ) { return num + base.GetHashCode ( ) ; } } class B : A { int num ; public B ( ) { num = 0 ; } public B ( int x ) { num = x ; } public override int GetHashCode ( ) { return num + base.GetHashCode ( ) ; } } class Program { static void Main ( string [ ] args ) { A a = new A ( ) ; B b = new B ( ) ; Console.Write ( a.GetHashCode ( ) + `` `` + b.GetHashCode ( ) ) ; Console.Read ( ) ; } } }",Multiple inheritance problem in C # C_sharp : I am creating an abstract base class which have functions implemented by other classes . My doubts are as follows1 ) Do i need give 'virtual ' in front of every function which need to be overridden by the child classes ? I see some examples without the virtual keyword and still they are open to be overridden.2 ) I need to have a function which will be implemented in the base class and i dont want it to be overridden by the child classes . I added the 'fixed ' keyword infront of that function . Compiler start complaining 'member ' can not be sealed because it is not an override . Am i doing any wrong here ? abstract public class ShapeBase { private ShapeDetails _shapedDetails ; public CampusCardBase ( ShapeDetails shDetails ) { _shapedDetails= shDetails ; } public virtual void Draw ( ) ; public virtual float getWidth ( ) ; public virtual void Swap ( ) ; public virtual void Erase ( ) ; public sealed ShapeDetails getShapeDetails ( ) { return _shapedDetails ; } } ;,C # inheritance questions "C_sharp : I 'm toying with the idea of making primitive .NET value types more type-safe and more `` self-documenting '' by wrapping them in custom structs . However , I 'm wondering if it 's actually ever worth the effort in real-world software . ( That `` effort '' can be seen below : Having to apply the same code pattern again and again . We 're declaring structs and so can not use inheritance to remove code repetition ; and since the overloaded operators must be declared static , they have to be defined for each type separately . ) Take this ( admittedly trivial ) example : Both Area and Length are basically a double , but augment it with a specific meaning . If you defined a method such as……it would not be possible to directly pass in an Area by accident . So far so good.BUT : You can easily sidestep this apparently improved type safety simply by casting a Area to double , or by temporarily storing an Area in a double variable , and then passing that into the method where a Length is expected : Question : Does anyone here have experience with extensive use of such custom struct types in real-world / production software ? If so : Has the wrapping of primitive value types in custom structs ever directly resulted in less bugs , or in more maintainable code , or given any other major advantage ( s ) ? Or are the benefits of custom structs too small for them to be used in practice ? P.S . : About 5 years have passed since I asked this question . I 'm posting some of my experiences that I 've made since then as a separate answer . struct Area { public static implicit operator Area ( double x ) { return new Area ( x ) ; } public static implicit operator double ( Area area ) { return area.x ; } private Area ( double x ) { this.x = x ; } private readonly double x ; } struct Length { public static implicit operator Length ( double x ) { return new Length ( x ) ; } public static implicit operator double ( Length length ) { return length.x ; } private Length ( double x ) { this.x = x ; } private readonly double x ; } Area CalculateAreaOfRectangleWith ( Length width , Length height ) Area a = 10.0 ; double aWithEvilPowers = a ; … = CalculateAreaOfRectangleWith ( ( double ) a , aWithEvilPowers ) ;",Type-proofing primitive .NET value types via custom structs : Is it worth the effort ? "C_sharp : through to stack-overflow questions but did n't get the proper answer.I need a separate Regex for before & after a matching string.1 ) Find word After a specific phrase/word ( this one working fine ) 2 ) Find word Before a specific phrase/word ( not working ) mytext= '' xyz '' Input= '' this is abc xyz defg '' output should be like that 1 ) for first , which is working xyz defg 2 ) second , which is not working abc xyz var regex = new Regex ( @ '' ( ? : '' + mytext + @ '' \s ) ( ? < word > \b\S+\b ) '' ) ; var regex = new Regex ( @ '' ( ? : \S+\s ) ? \S* '' + mytext + @ '' \b\S '' ) ;",How to find a word before matching string "C_sharp : This code takes about 8 seconds with a stream containing about 65K coming from a blob in a databaseThis code takes a few milliseconds : Why ? private string [ ] GetArray ( Stream stream ) { BinaryFormatter binaryFormatter = new BinaryFormatter ( ) ; object result = binaryFormatter.Deserialize ( stream ) ; return ( string [ ] ) result ; } private string [ ] GetArray ( Stream stream ) { BinaryFormatter binaryFormatter = new BinaryFormatter ( ) ; MemoryStream memoryStream = new MemoryStream ( ) ; Copy ( stream , memoryStream ) ; memoryStream.Position = 0 ; object result = binaryFormatter.Deserialize ( memoryStream ) ; return ( string [ ] ) result ; }",Why is copying a stream and then deserializing using a BinaryFormatter faster than just deserializing "C_sharp : I have some code that gives a user id to a utility that then send email to that user.MailException could be thrown for a number of reasons , problems with the email address , problems with the mail template etc.My question is this : do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception ( something computer-readable , not the description text ) that allows us to do different things based on what actually happened.Edit : As a clarification , the exceptions are n't for logs and what-not , this relates to how code reacts to them . To keep going with the mail example , let 's say that when we send mail it could fail because you do n't have an email address , or it could because you do n't have a valid email address , or it could fail.. etc.My code would want to react differently to each of these issues ( mostly by changing the message returned to the client , but actual logic as well ) .Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it ( an enum say ) that let the code distinguish what kind of issue it was . emailUtil.sendEmail ( userId , `` foo '' ) ; public void sendEmail ( String userId , String message ) throws MailException { /* ... logic that could throw a MailException */ }",Do you write exceptions for specific issues or general exceptions ? "C_sharp : I have actions that have different type parameters.And my request types are like this : Route is here : When I send request ( http : //localhost:52285/api/My/UpdateFeature ) via fiddler it returns HTTP/1.1 500 Internal Server ErrorError message is : { `` message '' : '' An error has occurred . `` , '' exceptionMessage '' : '' Multiple actions were found that match the request : \r\nUpdateFeature on type WebGUI.Controllers.MyController\r\nDeleteFeature on type WebGUI.Controllers.MyController '' , '' exceptionType '' : '' System.InvalidOperationException '' , '' stackTrace '' : '' ... .. public class MyController : ApiController { [ HttpPost ] public UpdateFeatureResponse UpdateFeature ( UpdateFeatureResuest reqResuest ) { return new UpdateFeatureResponse { IsSuccess = true } ; } [ HttpPost ] public DeleteFeatureResponse DeleteFeature ( DeleteFeatureRequest request ) { return new DeleteFeatureResponse { IsSuccess = true } ; } } public class UpdateFeatureResuest { public int Id { get ; set ; } public string Feature { get ; set ; } } public class UpdateFeatureResponse { public bool IsSuccess { get ; set ; } } public class DeleteFeatureRequest { public int Id { get ; set ; } } public class DeleteFeatureResponse { public bool IsSuccess { get ; set ; } } config.Routes.MapHttpRoute ( name : `` DefaultApi '' , routeTemplate : `` api/ { controller } / { id } '' , defaults : new { id = RouteParameter.Optional } ) ;",Web Api Multiple actions were found "C_sharp : I 'm learning C # at the moment for a bit of fun and am trying to make a windows application that has a bit of a gui for running some python commands . Basically , I 'm trying to teach myself the guts of running a process and sending commands to it , as well as receiving commands from it.I have the following code at the moment : Running python.exe from a command prompt gives some introductory text that I 'd like to capture and send to a textbox in the windows form ( textBox1 ) . Basically , the goal is to have something that looks like the python console running from the windows app . When I do n't set UseShellExecute to false , a console pops up and everything runs fine ; however , when I set UseShellExecute to false in order to re-direct the input , all I get is that a console pops up very quickly and closes again.What am I doing wrong here ? Process p = new Process ( ) ; p.StartInfo.UseShellExecute = false ; p.StartInfo.RedirectStandardOutput = true ; p.StartInfo.FileName = `` C : /Python31/python.exe '' ; p.Start ( ) ; string output = p.StandardOutput.ReadToEnd ( ) ; p.WaitForExit ( ) ; textBox1.Text = output ;",Why does Shellexecute=false break this ? "C_sharp : I 'm new in developing Windows Phone app , so sorry if I do some silly mistakes.I ca n't play shoutcast on WP 8 , I already tried what suggested on someone else thread , but it does n't help . Here 's part of my code : ( though it could play no shoutcast one ) private static List < AudioTrack > _playList = new List < AudioTrack > { new AudioTrack ( new Uri ( `` http : //198.50.156.4:8062/ ; '' , UriKind.RelativeOrAbsolute ) , `` Radio Vision '' , null , null , null , null , EnabledPlayerControls.All ) , new AudioTrack ( new Uri ( `` http : //live.radiocosmobandung.com . :8001/cosmo '' , UriKind.RelativeOrAbsolute ) , `` Ardan Cosmo '' , null , null , null , null , EnabledPlayerControls.All ) , } ;",ca n't play shoutcast ip with port with backgroundAudio on Windows Phone 8 "C_sharp : EDIT : On 09/15/2013 - I am describing my scenario further broken into steps to help everybody understand my situation better . Added the source for whole application for download too . If you want to jump to the original question , scroll down to the last heading . Please let me know the questions . ThanksSummaryAlaska state Capital Juneau has a AST ( Alaska State Trooper ) headquarters building where they would like to show a large screen with a single number displayed and updated automatically . That number is called ( Crime Quotient Index ) or CQICQI is basically a calculated number to show the current crime situation of the state ... How it is calculated ? The program that runs the screen is a .NET WPF Application that is constantly receiving CrimeReport objects through a Hot IObservable stream.CQI is calculated per city and then a Sum ( ) for all cities is taken which is called States CQIHere are the steps of calculating the State CQIStep 1 - Receive crime dataCrimeReport is sent to the .NET Application each time a crime is reported . It has the following componentsDateTime of the crimeCity - City/County of JurisdictionSeverityLevel - Serious/NonSeriousEstimatedSolveTime - Estimated number of days AST determines it would take to solve the crime . So in this step , we subscribe to the IObservable and create instance of MainViewModelStep 2 - Group by city and do maths per cityAs you receive the Report , group it by city soCityDto is a DTO class that takes all its report for current city and calculates the City 's CQI.The calculation of City 's CQI is done by the following formula if Ratio of Total number serious crimes to Total number of Non serious crimes is less than 1 then City 's CQI = Ratio x Minimum of Estimated Solve time else City 's CQI = Ratio x Maximum Estimated Solve timeHere is class definition of CityDtoNow that we have City DTO objects maintaining City 's CQI values and exposing that live CQI through an IObservable , Alaska State 's Capital would like to Sum ( ) up all the Cities ' CQI to show it as Alaska 's CQI and show it live on the screen and Each crime reported anywhere in the City/County participating in CQI program should have an immediate effect on the State 's CQIStep 3 - Roll up cities ' data for stateNow we have to calculate the whole state 's CQI which is live updating on the big screen , we have State 's view model called MainViewModelConstraintsNot all cities in Alaska currently participate in state 's CQI program , but cities are enrolling day by day so I can not have List and adding all the cities regardless of enrollment is not practical either . So it is IObservable which maintains only those cities not only participating but also have sent at least one CrimeReport object.Full Source codeSource can be downloaded by clicking HereOriginally asked questionI have a single hot observable of multiple hot observables ... I would like an observable that when subscribed will keep its observer informed of the sum of all `` Latest '' decimal numbers from all observables inside.How can I achieve that ? I tried CombineLatest ( ... ) but could not get it right.Thanks IObservable < CrimeReport > reportSource = mainSource.Publish ( ) ; MainVM = new MainViewModel ( reportSource ) ; reportSource.Connect ( ) ; var cities = reportSource.GroupBy ( k = > k.City ) .Select ( g = > new CityDto ( g.Key , g ) ; internal class CityDto { public string CityName { get ; set ; } public IObservable < decimal > CityCqi { get ; set ; } public CityDto ( string cityName , IObservable < CrimeReport > cityReports ) { CityName = cityName ; // Get all serious and non serious crimes // var totalSeriousCrimes = cityReports.Where ( c = > c.Severity == CrimeSeverity.Serious ) .Scan ( 0 , ( p , _ ) = > p++ ) ; var totalnonSeriousCrimes = cityReports.Where ( c = > c.Severity == CrimeSeverity.NonSerious ) .Scan ( 0 , ( p , _ ) = > p++ ) ; // Get the ratio // var ratio = Observable.CombineLatest ( totalSeriousCrimes , totalnonSeriousCrimes , ( s , n ) = > n == 0 ? s : s/n ) ; // Avoding DivideByZero here // Get the minimum and maximum estimated solve time // var minEstimatedSolveTime = cityReports.Select ( c = > c.EstimatedSolveTime ) .Scan ( 5000 , ( p , n ) = > n < p ? n : p ) ; var maxEstimatedSolveTime = cityReports.Select ( c= > c.EstimatedSolveTime ) .Scan ( 0 , ( p , n ) = > n > p ? n : p ) ; //Time for the City 's CQI // CityCqi = Observable.CombineLatest ( ratio , minEstimatedSolveTime , maxEstimatedSolveTime , ( r , n , x ) = > r < 1.0 ? r * n : r * m ) ; } } internal class MainViewModel { public MainViewModel ( IObservable < CrimeReport > mainReport ) { /// Here is the snippet also mentioned in Step 2 // var cities = mainReport.GroupBy ( k = > k.City ) .Select ( g = > new CityDto ( g.Key , g ) ) ; ///// T h i s ///// Is //// Where //// I /// am /// Stuck // var allCqis = cities.Select ( c = > c.CityCqi ) ; // gives you IObservable < IObservable < decimal > > , /// Need to use latest of each observable in allCqi and sum them up //// How do I do it ? } } IObservable < IObservable < decimal > >",How to get Sum of `` last '' items of N hot Observable < decimal > instances ? C_sharp : I am making HTTP calls using the System.Net.Http.HttpClient . It seems that all calls must be asynchronous.Let 's say I have a project structure of the following : MVC Web App - > Business Layer - > Data LayerIn the Data Layer I am making HTTP calls to a Web API to return data and I end up using a function like this : this then goes through to the BusinessLayer : Then finally in the MVC controller : Do I really have to make every single function return a list of type Task < IList < Product > > leading up to my MVC controller ? As you can see in the MVC controller I have to retrieve the products initially with Task wrapped around them . The debugger looks kind of strange when I go to view the list of products through it . So then as you can see I convert them to a regular list of product.I am wondering if it is the correct thing to do to have all of my functions return type Task < IList < Product > > all the way up to my MVC controller or if there is a workaround so that my functions can still return the a standard list of product but continue to use the async capabilities of the HttpClient ? UPDATE : Is there anything wrong with doing the following : public async Task < IList < Product > > GetProducts ( ) { HttpResponseMessage response = await client.GetAsync ( `` api/products '' ) ; string data = await response.Content.ReadAsStringAsync ( ) ; IList < Product > products = JsonConvert.DeserializeObject < IList < Product > > ( data ) ; return products ; } public Task < IList < Product > > GetProducts ( string name = null ) { return _repository.GetProducts ( name ) ; } public IActionResult Index ( ) { Task < IList < Product > > ProductsTask = _manager.GetProducts ( ) ; IList < Product > ProductsNonTask = products.Result.ToList ( ) ; return View ( ) ; } public IList < Product > GetProducts ( ) { Task < HttpResponseMessage > response = client.GetAsync ( `` api/products '' ) ; if ( response.Result.IsSuccessStatusCode ) { string data = response.Result.Content.ReadAsStringAsync ( ) .Result ; IList < Product > products = JsonConvert.DeserializeObject < IList < Product > > ( data ) ; retVal = products ; } },Avoid returning type Task < Object > from an async function when using HttpClient "C_sharp : When trying to compile an Expression in a medium trust web app I 'm getting a MethodAccessException . Does anyone know of another way to compile an expression under medium trust or a workaround to avoid this exception ? The code that throws the exception : The variable plan is an Expression that represents the following execution plan : The full stack trace : Expression < Func < object > > efn = Expression.Lambda < Func < object > > ( Expression.Convert ( ( plan , typeof ( object ) ) ) ; Func < object > fn = efn.Compile ( ) ; // Exception thrown here { Convert ( Query ( MyProjectNamespace.MyDatabaseTableObject ) .Provider ) .Execute ( new QueryCommand ( `` SELECT [ t0 ] . [ LinkId ] , [ t0 ] . [ Url ] FROM [ dbo ] . [ MyDatabaseTable ] AS t0 '' , value ( System.String [ ] ) , r0 = > new MyDatabaseTableObject ( ) { Id = IIF ( r0.IsDBNull ( 0 ) , 0 , Convert ( ChangeType ( r0.GetValue ( 0 ) , System.Int32 ) ) ) , Url = IIF ( r0.IsDBNull ( 1 ) , null , Convert ( ChangeType ( r0.GetValue ( 1 ) , System.String ) ) ) } , value ( System.Collections.Generic.List [ System.String ] ) ) , new [ ] { } ) } at System.Reflection.MethodBase.PerformSecurityCheck ( Object obj , RuntimeMethodHandle method , IntPtr parent , UInt32 invocationFlags ) at System.Reflection.RuntimeConstructorInfo.Invoke ( BindingFlags invokeAttr , Binder binder , Object [ ] parameters , CultureInfo culture ) at System.RuntimeType.CreateInstanceImpl ( BindingFlags bindingAttr , Binder binder , Object [ ] args , CultureInfo culture , Object [ ] activationAttributes ) at System.Activator.CreateInstance ( Type type , BindingFlags bindingAttr , Binder binder , Object [ ] args , CultureInfo culture , Object [ ] activationAttributes ) at System.Linq.Expressions.ExpressionCompiler.AddGlobal ( Type type , Object value ) at System.Linq.Expressions.ExpressionCompiler.GenerateConstant ( ILGenerator gen , Type type , Object value , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateConstant ( ILGenerator gen , ConstantExpression c , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateArgs ( ILGenerator gen , ParameterInfo [ ] pis , ReadOnlyCollection ` 1 args ) at System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall ( ILGenerator gen , MethodInfo mi , ReadOnlyCollection ` 1 args , Type objectType ) at System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall ( ILGenerator gen , MethodCallExpression mc , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateConvert ( ILGenerator gen , UnaryExpression u ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateConditional ( ILGenerator gen , ConditionalExpression b ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateMemberAssignment ( ILGenerator gen , MemberAssignment binding , Type objectType ) at System.Linq.Expressions.ExpressionCompiler.GenerateBinding ( ILGenerator gen , MemberBinding binding , Type objectType ) at System.Linq.Expressions.ExpressionCompiler.GenerateMemberInit ( ILGenerator gen , ReadOnlyCollection ` 1 bindings , Boolean keepOnStack , Type objectType ) at System.Linq.Expressions.ExpressionCompiler.GenerateMemberInit ( ILGenerator gen , MemberInitExpression init ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateLambda ( LambdaExpression lambda ) at System.Linq.Expressions.ExpressionCompiler.GenerateCreateDelegate ( ILGenerator gen , LambdaExpression lambda ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateArgs ( ILGenerator gen , ParameterInfo [ ] pis , ReadOnlyCollection ` 1 args ) at System.Linq.Expressions.ExpressionCompiler.GenerateNew ( ILGenerator gen , NewExpression nex , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateArgs ( ILGenerator gen , ParameterInfo [ ] pis , ReadOnlyCollection ` 1 args ) at System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall ( ILGenerator gen , MethodInfo mi , ReadOnlyCollection ` 1 args , Type objectType ) at System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall ( ILGenerator gen , MethodCallExpression mc , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateConvert ( ILGenerator gen , UnaryExpression u ) at System.Linq.Expressions.ExpressionCompiler.Generate ( ILGenerator gen , Expression node , StackType ask ) at System.Linq.Expressions.ExpressionCompiler.GenerateLambda ( LambdaExpression lambda ) at System.Linq.Expressions.ExpressionCompiler.CompileDynamicLambda ( LambdaExpression lambda ) at System.Linq.Expressions.Expression ` 1.Compile ( ) at SubSonic.Linq.Structure.DbQueryProvider.Execute ( Expression expression ) at SubSonic.Linq.Structure.QueryProvider.System.Linq.IQueryProvider.Execute ( Expression expression ) at SubSonic.Linq.Structure.Query ` 1.GetEnumerator ( ) at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) at WebApplication1._Default.Page_Load ( Object sender , EventArgs e ) at System.Web.Util.CalliHelper.EventArgFunctionCaller ( IntPtr fp , Object o , Object t , EventArgs e ) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback ( Object sender , EventArgs e ) at System.Web.UI.Control.OnLoad ( EventArgs e ) at System.Web.UI.Control.LoadRecursive ( ) at System.Web.UI.Page.ProcessRequestMain ( Boolean includeStagesBeforeAsyncPoint , Boolean includeStagesAfterAsyncPoint )",Expression < TDelegate > .Compile in Medium Trust environment "C_sharp : I have been using the Entity Framework with the POCO First approach . I have pretty much followed the pattern described by Steve Sanderson in his book 'Pro ASP.NET MVC 3 Framework ' , using a DI container and DbContext class to connect to SQL Server.The underlying tables in SQL server contain very large datasets used by different applications . Because of this I have had to create views for the entities I need in my application : and this seems to work fine for most of my needs.The problem I have is that some of these views have a great deal of data in them so that when I call something like : it appears to be bringing back the entire data set , which can take some time before the LINQ query reduces the set to those which I need . This seems very inefficient when the criteria is only applicable to a few records and I am getting the entire data set back from SQL server.I have tried to work around this by using stored procedures , such aswhilst this is much quicker , the problem here is that it does n't return a DbSet and so I lose all of the connectivity between my objects , e.g . I ca n't reference any associated objects such as orders or contacts even if I include their IDs because the return type is a collection of 'Customers ' rather than a DbSet of them.Does anyone have a better way of getting SQL server to do the querying so that I am not passing loads of unused data around ? class RemoteServerContext : DbContext { public DbSet < Customer > Customers { get ; set ; } public DbSet < Order > Orders { get ; set ; } public DbSet < Contact > Contacts { get ; set ; } ... protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Entity < Customer > ( ) .ToTable ( `` vw_Customers '' ) ; modelBuilder.Entity < Order > ( ) .ToTable ( `` vw_Orders '' ) ; ... } } var customers = _repository.Customers ( ) .Where ( c = > c.Location == location ) .Where ( ... ) ; public IEnumerable < Customer > CustomersThatMatchACriteria ( string criteria1 , string criteria2 , ... ) //or an object passed in ! { return Database.SqlQuery < Customer > ( `` Exec pp_GetCustomersForCriteria @ crit1 = { 0 } , @ crit2 = { 1 } ... '' , criteria1 , criteria2 , ... ) ; }",Improving efficiency with Entity Framework "C_sharp : I 've few doubts regarding how shared IEnumerable and IQueryable is accessed in multi-threaded application.Consider this code snippet.As you can see , I 'm using BeginInvoke ( ) passing the same instance allFilePatterns to each handler called sfile.SomeHandler . Suppose in SomeHandler , I iterate allFilePatterns in a foreach loop , something like this : Now my doubt is that : since BeginInvoke ( ) is asynchronous , that means all foreach in all SomeHandler of all the files would execute parallelly ( each in its own thread ) , would the shared instance of IEnumerable enumerate as expected/normal ? Is this a right approach ? Can I share same instance of IEnumerable in multiple threads , and enumerate it parallelly ? And what if I use IQueryable instead of IEnumerable in the above code ? Any side-effect that I should be aware of ? If its not thread-safe , then what should I use ? Please note that I 'm using IQueryable for database queries , as I do n't want to pull all the data from database . Therefore , I want to avoid IQueryable.ToList ( ) as much as possible . ObservableCollection < SessionFile > files = /* some code */IEnumerable < Pattern > allFilePatterns= /*some query */foreach ( Pattern pattern in allFilePatterns ) { string iclFilePath = Path.Combine ( pattern.Location , pattern.Filename ) ; SessionFile sfile = new SessionFile ( iclFilePath , pattern.AnalysisDate ) ; SomeDelegate invoker = new SomeDelegate ( sfile.SomeHandler ) ; invoker.BeginInvoke ( allFilePatterns , null , null ) ; files.Add ( sfile ) ; } void SomeHandler ( IEnumerable < Pattern > allFilePatterns ) { foreach ( Pattern pattern in allFilePatterns ) { //some code } }",Shared IEnumerable < T > and IQueryable < T > in a multi-threaded application "C_sharp : I have a int number And I have to shift it to the right a couple of times.I would like to get the value bit value that has been removed . I would have to get : 1 , 1 , 0How can I get the removed value x = 27 = 11011x > > 1= 13 = 1101x > > 2= 6 = 110x > > 3= 3 = 11",How to get the bit removed from the bitwise right shift in c # C_sharp : I want to implement this partial method in my Linq table class . My hope is that is it called right before an insert . Can anyone tell me when the OnValidate method is called ? Update 1I understand that I can check the enum to see what action causes it to fire . But WHEN does it get called ? I need to know if it gets called each time someone submits changes or what ? partial void OnValidate ( System.Data.Linq.ChangeAction action ) ;,When is OnValidate called in Linq ? "C_sharp : I am trying to debug a SQL response which is throwing an error : Conversion failed when converting the varchar value ' 0.01 ' to data type bit.That does not make a lot of sense as object does not have any bools.Code : SQL that gets executed ( I manually added parameters ) : I placed breakpoint on where read happens ( connection.Query < Rate > ( query , parameters ) ) , then enabled break on exceptions and when it failed jumped deeper into stack to TdsParser TryRun ( ) ( couple levels higher where exception is thrown ) System.Data.dll ! System.Data.SqlClient.TdsParser.TryRun ( System.Data.SqlClient.RunBehavior runBehavior , System.Data.SqlClient.SqlCommand cmdHandler , System.Data.SqlClient.SqlDataReader dataStream , System.Data.SqlClient.BulkCopySimpleResultSet bulkCopyHandler , System.Data.SqlClient.TdsParserStateObject stateObj , out bool dataReady ) + 0x1ce1 bytes At this point I have access to dataStream which is SqlDataReader I am looking for a way to output 'raw ' result right out of SqlDataReader , something like but for SqlDataReader.EDITas per request in comment SQLEDIT2 : For those who are wondering what was the causestatement was actually being converted to this by additional mechanism this then would fail with error when there was no row by selecting not top 1 like it was intended but row after that then would n't cast to bitQuestion still stands : How do I write SqlDataReader when debugging on the fly to immediate window ? using ( var connection = _connectionProvider.GetDbConnection ( ) ) { connection.Open ( ) ; return connection.Query < Rate > ( query , parameters ) ; } select * from ( select top 1 BuildNumber , RateVersion , SampleId , Tariff , TariffStepName , Factor1 , Result1 from dbo.Rateswhere Tariff = 'Default ' and TariffStepName = 'I_P ' and ( RateVersion < = 1 ) and Factor1 = 'false ' and ( SampleId is null ) order by RateVersion desc , sampleId desc ) top1 System.Diagnostics.Debug.WriteLine ( ( new System.IO.StreamReader ( stream ) ) .ReadToEnd ( ) ) ; public class Rate { public string Tariff { get ; set ; } public string TariffStepName { get ; set ; } public string Factor1 { get ; set ; } public string Factor2 { get ; set ; } public string Factor3 { get ; set ; } public string Factor4 { get ; set ; } public string Factor5 { get ; set ; } public string Factor6 { get ; set ; } public string Factor7 { get ; set ; } public string Factor8 { get ; set ; } public string Factor9 { get ; set ; } public string Factor10 { get ; set ; } public decimal Result1 { get ; set ; } public decimal Result2 { get ; set ; } public decimal Result3 { get ; set ; } public decimal Result4 { get ; set ; } public decimal Result5 { get ; set ; } public decimal Result6 { get ; set ; } public decimal Result7 { get ; set ; } public decimal Result8 { get ; set ; } public decimal Result9 { get ; set ; } public decimal Result10 { get ; set ; } public string TextResult1 { get ; set ; } public string TextResult2 { get ; set ; } public string TextResult3 { get ; set ; } public string TextResult4 { get ; set ; } public string TextResult5 { get ; set ; } public int ? SampleId { get ; set ; } public int BuildNumber { get ; set ; } public decimal ? RateVersion { get ; set ; } } CREATE TABLE dbo . [ Rates ] ( [ BuildNumber ] [ int ] NOT NULL , [ Tariff ] [ varchar ] ( 30 ) NOT NULL , [ TariffStepName ] [ varchar ] ( 60 ) NOT NULL , [ Factor1 ] [ varchar ] ( 50 ) NOT NULL , [ Factor2 ] [ varchar ] ( 50 ) NULL , [ Factor3 ] [ varchar ] ( 50 ) NULL , [ Factor4 ] [ varchar ] ( 50 ) NULL , [ Factor5 ] [ varchar ] ( 50 ) NULL , [ Factor6 ] [ varchar ] ( 50 ) NULL , [ Factor7 ] [ varchar ] ( 50 ) NULL , [ Factor8 ] [ varchar ] ( 50 ) NULL , [ Factor9 ] [ varchar ] ( 50 ) NULL , [ Factor10 ] [ varchar ] ( 50 ) NULL , [ Result1 ] [ varchar ] ( 50 ) NULL , [ Result2 ] [ decimal ] ( 19 , 6 ) NULL , [ Result3 ] [ decimal ] ( 19 , 6 ) NULL , [ Result4 ] [ decimal ] ( 19 , 6 ) NULL , [ Result5 ] [ decimal ] ( 19 , 6 ) NULL , [ Result6 ] [ decimal ] ( 19 , 6 ) NULL , [ Result7 ] [ decimal ] ( 19 , 6 ) NULL , [ Result8 ] [ decimal ] ( 19 , 6 ) NULL , [ Result9 ] [ decimal ] ( 19 , 6 ) NULL , [ Result10 ] [ decimal ] ( 19 , 6 ) NULL , [ RateVersion ] [ decimal ] ( 18 , 2 ) NULL , [ SampleId ] [ int ] NULL , [ TextResult1 ] [ varchar ] ( 50 ) NULL , [ TextResult2 ] [ varchar ] ( 50 ) NULL , [ TextResult3 ] [ varchar ] ( 50 ) NULL , [ TextResult4 ] [ varchar ] ( 50 ) NULL , [ TextResult5 ] [ varchar ] ( 50 ) NULL ) exec sp_executesql N'select * from ( select top 1 BuildNumber , RateVersion , SampleId , Tariff , TariffStepName , Factor1 , Result1 from dbo.Rateswhere Tariff = @ Tariff and TariffStepName = @ TariffStepName and ( RateVersion < = @ RV ) and Factor1 = @ Factor1 and ( SampleId is null ) order by RateVersion desc , sampleId desc ) top1 ' , N ' @ Tariff varchar ( 50 ) , @ TariffStepName varchar ( 50 ) , @ RV decimal ( 3,2 ) , @ Factor1 bit ' , @ Tariff='Default ' , @ TariffStepName='I_P ' , @ RV=1.00 , @ Factor1=0go",Write SqlDataReader to immediate window c # "C_sharp : We have a custom TraceListener ( inherited from System.Diagnostics.TraceListener ) which we use for our ASP.NET web application logging . It 's been working great - no issues . Then all the sudden it stopped working in our dev environment ( TraceListener.TraceEvent ( ) stopped firing ) . We are baffled as to why it stopped working . The only changes we really made in code was added more build configurations ( Dev , Test , Stage , Prod ) . Before , it only had Debug and Release.I notice that when I test locally having built using the Debug configuration , TraceListener.TraceEvent ( ) is fired just fine . When I switch to another build configuration ( i.e . Test ) , then TraceEvent ( ) is never fired anymore . Here 's a snippet of my web .csproj file : I 'm not sure why switching build configurations seems to turn off our logging . Can anyone point me in the right direction ? < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Debug|AnyCPU ' `` > < DebugSymbols > true < /DebugSymbols > < DebugType > full < /DebugType > < Optimize > false < /Optimize > < OutputPath > bin\ < /OutputPath > < DefineConstants > TRACE ; DEBUG ; SkipPostSharp < /DefineConstants > < ErrorReport > prompt < /ErrorReport > < WarningLevel > 4 < /WarningLevel > < ExcludeGeneratedDebugSymbol > false < /ExcludeGeneratedDebugSymbol > < PlatformTarget > AnyCPU < /PlatformTarget > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Dev|AnyCPU ' '' > < OutputPath > bin\ < /OutputPath > < DefineConstants > TRACE < /DefineConstants > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Test|AnyCPU ' '' > < DebugSymbols > true < /DebugSymbols > < DebugType > full < /DebugType > < Optimize > false < /Optimize > < OutputPath > bin\ < /OutputPath > < DefineConstants > TRACE ; DEBUG ; SkipPostSharp < /DefineConstants > < ErrorReport > prompt < /ErrorReport > < WarningLevel > 4 < /WarningLevel > < ExcludeGeneratedDebugSymbol > false < /ExcludeGeneratedDebugSymbol > < PlatformTarget > AnyCPU < /PlatformTarget > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Stage|AnyCPU ' '' > < OutputPath > bin\ < /OutputPath > < DefineConstants > TRACE < /DefineConstants > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Prod|AnyCPU ' '' > < OutputPath > bin\ < /OutputPath > < DefineConstants > TRACE < /DefineConstants > < /PropertyGroup > < PropertyGroup Condition= '' ' $ ( Configuration ) | $ ( Platform ) ' == 'Release|AnyCPU ' '' > < OutputPath > bin\ < /OutputPath > < DefineConstants > TRACE < /DefineConstants > < /PropertyGroup >",.Net Custom TraceListener.TraceEvent not firing "C_sharp : Zoran Horvat proposed the usage of the Either type to avoid null checks and to not forget to handle problems during the execution of an operation . Either is common in functional programming.To illustrate its usage , Zoran shows an example similar to this : As you see , the Operation returns Either < Failture , Resource > that can later be used to form a single value without forgetting to handle the case in which the operation has failed . Notice that all the failures derive from the Failure class , in case there are several of them.The problem with this approach is that consuming the value can be difficult.I 'm showcasing the complexity with a simple program : Please , notice that this sample does n't user the Either type at all , but the author himself told me that it 's possible to do that.Precisely , I would like to convert the sample above the Evaluation to use Either.In other words , I want to convert my code to use Either and use it properlyNOTEIt makes sense to have a Failure class that contains the information about the eventual error and a Success class that contains the int valueExtraIt would be very interesting that a Failure could contain a summary of all the problems that may have occurred during the evaluation . This behavior would be awesome to give the caller more information about the failure . Not only the first failing operation , but also the subsequent failures . I think of compilers during a semantic analysis . I would n't want the stage to bail out on the first error it detects , but to gather all the problems for better experience . void Main ( ) { var result = Operation ( ) ; var str = result .MapLeft ( failure = > $ '' An error has ocurred { failure } '' ) .Reduce ( resource = > resource.Data ) ; Console.WriteLine ( str ) ; } Either < Failed , Resource > Operation ( ) { return new Right < Failed , Resource > ( new Resource ( `` Success '' ) ) ; } class Failed { } class NotFound : Failed { } class Resource { public string Data { get ; } public Resource ( string data ) { this.Data = data ; } } public abstract class Either < TLeft , TRight > { public abstract Either < TNewLeft , TRight > MapLeft < TNewLeft > ( Func < TLeft , TNewLeft > mapping ) ; public abstract Either < TLeft , TNewRight > MapRight < TNewRight > ( Func < TRight , TNewRight > mapping ) ; public abstract TLeft Reduce ( Func < TRight , TLeft > mapping ) ; } public class Left < TLeft , TRight > : Either < TLeft , TRight > { TLeft Value { get ; } public Left ( TLeft value ) { this.Value = value ; } public override Either < TNewLeft , TRight > MapLeft < TNewLeft > ( Func < TLeft , TNewLeft > mapping ) = > new Left < TNewLeft , TRight > ( mapping ( this.Value ) ) ; public override Either < TLeft , TNewRight > MapRight < TNewRight > ( Func < TRight , TNewRight > mapping ) = > new Left < TLeft , TNewRight > ( this.Value ) ; public override TLeft Reduce ( Func < TRight , TLeft > mapping ) = > this.Value ; } public class Right < TLeft , TRight > : Either < TLeft , TRight > { TRight Value { get ; } public Right ( TRight value ) { this.Value = value ; } public override Either < TNewLeft , TRight > MapLeft < TNewLeft > ( Func < TLeft , TNewLeft > mapping ) = > new Right < TNewLeft , TRight > ( this.Value ) ; public override Either < TLeft , TNewRight > MapRight < TNewRight > ( Func < TRight , TNewRight > mapping ) = > new Right < TLeft , TNewRight > ( mapping ( this.Value ) ) ; public override TLeft Reduce ( Func < TRight , TLeft > mapping ) = > mapping ( this.Value ) ; } void Main ( ) { var result = Evaluate ( ) ; Console.WriteLine ( result ) ; } int Evaluate ( ) { var result = Op1 ( ) + Op2 ( ) ; return result ; } int Op1 ( ) { Throw.ExceptionRandomly ( `` Op1 failed '' ) ; return 1 ; } int Op2 ( ) { Throw.ExceptionRandomly ( `` Op2 failed '' ) ; return 2 ; } class Throw { static Random random = new Random ( ) ; public static void ExceptionRandomly ( string message ) { if ( random.Next ( 0 , 3 ) == 0 ) { throw new InvalidOperationException ( message ) ; } } }",How to use the Either type in C # ? "C_sharp : I have a project which contains two F # projects and a C # project in which I 'd like to write some XUnit tests : FS_PL : F # 3.1 ( 3.3.1.0 ) Portable LibraryFS_PL_Legacy : F # 31 . ( 2.3.5.1 ) Portable Library ( Legacy ) Tests : C # .NET 4.5/Win8 C # Portable Class Library ( PCL ) I am unable to add a reference from Tests to either of the F # libraries.When I try to add a reference to FS_PL , I am presented with a dialog that states `` Unable to add a reference to project 'FS_PL ' . The targets of Portable Library project 'FS_PL ' are not the same or compatible with the targets of the current Portable Library project '' : This is odd since both my Tests and FS_PL libraries are configured to target .NET 4.5 & Windows 8.So I created FS_PL_Legacy and tried adding a reference to it . Doing so gives me a very 'helpful ' message stating `` Unable to add a reference to project 'FS_PL_Legacy ' '' : Does anyone know what I am doing wrong ? Partial Workaround # 1Using miegirl 's workaround from a Connect issue discussing this problem , I added the following to the C # project : This at least allows VS to reference the F # projects , but those projects are tagged with several warnings and the C # portable library is unable to build as it can not reference the types in one or both of the F # libraries : ( Most of the warnings in the build output window indicate that the F # libraries can not be referenced as they appear to have `` an indirect dependency on the framework assembly `` [ System.Threading/System.Lync/etc . ] '' which could not be resolved in the currently targeted framework '' < ItemGroup > < ! -- Manually added reference to F # projects to overcome issue discussed here : http : //stackoverflow.com/questions/23111782/how-do-i-add-a-reference-to-f-portable-library-from-c-sharp-portable-class-libr -- > < ProjectReference Include= '' ..\FS_PL\FS_PL.fsproj '' > < Project > { 2c4b1776-3d34-4534-8520-8a1e6daa0e6e } < /Project > < Name > FS_PL < /Name > < /ProjectReference > < ProjectReference Include= '' ..\FS_PL_Legacy\FS_PL_Legacy.fsproj '' > < Project > { 0d7b657c-906b-4448-ae64-2153a1fa910c } < /Project > < Name > FS_PL_Legacy < /Name > < /ProjectReference > < /ItemGroup >",How do I add a reference to F # Portable Library from C # Portable Class Library ( PCL ) "C_sharp : I have an Windows Installer for my application . Application package also contains Installer class where some of the actions are performed other are performed in Custom Actions . The Installer installs another application from Custom Actions during Install . I want to know if this application already exists of same version I do n't want to install or provide a Messagebox asknig to Reinstall Y/N . If my application is already installed , and I click the same installer again , I get `` Repair '' and `` Remove '' options . But if the installer is newly built , I get a dialog stating `` Another version is already installed ... remove using Add Remove Programs.. '' . So I ca n't update the exisitng version without uninstallng it . How can I update the existing version ? Any help or guidance for these 2 queries are highly appreciated . I looked on net for these but could n't get apropriae answers . If you can help me , that would be really great.CODE prouct.xmlpackage.xmlUPDATE : I want to install XYZ if it is not alerady installed on PC . With the Above code it does n't install as Prerequisite . In Prerequisite I select my appication ( along with Windows Installer 3.1 & .NET3.5 ) and have selected `` Download prereq from same location as my appli '' . On Build of setup project , I get 3 folders in my Rel ( for winIns , Net & my app o be installed as preq i.e . XYZ ) . Currently XYZ is not installed on my comp - so the key will not be found . When I install the installer , it installs the app but not the prereq i.e XYZ.exe application . Where am I going wrong ? Thanks . < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Product xmlns= '' http : //schemas.microsoft.com/developer/2004/01/bootstrapper '' ProductCode= '' My.Bootstrapper.ABC '' > < ! -- Create Package , Product Manifest http : //msdn.microsoft.com/en-us/library/ee335702.aspx Schema Reference : http : //msdn.microsoft.com/en-us/library/ms229223.aspx -- > < PackageFiles > < PackageFile Name= '' XYZ.exe '' / > < /PackageFiles > < InstallChecks > < ! -- If its installed , it will be in Uninstall . DisplayName will be XYZ2.1_rc22 Can still get values of DisplayVersion ( 2.1_rc22 ) & UninstallString from this key -- > < RegistryCheck Property= '' IS_XYZ_INSTALLED '' Key= '' HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\XYZ '' Value= '' DisplayName '' / > < /InstallChecks > < Commands > < Command PackageFile= '' XYZ.exe '' Arguments= '' /Install '' > < InstallConditions > < BypassIf Property= '' IS_XYZ_INSTALLED '' Compare= '' ValueEqualTo '' Value= '' XYZ2.1_rc22 '' / > // tHIS IS THE DISPLAYNAME , THAT I SEE IN REGISTY < FailIf Property= '' AdminUser '' Compare= '' ValueNotEqualTo '' Value= '' True '' String= '' NotAnAdmin '' / > < /InstallConditions > < ExitCodes > < ExitCode Value= '' 0 '' Result= '' Success '' / > < ExitCode Value= '' 1641 '' Result= '' SuccessReboot '' / > < ExitCode Value= '' 3010 '' Result= '' SuccessReboot '' / > < DefaultExitCode Result= '' Fail '' String= '' GeneralFailure '' / > < /ExitCodes > < /Command > < /Commands > < /Product > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < Package xmlns= '' http : //schemas.microsoft.com/developer/2004/01/bootstrapper '' Name= '' DisplayName '' Culture= '' Culture '' > < ! -- Check for XYZversion 2.1_rc22 -- > < Strings > < String Name= '' DisplayName '' > Install My XYZ < /String > < String Name= '' Culture '' > en < /String > < String Name= '' NotAnAdmin '' > Administrator permissions are required to install XYZ.Contact your administrator. < /String > < String Name= '' GeneralFailure '' > A general error has occurred while installing this package. < /String > < /Strings > < /Package >",Issues regarding Installing an Application via Windows Installer "C_sharp : I would like to order the parents by the lowest age of their children , proceeding to the second or third child in the case of a tie.The closest I 've come is this , which only orders by the youngest child : This does n't account for second ( or third , etc ) youngest in the case of a tie.Given these 3 parents with corresponding child ages , I 'd like them to come out in this order.P1 1,2,7P2 1,3,6P3 1,4,5 Parent { List < Child > Children { get ; set ; } } Child { int Age { get ; set ; } } parents.OrderBy ( p = > p.Children.Min ( c = > c.Age ) )",Order parent collection by minimum values in child collection in Linq "C_sharp : This is a weird one I encountered in some legacy code that I 've ear-marked for re-factor . I 've checked it over and the code is not using .ConfigureAwait ( false ) ..The code in question looks much like this : ( The `` testx = ... . '' lines are part of debugging the issue to expose the behaviour . ) The calls themselves are simple queries against EF through the same lookup service . Given that they are EF and use the same UoW / DbContext , these can not be changed to use Task.WhenAll ( ) .Expected Results : True for test1 - > test7Actual Results : True for test1 , - > test3 , False for test4 - > test7The issue was discovered when I added a validation against a particular role after the awaited lookup calls . The check tripped a null reference exception on HttpContext.Current which the validation method uses . So it passed when used in the ValidateRoleAccess call before the async , but failed if called after all the awaited methods.I varied the order of the methods and it failed after either 2 or 3 awaits , with no particular culprit methods . The app is targeting .Net 4.6.1 . This is a non-blocking issue as I was able to perform the role check prior to the awaits , put the result in a variable , and reference the variable after the awaits , but it was a very unexpected `` gotcha '' to work after 1-2 awaits , but not more . The code will be getting re-factored since the async calls are n't needed for those lookups , neither are returning the whole entities , but I 'm still very curious if there is an explanation why the HttpContext would be `` lost '' after a couple of awaited tasks with .ConfigureAwait ( false ) was not used.Update 1 : The plot thickens..I adjusted the test calls to add the test Boolean results to a List then repeated the set of loads for 5 iterations . I wanted to see if once it tripped to `` False '' if it ever returned to `` True '' at some point . My thinking is that the await was resuming on a different Thread that did n't have a reference to the current HttpContext , however no matter how many iterations I added , once false , it was always false . So next I tried repeating the first call ( GetAllDecisions ) 10 times ... Surprisingly the first 10 iterations all came back as True ? ! So I took a more close look at varying the order to see if there were calls that were reliably tripping it up , and it turns out there were 3 of them.so for instance : returned True , True , True but then changing that to : returned False , False , False.Digging a little deeper I noticed that the methods were a mix of EntityFramework and older NHibernate-based repository code . It was the EntityFramework async methods that were tripping up the context on await.One of the methods that trips up the Context after an await : as did : *edit -whups that was a duplicate copy/paste : ) Yet this was fine : Looking at the code that `` works '' it 's pretty clear that it 's not actually doing anything Async given the Task.FromResult against a synchronous method . I think the original authors were caught in the allure of the async silver-bullet and just wrapped the older code for consistency . EF 's async methods work with await , but where async/await would seem to be supported with HttpContext.Current so long as < httpRuntime targetFramework= '' 4.5 '' / > , EF seems to trip this assumption up . public async Task < ActionResult > Index ( ) { ValidateRoleAccess ( Roles.Admin , Roles.AuthorizedUser , Roles.AuditReadOnly ) ; var test1 = System.Web.HttpContext.Current ! = null var decisions = await _lookupService.GetAllDecisions ( ) ; var test2 = System.Web.HttpContext.Current ! = null var statuses = await _lookupService.GetAllEnquiryStatuses ( ) ; var test3 = System.Web.HttpContext.Current ! = null var eeoGroups = await _lookupService.GetEEOGroups ( ) ; var test4 = System.Web.HttpContext.Current ! = null var subCategories = await _lookupService.GetEnquiryTypeSubCategories ( ) ; var test5 = System.Web.HttpContext.Current ! = null var paystreams = await _lookupService.GetPaystreams ( ) ; var test6 = System.Web.HttpContext.Current ! = null var hhses = await _lookupService.GetAllHHS ( ) ; var test7 = System.Web.HttpContext.Current ! = null // ... var decisions = await _lookupService.GetAllDecisions ( ) ; results.Add ( System.Web.HttpContext.Current ! = null ) ; decisions = await _lookupService.GetAllDecisions ( ) ; results.Add ( System.Web.HttpContext.Current ! = null ) ; decisions = await _lookupService.GetAllDecisions ( ) ; results.Add ( System.Web.HttpContext.Current ! = null ) ; var eeoGroups = _lookupService.GetEEOGroups ( ) ; results.Add ( System.Web.HttpContext.Current ! = null ) ; eeoGroups = _lookupService.GetEEOGroups ( ) ; results.Add ( System.Web.HttpContext.Current ! = null ) ; eeoGroups = _lookupService.GetEEOGroups ( ) ; results.Add ( System.Web.HttpContext.Current ! = null ) ; public async Task < List < string > > GetEEOGroups ( ) { return await _dbContext.EmployeeEEOGroup.GroupBy ( e = > e.EEOGroup ) .Select ( g = > g.FirstOrDefault ( ) .EEOGroup ) .ToListAsync ( ) ; } public async Task < IEnumerable < SapHHS > > GetAllHHS ( ) { return await _dbContext.HHS.Where ( x = > x.IsActive ) .ToListAsync ( ) ; } public async Task < IEnumerable < Decision > > GetAllDecisions ( ) { return await Task.FromResult ( _repository.Session.QueryOver < Lookup > ( ) .Where ( l = > l.Type == `` Decision '' & & l.IsActive ) .List ( ) .Select ( l = > new Decision { DecisionId = l.Id , Description = l.Name } ) .ToList ( ) ) ; }",HTTPContext.Current in controller is null after multiple awaits "C_sharp : I am currently using ANTLR4 in C # but I am facing a problem , I do n't know how to get the the object/class IParseTree.I find in C # the fully qualified name here is Antlr4.Runtime.Tree.IParseTree but how to get the object ? Can you please help ? AntlrInputStream inputStream = new AntlrInputStream ( sSpinTexte ) ; SpinParserLexer SpinLexer = new SpinParserLexer ( inputStream ) ; CommonTokenStream commonTokenStream = new CommonTokenStream ( SpinLexer ) ; SpinParserParser SpinParser = new SpinParserParser ( commonTokenStream ) ; IParseTree tree = ? ? ? ? ?",How to get IParseTree in ANTLR4 ? "C_sharp : I have a very simple image processing application . I am trying to remove the pixels which do not involve red tones.So far a basic code seems to achieve what I want . Basically if the difference of ( red and blue ) or ( red and green ) is less than a threshold it sets the pixel to white . My results seems to be promising however I am wondering if there is a better solution for determining whether a pixel involves red tones in it.My results for a threshold value of 75 is Any algorithm or thought will be very appreciated . Thanks in advance private void removeUnRedCellsBtn_Click ( object sender , EventArgs e ) { byte threshold = Convert.ToByte ( diffTxtBox.Text ) ; byte r , g , b ; for ( int i = 0 ; i < m_Bitmap.Width ; i++ ) { for ( int j = 0 ; j < m_Bitmap.Height ; j++ ) { r = im_matrix [ i , j ] .R ; g = im_matrix [ i , j ] .G ; b = im_matrix [ i , j ] .B ; if ( ( r - b ) < threshold || ( r - g ) < threshold ) { m_Bitmap.SetPixel ( i , j , Color.White ) ; } } } pictureArea_PictureBox.Image = m_Bitmap ; }",Removing non red toned pixels "C_sharp : I am trying to write a test that verifies that either Foo or FooAsync were called . I do n't care which one , but I need to make sure at least one of those methods were called.Is it possible to get Verify to do this ? So I have : If I try to write a test : I could try and catch the assertion exception , but that seems like a really odd work around . Is there an extension method for moq that would do this for me ? Or is there anyway to get the method invocation count ? public interface IExample { void Foo ( ) ; Task FooAsync ( ) ; } public class Thing { public Thing ( IExample example ) { if ( DateTime.Now.Hours > 5 ) example.Foo ( ) ; else example.FooAsync ( ) .Wait ( ) ; } } [ TestFixture ] public class Test { [ Test ] public void VerifyFooOrFooAsyncCalled ( ) { var mockExample = new Mock < IExample > ( ) ; new Thing ( mockExample.Object ) ; //use mockExample to verify either Foo ( ) or FooAsync ( ) was called //is there a better way to do this then to catch the exception ? ? ? try { mockExample.Verify ( e = > e.Foo ( ) ) ; } catch { mockExample.Verify ( e = > e.FooAsync ( ) ; } } }",Use Moq to Verify if either method was called "C_sharp : I 'm working with a class library called DDay ICal.It is a C # wrapper for the iCalendar System implemented in Outlook Calendars , and many many many more systems.My question is derived from some work I was doing with this system.There are 3 objects in question hereIRecurrencePattern - InterfaceRecurrencePattern - Implementation of IRecurrencePattern InterfaceDbRecurPatt - Custom Class that has an implicit type operatorIRecurrencePattern : Not all code is shownRecurrencePattern : Not all code is shownDbRecurPatt : Not all code is shownThe confusing part : Through out DDay.ICal system they are using ILists to contain a collection of Recurrence patterns for each event in the calendar , the custom class is used to fetch information from a database and then it is cast to the Recurrence Pattern through the implicit type conversion operator.But in the code , I noticed it kept crashing when converting to the List < IRecurrencePattern > from a List < DbRecurPatt > I realized that I needed to convert to RecurrencePattern , then Convert to IRecurrencePattern ( as there are other classes that implement IRecurrencePattern differently that are also included in the collectionThe above code does not work , it throws an error on IRecurrencePattern.This does work tho , so the question I have is ; Why does the first one not work ? ( And is there a way to improve this method ? ) I believe it might be because the implicit operator is on the RecurrencePattern object and not the interface , is this correct ? ( I 'm new to interfaces and implicit operators ) public interface IRecurrencePattern { string Data { get ; set ; } } public class RecurrencePattern : IRecurrencePattern { public string Data { get ; set ; } } public class DbRecurPatt { public string Name { get ; set ; } public string Description { get ; set ; } public static implicit operator RecurrencePattern ( DbRecurPatt obj ) { return new RecurrencePattern ( ) { Data = $ '' { Name } - { Description } '' } ; } } var unsorted = new List < DbRecurPatt > { new DbRecurPatt ( ) , new DbRecurPatt ( ) } ; var sorted = unsorted.Select ( t = > ( IRecurrencePattern ) t ) ; var sorted = unsorted.Select ( t = > ( IRecurrencePattern ) ( RecurrencePattern ) t ) ;","Interfaces , Inheritance , Implicit operators and type conversions , why is it this way ?" "C_sharp : There is ShadowCopy functionality in .Net to preserve file locking by copying assemblies.There are two properties : AppDomain.ShadowCopyFiles that uses AppDomainSetupAppDomainSetup.ShadowCopyFiles that stores it in internal string [ ] AppDomainSetup has string Value [ ] field , that used for storing configuration . The strange thing for me is that AppDomainSetup.ShadowCopyFiles is a string property , and we need to set `` true '' or `` false '' instead of real bool type . Here is an implementation for that property in AppDomainSetup : And here is an implementation for AppDomain.ShadowCopyFiles : But why in AppDomainSetup this property is a string ? Why Microsoft did n't used the some bool conversion logic as in AppDomain.ShadowCopyFiles ? It strange that such a bit smelly code located in AppDomainSetup , and I was just thinking is there a real reason for that that I 'm missing ? public string ShadowCopyFiles { get { return this.Value [ 8 ] ; } set { if ( value ! = null & & string.Compare ( value , `` true '' , StringComparison.OrdinalIgnoreCase ) == 0 ) this.Value [ 8 ] = value ; else this.Value [ 8 ] = ( string ) null ; } } public bool ShadowCopyFiles { get { String s = FusionStore.ShadowCopyFiles ; if ( ( s ! = null ) & & ( String.Compare ( s , `` true '' , StringComparison.OrdinalIgnoreCase ) == 0 ) ) return true ; else return false ; } }",Why AppDomain.ShadowCopyFiles is string ? "C_sharp : I have a slightly modified version of Mediatr handing command processing in my application . I have implemented a MediatorPipeline that allows me to have pre and post processors.I am registering my pre-processors with autofac like so : At runtime I am getting duplicate preprcessors . I have to filter the set removing duplicates . I am not sure why this is happening . If i comment out the registration , I do not get any preprocessors , which indicates that I am not duplicating the registration somewhere else.Update : Here are some more details on the type that appears to be getting registered twice . The various class definitions : The concrete handlerThe command classThe command interface public class AsyncMediatorPipeline < TRequest , TResponse > : IAsyncRequestHandler < TRequest , TResponse > where TRequest : IAsyncRequest < TResponse > { private readonly IAsyncRequestHandler < TRequest , TResponse > inner ; private readonly IAsyncPreRequestHandler < TRequest > [ ] preRequestHandlers ; private readonly IAsyncPostRequestHandler < TRequest , TResponse > [ ] postRequestHandlers ; public AsyncMediatorPipeline ( IAsyncRequestHandler < TRequest , TResponse > inner , IAsyncPreRequestHandler < TRequest > [ ] preRequestHandlers , IAsyncPostRequestHandler < TRequest , TResponse > [ ] postRequestHandlers ) { this.inner = inner ; this.preRequestHandlers = preRequestHandlers ; this.postRequestHandlers = postRequestHandlers ; } public async Task < TResponse > Handle ( TRequest message ) { foreach ( var preRequestHandler in preRequestHandlers ) { await preRequestHandler.Handle ( message ) ; } var result = await inner.Handle ( message ) ; foreach ( var postRequestHandler in postRequestHandlers ) { await postRequestHandler.Handle ( message , result ) ; } return result ; } } builder.RegisterAssemblyTypes ( Assembly.GetExecutingAssembly ( ) ) .As ( type = > type.GetInterfaces ( ) .Where ( type = > type.IsClosedTypeOf ( typeof ( IAsyncPreRequestHandler < > ) ) ) ) .InstancePerLifetimeScope ( ) ; public class ClientEditorFormIdentifierValidationHandler : IAsyncPreRequestHandler < AddOrEditClientCommand > { } public class AddOrEditClientCommand : IAsyncRequest < ICommandResult > { } public interface IAsyncRequest < out TResponse > { }",Autofac resolves multiple instances of the same type "C_sharp : Consider the following code : I get the following warning : Detected call to method 'System.Func ' 2 < System.Int32 , System.Object > .Invoke ( System.Int32 ) ' without [ Pure ] in contracts of method ' ... .Foo ( System.Func ' 2 < System.Int32 , System.Object > ) 'This warning makes perfect sense . But I 'd still like to call the delegate in contracts and not get a warning ( suppose I had warnings turned into errors ) . How do I achieve that ? I tried the attribute Pure , as shown in the example , but that does n't work.I 'd also like to know why the PureAttribute can be specified on parameters . It would n't make sense if the type of the parameter was n't a delegate type , and even if it is , it does n't work as I 'd expect , as I stated above . int SomeField ; void Foo ( [ Pure ] Func < int , object > getData ) { Contract.Requires ( getData ! = null ) ; Contract.Requires ( getData ( this.SomeField ) ! = null ) ; }",How to tell code contracts a delegate specified as argument is Pure ? C_sharp : Some code to replicate the issue : As far as i can tell the LoginRequest class is a Request < Response > because is inherits from Request < T > and LoginResponse inherits from Response so can anybody enlighten me as to why i get the compiler error ? note : i have also tried an explicit cast using System ; public abstract class Response { } public abstract class Request < T > where T : Response { } public class LoginResponse : Response { } public class LoginRequest : Request < LoginResponse > { } public class Program { static void Main ( string [ ] args ) { LoginRequest login = new LoginRequest ( ) ; /* Error : Can not implicitly convert type 'LoginRequest ' to 'Request ' */ Request < Response > castTest = login ; /* No Error */ Request < LoginResponse > castTest2 = login ; } },Why wo n't a class derived from an abstract class with a where clause cast to its lowest common class "C_sharp : Here is a trivial C # struct that does some validation on the ctor argument : I 've managed to translate this into an F # class : However , I ca n't translate this to a structure in F # : This gives compile errors : Invalid record , sequence or computation expression . Sequence expressions should be of the form 'seq { ... } ' This is not a valid object construction expression . Explicit object constructors must either call an alternate constructor or initialize all fields of the object and specify a call to a super class constructor.I 've had a look at this and this but they do not cover argument validation.Where am I doing wrong ? public struct Foo { public string Name { get ; private set ; } public Foo ( string name ) : this ( ) { Contract.Requires < ArgumentException > ( name.StartsWith ( `` A '' ) ) ; Name = name ; } } type Foo ( name : string ) = do Contract.Requires < ArgumentException > ( name.StartsWith `` A '' ) member x.Name = name [ < Struct > ] type Foo = val Name : string new ( name : string ) = { do Contract.Requires < ArgumentException > ( name.StartsWith `` A '' ) ; Name = name }",Argument validation in F # struct constructor "C_sharp : I´m having a little bit of trouble sorting a way to manage automatic resolved and manual dependencies in my classes.Let´s say I have two classes to calculate prices : one calculates how much I will charge for shipping and the other how much I will charge for the entire order . The second uses the first in order to sum the shipping price to the entire order price.Both classes have a dependency to a third class that I will call ExchangeRate which gives me the exchange rate I should use for price calculation . So far we have this chain of dependency : OrderCalculator - > ShippingCalculator - > ExchangeRateI´m using Ninject to resolve these dependencies and this was working until now . Now I have a requirement that the rate returned by ExchangeRate class will vary upon a parameter that will be provided in the Constructor ( because the object won´t work without this , so to make the dependency explicit it´s placed on the constructor ) coming from a user input . Because of that I can no longer resolve my dependencies automatically . Whenever I want to the OrderCalculator or any other classes that depends on ExchangeRate I can not ask the Ninject container to resolve it to me since I need to provide the parameter in the constructor.What do u suggest in this case ? Thanks ! EDIT : Let 's add some codeThis chain of objects is consumed by a WCF service and I 'm using Ninject as the DI container . public class OrderCalculator : IOrderCalculator { private IExchangeRate _exchangeRate ; public OrderCalculator ( IExchangeRate exchangeRate ) { _exchangeRate = exchangeRate ; } public decimal CalculateOrderTotal ( Order newOrder ) { var total = 0m ; foreach ( var item in newOrder.Items ) { total += item.Price * _exchangeRate.GetRate ( ) ; } return total ; } } public class ExchangeRate : IExchangeRate { private RunTimeClass _runtimeValue ; public ExchangeRate ( RunTimeClass runtimeValue ) { _runtimeValue = runtimeValue ; } public decimal GetRate ( ) { //returns the rate according to _runtimeValue if ( _runtimeValue == 1 ) return 15.3m ; else if ( _runtimeValue == 2 ) return 9.9m else return 30m ; } } //WCF Servicepublic decimal GetTotalForOrder ( Order newOrder , RunTimeClass runtimeValue ) { //I would like to pass the runtimeValue when resolving the IOrderCalculator depedency using a dictionary or something //Something like this ObjectFactory.Resolve ( runtimeValue ) ; IOrderCalculator calculator = ObjectFactory.Resolve ( ) ; return calculator.CalculateOrderTotal ( newOrder ) ; }",Resolving automatic and manual dependencies "C_sharp : I 'm driving myself crazy trying to understand Expressions in LINQ . Any help is much appreciated ( even telling me that I 'm totally off base here ) .Let 's say I have three classesI 'm trying to create a method that takes in a string , such as Locations.Name or Locations.Floor , or Educations.SchoolName which will then create a dynamic linq queryThis GetFilteredResults ( IEnumerable < Person > people , string ModelProperty , string Value ) method should create an expression that is roughly equivalent to people.Where ( p = > p.Locations.Any ( pl = > pl.Name == Value ) ; I have this working if ModelProperty is a string , i.e . people.Where ( p = > p.Name == Value ) looks like this : Here 's what I have been playing around with for an IEnumerable type , but I just ca n't get the inner Any , which seems correct , hooked into the outer Where : public class Person { public string Name { get ; set ; } public IEnumerable < PersonLocation > Locations { get ; set ; } public IEnumerable < PersonEducation > Educations { get ; set : } } public class PersonLocation { public string Name { get ; set ; } public string Floor { get ; set ; } public string Extension { get ; set ; } } public class PersonEducation { public string SchoolName { get ; set ; } public string GraduationYear { get ; set ; } } IEnumerable < Person > people = GetAllPeople ( ) ; GetFilteredResults ( people , `` Location.Name '' , `` San Francisco '' ) ; GetFilteredResults ( people , `` Location.Floor '' , `` 17 '' ) ; GetFilteredResults ( people , `` Educations.SchoolName '' , `` Northwestern '' ) ; string [ ] modelPropertyParts = ModelProperty.Split ( ' . ' ) ; var prop = typeof ( Person ) .GetProperty ( modelPropertyParts [ 0 ] ) ; var sourceParam = Expression.Parameter ( typeof ( Person ) , `` person '' ) ; var expression = Expression.Equal ( Expression.PropertyOrField ( sourceParam , modelPropertyParts [ 0 ] ) , Expression.Constant ( option.Name ) ) ; var whereSelector = Expression.Lambda < Func < Person , bool > > ( orExp , sourceParam ) ; return people.Where ( whereSelector.Compile ( ) ) ; /*i.e . modelPropertyParts [ 0 ] = Locations & modelPropertyParts [ 1 ] = Name */string [ ] modelPropertyParts = ModelProperty.Split ( ' . ' ) ; var interiorProperty = prop.PropertyType.GetGenericArguments ( ) [ 0 ] ; var interiorParameter = Expression.Parameter ( interiorProperty , `` personlocation '' ) ; var interiorField = Expression.PropertyOrField ( interiorParameter , modelPropertyParts [ 1 ] ) ; var interiorExpression = Expression.Equal ( interiorField , Expression.Constant ( Value ) ) ; var innerLambda = Expression.Lambda < Func < PersonLocation , bool > > ( interiorExpression , interiorParameter ) ; var outerParameter = Expression.Parameter ( typeof ( Person ) , `` person '' ) ; var outerField = Expression.PropertyOrField ( outerParameter , modelPropertyParts [ 0 ] ) ; var outerExpression = ? ? var outerLambda == ? ? return people.Where ( outerLambda.Compile ( ) ) ;",Nested Generic Lambdas in LINQ "C_sharp : I 'm writing code that looks similar to this : Obviously , this method is never going to return . ( The C # compiler silently allows this , while R # gives me the warning `` Function never returns '' . ) Generally speaking , is it bad design to provide an enumerator that returns an infinite number of items , without supplying a way to stop enumerating ? Are there any special considerations for this scenario ? Mem ? Perf ? Other gotchas ? If we always supply an exit condition , which are the options ? E.g : an object of type T that represents the inclusive or exclusive boundarya Predicate < T > continue ( as TakeWhile does ) a count ( as Take does ) ... Should we rely on users calling Take ( ... ) / TakeWhile ( ... ) after Unfold ( ... ) ? ( Maybe the preferred option , since it leverages existing Linq knowledge . ) Would you answer this question differently if the code was going to be published in a public API , either as-is ( generic ) or as a specific implementation of this pattern ? public IEnumerable < T > Unfold < T > ( this T seed ) { while ( true ) { yield return [ next ( T ) object in custom sequence ] ; } }",How do you design an enumerator that returns ( theoretically ) an infinite amount of items ? "C_sharp : I 'm inserting Log4Net events into a SQL database . The Message and Exception fields are both 8000 characters , but occasionally , an event will come through that is longer than 8000 characters , and the data is getting truncated.Is there any configurable way to get it to chunk out the events into multiple rows ? If not , I 'm currently thinking about implementing my own ILog that automatically handles chunking the logging events up so I do n't get any truncated data . Does anyone have a better idea ? Edit - Logging Config / Database Column DefinitionHere is my current parameter Configuration : The database tables are defined as such : < parameter > < parameterName value= '' @ message '' / > < dbType value= '' String '' / > < size value= '' 8000 '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % message '' / > < /layout > < /parameter > < parameter > < parameterName value= '' @ exception '' / > < dbType value= '' String '' / > < size value= '' 8000 '' / > < layout type= '' log4net.Layout.ExceptionLayout '' / > < /parameter > [ Message ] [ nvarchar ] ( max ) NULL , [ Exeception ] [ ntext ] NULL ,",How to Keep Log4Net From Truncating Exceptions ? "C_sharp : I 'm having trouble getting my head around the colour/material system of C # WPF projects , currently I am updating the colour of an entire system of points on each update of the model when I would instead like to just update the colour of a single point ( as it is added ) .AggregateSystem Classwhere AggregateParticle is a POD class consisting of Point3D position , Color color and double size fields which are self-explanatory.Is there any simple and efficient method to update the colour of the single particle as it is added in the Update method rather than the entire system of particles ? Or will I need to create a List ( or similar data structure ) of DiffuseMaterial instances for each and every particle in the system and apply brushes for the necessary colour to each ? [ The latter is something I want to avoid at all costs , partly due to the fact it would require large structural changes to my code , and I am certain that there is a better way to approach this than that - i.e . there MUST be some simple way to apply colour to a set of texture co-ordinates , surely ? ! . ] Further DetailsAggregateModel is a single Model3D instance corresponding to the field particle_model which is added to a Model3DGroup of the MainWindow.I should note that what I am trying to achieve , specifically , here is a `` gradient '' of colours for each particle in an aggregate structure where a particle has a Color in a `` temperature-gradient '' ( computed elsewhere in the program ) which is dependent upon order in which it was generated - i.e . particles have a colder colour if generated earlier and a warmer colour if generated later . This colour list is pre-computed and passed to each particle in the Update method as can be seen above.One solution I attempted involved creating a separate AggregateComponent instance for each particle where each of these objects has an associated Model3D and thus a corresponding brush . Then an AggregateComponentManager class was created which contained the List of each AggregateComponent . This solution works , however it is horrendously slow as each component has to be updated every time a particle is added so memory usage explodes - is there a way to adapt this where I can cache already rendered AggregateComponents without having to call their Update method each time a particle is added ? Full source code ( C # code in the DLAProject directory ) can be found on GitHub : https : //github.com/SJR276/DLAProject public class AggregateSystem { // stack to store each particle in aggregate private readonly Stack < AggregateParticle > particle_stack ; private readonly GeometryModel3D particle_model ; // positions , indices and texture co-ordinates for particles private readonly Point3DCollection particle_positions ; private readonly Int32Collection triangle_indices ; private readonly PointCollection text_coords ; // brush to apply to particle_model.Material private RadialGradientBrush rad_brush ; // ellipse for rendering private Ellipse ellipse ; private RenderTargetBitmap render_bitmap ; public AggregateSystem ( ) { particle_stack = new Stack < AggregateParticle > ( ) ; particle_model = new GeometryModel3D { Geometry = new MeshGeometry3D ( ) } ; ellipse = new Ellipse { Width = 32.0 , Height = 32.0 } ; rad_brush = new RadialGradientBrush ( ) ; // fill ellipse interior using rad_brush ellipse.Fill = rad_brush ; ellipse.Measure ( new Size ( 32,32 ) ) ; ellipse.Arrange ( new Rect ( 0,0,32,32 ) ) ; render_bitmap = new RenderTargetBitmap ( 32,32,96,96 , PixelFormats.Pbgra32 ) ) ; ImageBrush img_brush = new ImageBrush ( render_bitmap ) ; DiffuseMaterial diff_mat = new DiffuseMaterial ( img_brush ) ; particle_model.Material = diff_mat ; particle_positions = new Point3DCollection ( ) ; triangle_indices = new Int32Collection ( ) ; tex_coords = new PointCollection ( ) ; } public Model3D AggregateModel = > particle_model ; public void Update ( ) { // get the most recently added particle AggregateParticle p = particle_stack.Peek ( ) ; // compute position index for triangle index generation int position_index = particle_stack.Count * 4 ; // create points associated with particle for circle generation Point3D p1 = new Point3D ( p.position.X , p.position.Y , p.position.Z ) ; Point3D p2 = new Point3D ( p.position.X , p.position.Y + p.size , p.position.Z ) ; Point3D p3 = new Point3D ( p.position.X + p.size , p.position.Y + p.size , p.position.Z ) ; Point3D p4 = new Point3D ( p.position.X + p.size , p.position.Y , p.position.Z ) ; // add points to particle positions collection particle_positions.Add ( p1 ) ; particle_positions.Add ( p2 ) ; particle_positions.Add ( p3 ) ; particle_positions.Add ( p4 ) ; // create points for texture co-ords Point t1 = new Point ( 0.0 , 0.0 ) ; Point t2 = new Point ( 0.0 , 1.0 ) ; Point t3 = new Point ( 1.0 , 1.0 ) ; Point t4 = new Point ( 1.0 , 0.0 ) ; // add texture co-ords points to texcoords collection tex_coords.Add ( t1 ) ; tex_coords.Add ( t2 ) ; tex_coords.Add ( t3 ) ; tex_coords.Add ( t4 ) ; // add position indices to indices collection triangle_indices.Add ( position_index ) ; triangle_indices.Add ( position_index + 2 ) ; triangle_indices.Add ( position_index + 1 ) ; triangle_indices.Add ( position_index ) ; triangle_indices.Add ( position_index + 3 ) ; triangle_indices.Add ( position_index + 2 ) ; // update colour of points - **NOTE : UPDATES ENTIRE POINT SYSTEM** // - > want to just apply colour to single particles added rad_brush.GradientStops.Add ( new GradientStop ( p.colour , 0.0 ) ) ; render_bitmap.Render ( ellipse ) ; // set particle_model Geometry model properties ( ( MeshGeometry3D ) particle_model.Geometry ) .Positions = particle_positions ; ( ( MeshGeometry3D ) particle_model.Geometry ) .TriangleIndices = triangle_indices ; ( ( MeshGeometry3D ) particle_model.Geometry ) .TextureCoordinates = tex_coords ; } public void SpawnParticle ( Point3D _pos , Color _col , double _size ) { AggregateParticle agg_particle = new AggregateParticle { position = _pos , colour = _col , size = _size ; } // push most-recently-added particle to stack particle_stack.Push ( agg_particle ) ; } }",Update color of single point of GeometryModel3D Material rather than whole system of points "C_sharp : I 'm working on custom UI for company 's directory based on Lync . Using Lync 2013 I execute this search : For each of matching contacts I try to access their endpoints to display phone number : ProblemIf found contact is in the contact list of account I 'm using to connect Lync , then I get access to full details ( 5 endpoints ) . However if he is not in contact list , I get access to only 1 endpoint.Any ideas why is it happening like that ? Is there a global privacy setting I need to turn off or something ? How can I get access to all endpoints at all times ? Thank you.PS : I tried to load each contact in the result set individually and still get the same behavior . Container.Instance.Lync.ContactManager.BeginSearch ( SearchQuery , SearchProviders.GlobalAddressList , SearchFields.AllFields , SearchOptions.IncludeContactsWithoutSipOrTelUri , 500 , ContactsAndGroupsCallback , SearchQuery ) ; var cit = ContactInformationType.ContactEndpoints ; var endpoints = contact.GetContactInformation ( cit ) as List < object > ;",Lync - inconsistent behavior with ContactEndpoints "C_sharp : I 'm using .NET Core 2.0 . I 've got the following function that calls IDbCommand.ExecuteReaderI get a warning This async method lacks 'await ' operators and will run synchronously . Consider using the 'await ' operator to await non-blocking API calls , or 'await Task.Run ( ... ) ' to do CPU-bound work on a background thread.I was thinking about converting the command.ExecuteReader ( ) statement to await Task.Run ( ( ) = > command.ExecuteReader ( ) ) as advised in the warning . But I 'm not sure this is the correct approach , I believe Task.Run ( ... ) is for doing CPU based work . This is primarily IO work.So my questions areIs Task.Run ( ... ) the correct approach ? If not , is there another solution ? Or should I just ignore the warning for now and wait until ExecuteReaderAsync gets added to the IDbCommand interface ? ( is there a plan for this ? ) public async Task < IEnumerable < Widget > > ReadAllAsync ( System.Data.IDbConnection databaseConnection , System.Data.IDbTransaction databaseTransaction ) { var commandText = `` SELECT WidgetId , Name FROM Widget '' ; // _databaseCommandFactory.Create returns an IDbCommand var command = this._databaseCommandFactory.Create ( databaseConnection , databaseTransaction , commandText ) ; using ( var dataReader = command.ExecuteReader ( ) ) { // iterate through the data reader converting a collection of Widgets ( ` IEnumerable < Widget > ` ) } }",IDbCommand missing ExecuteReaderAsync "C_sharp : So this code triggers CA1031.While this one does not : Because the exception type is meaningful , I do n't need the ex in the first example . But it 's not a a general exception type . It 's not IOException or Exception . So why does it still trigger the CA1031 ? So is there a difference between catch ( FileNotFoundException ) and catch ( FileNotFoundException ex ) outside the fact that I do n't capture exception info ? try { // logic } catch ( FileNotFoundException ) // exception type { // handle error } try { // logic } catch ( FileNotFoundException ex ) // exception var { // handle error }",C # catch ( FileNotFoundException ) and CA1031 "C_sharp : Can anyone explain to me how an a member of this enum takes a value of 0 ? public enum EnumLogicalOperator { And = 1 , Or = 2 }",How can a variable typed as an enum take a value that is out of range of its elements ? "C_sharp : I have the following method which uses implicit scheduling : However , from one particular call-site I want it run on a low-priority scheduler instead of the default : How do I achieve this ? It seems like a really simple ask , but I 'm having a complete mental block ! Note : I 'm aware the example wo n't actually compile : ) private async Task FooAsync ( ) { await Something ( ) ; DoAnotherThing ( ) ; await SomethingElse ( ) ; DoOneLastThing ( ) ; } private async Task BarAsync ( ) { await Task.Factory.StartNew ( ( ) = > await FooAsync ( ) , ... , ... , LowPriorityTaskScheduler ) ; }",Explicitly specifying the TaskScheduler for an implicitly scheduled method "C_sharp : I 'm using Unity 's Register by convention mechanism in the following scenario : Given Implementation class and its interface I 'm running RegisterTypes in the following way : After this call , unitContainer contains three registrations : IUnityContainer - > IUnityContainer ( ok ) IInterface - > Implementation ( ok ) Implementation - > Implementation ( ? ? ? ) When I change the call as follows : The container contains only two registrations : IUnityContainer - > IUnityContainer ( ok ) IInterface - > Implementation ( ok ) ( this is the desired behaviour ) .After peeking into Unity 's source code , I 've noticed that there is some misunderstanding about how IUnityContainer.RegisterType should work.The RegisterTypes method works as follows ( the comments indicate what are the values in the scenarios presented above ) : Because fromTypes is not empty , the RegisterTypeMappings adds one type mapping : IInterface - > Implementation ( correct ) .Then , in case when lifetimeManager is not null , the code attempts to change the lifetime manager with the following call : This function 's name is completely misleading , because the documentation clearly states that : RegisterType a LifetimeManager for the given type and name with the container . No type mapping is performed for this type.Unfortunately , not only the name is misleading but the documentation is wrong . When debugging this code , I 've noticed , that when there is no mapping from type ( Implementation in the scenarios presented above ) , it is added ( as type - > type ) and that 's why we end up with three registrations in the first scenario.I 've downloaded Unity 's sources to fix the problem , but I 've found the following unit test : - which is almost exactly my case , and leads to my question : Why is this expected ? Is it a conceptual mistake , a unit test created to match existing behaviour but not necessarily correct , or am I missing something important ? I 'm using Unity v4.0.30319 . public interface IInterface { } public class Implementation : IInterface { } unityContainer.RegisterTypes ( new [ ] { typeof ( Implementation ) } , WithMappings.FromAllInterfaces , WithName.Default , WithLifetime.ContainerControlled ) ; unityContainer.RegisterTypes ( new [ ] { typeof ( Implementation ) } , WithMappings.FromAllInterfaces , WithName.Default ) ; foreach ( var type in types ) { var fromTypes = getFromTypes ( type ) ; // { IInterface } var name = getName ( type ) ; // null var lifetimeManager = getLifetimeManager ( type ) ; // null or ContainerControlled var injectionMembers = getInjectionMembers ( type ) .ToArray ( ) ; // null RegisterTypeMappings ( container , overwriteExistingMappings , type , name , fromTypes , mappings ) ; if ( lifetimeManager ! = null || injectionMembers.Length > 0 ) { container.RegisterType ( type , name , lifetimeManager , injectionMembers ) ; // ! } } container.RegisterType ( type , name , lifetimeManager , injectionMembers ) ; [ TestMethod ] public void RegistersMappingAndImplementationTypeWithLifetimeAndMixedInjectionMembers ( ) { var container = new UnityContainer ( ) ; container.RegisterTypes ( new [ ] { typeof ( MockLogger ) } , getName : t = > `` name '' , getFromTypes : t = > t.GetTypeInfo ( ) .ImplementedInterfaces , getLifetimeManager : t = > new ContainerControlledLifetimeManager ( ) ) ; var registrations = container.Registrations.Where ( r = > r.MappedToType == typeof ( MockLogger ) ) .ToArray ( ) ; Assert.AreEqual ( 2 , registrations.Length ) ; // ...",Why is a type registered twice when lifetime manager is specified ? "C_sharp : I 'm writing a custom HTML helper to display a Grid and I 'm focussing myself on Telerik and other parties for the syntax I would like to use.I have a model with 3 properties ( Name , DateUpdated and DateCreted ) and an IEnumerable of that one is passed to my view : Then I have my static HtmlHelperExtensions class : This class does return a GridBuilder which looks as the following : And then I have my ColumnBuilder class.With all this code into place ( nothing is rendered at this point ) , I can use the following syntax : The 'problem ' here is that I need to specify the type of object that a single item in the Grid is holding ( the GridPageFolderViewModel ) , otherwise , I can not access the properties in the column binder code.Anyone has some advice on how I can get rid of it ? @ model IEnumerable < GridPageFolderViewModel > public static class HtmlHelperExtensions { # region Grid public static GridBuilder < TModelEntry > GridFor < TModel , TModelEntry > ( this HtmlHelper < TModel > htmlHelper , TModelEntry model ) { return new GridBuilder < TModelEntry > ( ) ; } # endregion } public class GridBuilder < TModel > : IGridBuilder { # region Properties private string name { get ; set ; } # endregion # region Methods public GridBuilder < TModel > WithColumns ( Action < ColumnBuilder < TModel > > function ) { return this ; } internal MvcHtmlString Render ( ) { return new MvcHtmlString ( `` This is a value . `` ) ; } # endregion # region IGridBuilder Members public GridBuilder < TModel > Name ( string name ) { this.name = name ; return this ; } # endregion # region IHtmlString Members public string ToHtmlString ( ) { return Render ( ) .ToHtmlString ( ) ; } # endregion } public class ColumnBuilder < TModel > { public void Bind < TItem > ( Func < TModel , TItem > func ) { } } @ ( Html.GridFor ( new GridPageFolderViewModel ( ) ) .Name ( `` PageOverviewGrid '' ) .WithColumns ( column = > { column.Bind ( c = > c.Name ) ; column.Bind ( c = > c.DateCreated ) ; column.Bind ( c = > c.DateUpdated ) ; } )","MVC : Custom , fluent Html Helpers" "C_sharp : I try to add a method to the class using Roslyn.I parse .cs file and get the decidered class.Then i create an instance of the type MemberDeclarationwhere lList is the body of method . Then i try to add this instance to the classbut nothing in response.How i can do this ? SyntaxTree tree = SyntaxTree.ParseFile ( Path ) ; CompilationUnitSyntax root = ( CompilationUnitSyntax ) tree.GetRoot ( ) ; MemberDeclarationSyntax firstMember = root.Members [ 0 ] ; TypeDeclarationSyntax lClassDeclarationSyntax = ( TypeDeclarationSyntax ) NamespaceDeclaration.Members [ 1 ] ; MethodDeclarationSyntax lMethodDeclarationSyntax= Syntax.MethodDeclaration ( Syntax.List < AttributeListSyntax > ( ) , Syntax.TokenList ( ) , Syntax.IdentifierName ( `` MemoryStream '' ) , null , Syntax.Identifier ( `` Serialize '' ) , null , Syntax.ParameterList ( ) , Syntax.List < TypeParameterConstraintClauseSyntax > ( ) , Syntax.Block ( lList ) ) ; lClassDeclarationSyntax.Members.Add ( lMethodDeclarationSyntax ) ;",Ca n't add member to the Class programmatically using Roslyn "C_sharp : I am trying to create a Blazor WebAssembly app using the latest build of Visual Studio for Mac ( v8.4.6 build 36 ) . I have .NET Core 3.1 SDK installed . I also installed the latest Blazor WebAssembly 3.2.0 Preview 1 by running : dotnet new -i Microsoft.AspNetCore.Blazor.Templates : :3.2.0-preview1.20073.1 . The output log shows it installed successfully : However , the Blazor WebAssembly App template does not show up in Visual Studio for Mac , even after restarting : And if I create a Blazor WebAssembly app from the CLI as follows , it builds but does not run : And if I try to run it in Visual Studio for Mac I get this error : Can not open assembly '/Users/my.username/projects/blazor/BlazerWasm/bin/Debug/netstandard2.1/BlazerWasm.exe ' : No such file or directory.Is Visual Studio for Mac not able to build or run Blazor WebAssembly apps , or am I missing something ? Templates Short Name Language Tags -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Blazor Server App blazorserver [ C # ] Web/Blazor Blazor WebAssembly App blazorwasm [ C # ] Web/Blazor/WebAssembly dotnet new blazorwasmdotnet builddotnet run",Missing Blazor WebAssembly app template for Visual Studio for Mac "C_sharp : Here is the sample code for the discussion ( consider Reptile `` is a '' Animal and Mammal `` is a '' Animal too ) When I run this code I get a ArrayTypeMismatchException , with as comment Array.ConstrainedCopy will only work on array types that are provably compatible , without any form of boxing , unboxing , widening , or casting of each array element . Change the array types ( i.e. , copy a Derived [ ] to a Base [ ] ) , or use a mitigation strategy in the CER for Array.Copy 's less powerful reliability contract , such as cloning the array or throwing away the potentially corrupt destination array.However when I look at MSDN I see this method also throws an InvalidCastException . The condition for throwing an InvalidCastException is : At least one element in sourceArray can not be cast to the type of destinationArray.So I am stumped , how do you get an InvalidCastException out of this method , if as it states there can never be any casting of an array element ? Animal [ ] reptiles = new Reptile [ ] { new Reptile ( `` lizard '' ) , new Reptile ( `` snake '' ) } ; Animal [ ] animals = new Animal [ ] { new Reptile ( `` alligator '' ) , new Mammal ( `` dolphin '' ) } ; try { Array.ConstrainedCopy ( animals , 0 , reptiles , 0 , 2 ) ; } catch ( ArrayTypeMismatchException atme ) { Console.WriteLine ( ' [ ' + String.Join < Animal > ( `` , `` , reptiles ) + ' ] ' ) ; }",How to get InvalidCastException from Array.ConstrainedCopy "C_sharp : Alright , so I 'm running into a strange little issue and frankly I 'm out of ideas . I wanted to throw this out there to see if I 'm missing something that I 've done wrong , or if ConcurrentDictionary is n't working correctly . Here 's the code : ( Cache is a class containing the static ConcurrentDictionary Keys ) The problem is that occasionally tmp is null , causing the TryRemove line to run , yet the return null ; line above is never hit . Since that return null is the only thing putting null into the dictionary and it never runs , how could tmp ever be null ? Including the Cache class ( SetNames is not used by this code ) : var tmp = Cache.Keys.GetOrAdd ( type , key = > { var keys = context.GetKeys ( key ) ; if ( keys.Count ( ) == 1 ) { return new KeyInfo { Name = keys.First ( ) .Name , Info = key.GetInfo ( keys.First ( ) .Name ) } ; } return null ; } ) ; if ( tmp == null ) Cache.Keys.TryRemove ( type , out tmp ) ; return tmp ; public class Cache { public static ConcurrentDictionary < Type , Info > Keys = new ConcurrentDictionary < Type , Info > ( ) ; public static ConcurrentDictionary < Type , string > SetNames = new ConcurrentDictionary < Type , string > ( ) ; }",ConcurrentDictionary - broken dictionary or bad code ? "C_sharp : I have come across a problem with a unit test that failed because a TPL Task never executed its ContinueWith ( x , TaskScheduler.FromCurrentSynchronizationContext ( ) ) . The problem turned out to be because a Winforms UI Control was accidentally being created before the Task was started . Here is an example that reproduces it . You will see that if you run the test as-is , it passes . If you run the test with the Form line uncommented , it fails.Can anyone explain why this is the case ? I thought it might have been because the wrong SynchronizationContext is used , but actually , the ContinueWith never executes at all ! And besides , in this unit test , whether or not it is the correct SynchronizationContext is irrelevant because as long as the waitHandle.set ( ) is called on any thread , the test should pass . [ TestClass ] public class UnitTest1 { [ TestMethod ] public void TestMethod1 ( ) { // Create new sync context for unit test SynchronizationContext.SetSynchronizationContext ( new SynchronizationContext ( ) ) ; var waitHandle = new ManualResetEvent ( false ) ; var doer = new DoSomethinger ( ) ; //Uncommenting this line causes the ContinueWith part of the Task //below never to execute . //var f = new Form ( ) ; doer.DoSomethingAsync ( ( ) = > waitHandle.Set ( ) ) ; Assert.IsTrue ( waitHandle.WaitOne ( 10000 ) , `` Wait timeout exceeded . `` ) ; } } public class DoSomethinger { public void DoSomethingAsync ( Action onCompleted ) { var task = Task.Factory.StartNew ( ( ) = > Thread.Sleep ( 1000 ) ) ; task.ContinueWith ( t = > { if ( onCompleted ! = null ) onCompleted ( ) ; } , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ; } }",Why does the Task.ContinueWith fail to execute in this Unit Test ? "C_sharp : How would I go about passing an entity type as a parameter in linq ? For e.g . The method will receive the entity name value as a string and I would like to pass the entity name to the below linq query . Is it possible to make the linq query generic ? I would like to pass the Entity type as a parameter and return all property values.Also , is it possible to filter results based the some property ? public ActionResult EntityRecords ( string entityTypeName ) { var entityResults = context. < EntityType > .Tolist ( ) ; return View ( entityResults ) ; }",passing entity type as parameter in linq "C_sharp : I have two similar structs in C # , each one holds an integer , but the latter has get/set accessors implemented.Why do I have to initialize the Y struct with new operator prior to assigning the a field ? Is y still a value type when I init it with new ? public struct X { public int a ; } public struct Y { public int a { get ; set ; } } class Program { static void Main ( string [ ] args ) { X x ; x.a = 1 ; Y y ; y.a = 2 ; // < < compile error `` unused local variable '' here Y y2 = new Y ( ) ; y2.a = 3 ; } }",Struct initialization and new operator "C_sharp : I sometimes use these and others when delaying evaluation . Are these already in the .net library ? Edit : Here is an example usage : ToErrorText checks ' v ' as legitimate ( non-error code , non-null , etc ) , if good it runs the chained in Func , if bad it produces fail-safe text result . If v , suffix , or columns are not good then ToFormat will never be called . ( Hence the delayed/non-evaluated usage ) .ToFormat is nearly the composition of the provided Func and string.Format . ToIdentity is used to lift v to a Func and then everything in the chain is based on some Func of T . public static Func < V > To < T , V > ( this Func < T > g , Func < T , V > h ) { return ( ) = > h ( g ( ) ) ; } public static Func < T > ToIdentity < T > ( this T t ) { return ( ) = > t ; } public static string SuffixColumn ( this string v , string suffix , int columns ) { return v.ToIdentity ( ) .ToScrubbedHtml ( ) .ToFormat ( ( ) = > `` { 0 } `` + suffix.ToLower ( ) .PadLeft ( columns , ' ' ) ) .ToErrorText ( v , suffix , columns ) ( ) ; }","Are there already built in functional C # /.NET constructs like these ? g ( h ( ) ) , or" "C_sharp : This question deals with events ( base class events and subclass events ) and event handlers . I 'm working on existing code , that does n't seem to work the way the author expected it . I have difficulty understanding why it does n't work though , so I want to understand what 's going on before I try to fix the existing code.I 've found the following question , which may or may not suggest I need to make an additional event handler for the subtype events : C # : Raising an inherited eventIf making an additional event handler is indeed the solution , I would still like to learn why this is the case . This is my first question here , and I did really try to search for the answer/explanation to my question , but sincere apologies if it 's still something I should 've easily found . A stern `` RTFM ! '' with a educational link would be fine with me at this point : ) We have 2 event classes , a base type and a subtype . The subtype event exists to deal with deletion events.A usage of these events that seems to be failing : The declaration of the events are in the IEventBusService and EventBusService : And then finally the place where we send the deletion event ( to try to delete an item of what I have cleverly named SomeRandomThing above ) : So the problem : after sending the deletion event with the last line of code above , the if-statement in the UsageClass that checks whether an incoming event is of type SubTypeEvent is never actually true . The type of e in HandleMethod of UsageClass is BaseTypeEvent.Edit : I 've decided to get rid of the subtyping in this case . We now no longer have BaseTypeEvent and SubTypeEvent , but simply EventTypeA and EventTypeB . One deals with creates and updates , the other deals with deletes ( for which we need significantly less information that the creates and updates anyway ) .andand so on.I 've made an extra subscription to MassTransit in the Initialize method of our EventbusService , and made extra handlers in the various UsageClasses that needed them : andand so on.I now no longer have to check if an incoming event is of a certain type , I just handle to two types separately . Perhaps a cop out , but it works.I 'm hesitant to qualify this as the answer to my own question , as @ Glubus ' comments as well as @ Travis ' comments were what answered my question . Still thought this small edit write-up might be nice to let everyone know what I did as a solution : ) Edit 2 : Sources of information that were helpful : Derived types are not published to consumers in MassTransitMassTransit message mis-typingMassTransit : Message contracts , polymorphism and dynamic proxy objectshttps : //groups.google.com/forum/ # ! searchin/masstransit-discuss/polymorphism/masstransit-discuss/q_M4erHQ7OI/FxaotfIzI7YJ public class BaseTypeEvent { public Guid Id { get ; set ; } public string Name { get ; set ; } public BaseTypeEvent ( ) { } public BaseTypeEvent ( SomeRandomThing item ) { Id = item.Id ; Name = item.Name ; } } public class SubTypeEvent : BaseTypeEvent { public DateTimeOffset Deleted { get ; set ; } public SubTypeEvent ( ) { Deleted = DateTimeOffset.UtcNow ; } } public class UsageClass { public UsageClass ( IEventBusService eventBusService ) { eventBusService.MyBaseTypeEvents += HandleMethod ; } private void HandleMethod ( BaseTypeEvent e ) { if ( e is SubTypeEvent ) { //code that deals with deletion events //execution never actually gets here } //code that deals with events that are not deletion events } } public delegate void MyEventHandler ( BaseTypeEvent e ) ; public interface IEventBusService { public event MyEventHandler MyBaseTypeEvents ; void PublishStuff ( BaseTypeEvent e ) ; } public class EventBusService : IEventBusService , IDisposable { public void Initialize ( ) { //Bus is MassTransit Bus.Initialize ( sbc = > { sbc.Subscribe ( subs = > subs.Handler < BaseTypeEvent > ( OnBaseTypeEvent ) ) ; } } private void OnBaseTypeEvent ( BaseTypeEvent e ) { if ( MyBaseTypeEvents == null ) return ; try { MyBaseTypeEvents ( e ) ; } catch ( Exception e ) { //some logging } } public event MyEventHandler MyBaseTypeEvents ; public void PublishStuff ( BaseTypeEvent e ) { //some logging //publish e to the event bus of our choice ( MassTransit ) Bus.Instance.Publish ( e ) ; } } eventBusService.PublishStuff ( new SubTypeEvent { Id = id , Deleted = DateTimeOffset.UtcNow } ) ; public delegate void MyEventAHandler ( EventTypeA e ) ; public delegate void MyEventBHandler ( EventTypeB e ) ; void PublishStuffForA ( EventTypeA e ) ; void PublishStuffForB ( EventTypeB e ) ; sbc.Subscribe ( subs = > subs.Handler < EventTypeA > ( OnEventTypeA ) ) ; sbc.Subscribe ( subs = > subs.Handler < EventTypeB > ( OnEventTypeB ) ) ; public UsageClass ( IEventBusService eventBusService ) { eventBusService.MyEventTypeAEvents += HandleMethodForA ; eventBusService.MyEventTypeBEvents += HandleMethodForB ; }",MassTransit message consumers never see subclass type "C_sharp : I am trying to print the contents of a rich-text box . I do that in the following way : Obtain a TextRange from the FlowDocument.Create a new FlowDocument with a smaller font using the TextRange.Send this new FlowDocument to the printer.My problem , is that the font does n't seem to change . I would like it to go down to size 8 . Instead , it remains at a fixed size . Here is my code : I would like to add that , changing the font works just fine for the flow-document when it is inside of the rich-text box . However , when I am doing it programmatically ( as shown above ) I run into problems . private void button_Print_Click ( object sender , RoutedEventArgs e ) { IDocumentPaginatorSource ps = null ; FlowDocument fd = new FlowDocument ( ) ; PrintDialog pd = new PrintDialog ( ) ; Paragraph pg = new Paragraph ( ) ; Style style = new Style ( typeof ( Paragraph ) ) ; Run r = null ; string text = string.Empty ; // get the text text = new TextRange ( this.richTextBox_Info.Document.ContentStart , this.richTextBox_Info.Document.ContentEnd ) .Text ; // configure the style of the flow document style.Setters.Add ( new Setter ( Block.MarginProperty , new Thickness ( 0 ) ) ) ; fd.Resources.Add ( typeof ( Paragraph ) , style ) ; // style the paragraph pg.LineHeight = 0 ; pg.LineStackingStrategy = LineStackingStrategy.BlockLineHeight ; pg.FontFamily = new FontFamily ( `` Courier New '' ) ; pg.TextAlignment = TextAlignment.Left ; pg.FontSize = 8 ; // create the paragraph r = new Run ( text ) ; r.FontFamily = new FontFamily ( `` Courier New '' ) ; r.FontSize = 8 ; pg.Inlines.Add ( r ) ; // add the paragraph to the document fd.Blocks.Add ( pg ) ; ps = fd ; // format the page fd.PagePadding = new Thickness ( 50 ) ; fd.ColumnGap = 0 ; fd.ColumnWidth = pd.PrintableAreaWidth ; // print the document if ( pd.ShowDialog ( ) .Value == true ) { pd.PrintDocument ( ps.DocumentPaginator , `` Information Box '' ) ; } }",WPF : The font will not change on a printed FlowDocument "C_sharp : Is there any way to enumerate all the bluetooth com ports and get their names ? And by name i do n't mean COM10 , in this case i mean GNSS:51622 'GNSS Server'.Using 32Feet i have been able to find the names of the ports , but still no luck mapping them to the actual com port.Output : Connecting to BluetoothDiscoverDevicesEnumeratingGNSS:51622Getting serial portsCOM1COM2COM3GNSS Server class Program { static void Main ( string [ ] args ) { Console.WriteLine ( `` Connecting to Bluetooth '' ) ; var client = new BluetoothClient ( ) ; Console.WriteLine ( `` DiscoverDevices '' ) ; var devices = client.DiscoverDevices ( ) ; Console.WriteLine ( `` Enumerating '' ) ; foreach ( var device in devices ) { if ( ! device.DeviceName.StartsWith ( `` GNSS '' ) ) continue ; Console.WriteLine ( device.DeviceName ) ; try { Console.WriteLine ( `` Getting serial ports '' ) ; var serviceRecords = device.GetServiceRecords ( BluetoothService.SerialPort ) ; foreach ( var serviceRecord in serviceRecords ) { var name = GetName ( serviceRecord ) ; Console.WriteLine ( name ) ; } } catch ( Exception ex ) { Console.WriteLine ( `` Failed to get SerialPort '' ) ; Console.WriteLine ( ex.ToString ( ) ) ; } } Console.ReadKey ( ) ; } private static string GetName ( ServiceRecord serviceRecord ) { var nameAttribute = serviceRecord.SingleOrDefault ( a = > a.Id == 0 ) ; var name = serviceRecord.GetPrimaryMultiLanguageStringAttributeById ( nameAttribute.Id ) ; return name ; } }",Get bluetooth comport name "C_sharp : I have created a display template in ~/Views/Shared/DisplayTemplates named ImpactMatrix.cshtml . It accepts a nullable int and renders a two-dimensional matrix with the selected number highlighted : It 's easily reusable and works great . I can invoke it within my view like so : Now I 've decided to extend that and make it an editor as well . The idea is to add a hidden input for the selected number and wrap the input along with the matrix template with a div . From there it should be a simple matter to use Javascript to interact with my display grid and populate the hidden input.I 've created an editor template , also named ImpactMatrix.cshtml , within my ~/Views/Shared/EditorTemplates folder . Here 's the code : My problem is that the hidden input renders correctly , but the nested display template does not render inside my editor template . Is what I am trying to do possible ? @ model int ? @ { var matrix = ImpactMatrix.GetMatrix ( ) ; } < div class= '' impactmatrix '' > < table > @ for ( int i = 0 ; i < matrix.GetLength ( 0 ) ; i++ ) { < tr > @ for ( int j = 0 ; j < matrix.GetLength ( 1 ) ; j++ ) { var cell = matrix [ i , j ] ; < td data-color= '' @ cell.Color '' class= '' matrix @ ( Model == cell.Value ? cell.Color.ToString ( ) : `` '' ) '' > @ cell.Value < /td > } < /tr > } < /table > < /div > @ Html.DisplayFor ( m= > m.ImpactFactor , `` ImpactMatrix '' ) @ model int ? < div class= '' impactmatrix-editor '' > @ Html.HiddenFor ( m = > m ) @ Html.DisplayFor ( m = > m , `` ImpactMatrix '' ) < /div >",Can a display template be invoked from within an editor template ? C_sharp : I am entry level .Net developer and using it to develop web sites . I started with classic asp and last year jumped on the ship with a short C # book.As I developed I learned more and started to see that coming from classic asp I always used C # like scripting language.For example in my last project I needed to encode video on the webserver and wrote a code likeWhile searching samples related to my project I ’ ve seen people doing thisAs I understand second example is more object oriented but I don ’ t see the point of using EncodedVideo object.Am I doing something wrong ? Does it really necessary to use this sort of code in a web app ? public class Encoder { Public static bool Encode ( string videopath ) { ... snip ... return true ; } } public class Encoder { Public static Encode ( string videopath ) { EncodedVideo encoded = new EncodedVideo ( ) ; ... snip ... encoded.EncodedVideoPath = outputFile ; encoded.Success = true ; ... snip ... } } public class EncodedVideo { public string EncodedVideoPath { get ; set ; } public bool Success { get ; set ; } },Getting my head around object oriented programming "C_sharp : I currently have a system where the server tells all client applications when to next connect to the server between a server configured time window ( say 12 to 6 am client time ) . The current algorithm does a mod of the client 's 10 digit ID number ( fairly distributed ) by the number of seconds in the time window and gives a pretty evenly distributed , predictable time for each client to connect to the server . The problem now , is that clients are in different time zones dis-proportionately , and certain time zones overlap for the given window , so the net effect is that the load is not distributed evenly on the server . What I would like is to devise an algorithm that I could configure with a percentage of clients we currently have for each time zone , and have it distribute the client 's next connect time between the window that results in an even load on the server in a manner that is predictable ( non-random ) .here is a simple graphical representation : 12AM 1AM 2AM 3AM 4AM 5AM 6AM GMTGMT -4 40 % of the clients |||||||||||||||||||||||||||||| GMT -5 10 % of the clients |||||||||||||||||||||||||||||| GMT -6 20 % of the clients |||||||||||||||||||||||||||||| GMT -7 30 % of the clients ||||||||||||||||||||||||||||||",Non-Random Weighted Distribution "C_sharp : According to the FakeItEasy tutorial here the WithArgumentsForConstructor ( ) extension method does not call the class constructor : However , the breakpoint in my Person class constructor is triggered in my test below . How so ? Am I using WithArgumentsForConstructor ( ) incorrectly ? Stack trace : ... // Specifying arguments for constructor using expression . This is refactoring friendly ! // The constructor seen here is never actually invoked . It is an expression and it 's purpose// is purely to communicate the constructor arguments which will be extracted from itvar foo = A.Fake < FooClass > ( x = > x.WithArgumentsForConstructor ( ( ) = > new FooClass ( `` foo '' , `` bar '' ) ) ) ; [ Test ] public void Constructor_With_Arguments ( ) { var driver = A.Fake < Person > ( x = > x.WithArgumentsForConstructor ( ( ) = > new Person ( `` Jane '' , 42 ) ) ) ; var age = driver.GetAge ( ) ; Assert.AreEqual ( 42 , age ) ; } MyStuff.Tests.Domain.dll ! MyStuff.Tests.Domain.Driver.Person ( string name , int age ) Line 61 C # DynamicProxyGenAssembly2 ! Castle.Proxies.DriverProxy.DriverProxy ( Castle.DynamicProxy.IInterceptor [ ] value , string value , int value ) Unknown [ Native to Managed Transition ] [ Managed to Native Transition ] mscorlib.dll ! System.RuntimeType.CreateInstanceImpl ( System.Reflection.BindingFlags bindingAttr , System.Reflection.Binder binder , object [ ] args , System.Globalization.CultureInfo culture , object [ ] activationAttributes , ref System.Threading.StackCrawlMark stackMark ) Unknownmscorlib.dll ! System.Activator.CreateInstance ( System.Type type , System.Reflection.BindingFlags bindingAttr , System.Reflection.Binder binder , object [ ] args , System.Globalization.CultureInfo culture , object [ ] activationAttributes ) Unknownmscorlib.dll ! System.Activator.CreateInstance ( System.Type type , object [ ] args ) UnknownFakeItEasy.dll ! Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance ( System.Type proxyType , System.Collections.Generic.List < object > proxyArguments , System.Type classToProxy , object [ ] constructorArguments ) UnknownFakeItEasy.dll ! Castle.DynamicProxy.ProxyGenerator.CreateClassProxy ( System.Type classToProxy , System.Type [ ] additionalInterfacesToProxy , Castle.DynamicProxy.ProxyGenerationOptions options , object [ ] constructorArguments , Castle.DynamicProxy.IInterceptor [ ] interceptors ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.GenerateClassProxy ( System.Type typeOfProxy , System.Collections.Generic.IEnumerable < object > argumentsForConstructor , Castle.DynamicProxy.IInterceptor interceptor , System.Collections.Generic.IEnumerable < System.Type > allInterfacesToImplement ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.DoGenerateProxy ( System.Type typeOfProxy , System.Collections.Generic.IEnumerable < System.Type > additionalInterfacesToImplement , System.Collections.Generic.IEnumerable < object > argumentsForConstructor , Castle.DynamicProxy.IInterceptor interceptor ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.CreateProxyGeneratorResult ( System.Type typeOfProxy , System.Collections.Generic.IEnumerable < System.Type > additionalInterfacesToImplement , System.Collections.Generic.IEnumerable < object > argumentsForConstructor , FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.GenerateProxy ( System.Type typeOfProxy , System.Collections.Generic.IEnumerable < System.Type > additionalInterfacesToImplement , System.Collections.Generic.IEnumerable < object > argumentsForConstructor , FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.CastleDynamicProxy.CastleDynamicProxyGenerator.GenerateProxy ( System.Type typeOfProxy , System.Collections.Generic.IEnumerable < System.Type > additionalInterfacesToImplement , System.Collections.Generic.IEnumerable < object > argumentsForConstructor , System.Collections.Generic.IEnumerable < System.Reflection.Emit.CustomAttributeBuilder > customAttributeBuilders , FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.ProxyGeneratorSelector.GenerateProxy ( System.Type typeOfProxy , System.Collections.Generic.IEnumerable < System.Type > additionalInterfacesToImplement , System.Collections.Generic.IEnumerable < object > argumentsForConstructor , System.Collections.Generic.IEnumerable < System.Reflection.Emit.CustomAttributeBuilder > customAttributeBuilders , FakeItEasy.Core.IFakeCallProcessorProvider fakeCallProcessorProvider ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.FakeObjectCreator.GenerateProxy ( System.Type typeOfFake , FakeItEasy.Creation.FakeOptions fakeOptions , System.Collections.Generic.IEnumerable < object > argumentsForConstructor ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.FakeObjectCreator.CreateFake ( System.Type typeOfFake , FakeItEasy.Creation.FakeOptions fakeOptions , FakeItEasy.Creation.IDummyValueCreationSession session , bool throwOnFailure ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.DefaultFakeAndDummyManager.CreateFake ( System.Type typeOfFake , FakeItEasy.Creation.FakeOptions options ) UnknownFakeItEasy.dll ! FakeItEasy.Creation.DefaultFakeCreatorFacade.CreateFake < SysSurge.DynMock.Tests.Domain.Driver > ( System.Action < FakeItEasy.Creation.IFakeOptionsBuilder < SysSurge.DynMock.Tests.Domain.Driver > > options ) Unknown",WithArgumentsForConstructor ( ) extension method calls constructor "C_sharp : The following code produces no errors when executed : Is a null value to using 'allowed ' ? If so , where is it documented ? Most C # code I 've seen will create a `` dummy/NOP '' IDisposable object - is there a particular need for a non-null Disposable object ? Was there ever ? If/since null is allowed , it allows placing a null guard inside the using statement as opposed to before or around.The C # Reference on Using does not mention null values . using ( ( IDisposable ) null ) { Console.WriteLine ( `` A '' ) ; } Console.WriteLine ( `` B '' ) ;",Using a null IDisposable value with the using statement "C_sharp : I 'm writing a C # Program to display the Temperature of CPU/GPU from my PS3.There is a connect button . This works really good and it shows me the Temp . from my PS3 's CPU/GPU.Now I 've implemented a `` refresh '' button , which starts a timer for all x Seconds to do this : So this `` get_psdata '' works only on the first time , when i press the connect button . ( The connect button starts directly the `` get_psdate '' function , while the refresh button does a bit different , like you can see later ... ) Here is the code to run the get_psdata : For testing , I added a Messagebox.Show to the `` get_psdata '' function to see if it runs all x Seconds ... Yes it does and this is my timer : And this is what starts my timer : So I 'm sure that the code will run all x Seconds but the label 's are only updated when I hit the connect button , but not if I start the counter after connecting with the B_set button.The Variables from `` get_psdata '' are not showing the updated value . They just show the result from the first `` Get '' . Why are n't they show the latest result ? public void get_psdata ( ) { //Get data from PS3 cputemp = PS3.GetTemperatureCELL ( ) ; gputemp = PS3.GetTemperatureRSX ( ) ; psversion = PS3.GetFirmwareVersion ( ) ; psversiontype = PS3.GetFirmwareType ( ) ; //Set data into Var L_cputemp_show.Text = cputemp ; L_gputemp_show.Text = gputemp ; L_firmware_show.Text = psversion ; L_type_show.Text = psversiontype ; //Update Label L_cputemp_show.Refresh ( ) ; } //B_connect , Connect Button private void b_connect_Click ( object sender , EventArgs e ) { //Connect CCAPI to PS3 if Button clicked PS3.ConnectTarget ( psip ) ; //Check Connection if ( PS3.SUCCESS ( PS3.ConnectTarget ( psip ) ) ) { //Show Status MessageBox.Show ( `` Connected to : `` + psip + `` ! `` ) ; this.L_status_show.Text = `` Connected ! `` ; L_status_show.ForeColor = System.Drawing.Color.Green ; //Call Function get_psdata ( ) ; } else { //Show Status MessageBox.Show ( `` Failed to Connect to : `` + psip + `` ! `` ) ; this.L_status_show.Text = `` Not Connected ! `` ; L_status_show.ForeColor = System.Drawing.Color.Red ; } } //Function to set refresh delay public void refresh_delay ( ) { MessageBox.Show ( `` Delay set to `` + refresh_int + `` Seconds ! `` ) ; refresh_int = refresh_int * 1000 ; //Change to Miliseconds init_timer ( ) ; } //Timer public Timer timer1 ; public void init_timer ( ) { timer1 = new Timer ( ) ; timer1.Tick += new EventHandler ( timer1_Tick ) ; timer1.Interval = refresh_int ; // in miliseconds timer1.Start ( ) ; } public void timer1_Tick ( object sender , EventArgs e ) { get_psdata ( ) ; } //B_set , Set refresh time button private void B_set_Click ( object sender , EventArgs e ) { //Check refresh Value refresh_string = TB_refresh.Text ; //Check empty if ( refresh_string ! = `` '' ) { //Check minimum refresh_int = Convert.ToInt32 ( TB_refresh.Text ) ; if ( refresh_int < 5 ) { DialogResult confirm = MessageBox.Show ( `` This is not the delay you are looking for ! \r ( I recommend to set it bigger then 5 ) \r Continue with `` + refresh_int + `` Seconds ? `` , `` Realy dude ? `` , MessageBoxButtons.YesNo ) ; if ( confirm == DialogResult.Yes ) { //Call Function refresh_delay ( ) ; } } else { //Call Function refresh_delay ( ) ; } } else { MessageBox.Show ( `` Please set refresh delay ! `` ) ; } }",C # Variable wo n't update "C_sharp : I am trying to use one web service which returns demanded data in json format . Now the actual point is I can fetch the data from the particular web service url in string.Now the point is I get the data in string ( in JSON format ) . But I dont know how to convert the string into JSON string and how to fetch data from this string.Let me give you example so you can easily understandif my jsonString is likeHow can i get region_name from that string ? Hope you understand me ! Try to use Test Link ! string url= @ '' http : //api.oodle.com/api/v2/listings ? key=TEST & region=chicago & category=vehicle & format=json '' ; string jsonString = new WebClient ( ) .DownloadString ( url ) ; { `` current '' : { `` region '' : { `` id '' : '' chicago '' , `` name '' : '' Chicago '' } , `` category '' : { `` id '' : '' vehicle '' , `` name '' : '' Cars & Vehicles '' , `` abbrev '' : '' Vehicles '' } , `` start '' :1 , `` num '' :10 } }",Confusion in fetching data from JSON "C_sharp : I 'm trying to programmatically add a menu to my MonoMac application . I 've opened up the MainMenu.xib and removed all NSMenuItem from the MainMenu control.I 'm adding the following code into my FinishedLaunching override : But it 's not doing anything.When I add the code to MainWindowController.Initialize ( ) , I get an assertion failure `` item to be inserted into menu already is in another menu '' I was porting the code found in this SO answer : Creating NSMenu with NSMenuItems in it , programmatically ? var fileMenuItem = new NSMenuItem ( `` File '' ) ; var fileMenu = new NSMenu ( ) ; var fileNew = new NSMenuItem ( `` New '' ) ; var fileOpen = new NSMenuItem ( `` Open '' ) ; var fileSave = new NSMenuItem ( `` Save '' ) ; fileMenu.AddItem ( fileNew ) ; fileMenu.AddItem ( fileOpen ) ; fileMenu.AddItem ( fileSave ) ; fileMenuItem.Menu = fileMenu ; NSApplication.SharedApplication.MainMenu.AddItem ( fileMenuItem ) ;",Creating NSMenuItems programmatically in MonoMac "C_sharp : Is there a way to set the value of an OutputCache based on a cookie value ? For simplicities sake , this is my methodMy Global.asax has this ( in order to override the GetVaryByCustomString methodI can verify that my browser has the ztest cookie , but when I debug the Index method , I hit the breakpoint every time ( meaning that the cache is n't working ) .The HttpResponse has no outbound cookies , so this point would not apply : https : //msdn.microsoft.com/en-us/library/system.web.httpcookie.shareable ( v=vs.110 ) .aspx If a given HttpResponse contains one or more outbound cookies with Shareable is set to false ( the default value ) , output caching will be suppressed for the response . This prevents cookies that contain potentially sensitive information from being cached in the response and sent to multiple clients . To allow a response containing cookies to be cached , configure caching normally for the response , such as using the OutputCache directive or MVC 's [ OutputCache ] attribute , and set all outbound cookies to have Shareable set to true . [ OutputCache ( Duration = 600 , VaryByParam = `` None '' , VaryByCustom = `` ztest '' ) ] public ViewResult Index ( ) { return View ( ) ; } public override string GetVaryByCustomString ( HttpContext context , string custom ) { if ( custom == `` ztest '' ) { HttpCookie ztest = context.Request.Cookies [ `` ztest '' ] ; if ( ztest ! = null ) { return ztest.Value ; } } return base.GetVaryByCustomString ( context , custom ) ; }",OutputCache VaryByCustom cookie value "C_sharp : I 'd like to traverse a directory on my hard drive and search through all the files for a specific search string . This sounds like the perfect candidate for something that could ( or should ) be done in parallel since the IO is rather slow.Traditionally , I would write a recursive function to finds and processes all files in the current directory and then recurse into all the directories in that directory . I 'm wondering how I can modify this to be more parallel . At first I simply modified : to but I feel that this might create too many tasks and get itself into knots , especially when trying to dispatch back onto a UI thread . I also feel that the number of tasks is unpredictable and that this might not be an efficient way to parallize ( is that a word ? ) this task.Has anyone successfully done something like this before ? What advice do you have in doing so ? foreach ( string directory in directories ) { ... } Parallel.ForEach ( directories , ( directory ) = > { ... } )",Task Parallel Library for directory traversal C_sharp : Can mock objects be used to return more than one desired result like below ? mockObject.Setup ( o = > o.foo ( It.IsAny < List < string > > ( ) ) ) .Returns ( fooBall ) ; mockObject.Setup ( o = > o.foo ( It.IsAny < int > ( ) ) ) .Returns ( fooSquare ) ;,Can mock objects setup to return two desired results ? "C_sharp : I 'm using Resharper 5.1.1 to reformat my code ( Cleanup Code , Ctrl+E , Ctrl+C ) . I ca n't get it to format my code the way I want it to . I want my code to look like this : My problem is with the enum . Since an enum is a type , just as a class is a type , they are treated the same . Therefor , the enum is formatted asThe curly braces of the type ( i.e . the enum ) are placed on a separate line and the members are also placed on a separate line . For a Class that is exactly what I want . But for a ( simple ) enum I just want them on a single line.For an auto property there is an exception ( Place abstract property/indexer/event declaration on single line ) , so the auto property is formatted the way I want it to.Is there an option in Resharper to have it place an enum on a single line ? UpdateAfter posting the same question on the Resharper forum , I 've been told it currently is n't possible . A Feature Request has been created for it . If you also feel this is an option you 'd like to see in a future version of Resharper , please vote for the request . public class Person { public enum Sex { Male , Female } public Sex Gender { get ; set ; } public Person ( Sex gender ) { Gender = gender ; } } public enum Sex { Male , Female }",Can Resharper have special settings for enum ? "C_sharp : I have spent a good time now on configuring my proxy . At the moment I use a service called proxybonanza . They supply me with a proxy which I use to fetch webpages.I 'm using HTMLAGILITYPACKNow if I run my code without a proxy there 's no problem locally or when uploaded to webhost server.If I decide to use the proxy , it takes somewhat longer but it stills works locally.I have been debugging this for a long time.My app.config has two entries that are relevant for this That helped me through a couple of problems.Now this is my C # code.What am I doing wrong ? I have enabled the tracer in the appconfig , but I do n't get a log on my webhost ... ? Can anyone spot the problem I have these setting on and off like a thousand times..Carl If I publish my solution to , to my webhost I get a SocketException ( 0x274c ) `` A connection attempt failed because the connected party did not properly respond after a period of time , or established connection failed because connected host has failed to respond 38.69.197.71:45623 '' httpWebRequest useUnsafeHeaderParsing= '' true '' httpRuntime executionTimeout= '' 180 '' HtmlWeb htmlweb = new HtmlWeb ( ) ; htmlweb.PreRequest = new HtmlAgilityPack.HtmlWeb.PreRequestHandler ( OnPreRequest ) ; HtmlDocument htmldoc = htmlweb.Load ( @ '' http : //www.websitetofetch.com , `` IP '' , port , `` username '' , `` password '' ) ; //This is the preRequest config static bool OnPreRequest ( HttpWebRequest request ) { request.KeepAlive = false ; request.Timeout = 100000 ; request.ReadWriteTimeout = 1000000 ; request.ProtocolVersion = HttpVersion.Version10 ; return true ; // ok , go on } Log stuff from app.config < system.diagnostics > < sources > < source name= '' System.ServiceModel.MessageLogging '' switchValue= '' Warning , ActivityTracing '' > < listeners > < add name= '' ServiceModelTraceListener '' / > < /listeners > < /source > < source name= '' System.ServiceModel '' switchValue= '' Verbose , ActivityTracing '' > < listeners > < add name= '' ServiceModelTraceListener '' / > < /listeners > < /source > < source name= '' System.Runtime.Serialization '' switchValue= '' Verbose , ActivityTracing '' > < listeners > < add name= '' ServiceModelTraceListener '' / > < /listeners > < /source > < /sources > < sharedListeners > < add initializeData= '' App_tracelog.svclog '' type= '' System.Diagnostics.XmlWriterTraceListener , System , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' name= '' ServiceModelTraceListener '' traceOutputOptions= '' Timestamp '' / > < /sharedListeners > < /system.diagnostics > request.KeepAlive = false ; System.Net.ServicePointManager.Expect100Continue = false ;",Proxy works locally but fails when uploaded to webhost "C_sharp : I 'm building a WPF app which will do some heavy work in the background . The issue is that when I run the task in the unit tests , it usually takes about 6~7s to run . But when I run it using TPL in WPF app , it takes somewhere between 12s~30s to run . Is there a way to speed up this thing . I 'm calling COM api of LogParser to do the real work . Update : My code for calling Log Parser API looks like belowThe thing now is with this change , I can see about 3 - 4s improvement in debugging mode , but not when I hit Ctrl + F5 to run it which is quite beyond me . How come ? ? var thread = new Thread ( ( ) = > { var logQuery = new LogQueryClassClass ( ) ; var inputFormat = new COMEventLogInputContextClassClass { direction = `` FW '' , fullText = true , resolveSIDs = false , formatMessage = true , formatMsg = true , msgErrorMode = `` MSG '' , fullEventCode = false , stringsSep = `` | '' , iCheckpoint = string.Empty , binaryFormat = `` HEX '' } ; try { Debug.AutoFlush = true ; var watch = Stopwatch.StartNew ( ) ; var recordset = logQuery.Execute ( query , inputFormat ) ; watch.Stop ( ) ; watch = Stopwatch.StartNew ( ) ; while ( ! recordset.atEnd ( ) ) { var record = recordset.getRecord ( ) ; recordProcessor ( record ) ; recordset.moveNext ( ) ; } recordset.close ( ) ; watch.Stop ( ) ; } catch { } finally { if ( logQuery ! = null ) { Marshal.ReleaseComObject ( logQuery ) ; GC.SuppressFinalize ( logQuery ) ; logQuery = null ; } } } ) ; thread.SetApartmentState ( ApartmentState.STA ) ; thread.Start ( ) ; thread.Join ( ) ;",How to improve performance of background task in WPF ? "C_sharp : I am fairly new to C # , and I come from a C++ background.I have defined a struct , and the ( Microsoft ) compiler keeps popping up the error CA1815 `` 'GenericSendRequest ' should override Equals '' I read a bit around and saw that C # structs derive from ValueType which impleents a generic Equals using reflection . This confused me more : Why does the compiler create an error instead of a warning if its just a performance issue ? Why does it define that generic Equals in the first place if it 's not going to let you use it ? So how can I tell the compiler that `` I do n't care '' ? Something similar with just declaring assignment operator in a C++ class without providing definition to acknowledge that I know what I am doing.So far my solution has been to include : in my struct , which is just awful.Edit : This is the struct definition : Its usage is just multiple return values from a function : public static bool operator == ( GenericSendRequest lhs , GenericSendRequest rhs ) { return lhs.Equals ( rhs ) ; } public static bool operator ! = ( GenericSendRequest lhs , GenericSendRequest rhs ) { return ! lhs.Equals ( rhs ) ; } public override bool Equals ( object obj ) { return base.Equals ( obj ) ; } //Yes , it also makes me override GetHashCode since I 'm overriding Equals . public override int GetHashCode ( ) { return base.GetHashCode ( ) ; } public struct GenericSendRequest { public LiveUser Sender ; public LiveUser [ ] Receivers ; public Message Msg ; public ServiceHttpRequest HttpRequest ; } public static GenericSendRequest CreateGenericSendRequest ( ... ) ;",Is there a compact way of telling the C # compiler to use the base Equals and == operator ? "C_sharp : I 've never really been a big fan of the way most editors handle namespaces . They always force you to add an extra pointless level of indentation . For instance , I have a lot of code in a page that I would much rather prefer formatted asand not something likeHonestly , I do n't really even like the class thing being indented most of the time because I usually only have 1 class per file . And it does n't look as bad here , but when you get a ton of code and lot of scopes , you can easily have indentation that forces you off the screen , and plus here I just used 2-space tabs and not 4-space as is used by us . Anyway , is there some way to get Visual Studio to stop trying to indent namespaces for me like that ? namespace mycode { class myclass { void function ( ) { foo ( ) ; } void foo ( ) { bar ( ) ; } void bar ( ) { //code.. } } } namespace mycode { class myclass { void function ( ) { foo ( ) ; } void foo ( ) { bar ( ) ; } void bar ( ) { //code.. } } }",Way to get VS 2008 to stop forcing indentation on namespaces ? "C_sharp : I have some extension methods which could be used like this : The problem here is that it needs an instance , even if the extension method only needs the type MyType . So if there is no instance , it needs to be called like this : Which is not so nice anymore.Is there a way to write better syntax for such cases ? What I actually want to do is this ( pseudo language ) : Which of course does not work with C # .But what about something like this : This is also not possible ( after a lambda , a dot is not accepted ) . Any ideas ? Edit : My `` favorite syntax '' MyType.Property.GetDisplayName ( ) seems to be misleading . I do n't talk about static properties here . I know that this syntax wo n't be possible . I just tried to show in pseudo language , what information is necessary . This would be ideal , every additional stuff is just syntactical overhead . Any working syntax that is close to this would be great.I do n't want to write a certain extension method . I want an easy , readable and compile time safe syntax , using any language feature . MyType myObject ; string displayName = myObject.GetDisplayName ( x = > x.Property ) ; string displayName = BlahBlahUtility.GetDisplayName ( ( MyTpe x ) = > x.Property ) ; string displayName = MyType.Property.GetDisplayName ( ) string displayName = ( ( MyType x ) = > x.Property ) .GetDisplayName ( ) ;",C # Extension methods on `` members '' C_sharp : A question was raised in a discussion I had around whether an interface method should return a Custom object vs a primitive type.e.g . vs Where MyFooObj is : The argument being that you can easily add properties to the object in the future without needing to change the interface contract.I am unsure what the standard guidelines on this are ? public interface IFoo { bool SomeMethod ( ) ; } public interface IFoo { MyFooObj SomeMethod ( ) ; } public class MyFooObj { bool SomeProp { get ; set ; } },Should an interface method return a custom object ? "C_sharp : It is known that , unlike Java 's volatiles , .NET 's ones allow reordering of volatile writes with the following volatile reads from another location . When it is a problem MemoryBarier is recommended to be placed between them , or Interlocked.Exchange can be used instead of volatile write . It works but MemoryBarier could be a performance killer when used in highly optimized lock-free code . I thought about it a bit and came with an idea . I want somebody to tell me if I took the right way.So , the idea is the following : We want to prevent reordering between these two accesses : From .NET MM we know that : To prevent unwanted reordering between write and read we introduce a dummy volatile read from the variable we 've just written to : In such case B can not be reordered with A as they both access the same variable , C can not be reordered with B because two volatile reads can not be reordered with each other , and transitively C can not be reordered with A.And the question : Am I right ? Can that dummy volatile read be used as a lightweight memory barrier for such scenario ? volatile1 write volatile2 read 1 ) writes to a variable can not be reordered with a following read from the same variable 2 ) no volatile accesses can be eliminated 3 ) no memory accesses can be reordered with a previous volatile read A ) volatile1 write B ) volatile1 read [ to a visible ( accessible | potentially shared ) location ] C ) volatile2 read",Memory Model : preventing store-release and load-acquire reordering "C_sharp : Recently , I came across some troubles about boxing using Expression Trees when I was developing my homemade SQLite ORM . I am still coding again C # 3.5.To make a long story short , I 'm gon na use this simple class definition : So this from that POCO class definition I instantiated a new object and my ORM engine converted that object into a record and it 's properly inserted . Now the trick is that when I get back the value from SQLite I got an Int64.I thought that my delegate setter was OK because it 's an Action < Object , Object > but I still got that InvalidCastException . Seems that the Object ( parameter , an Int64 ) is attempted to be cast into a UInt32 . Unfortunately it does not work . I tried to add some Expression.Constant and Expression.TypeAs ( that one does not really help for value typed objects ) . So I am wondering what sort of things are wrong in my setter generation.Here below is my setter generation method : So basically : I should probably add another Expression.Convert but I do not really know how it would help to make it work . Since there is already one supposed to ( attempt to ) convert from any Object to the property type ( here in my example the UInt32 type ) .Any idea to fix it up ? [ Table ] public class Michelle { [ Column ( true ) , PrimaryKey ] public UInt32 A { get ; set ; } [ Column ] public String B { get ; set ; } } public static Action < Object , Object > GenerateSetter ( PropertyInfo propertyInfo ) { if ( ! FactoryFastProperties.CacheSetters.ContainsKey ( propertyInfo ) ) { MethodInfo methodInfoSetter = propertyInfo.GetSetMethod ( ) ; ParameterExpression parameterExpressionInstance = Expression.Parameter ( FactoryFastProperties.TypeObject , `` Instance '' ) ; ParameterExpression parameterExpressionValue = Expression.Parameter ( FactoryFastProperties.TypeObject , `` Value '' ) ; UnaryExpression unaryExpressionInstance = Expression.Convert ( parameterExpressionInstance , propertyInfo.DeclaringType ) ; UnaryExpression unaryExpressionValue = Expression.Convert ( parameterExpressionValue , propertyInfo.PropertyType ) ; MethodCallExpression methodCallExpression = Expression.Call ( unaryExpressionInstance , methodInfoSetter , unaryExpressionValue ) ; Expression < Action < Object , Object > > expressionActionObjectObject = Expression.Lambda < Action < Object , Object > > ( methodCallExpression , new ParameterExpression [ ] { parameterExpressionInstance , parameterExpressionValue } ) ; FactoryFastProperties.CacheSetters.Add ( propertyInfo , expressionActionObjectObject.Compile ( ) ) ; } return FactoryFastProperties.CacheSetters [ propertyInfo ] ; } // Considering setter as something returned by the generator described above// So : // That one works ! setter ( instance , 32u ) ; // This one ... hm not really =/setter ( instance , 64 ) ;",Explicit Boxing between does not work properly with Expression.Convert ? "C_sharp : Code below generates output as { `` error_message '' : null , '' status '' : '' InvalidRequest '' } where I would like to get it as { `` error_message '' : null , '' status '' : '' INVALID_REQUEST '' } So simply , I was wondering how to honor PropertyName attribute while serializing with JSON.NET ? void Main ( ) { var payload = new GooglePlacesPayload ( ) ; payload.Status = StatusCode.InvalidRequest ; JsonConvert.SerializeObject ( payload ) .Dump ( ) ; } public class GooglePlacesPayload { [ JsonProperty ( PropertyName = `` error_message '' ) ] public string ErrorMessage { get ; set ; } [ JsonProperty ( PropertyName = `` status '' ) ] [ JsonConverter ( typeof ( StringEnumConverter ) ) ] public StatusCode Status { get ; set ; } } [ Flags ] public enum StatusCode { // reference https : //developers.google.com/maps/premium/previous-licenses/articles/usage-limits # limitexceeded // reference https : //developers.google.com/places/web-service/search # PlaceSearchStatusCodes None = 0 , // indicates that no errors occurred ; the place was successfully detected and at least one result was returned . [ JsonProperty ( PropertyName = `` OK '' ) ] Ok = 1 , // indicates that the search was successful but returned no results . This may occur if the search was passed a latlng in a remote location . [ JsonProperty ( PropertyName = `` ZERO_RESULTS '' ) ] ZeroResults = 2 , // indicates that you are over your quota . The daily quotas are reset at midnight , Pacific Time . [ JsonProperty ( PropertyName = `` OVER_QUERY_LIMIT '' ) ] OverQueryLimit = 4 , // indicates that your request was denied , generally because of lack of an invalid key parameter . [ JsonProperty ( PropertyName = `` REQUEST_DENIED '' ) ] RequestDenied = 8 , // generally indicates that a required query parameter ( location or radius ) is missing . [ JsonProperty ( PropertyName = `` INVALID_REQUEST '' ) ] InvalidRequest = 16 , // When the Google Places service returns a status code other than OK , there may be an additional error_message field within the search response object . // This field contains more detailed information about the reasons behind the given status code . Positive = Ok | ZeroResults , Negative = OverQueryLimit | RequestDenied | InvalidRequest }",How to serialize an enum with JSON.NET based on an attribute ? "C_sharp : My application was crashing with out-of-memory exceptions and sometimes other exceptions probably also caused by running out of memory.I reproduced the problem with this simple code : In theory this code should not crash because the bitmaps should be automatically garbage collected , but it crashes consistently when running in 32 bit mode.The problem can be fixed like this : Of course this solution is contrary to the common wisdom that you should n't explicitly call GC.Collect , but I suspect that this is a scenario where it does actually make sense.Can anyone offer any informed insight into this ? Is there a better way of solving the problem ? for ( int i = 0 ; i < 100000 ; i++ ) var bmp = new RenderTargetBitmap ( 256 , 256 , 96 , 96 , PixelFormats.Default ) ; for ( int i = 0 ; i < 100000 ; i++ ) { var bmp = new RenderTargetBitmap ( 256 , 256 , 96 , 96 , PixelFormats.Default ) ; if ( i % 500 == 0 ) { GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; } }",Out-of-memory due to latency of unmanaged memory disposal ? "C_sharp : I managed to run my self hosted WEP API using OWIN in a console application by starting it with a code like this : By using and registering an address like `` http : //+:9000/ '' on the service host machine the idea was to use a generic IP address for the host that would not affect the clients when the IP of the host might change.The clients are on other machines than the one that is running the service . Something like a mobile phone from the LAN or another laptop from the LAN , and in the future if possible also outside the LAN . In the client of my self hosted service , which is a html page , I have a JavaScript code like : By using the static commented IP address of the host in the client I can get to the self hosted WEB API but when I try to use the generic one `` http : //+:9000/api/tests '' it fails to connect to the service.Is there a way to connect from the client to the service by using such a generic configuration ? or how should I configure the service host machine and the client so that an IP change on the host will not stop the service on the client machine ? I need to take into account that the IP address of my self hosted machine might change and the clients will lose the connection since they will use an old outdated IP address of the service host machine . //string baseAddress = `` http : //192.168.1.6:8111/ '' ; string baseAddress = `` http : //+:8111/ '' ; // Start OWIN host using ( Microsoft.Owin.Hosting.WebApp.Start < Startup > ( url : baseAddress ) ) { Console.ReadLine ( ) ; } //var uri = 'http : //192.168.1.6:8111/api/tests ' ; var uri = 'http : //+:8111/api/tests ' ; function Read ( ) { $ .getJSON ( uri + '/ ' + id ) }",Web API self hosted client configuration "C_sharp : I want to know what is best way to call nested async methods , if I want both methods to be async . First : Caller method must just return Task Second : Caller method must have an async-await as called method public async Task SaveChangesAsync ( ) { await Context.SaveChangesAsync ( ) ; } public Task UpdateAsync ( List < TEntity > entities ) { foreach ( TEntity entity in entities ) { BeforeUpdate ( entity ) ; Context.Entry ( entity ) .State = EntityState.Modified ; } return SaveChangesAsync ( ) ; } public async Task SaveChangesAsync ( ) { await Context.SaveChangesAsync ( ) ; } public async Task UpdateAsync ( List < TEntity > entities ) { foreach ( TEntity entity in entities ) { BeforeUpdate ( entity ) ; Context.Entry ( entity ) .State = EntityState.Modified ; } await SaveChangesAsync ( ) ; }",How to call nested Async method "C_sharp : I searched around SO and found various related questions , some answered with essentially `` do n't do that . `` I want to call some unmanaged C++ code that accesses various existing C++ code . The existing code may have a variety of error conditions that I want to map into C # exceptions . From doing something similar in Java and JNI , it seemed that it might be possible to have a delegate function to raise defined exceptions , which could then be called directly from unmanaged code . The calls then look like ( csharp ) - > ( unmanaged ) - > ( csharp delegate , throw/set pending exception ) and then return back up . The code below seems to work fine ( vs2010 , mono ) . My question is is there any problem with this approach - e.g . the spec says that the exception is not guaranteed to still be `` pending '' after unmanaged code is called , or threading issues , etc ... Updated : Corrected test and output , showing mono and Windows ( with /EHsc ) leaks // unmanaged.cpp # include < cstdio > # define EXPORT __declspec ( dllexport ) # define STDCALL __stdcalltypedef void ( STDCALL* raiseExcpFn_t ) ( const char * ) ; extern `` C '' { // STRUCT ADDED TO TEST CLEANUP struct Allocated { int x ; Allocated ( int a ) : x ( a ) { } ~Allocated ( ) { printf ( `` -- - Deleted allocated stack ' % d ' -- -\n '' , x ) ; fflush ( stdout ) ; } } ; static raiseExcpFn_t exceptionRaiser = 0 ; EXPORT void STDCALL registerRaiseExcpFn ( raiseExcpFn_t fun ) { exceptionRaiser = fun ; } EXPORT void STDCALL hello ( const char * x ) { Allocated a0 ( 0 ) ; try { Allocated a1 ( 1 ) ; printf ( `` 1 -- - ' % s ' -- -\n '' , x ) ; fflush ( stdout ) ; ( *exceptionRaiser ) ( `` Something bad happened ! `` ) ; printf ( `` 2 -- - ' % s ' -- -\n '' , x ) ; fflush ( stdout ) ; } catch ( ... ) { printf ( `` 3 -- - ' % s ' -- -\n '' , x ) ; fflush ( stdout ) ; throw ; } printf ( `` 4 -- - ' % s ' -- -\n '' , x ) ; fflush ( stdout ) ; } } // Program.csusing System ; using System.Runtime.InteropServices ; class Program { [ DllImport ( `` unmanaged.dll '' ) ] public static extern void registerRaiseExcpFn ( RaiseException method ) ; [ DllImport ( `` unmanaged.dll '' ) ] public static extern void hello ( [ MarshalAs ( UnmanagedType.LPStr ) ] string m ) ; public delegate void RaiseException ( string s ) ; public static RaiseException excpfnDelegate = new RaiseException ( RaiseExceptionMessage ) ; // Static constructor ( initializer ) static Program ( ) { registerRaiseExcpFn ( excpfnDelegate ) ; } static void RaiseExceptionMessage ( String msg ) { throw new ApplicationException ( msg ) ; } public static void Main ( string [ ] args ) { try { hello ( `` Hello World ! `` ) ; } catch ( Exception e ) { Console.WriteLine ( `` Exception : `` + e.GetType ( ) + `` : '' + e.Message ) ; } } } // Observed output // with Release builds /EHa , VS2010 , .Net 3.5 target//cstest.exe// -- - Deleted allocated stack ' 0 ' -- -// -- - Deleted allocated stack ' 1 ' -- -// 1 -- - 'Hello World ! ' -- -// 3 -- - 'Hello World ! ' -- -// Exception : System.ApplicationException : Something bad happened ! // Observed LEAKING output // with Release builds /EHsc , VS2010 , .Net 3.5 target// cstest.exe// 1 -- - 'Hello World ! ' -- -// Exception : System.ApplicationException : Something bad happened ! // LEAKING output DYLD_LIBRARY_PATH= ` pwd ` mono program.exe // 1 -- - 'Hello World ! ' -- -// Exception : System.ApplicationException : Something bad happened !",Can an .Net exception be raised from unmanaged code using a delegate function ? "C_sharp : I am using AWS.Net to upload user content ( images ) and display them on my site . This is what my code looks like currently for the upload : Whats the best way to store the path to these files ? Is there a way to get a link to my file from the response ? Currently I just have a URL in my webconfig like https : //s3.amazonaws.com/ < MyBucketName > / and then when I need to show an image I take that string and use the key from the object I store in the db that represents the file uploaded.Is there a better way to do this ? All the examples that come with it do n't really address this kind of usage . And the documentation is n't online and I do n't know how to get to it after I install the SDK , despite following the directions on Amazon . using ( client = Amazon.AWSClientFactory.CreateAmazonS3Client ( ) ) { var putObjectRequest = new PutObjectRequest { BucketName = bucketName , InputStream = fileStream , Key = fileName , CannedACL = S3CannedACL.PublicRead , //MD5Digest = md5Base64 , //GenerateMD5Digest = true , Timeout = 3600000 //1 Hour } ; S3Response response = client.PutObject ( putObjectRequest ) ; response.Dispose ( ) ; }",Using S3 Storage with .NET "C_sharp : If I create a new WPF application with a simple empty window like the code shown below , I find that all applications which are covered by the WPF app lost touch or stylus reaction . This can only be reproduced when Windows 10 is upgraded to 1803 ( 10.0.17134.0 ) .I wrote another WPF application to find out what happened . So I add a StylusDown event to the Window like the code shown below : But the breakpoint never reached until I closed the transparent WPF window which is on top.I pushed the very simple code to GitHub : dotnet-campus/TouchIssueOnWindows10.0.17134 . Cloning it might help a little.Why does this happen and how to solve it ? Any reply is appreciated . < Window x : Class= '' TheWPFCoveringWindow.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' WindowStyle= '' None '' WindowState= '' Maximized '' AllowsTransparency= '' True '' Background= '' Transparent '' Topmost= '' True '' > < Button Content= '' Test '' Width= '' 200 '' Height= '' 100 '' / > < /Window > // This code is in another WPF application.private void OnStylusDown ( object sender , StylusDownEventArgs e ) { // Set a breakpoint here . }","On Windows 10 ( 1803 ) , all applications lost touch or stylus if a WPF transparent window covers on them" "C_sharp : I have a C # solution with several projects , one of which is a web server run by IIS . I have set < UseGlobalApplicationHostFile > True < /UseGlobalApplicationHostFile > in the csproj file of that project.When I open Visual Studio , it generates this in ~/Documents/IISExpress/config/applicationhost.config : I want to be able to run my project with IIS Express from the command line ( for build server integration testing purposes ) . How can I generate the SealingService site section of applicationhost.config from the command line ( without opening Visual Studio ) ? I have tried running in my solution folder , but it only generates the WebSite1 section . < sites > < site name= '' WebSite1 '' id= '' 1 '' serverAutoStart= '' true '' > < application path= '' / '' > < virtualDirectory path= '' / '' physicalPath= '' % IIS_SITES_HOME % \WebSite1 '' / > < /application > < bindings > < binding protocol= '' http '' bindingInformation= '' :8080 : localhost '' / > < /bindings > < /site > < site name= '' SealingService '' id= '' 2 '' > < application path= '' / '' applicationPool= '' Clr4IntegratedAppPool '' > < virtualDirectory path= '' / '' physicalPath= '' C : \Users\sehch\Documents\Paragon\ParagonCore\servers\SealingService\SealingService '' / > < /application > < bindings > < binding protocol= '' http '' bindingInformation= '' *:61800 : localhost '' / > < binding protocol= '' https '' bindingInformation= '' *:44300 : localhost '' / > < /bindings > < /site > < siteDefaults > < logFile logFormat= '' W3C '' directory= '' % IIS_USER_HOME % \Logs '' / > < traceFailedRequestsLogging directory= '' % IIS_USER_HOME % \TraceLogFiles '' enabled= '' true '' maxLogFileSizeKB= '' 1024 '' / > < /siteDefaults > < applicationDefaults applicationPool= '' Clr4IntegratedAppPool '' / > < virtualDirectoryDefaults allowSubDirConfig= '' true '' / > < /sites > `` C : \Program Files ( x86 ) \IIS Express\iisexpress.exe ''",IIS CLI generate applicationhost.config with site for my project "C_sharp : I want to create gridview with code . My code is : this code does not work , and how to add TemplateField do : how can do it ? GridView gdvList = new GridView ( ) ; gdvList.ID = `` gdvList '' ; TemplateField tField = new TemplateField ( ) ; BoundField dateBF = new BoundField ( ) ; dateBF.DataField = `` Date '' ; gdvList.Columns.Add ( dateBF ) ; BoundField countResponse = new BoundField ( ) ; countResponse.DataField = `` CountResponse '' ; gdvList.Columns.Add ( countResponse ) ; ObjectDataSource ods = new ObjectDataSource ( ) ; ods.ID = `` ods '' ; ods.TypeName = `` Project.BLLQuestion '' ; ods.SelectMethod = `` GetByGroupID '' ; ods.SelectParameters [ `` GroupID '' ] = new Parameter ( `` inGroupID '' , DbType.Int32 , `` 0 '' ) ; ods.DataBind ( ) ; gdvList.DataSource = ods ; gdvList.DataBind ( ) ; < asp : TemplateField ItemStyle-CssClass= '' GridItemTemplateField '' > < ItemTemplate > < a href= '' Question.aspx ? id= < % # Eval ( `` ID '' ) % > '' > < % # Eval ( `` Content '' ) .ToString ( ) .PadRight ( 140 ) .Substring ( 0,140 ) .TrimEnd ( ) + '' ... '' % > < /a > < /ItemTemplate > < /asp : TemplateField >",how to add gridview with objectdatasource in code behind c # ? "C_sharp : The following program prints ( as it should ) however , if I change keyword 'new ' to 'override ' in class B like so : all of a sudden program starts to print : Why ? A : C ( A , B ) B : C ( A , B ) public interface I { string A ( ) ; } public class C : I { public string A ( ) { return `` A '' ; } public string B ( ) { return `` B '' ; } } public class A { public virtual void Print ( C c ) { Console.WriteLine ( `` A : C ( `` + c.A ( ) + `` , '' + c.B ( ) + `` ) '' ) ; } } public class B : A { public new void Print ( C c ) { Console.WriteLine ( `` B : C ( `` + c.A ( ) + `` , '' + c.B ( ) + `` ) '' ) ; } public void Print ( I i ) { Console.WriteLine ( `` B : I ( `` + i.A ( ) + `` ) '' ) ; } } class Program { public static void Main ( string [ ] args ) { A a = new A ( ) ; B b = new B ( ) ; C c = new C ( ) ; a.Print ( c ) ; b.Print ( c ) ; } } public override void Print ( C c ) A : C ( A , B ) B : I ( A )",How method hiding works in C # ? ( Part Two ) "C_sharp : As experiencing the new async & Await features of 4.5 I want to clear some confusions before going any further . I have been reading different article and also different question on SO and it help me undertands how Async and Await works . I will just try to put my understanding and confusions here and will appreciate if someone code educate me and other people who are looking for same things . I am discussing this in very simple wordings.So Async is used so that compiler know that method marked by Async contains Await operation ( Long operation ) . Latest framework contains different new builtin methods for Async Operations.The builtin Async functions like connection.OpenAsync , ExecuteScalarAsync etc are used with Await keyword . I do n't know the inner working of these Async Methods but my strong guess is that under the hood they are using Tasks . Can I make this as general rule that Await will be with any method which implements Task . So if I need to create my own method which is performing long operation then will I create it as Task and when it is called I will use Await Keyword with it ? Second most important thing is that what is the rule of thumb of creating a method as Async or creating it as task . For example , Now this is a very simple scenario that I have created based on some real world application I worked in past . So I was just wondering how to make this whole process Async.Should I make GetPrimaryConnectionString and GetSecondaryConnectionString as Tasks and Await them in ReadData . Will ReadData be also a Task ? How to call ReadData in the SampleMain function ? Another way could be to create a Task for ReadData in SampleMain and run that Task and skip converting other methods as Task . Is this the good approach ? Will it be truly Asynchronous ? public void SampleMain ( ) { for ( int i = 1 ; i < = 100 ; i++ ) { DataTable dt = ReadData ( int id ) ; } } public DataTable ReadData ( int id ) { DataTable resultDT = new DataTable ( ) ; DataTable dt1 = new DataTable ( ) ; // Do Operation to Fill DataTable from first connection string adapter.Fill ( dt1 ) ; DataTable dt2 = new DataTable ( ) ; // Do Operation to Fill DataTable from first connection string adapter.Fill ( dt2 ) ; // Code for combining datatable and returning the resulting datatable // Combine DataTables return resultDT ; } public string GetPrimaryConnectionString ( ) { // Retrieve connection string from some file io operations return `` some primary connection string '' ; } public string GetSecondaryConnectionString ( ) { // Retrieve connection string from some file io operations return `` some secondaryconnection string '' ; }",Async Await Few Confusions "C_sharp : My project solution is currently having three projects : MyProject , which is my main startup project ( using .NET Framework 4.7 ) - WPF , UI specfic , MyProject.Core - class library ( .NET Standard 2.0 ) - holding the models , and all of the 'behind the scenes ' dataMyProject.Relational - class library ( .NET Standard 2.0 ) - responsible for processing and saving the database specific informationsProject 1 ( main ) has set a reference to project 2 and 3.For the project 3 I have installed a NuGet dependency of Microsoft.EntityFrameworkCore.Sqlite ( 2.0.3 ) .Now , when I finally want to make use of project 3 and call it 's method , the following exception is being thrown : This , of course is a missing DLL file - no entity framework DLL 's are being copied to the app Debug directory.Why is that ? Is this intended behaviour ? Do I have to install the dependency of Microsoft.EntityFrameworkCore.Sqlite for project 1 as well ? Pretty pointless to me , referencing the same dependency to project that is making no use of it . What have I tried : Cleaning up the project , removing bin/obj directories , Set project reference properties setting copy local to True , Solutions given in this question : Referenced DLL not being copied to referencing projectUsing Visual Studio 2017 . System.IO.FileNotFoundException : 'Could not load file or assembly 'Microsoft.EntityFrameworkCore , Version=2.0.3.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 ' or one of its dependencies . The system can not find the file specified .",Referenced project dependencies DLL are not being copied "C_sharp : So I decided to upgrade my version of simpleinjector to 3.0 , and all of a sudden I get a message : 'SimpleInjector.Extensions.OpenGenericBatchRegistrationExtensions.RegisterManyForOpenGeneric ( SimpleInjector.Container , System.Type , params System.Reflection.Assembly [ ] ) ' is obsolete : 'This extension method has been removed . Please use Container.Register ( Type , IEnumerable ) instead.The documentation still has this method in there : http : //simpleinjector.readthedocs.org/en/latest/advanced.htmlSo I 'm curious , what 's the alternative to : container.RegisterManyForOpenGeneric ( typeof ( IEventHandler < > ) , container.RegisterAll , typeof ( IEventHandler < > ) .Assembly ) ;",simpleinjector 3.0 not supporting RegisterManyForOpenGeneric "C_sharp : I was trying to use the pagedList.mvc package to page the results i get from a query and i did it like this in my controller.and in my view i did thisHowever when i run build this code and i navigate to the page i get an error saying Please how do i solve this ? public ActionResult AllPosts ( ) { int pageSize = 4 ; int pageNum = ( page ? ? 1 ) ; var query = from p in db.Postsselect new ListPostsVM ( ) { PostTitle = p.PostTitle , Author = p.UserProfile.UserName , DateCreated = p.DateCreated , CategoryName = p.Category.CategoryName } ; return View ( query.ToPagedList ( pageNum , pageSize ) ) ; } @ model IPagedList < Blogger.ViewModels.ListPostsVM > @ using PagedList ; @ using PagedList.Mvc ; @ { ViewBag.Title = `` AllPosts '' ; Layout = `` ~/Views/Shared/_AdminLayout.cshtml '' ; } < link href= '' ~/Content/PagedList.css '' rel= '' stylesheet '' / > < h2 > AllPosts < /h2 > < div class= '' allposts '' > < table class= '' table '' > < tr > < th > Title < /th > < th > Author < /th > < th > Category < /th > < th > Date < /th > < /tr > @ foreach ( var item in Model ) { < tr > < td > @ item.PostTitle < p class= '' actions '' > Edit | Delete | View < /p > < /td > < td > @ item.Author < /td > < td > @ item.CategoryName < /td > < td > @ item.DateCreated < /td > < /tr > } < /table > < /div > @ Html.PagedListPager ( Model , page = > Url.Action ( `` Index '' , new { page = page } ) , PagedListRenderOptions.OnlyShowFivePagesAtATime ) An exception of type 'System.NotSupportedException ' occurred in System.Data.Entity.dll but was not handled in user codeAdditional information : The method 'Skip ' is only supported for sorted input in LINQ to Entities . The method 'OrderBy ' must be called before the method 'Skip ' .",Errors in using PagedList.Mvc "C_sharp : I have a Web API project which uses StructureMap for its DI . It 's been working fine for awhile , but I 'm having some issues with the Web API help pages ( Microsoft.AspNet.WebApi.HelpPage ) where InvalidOperationExceptions are being thrown as a result of an empty stack . I created a new Web API project with the help pages , and it works fine until I add the StructureMap.WebApi2 package , whereas the previously mentioned exception is being thrown here , inside ModelDescriptionLink.cshtmlIt 's being thrown at @ : Collection of @ Html.DisplayFor ( m = > elementDescription.ModelType , `` ModelDescriptionLink '' , new { modelDescription = elementDescription } ) when it tries to display the link to the resource description for his this model.This is a slimmed down route that still causes the exception : Attempting to visit the documentation for this route at http : //localhost:21966/Help/Api/POST-Test causes the exception : I was only able to find one example of someone having the same problem and their solutions were to switch from StructureMap to Ninject or to avoid the exception with null checks . Here 's the top of the stack trace : By catching the exception in this place , it pops up later on in HelpPageApiModel.cshtml on a nearly identical line : @ Html.DisplayFor ( m = > m.ResourceDescription.ModelType , `` ModelDescriptionLink '' , new { modelDescription = Model.ResourceDescription } ) . This is the top of that stack trace : else if ( modelDescription is CollectionModelDescription ) { var collectionDescription = modelDescription as CollectionModelDescription ; var elementDescription = collectionDescription.ElementDescription ; @ : Collection of @ Html.DisplayFor ( m = > elementDescription.ModelType , `` ModelDescriptionLink '' , new { modelDescription = elementDescription } ) } else { @ Html.DisplayFor ( m = > modelDescription ) } [ Route ( `` Test '' ) ] public IHttpActionResult Post ( [ FromBody ] IEnumerable < MySimpleModel > models ) { return null ; } [ InvalidOperationException : Stack empty . ] System.ThrowHelper.ThrowInvalidOperationException ( ExceptionResource resource ) +52System.Collections.Generic.Stack ` 1.Peek ( ) +6693321System.Web.WebPages.WebPageBase.get_Output ( ) +51System.Web.WebPages.WebPageBase.GetOutputWriter ( ) +35System.Web.WebPages.WebPageExecutingBase.BeginContext ( String virtualPath , Int32 startPosition , Int32 length , Boolean isLiteral ) +50ASP._Page_Areas_HelpPage_Views_Help_DisplayTemplates_ModelDescriptionLink_cshtml.Execute ( ) in c : ... ModelDescriptionLink.cshtml:28System.Web.WebPages.WebPageBase.ExecutePageHierarchy ( ) +271System.Web.Mvc.WebViewPage.ExecutePageHierarchy ( ) +122System.Web.WebPages.WebPageBase.ExecutePageHierarchy ( WebPageContext pageContext , TextWriter writer , WebPageRenderingBase startPage ) +145System.Web.Mvc.RazorView.RenderView ( ViewContext viewContext , TextWriter writer , Object instance ) +695System.Web.Mvc.BuildManagerCompiledView.Render ( ViewContext viewContext , TextWriter writer ) +382System.Web.Mvc.Html.ActionCacheViewItem.Execute ( HtmlHelper html , ViewDataDictionary viewData ) +278 [ InvalidOperationException : Stack empty . ] System.ThrowHelper.ThrowInvalidOperationException ( ExceptionResource resource ) +52System.Collections.Generic.Stack ` 1.Pop ( ) +6667365System.Web.WebPages.WebPageBase.PopContext ( ) +66System.Web.WebPages.WebPageBase.ExecutePageHierarchy ( WebPageContext pageContext , TextWriter writer , WebPageRenderingBase startPage ) +154",StructureMap causes Stack Empty exception in Web API Help Pages ModelDescriptionLink.cshtml "C_sharp : I have a externall dll in which following is definedI am calling this dll from repository to perform CRUD in my webapi application , now in my repostory i am writing GetMovieById method in which i am confused what to return if a movie is not found in repository and what is the more appropriate way to handle this in webapi ? MovieRepositoryMoviesController namespace MoviesLibrary { public class MovieDataSource { public MovieDataSource ( ) ; public int Create ( MovieData movie ) ; public List < MovieData > GetAllData ( ) ; public MovieData GetDataById ( int id ) ; public void Update ( MovieData movie ) ; } } public Movie GetMovieById ( int movieId ) { MovieData movieData = new MovieDataSource ( ) .GetDataById ( movieId ) ; if ( movieData ! = null ) { return MovieDataToMovieModel ( movieData ) ; } else { ? ? } } /// < summary > /// Returns a movie/// < /summary > /// < param name= '' movie '' > movieId < /param > /// < returns > Movie < /returns > public Movie Get ( int movieId ) { //try // { var movie = repository.GetMovieById ( movieId ) ; if ( movie == null ) { throw new HttpResponseException ( HttpStatusCode.NotFound ) ; } return movie ; // } //catch ( Exception e ) // { // if ( e is HttpResponseException ) // throw new HttpResponseException ( HttpStatusCode.NotFound ) ; // } }",handling not found object in repository C_sharp : Bellow is simplified version of the code I have : The problem is in GetControl method of ControlFactory class . Because it returns IControl and I have only IControl < T > that is a generic interface . I can not provide T because in Bool case it 's going to bool and in String case it 's going to be string.Any idea what I need to do to make it work ? public interface IControl < T > { T Value { get ; } } public class BoolControl : IControl < bool > { public bool Value { get { return true ; } } } public class StringControl : IControl < string > { public string Value { get { return `` '' ; } } } public class ControlFactory { public IControl GetControl ( string controlType ) { switch ( controlType ) { case `` Bool '' : return new BoolControl ( ) ; case `` String '' : return new StringControl ( ) ; } return null ; } },Generic class factory problem "C_sharp : I am creating a Window in a different thread that 's marked STA this window has a few controls and images.I than go and close this window and open another window in the main UI Thread in this I have a print dialog and use the following code to get a FixedDocumentSequence : On the line : I am getting a InvalidOperationException from a internal call to VerifyAccess , this is the StackTrace : Since the StackTrace does some call to BitmapSource/BitmapDecoder , I thought about trying to remove the Images and set the Source of the in-place Image controls to nullAfter I did this with all of my Images my code was running smoothly and no more exception was firing.I tried to make a customimage to solve this problem with the following : But I am still getting the error.Preferable I am searching for a solution that works on all images in my WPF application.Hope I made my self clear , since this is rather odd to explain with the 2 threads and a random exception at some point.Edit : After some further testing I am now able to present to you a reproducible application with the problem at hand , hope its clearer with this.You need 3 windows , 1 folder and 1 image.In my case itsMainWindow.xamlWindow1.xamlWindow2.xamlImages is the name of the folder , and in there is an image called `` plus.png '' .MainWindow.xaml : MainWindow.xaml.cs : Window1.xaml : Window1.xaml.cs : No Code in there just constructor ... Window2.xaml : Window2.xaml.cs : App.xaml : Steps to reproduce : In the MainWindow click on the button saying `` Open Window 1 '' .A window will popup in a second UI-Thread , close this Window.Click the button saying `` Open Window 2 '' A window will popup in the main UI-ThreadHit the button saying `` Print Me '' , application should crashHope its now easier to help me out.Edit2 : Added the missing code part , sorry about this mistake.Another info that might help solve the problem is that when you click the buttons in reversed order - first Window 2 and than Window 1 - and than go try to print no exception will fire , so I still believe that its some image caching problem , that when the image first gets loaded into main UI-Thread printing works if not it will fail . var tempFileName = System.IO.Path.GetTempFileName ( ) ; File.Delete ( tempFileName ) ; using ( var xpsDocument = new XpsDocument ( tempFileName , FileAccess.ReadWrite , CompressionOption.NotCompressed ) ) { var writer = XpsDocument.CreateXpsDocumentWriter ( xpsDocument ) ; writer.Write ( this.DocumentPaginator ) ; } using ( var xpsDocument = new XpsDocument ( tempFileName , FileAccess.Read , CompressionOption.NotCompressed ) ) { var xpsDoc = xpsDocument.GetFixedDocumentSequence ( ) ; return xpsDoc ; } writer.Write ( this.DocumentPaginator ) ; bei System.Windows.Threading.Dispatcher.VerifyAccess ( ) bei System.Windows.Threading.DispatcherObject.VerifyAccess ( ) bei System.Windows.Media.Imaging.BitmapDecoder.get_IsDownloading ( ) bei System.Windows.Media.Imaging.BitmapFrameDecode.get_IsDownloading ( ) bei System.Windows.Media.Imaging.BitmapSource.FreezeCore ( Boolean isChecking ) bei System.Windows.Freezable.Freeze ( Boolean isChecking ) bei System.Windows.PropertyMetadata.DefaultFreezeValueCallback ( DependencyObject d , DependencyProperty dp , EntryIndex entryIndex , PropertyMetadata metadata , Boolean isChecking ) bei System.Windows.Freezable.FreezeCore ( Boolean isChecking ) bei System.Windows.Media.Animation.Animatable.FreezeCore ( Boolean isChecking ) bei System.Windows.Freezable.Freeze ( ) bei System.Windows.Media.DrawingDrawingContext.DrawImage ( ImageSource imageSource , Rect rectangle , AnimationClock rectangleAnimations ) bei System.Windows.Media.DrawingDrawingContext.DrawImage ( ImageSource imageSource , Rect rectangle ) bei System.Windows.Media.DrawingContextDrawingContextWalker.DrawImage ( ImageSource imageSource , Rect rectangle ) bei System.Windows.Media.RenderData.BaseValueDrawingContextWalk ( DrawingContextWalker ctx ) bei System.Windows.Media.DrawingServices.DrawingGroupFromRenderData ( RenderData renderData ) bei System.Windows.UIElement.GetDrawing ( ) bei System.Windows.Media.VisualTreeHelper.GetDrawing ( Visual reference ) bei System.Windows.Xps.Serialization.VisualTreeFlattener.StartVisual ( Visual visual ) bei System.Windows.Xps.Serialization.ReachVisualSerializer.SerializeTree ( Visual visual , XmlWriter resWriter , XmlWriter bodyWriter ) bei System.Windows.Xps.Serialization.ReachVisualSerializer.SerializeObject ( Object serializedObject ) bei System.Windows.Xps.Serialization.DocumentPageSerializer.SerializeChild ( Visual child , SerializableObjectContext parentContext ) bei System.Windows.Xps.Serialization.DocumentPageSerializer.PersistObjectData ( SerializableObjectContext serializableObjectContext ) bei System.Windows.Xps.Serialization.ReachSerializer.SerializeObject ( Object serializedObject ) bei System.Windows.Xps.Serialization.DocumentPageSerializer.SerializeObject ( Object serializedObject ) bei System.Windows.Xps.Serialization.DocumentPaginatorSerializer.PersistObjectData ( SerializableObjectContext serializableObjectContext ) bei System.Windows.Xps.Serialization.DocumentPaginatorSerializer.SerializeObject ( Object serializedObject ) bei System.Windows.Xps.Serialization.XpsSerializationManager.SaveAsXaml ( Object serializedObject ) bei System.Windows.Xps.XpsDocumentWriter.SaveAsXaml ( Object serializedObject , Boolean isSync ) bei System.Windows.Xps.XpsDocumentWriter.Write ( DocumentPaginator documentPaginator ) < Image Source= { x : Null } / > public class CustomImage : Image { public CustomImage ( ) { this.Loaded += CustomImage_Loaded ; this.SourceUpdated += CustomImage_SourceUpdated ; } private void CustomImage_SourceUpdated ( object sender , System.Windows.Data.DataTransferEventArgs e ) { FreezeSource ( ) ; } private void CustomImage_Loaded ( object sender , System.Windows.RoutedEventArgs e ) { FreezeSource ( ) ; } private void FreezeSource ( ) { if ( this.Source == null ) return ; var freeze = this.Source as Freezable ; if ( freeze ! = null & & freeze.CanFreeze & & ! freeze.IsFrozen ) freeze.Freeze ( ) ; } } < StackPanel Orientation= '' Vertical '' > < StackPanel.Resources > < Style TargetType= '' { x : Type Button } '' > < Setter Property= '' Margin '' Value= '' 0,0,0,5 '' > < /Setter > < /Style > < /StackPanel.Resources > < Button Content= '' Open Window 1 '' Click= '' OpenWindowInNewThread '' / > < Button Content= '' Open Window 2 '' Click= '' OpenWindowInSameThread '' / > < /StackPanel > private void OpenWindowInNewThread ( object sender , RoutedEventArgs e ) { var th = new Thread ( ( ) = > { SynchronizationContext.SetSynchronizationContext ( new DispatcherSynchronizationContext ( Dispatcher.CurrentDispatcher ) ) ; var x = new Window1 ( ) ; x.Closed += ( s , ec ) = > Dispatcher.CurrentDispatcher.BeginInvokeShutdown ( DispatcherPriority.Background ) ; x.Show ( ) ; System.Windows.Threading.Dispatcher.Run ( ) ; } ) ; th.SetApartmentState ( ApartmentState.STA ) ; th.IsBackground = true ; th.Start ( ) ; } private void OpenWindowInSameThread ( object sender , RoutedEventArgs e ) { var x = new Window2 ( ) ; x.Show ( ) ; } < StackPanel Orientation= '' Horizontal '' > < ToggleButton Template= '' { StaticResource PlusToggleButton } '' / > < /StackPanel > < StackPanel Orientation= '' Horizontal '' > < ToggleButton Template= '' { StaticResource PlusToggleButton } '' / > < Button Content= '' Print Me '' Click= '' Print '' > < /Button > < /StackPanel > public void Print ( object sender , RoutedEventArgs e ) { PrintDialog pd = new PrintDialog ( ) ; pd.PrintVisual ( this , `` HelloWorld '' ) ; } < ControlTemplate x : Key= '' PlusToggleButton '' TargetType= '' { x : Type ToggleButton } '' > < Image Name= '' Image '' Source= '' /WpfApplication1 ; component/Images/plus.png '' Stretch= '' None '' / > < /ControlTemplate >",Image handling in WPF not thread safe ? "C_sharp : I have a program wherein I will check if a file exists . If it does , the form will load . But if not , a messagebox will appear to inform the user , and then the application needs to close without showing the form.How do I do this properly ? I tried using this code on the constructor : It does what I want , but from what I 've read it 's not a good way to do it . Is this correct ? Or shall I just go with using the above code . Environment.Exit ( -1 ) ;",Close the application before the form loads "C_sharp : I have a function that expect HttpRequest as parameter : I wrote a unit testMy question is , how to add a cookie to repo.Request.Cookies ? public string Read ( HttpRequest req ) { if ( req.Headers [ `` X-Requested-With '' ] == `` XMLHttpRequest '' ) { return req.Headers [ ConfigurationManager.AppSettings [ `` ajaxsession '' ] ] ; } return req.Cookies [ ConfigurationManager.AppSettings [ `` cookiename '' ] ] ; } [ Test ] public void ReadSessionToken_BrowserRequest_ExpectSidToken ( ) { var repo = new DefaultHttpContext ( ) ; }",How to add a cookie to DefaultHttpContext "C_sharp : I have a custom ribbon with several checkboxes within a menu : This is the respective C # code : However , OnCheckboxChanged is never called . It works fine when I use this callback function with buttons but it does not with checkboxes , neither in the menu nor directly in the ribbon group . It also does work with getPressed instead of onAction . < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < customUI xmlns= '' http : //schemas.microsoft.com/office/2006/01/customui '' onLoad= '' Ribbon_Load '' > < ribbon > < tabs > < tab id= '' ribbon '' label= '' Ribbon '' > < group id= '' ribbonGroup '' label= '' Group '' > < menu id= '' menu '' label= '' Menu '' > < checkBox id= '' checkbox1 '' label= '' Checkbox 1 '' visible= '' true '' onAction= '' OnCheckboxChanged '' / > < checkBox id= '' checkbox2 '' label= '' Checkbox 2 '' visible= '' true '' onAction= '' OnCheckboxChanged '' / > < checkBox id= '' checkbox2 '' label= '' Checkbox 2 '' visible= '' true '' onAction= '' OnCheckboxChanged '' / > < /group > < /tab > < /tabs > < /ribbon > < /customUI > using System ; using System.Collections.Generic ; using System.IO ; using System.Linq ; using System.Reflection ; using System.Runtime.InteropServices ; using System.Text ; using System.Drawing ; using System.Windows.Forms ; using Office = Microsoft.Office.Core ; using Excel = Microsoft.Office.Interop.Excel ; using Microsoft.Office.Tools.Excel ; namespace ExcelAddIn1 { [ ComVisible ( true ) ] public class SSRRibbon : Office.IRibbonExtensibility { private Office.IRibbonUI ribbon ; public SSRRibbon ( ) { } # region IRibbonExtensibility-Member public string GetCustomUI ( string ribbonID ) { return GetResourceText ( `` ExcelAddIn1.SSRRibbon.xml '' ) ; } # endregion # region ribbon callback functions public void Ribbon_Load ( Office.IRibbonUI ribbonUI ) { this.ribbon = ribbonUI ; } public void OnCheckboxChanged ( Office.IRibbonControl control ) { int i = 1 ; } # endregion # region auxiliary private static string GetResourceText ( string resourceName ) { Assembly asm = Assembly.GetExecutingAssembly ( ) ; string [ ] resourceNames = asm.GetManifestResourceNames ( ) ; for ( int i = 0 ; i < resourceNames.Length ; ++i ) { if ( string.Compare ( resourceName , resourceNames [ i ] , StringComparison.OrdinalIgnoreCase ) == 0 ) { using ( StreamReader resourceReader = new StreamReader ( asm.GetManifestResourceStream ( resourceNames [ i ] ) ) ) { if ( resourceReader ! = null ) { return resourceReader.ReadToEnd ( ) ; } } } } return null ; } # endregion } }",Checkbox 's OnAction does not do anything "C_sharp : I have a method that determines the min and max of a column in a DataTable : I want to refactor this to be : I need to determine the datatype and use it instead of hard-coding m.Field < double > . How to do this ? UPDATEAs to why I want to calculate the difference between the min and the max public void GetMinMaxRange ( DataTable data , string valueColumnName ) { var min = data.AsEnumerable ( ) .Min ( m = > m.Field < double > ( valueColumnName ) ) ; var max = data.AsEnumerable ( ) .Max ( m = > m.Field < double > ( valueColumnName ) ) ; } public void GetMinMaxRange ( DataTable data , string valueColumnName ) { DataColumn column = data.Columns [ valueColumnName ] ; var min = data.AsEnumerable ( ) .Min ( m = > m.Field < column.DataType > ( valueColumnName ) ) ; var max = data.AsEnumerable ( ) .Max ( m = > m.Field < column.DataType > ( valueColumnName ) ) ; } public static double/decimal/int GetMinMaxRange < T > ( DataTable data , string valueColumnName ) where T : IComparable < T > { DataColumn column = data.Columns [ valueColumnName ] ; var min = data.AsEnumerable ( ) .Min ( m = > m.Field < T > ( valueColumnName ) ) ; var max = data.AsEnumerable ( ) .Max ( m = > m.Field < T > ( valueColumnName ) ) ; ; return max - min ; }",How to use Field < T > with Type ? "C_sharp : Writing an answer for another question some interesting things came out and now I ca n't understand how Interlocked.Increment ( ref long value ) works on 32 bit systems . Let me explain.Native InterlockedIncrement64 is now not available when compiling for 32 bit environment , OK , it makes sense because in .NET you ca n't align memory as required and it may be called from managed then they dropped it.In .NET we can call Interlocked.Increment ( ) with a reference to a 64 bit variable , we still do n't have any constraint about its alignment ( for example in a structure , also where we may use FieldOffset and StructLayout ) but documentation does n't mention any limitation ( AFAIK ) . It 's magic , it works ! Hans Passant noted that Interlocked.Increment ( ) is a special method recognized by JIT compiler and it will emit a call to COMInterlocked : :ExchangeAdd64 ( ) which will then call FastInterlockExchangeAddLong which is a macro for InterlockedExchangeAdd64 which shares same limitations of InterlockedIncrement64.Now I 'm perplex.Forget for one second managed environment and go back to native . Why InterlockedIncrement64 ca n't work but InterlockedExchangeAdd64 does ? InterlockedIncrement64 is a macro , if intrinsics are n't available and InterlockedExchangeAdd64 works then it may be implemented as a call to InterlockedExchangeAdd64 ... Let 's go back to managed : how an atomic 64 bit increment is implemented on 32 bit systems ? I suppose sentence `` This function is atomic with respect to calls to other interlocked functions '' is important but still I did n't see any code ( thanks Hans to point out to deeper implementation ) to do it . Let 's pick InterlockedExchangedAdd64 implementation from WinBase.h when intrinsics are n't available : How can it be atomic for reading/writing ? FORCEINLINELONGLONGInterlockedExchangeAdd64 ( _Inout_ LONGLONG volatile *Addend , _In_ LONGLONG Value ) { LONGLONG Old ; do { Old = *Addend ; } while ( InterlockedCompareExchange64 ( Addend , Old + Value , Old ) ! = Old ) ; return Old ; }",Atomic increment of 64 bit variable on 32 bit environment "C_sharp : I was looking at the code I have currently in my project and found something like this : The < < operand is the shift operand , which shifts the first operand left by the number bits specified in the second operand.But why would someone use this in an enum declaration ? public enum MyEnum { open = 1 < < 00 , close = 1 < < 01 , Maybe = 1 < < 02 , ... ... .. }",Why would someone use the < < operator in an enum declaration ? "C_sharp : I am testing spawning off many threads running the same function on a 32 core server for Java and C # . I run the application with 1000 iterations of the function , which is batched across either 1,2,4,8 , 16 or 32 threads using a threadpool.At 1 , 2 , 4 , 8 and 16 concurrent threads Java is at least twice as fast as C # . However , as the number of threads increases , the gap closes and by 32 threads C # has nearly the same average run-time , but Java occasionally takes 2000ms ( whereas both languages are usually running about 400ms ) . Java is starting to get worse with massive spikes in the time taken per thread iteration.EDIT This is Windows Server 2008EDIT2 I have changed the code below to show using the Executor Service threadpool . I have also installed Java 7.I have set the following optimisations in the hotspot VM : -XX : +UseConcMarkSweepGC -Xmx 6000 but it still hasnt made things any better . The only difference between the code is that im using the below threadpool and for the C # version we use : http : //www.codeproject.com/Articles/7933/Smart-Thread-PoolIs there a way to make the Java more optimised ? Perhaos you could explain why I am seeing this massive degradation in performance ? Is there a more efficient Java threadpool ? ( Please note , I do not mean by changing the test function ) import java.io.DataOutputStream ; import java.io.FileNotFoundException ; import java.io.FileOutputStream ; import java.io.PrintStream ; import java.util.concurrent.ExecutorService ; import java.util.concurrent.Executors ; import java.util.concurrent.ThreadPoolExecutor ; public class PoolDemo { static long FastestMemory = 2000000 ; static long SlowestMemory = 0 ; static long TotalTime ; static int [ ] FileArray ; static DataOutputStream outs ; static FileOutputStream fout ; static Byte myByte = 0 ; public static void main ( String [ ] args ) throws InterruptedException , FileNotFoundException { int Iterations = Integer.parseInt ( args [ 0 ] ) ; int ThreadSize = Integer.parseInt ( args [ 1 ] ) ; FileArray = new int [ Iterations ] ; fout = new FileOutputStream ( `` server_testing.csv '' ) ; // fixed pool , unlimited queue ExecutorService service = Executors.newFixedThreadPool ( ThreadSize ) ; ThreadPoolExecutor executor = ( ThreadPoolExecutor ) service ; for ( int i = 0 ; i < Iterations ; i++ ) { Task t = new Task ( i ) ; executor.execute ( t ) ; } for ( int j=0 ; j < FileArray.length ; j++ ) { new PrintStream ( fout ) .println ( FileArray [ j ] + `` , '' ) ; } } private static class Task implements Runnable { private int ID ; public Task ( int index ) { this.ID = index ; } public void run ( ) { long Start = System.currentTimeMillis ( ) ; int Size1 = 100000 ; int Size2 = 2 * Size1 ; int Size3 = Size1 ; byte [ ] list1 = new byte [ Size1 ] ; byte [ ] list2 = new byte [ Size2 ] ; byte [ ] list3 = new byte [ Size3 ] ; for ( int i=0 ; i < Size1 ; i++ ) { list1 [ i ] = myByte ; } for ( int i = 0 ; i < Size2 ; i=i+2 ) { list2 [ i ] = myByte ; } for ( int i = 0 ; i < Size3 ; i++ ) { byte temp = list1 [ i ] ; byte temp2 = list2 [ i ] ; list3 [ i ] = temp ; list2 [ i ] = temp ; list1 [ i ] = temp2 ; } long Finish = System.currentTimeMillis ( ) ; long Duration = Finish - Start ; TotalTime += Duration ; FileArray [ this.ID ] = ( int ) Duration ; System.out.println ( `` Individual Time `` + this.ID + `` \t : `` + ( Duration ) + `` ms '' ) ; if ( Duration < FastestMemory ) { FastestMemory = Duration ; } if ( Duration > SlowestMemory ) { SlowestMemory = Duration ; } } } }",Java is scaling much worse than C # over many cores ? "C_sharp : I 'm having issues with the SelectedPath property of the FolderBrowserDialog when the folder I select is on a remote server and is a symbolic link ( or any kind of reparse point ) .If i select a normal folder , then I get the full path returned , for example `` \SERVER\folder\subfolder\thing_I_clicked_on '' .However , if the folder is a reparse point , i get just `` \SERVER\thing_I_clicked_on '' ( so it 's missing the full path ) Anyone come across this or have any suggestions ? It does n't appear to be permissions related , as if I know the full path i can quite happily browse to it , etc . var dialog = new FolderBrowserDialog ( ) ; dialog.ShowDialog ( ) ; MessageBox.Show ( dialog.SelectedPath ) ;",FolderBrowserDialog SelectedPath with reparse points "C_sharp : My event dispatcher class loosely couples instances of other classes by implementing sort of signals-slots design pattern.Only one unique event dispatcher is supposed to exist in an application.Since my Dispatcher class – which does all the work – inherits from Dictionary < TKey , TValue > , it can not be declared static.To overcome this constraint , I implemented a main static wrapper class EVD with a private property evd which provides the Dispatcher singleton , along with the public static methods Subscribe , UnSubscribe , and Dispatch , which wrap the singleton 's corresponding methods : So here is my question : Does it really make sense to create a singleton instance in a static class ? AFAIK a static class is unique anyway . So maybe it would be best practice not to create the singleton and declare the evd property just like so : What about lazy intantiation and thread safety in that case ? At least the generic singleton class uses Lazy < T > and is said to be thread safe . Or should I better declare the property like so : I 'm afraid I do n't completely understand all that lazy instatantiation and thread safety stuff ... Thanks for any help , Don P namespace EventDispatcher { public static class EVD { static Dispatcher evd { get { return Singleton < Dispatcher > .Instance ; } } public static void Subscribe ( string name , EvtHandler handler ) { evd.Subscribe ( name , handler ) ; } public static void UnSubscribe ( string name , EvtHandler handler = null ) { evd.UnSubscribe ( name , handler ) ; } public static void Dispatch ( string name , object sender , EvtArgs e = null ) { evd.Dispatch ( name , sender , e ) ; } } class Dispatcher : Dictionary < string , Event > { /* main event dispatcher */ } static class Singleton < T > where T : /* generic singleton creation */ } static Dispatcher evd = new Dispatcher ( ) ; static Dispatcher _evd ; static Dispatcher evd { get { return _evd ? ? ( _evd = new Dispatcher ( ) ) ; } }",C # singleton pattern in a static class ? C_sharp : Can anyone explain why Regex.Match captures noncapturing groups . Ca n't find anything about it in MSDN . Whyproduces outputinstead of empty one ? Regex regexObj = new Regex ( `` ( ? : a ) '' ) ; Match matchResults = regexObj.Match ( `` aa '' ) ; while ( matchResults.Success ) { foreach ( Capture g in matchResults.Captures ) { Console.WriteLine ( g.Value ) ; } matchResults = matchResults.NextMatch ( ) ; } aa,Regex.Match and noncapturing groups "C_sharp : I have a class that implements ICollection < SomeConcreteClass > . The NUnit collections constraints do not recognize it as a collection.e.g . Assert.That ( sut , Has.No.Member ( someObjectOfTypeSomeConcreteClass ) ) ; throws System.ArgumentException : The actual value must be a collectionand Assert.That ( sut , Is.Empty ) ; fails with empty sut.So when is a collection a collection ( according to NUnit ) ? Stack Trace : Above problems occurred with NUnit 2.4.3.0 . I just tried it with 2.6 . Is.Empty works now , but Has.No.Member still fails . It does not even call Equals ( ) or operator == ( ) . How does it compare the collection elements ? RhinoMocks Arg < MyCollection > .List.Count ( Is.Equal ( 1 ) ) does now fail too.Conclusion : With NUnit 2.4 the collection constraints require implementation of non-generic ICollection for the collection to be recognized as a collection ( that answers the original question ) . IEnumerable equality works as expected.With NUnit 2.6 ( and possibly 3.0 ) equality of IEnumerables is checked by matching elements even if Equals is overridden . That 's why the membership constraint does not work if the elements are IEnumerables themselves . This is a known issue ( https : //bugs.launchpad.net/nunit-3.0/+bug/646786 ) .For details see my own answer . System.ArgumentException : The actual value must be a collection Parametername : actualat NUnit.Framework.Constraints.CollectionConstraint.Matches ( Object actual ) at NUnit.Framework.Constraints.NotConstraint.Matches ( Object actual ) MyTestFile.cs ( 36,0 ) : at MyAssembly.MyTestFixture.MyTestMethod ( )",What makes a class a collection according to NUnit collection constraints ? "C_sharp : Using ReSharper 8.2 I get a warning ( `` Expression is always false '' ) for the null check infrom NHibernate NullableDictionary . Why is this ? When I try it withthen I do n't get the warning for null checks on T variables as expected.Edit : To make things easier here is the class signature of the linked source : public bool TryGetValue ( TKey key , out TValue value ) { if ( key == null ) class Test < T > where T : class public class NullableDictionary < TKey , TValue > : IDictionary < TKey , TValue > where TKey : class",ReSharper : Null check is always false warning "C_sharp : I have filter attribute in ASP.NET core 2.0 , See my code snippet below . Here the problem is I always get the status code is 200 . Even the actual status code is 500 then also I get a 200 . How do I get the actual status code ? public void OnActionExecuted ( ActionExecutedContext context ) { try { var controller = context.Controller as APIServiceBase ; var statusCode = controller.Response.StatusCode ; .. .. } catch { } }",Get HttpStatus code from IActionFilter in .Net Core 2.0 "C_sharp : Can someone explain me the reason of overflow in variable a ? Note that b is bigger than a.Thanks ! static void Main ( string [ ] args ) { int i = 2 ; long a = 1024 * 1024 * 1024 * i ; long b = 12345678901234567 ; System.Console.WriteLine ( `` { 0 } '' , a ) ; System.Console.WriteLine ( `` { 0 } '' , b ) ; System.Console.WriteLine ( `` { 0 } '' , long.MaxValue ) ; } -2147483648 12345678901234567 9223372036854775807 Press any key to continue . . .",Strange c # overflow error "C_sharp : Here 's an integration test I wrote for a class that interacts with a database : It seems to me that I ca n't test the Save function without involving the SearchSubscriberByUsername function to find out if the user was successfully saved . I realize that integration tests are n't meant to be unit tests which are supposed to test one unit of code at a time . But ideally , it would be nice if I could test one function in my repository class per test but I do n't know how I can accomplish that.Is it fine how I 've written the code so far or is there a better way ? [ Test ] public void SaveUser ( ) { // Arrange var user = new User ( ) ; // Set a bunch of properties of the above User object // Act var usersCountPreSave = repository.SearchSubscribersByUsername ( user.Username ) .Count ( ) ; repository.Save ( user ) ; var usersCountPostSave = repository.SearchSubscribersByUsername ( user.Username ) .Count ( ) ; // Assert Assert.AreEqual ( userCountPreSave + 1 , userCountPostSave ) ; }",Integration Testing : Am I doing it right ? "C_sharp : I 'm working the C # in Azure Mobile Apps trying to learn them . I created the Model to link to my Azure SQL DB , created a DataObject like this : Notice that I commented out the public int id above ; it was giving me a duplicate column error on the query.Finally , I created a controller using the newly created Account DataObject.So I ran the application and hit the `` tables/Account '' function and it returned zero rows ( but there is data and I can query it with the user I 'm using in the azure mobile app ) .I then noticed the model schema as this : There 's a couple of issues I see with the configured model ( and I do n't know where some of the columns are coming from ... ) First , the id is listed twice , once as an int ( which has to be mine ) and another id as string and I have no idea where that came from.Also , in the DB , the oGuid is of type uniqueIdentifier ; not string . This may or may not be an issue because I ca n't test yet . Then there are the other columns that just do not exist in my DB including CreatedAt ( datetime ) , UpdatedAt ( datetime ) , Version ( string ) and Deleted ( bit ) .I 'm thinking the issue / reason why I 'm not getting any data back from that call is that there is a data mismatch.Do I need to add the other columns that are listed in the model in the api test ? I 've also tested trying to call the /table/Account/3 to load a specific account and it returns no rows ... I 'm guessing it 's a model mismatch but I 'm not sure if that 's the issue or something else causing it ? I 'm not seeing any errors or warnings.UpdateI figured out what is going on with model first and Azure and how to attach an existing DB in Azure to new code . I 'm going to post this here for the hopes that it saves other 's time . This really should have been easier to do . I 'm not a fan of codefirst ( yet ) as I like to control the DB by hand ... So this makes it a lot easier for me to work with the db backend.First I created a new project ( Azure Mobile App ) then under models I right clicked the model and add- > new entity data model then added in the azure db name , password and gave it my `` user created profile name '' as used below . This connection must be edited in the web.config as shown below . I then had to create the model for the table in DataObjects ( without the MS required columns ) and create a controller off of the dataobject . I then had to edit the web.config and set a non-entity DB connection string : eg : Finally , in the MobileServiceContext , I had to map the DataObject model to the table in Azure sql and set the connection string to use from the default MS_TableConnectionString to the connectionstring in web.config.and under OnModelCreating ( ) I added : Where Account was the model ( class ) I created in DataObjects and the tblAccount is the table name in AzureDB . public class Account : EntityData { //public int id { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public string PhoneNumber { get ; set ; } public string Password { get ; set ; } public DateTime dtCreated { get ; set ; } public Guid oGuid { get ; set ; } } [ { `` id '' : 0 , `` FirstName '' : `` string '' , `` LastName '' : `` string '' , `` PhoneNumber '' : `` string '' , `` Password '' : `` string '' , `` dtCreated '' : `` 2016-07-06T17:45:47.114Z '' , `` oGuid '' : `` string '' , `` Id '' : `` string '' , `` Version '' : `` string '' , `` CreatedAt '' : `` 2016-07-06T17:45:47.114Z '' , `` UpdatedAt '' : `` 2016-07-06T17:45:47.114Z '' , `` Deleted '' : true } ] < add name= '' [ user created preset name ] '' providerName= '' System.Data.SqlClient '' connectionString= '' Server= [ Azuredb server connection ] ; initial catalog= [ DBName ] ; persist security info=True ; user id= [ user ] ; password= [ pass ] ; MultipleActiveResultSets=True '' / > private const string connectionStringName = `` Name= [ user created preset name ] '' ; modelBuilder.Entity < Account > ( ) .ToTable ( `` tblAccount '' ) ;",Why is there a string ID in the data model of Azure Mobile Apps ? "C_sharp : I am trying to implement a useful general exception handler for my MonoTouch code.If I attach a handler to AppDomain.CurrentDomain.UnhandledException , there is no stack trace present at all , i.e . the .StackTrace property is null or empty.If I wrap my UIApplication.Main ( args ) call in try { } catch { } , the stack trace does n't contain any useful information : i.e . it does n't go any deeper than the Main ( ) method where I caught the exception.Any ideas how I can get some more useful information in the stack trace at all , or is it all optimised away completely by the AOT compilation ? ( The stack trace is as expected in debug mode . ) at MonoTouch.UIKit.UIApplication.Main ( System.String [ ] args , System.String principalClassName , System.String delegateClassName ) [ 0x00000 ] in < filename unknown > :0 at MonoTouch.UIKit.UIApplication.Main ( System.String [ ] args ) [ 0x00000 ] in < filename unknown > :0 at MyNamespace.MyProduct.MyProject.Application.Main ( System.String [ ] args ) [ 0x00000 ] in < filename unknown > :0",MonoTouch stack traces not detailed "C_sharp : I have a program that opens a large binary file , appends a small amount of data to it , and closes the file . If test.tmp is 5MB before this program is run and the data array is 100 bytes , this program will cause over 5MB of data to be transmitted across the network . I would have expected that the data already in the file would not be transmitted across the network since I 'm not reading it or writing it . Is there any way to avoid this behavior ? This makes it agonizingly slow to append to very large files . FileStream fs = File.Open ( `` \\\\s1\\temp\\test.tmp '' , FileMode.Append , FileAccess.Write , FileShare.None ) ; fs.Write ( data , 0 , data.Length ) ; fs.Close ( ) ;",How do I avoid excessive Network File I/O when appending to a large file with .NET ? "C_sharp : I 'm having an issue at design time with all my forms and custom controls within Visual Studios 2008 . Up until the previous check in , all of the controls were rendering as expected . The only main difference between the current version and the previous working version was that a Property on the control UIText was renamed from Content to Value . The other changes are adding a new form and 3 new enums , but there 's certainly no obvious change that would affect all forms in the program ( including new ones ) . All of the controls ( on every form ) now render as a box with the name of the control ( however they all render correctly at run time ) : I 've tried creating a brand new form in my project , creating a brand new custom control with just a label on it , and I 've still got exactly the same problem : Note that standard .Net form controls work fine , so this is only an issue with custom controls.If I restore my previous version from the repository , then everything starts rendering correctly again : I could just revert back to this working version and carry on , but I 'd rather know how to fix the problem should it occur again . I 'm posting here hoping it 's a programming issue as apposed to a Visual Studios 2008 issue ( on SP1 by the way ) .UPDATE - Issue traced , ca n't explain itI fixed the issue . Well , fixed is n't really the right word for it . I located the issue by removing all of the user controls 1 at a time until the form started rendering properly again . The issue was in my Signature control ( which has been present for ages , only in my latest check in I had added a reference to the project iVirtualDocket.CodeLibrary into the main project : The signature has a property called SignatureData , which was doing this : ImageToByteArray looks like the following : If I move the above method into the UIControls project , then everything works fine . However , as soon as I put the method back into the CodeLibrary project and call it there , all my forms stop rendering UserControls.So doing the following fixes the problem , but I 'd really like to know why : ( What 's even more bizarre is that I do n't even use this property yet . ) iVirtualDocket - References iVirtualDocket.UIControls - References iVirtualDocket.CodeLibrary iVirtualDocket.UIControls -References iVirtualDocket.CodeLibrary public byte [ ] SignatureData { get { if ( _signature == null ) { return null ; } else { return iVirtualDocket.CodeLibrary.Conversions.ImageToByteArray ( _signature , ImageFormat.Png ) ; } } } public static byte [ ] ImageToByteArray ( Image imageToConvert , ImageFormat formatOfImage ) { byte [ ] ret ; using ( MemoryStream ms = new MemoryStream ( ) ) { imageToConvert.Save ( ms , formatOfImage ) ; ret = ms.ToArray ( ) ; } return ret ; } public byte [ ] SignatureData { get { if ( _signature == null ) { return null ; } else { // Need to call this code directly here instead of through // the CodeLibrary conversions , otherwise all user controls stop // rendering in design mode byte [ ] ret ; using ( MemoryStream ms = new MemoryStream ( ) ) { _signature.Save ( ms , ImageFormat.Png ) ; ret = ms.ToArray ( ) ; } return ret ; } } }",Visual studio 2008 IDE not rendering Custom Controls correctly "C_sharp : TLDR : Is it possible to modify the IServiceProvider after the Startup has ran ? I am running dll 's ( which implement a interface of me ) during run-time . Therefore there 's a file listener background job , which waits till the plugin-dll is dropped . Now I want to register classes of this dll to the dependency-injection system . Therefore I added IServiceCollection as a Singleton to the DI inside ConfigureServices to use inside another method.In therefore I created a test-project and just tried to modify the ServiceCollection in the controller , because it was easier than stripping the background job down.So I added IServiceCollection to my controller to check if I can add a class to the DI after the Startup class has ran.The Service was successfully added to the IServiceCollection , but the change is not persisted yet to HttpContext.RequestServices even after multiple calls the service count increases each time but I do n't get the reference by the IServiceProvider.Now my question is : Is that possible to achieve and yes how . Or should I rather not do that ? services.AddSingleton < IServiceCollection > ( services ) ; [ Route ( `` api/v1/test '' ) ] public class TestController : Microsoft.AspNetCore.Mvc.Controller { private readonly IServiceCollection _services ; public TestController ( IServiceCollection services ) { _services = services ; var myInterface = HttpContext.RequestServices.GetService < IMyInterface > ( ) ; if ( myInterface == null ) { //check if dll exist and load it // ... . var implementation = new ForeignClassFromExternalDll ( ) ; _services.AddSingleton < IMyInterface > ( implementation ) ; } } [ HttpGet ] public IActionResult Test ( ) { var myInterface = HttpContext.RequestServices.GetService < IMyInterface > ( ) ; return Json ( myInterface.DoSomething ( ) ) ; } } public interface IMyInterface { /* ... */ } public class ForeignClassFromExternalDll : IMyInterface { /* ... */ }",Is it possible to extend IServiceProvider during runtime "C_sharp : I have a list of audit data from Dynamics CRM 2013 that I have deserialised and stuck into a HashSet , defined as : I add the data like this ( from a SQL Server recordset ) : I end up with roughly half a million records.Next I need to iterate through every Guid and pull out the subset of data from my audit data that matches . I have a list of the Guids that I generate elsewhere and there are around 300,000 to process . I store them in this : ... and iterate through them like this : Then I need to do this to pull out the subset for each Guid : But it 's slow.It take around 1 minute to populate my initial audit data list but will take hours ( I never ran it to completion so this is based on the time to process 1 % of the data ) to pull out each set , process it and squirt it back into a database table.Stepping through the code I can see the bottleneck seems to be pulling out the subset from my list for each Guid . So my question is , is there a better/ more efficient way ( architecture ? ) to store/ retrieve my data set ? One thing to note , I know Guids are inherently slow to index/ search but I am pretty much constrained to using them due to the way Dynamics CRM works . I guess I could create a Dictionary to lookup Guids and `` convert '' them to integer values , or something along those lines , but I am not convinced that would help much ? EditOkay , I tested the three solutions using my live data ( 371,901 Guids ) and these are the results as an average time per 1,000 Guids . Note that this includes the processing/ INSERT to SQL Server so it is n't a proper benchmark.On the basis of this I am going to probably rewrite my code from scratch as I think the whole approach I was taking was incorrect.However , this has been a very useful learning exercise and many thanks to everyone who contributed . I am going to accept the BinarySearch as the correct answer as it does what I wanted and is much faster than my original code.Just to be clear here , the IntersectWith is indeed `` smoking '' fast , but it does n't work for my particular problem as I need to constantly go back to my original hashset . private class AuditCache { public Guid ObjectId ; public int HistoryId ; public DateTime ? DateFrom ; public DateTime ? DateTo ; public string Value ; } ; private HashSet < AuditCache > _ac = new HashSet < AuditCache > ( ) ; _ac.Add ( new AuditCache { ObjectId = currentObjectId , HistoryId = Convert.ToInt32 ( dr [ `` HistoryId '' ] ) , DateTo = Convert.ToDateTime ( dr [ `` CreatedOn '' ] ) , Value = value } ) ; var workList = new Dictionary < Guid , DateTime > ( ) ; foreach ( var g in workList ) List < AuditCache > currentSet = _ac.Where ( v = > v.ObjectId == g.Key ) .ToList ( ) ; Method # 0 - List with Lambda ~30.00s per 1,000 rows ( I never benchmarked this precisely ) Method # 1 - IntersectWith 40.24s per 1,000 rows ( cloning my Hashset spoilt this ) Method # 2 - BinarySearch 3.20s per 1,000 rowsMethod # 3 - Generic Dictionary 2.19s per 1,000 rows","I have a large list of GUIDs and other data that I need to pull a subset from , what is the quickest way to do this ?" "C_sharp : I have two snippets of code from nest 2.3 that I have n't been able to get to cooperate in the latest 5.0.0-rc3.The build error here is `` Can not implicitly convert Nest.Field [ ] to Nest.Fields '' . I can do something like But then I lose the field weighting . Second field useagle I 've been having troubles with is Build error here is 'Nest.SearchDescriptor ' does not contain a definition for 'Fields ' and no extension method 'Fields ' accepting a first argument of type 'Nest.SearchDescriptor ' could be found ( are you missing a using directive or an assembly reference ? I have n't had any luck with getting something compile-able in the case . var titleField = Infer.Field < Page > ( p = > p.Title , 2 ) ; var metaDescriptionField = Infer.Field < Page > ( p = > p.MetaDescription , 1.5 ) ; var metaKeywordsField = Infer.Field < Page > ( p = > p.Keywords , 2 ) ; var bodyField = Infer.Field < Page > ( p = > p.Body ) ; MultiMatchQuery multiMatchQuery = new MultiMatchQuery ( ) { Fields = new [ ] { bodyField , metaKeywordsField , metaKeywordsField , titleField } , Query = search.Term } ; MultiMatchQuery multiMatchQuery = new MultiMatchQuery ( ) { Fields = Infer.Fields < Page > ( p = > p.Title , p = > p.MetaDescription , p = > p.Keywords , p = > p.Body ) , Query = search.Term } ; var searchResponse = client.Search < Page > ( s = > s .MatchAll ( ) .From ( from ) .Size ( size ) .Fields ( f = > f.Field ( fi = > fi.Id ) .Field ( fi = > fi.SourceId ) ) ) ;",NEST 5.x Fields Usage "C_sharp : I my code I 'm using the System.Function method Debug.Assert ( .. ) for verify the input parameter at the beginning of a method ( see following example code snipped ) : If I comment out the Debug.Assert statement the ReSharper warning disappears.In my opinion , ReSharper has to ignore this Debug.Assert statement , because also if the Debug.Assert statement is not fulfilled , the code beneath is executed ( e.g . in Release-mode ) What is your opinion ? Or is there a alternative implementation idea ? public class TestClass : IInterface { } public class Verifier { public static void Verify ( IInterface objectToVerify ) { Debug.Assert ( ( objectToVerify is TestClass ) , `` Passed object must be type of TestClass '' ) ; // ReSharper ( Version 7.1.1 ) marks here `` Expression is always false if ( ! ( objectToVerify is TestClass ) ) { return ; } // do something ... } }",Does ReSharper handle Debug.Assert ( .. ) correctly ? C_sharp : When the Label text value ends with end bracket . The result in Right to Left is wrong like example.Is there any solution to fix it ? Text : ABC ( 123 ) Result : ( ABC ( 123Expected Result : ABC ( 123 ),Right To Left Bracket display wrong "C_sharp : For example , whenever I await something the compiler notifies me the containing method must be Async . Why is the async lamba not seen this way ? If the ForEach is hiding it then is there some danger regarding not returning a Task object and the ForEach being implicitly async void ? public void SaveSome ( ) { Array.ForEach ( Enumerable.Range ( 0,3 ) .ToArray ( ) , async x = > await SaveRep ( ) ) ; }",Why does n't a method containing an async lambda need to be Async itself ? "C_sharp : Given the following snippet : The output is this : Now if I change TypeNameHandling to TypeNameHandling.All , the output becomes this : But what I want is this : The reason is that I want to be able to serialize a bunch of objects and deserialize them later , without knowing the type that they deserialize to , but I also do n't want to pollute the content with these $ type properties all over the place where they 're not needed.In other words , I want TypeNameHandling.Auto except for the root object . How do I do this ? using System ; using Newtonsoft.Json ; namespace JsonTestje { class Other { public string Message2 { get ; set ; } } class Demo { public string Message { get ; set ; } public Other Other { get ; set ; } } class Program { static void Main ( string [ ] args ) { var demo = new Demo { Message = `` Hello , World ! `` , Other = new Other { Message2 = `` Here be dragons ! '' } } ; var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto , Formatting = Formatting.Indented } ; var serialized = JsonConvert.SerializeObject ( demo , settings ) ; Console.WriteLine ( serialized ) ; } } } { `` Message '' : `` Hello , World ! `` , `` Other '' : { `` Message2 '' : `` Here be dragons ! '' } } { `` $ type '' : `` JsonTestje.Demo , JsonTestje '' , `` Message '' : `` Hello , World ! `` , `` Other '' : { `` $ type '' : `` JsonTestje.Other , JsonTestje '' , `` Message2 '' : `` Here be dragons ! '' } } { `` $ type '' : `` JsonTestje.Demo , JsonTestje '' , `` Message '' : `` Hello , World ! `` , `` Other '' : { `` Message2 '' : `` Here be dragons ! '' } }",JSON.NET TypeNameHandling.Auto except for top level "C_sharp : I have the following Cypher Query which works fine in the Neo4j 2.0.0.The following Query in Neo4jClient gives the error : Function Evaluation Timed out.AND After following Another Similar work on Xclave : http : //geekswithblogs.net/cskardon/archive/2013/07/23/neo4jclient-ndash-getting-path-results.aspx The Results value as : Function Evaluation Timed out.How can I get all the nodes returned by the query in C # as a List of PointEntity Types ? EDIT : I was able to get back the URIs of the nodes and relations from this code : Following Craig Brett 's blog here : http : //craigbrettdevden.blogspot.co.uk/2013/03/retrieving-paths-in-neo4jclient.htmlI tried to get the POCO but got error : Error : MATCH ( ab : Point { Latitude : 24.96325 , Longitude : 67.11343 } ) , ( cd : Point { Latitude : 24.95873 , Longitude : 67.10335 } ) , p = shortestPath ( ( ab ) - [ *..150 ] - ( cd ) ) RETURN p var pathsQuery = client.Cypher .Match ( `` ( ab : Point { Latitude : 24.96325 , Longitude : 67.11343 } ) , ( cd : Point { Latitude : 24.95873 , Longitude : 67.10335 } ) , p = shortestPath ( ( ab ) - [ *..150 ] - ( cd ) ) '' ) .Return < IEnumerable < PointEntity > > ( `` extract ( n in nodes ( p ) : id ( n ) ) '' ) ; var pathsQuery = client.Cypher .Match ( `` ( ab : Point { Latitude : 24.96325 , Longitude : 67.11343 } ) , ( cd : Point { Latitude : 24.95873 , Longitude : 67.10335 } ) , p = shortestPath ( ( ab ) - [ *..150 ] - ( cd ) ) '' ) .Return ( p = > new PathsResult < PointEntity > { Nodes = Return.As < IEnumerable < Node < PointEntity > > > ( `` nodes ( p ) '' ) , } ) ; var pathsQuery = client.Cypher .Match ( `` ( ab : Point { Latitude : 24.96325 , Longitude : 67.11343 } ) , ( cd : Point { Latitude : 24.95873 , Longitude : 67.10335 } ) , p = shortestPath ( ( ab ) - [ *..150 ] - ( cd ) ) '' ) var results = pathsQuery.Return < PathsResult > ( `` p '' ) .Results ; var paths = pathsQuery.Returns < PathsResult > ( `` EXTRACT ( n in nodes ( p ) : n ) AS Nodes , EXTRACT ( rel in rels ( p ) : rel ) AS Relationships '' , CypherResultMode.Projection ) .Results ; 'Neo4jClient.Cypher.ICypherFluentQuery ' does not contain a definition for 'Returns ' and no extension method 'Returns ' accepting a first argument of type 'Neo4jClient.Cypher.ICypherFluentQuery ' could be found ( are you missing a using directive or an assembly reference ? )",Return All Nodes in Shortest Path as Object List "C_sharp : I 'm working on a recommender system for restaurants using an item-based collaborative filter in C # 6.0 . I want to set up my algorithm to perform as well as possible , so I 've done some research on different ways to predict ratings for restaurants the user has n't reviewed yet.I 'll start with the research I have doneFirst I wanted to set up a user-based collaborative filter using a pearson correlation between users to be able to see which users fit well together.The main problem with this was the amount of data required to be able to calculate this correlation . First you needed 4 reviews per 2 users on the same restaurant . But my data is going to be very sparse . It was n't likely that 2 users would have reviewed the exact same 4 restaurants . I wanted to fix this by widening the match terms ( I.e . not matching users on same restaurants , but on a same type of restaurant ) , but this gave me the problem where it was hard to determine which reviews I would use in the correlation , since a user could have left 3 reviews on a restaurant with the type 'Fast food ' . Which of these would fit best with the other user 's review on a fast food restaurant ? After more research I concluded that an item-based collaborative filter outperforms an user-based collaborative filter . But again , I encountered the data sparsity issue . In my tests I was successfully able to calculate a prediction for a rating on a restaurant the user has n't reviewed yet , but when I used the algorithm on a sparse dataset , the results were n't good enough . ( Most of the time , a similarity was n't possible between two restaurants , since no 2 users have rated the same restaurant ) .After even more research I found that using a matrix factorization method works well on sparse data.Now my problemI have been looking all over the internet for tutorials on using this method , but I do n't have any experience in recommender systems and my knowledge on algebra is also limited . I understand the just of the method . You have a matrix where you have 1 side the users and the other side the restaurants . Each cell is the rating the user has given on the restaurant.The matrix factorization method creates two matrices of this , one with the weight between users and the type of the restaurant , and the other between restaurants and these types . The thing I just ca n't figure out is how to calculate the weight between the type of restaurant and the restaurants/users ( If I understand matrix factorization correctly ) . I found dozens of formulas which calculates these numbers , but I ca n't figure out how to break them down and apply them in my application.I 'll give you an example on how data looks in my application : In this table U1 stands for a user and R1 stands for a restaurant.Each restaurant has their own tags ( Type of restaurant ) . I.e . R1 has the tag 'Italian ' , R2 has 'Fast food ' , etc.Is there anyone who can point me in the right direction or explain how I should use this method on my data ? Any help would be greatly appreciated ! | R1 | R2 | R3 | R4 |U1 | 3 | 1 | 2 | - |U2 | - | 3 | 2 | 2 |U3 | 5 | 4 | - | 4 |U4 | - | - | 5 | - |",Using matrix factorization for a recommender system "C_sharp : I have a tendency ( throw back to c++ days ) to add inlining hints to small methods , for example : I was wondering whether a static class extension-methods could be inlined in the first place ? [ MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static void Add ( this IProject @ this , IComponent component ) { @ this.Components.Add ( component ) ; }",Can a static class extension be inlined ? "C_sharp : Consider the following code in C # .The last line will return a compilation error can not convert from 'int ? ' to 'int ' which is fair enough . However , for example in Haskell there is Maybe which is a counterpart to Nullable in C # . Since Maybe is a Functor I would be able to apply Foo to x using fmap . Does C # have a similar mechanism ? public int Foo ( int a ) { // ... } // in some other methodint ? x = 0 ; x = Foo ( x ) ;",Can Nullable be used as a functor in C # ? "C_sharp : I have a public facing interface in one project that will end up becoming a nuget package . Here is the code : Now every method in this interface is not used in this library but is used in other via the package . However , every single method here has a warning of Method x is never used.Is there a simple way to tell ReSharper to ignore every public method in every project in every solution that I ever open to not perform this check in public methods.I have a couple of ways to fix this but it is far too tedious.Option 1 : [ UsedImplicitly ] on every method inside my class . This is far too tedious in my opinion.Option 2 : [ SuppressMessage ( `` ReSharper '' , `` UnusedMember.Global '' ) ] A little less tedious , but still have to implement on every class.There has to be a better way ? I also read somewhere that this only happens if Enable solution-wide analysis is checked . In my case it is not . I found this setting under Reshaper Options > Code Inspection > Settings public interface MyInterface { void MyMethod ( ) ; }",Resharper Method is never used "C_sharp : When handling a PUT call , a WebAPI handler seems to go into a stack overflow type situation when validating the model . The exception is n't clear , and there is no indication as to what in the model is causing this validation class to go into a loop . Attaching the debugger does nothing . The handler will never get called , the serializer will deserialize the posted json normally without incident . What could be wrong ? The following code just loops several hundred times before exiting throwing the exception '' Insufficient stack to continue executing the program safely . This can happen from having too many functions on the call stack or function on the stack using too much stack space.The Model is akin to this simple example . The model has default values which I can confirm are all initialized . The model also has no references to itself . at System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack ( ) at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren ( ModelMetadata metadata , ValidationContext validationContext , Object container , IEnumerable ` 1 validators ) at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateProperties ( ModelMetadata metadata , ValidationContext validationContext ) public class Example { [ Required ] public string test { get ; set ; } [ Required ] public CustomEnumType myEnum { get ; set ; } }",WebAPI PUT InsufficientExecutionStackException with DbGeography Type "C_sharp : I have a controller with two simple Methods : UserController Methods : Then there is one simple view for displaying the details : As you can see , I use an editor template `` LabelTextBoxValidation '' : Showing user information is no problem . The view renders perfectly user details.When I submit the form , the object user is lost . I debugged on the row `` return View ( User ) ; '' in the Post Details method , the user object is filled with nullable values . If I dont use the editor template , the user object is filled with correct data . So there has to be something wrong with the editor template , but ca n't figure out what it is . Suggestions ? [ AcceptVerbs ( HttpVerbs.Get ) ] public ActionResult Details ( string id ) { User user = UserRepo.UserByID ( id ) ; return View ( user ) ; } [ AcceptVerbs ( HttpVerbs.Post ) ] public ActionResult Details ( User user ) { return View ( user ) ; } < % using ( Html.BeginForm ( `` Details '' , `` User '' , FormMethod.Post ) ) { % > < fieldset > < legend > Userinfo < /legend > < % = Html.EditorFor ( m = > m.Name , `` LabelTextBoxValidation '' ) % > < % = Html.EditorFor ( m = > m.Email , `` LabelTextBoxValidation '' ) % > < % = Html.EditorFor ( m = > m.Telephone , `` LabelTextBoxValidation '' ) % > < /fieldset > < input type= '' submit '' id= '' btnChange '' value= '' Change '' / > < % } % > < % @ Control Language= '' C # '' Inherits= '' System.Web.Mvc.ViewUserControl < string > '' % > < % = Html.Label ( `` '' ) % > < % = Html.TextBox ( Model , Model ) % > < % = Html.ValidationMessage ( `` '' ) % >",Asp.Net MVC EditorTemplate Model is lost after Post "C_sharp : I am trying to create a binding to change the background color of a label based on a property of the selected item . I 'm using the form : If I use `` Value '' as the path , it uses the value of ItemDisplayTitle to set the color using MyIconverter ( ) But I really want to use another property `` Health '' which is on the screen but is a Local Property for this window.Research has show me that I should use the form `` Details.Entity.AnotherProperty `` June 06 , 2012 10:16 AM - Otis RangerBut when I try to use `` DataSourceName.MyEntityName.MyProperty '' it does not seem to work.I 've also tried `` Details.MyEntityName.MyProperty '' and in desperation `` Details.Entity.MyProperty '' I pretty sure I 'm just having a mental hiccup , but what shouldDetails , Entity and AnotherProperty be ? and am I missing a obvious reference page to what exactly the path should be ? this.FindControl ( `` ItemDisplayTitle '' ) .SetBinding ( TextBox.BackgrounProperty , **PATH** , new MyIconverter ( ) , BindingMode.OneWay ) ;",How to get the path for the SetBinding method on an IContentItemProxy in LightSwitch ? "C_sharp : I am writing a custom scaffolder for our project . And this scaffolder should add links to DTO declarations for client side app.I have a possibility to retrieve an instance of project item , and I already found that it is possible to add links using ProjectNode.AddNewFileNodeToHierarchy ( string , string ) method.I can get a reference to the DTE service by simply accessing $ DTE variable predefined in PowerConsole.The question is how to get instance of ProjectNode I am interested in ? $ folder = Get-ProjectFolder `` Views\Shared ''",How to add a link to a file in visual studio using EnvDTE "C_sharp : Current stateHaving two classes : Using them : Inside the debugger , the tool tip value that is displayed at a is One = 5 , two = { DebuggerDisplayTest.B } GoalWhat I would want is something like One = 5 , two = 'Three = 10 ' I know this could be achieved by overriding the ToString ( ) method of class B . This just feels not right , since I 'm writing code in my application for debugging only.I also know that using a string similar towould work , too . This also does not feel right to me , since it would require that class A has knowledge of class B.I would like to have more of a way to `` inject '' the value of DebuggerDisplay of type B to the instance of that type in class A.QuestionIs it somehow possible to access the DebuggerDisplay attribute of a member inside the DebuggerDisplay attribute of a `` has-a '' composited class ? UpdateProbably , my requirement is not possible as per this SO answer . Maybe a good solution would be to override ToString in class B and do some if..else and use the Debugger.IsAttached property to behave different only inside the debugger.Something like : [ DebuggerDisplay ( @ '' One = { One } , two = { Two } '' ) ] public class A { public int One { get ; set ; } public B Two { get ; set ; } } [ DebuggerDisplay ( @ '' Three = { Three } '' ) ] public class B { public int Three { get ; set ; } } var a = new A { One = 5 , Two = new B { Three = 10 } } ; [ DebuggerDisplay ( @ '' One = { One } , two = 'Three = { Two.Three } ' '' ) ] [ DebuggerDisplay ( @ '' Three = { Three } '' ) ] public class B { public int Three { get ; set ; } public override string ToString ( ) { if ( Debugger.IsAttached ) { return string.Format ( @ '' Three = { 0 } '' , Three ) ; } else { return base.ToString ( ) ; } } }",Possible to accessing child `` DebuggerDisplay '' attribute of property ? "C_sharp : Im having a problem in mapping back to DTO.DTO : ViewModel : ControllerFor Mapping from DTO To ViewModel im using the below code , and its working fine.While converting back im not able to do . Below code i tried.But i didnt get any success . For an example i provided few properties . I real time i might have more than 30 property.Any suggestion would be appreciated ... public class ServiceEntity : BaseChild { public int Id { get ; set ; } } public class BaseChild { public string FirstName { get ; set ; } public string LastName { get ; set ; } public int Salary { get ; set ; } public string BkName { get ; set ; } public int BkPrice { get ; set ; } public string BkDescription { get ; set ; } } public class BusinessEntity { public ChildBussiness Details { get ; set ; } } public class ChildBussiness { public string NameFirst { get ; set ; } public string LastName { get ; set ; } public Books BookDetails { get ; set ; } public string Salary { get ; set ; } } public class Books { public string BookName { get ; set ; } public int BookPrice { get ; set ; } public string BookDescription { get ; set ; } } public ActionResult Index ( ) { ServiceEntity obj = GetData ( ) ; Mapper.CreateMap < ServiceEntity , BusinessEntity > ( ) .ForMember ( d = > d.Details , o = > o.MapFrom ( x = > new ChildBussiness { NameFirst = x.FirstName , LastName = x.LastName , Salary = x.Salary.ToString ( ) , BookDetails = new Books { BookDescription = x.BkDescription , BookName = x.BkName , BookPrice = x.BkPrice } } ) ) ; BusinessEntity objDetails = Mapper.Map < ServiceEntity , BusinessEntity > ( obj ) ; } ... ServiceEntity objser = new ServiceEntity ( ) ; Mapper.CreateMap < BusinessEntity , ServiceEntity > ( ) ; Mapper.CreateMap < Books , ServiceEntity > ( ) ; objser = Mapper.Map < BusinessEntity , ServiceEntity > ( model ) ; ...",AutoMapper issue when mapping back to DTO from ViewModel "C_sharp : I am trying to create a native UWP view from a Xamarin Forms view . Following the example from here , I managed to do it for Android and IOS . More precisely , on IOS the conversion looks like this : However , I need a similar approach for UWP.Any help would be appreciated ! public static UIView ConvertFormsToNative ( Xamarin.Forms.View view , CGRect size ) { var renderer = RendererFactory.GetRenderer ( view ) ; renderer.NativeView.Frame = size ; renderer.NativeView.AutoresizingMask = UIViewAutoresizing.All ; renderer.NativeView.ContentMode = UIViewContentMode.ScaleToFill ; renderer.Element.Layout ( size.ToRectangle ( ) ) ; var nativeView = renderer.NativeView ; nativeView.SetNeedsLayout ( ) ; return nativeView ; }",How to create a native UWP view from Xamarin Forms view ? "C_sharp : In our IdentityManager class we have the follow line : What is the implication of that last parameter , and does it have any correlation to how the site is set up on IIS ? Background : We 've been deploying an MVC5 site with a custom IdentityManager class to a validation environment for a long time without hassles , and now we 're getting the following issue when attempting to reset user passwords : Some solutions are described in the following thread : Generating reset password token does not work in Azure WebsiteEverything is located on the same machine : IIS , Sql Server , Firefox test browser.Unfortunately I do n't have a full grasp of the concepts and I 'm trying to figure out how the test environment has changed in order to trigger this issue where it 's never happened before ? protectionProvider = new DpapiDataProtectionProvider ( `` OurProduct '' ) ; System.Security.Cryptography.CryptographicException : The data protection operation was unsuccessful . This may have been caused by not having the user profile loaded for the current thread 's user context , which may be the case when the thread is impersonating .",What is the impact of appName in DpapiDataProtectionProvider constructor "C_sharp : I 've been banging my head against the wall for 25 minutes trying to figure out why I ca n't access the 'first ' index of an array , which I was trying to do with array [ 0 ] . I kept getting an Array Index Out of Bounds Exception . Just to see what would happen , I tried using array [ 1 ] ... and it worked . Perfectly . I have no idea why . The whole thing works fine . What 's going on here ? for ( int i = 1 ; i < itemCounter+1 ; i++ ) { if ( explorer.CurrentFolder.Items [ i ] is Outlook.MailItem ) { //Do something } }",C # Outlook Add-In Arrays Start at 1 ? "C_sharp : I have a MyButton class that inherits from Button . On this class I have placed several other controls ( Labels , Progessbar ) . The problem with this is that the controls on the Button make it impossible to fire the Button.Click or Button.MouseHover event . How can I achieve it that the controls on the Button are only displayed but are `` event transparent '' : A click/hover on the label and progessbar is the same as if I clicked/hover directly on the Button ( including sender and everything ) . Something like `` inheriting the events from the parent '' . class MyButton : Button { Label foo = new Label ( ) ; ProgressBar bar = new ProgessBar ( ) ; }","C # , fire event of container" "C_sharp : I switched to VS 2012 yesterday from VS 2010 and all seemed to go well except this.I have a button on my form that when pressed extends the width of the form to show additional controls . Press the button again and it reduces the width to hide those controls . Now all of this worked great in VS 2010 and also works fine when I debug in VS 2012 but as soon as I publish or compile the project and open the .exe when you click on the button it adds like 5 to the width instead of the 100+ it needs to . I click it again and it will then change it to 372 like it should and shows all my controls . I click it again to hide the controls and it hides the controls partially ( goes to the 188 + the mysterious 5 ) I hope all of this makes sense and am hoping there is a better way to run the process I need to.Here is the code I am currently working with and I did n't change anything between switching from 2010 to 2012 . In fact , if I open this same solution in 2010 and publish everything works fine . private void button1_Click ( object sender , EventArgs e ) { if ( this.Width == 188 ) { this.Width = 372 ; this.Height = 540 ; progressBar.Value = 100 ; copied_status.Text = ( `` Output View Enabled '' ) ; } else { progressBar.Value = 100 ; copied_status.Text = ( `` Output View Disabled '' ) ; this.Width = 188 ; this.Height = 540 ; } if ( this.Width == 372 ) { button1.Text = `` < < `` ; } else button1.Text = `` > > '' ; }",Switched to VS 2012 and now form doesnt resize properly ? "C_sharp : I have a datagrid that has a column ( the last one ) that should always show when there is room for it . Unfortunately I 'm not able to make this happen and ca n't find a solution anywhere.this WPF application is available in portrait mode and landscape mode ... When starting the application in portrait mode , I want the datagrid to always show the last column , but initially it hides several columns . But when resizing the application ( getting a larger width ) by going to landscape , and then back to portrait mode , it does work as expected.Most columns have their width set to either Auto or * . Only the last column has a minimum width of 80 pixels Because I do n't want that one to resize , It should always show.Here are the settings of the grid : Here is the initial situation in portrait modeThen when I resize to landscape : And finally when I go back to portrait mode , I get the desired result : What can I change in order to have my initial situation look like picture 3 ... So that all columns are shown from the beginning ( without the need to resize ) ? EDIT : For clarity : when I say portrait and landscape mode , I mean that the software is used on windows tablets , but the same problem occurs on regular screens aswell . When the window is initially small , not all columns show , but when I enlarge the window and then resize back to the initial small size , all columns do show . EDIT 2 : I can fix the problem if I change the width of the first column to * instead of Auto ... . I do n't know why though ... ... . Here is the Full DataGrid < DataGrid Grid.Row= '' 1 '' AutoGenerateColumns= '' False '' CanUserAddRows= '' False '' CanUserDeleteRows= '' False '' CanUserReorderColumns= '' False '' CanUserResizeColumns= '' False '' CanUserResizeRows= '' False '' CanUserSortColumns= '' False '' HorizontalScrollBarVisibility= '' Disabled '' ItemsSource= '' { Binding Path=MyCollection , Mode=OneWay } '' RowDetailsVisibilityMode= '' Collapsed '' RowHeaderStyle= '' { StaticResource ExpanderRowHeaderStyle } '' SelectionMode= '' Single '' SelectionUnit= '' Cell '' > < DataGrid Grid.Row= '' 1 '' AutoGenerateColumns= '' False '' CanUserAddRows= '' False '' CanUserDeleteRows= '' False '' CanUserReorderColumns= '' False '' CanUserResizeColumns= '' False '' CanUserResizeRows= '' False '' CanUserSortColumns= '' False '' HorizontalScrollBarVisibility= '' Disabled '' ItemsSource= '' { Binding Path=BstCollection , Mode=OneWay } '' RowDetailsVisibilityMode= '' Collapsed '' RowHeaderStyle= '' { StaticResource ExpanderRowHeaderStyle } '' SelectionMode= '' Single '' SelectionUnit= '' Cell '' EnableRowVirtualization= '' False '' Loaded= '' DataGrid_Loaded '' DataContextChanged= '' DataGrid_DataContextChanged '' ColumnWidth= '' * '' > < DataGrid.RowStyle > < Style TargetType= '' DataGridRow '' > < Style.Triggers > < DataTrigger Value= '' True '' > < DataTrigger.Binding > < MultiBinding Converter= '' { StaticResource IsLastOrderToBooleanMultiConverter } '' > < MultiBinding.Bindings > < Binding Mode= '' OneWay '' Path= '' BstCollection [ 0 ] .BesbstldOp '' Source= '' { StaticResource BstGbrModel } '' / > < ! -- ReSharper disable Xaml.BindingWithContextNotResolved -- > < Binding Mode= '' OneWay '' Path= '' BesbstldOp '' / > < Binding Mode= '' OneWay '' Path= '' BesHoeveelheid '' / > < ! -- ReSharper restore Xaml.BindingWithContextNotResolved -- > < /MultiBinding.Bindings > < /MultiBinding > < /DataTrigger.Binding > < Setter Property= '' Background '' Value= '' PowderBlue '' / > < /DataTrigger > < /Style.Triggers > < /Style > < /DataGrid.RowStyle > < DataGrid.Columns > < DataGridTemplateColumn Width= '' Auto '' Header= '' { specialLocalization : Translate CtlBstGbr -- grdBsten -- atlOmschrijving } '' IsReadOnly= '' True '' > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate DataType= '' bl : Bst '' > < TextBlock Text= '' { Binding atlOmschrijving , Mode=OneWay } '' IsEnabled= '' False '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < DataGridTemplateColumn.CellTemplate > < DataTemplate DataType= '' bl : Bst '' > < TextBlock > < Run Text= '' { Binding atlOmschrijving , Mode=OneWay } '' / > < Run Foreground= '' Red '' Text= '' { Binding Path=atl.atlVKMat , Mode=OneWay , Converter= { StaticResource BooleanToBstTextConverter } } '' / > < /TextBlock > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < /DataGridTemplateColumn > < DataGridTextColumn Width= '' Auto '' Binding= '' { Binding Path=BesbstldOp , Mode=OneWay , Converter= { StaticResource DateToStringValueConverter } } '' Header= '' { specialLocalization : Translate CtlBstGbr -- grdBsten -- BesbstldOp } '' IsReadOnly= '' True '' / > < DataGridTextColumn Width= '' Auto '' Binding= '' { Binding Path=BesGeleverdOp , Mode=OneWay , Converter= { StaticResource DateToStringValueConverter } } '' Header= '' { specialLocalization : Translate CtlBstGbr -- grdBsten -- BesGeleverdOp } '' IsReadOnly= '' True '' / > < DataGridTextColumn Width= '' * '' Binding= '' { Binding Path=BesHoeveelheid , Mode=OneWay , Converter= { StaticResource IntToStringValueConverter } } '' Header= '' { specialLocalization : Translate CtlBstGbr -- grdBsten -- BesHoeveelheid } '' IsReadOnly= '' True '' / > < DataGridTextColumn Width= '' Auto '' Binding= '' { Binding Path=atlbstleenheid , Mode=OneWay } '' Header= '' { specialLocalization : Translate CtlBstGbr -- grdBsten -- atlbstleenheid } '' IsReadOnly= '' True '' / > < DataGridTextColumn Width= '' * '' Binding= '' { Binding Path=vpeNaam , Mode=OneWay } '' Header= '' { specialLocalization : Translate CtlBstGbr -- grdBsten -- vpeNaam } '' IsReadOnly= '' True '' / > < DataGridTemplateColumn Width= '' * '' MinWidth= '' 85 '' Header= '' { specialLocalization : Translate CtlBstGbr -- grdBsten -- NHoevheid } '' > < DataGridTemplateColumn.CellTemplate > < DataTemplate DataType= '' bl : Bst '' > < TextBlock Text= '' { Binding NHoevheid , Mode=OneWay } '' IsEnabled= '' { Binding atl.atlVKMat , Mode=OneWay } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate DataType= '' bl : Bst '' > < customControls : UpDownTextBox MinValue= '' 0 '' Text= '' { Binding NHoevheid , Mode=TwoWay } '' Visibility= '' { Binding Path=atl.atlVKMat , Mode=OneWay , Converter= { StaticResource BooleanToVisibilityConverter } } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < /DataGridTemplateColumn > < /DataGrid.Columns > < DataGrid.RowDetailsTemplate > < DataTemplate DataType= '' bl : Bst '' > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' Auto '' / > < /Grid.RowDefinitions > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < Label Grid.Row= '' 0 '' Grid.Column= '' 0 '' Content= '' { specialLocalization : Translate CtlBstGbr -- lblatl -- } '' / > < TextBox Grid.Row= '' 0 '' Grid.Column= '' 1 '' IsReadOnly= '' True '' Text= '' { Binding Path=atlOmschrijving , Mode=OneWay } '' / > < Label Grid.Row= '' 1 '' Grid.Column= '' 0 '' Content= '' { specialLocalization : Translate CtlBstGbr -- lblInfo -- } '' / > < TextBox Grid.Row= '' 1 '' Grid.Column= '' 1 '' Height= '' 75 '' AcceptsReturn= '' True '' IsReadOnly= '' True '' Text= '' { Binding Path=atl.ArtInfo , Mode=OneWay } '' TextWrapping= '' WrapWithOverflow '' VerticalScrollBarVisibility= '' Visible '' / > < /Grid > < /DataTemplate > < /DataGrid.RowDetailsTemplate > < /DataGrid >",How can I make WPF datagrid columns autoresize from the beginning so they are all visible ? "C_sharp : I have several Expression < Func < User , bool > > expressions that shares properties . For example , Is there an easy way to put the u.IsActive & & u.Group ! = `` PROCESS '' in a variable and use it in e1 , e2 and e3 ? Edited : And I still want the same tree.Seems I can do it by building the expression with Expression.Lambda < Func < User , bool > > ( BinaryExpression.AndAlso ( etc ... But rather than simplifying my code it made it more difficult to read . Expression < Func < User , bool > > e1 = ( User u ) = > u.IsActive & & u.Group ! = `` PROCESS '' & & u.Name ! = null ; Expression < Func < User , bool > > e2 = ( User u ) = > u.IsActive & & u.Group ! = `` PROCESS '' & & u.Name ! = `` A '' ; Expression < Func < User , bool > > e3 = ( User u ) = > u.IsActive & & u.Group ! = `` PROCESS '' & & u.Name ! = `` B '' ;",C # refactoring lambda expressions "C_sharp : I 'm just learning Rx and was trying to implement a `` NMEA sentence reader '' from a GPS device using SerialPort . The fact that it 's GPS data is of lesser importance to the question , so let 's just clarify that the NMEA format consists of lines , and a ' $ ' sign represents the start of a new entry , so you get `` sentences '' that look similar to : Hooking up the SerialPort 's DataReceived event is pretty straightforward : This gives an IObservable < string > , but obviously the strings returned here are not necessarily aligned as NMEA sentences . For example , for the above sample data , one could get a sequence like this : How to properly turn this into a sequence of actual sentences ? In the IEnumerable world , I would probably start from a sequence of chars and write an extension method similar to this : Now I 'm wondering if there is an idiomatic way for this kind of operation in Rx ? $ [ data for first line goes here ] $ [ data for second line goes here ] ... var port = new SerialPort ( `` COM3 '' , 4800 ) ; var serialPortSource = Observable.FromEventPattern < SerialDataReceivedEventHandler , SerialDataReceivedEventArgs > ( handler = > port.DataReceived += handler , handler = > port.DataReceived -= handler ) .Select ( e = > port.ReadExisting ( ) ) ; $ [ data for first line goes here ] \r\n $ [ data forsecond line goes here ] public static IEnumerable < string > ToNmeaSentence ( this IEnumerable < char > characters ) { var sb = new StringBuilder ( ) ; foreach ( var ch in characters ) { if ( ch == ' $ ' & & sb.Length > 0 ) { yield return sb.ToString ( ) ; sb.Clear ( ) ; } sb.Append ( ch ) ; } }",How to `` reconstruct lines '' of data read from SerialPort using Rx "C_sharp : If I have a method that contains a lot of if else statements , for example : Would it be faster to place return inside these statements , so that the rest of the code is not checked after one statement is found true , or would it be faster to let the compiler hit the end bracket ? I guess it comes down to the question : Is the return statement efficient or not ? EDIT : The point of the question : Say you have a game loop that is constantly running , with code that holds a lot of methods and 'else ifs ' . If I have to update 2000 different objects 60 times a second , that 's 120000 'else ifs ' checked ( at the minimum ) per second . So the answer to the question could potentially make a difference over time . public void myMethod ( ) { if ( .. ) else if ( .. ) else if ( ... ) else if ( ... ) else if ( ... ) //and so on }",Is it faster to return early or to let the code finish ? "C_sharp : When a value type is boxed , it is placed inside an untyped reference object.So what causes the invalid cast exception here ? long l = 1 ; object obj = ( object ) l ; double d = ( double ) obj ;",How does the CLR know the type of a boxed object ? "C_sharp : I know there are a lot of questions about async/await , but I could n't find any answer to this.I 've encountered something I do n't understand , consider the following code : Obviously , on the await operator , the control returns to the caller , while the method being awaited , is running on the background . ( assume an IO operation ) But after the control comes back to the await operator , the execution becomes parallel , instead of ( my expectation ) remaining single-threaded.I 'd expect that after `` Delay '' has been finished the thread will be forced back into the Poetry method , continues from where it left.Which it does . The weird thing for me , is why the `` Main '' method keeps running ? is that one thread jumping from one to the other ? or are there two parallel threads ? Is n't it a thread-safety problem , once again ? I find this confusing . I 'm not an expert . Thanks . void Main ( ) { Poetry ( ) ; while ( true ) { Console.WriteLine ( `` Outside , within Main . `` ) ; Thread.Sleep ( 200 ) ; } } async void Poetry ( ) { //.. stuff happens before await await Task.Delay ( 10 ) ; for ( int i = 0 ; i < 10 ; i++ ) { Console.WriteLine ( `` Inside , after await . `` ) ; Thread.Sleep ( 200 ) ; } }",Unexpected behaviour after returning from await "C_sharp : Maybe there is a very logic explanation for this , but I just ca n't seem to understand why the seeds 0 and 2,147,483,647 produce the same `` random '' sequence , using .NET 's Random Class ( System ) .Quick code example : Output : As you can see , the first and the third sequence are the same . Can someone please explain this to me ? EDIT : Apparently , as alro pointed out , these sequences are not the same . But they are very similar . var random1 = new Random ( 0 ) ; var random2 = new Random ( 1 ) ; var random3 = new Random ( int.MaxValue ) ; //2,147,483,647var buffer1 = new byte [ 8 ] ; var buffer2 = new byte [ 8 ] ; var buffer3 = new byte [ 8 ] ; random1.NextBytes ( buffer1 ) ; random2.NextBytes ( buffer2 ) ; random3.NextBytes ( buffer3 ) ; for ( int i = 0 ; i < 8 ; i++ ) { Console.WriteLine ( `` { 0 } \t\t { 1 } \t\t { 2 } '' , buffer1 [ i ] , buffer2 [ i ] , buffer3 [ i ] ) ; } 26 70 2612 208 1270 134 76111 130 11193 64 93117 151 115228 228 228216 163 216",Two different seeds producing the same 'random ' sequence "C_sharp : Following my previous question as to whether ASP.net 's default Page.IsPostBack implementation is secure ( it 's not ; it can be faked ... the HTTP verb does n't even have to be POST ! ) , I was thinking ; surely there must be a better way to implement it ? Can we come up with a Page.IsPostBack implementation which , when it is true , is almost guaranteed to indicate that the page is an actual ASP.net postback ? This is important if one wants to do security checking only once ( like whether some content is going to appear , based on the user 's role ( s ) ) , and wants to do it only if we 're NOT dealing with an ASP.net postback.My first thoughts as to how to do this are to implement the checking code in a property , so I can write something like this inside Page_Load : Is there a way to securely implement _isPostBack ? Perhaps storing something in the ViewState that would be hard or impossible to jerry-rig to fake a postback ? A random string ? if ( ! _isPostBack ) { // Do security check if ( userIsNotAuthorized ) { btnViewReports.Visible = false ; btnEditDetails.Visible = false ; // etc . } }",A secure implementation of Page.IsPostBack ? "C_sharp : I 've an SQL Query : I 've tried converting it to LINQ myself but I 'm unfamiliar with the language , after some research I 've tried using Linqer but it wo n't convert the functions 'BETWEEN ' or 'COUNT'.The closest I 've gotten so far is : which does n't work and would n't return the 'depth ' even if it did , help please ! Edit : The query is used to return the depth of nodes in a nested set in an order so that I can create a representation of a hierarchy ; I 'm following this tutorial : http : //mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ on the chapter 'Finding the Depth of the Nodes ' SELECT node.GroupName , depth = COUNT ( parent.GroupName ) - 1FROM CompanyGroup nodeJOIN CompanyGroup parent ON node.LeftID BETWEEN parent.LeftID AND parent.RightIDGROUP BY node.GroupName , node.LeftIDORDER BY node.LeftID ; var groupModel = from node in db.CompanyGroups join parent in db.CompanyGroups.Where ( node.LeftID > parent.LeftID & & node.LeftID < parent.RightID ) orderby node.LeftID select node.GroupName ;",Converting an SQL query in to LINQ C # "C_sharp : I have a little C # console application that reads a key and checks to see if the key was a question mark : I arrived at Oem2 by seeing what value is actually assigned in the debugger , because there is no ConsoleKey code for question mark.Now I could certainly use ki.KeyChar instead , but the application also needs to respond to certain keys ( e.g . media keys ) that do not map to characters . It feels inelegant to check both ConsoleKey and KeyChar to determine which key has in fact been pressed . On the other hand , it does not feel safe to rely on Oem2 to always map to ? in all circumstances and regions.Is it best practice to check both properties to determine which key was in fact pressed ? Any insight into why ConsoleKeyInfo was designed this way is appreciated . ConsoleKeyInfo ki = System.Console.ReadKey ( ) ; if ( ki.ConsoleKey.Oem2 ) // Do something","ConsoleKeyInfo , the Question Mark and Portability" "C_sharp : One of my co-workers has been reading Clean Code by Robert C Martin and got to the section about using many small functions as opposed to fewer large functions . This led to a debate about the performance consequence of this methodology . So we wrote a quick program to test the performance and are confused by the results.For starters here is the normal version of the function.Here is the version I made that breaks the functionality into small functions.I use the stopwatch class to time the functions and when I ran it in debug I got the following results.These results make sense to me especially in debug as there is additional overhead in function calls . It is when I run it in release that I get the following results.These results confuse me , even if the compiler was optimizing the TinyFunctions by in-lining all the function calls , how could that make it ~57 % faster ? We have tried moving variable declarations around in NormalFunctions and it basically no effect on the run time.I was hoping that someone would know what is going on and if the compiler can optimize TinyFunctions so well , why ca n't it apply similar optimizations to NormalFunction.In looking around we found where someone mentioned that having the functions broken out allows the JIT to better optimize what to put in the registers , but NormalFunctions only has 4 variables so I find it hard to believe that explains the massive performance difference.I 'd be grateful for any insight someone can provide.Update 1As pointed out below by Kyle changing the order of operations made a massive difference in the performance of NormalFunction.Here are the results with this configuration.This is more what I expected but still leaves the question as to why order of operations can have a ~56 % performance hit.Furthermore , I then tried it with integer operations and we are back to not making any sense.And this does n't change regardless of the order of operations . static double NormalFunction ( ) { double a = 0 ; for ( int j = 0 ; j < s_OuterLoopCount ; ++j ) { for ( int i = 0 ; i < s_InnerLoopCount ; ++i ) { double b = i * 2 ; a = a + b + 1 ; } } return a ; } static double TinyFunctions ( ) { double a = 0 ; for ( int i = 0 ; i < s_OuterLoopCount ; i++ ) { a = Loop ( a ) ; } return a ; } static double Loop ( double a ) { for ( int i = 0 ; i < s_InnerLoopCount ; i++ ) { double b = Double ( i ) ; a = Add ( a , Add ( b , 1 ) ) ; } return a ; } static double Double ( double a ) { return a * 2 ; } static double Add ( double a , double b ) { return a + b ; } s_OuterLoopCount = 10000 ; s_InnerLoopCount = 10000 ; NormalFunction Time = 377 ms ; TinyFunctions Time = 1322 ms ; s_OuterLoopCount = 10000 ; s_InnerLoopCount = 10000 ; NormalFunction Time = 173 ms ; TinyFunctions Time = 98 ms ; static double NormalFunction ( ) { double a = 0 ; for ( int j = 0 ; j < s_OuterLoopCount ; ++j ) { for ( int i = 0 ; i < s_InnerLoopCount ; ++i ) { double b = i * 2 ; a = b + 1 + a ; } } return a ; } s_OuterLoopCount = 10000 ; s_InnerLoopCount = 10000 ; NormalFunction Time = 91 ms ; TinyFunctions Time = 102 ms ; s_OuterLoopCount = 10000 ; s_InnerLoopCount = 10000 ; NormalFunction Time = 87 ms ; TinyFunctions Time = 52 ms ;",C # Performance on Small Functions "C_sharp : I use ServiceStack.Text with ServiceStack ( the web service framework ) .I 'm trying to add a custom serialization route for a specific type in AppHost.Configure ( ) . However , the settings do not apply/are ignored . public AppHost : AppHostBase { ... public override void Configure ( Container container ) { //Register custom serialization routine ServiceStack.Text.JsConfig < CultureInfo > .SerializeFn = r = > r.TwoLetterISOLanguageName ; ServiceStack.Text.JsConfig < CultureInfo > .DeSerializeFn = r = > return new CultureInfo ( r ) ; } }",Why do ServiceStack.Text custom deserialization settings not apply ? "C_sharp : I 'm currently working on improving my coding sensation so I 've started adding some extension methods to the types I 'm using.I figured out , that I 'm doing the same action quite often always with the same attributes.I want to show this hint when someone calls ReplaceNewLine ( `` | '' ) : The char you want to remove is | . Use the RemoveNewLine ( ) extension without any attributes instead.I tried it with the [ Obsolete ( ... ) ] attribute , but this got shown every time I called the function . My question is : How can I show a specific hint based on my input within Visual Studio ? Code : Apposition : Of course the hint may have the Obsolete code ( 0618/CS0618 ) when it is shown , but that 's not important for me . I just want to get the hint shown ! I 'm working with C # 6.0 , .NET 4.6 and Visual Studio 2015 RC . public static class StringExtension { public static string ReplaceNewLine ( this string s ) { return s.Replace ( `` | '' , Environment.NewLine ) ; } // show hint if c is | public static string ReplaceNewLine ( this string s , string c ) { return s.Replace ( c , Environment.NewLine ) ; } }",How to show a specific hint within Visual Studio "C_sharp : The only difference between MutableSlab and ImmutableSlab implementations is the readonly modifier applied on the handle field : But they produce different results : GCHandle is a mutable struct and when you copy it then it behaves exactly like in scenario with immutableSlab.Does the readonly modifier create a hidden copy of a field ? Does it mean that it 's not only a compile-time check ? I could n't find anything about this behaviour here . Is this behaviour documented ? using System ; using System.Runtime.InteropServices ; public class Program { class MutableSlab : IDisposable { private GCHandle handle ; public MutableSlab ( ) { this.handle = GCHandle.Alloc ( new byte [ 256 ] , GCHandleType.Pinned ) ; } public bool IsAllocated = > this.handle.IsAllocated ; public void Dispose ( ) { this.handle.Free ( ) ; } } class ImmutableSlab : IDisposable { private readonly GCHandle handle ; public ImmutableSlab ( ) { this.handle = GCHandle.Alloc ( new byte [ 256 ] , GCHandleType.Pinned ) ; } public bool IsAllocated = > this.handle.IsAllocated ; public void Dispose ( ) { this.handle.Free ( ) ; } } public static void Main ( ) { var mutableSlab = new MutableSlab ( ) ; var immutableSlab = new ImmutableSlab ( ) ; mutableSlab.Dispose ( ) ; immutableSlab.Dispose ( ) ; Console.WriteLine ( $ '' { nameof ( mutableSlab ) } .handle.IsAllocated = { mutableSlab.IsAllocated } '' ) ; Console.WriteLine ( $ '' { nameof ( immutableSlab ) } .handle.IsAllocated = { immutableSlab.IsAllocated } '' ) ; } } mutableSlab.handle.IsAllocated = FalseimmutableSlab.handle.IsAllocated = True",Does the 'readonly ' modifier create a hidden copy of a field ? "C_sharp : The ECMA-335 specification states the following : *Acquiring a lock ( System.Threading.Monitor.Enter or entering a synchronized method ) shall implicitly perform a volatile read operation , and releasing a lock ( System.Threading.Monitor.Exit or leaving a synchronized method ) shall implicitly perform a volatile write operation. ( ... ) A volatile read has acquire semantics meaning that the read is guaranteed to occur prior to any references to memory that occur after the read instruction in the CIL instruction sequence . A volatile write has release semantics meaning that the write is guaranteed to happen after any memory references prior to the write instruction in the CIL instruction sequence . *This means that compilers can not move statements out of Monitor.Enter/Monitor.Exit blocks , but other statements are not forbidden to be moved into the block . Perhaps , even another Monitor.Enter could be moved into the block ( as volatile write followed by a volatile read can be swapped ) .So , could the following code : , be turned into an equivalent of the followig : , possibly leading to deadlocks ? Or am I missing anything ? class SomeClass { object _locker1 = new object ( ) ; object _locker2 = new object ( ) ; public void A ( ) { Monitor.Enter ( _locker1 ) ; //Do something Monitor.Exit ( _locker1 ) ; Monitor.Enter ( _locker2 ) ; //Do something Monitor.Exit ( _locker2 ) ; } public void B ( ) { Monitor.Enter ( _locker2 ) ; //Do something Monitor.Exit ( _locker2 ) ; Monitor.Enter ( _locker1 ) ; //Do something Monitor.Exit ( _locker1 ) ; } } class SomeClass { object _locker1 = new object ( ) ; object _locker2 = new object ( ) ; public void A ( ) { Monitor.Enter ( _locker1 ) ; //Do something Monitor.Enter ( _locker2 ) ; Monitor.Exit ( _locker1 ) ; //Do something Monitor.Exit ( _locker2 ) ; } public void B ( ) { Monitor.Enter ( _locker2 ) ; //Do something Monitor.Enter ( _locker1 ) ; Monitor.Exit ( _locker2 ) ; //Do something Monitor.Exit ( _locker1 ) ; } }",Interlocking Monitor.Enter and Monitor.Exit blocks "C_sharp : I have a Message object which wraps a message format I do not have control over . The format is a simple list of Key/Value pairs . I want to extract a list of Users from a given Message . For example given the following message ... I want to extract four Users with the provided properties set . The initial keys 200/300 ... .405 represent fields I do n't need and can skip to get to the User data . Each users data is in consecutive fields but the number of fields varies depending on how much information is known about a user . The following method does what I 'm looking for . It uses an enumeration of possible key types and a method to find the index of the first field with user data . I 'm wondering if its possible to replace the method with a Linq query . I 'm having trouble telling Linq to select a new user and populate its fields with all matching data until you find the start of the next user entry . Note : Relative key numbers are random ( not 1,2,3,4 ) in the real message format . 1 . 200- > ... .2 . 300- > ... .3 . ... .4 . 405- > ... . 5 . 001- > first_user_name6 . 002- > first_user_phone7 . 003- > first_user_fax8 . 001- > second_user_name9 . 001- > third_user_name10 . 002- > third_user_phone11 . 003- > third_user_fax12 . 004- > third_user_address13 . ... ..14 . 001- > last_user_name15 . 003- > last_user_fax private List < User > ParseUsers ( Message message ) { List < User > users = new List < User > ( ) ; User user = null ; String val = String.Empty ; for ( Int32 i = message.IndexOfFirst ( Keys.Name ) ; i < message.Count ; i++ ) { val = message [ i ] .Val ; switch ( message [ i ] .Key ) { case Keys.Name : user = new User ( val ) ; users.Add ( user ) ; break ; case Keys.Phone : user.Phone = val ; break ; case Keys.Fax : user.Fax = val ; break ; case Keys.Address : user.Address = val ; break ; default : break ; } } return users ; }",Replace for-switch loop with a Linq query "C_sharp : Disclaimer , I 'm from a Java background . I do n't do much C # . There 's a great deal of transfer between the two worlds , but of course there are differences and one is in the way Exceptions tend to be thought about.I recently answered a C # question suggesting that under some circstances it 's reasonable to do this : ( The reasons why are immaterial ) . I got a response that I do n't quite understand : until .NET 4.0 , it 's very bad to catch Exception . It means you catch various low-level fatal errors and so disguise bugs . It also means that in the event of some kind of corruption that triggers such an exception , any open finally blocks on the stack will be executed , so even if the callExceptionReporter fuunction tries to log and quit , it may not even get to that point ( the finally blocks may throw again , or cause more corruption , or delete something important from the disk or database ) .May I 'm more confused than I realise , but I do n't agree with some of that . Please would other folks comment . I understand that there are many low level Exceptions we do n't want to swallow . My commonExceptionHandler ( ) function could reasonably rethrow those . This seems consistent with this answer to a related question . Which does say `` Depending on your context it can be acceptable to use catch ( ... ) , providing the exception is re-thrown . '' So I conclude using catch ( Exception ) is not always evil , silently swallowing certain exceptions is.The phrase `` Until .NET 4 it is very bad to Catch Exception '' What changes in .NET 4 ? IS this a reference to AggregateException , which may give us some new things to do with exceptions we catch , but I do n't think changes the fundamental `` do n't swallow '' rule.The next phrase really bothers be . Can this be right ? It also means that in the event of some kind of corruption that triggers such an exception , any open finally blocks on the stack will be executed ( the finally blocks may throw again , or cause more corruption , or delete something important from the disk or database ) My understanding is that if some low level code hadand in my code I call lowLevel ( ) ; Whether or not I catch Exception this has no effect whatever on the excution of the finally block . By the time we leave lowLevelMethod ( ) the finally has already run . If the finally is going to do any of the bad things , such as corrupt my disk , then it will do so . My catching the Exception made no difference . If It reaches my Exception block I need to do the right thing , but I ca n't be the cause of dmis-executing finallys try { some work } catch ( Exeption e ) { commonExceptionHandler ( ) ; } lowLevelMethod ( ) { try { lowestLevelMethod ( ) ; } finally { some really important stuff } } try { lowLevel ( ) } catch ( Exception e ) { exception handling and maybe rethrowing }",.NET and C # Exceptions . What is it reasonable to catch "C_sharp : Ok , here is the deal : I want to load a user defined Assembly into my AppDomain , but I only want to do so if the specified Assembly matches some requirements . In my case , it must have , among other requirements , an Assembly level Attribute we could call MandatoryAssemblyAttribute.There are two paths I can go as far as I see : Load the Assembly into my current AppDomain and check if the Attribute is present . Easy but inconvenient as I 'm stuck with the loaded Assembly even if it doesnt have the MandatoryAssemblyAttribute . Not good.I can create a new AppDomain and load the Assembly from there and check if my good old MandatoryAddemblyAttribute is present . If it is , dump the created AppDomain and go ahead and load the Assembly into my CurrentAppDomain , if not , just dump the new AppDomain , tell the user , and have him try again.Easier said than done . Searching the web , I 've found a couple of examples on how to go about this , including this previous question posted in SO : Loading DLLs into a separate AppDomainThe problem I see with this solution is that you actually have to know a type ( full name ) in the Assembly you want to load to begin with . That is not a solution I like . The main point is trying to plug in an arbitrary Assembly that matches some requirements and through attributes discover what types to use . There is no knowledge beforehand of what types the Assembly will have . Of course I could make it a requirement that any Assembly meant to be used this way should implement some dummy class in order to offer an `` entry point '' for CreateInstanceFromAndUnwrap . I 'd rather not.Also , if I go ahead and do something along this line : This will work fine , but if then I go ahead and do the following : I get a FileNotFoundException . Why ? Another path I could take is this one : How load DLL in separate AppDomain But I 'm not getting any luck either . I 'm getting a FileNotFoundException whenever I choose some random .NET Assembly and besides it defeats the purpose as I need to know the Assembly 's name ( not file name ) in order to load it up which does n't match my requirements.Is there another way to do this barring MEF ( I am not targeting .NET 3.5 ) ? Or am I stuck with creating some dummy object in order to load the Assembly through CreateInstanceFromAndUnwrap ? And if so , why ca n't I iterate through the loaded assemblies without getting a FileNotFoundException ? What am I doing wrong ? Many thanks for any advice . using ( var frm = new OpenFileDialog ( ) ) { frm.DefaultExt = `` dll '' ; frm.Title = `` Select dll ... '' ; frm.Filter = `` Model files ( *.dll ) |*.dll '' ; answer = frm.ShowDialog ( this ) ; if ( answer == DialogResult.OK ) { domain = AppDomain.CreateDomain ( `` Model '' , new Evidence ( AppDomain.CurrentDomain.Evidence ) ) ; try { domain.CreateInstanceFrom ( frm.FileName , `` DummyNamespace.DummyObject '' ) ; modelIsValid = true ; } catch ( TypeLoadException ) { ... } finally { if ( domain ! = null ) AppDomain.Unload ( domain ) ; } } } foreach ( var ass in domain.GetAssemblies ( ) ) //Do not fret , I would run this before unloading the AppDomain Console.WriteLine ( ass.FullName ) ;",Loading an Assembly if a certain Attribute is present "C_sharp : What 's the difference between RDF and XMP ? From what I can tell , XMP is derived from RDF ... so what does it offer that RDF does n't ? My particular situation is this : I 've got some images which need tagging with details of how an experiment was performed , and what sort of data analysis has been performed on the images . A colleague of mine is pushing for XMP , but he 's thinking of the images as photos - they 're not really , they 're just bits of data.From what I 've seen ( mainly by opening images in notepad++ ) the XMP data looks very similar to RDF - even so far as using RDF in the tag names ( e.g . < rdf : Seq > ) .I 'd like this data to be usable by other people who use similar instruments for similar experiments , so creating a mini standard ( schema ? ) seems like the way to go.Apologies for the lack of fundemental understanding - I 'm a Doctor , not a programmer ! If it makes any difference , the language of choice will be C # .Edit for more information : First off , thanks for the excellent replies - thinking of XMP as a vocabulary for RDF makes things a lot clearer.The sort of data I 'll be storing wont be avaliable in any of the pre-defined sets . It 'll detail experimental set ups , locations and results . I think using RDF is the way to go . An example of the sort of thing ( stored in XML as it is currently ) would be : Off the top of my head , I guess I 'm going to be storing this in RDF as follows : Thanks for the advice : ) < Experiment name= '' test2 '' loc= '' lab '' timestamp= '' 65420233400 '' > < Instrument name= '' a1 '' rev= '' 1.0 '' / > < Calibration > < date > 13-02-10 < /date > < type > complete < /type > < /Calibration > < /Experiment > < rdf : RDF xmlns : rdf= '' http : //www.w3.org/1999/02/22-rdf-syntax-ns # '' xmlns : zotty= '' http : //www.zotty.com/rdf/ '' > < zotty : experiment > < rdf : Bag > < zotty : name > test2 < /zotty : name > < zotty : loc > lab < /zotty : loc > < zotty : timestamp > 65420233400 < /zotty : timestamp > < zotty : instrument > < rdf : Bag > < zotty : name > a1 < /zotty : name > < zotty : rev > 1.0 < /zotty : rev > < zotty : calibration > < rdf : bag > < zotty : date > 13-02-10 < /zotty : date > < zotty : type > complete < /zotty : type > < /rdf : bag > < /zotty : calibration > < /rdf : Bag > < /zotty : instrument > < rdf : Bag > < /zotty : experiment > < /rdf : RDF >","Which to use , XMP or RDF ?" "C_sharp : I am trying this sample of code and OpTest when System.Console.WriteLine ( s == t ) ; it returns false . Can somebody explain this ? public static void OpTest < T > ( T s , T t ) where T : class { System.Console.WriteLine ( s == t ) ; } static void Main ( ) { string s1 = `` строка '' ; System.Text.StringBuilder sb = new System.Text.StringBuilder ( s1 ) ; System.Console.Write ( sb ) ; string s2 = sb.ToString ( ) ; OpTest < string > ( s1 , s2 ) ; }",StringBuilder and string equality check C_sharp : The problem I am having is that the List of IFormFile is not being populated with the given files but when i call HttpContext.Request.Form.Files ; then I have access to the files . I would prefer to use IFormFile as it seems to be new Dotnet core 2.0 way of doing things.I have the following request payload : With the following request headers : And Razor pages handler : Condition response model : public async Task < ActionResult > OnPostSend ( ConditionResponse conditionResponse ) { var files = HttpContext.Request.Form.Files ; } public class ConditionResponse { public List < string > Plots { get ; set ; } public string Comments { get ; set ; } public List < IFormFile > Files { get ; set ; } },IFormFile not being populated by dropzone uploadMultiple request "C_sharp : I have a class I am working with : It 's ToString is weak ( Just shows Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType ) .Is there any way to override this to show the name of the WorkItemType ? Normally I would just aggregate the value in a new class , but I am using this for bindings in WPF ( I want to have a list of WorkItemTypes in a combo box and assign the selected value to a bound WorkItemType variable . ) I think I am out of luck here , but I thought I would ask . public sealed class WorkItemType",Change `` ToString '' for a sealed class "C_sharp : I 'm fine with both C # and VB.NETI have two tables . Authors and Books . It 's a one to many relationship , Authors to Books . I 'm writing a query to show how many books that each author has.I wrote the following query : This query will give the following result : But in the Authors table , there are some authors without any books yet . For example , there two authors , Author D and Author E that have no books yet . I want to write query that includes all authors and number of ther books , even though they do n't have any book yet , no record in the Books table yet.I want to get something like like this : Thank you . Dim query = From oa In db.Authors _ Group oa By oa.Book Into grouping = Group _ Select Author = Book , Count = grouping.Count ( Function ( s ) s.AuthorId ) - Author A : 2 books - Author B : 3 books - Author C : 1 book - Author A : 2 books - Author B : 3 books - Author C : 1 book - Author D : 0 book - Author E : 0 book",Count child record and show zero if empty "C_sharp : It seems that C # is faster at adding two arrays of UInt16 [ ] than it is at adding two arrays of int [ ] . This makes no sense to me , since I would have assumed the arrays would be word-aligned , and thus int [ ] would require less work from the CPU , no ? I ran the test-code below , and got the following results : The test code does the following : Creates two arrays named a and b , once.Fills them with random data , once.Starts a stopwatch.Adds a and b , item-by-item . This is done 1000 times.Stops the stopwatch.Reports how long it took.This is done for int [ ] a , b and for UInt16 a , b . And every time I run the code , the tests for the UInt16 arrays take 30 % -50 % less time than the int arrays . Can you explain this to me ? Here 's the code , if you want to try if for yourself : Int for 1000 took 9896625613 tick ( 4227 msec ) UInt16 for 1000 took 6297688551 tick ( 2689 msec ) public static UInt16 [ ] GenerateRandomDataUInt16 ( int length ) { UInt16 [ ] noise = new UInt16 [ length ] ; Random random = new Random ( ( int ) DateTime.Now.Ticks ) ; for ( int i = 0 ; i < length ; ++i ) { noise [ i ] = ( UInt16 ) random.Next ( ) ; } return noise ; } public static int [ ] GenerateRandomDataInt ( int length ) { int [ ] noise = new int [ length ] ; Random random = new Random ( ( int ) DateTime.Now.Ticks ) ; for ( int i = 0 ; i < length ; ++i ) { noise [ i ] = ( int ) random.Next ( ) ; } return noise ; } public static int [ ] AddInt ( int [ ] a , int [ ] b ) { int len = a.Length ; int [ ] result = new int [ len ] ; for ( int i = 0 ; i < len ; ++i ) { result [ i ] = ( int ) ( a [ i ] + b [ i ] ) ; } return result ; } public static UInt16 [ ] AddUInt16 ( UInt16 [ ] a , UInt16 [ ] b ) { int len = a.Length ; UInt16 [ ] result = new UInt16 [ len ] ; for ( int i = 0 ; i < len ; ++i ) { result [ i ] = ( ushort ) ( a [ i ] + b [ i ] ) ; } return result ; } public static void Main ( ) { int count = 1000 ; int len = 128 * 6000 ; int [ ] aInt = GenerateRandomDataInt ( len ) ; int [ ] bInt = GenerateRandomDataInt ( len ) ; Stopwatch s = new Stopwatch ( ) ; s.Start ( ) ; for ( int i=0 ; i < count ; ++i ) { int [ ] resultInt = AddInt ( aInt , bInt ) ; } s.Stop ( ) ; Console.WriteLine ( `` Int for `` + count + `` took `` + s.ElapsedTicks + `` tick ( `` + s.ElapsedMilliseconds + `` msec ) '' ) ; UInt16 [ ] aUInt16 = GenerateRandomDataUInt16 ( len ) ; UInt16 [ ] bUInt16 = GenerateRandomDataUInt16 ( len ) ; s = new Stopwatch ( ) ; s.Start ( ) ; for ( int i=0 ; i < count ; ++i ) { UInt16 [ ] resultUInt16 = AddUInt16 ( aUInt16 , bUInt16 ) ; } s.Stop ( ) ; Console.WriteLine ( `` UInt16 for `` + count + `` took `` + s.ElapsedTicks + `` tick ( `` + s.ElapsedMilliseconds + `` msec ) '' ) ; }",Why do UInt16 arrays seem to add faster than int arrays ? "C_sharp : I would like to get your opinion on as how far to go with side-effect-free setters.Consider the following example : Note that values for date and duration are shown only for indicative purposes.So using setter for any of the properties Start , Finish and Duration will consequently change other properties and thus can not be considered side-effect-free.Same applies for instances of the Rectangle class , where setter for X is changing the values of Top and Bottom and so on.The question is where would you draw a line between using setters , which have side-effects of changing values of logically related properties , and using methods , which could n't be much more descriptive anyway . For example , defining a method called SetDurationTo ( Duration duration ) also does n't reflect that either Start or Finish will be changed . Activity activity ; activity.Start = `` 2010-01-01 '' ; activity.Duration = `` 10 days '' ; // sets Finish property to `` 2010-01-10 ''",Approach to side-effect-free setters "C_sharp : I have found myself recently writing a lot of boilerplate MVVM code and wonder if there is a fancy way to get around writing it all ? I already use a ViewModelBase class that implements INotifyPropertyChanged but that doesnt solve the problem of having to write all the accessor code etc . Perhaps by writing a custom attribute that does this , or via a templating system ? public MyClass : ViewModelBase { private int someVariable ; public int SomeVariable { get { return this.someVariable ; } set { this.someVariable = value ; this.NotifyPropertyChanged ( `` SomeVariable '' ) ; } } }",A better way to write MVVM boilerplate code ? "C_sharp : When using IFormFile I am getting this error at running time : Could not load type 'Microsoft.AspNetCore.Http.Internal.FormFile ' from assembly 'Microsoft.AspNetCore.Http , Version=3.0.0.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60'.I have tried adding packages : Documentation exists for FormFile Aspnetcore 3.0 . However when checking my sdk , instead of using 3.0 . It is only available in .net core 2.2 . I have both versions 2.2 and 3.0 installedregion Assembly Microsoft.AspNetCore.Http , Version=2.2.0.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 < ItemGroup > < PackageReference Include= '' Microsoft.AspNetCore.Http '' Version= '' 2.2.2 '' / > < PackageReference Include= '' Microsoft.AspNetCore.Http.Features '' Version= '' 3.0.0 '' / > < PackageReference Include= '' Microsoft.AspNetCore.Mvc.Core '' Version= '' 2.2.5 '' / > < PackageReference Include= '' Microsoft.AspNetCore.Mvc.NewtonsoftJson '' Version= '' 3.0.0 '' / > < PackageReference Include= '' Microsoft.Extensions.Http '' Version= '' 3.0.0 '' / > < PackageReference Include= '' Microsoft.Net.Http.Headers '' Version= '' 2.2.0 '' / > using Microsoft.AspNetCore.Http.Internal ; IFormFile f = new FormFile ( memoryStream , 0 , memoryStream.Length , `` test '' , `` test.pdf '' ) ; // C : \Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.http\2.2.0\lib\netstandard2.0\Microsoft.AspNetCore.Http.dll # endregionusing System.IO ; using System.Runtime.CompilerServices ; using System.Threading ; using System.Threading.Tasks ; namespace Microsoft.AspNetCore.Http.Internal { public class FormFile : IFormFile }",IFormFile not load type Microsoft.AspNetCore.Http.Internal.FormFile ' from assembly 'Microsoft.AspNetCore.Http 3.0 ' C_sharp : Its my understanding that the questions in StackOverflow has the following formatSo basically the question is retrieved using the question-id . so whatever value I give the slug is immaterial.First I would like to know whether this understanding is wrong : ) I have a URLThen I changed the slug manually like this.But it changed to the original slug . Firebug showed me a permenant redirect 301 on the altered URL . How to implement this functionality ? http : //stackoverflow.com/questions/ { question-id } / { slug-made-from-question-title } http : //stackoverflow.com/questions/6291678/convert-input-string-to-a-clean-readable-and-browser-acceptable-route-data http : //stackoverflow.com/questions/6291678/naveen,StackOverflow like URL Routing "C_sharp : I have a TreeNode class as follows : And I have a BuildTree method that populates the tree structure setting the node Name and type for each node ( e.g . The first node will be set to Root Type , and child nodes could be either Element or Category types ) . I 'm looking for an efficient way ( perhaps using LINQ ) to prune tree branches where the ending node type is not of type Category . Any ideas on how to achieve that ? Here a visual example : Before : After : Thanks in advance ! public class TreeNode { public enum NodeType { Root , Element , Category } public TreeNode ( ) { Children = new List < TreeNode > ( ) ; } public List < TreeNode > Children { get ; set ; } public string Name { get ; set ; } public NodeType Type { get ; set ; } } Root||_ NodeA ( Element ) |_ Node B ( Element ) | |_ Node B.1 ( Category ) |_ Node C ( Element ) | |_ Node C.1 ( Element ) | |_Node C.1.1 ( Category ) |_ Node D ( Element ) |_Node D.1 ( Element ) Root||_ Node B ( Element ) | |_ Node B.1 ( Category ) |_ Node C ( Element ) |_ Node C.1 ( Element ) |_Node C.1.1 ( Category )",Prune tree branches where ending nodes meet some criteria "C_sharp : Am using a For Loop like following : it works fine , but when i put a break point and apply condition as mod=150 then it slow down the execution . why this is happening ? what is actually happening when i add such conditional breakpoints ? for ( int i = 0 ; i < 1000 ; i++ ) { int mod = i % 1795 ; //Do some operations here }",Visual Studio slow down the execution when use conditional break points "C_sharp : I 'm thinking about designing a method that would return an object that implements an interface but whose concrete type wo n't be know until run-time . For example suppose : We do n't know what car we will get back until runtime . a ) I want to know what type of car the person has.b ) depending on the concrete car type we get back we will call different methods ( because some methods only make sense on the class ) . So the client code will do something like.Is this a good design ? Is there a code smell ? Is there a better way to do this ? I 'm fine with the method that returns the interface , and if the client code was calling interface methods obviously this would be fine . But my concern is whether the client code casting to concrete types is good design . ICarFord implements ICarBmw implements ICarToyota implements ICarpublic ICar GetCarByPerson ( int personId ) ICar car = GetCarByPerson ( personId ) ; if ( car is Bmw ) { ( ( Bmw ) car ) .BmwSpecificMethod ( ) ; } else if ( car is Toyota ) { ( ( Toyota ) car ) .ToyotaSpecificMethod ( ) ; }",C # : Method to return object whose concrete type is determined at runtime ? "C_sharp : In the When method , I would like to log when a predicate or Func < bool > returns false . However , just logging `` condition not met '' does n't give me much information . If I call the method like so : Is there a way to convert that expression into a readable/meaningful string for logging purposes ? public class Demo { public void When ( Func < Person , bool > condition ) { if ( ! condition ) { Log.Info ( `` Condition not met . `` ) ; return ; } // Do something } } demo.When ( x = > x.Name == `` John '' ) ;",Logging lambda expressions "C_sharp : I have a list of complex objects i.e.And I have a list from another source that just give me int ids that are in the list of objectsNow for each of the items in the idList I want to set the selected property true . I know I can set up a foreach of one list and then search for the matching items in the other list and set it that way , but I was wondering if there 's a different way that might be quicker . class MyObject { public bool selected ; public int id ; public string name ; } List < MyObject > theObjects = functionThatSelectsObjectsFromContainer ( ) ; List < int > idList = functionThatReturnsListOfIds ( ) ;",Apply function to some elements of list "C_sharp : I have a C # /.NET app which currently uses StringBuilder to generate an HTML email message.A new message format has been developed and now includes more formatting and CSS . I 'd like to avoid appending each line of the file using StringBuilder , so I thought it best to include the HTML file as a resource.However , there are about 21 variables within the CSS and HTML which I need to change on the fly . My first thought was to replace them with the standard String.Format placeholders ( { 0 } , { 1 } etc ) but when viewing the HTML , validation complains about these.I 'm rather stumped as to what the best practice is for storing a 200-line HTML file and changing parts of it before inclusion in an email.Example : Within the CSS , I need to change the color of certain elements , like this : And within the HTML , I need to change strings and URLs , like this : It seems including the HTML as a resource in the project would be best , but trying to use String.Format with that resource , regardless if it would work , is a poor method because of the aforementioned validation errors.Any suggestions ? # header { background-color : { 0 } ; } < img src= '' { 1 } '' / > < span > { 2 } < /span >",How to include HTML document in .NET application with variable fields ? "C_sharp : I know how to run complete NUnit assemblies from C # CodeBut how can I run single TestFixtures or even Single Tests ? TestPackage testPackage = new TestPackage ( assemblyName ) ; RemoteTestRunner remoteTestRunner = new RemoteTestRunner ( ) ; remoteTestRunner.Load ( testPackage ) ; TestResult testResult = remoteTestRunner.Run ( new NullListener ( ) , TestFilter.Empty , false , LoggingThreshold.Error ) ;",Running Single TestFixtures from C # Code "C_sharp : If I have an application with a synchronous method , is it safe to call an async method as shown below on a UI thread or is there an issue or potential deadlock situation ? I know that calling Wait will obviously cause issues , but I feel like this may work out alright.I can successfully run on a UI thread without issue , but I feel as if I may be missing something . I understand that I could use a Task and ContinueWith , but in this example , I would want to wait for the result of the async method before exiting the synchronous method.Update / ClarificationIn the example above , let 's assume that the MyMainMethod is an overridden method or a property , etc . and can not be modified to be async . public void MyMainMethod ( ) { var getResult = Task.Run ( async ( ) = > { await getResultAsync ( ) ; } ) .Result ; myLabel.Text = getResult ; }",Safe to run async delegate in synchronous method on UI ? "C_sharp : Is there a recommended way to search for each of multiple terms using StartsWith when the terms are not known at compile time ? I envision something like this : The query would be the equivalent of : Is the answer to build a LINQ query at runtime ( PredicateBuilder or similar ) ? var searchTerms = `` John Doe '' .Split ( new [ ] { ' ' } , StringSplitOptions.RemoveEmptyEntries ) ; var query = session.Query < Person , PersonIndex > ( ) .Where ( x = > x.FirstName.StartsWithAnyOf ( searchTerms ) || x.LastName.StartsWithAnyOf ( searchTerms ) ) ; var query = session.Query < Person , PersonIndex > ( ) .Where ( x = > x.FirstName.Starts ( searchTerms [ 0 ] ) || x.LastName.StartsWith ( searchTerms [ 0 ] ) || x.FirstName.Starts ( searchTerms [ 1 ] ) || x.LastName.StartsWith ( searchTerms [ 1 ] ) ) ;",RavenDB search for each of multiple terms using StartsWith "C_sharp : I wrote a simple program to examine how IL works : The IL : I 'm trying to understand the implemented efficiency : at line # 1 ( IL code ) it pushes the value 5 onto the stack ( 4 bytes which is int32 ) at line # 2 ( IL code ) it POPs from the stack into a local variable.same goes for the next 2 lines.and then , it loads those local variables onto the stack and THEN it evaluate bge.s.Question # 1Why does he loads the local variables to the stack ? the values has already been in the stack . but he poped them in order to put them in a local variables . is n't it a waste ? I mean , why the code could n't be something like : my sample of code is just 5 lines of code . what about 50,000,000 lines of code ? there will be plenty of extra code emitted by ILQuestion # 2Looking at the code address : where is the IL_0009 address ? isnt it supposed to be sequential ? p.s . Im with Optimize flag on + release mode void Main ( ) { int a=5 ; int b=6 ; if ( a < b ) Console.Write ( `` 333 '' ) ; Console.ReadLine ( ) ; } IL_0000 : ldc.i4.5 IL_0001 : stloc.0 IL_0002 : ldc.i4.6 IL_0003 : stloc.1 IL_0004 : ldloc.0 IL_0005 : ldloc.1 IL_0006 : bge.s IL_0012IL_0008 : ldstr `` 333 '' IL_000D : call System.Console.WriteIL_0012 : call System.Console.ReadLine IL_0000 : ldc.i4.5IL_0001 : ldc.i4.6 IL_0002 : bge.s IL_0004IL_0003 : ldstr `` 333 '' IL_0004 : call System.Console.WriteIL_0005 : call System.Console.ReadLine",IL & stack implementation in .net ? "C_sharp : I have created a newsletter system that allows me to specify which members should receive the newsletter . I then loop through the list of members that meet the criteria and for each member , I generate a personalized message and send them the email asynchronously .When I send out the email , I am using ThreadPool.QueueUserWorkItem . For some reason , a subset of the members are getting the email twice . In my last batch , I was only sending out to 712 members , yet a total of 798 messages ended up being sent.I am logging the messages that get sent out and I was able to tell that the first 86 members received the message twice . Here is the log ( in the order the messages were sent ) Each member should receive the newsletter once , however , as you can see member 163992 receives message # 1 and # 86 ; member 163993 received message # 2 and # 87 ; and so on . The other thing to note is that there was a 7 second delay between sending message # 85 and # 86.I have reviewed the code several times and ruled out pretty much all of the code as being the cause of it , except for possibly the ThreadPool.QueueUserWorkItem.This is the first time I work with ThreadPool , so I am not that familiar with it . Is it possible to have some sort of race-condition that is causing this behavior ? === -- - Code Sample -- - === No . Member Date1 . 163992 3/8/2012 12:28:13 PM2 . 163993 3/8/2012 12:28:13 PM ... 85 . 164469 3/8/2012 12:28:37 PM86 . 163992 3/8/2012 12:28:44 PM87 . 163993 3/8/2012 12:28:44 PM ... 798 . 167691 3/8/2012 12:32:36 PM foreach ( var recipient in recipientsToEmail ) { _emailSender.SendMemberRegistrationActivationReminder ( eventArgs.Newsletter , eventArgs.RecipientNotificationInfo , previewEmail : string.Empty ) ; } public void SendMemberRegistrationActivationReminder ( DomainObjects.Newsletters.Newsletter newsletter , DomainObjects.Members.MemberEmailNotificationInfo recipient , string previewEmail ) { //Build message here ... ..//Send the message this.SendEmailAsync ( fromAddress : _settings.WebmasterEmail , toAddress : previewEmail.IsEmailFormat ( ) ? previewEmail : recipientNotificationInfo.Email , subject : emailSubject , body : completeMessageBody , memberId : previewEmail.IsEmailFormat ( ) ? null //if this is a preview message , do not mark it as being sent to this member : ( int ? ) recipientNotificationInfo.RecipientMemberPhotoInfo.Id , newsletterId : newsletter.Id , newsletterTypeId : newsletter.NewsletterTypeId , utmCampaign : utmCampaign , languageCode : recipientNotificationInfo.LanguageCode ) ; } private void SendEmailAsync ( string fromAddress , string toAddress , string subject , MultiPartMessageBody body , int ? memberId , string utmCampaign , string languageCode , int ? newsletterId = null , DomainObjects.Newsletters.NewsletterTypeEnum ? newsletterTypeId = null ) { var urlHelper = UrlHelper ( ) ; var viewOnlineUrlFormat = urlHelper.RouteUrl ( `` UtilityEmailRead '' , new { msgid = `` msgid '' , hash = `` hash '' } ) ; ThreadPool.QueueUserWorkItem ( state = > SendEmail ( fromAddress , toAddress , subject , body , memberId , newsletterId , newsletterTypeId , utmCampaign , viewOnlineUrlFormat , languageCode ) ) ; }",Partial work being done twice ( ThreadPool.QueueUserWorkItem ) "C_sharp : I 'm new to C # , and I am programming my first big project , a Discord bot.The idea is that the bot scans through comments , waiting for the word Cthulhu , and once someone says Cthulhu , the bot sends a message . However , in it 's current state , it never stops sending messages . I suspect there 's something wrong with my conditional , but have no idea how to fix it . How should I modify my code to fix this ? This is my code , I have the NuGet packages discord.net and discord.commands installed : discord.MessageReceived += async ( s , e ) = > { if ( e.Message.RawText.Contains ( `` Cthulhu '' ) ) await e.Channel.SendMessage ( `` *Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn* '' ) ; } ;",Continuous Message Sending in C # C_sharp : The board is int [ ] [ ] and I would like to find this shape with all 4 of it 's symmetric ( rotational ) variants from the board and log the positions.e.g.Is it better to use F # to deal with these kinds of problems ? Below is my c # code for checking patterns vertically only ( the code to check horizontally is simillar ) 1 1 1 ... ... ... x x x x x x ... ... x x 1 1 x x ... ... x 1 x x x x ... ... x x x x x x ... ... ... List < Position > GetMatchVertical ( int reelID ) { List < Position > ret = new List < Position > ( ) ; var myReel = board [ reelID ] ; var leftReel = reelID - 1 > = 0 ? board [ reelID - 1 ] : null ; var rightReel = reelID + 1 < boardSize ? board [ reelID + 1 ] : null ; int currentColor = myReel [ 0 ] ; for ( int reelPosition = 1 ; reelPosition < boardSize ; reelPosition++ ) { int nextColor = myReel [ reelPosition ] ; if ( currentColor == nextColor ) { if ( leftReel ! =null ) { if ( reelPosition + 1 < boardSize & & leftReel [ reelPosition + 1 ] == currentColor ) { ret.Add ( logPosition ( ... ) ) ; } } if ( rightReel ! =null ) { if ( reelPosition - 2 > = 0 & & rightReel [ reelPosition - 2 ] == currentColor ) { ret.Add ( logPosition ( ... ) ) ; } } } else { currentColor = nextColor ; } } return ret ; },How to do pattern /shape match / recognition on a board ( 20x20 ) ? "C_sharp : With two immutable classes Base and Derived ( which derives from Base ) I want to define Equality so thatequality is always polymorphic - that is ( ( Base ) derived1 ) .Equals ( ( Base ) derived2 ) will call Derived.Equalsoperators == and ! = will call Equals rather than ReferenceEquals ( value equality ) What I did : Here everything ends up in Equals ( object ) which is always polymorphic so both targets are achieved.I then derive like this : Which is basically the same except for one gotcha - when calling base.Equals I call base.Equals ( object ) and not base.Equals ( Derived ) ( which will cause an endless recursion ) .Also Equals ( C ) will in this implementation do some boxing/unboxing but that is worth it for me.My questions are - First is this correct ? my ( testing ) seems to suggest it is but with C # being so difficult in equality I 'm just not sure anymore .. are there any cases where this is wrong ? and Second - is this good ? are there better cleaner ways to achieve this ? class Base : IEquatable < Base > { public readonly ImmutableType1 X ; readonly ImmutableType2 Y ; public Base ( ImmutableType1 X , ImmutableType2 Y ) { this.X = X ; this.Y = Y ; } public override bool Equals ( object obj ) { if ( object.ReferenceEquals ( this , obj ) ) return true ; if ( obj is null || obj.GetType ( ) ! =this.GetType ( ) ) return false ; return obj is Base o & & X.Equals ( o.X ) & & Y.Equals ( o.Y ) ; } public override int GetHashCode ( ) = > HashCode.Combine ( X , Y ) ; // boilerplate public bool Equals ( Base o ) = > object.Equals ( this , o ) ; public static bool operator == ( Base o1 , Base o2 ) = > object.Equals ( o1 , o2 ) ; public static bool operator ! = ( Base o1 , Base o2 ) = > ! object.Equals ( o1 , o2 ) ; } class Derived : Base , IEquatable < Derived > { public readonly ImmutableType3 Z ; readonly ImmutableType4 K ; public Derived ( ImmutableType1 X , ImmutableType2 Y , ImmutableType3 Z , ImmutableType4 K ) : base ( X , Y ) { this.Z = Z ; this.K = K ; } public override bool Equals ( object obj ) { if ( object.ReferenceEquals ( this , obj ) ) return true ; if ( obj is null || obj.GetType ( ) ! =this.GetType ( ) ) return false ; return obj is Derived o & & base.Equals ( obj ) /* ! */ & & Z.Equals ( o.Z ) & & K.Equals ( o.K ) ; } public override int GetHashCode ( ) = > HashCode.Combine ( base.GetHashCode ( ) , Z , K ) ; // boilerplate public bool Equals ( Derived o ) = > object.Equals ( this , o ) ; }",Equality and polymorphism "C_sharp : Consider the following code : Let 's say I call Run ( ) . I have a few questions regarding behaviour : Will PerformCalc ( ) be called synchronously on the same thread as the one that called Run ( ) ? Will DoLongTaskAsync ( ) be called asynchronously or synchronously ? In other words , will/can PerformAnotherCalc ( ) be called before DoLongTaskAsync ( ) has finished ? Subsequently , can the DoStuffAsync ( ) method return before execution of DoLongAsyncTask ( ) has completed ? public static void Run ( ) { DoStuffAsync ( ) ; } public static async Task DoStuffAsync ( ) { PerformCalc ( ) ; await DoLongTaskAsync ( ) ; PerformAnotherCalc ( ) ; }",Are awaits in async method called without await still asynchronous ? "C_sharp : I am trying to write an app , that will be scheduled to autodownload one page from a Sharepoint server every hour . It is an xml file . Everything works so far , except I do not like storing the password needed to connect to Sharepoint in plaintext in my app . Sample code here : Is there a way how to make it harder to read my password if someone got the executabe file from my server and disassembled it e.g . with Reflector ? I have found this : How to store passwords in Winforms application ? but I did not really figure out how to use it in my app . WebClient client = new WebClient ( ) ; String username = `` myusername '' ; String password = `` mypassword '' String filename = `` C : \\Temp\\ '' + DateTime.Now.ToString ( `` yyyyMMddHHmmssffff '' ) + `` .xml '' ; client.Credentials = new System.Net.NetworkCredential ( username , password ) ; string credentials = Convert.ToBase64String ( Encoding.ASCII.GetBytes ( username + `` : '' + password ) ) ; client.DownloadFile ( `` myurl '' , filename ) ;",C # How to store password in application C_sharp : This will throw a null reference exception when InnerException is null . but this wo n't : Both of the above build fine . I ca n't figure out what the former is trying to do that would cause it to evaluate e.InnerException.Message . Why are n't they equivalent ? String s = `` inner exception : `` + e.InnerException == null ? `` None '' : e.InnerException.Message ; String s = `` inner exception : `` + ( e.InnerException == null ? `` None '' : e.InnerException.Message ) ;,Why does this throw a null reference exception ? C_sharp : I have a big modelNow on Post ActionResult Edit ( somemodel SomeModel ) I want to check if anything has been changed by user with respect to original model values in database . Using If Else makes for a lot of messy code . Is there anyway to check if something was altered by the user and if possible what field was altered by user ? public class SomeModel { public int Id { get ; set ; } ... ..A lot ( 24 ) of Fields here ... .. },How to check a change in a Model Object fields without checking individual fields in MVC ? "C_sharp : I am trying to return status codes in the following way now this is not supported in MVC6 , which sucks because using IActionResult seems really silly to me , and way less intuitive.I have found the following posts one and two.the first leads to a broken link , and the second applies to an MVC application.I did realize that I need to create a middleware to address this issue , but I am not sure where to start , and since this is pretty useful stuff , I would expect there to be some open source solution I could use or maybe a code snippet.For the record , I am using ASP.net 5 rc1 update 1 MVC 6 throw new HttpResponseException ( new HttpResponseMessage ( HttpStatusCode.Unauthorized ) { ReasonPhrase = `` invalid username/password '' } ) ;",MVC 6 HttpResponseException "C_sharp : I am making an instructional video for C # 4.0 for beginning programmers.For every topic I introduce I include a practical example which the student could actually use , for instance , for the improved COM Interop functionality , I show how to create an Excel file and fill it with values from code.For named and option parameters I show how you can create a logging method with 5 parameters but do n't have to pass any if you do n't want since they all have default values . So they see how calling methods is easier with this feature.I would also like to introduce tuples as well if I can , but it seems that all the `` practical examples '' ( as in this question : Practical example where Tuple can be used in .Net 4.0 ? ) are very advanced . The learners that use the video learn OOP , LINQ , using generics , etc . but e.g . functional programming or `` solving Problem 11 of Project Euler '' are beyond the scope of this video.Can anyone think of an example where tuples would actually be useful to a beginning programmer or some example where they could at least understand how they could be used by and advanced programmer ? Their mechanics are quite straight-forward for a beginning programmer to grasp , I would just like to find an example so that the learner could actually use them for a practical reason . Any ideas ? Here 's what I have so far , but it is just dry mechanics without any functionality : using System ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { //two ways to define them var customer = new Tuple < int , string , string > ( 23 , `` Sam '' , `` Smith '' ) ; var customer2 = Tuple.Create < int , string , string > ( 34 , `` James '' , `` Allard '' ) ; //with type inference , more concise ( only available with the Create keyword ) var customer3 = Tuple.Create ( 23 , `` John '' , `` Hoopes '' ) ; //you can go up to eight , then you have to send in another tuple var customer4 = Tuple.Create ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , Tuple.Create ( 8 , 9 , 10 ) ) ; Console.WriteLine ( customer.Item1 ) ; Console.WriteLine ( customer2.Item2 ) ; Console.WriteLine ( customer3.Item3 ) ; Console.WriteLine ( customer4.Rest.Item1.Item3 ) ; Console.ReadLine ( ) ; } } }",Are there any practical examples of tuples for beginning programmers ? "C_sharp : I am working on a project where we have several attributes in AssemblyInfo.cs , that are being multicast to methods of a particular class.What I do n't like about this , is that it puts a piece of logic into AssemblyInfo ( Info , mind you ! ) , which for starters should not contain any logic at all . The worst part of it , is that the actual MyClass.cs does not have the attribute anywhere in the file , and it is completely unclear that methods of this class might have them . From my perspective it greatly hurts readability of the code ( not to mention that overuse of PostSharp can make debugging a nightmare ) .Especially when you have multiple multicast attributes.What is the best practice here ? Is anyone out there is using PostSharp attributes like this ? [ assembly : Repeatable ( AspectPriority = 2 , AttributeTargetAssemblies = `` MyNamespace '' , AttributeTargetTypes = `` MyNamespace.MyClass '' , AttributeTargetMemberAttributes = MulticastAttributes.Public , AttributeTargetMembers = `` *Impl '' , Prefix = `` Cls '' ) ]",Assembly wide multicast attributes . Are they evil ? "C_sharp : I 'm having problems having my visual studio template wizard 's gui showing up . I followed these steps : http : //msdn.microsoft.com/en-us/library/ms185301.aspxHere 's what I did:1 ) Generated a C # class library ( .dll ) with the following files : UserInputForm.cs2 ) Added a user input form with a editbox and a combobox with code UserInputForm.cs3 ) generated a public/private strong key and registered the assembly from the `` signing '' tab in the property page4 ) Release-generated the dll5 ) registered it with gacutil /i mydllname.dll , no errors6 ) Created a C++ console project template with just one file:7 ) Exported as a template project ( not item ) with checkbox on `` import automatically into vs '' . Modified inside the zip file the .vstemplate file like this : Unfortunately when I try to create a new template project the UI is not displayed at all . The project is just opened and there 's no substitution of the $ custommessage $ parameter.Why ca n't I show my wizard 's GUI ? Additionally : is there any way to debug why the assembly is n't being loaded ? ? using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace myprojectvstemplate { public partial class UserInputForm : Form { private string customMessage ; public UserInputForm ( ) { InitializeComponent ( ) ; MessageBox.Show ( `` here , calling ui '' ) ; } public string get_CustomMessage ( ) { return customMessage ; } private void button1_Click ( object sender , EventArgs e ) { customMessage = textBox1.Text ; this.Dispose ( ) ; } } } using System ; using System.Collections.Generic ; using Microsoft.VisualStudio.TemplateWizard ; using System.Windows.Forms ; using EnvDTE ; namespace myprojectvstemplate { public class IWizardImplementation : IWizard { private UserInputForm inputForm ; private string customMessage ; // This method is called before opening any item that // has the OpenInEditor attribute . public void BeforeOpeningFile ( ProjectItem projectItem ) { } public void ProjectFinishedGenerating ( Project project ) { } // This method is only called for item templates , // not for project templates . public void ProjectItemFinishedGenerating ( ProjectItem projectItem ) { } // This method is called after the project is created . public void RunFinished ( ) { } public void RunStarted ( object automationObject , Dictionary < string , string > replacementsDictionary , WizardRunKind runKind , object [ ] customParams ) { try { // Display a form to the user . The form collects // input for the custom message . inputForm = new UserInputForm ( ) ; inputForm.ShowDialog ( ) ; customMessage = inputForm.get_CustomMessage ( ) ; // Add custom parameters . replacementsDictionary.Add ( `` $ custommessage $ '' , customMessage ) ; } catch ( Exception ex ) { MessageBox.Show ( ex.ToString ( ) ) ; } } // This method is only called for item templates , // not for project templates . public bool ShouldAddProjectItem ( string filePath ) { return true ; } } } # include < iostream > using namespace std ; int main ( int argc , char** argv ) { cout < < `` Hi hello world : '' < < `` $ custommessage $ '' ; return 0 ; } < VSTemplate Version= '' 3.0.0 '' xmlns= '' http : //schemas.microsoft.com/developer/vstemplate/2005 '' Type= '' Project '' > < TemplateData > < Name > myproject_project < /Name > < Description > & lt ; No description available & gt ; < /Description > < ProjectType > VC < /ProjectType > < ProjectSubType > < /ProjectSubType > < SortOrder > 1000 < /SortOrder > < CreateNewFolder > true < /CreateNewFolder > < DefaultName > myproject_project < /DefaultName > < ProvideDefaultName > true < /ProvideDefaultName > < LocationField > Enabled < /LocationField > < EnableLocationBrowseButton > true < /EnableLocationBrowseButton > < Icon > __TemplateIcon.ico < /Icon > < /TemplateData > < TemplateContent > < Project TargetFileName= '' myproject_project.vcxproj '' File= '' myproject_project.vcxproj '' ReplaceParameters= '' true '' > < ProjectItem ReplaceParameters= '' false '' TargetFileName= '' $ projectname $ .vcxproj.filters '' > myproject_project.vcxproj.filters < /ProjectItem > < ProjectItem ReplaceParameters= '' true '' TargetFileName= '' myproject_project.cpp '' > myproject_project.cpp < /ProjectItem > < ProjectItem ReplaceParameters= '' false '' TargetFileName= '' ReadMe.txt '' > ReadMe.txt < /ProjectItem > < /Project > < /TemplateContent > < WizardExtension > < Assembly > myprojectvstemplate , Version=1.0.0.0 , Culture=Neutral , PublicKeyToken=a0a3d031ed112d61 < /Assembly > < FullClassName > myprojectvstemplate.IWizardImplementation < /FullClassName > < /WizardExtension > < /VSTemplate >",VS2012 template wizard - GUI not showing "C_sharp : Hello fellow programmersI 'm implementing a download feature in an app using Xamarin ( iOS ) , to get a progress on the files it is downloading.The code I use is various examples from all around the web , showing the same principal , with the biggest difference in coding style . They all use the same ReadAsync and WriteAsync functions on System.IO.File , with a byte-array as buffer.But no matter what example I turn to , it results in the pictures getting different artifacts on them , like this : ( Original / Downloaded ) I ca n't seem to find any reason why this happens.I 've tried out different things to see what could trigger this . I found that changing the buffer to a larger size ( say 10240 ) results in more artifacts , and a smaller buffer ( say 1024 ) results in less artifacts.When debugging different things , I found a `` way '' to `` avoid '' this from happening , but that includes adding a Task Delay right after the WriteAsync just finished , for 20 milliseconds ( commented out in the code ) - Not a solution I wan na go with , but tells the issue may lay in the usage of the two streams ( in witch my knowledge is 'basic usage only ' ) .I also tried to use the non-async methods , but gives the same result.Hope someone can tell me what I did wrong here , and why.Thanks in advance public async Task < bool > MakeDownloadRequestAsync ( string url , string destination , Action < string , long , long , float > progress = null ) { if ( _downloadHttpClient == null ) { _downloadHttpClient = new HttpClient ( new NativeMessageHandler ( ) ) ; } bool finished = false ; try { var result = await _downloadHttpClient.GetAsync ( url , HttpCompletionOption.ResponseHeadersRead ) ; long receivedBytes = 0 ; long totalBytes = result.Content.Headers.ContentLength.HasValue ? result.Content.Headers.ContentLength.Value : 0 ; System.Diagnostics.Debug.WriteLine ( `` Started download file : { 0 } '' , url ) ; using ( var stream = await _downloadHttpClient.GetStreamAsync ( url ) ) { byte [ ] buffer = new byte [ 4096 ] ; var filename = Path.GetFileName ( url ) ; var writeStream = _fileStore.OpenWrite ( Path.Combine ( destination , filename ) ) ; while ( true ) { int bytesRead = await stream.ReadAsync ( buffer , 0 , buffer.Length ) ; if ( bytesRead == 0 ) { finished = true ; System.Diagnostics.Debug.WriteLine ( `` Finished downloading file : { 0 } '' , url ) ; break ; } await writeStream.WriteAsync ( buffer , 0 , buffer.Length ) ; //Task.Delay ( 20 ) ; receivedBytes += bytesRead ; if ( progress ! = null ) { progress.Invoke ( url , receivedBytes , totalBytes , ( float ) receivedBytes/ ( float ) totalBytes ) ; } } writeStream.Dispose ( ) ; stream.Dispose ( ) ; } } catch ( Exception e ) { System.Diagnostics.Debug.WriteLine ( e ) ; } return finished ; }",Corrupted images when using Read and Write streams to save files C_sharp : I am trying to run intellitest on x64 project ( for that matter i even tried to create simple 64x project ) but for some reason all i get in intellitest output is public class Program { public static void Main ( string [ ] args ) { if ( args == null ) throw new Exception ( `` test '' ) ; } } saving all filesbuilding projectLaunching explorationstarting ... preparing monitored process for ' C : \Users\User\Documents\Visual Studio 2012\Projects\Unitest\ConsoleApplication9\bin\Debug\ConsoleApplication9.exe'failed to prepare process for assembly ' C : \Users\User\Documents\Visual Studio 2012\Projects\Unitest\ConsoleApplication9\bin\Debug\ConsoleApplication9.exe'monitored process exited with error while loading assembly ( -1006 - 0xfffffc12 ) finished,Visual studio 2015 Intellitest not working on 64bit projects "C_sharp : I 'm adding a custom endpoint behaviour to my WCF service with a class extended from BehaviorExtensionElement to initialise it . In my web.config , I add the following to register the behaviour extension : This works absolutely fine , but I have to specify the version of the assembly to get it to load . If I change the assembly reference to just MyNamespace.MyBehaviorExtensionElement , MyAssembly without the version/culture/token then the service fails to launch with the error : Description : An error occurred during the processing of a configuration file required to service this request . Please review the specific error details below and modify your configuration file appropriately . Parser Error Message : An error occurred creating the configuration section handler for system.serviceModel/behaviors : Extension element 'logBehavior ' can not be added to this element . Verify that the extension is registered in the extension collection at system.serviceModel/extensions/behaviorExtensions . Parameter name : elementThe final portion of my assembly version will change frequently as part of my build process . How can I avoid having to keep updating the web.config with the new version number every time the build version increments ( which could be hundreds of times ) ? < system.serviceModel > < services > < service name= '' Service.MyService '' > < endpoint address= '' '' behaviorConfiguration= '' endpointBehavior '' binding= '' basicHttpBinding '' contract= '' Contracts.IMyService '' / > < /service > < /services > < behaviors > < endpointBehaviors > < behavior name= '' endpointBehavior '' > < logBehavior / > < /behavior > < /endpointBehaviors > < /behaviors > < extensions > < behaviorExtensions > < add name= '' logBehavior '' type= '' MyNamespace.MyBehaviorExtensionElement , MyAssembly , Version=0.0.0.1 , Culture=neutral , PublicKeyToken=null '' / > < /behaviorExtensions > < /extensions > < /system.serviceModel >",How Can I Avoid Adding Assembly Version In web.config ? "C_sharp : I have a C # console project that references a C # class library project in the same solution . When using the VS2010 Profiler ( launched with ALT-F2 ) , I can see timing for methods in both the console project and class library project , but the source code for the class library project is unavailable . Instead , I receive the error message : `` Source code not available . You may not have the appropriate symbol paths . `` It looks like symbols for the class library project were loaded : Also , Tools / Options / Debugger / Symbols says it 's configured to automatically load symbols for all modules except excluded , and the excluded list is empty.What else can I check or do to resolve this ? Loaded symbols for C : \ ... \MyApp\MyAppConsole\bin\Debug\MyAppConsoleApp.exe.Loaded symbols for C : \ ... \MyApp\MyAppConsole\bin\Debug\MyAppClassLib.dll .",VS2010 Profiler Can not Locate Symbols "C_sharp : When starting multiple threads , the id parameter I 'm parsing is sometimes wrong . Here is my startup : And my thread function : The output of this code is : Where in my mind , this code should create every thread with a unique id instead of duplicates as seen above.Compiler info : Platform target : x64Target Framework : .NET Framework 4.5 for ( int i = 0 ; i < _threadCount ; i++ ) { Thread thread = new Thread ( ( ) = > WorkerThread ( i ) ) ; thread.Start ( ) ; _threads.Add ( thread ) ; } private void WorkerThread ( int id ) { Console.WriteLine ( `` [ { 0 } ] Thread started { 1 } '' , DateTime.Now.ToLongTimeString ( ) , id ) ; } [ 19:10:54 ] Thread start 3 [ 19:10:54 ] Thread start 9 [ 19:10:54 ] Thread start 4 [ 19:10:54 ] Thread start 12 [ 19:10:54 ] Thread start 11 [ 19:10:54 ] Thread start 3 [ 19:10:54 ] Thread start 12 [ 19:10:54 ] Thread start 6 [ 19:10:54 ] Thread start 9 [ 19:10:54 ] Thread start 6 [ 19:10:54 ] Thread start 13 [ 19:10:54 ] Thread start 2 [ 19:10:54 ] Thread start 15 [ 19:10:54 ] Thread start 9 [ 19:10:54 ] Thread start 15",Thread parameters being changed "C_sharp : I have an application with multiple usercontrols that are used within certain windows . One of these usercontrols defines whether all other usercontrols in this window should allow editing , hence setting the IsEnabled property to False for all CheckBoxes , ComboBoxes and Buttons . However , TextBoxes should allow to copying their text , hence should not be disabled , but only read-only.I tried traversing the LogicalTree , but some self-built usercontrol does not have any property to disable them , but the controls contained within this usercontrol are only buttons and textboxes . That 's why I tried applying a style to all changable elements ( CheckBox , ComboBox , Button and TextBox ) , but it wo n't work.In the usercontrol 's Ressources section I definded some styles : And in CodeBehind , after checking the condition , I tried the following : But nothing happened . What am I doing wrong ? Should I be doing it differently ? =EDIT 1==================================================================I now tried the following , XAML : CodeBehind : Suprisingly , even though the IsEnabled property is only set for ComboBox , everything is disabled . And if I only set the TextBox.IsReadOnly property nothing happens . Could someone explain this ? =EDIT 2==================================================================I now also tried using a converter : ( XAML ) ( Converter ) But again , everything is just disabled ( or nothing happens if you use the variant commented out ) .I got it working traversing the visual tree : But I also would like to be able to later reset the changes to the original state . And that would mean I 'd have to save all changes , which makes this far to complicated than it should be . I 'm out of ideas . < Style TargetType= '' Control '' x : Key= '' disabledStyle '' > < Setter Property= '' IsEnabled '' Value= '' False '' / > < /Style > < Style TargetType= '' TextBox '' x : Key= '' readOnlyStyle '' > < Setter Property= '' IsReadOnly '' Value= '' True '' / > < /Style > # windowOwner is the root window containing this usercontrolfor control in [ Button , ComboBox , CheckBox ] : if self.windowOwner.Resources.Contains ( control ) : self.windowOwner.Resources.Remove ( control ) self.windowOwner.Resources.Add ( control , self.Resources [ 'disabledStyle ' ] ) if self.windowOwner.Resources.Contains ( TextBox ) : self.windowOwner.Resources.Remove ( TextBox ) self.windowOwner.Resources.Add ( TextBox , self.Resources [ 'readOnlyStyle ' ] ) < Style x : Key= '' disabledStyle '' > < ! -- < Setter Property= '' Button.IsEnabled '' Value= '' False '' / > < Setter Property= '' CheckBox.IsEnabled '' Value= '' False '' / > -- > < Setter Property= '' ComboBox.IsEnabled '' Value= '' False '' / > < Setter Property= '' TextBox.IsReadOnly '' Value= '' True '' / > < /Style > self.windowOwner.Style = self.Resources [ 'disabledStyle ' ] < Style TargetType= '' Control '' x : Key= '' disabledStyle '' > < Setter Property= '' IsEnabled '' Value= '' False '' / > < ! -- < Setter Property= '' Button.IsEnabled '' Value= '' False '' / > < Setter Property= '' CheckBox.IsEnabled '' Value= '' False '' / > < Setter Property= '' ComboBox.IsEnabled '' Value= '' False '' / > -- > < Style.Triggers > < DataTrigger Binding= '' { Binding RelativeSource= { RelativeSource Self } , Converter= { StaticResource typeConverter } } '' Value= '' True '' > < Setter Property= '' IsEnabled '' Value= '' True '' / > < Setter Property= '' TextBox.IsReadOnly '' Value= '' True '' / > < /DataTrigger > < /Style.Triggers > < /Style > public class TypeConverter : IValueConverter { public object Convert ( object value , Type targetType , object parameter , CultureInfo culture ) { bool res = value.GetType ( ) == typeof ( TextBox ) ; return res ; } public object ConvertBack ( object value , Type targetType , object parameter , CultureInfo culture ) { // Do n't need any convert back return null ; } } visited = set ( ) def disableControls ( control ) : visited.add ( control ) try : for childNumber in xrange ( VisualTreeHelper.GetChildrenCount ( control ) ) : child = VisualTreeHelper.GetChild ( control , childNumber ) if hasattr ( child , 'Content ' ) and child.Content not in visited : disableControls ( child.Content ) if type ( child ) in [ Button , ComboBox , CheckBox ] : child.IsEnabled = False elif type ( child ) == TextBox : child.IsReadOnly = True elif child not in visited : disableControls ( child ) except : passdisableControls ( self.windowOwner )",Set style for certain controls within window from contained usercontrol "C_sharp : I have a more general question regarding Unity C # and the brand new Firebase SDK . I 've looked through all of the new documentation and have n't seen an answer to this yet . If you retrieve data from the database below , it does n't allow you to execute methods like Instantiate inside this function because it is not happening on the main thread . How would you go about doing this ? TLDR I want to know how to execute game functions after or while retrieving stuff from Firebase . FirebaseDatabase.DefaultInstance .GetReference ( `` Scenes '' ) .OrderByChild ( `` order '' ) .ValueChanged += ( object sender2 , ValueChangedEventArgs e2 ) = > { if ( e2.DatabaseError ! = null ) { Debug.LogError ( e2.DatabaseError.Message ) ; } scenes = asset.text.Split ( '\n ' ) ; return ; } if ( e2.Snapshot ! = null & & e2.Snapshot.ChildrenCount > 0 ) { sceneCollection.Clear ( ) ; foreach ( var childSnapshot in e2.Snapshot.Children ) { var sceneName = childSnapshot.Child ( `` name '' ) .Value.ToString ( ) ; sceneCollection.Add ( new SceneItem ( sceneName , 0 ) ) ; // I WANTED TO INSTANTIATE SOMTHING HERE } } } ;",Regarding the new Firebase SDK for Unity and Threading Tasks "C_sharp : I see that CancellationToken is a structhttps : //docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken ? view=netframework-4.7.1If I pass a struct to a new function by value , it should n't be modified in the caller . So if i 'm passing a CancellationTokenSource ( by value ) , then I call cts.cancel ( ) , how does the method that has a copy of that token is notified that it has been canceled ? Should n't it work only if we pass by reference ? For example : public static void Main ( ) { var cts = new CancellationTokenSource ( ) ; SomeCancellableOperation ( cts.Token ) ; cts.cancel ( ) ; } public void SomeCancellableOperation ( CancellationToken token ) { ... token.ThrowIfCancellationRequested ( ) ; ... }","If CancellationToken is a struct and is passed by Value , how is it updated ?" "C_sharp : HiI was wondering if there is any difference between initializing object like thisand initializaing object like thisI was also wondering what is the name of this kind of initialization MyClass calass = new MyClass ( ) { firstProperty = `` text '' , secondProperty = `` text '' } MyClass calass = new MyClass // no brackets { firstProperty = `` text '' , secondProperty = `` text '' }",Different kinds of object initialization "C_sharp : I am using this command to list available voices I get only 4 different voices ( Hedda , Hazel , David and Zira ) yet windows itself shows many more speakers.Therefore I only get the `` -Desktop '' -voices . How do I access the other speakers via c # ? private static SpeechSynthesizer sprecher ; ... sprecher = new SpeechSynthesizer ( ) ; ... private static List < VoiceInfo > GetInstalledVoices ( ) { var listOfVoiceInfo = from voice in sprecher.GetInstalledVoices ( ) select voice.VoiceInfo ; return listOfVoiceInfo.ToList < VoiceInfo > ( ) ; }",How to use all voices available ? "C_sharp : I have a client for a web service that I have developed using a Visual Studio service reference via WSDL . It is configured to sign requests with a certificate and can send requests to the service fine , however the service replies with a 400 - Bad Request error , as there is an extra signature in addition to the one I want , with multiple < Reference > tags , which uses HMAC-SHA1 as its signature method . The HMAC-SHA1 is unsupported by the web service and as such the request is rejected . However , I do n't even want or need this other signature , and I am unsure of where it is coming from . The following is my binding configuration : I also put ProtectionLevel = System.Net.Security.ProtectionLevel.Sign as part of the ServiceContractAttribute.Which part of my configuration is causing the second signature ? How can I change the configuration so that I have one signature in my requests ? EDIT : Below is the Request that is sent . In order to highlight the undesirable part I have split it into sections but in reality it is all contiguous.Beginning of part I do n't wantEnd of part I do n't wantEDIT 2 : After some digging and reading I now understand that the two signatures are signatures for the body and the header . I only want to sign the body . I 've changed the title accordingly . < customBinding > < binding name= '' mainBinding '' > < security authenticationMode= '' MutualCertificate '' allowSerializedSigningTokenOnReply= '' true '' requireDerivedKeys= '' false '' requireSignatureConfirmation= '' false '' / > < httpsTransport / > < /binding > < /customBinding > < s : Envelope xmlns : s= '' http : //www.w3.org/2003/05/soap-envelope '' xmlns : a= '' http : //www.w3.org/2005/08/addressing '' xmlns : u= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd '' > < s : Header > < a : Action s : mustUnderstand= '' 1 '' u : Id= '' _1 '' > [ removed ] < /a : Action > < a : MessageID u : Id= '' _2 '' > [ removed ] < /a : MessageID > < a : ReplyTo u : Id= '' _3 '' > < a : Address > [ removed ] < /a : Address > < /a : ReplyTo > < a : To s : mustUnderstand= '' 1 '' u : Id= '' _4 '' > [ removed ] < /a : To > < o : Security s : mustUnderstand= '' 1 '' xmlns : o= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd '' > < u : Timestamp u : Id= '' [ removed ] '' > < u : Created > 2017-05-11T08:59:25.681Z < /u : Created > < u : Expires > 2017-05-11T09:04:25.681Z < /u : Expires > < /u : Timestamp > < e : EncryptedKey Id= '' [ removed ] '' xmlns : e= '' http : //www.w3.org/2001/04/xmlenc # '' > [ removed ] < /e : EncryptedKey > < o : BinarySecurityToken u : Id= '' [ removed ] '' ValueType= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0 # X509v3 '' > [ removed ] < /o : BinarySecurityToken > < Signature Id= '' _0 '' xmlns= '' http : //www.w3.org/2000/09/xmldsig # '' > < SignedInfo > < CanonicalizationMethod Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < SignatureMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # hmac-sha1 '' / > < Reference URI= '' # _1 '' > < Transforms > < Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /Transforms > < DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < DigestValue > [ removed ] < /DigestValue > < /Reference > < Reference URI= '' # _2 '' > < Transforms > < Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /Transforms > < DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < DigestValue > [ removed ] < /DigestValue > < /Reference > < Reference URI= '' # _3 '' > < Transforms > < Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /Transforms > < DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < DigestValue > [ removed ] < /DigestValue > < /Reference > < Reference URI= '' # _4 '' > < Transforms > < Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /Transforms > < DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < DigestValue > [ removed ] < /DigestValue > < /Reference > < Reference URI= '' [ removed ] '' > < Transforms > < Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /Transforms > < DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < DigestValue > [ removed ] < /DigestValue > < /Reference > < /SignedInfo > < SignatureValue > [ removed ] < /SignatureValue > < KeyInfo > < o : SecurityTokenReference > < o : Reference URI= '' [ removed ] '' / > < /o : SecurityTokenReference > < /KeyInfo > < /Signature > < Signature xmlns= '' http : //www.w3.org/2000/09/xmldsig # '' > < SignedInfo > < CanonicalizationMethod Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < SignatureMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # rsa-sha1 '' / > < Reference URI= '' # _0 '' > < Transforms > < Transform Algorithm= '' http : //www.w3.org/2001/10/xml-exc-c14n # '' / > < /Transforms > < DigestMethod Algorithm= '' http : //www.w3.org/2000/09/xmldsig # sha1 '' / > < DigestValue > [ removed ] < /DigestValue > < /Reference > < /SignedInfo > < SignatureValue > [ removed ] < /SignatureValue > < KeyInfo > < o : SecurityTokenReference > < o : Reference URI= '' [ removed ] '' / > < /o : SecurityTokenReference > < /KeyInfo > < /Signature > < /o : Security > < /s : Header > < s : Body > [ removed ] < /s : Body > < /s : Envelope >",SOAP service client generated with WSDL configure signing body only "C_sharp : I use NodaTime to do time zone conversions in ical.net , because it performs much better than the previous implementation which tried to use the VTIMEZONE element to handle time changes and time zone conversions.Under the hood , this method is pretty important for performance : it drops the test suite runtime from about 6 seconds to around 2.5.The .NET Core implementation of NodaTime does not have Bcl as a DateTimeZoneProvider . ( It still has Tzdb and Serialization . ) I poked around in the NodaTime source a bit , but I was n't sure what the replacement was meant to be , if any.What should we be using for BCL time zone lookups in the .NET Core port of NodaTime ? public static DateTimeZone GetZone ( string tzId ) { // IANA lookup attempt zone = DateTimeZoneProviders.Bcl.GetZoneOrNull ( tzId ) ; if ( zone ! = null ) { return zone ; } // Serialization lookup attempt // Some other tricks to find a reasonable time zone , etc . }",Where is the BCL DateTimeZoneProvider in the .NET Core implementation of NodaTime ? "C_sharp : I 've got a small hierarchy of objects that in general gets constructed from data in a Stream , but for some particular subclasses , can be synthesized from a simpler argument list . In chaining the constructors from the subclasses , I 'm running into an issue with ensuring the disposal of the synthesized stream that the base class constructor needs . Its not escaped me that the use of IDisposable objects this way is possibly just dirty pool ( plz advise ? ) for reasons I 've not considered , but , this issue aside , it seems fairly straightforward ( and good encapsulation ) .Codes : I realize that not disposing of a MemoryStream is not exactly a world-stopping case of bad CLR citizenship , but it still gives me the heebie-jeebies ( not to mention that I may not always be using a MemoryStream for other subtypes ) . It 's not in scope , so I ca n't explicitly Dispose ( ) it later in the constructor , and adding a using statement in GenerateRaw ( ) is self-defeating since I need the stream returned.Is there a better way to do this ? Preemptive strikes : yes , the properties calculated in the Node constructor should be part of the base class , and should not be calculated by ( or accessible in ) the subclassesI wo n't require that a stream be passed into CompositeNode ( its format should be irrelevant to the caller ) The previous iteration had the value calculation in the base class as a separate protected method , which I then just called at the end of each subtype constructor , moved the body of GenerateRaw ( ) into a using statement in the body of the CompositeNode constructor . But the repetition of requiring that call for each constructor and not being able to guarantee that it be run for every subtype ever ( a Node is not a Node , semantically , without these properties initialized ) gave me heebie-jeebies far worse than the ( potential ) resource leak here does . abstract class Node { protected Node ( Stream raw ) { // calculate/generate some base class properties } } class FilesystemNode : Node { public FilesystemNode ( FileStream fs ) : base ( fs ) { // all good here ; disposing of fs not our responsibility } } class CompositeNode : Node { public CompositeNode ( IEnumerable some_stuff ) : base ( GenerateRaw ( some_stuff ) ) { // rogue stream from GenerateRaw now loose in the wild ! } static Stream GenerateRaw ( IEnumerable some_stuff ) { var content = new MemoryStream ( ) ; // molest elements of some_stuff into proper format , write to stream content.Seek ( 0 , SeekOrigin.Begin ) ; return content ; } }",Passing IDisposable objects through constructor chains "C_sharp : I have a multi-project Visual Studio solution targeting .Net 4.5.2 . In one of the projects ( a WPF application ) , I 've used nuget to add the System.Reactive version 3.0.1000.0 package followed by the ReactiveUI 7.0.0.0 package.In another project which is a class library used by the WPF application , I 've simply added the System.Reactive version 3.0.1000.0 package.The ReactiveUI package appears to depend on an old set of reactive packages ( RX-Core2.2.5 etc. ) . I can tell this because the HintPaths in the WPF applicatio project file are pointing to locations such as packages\Rx-Core.2.2.5\lib\net45\System.Reactive.Core.dllWhen I build and run the application I get a FileLoadException since at least one of the projects is attempting to use the wrong dll version . The following is typical ... .I might be able to fix this up by downgrading all System.Reactive packages across the solution to 2.2.5 but this appears to be a very old version ( 2014 ) .Why is ReactiveUI pulling in the dependency on v2.2.5 of System.Reactive ? Is there any way to change this behaviour so that I can use latest version of System.Reactive throughout the solution ? System.IO.FileLoadException occurred HResult=0x80131040 Message=Could not load file or assembly 'System.Reactive.Linq , Version=3.0.1000.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 ' or one of its dependencies . The located assembly 's manifest definition does not match the assembly reference . ( Exception from HRESULT : 0x80131040 )",Why does ReactiveUI have a dependency on an old version of System.Reactive ? "C_sharp : I started to use the method group syntax a couple of years ago based on some suggestion from ReSharper and recently I gave a try to ClrHeapAllocationAnalyzer and it flagged every location where I was using a method group in a lambda with the issue HAA0603 - This will allocate a delegate instance.As I was curious to see if this suggestion was actually useful , I wrote a simple console app for the 2 cases.Code1 : Code2 : Putting a break point on the Console.ReadKey ( ) ; of Code1 shows a memory consumption of ~500MB and on Code2 a consumption of ~800MB . Even if we can argue on whether this test case is good enough to explain something it actually shows a difference.So I decided to have a look at the IL code produced to try to understand the difference between the 2 code.IL Code1 : IL Code2 : I have to admit I am not enough expert in IL code to actually fully understand the difference and that 's why I am raising this thread.As far as I have understood , the actual Select seems to generate more instructions when not done through a method group ( Code1 ) BUT is using some pointer to native functions . Is it reusing the method through the pointer compared to the other case which is always generating a new delegate ? Also I have noticed that the method group IL ( Code2 ) is generating 3 comments linked to the for loop compared to the IL code of Code1.Any help in understanding the difference of allocation would be appreciated . class Program { static void Main ( string [ ] args ) { var temp = args.AsEnumerable ( ) ; for ( int i = 0 ; i < 10_000_000 ; i++ ) { temp = temp.Select ( x = > Foo ( x ) ) ; } Console.ReadKey ( ) ; } private static string Foo ( string x ) { return x ; } } class Program { static void Main ( string [ ] args ) { var temp = args.AsEnumerable ( ) ; for ( int i = 0 ; i < 10_000_000 ; i++ ) { temp = temp.Select ( Foo ) ; } Console.ReadKey ( ) ; } private static string Foo ( string x ) { return x ; } } .method private hidebysig static void Main ( string [ ] args ) cil managed { // Method begins at RVA 0x2050 // Code size 75 ( 0x4b ) .maxstack 3 .entrypoint .locals init ( [ 0 ] class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < string > , [ 1 ] int32 , [ 2 ] bool ) // temp = from x in temp // select Foo ( x ) ; IL_0000 : nop // IEnumerable < string > temp = args.AsEnumerable ( ) ; IL_0001 : ldarg.0 IL_0002 : call class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 0 > [ System.Core ] System.Linq.Enumerable : :AsEnumerable < string > ( class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 0 > ) IL_0007 : stloc.0 // for ( int i = 0 ; i < 10000000 ; i++ ) IL_0008 : ldc.i4.0 IL_0009 : stloc.1 // ( no C # code ) IL_000a : br.s IL_0038 // loop start ( head : IL_0038 ) IL_000c : nop IL_000d : ldloc.0 IL_000e : ldsfld class [ mscorlib ] System.Func ` 2 < string , string > ConsoleApp1.Program/ ' < > c ' : : ' < > 9__0_0 ' IL_0013 : dup IL_0014 : brtrue.s IL_002d IL_0016 : pop IL_0017 : ldsfld class ConsoleApp1.Program/ ' < > c ' ConsoleApp1.Program/ ' < > c ' : : ' < > 9 ' IL_001c : ldftn instance string ConsoleApp1.Program/ ' < > c ' : : ' < Main > b__0_0 ' ( string ) IL_0022 : newobj instance void class [ mscorlib ] System.Func ` 2 < string , string > : :.ctor ( object , native int ) IL_0027 : dup IL_0028 : stsfld class [ mscorlib ] System.Func ` 2 < string , string > ConsoleApp1.Program/ ' < > c ' : : ' < > 9__0_0 ' IL_002d : call class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 1 > [ System.Core ] System.Linq.Enumerable : :Select < string , string > ( class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 0 > , class [ mscorlib ] System.Func ` 2 < ! ! 0 , ! ! 1 > ) IL_0032 : stloc.0 IL_0033 : nop // for ( int i = 0 ; i < 10000000 ; i++ ) IL_0034 : ldloc.1 IL_0035 : ldc.i4.1 IL_0036 : add IL_0037 : stloc.1 // for ( int i = 0 ; i < 10000000 ; i++ ) IL_0038 : ldloc.1 IL_0039 : ldc.i4 10000000 IL_003e : clt IL_0040 : stloc.2 // ( no C # code ) IL_0041 : ldloc.2 IL_0042 : brtrue.s IL_000c // end loop // Console.ReadKey ( ) ; IL_0044 : call valuetype [ mscorlib ] System.ConsoleKeyInfo [ mscorlib ] System.Console : :ReadKey ( ) IL_0049 : pop // ( no C # code ) IL_004a : ret } // end of method Program : :Main .method private hidebysig static void Main ( string [ ] args ) cil managed { // Method begins at RVA 0x2050 // Code size 56 ( 0x38 ) .maxstack 3 .entrypoint .locals init ( [ 0 ] class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < string > , [ 1 ] int32 , [ 2 ] bool ) // ( no C # code ) IL_0000 : nop // IEnumerable < string > temp = args.AsEnumerable ( ) ; IL_0001 : ldarg.0 IL_0002 : call class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 0 > [ System.Core ] System.Linq.Enumerable : :AsEnumerable < string > ( class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 0 > ) IL_0007 : stloc.0 // for ( int i = 0 ; i < 10000000 ; i++ ) IL_0008 : ldc.i4.0 IL_0009 : stloc.1 // ( no C # code ) IL_000a : br.s IL_0025 // loop start ( head : IL_0025 ) IL_000c : nop // temp = temp.Select ( Foo ) ; IL_000d : ldloc.0 IL_000e : ldnull IL_000f : ldftn string ConsoleApp1.Program : :Foo ( string ) IL_0015 : newobj instance void class [ mscorlib ] System.Func ` 2 < string , string > : :.ctor ( object , native int ) IL_001a : call class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 1 > [ System.Core ] System.Linq.Enumerable : :Select < string , string > ( class [ mscorlib ] System.Collections.Generic.IEnumerable ` 1 < ! ! 0 > , class [ mscorlib ] System.Func ` 2 < ! ! 0 , ! ! 1 > ) IL_001f : stloc.0 // ( no C # code ) IL_0020 : nop // for ( int i = 0 ; i < 10000000 ; i++ ) IL_0021 : ldloc.1 IL_0022 : ldc.i4.1 IL_0023 : add IL_0024 : stloc.1 // for ( int i = 0 ; i < 10000000 ; i++ ) IL_0025 : ldloc.1 IL_0026 : ldc.i4 10000000 IL_002b : clt IL_002d : stloc.2 // ( no C # code ) IL_002e : ldloc.2 IL_002f : brtrue.s IL_000c // end loop // Console.ReadKey ( ) ; IL_0031 : call valuetype [ mscorlib ] System.ConsoleKeyInfo [ mscorlib ] System.Console : :ReadKey ( ) IL_0036 : pop // ( no C # code ) IL_0037 : ret } // end of method Program : :Main",Delegate instance allocation with method group compared to "C_sharp : I am creating a multi-project template , that has a few optional projects and solution folders . I have been through quite a few different documentations and code in github to achieve this , but with very little success . I really appreciate if someone could give me some clarity on some of these questions ? Is VSTemplate xml file still relevant ? This blog suggests making changes in the template.json file , however when I check for examples in github , people use VSTemplate to make to create the project , and also SideWaffle plugin still creates the VSTemplate file . If its still relevant , Would like to know how does it differ from the json file ? Using the above VSTemplate I attempted to create a multi project template , using the ProjectCollection tage , when I run the dotnet run command , the template gets executed but the project does not get created . Can we create a multi-project template using template.json file ? Would appreciate if anyone can help me get started . < ProjectTemplateLink ProjectName= '' $ safeprojectname $ .Forms.Plugin.Abstractions '' > Forms.Plugin.Abstractions\Forms.Plugin.Abstractions.vstemplate < /ProjectTemplateLink > < ProjectTemplateLink ProjectName= '' $ safeprojectname $ .Forms.Plugin.iOS '' > Forms.Plugin.iOS\Forms.Plugin.iOS.vstemplate < /ProjectTemplateLink > < ProjectTemplateLink ProjectName= '' $ safeprojectname $ .Forms.Plugin.iOSUnified '' > Forms.Plugin.iOSUnified\Forms.Plugin.iOSUnified.vstemplate < /ProjectTemplateLink > < ProjectTemplateLink ProjectName= '' $ safeprojectname $ .Forms.Plugin.Android '' > Forms.Plugin.Android\Forms.Plugin.Android.vstemplate < /ProjectTemplateLink > < ProjectTemplateLink ProjectName= '' $ safeprojectname $ .Forms.Plugin.WindowsPhone '' > Forms.Plugin.WindowsPhone\Forms.Plugin.WindowsPhone.vstemplate < /ProjectTemplateLink > < /ProjectCollection > `` `",Multi project template for dotnet new "C_sharp : Which CPU information this code is trying to retrieve . This code is part of a larger package . I am not a Python programmer , and I want to convert this code to C # .If you are a Python programmer and knows what this code is doing , it will be a great help for me . from ctypes import c_uint , create_string_buffer , CFUNCTYPE , addressofCPUID = create_string_buffer ( `` \x53\x31\xc0\x40\x0f\xa2\x5b\xc3 '' ) cpuinfo = CFUNCTYPE ( c_uint ) ( addressof ( CPUID ) ) print cpuinfo ( )",What does this line mean in Python ? "C_sharp : I am new to arrays and I want to display the size ( in MB ) of multiple files into a textBox . The paths to the files are in an array.I saw this code in another post to get the size of a file : How can I add all of the file sizes to an int/string and write them into the textBox ? var Files = Directory.GetFiles ( Path , `` * '' + filetype , SearchOption.AllDirectories ) ; long length = new System.IO.FileInfo ( file ) .Length ;",C # Get file size of array with paths "C_sharp : On a Computer with culture Setting `` de-DE '' ( or any other than `` en-US '' ) , I would like to have a RichTextBox with spell checking enabled , with the checked language set to English ( `` en-US '' ) .This enables the spell check , but checks with `` de-DE '' culture , rather than `` en-US '' . The same holds when adding xml : lang= '' en-us '' .However , correctly enables spell checking in English , but also changes the Keyboard layout to `` en-US '' .How can I have the system 's keyboard setting ( in my case `` de-DE '' ) , but the spell checking of the RichTextBox to be English ? ( Potentially relevant : I 'm using .NET Framework 4.5 ) < RichTextBox SpellCheck.IsEnabled= '' True '' Language= '' en-US '' / > < RichTextBox SpellCheck.IsEnabled= '' True '' InputLanguageManager.InputLanguage= '' en-US '' / >",conflicting language settings of WPF richtextbox "C_sharp : When comparing `` Île '' and `` Ile '' , C # does not consider these to be to be the same . For all other accented characters I have come across the comparison works fine.Is there another comparison function I should use ? string.Equals ( `` Île '' , `` Ile '' , StringComparison.InvariantCultureIgnoreCase )",Problem comparing French character Î "C_sharp : I 'm trying to figure out how this would be done in practice , so as not to violate the Open Closed principle.Say I have a class called HttpFileDownloader that has one function that takes a url and downloads a file returning the html as a string . This class implements an IFileDownloader interface which just has the one function . So all over my code I have references to the IFileDownloader interface and I have my IoC container returning an instance of HttpFileDownloader whenever an IFileDownloader is Resolved.Then after some use , it becomes clear that occasionally the server is too busy at the time and an exception is thrown . I decide that to get around this , I 'm going to auto-retry 3 times if I get an exception , and wait 5 seconds in between each retry.So I create HttpFileDownloaderRetrier which has one function that uses HttpFileDownloader in a for loop with max 3 loops , and a 5 second wait between each loop . So that I can test the `` retry '' and `` wait '' abilities of the HttpFileDownloadRetrier I have the HttpFileDownloader dependency injected by having the HttpFileDownloaderRetrier constructor take an IFileDownloader.So now I want all Resolving of IFileDownloader to return the HttpFileDownloaderRetrier . But if I do that , then HttpFileDownloadRetrier 's IFileDownloader dependency will get an instance of itself and not of HttpFileDownloader.So I can see that I could create a new interface for HttpFileDownloader called IFileDownloaderNoRetry , and change HttpFileDownloader to implement that . But that means I 'm changing HttpFileDownloader , which violates Open Closed.Or I could implement a new interface for HttpFileDownloaderRetrier called IFileDownloaderRetrier , and then change all my other code to refer to that instead of IFileDownloader . But again , I 'm now violating Open Closed in all my other code.So what am I missing here ? How do I wrap an existing implementation ( downloading ) with a new layer of implementation ( retrying and waiting ) without changing existing code ? Here 's some code if it helps : public interface IFileDownloader { string Download ( string url ) ; } public class HttpFileDownloader : IFileDownloader { public string Download ( string url ) { //Cut for brevity - downloads file here returns as string return html ; } } public class HttpFileDownloaderRetrier : IFileDownloader { IFileDownloader fileDownloader ; public HttpFileDownloaderRetrier ( IFileDownloader fileDownloader ) { this.fileDownloader = fileDownloader ; } public string Download ( string url ) { Exception lastException = null ; //try 3 shots of pulling a bad URL . And wait 5 seconds after each failed attempt . for ( int i = 0 ; i < 3 ; i++ ) { try { fileDownloader.Download ( url ) ; } catch ( Exception ex ) { lastException = ex ; } Utilities.WaitForXSeconds ( 5 ) ; } throw lastException ; } }","Using IoC and Dependency Injection , how to wrap code with a new layer of implementation without violating the Open-Closed principle ?" "C_sharp : I have a T4 C # file in which I need to reference a constant in a static class . The static class is in the same namespace.Is this possible ? The below is merely an illustration . I need to calculate the actual constant based on existing constants , but there is also a call to an extension method involved . To keep it simple , I am merely illustrating the concept..cs file : . tt file : namespace me { public static class Stat { public const int Const = 1 ; } } ... namespace me { public static int Test { return < # = Stat.Const # > ; } }",T4 reference a const in a static class at compile time C_sharp : Is there a way to write custom refactorings or code transformations for Visual Studio ? An example : I have a codebase with a billion instances of : I would like to transform this into : Everywhere the above pattern appears.Edit : The above is just an example . The point is that I need to do a number of code transformations which are too complex to perform with a text-based search-replace . I wonder if I can hook into the same mechanism underlying the built-in refactorings to write my own code transformations . DbConnection conn = null ; conn = new DbConnection ( ) ; conn.Open ( ) ; ... a number of statements using conn ... conn.Close ( ) ; conn = null ; using ( DbConnection conn = GetConnection ( ) ) { ... statements ... },Write custom refactorings for Visual Studio "C_sharp : I 'm working on a MVC/EF Web Application . In one of the forms I edit a model . The model has an image field ( public byte [ ] BioPhoto ) When I upload an image to that field and save data , ModelState.IsValid is false , because BioPhoto property is null in ModelState . Note that the BioPhoto in model is loaded with image data.I tried to inject the picture to ModelState using below code but still ModelState.IsValid is falseWhat am I doing wrong . Is there any better solution for this issue ? I read couple of answer in SO but could not figure out how to solve my case.This is my modelMy View public ActionResult Edit ( [ Bind ( Include = `` BusinessId , Name , About , Phone , TollFree , FAX , Email , Bio , BioPhoto '' ) ] Business business ) { if ( System.IO.File.Exists ( `` image.jpg '' ) ) { business.BioPhoto = System.IO.File.ReadAllBytes ( `` image.jpg '' ) ; ModelState.SetModelValue ( `` BioPhoto '' , new ValueProviderResult ( business.BioPhoto , `` '' , System.Globalization.CultureInfo.InvariantCulture ) ) ; } if ( ModelState.IsValid ) { db.Entry ( business ) .State = EntityState.Modified ; db.SaveChanges ( ) ; return RedirectToAction ( `` Index '' ) ; } return View ( business ) ; } public class Business { public int BusinessId { get ; set ; } [ Required ] [ StringLength ( 100 ) ] public string Name { get ; set ; } [ Required ] public Address address { get ; set ; } [ Required ] [ StringLength ( 20 ) ] public string Phone { get ; set ; } [ StringLength ( 20 ) ] public string TollFree { get ; set ; } [ StringLength ( 20 ) ] public string FAX { get ; set ; } [ Required ] [ StringLength ( 50 ) ] public string Email { get ; set ; } [ Required ] [ StringLength ( 100 ) ] public string WebSite { get ; set ; } [ Required ] public string About { get ; set ; } [ Required ] public string Bio { get ; set ; } [ Required ] public byte [ ] BioPhoto { get ; set ; } } < div class= '' form-group '' > @ Html.LabelFor ( model = > model.BioPhoto , `` BIO Photo ( Best Size : 350 x 450 ) '' , htmlAttributes : new { @ class = `` control-label col-md-2 '' } ) < div class= '' col-md-10 '' > < form enctype= '' multipart/form-data '' > < div class= '' form-group '' style= '' width:400px '' > < input id= '' BioPhoto '' type= '' file '' multiple class= '' file '' data-overwrite-initial= '' false '' / > < /div > < /form > @ Html.ValidationMessageFor ( model = > model.BioPhoto , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div >",Can not modify ModelState using SetModelValue "C_sharp : I am trying to generate code coverage report using vstest.console.exe . I am also using .runsettings file and passing it as a parameter.Whatever I am trying to do , it generates a coverage report for only moq.dll.I am sharing below the full text of command parameters I am running and also content of .runsettings file . Any idea , where am I doing something wrong ? Command : vstest.console.exe `` C : \Xyz.Tests\bin\Debug\netcoreapp2.0\Xyz.Tests.dll '' /InIsolation /EnableCodeCoverage /settings : CodeCoverage.runsettingsCodeCoverage.runsettings file content : Image of generated code coverage report : < RunSettings > < DataCollectionRunSettings > < DataCollectors > < DataCollector friendlyName= '' Code Coverage '' uri= '' datacollector : //Microsoft/CodeCoverage/2.0 '' assemblyQualifiedName= '' Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector , Microsoft.VisualStudio.TraceCollector , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a '' enabled= '' false '' > < Configuration > < CodeCoverage > < /CodeCoverage > < /Configuration > < /DataCollector > < /DataCollectors > < /DataCollectionRunSettings > < /RunSettings >",vstest.console.exe generate cover for only Moq.dll "C_sharp : Does null have a type ? How is a null value represented internally ? What is happening in the following code ? Edit : The answers so far have been unspecific and too high-level . I understand that a reference type object consists of a pointer on the stack which points to a location on the heap which contains a sync block index , a type handle and the object 's fields . When I set an instance of an object to null , where does the pointer on the stack point to , exactly ? And in the code snippet , is the cast simply used by the C # compiler to decide which overload to call , and there is not really any casting of null going on ? I am looking for an in-depth answer by someone who understands the CLR internals . void Foo ( string bar ) { ... } void Foo ( object bar ) { ... } Foo ( ( string ) null ) ;","In .Net/C # , is null strongly-typed ?" "C_sharp : So getting the objects I need in JS , I did : If I console.log vmopl in the end , I 'll get something likeNow if I try to send this to AJAX this up usingA controller action Should pick vmop up , the controller looks like so : But when I put a breakpoint , I always see vmop as null , even when I pass it to another object ( var temp = vmop ; ) .ViewMethodOfPayment is a simple model class : If I missed any info , or if it 's unclear what I want to do/expect , please leave a comment , I 'll answer as soon as I can ! Thanks for reading ! edit : changed the first block of code ( line : 9 , because I included a code that will bring a JavaScript error ) $ ( '.combine-payment-input ' ) .each ( function ( index , value ) { if ( parseFloat ( value.value ) > 0 ) { if ( methodOfPayment == -1 ) { methodOfPayment = value.dataset.method ; } else { methodOfPayment = 0 ; } vmopl.push ( { id : value.dataset.method , name : $ ( 'label [ for= '' ' + value.id + ' '' ] ' ) .html ( ) , inUse : 'True ' , ammount : value.value } ) ; } } ) ; [ Object { id= '' 2 '' , name= '' Card '' , inUse= '' True '' , ammount= '' 500 '' } , Object { id= '' 1 '' , name= '' Cash '' , inUse= '' True '' , ammount= '' 250 '' } ] $ .get ( '/reports/savebill/ ' + methodOfPayment + ' ? vmop= ' + JSON.stringify ( vmopl ) , function ( data ) { if ( data == 'True ' ) { location.href = '/order/neworder/ ' ; } else { alert ( `` Unsuccessful ! `` ) ; } } ) ; public bool SaveBill ( int id , ViewMethodOfPayment [ ] vmop ) { //lots of code ... } public class ViewMethodOfPayment { public long Id { get ; set ; } public string Name { get ; set ; } public bool InUse { get ; set ; } public double Ammount { get ; set ; } }",Sending an array of objects via AJAX - ASP.NET MVC "C_sharp : I am wondering if anyone can help me , for some time now I have being trying to figure out how to implement custom paging in a OData feed ( v4 ) Web API 2 to feed a power bi feed and having no success.The data is derived from a database first , database and is a combination of 5 tables using joins , which makes it not suitable to use with Entity Framework apart from being really slow with Entity Framework ( 45k of records out of one controller ) . I have tried many different approaches from , setting the total amount of records to trick the framework and padding the paged results with empty members of the list , to the more basic example below . However I still can not the get client ( Power BI ) take the paged results correctly without returning an extremely large amount of records from the controller . Please see a simplified query and code , any help would be extremely welcome as there appears to be no clear examples of how to do this without using Entity Framework.The below code works but I keep having variants of the same problem the framework is doing the paging on the list after it returns , despite whatever I do before thatT-SQL Stored Procedure : The controller which points to a repo which calls the above queryThe paging by the framework is done after this point return response ; . CREATE PROCEDURE [ dbo ] . [ GetOrders ] @ CompanyID int , @ Skip INT , @ Take INTASBEGIN SET NOCOUNT ON ; SELECT *FROM Orders WHERE CompanyID = @ CompanyIDORDER BY t.OrderIDOFFSET @ Skip ROWS FETCH NEXT @ Take ROWS ONLYEND [ EnableQuery ] public async Task < PageResult < Order > > GetOrders ( ODataQueryOptions < Order > queryOptions ) { int CompanyID = User.Identity.GetCompanyID ( ) .TryParseInt ( 0 ) ; ODataQuerySettings settings = new ODataQuerySettings ( ) { PageSize = 100 , } ; int OrderCount = _OrderRepo.GetOrderCount ( CompanyID ) ; int Skip = 0 ; if ( queryOptions.Skip ! = null ) { Skip = queryOptions.Skip.Value ; } IEnumerable < Order > results = await _OrderRepo.GetAll ( CompanyID , Skip , 100 ) ; IQueryable result = queryOptions.ApplyTo ( results.AsQueryable ( ) , settings ) ; Uri uri = Request.ODataProperties ( ) .NextLink ; Request.ODataProperties ( ) .TotalCount = OrderCount ; PageResult < Order > response = new PageResult < Order > ( result as IEnumerable < Order > , uri , Request.ODataProperties ( ) .TotalCount ) ; return response ; }",Custom Paging using a stored procedure with OData feed C # without Entity Framework "C_sharp : I am developing an app I want to add some cool icons . Because I am using the beautiful MahApps library , I want to have a visual on the icons in MahApps.Metro/MahApps.Metro.Resources/Icons.xaml , so I did some string manipulations to grab the x : Key part of each < Canvas x : Key= '' appbar_3d_3ds '' Width= '' 76 '' Height= '' 76 '' Clip= '' F1 M 0,0L 76,0L 76,76L 0,76L 0,0 '' > line . In short , all the string manipulations I did ended up with 1216 copies of the following : Note that each copy of the < control : Tile has the appropriate properties Count , Grid.Row and Grid.Column correctly set.However , I always end up with the Application not responding window message . Now as I said , my motive is just to get a visual on that collection of pretty icons and instead I get a fat application crash . I just want to know if there is a way to display such a huge collection without crashing anybody 's computer ( Note : the system is really low on RAM : one of my test machines that run inside virtualbox ) . < controls : TileTitle= '' appbar_zune '' Count= '' 1215 '' Grid.Row= '' 121 '' Grid.Column= '' 15 '' TiltFactor= '' 2 '' Width= '' 1* '' Height= '' 1* '' VerticalAlignment= '' Stretch '' HorizontalAlignment= '' Stretch '' > < Rectangle Margin= '' 0 '' Fill= '' { Binding RelativeSource= { RelativeSource AncestorType=Button } , Path=Foreground } '' > < Rectangle.OpacityMask > < VisualBrush Stretch= '' Fill '' Visual= '' { StaticResource appbar_zune } '' / > < /Rectangle.OpacityMask > < /Rectangle > < /controls : Tile >",How to draw 1216 canvas elements without hanging application in WPF "C_sharp : I am looking for suggestions as to the best way to design objects for IoCSuppose I have an object ( Service ) that has a dependency to a DataContext which is registered with Ioc.But it also requires a name property , i could design the object like this : The problem is it becomes very complicated to use with Ioc containers as a string object such as name is not easy to register and the usage becomes complicated with the Ioc container : So resolution becomes confusing : Another approach is to design it as follows : The resolution is now easier : The only downsite is specifying the name is no longer required.I would like to hear from DI or IoC experts how they would go about designing this and still stay fairly agnostic to the concrete Ioc container technology.I know that a lot depends on how you want to use this , option 2 would be perfect if name really was optional . But in the case where name is required you could add the validation step at another point in code , but rather go for the design to make Ioc simpler.Thoughts ? class Service { public Service ( IDataContext dataContext , string name ) { this._dataContext = dataContext ; this._name = name } public string Name { get { return _name ; } } } var service = Ioc.Resolve < Service > ( ? ? ) class Service { public Service ( IDataContext dataContext ) { this._dataContext = dataContext ; } public string Name { get ; set ; } } var service = Ioc.Resolve < Service > ( ) ; service.Name = `` Some name '' ;",IoC with value type and object type dependencies "C_sharp : I need to deploy multiple versions of the same C # .NET project . The project output is a COM interop assembly to be used in a native application . The problem I 'm having is that I have to deploy several versions of this assembly side-by-side but whatever I do does n't seem to create different versions . Instead the versions override eachother.I 've tried changing the assembly GUID , tried changing the assembly version numbers , tried regenerating the assembly strong name key , tried changing the assembly title and description . I 'd rather not have to change the GUID 's or names for individual types in the assembly for versioning purposes.How do I ensure these versions do not override eachother and that I can see and deploy them side-by-side ? Thanks in advance ! using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Runtime.InteropServices ; namespace InteropTest { [ Guid ( `` ... '' ) ] [ ClassInterface ( ClassInterfaceType.AutoDual ) ] public class Test { public Test ( ) { } public string Version { get { return `` 1.0 '' ; } } } }",COM interop side-by-side assemblies "C_sharp : I 'm using code examples from this article by Rick Strahl : http : //www.west-wind.com/weblog/posts/324917.aspx to make async calls to a WCF service , which works just great.My problem is this : First call to the WCF Service takes in the vicinity of 20ms , whereas the next takes around 1sec 20ms ( doing exactly the same and receiving the exact same data ) . If I repeat the process the result is the same all the time . Every other call takes one second longer than the first.I 've tried setting the InstanceContextMode on my service : I 've also set timers in the methods being called on the service , and the result is the same every time ( of course some ms differences , but nothing significant ) ( These values - JSON_Took & Set_took - are timers in the code behind methods . So not the total time from client-server-client . It 's simply to illustrate that it 's not a problem with the actual code being timeconsuming ) Any ideas ? Let me know if you need more information. -- -- Interesting Update -- -- I downloaded IE9 RC and also Firefox ( I 've been testing in Chrome ) My results from the different browsers : Firefox : All calls are consistent at approx ~1s 20ms to 1s 30msChrome : Every other call fires at the speed of Firefox , and the rest at 1 second quickerIE9 : All calls are consistent at virtually no time at all ( ~20ms ) Opera : Pretty much the same as IE9 ( ~30ms ) Is this a webkit-issue ? ( I 'm using $ .ajax to call the WCF ) [ ServiceBehavior ( IncludeExceptionDetailInFaults = true , InstanceContextMode = InstanceContextMode.PerSession ) ] [ AspNetCompatibilityRequirements ( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed ) ] public abstract class AjaxPostBack : IAjaxPostBack `` JSON_Took '' : '' 00:00:00.0012939 '' , '' Set_took '' : '' 00:00:00.0000274 ''",Every other call to Async WCF is slow "C_sharp : Take this code for example : One would expect that either one of the following would happen : -rndNumber contains a random integer between 0 and 101-rndNumber contains a random integer between 1 and 100What actually happens though , is that rndNumber contains a random integer between 0 and 100 . Why is this the case ? I understand that the upper limit is exclusive , but then why is the lower limit inclusive ? Why is this not consistent ? Random rnd = new Random ( ) ; int rndNumber = rnd.Next ( 0,101 ) ;","Why is C # 's random lower limit inclusive , but upper limit exclusive ?" "C_sharp : I 've noticed something peculiar about Visual Studio . First , try typing this ( C # ) somewhere in a function : Now , right away it will mark the s in s.Length as an error , saying `` Use of unassigned local variable 's ' '' . On the other hand , try this code : It will compile , and underline the s in private string s with a warning , saying `` Field 'Foo.s ' is never assigned to , and will always have its default value null '' .Now , if VS is that smart and knows that s will always be null , why is it not an error to get its length in the second example ? My original guess was , `` It only gives a compile error if the compiler simply can not complete its job . Since the code technically runs as long as you never call Bar ( ) , it 's only a warning . '' Except that explanation is invalidated by the first example . You could still run the code without error as long as you never call Bar ( ) . So what gives ? Just an oversight , or am I missing something ? class Foo { public void Bar ( ) { string s ; int i = s.Length ; } } class Foo { private string s ; public void Bar ( ) { int i = s.Length ; } }",Visual Studio null reference warning - why no error ? "C_sharp : Is there any way to build a group of attributes ? Before : What I want : Is this possible ? Can I build an attribute that groups others ? [ SuppressMessage ( `` Microsoft.Design '' , `` CA1061 '' ) ] [ SuppressMessage ( `` Microsoft.Usage '' , `` CA1812 '' ) ] [ SuppressMessage ( `` Microsoft.Design '' , `` CA1064 '' ) ] public abstract void Foo ( ) ; [ SpecialStuff ] public abstract void Foo ( ) ;",Groups of C # Attributes "C_sharp : I 've created a menu item for the extension I 'm working on ; however , it is showing up 4 times in the Tools menu instead of just once . Below is what I have , but I have been unable to figure out why the menu item is showing up more than once.VSCT FileTemplatePackPackage.csPackageConstants.csI just ca n't seem to figure out what I might be doing wrong . Any suggestions ? < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < CommandTable xmlns= '' http : //schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' > < Extern href= '' stdidcmd.h '' / > < Extern href= '' vsshlids.h '' / > < Commands package= '' guidTemplatePackPkg '' > < Groups > < Group guid= '' guidTemplatePackCmdSet '' id= '' MyMenuGroup '' priority= '' 0x0600 '' > < Parent guid= '' guidSHLMainMenu '' id= '' IDM_VS_MENU_TOOLS '' / > < /Group > < /Groups > < Buttons > < Button guid= '' guidTemplatePackCmdSet '' id= '' cmdidMyCommand '' priority= '' 0x2000 '' type= '' Button '' > < Parent guid= '' guidSHLMainMenu '' id= '' IDG_VS_CTXT_PROJECT_ADD_REFERENCES '' / > < CommandFlag > DynamicVisibility < /CommandFlag > < CommandFlag > DefaultInvisible < /CommandFlag > < Strings > < CommandName > AddSideWaffleProject < /CommandName > < ButtonText > Add Template Reference ( SideWaffle project ) < /ButtonText > < /Strings > < /Button > < /Buttons > < /Commands > < ! -- SideWaffle Menu Options -- > < Commands package= '' guidMenuOptionsPkg '' > < Groups > < Group guid= '' guidMenuOptionsCmdSet '' id= '' SWMenuGroup '' priority= '' 0x0600 '' > < Parent guid= '' guidSHLMainMenu '' id= '' IDM_VS_MENU_TOOLS '' / > < /Group > < /Groups > < Buttons > < Button guid= '' guidMenuOptionsCmdSet '' id= '' cmdidOpenSWMenu '' priority= '' 0x0100 '' type= '' Button '' > < Parent guid= '' guidMenuOptionsCmdSet '' id= '' SWMenuGroup '' / > < Icon guid= '' guidImages '' id= '' bmpPic1 '' / > < Strings > < ButtonText > SideWaffle Settings < /ButtonText > < /Strings > < /Button > < /Buttons > < Bitmaps > < Bitmap guid= '' guidImages '' href= '' Resources\Images.png '' usedList= '' bmpPic1 , bmpPic2 , bmpPicSearch , bmpPicX , bmpPicArrows '' / > < /Bitmaps > < /Commands > < ! -- End SideWaffle Menu Options -- > < Symbols > < GuidSymbol name= '' guidTemplatePackPkg '' value= '' { e6e2a48e-387d-4af2-9072-86a5276da6d4 } '' / > < GuidSymbol name= '' guidTemplatePackCmdSet '' value= '' { a94bef1a-053e-4066-a851-16e5f6c915f1 } '' > < IDSymbol name= '' MyMenuGroup '' value= '' 0x1020 '' / > < IDSymbol name= '' cmdidMyCommand '' value= '' 0x0100 '' / > < /GuidSymbol > < ! -- SideWaffle Menu Options -- > < GuidSymbol name= '' guidMenuOptionsPkg '' value= '' { ee0cf212-810b-45a1-8c62-e10041913c94 } '' / > < GuidSymbol name= '' guidMenuOptionsCmdSet '' value= '' { c75eac28-63cd-4766-adb1-e655471525ea } '' > < IDSymbol name= '' SWMenuGroup '' value= '' 0x1020 '' / > < IDSymbol name= '' cmdidOpenSWMenu '' value= '' 0x0100 '' / > < /GuidSymbol > < GuidSymbol name= '' guidImages '' value= '' { e2bf6a31-afea-46fb-9397-0c2add3a59d8 } '' > < IDSymbol name= '' bmpPic1 '' value= '' 1 '' / > < IDSymbol name= '' bmpPic2 '' value= '' 2 '' / > < IDSymbol name= '' bmpPicSearch '' value= '' 3 '' / > < IDSymbol name= '' bmpPicX '' value= '' 4 '' / > < IDSymbol name= '' bmpPicArrows '' value= '' 5 '' / > < IDSymbol name= '' bmpPicStrikethrough '' value= '' 6 '' / > < /GuidSymbol > < ! -- End SideWaffle Menu Options -- > < /Symbols > < /CommandTable > using System ; using System.Linq ; using System.Diagnostics ; using System.Globalization ; using System.Runtime.InteropServices ; using System.ComponentModel.Design ; using Microsoft.Win32 ; using Microsoft.VisualStudio ; using Microsoft.VisualStudio.Shell.Interop ; using Microsoft.VisualStudio.OLE.Interop ; using Microsoft.VisualStudio.Shell ; using System.Collections.Generic ; using EnvDTE ; using EnvDTE80 ; using LigerShark.Templates.DynamicBuilder ; using TemplatePack.Tooling ; namespace TemplatePack { [ PackageRegistration ( UseManagedResourcesOnly = true ) ] [ InstalledProductRegistration ( `` # 110 '' , `` # 112 '' , `` 1.0 '' , IconResourceID = 400 ) ] [ ProvideMenuResource ( `` Menus.ctmenu '' , 1 ) ] [ Guid ( GuidList.guidTemplatePackPkgString ) ] [ ProvideAutoLoad ( UIContextGuids80.SolutionExists ) ] public sealed class TemplatePackPackage : Package { private DTE2 _dte ; protected override void Initialize ( ) { base.Initialize ( ) ; _dte = GetService ( typeof ( DTE ) ) as DTE2 ; OleMenuCommandService mcs = GetService ( typeof ( IMenuCommandService ) ) as OleMenuCommandService ; if ( null ! = mcs ) { CommandID cmdId = new CommandID ( GuidList.guidTemplatePackCmdSet , ( int ) PkgCmdIDList.cmdidMyCommand ) ; OleMenuCommand button = new OleMenuCommand ( ButtonClicked , cmdId ) ; button.BeforeQueryStatus += button_BeforeQueryStatus ; mcs.AddCommand ( button ) ; } /*if ( Environment.GetEnvironmentVariable ( `` SideWaffleEnableDynamicTemplates '' ) ! = null ) */ { try { new DynamicTemplateBuilder ( ) .ProcessTemplates ( ) ; } catch ( Exception ex ) { // todo : replace with logging or something System.Windows.MessageBox.Show ( ex.ToString ( ) ) ; } } } void button_BeforeQueryStatus ( object sender , EventArgs e ) { var button = ( OleMenuCommand ) sender ; var project = GetSelectedProjects ( ) .ElementAt ( 0 ) ; // TODO : We should only show this if the target project has the TemplateBuilder NuGet pkg installed // or something similar to that . button.Visible = true ; // button.Visible = project.IsWebProject ( ) ; } private void ButtonClicked ( object sender , EventArgs e ) { Project currentProject = GetSelectedProjects ( ) .ElementAt ( 0 ) ; var projects = _dte.Solution.GetAllProjects ( ) ; var names = from p in projects where p ! = currentProject select p.Name ; ProjectSelector selector = new ProjectSelector ( names ) ; bool ? isSelected = selector.ShowDialog ( ) ; if ( isSelected.HasValue & & isSelected.Value ) { // need to save everything because we will directly write to the project file in the creator _dte.ExecuteCommand ( `` File.SaveAll '' ) ; TemplateReferenceCreator creator = new TemplateReferenceCreator ( ) ; var selectedProject = projects.First ( p = > p.Name == selector.SelectedProjectName ) ; creator.AddTemplateReference ( currentProject , selectedProject ) ; } } public IEnumerable < Project > GetSelectedProjects ( ) { var items = ( Array ) _dte.ToolWindows.SolutionExplorer.SelectedItems ; foreach ( UIHierarchyItem selItem in items ) { var item = selItem.Object as Project ; if ( item ! = null ) { yield return item ; } } } } [ PackageRegistration ( UseManagedResourcesOnly = true ) ] [ InstalledProductRegistration ( `` # 110 '' , `` # 112 '' , `` 1.0 '' , IconResourceID = 400 ) ] [ ProvideMenuResource ( `` Menus.ctmenu '' , 1 ) ] [ Guid ( GuidList.guidMenuOptionsPkgString ) ] public sealed class MenuOptionsPackage : Package { // Overridden Package Implementation # region Package Members protected override void Initialize ( ) { base.Initialize ( ) ; // Add our command handlers for menu ( commands must exist in the .vsct file ) OleMenuCommandService mcs = GetService ( typeof ( IMenuCommandService ) ) as OleMenuCommandService ; if ( null ! = mcs ) { // Create the command for the menu item . CommandID menuCommandID = new CommandID ( GuidList.guidMenuOptionsCmdSet , ( int ) PkgCmdIDList.cmdidMyCommand ) ; MenuCommand menuItem = new MenuCommand ( MenuItemCallback , menuCommandID ) ; mcs.AddCommand ( menuItem ) ; } } # endregion private void MenuItemCallback ( object sender , EventArgs e ) { // Here is where our UI ( i.e . user control ) will go to do all the settings . var window = new SettingsForm ( ) ; window.Show ( ) ; } } } using System ; namespace TemplatePack { static class GuidList { public const string guidTemplatePackPkgString = `` e6e2a48e-387d-4af2-9072-86a5276da6d4 '' ; public const string guidTemplatePackCmdSetString = `` a94bef1a-053e-4066-a851-16e5f6c915f1 '' ; public static readonly Guid guidTemplatePackCmdSet = new Guid ( guidTemplatePackCmdSetString ) ; // SideWaffle Remote Source Settings public const string guidMenuOptionsPkgString = `` ee0cf212-810b-45a1-8c62-e10041913c94 '' ; public const string guidMenuOptionsCmdSetString = `` c75eac28-63cd-4766-adb1-e655471525ea '' ; public static readonly Guid guidMenuOptionsCmdSet = new Guid ( guidMenuOptionsCmdSetString ) ; } static class PkgCmdIDList { public const uint cmdidMyCommand = 0x100 ; public const uint SWMenuGroup = 0x100 ; } ; }",Visual Studio menu item appearing multiple times "C_sharp : Is it possible to specify an operator R where R can be an arithmetic , relational or logical operator ? For example a function that calculateswhere I can specify whether R is + , - , * , /Can this be done in C # ? c = a R b",programmatically specify operator "C_sharp : I have an IEnumerable and I wanted to split the data across 3 columns using the following business logic . if 3 or less items , 1 item per column , anything else I wanted to divide the total items by 3 split the leftovers ( either 1 or 2 items ) between the first two columns . Now this is pretty ugly but it does the job . I 'm looking for tips to leverage linq a little better or possibly eliminate the switch statement . Any advice or tips that improve the code are appreciated.Ultimately I am using these in a mvc Razor viewIn my first attempt I want to get rid of the colNItems and colNTake variables but i ca n't figure out the correct algorithm to make it work the same . var numItems = items.Count ; IEnumerable < JToken > col1Items , col2Items , col3Items ; if ( numItems < =3 ) { col1Items = items.Take ( 1 ) ; col2Items = items.Skip ( 1 ) .Take ( 1 ) ; col3Items = items.Skip ( 2 ) .Take ( 1 ) ; } else { int remainder = numItems % 3 , take = numItems / 3 , col1Take , col2Take , col3Take ; switch ( remainder ) { case 1 : col1Take = take + 1 ; col2Take = take ; col3Take = take ; break ; case 2 : col1Take = take + 1 ; col2Take = take + 1 ; col3Take = take ; break ; default : col1Take = take ; col2Take = take ; col3Take = take ; break ; } col1Items = items.Take ( col1Take ) ; col2Items = items.Skip ( col1Take ) .Take ( col2Take ) ; col3Items = items.Skip ( col1Take + col2Take ) .Take ( col3Take ) ; < div class= '' widgetColumn '' > @ Html.DisplayFor ( m = > col1Items , `` MenuColumn '' ) < /div > < div class= '' widgetColumn '' > @ Html.DisplayFor ( m = > col2Items , `` MenuColumn '' ) < /div > < div class= '' widgetColumn '' > @ Html.DisplayFor ( m = > col3Items , `` MenuColumn '' ) < /div > for ( int i = 1 ; i < = 3 ; i++ ) { IEnumerable < JToken > widgets = new List < JToken > ( ) ; var col = i ; switch ( col ) { case 1 : break ; case 2 : break ; case 3 : break ; } }",C # algorithm refactor splitting an array into 3 parts ? C_sharp : I have these 2 entities : I would like to add a validation rule so that the total Percentage of all children is 100 . How can I add this rule in the following validator ? public class Parent { public ICollection < Child > Children { get ; set ; } } public class Child { public decimal Percentage { get ; set ; } } public ParentValidator ( ) { RuleFor ( x = > x.Children ) .SetCollectionValidator ( new ChildValidator ( ) ) ; } private class ChildValidator : AbstractValidator < Child > { public ChildValidator ( ) { RuleFor ( x = > x.Percentage ) .GreaterThan ( 0 ) ) ; } },Validate collection using sum on a property "C_sharp : I have MVC Attribute routing enabled alongside Convention routing . I get this error every time I run the application . The inline constraint resolver of type 'DefaultInlineConstraintResolver ' was unable to resolve the following inline constraint : 'string ' . Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : System.InvalidOperationException : The inline constraint resolver of type 'DefaultInlineConstraintResolver ' was unable to resolve the following inline constraint : 'string'.Here is the stack trace : [ InvalidOperationException : The inline constraint resolver of type 'DefaultInlineConstraintResolver ' was unable to resolve the following inline constraint : 'string ' . ] System.Web.Mvc.Routing.InlineRouteTemplateParser.GetInlineConstraint ( Group constraintGroup , Boolean isOptional , IInlineConstraintResolver constraintResolver ) +389 System.Web.Mvc.Routing.InlineRouteTemplateParser.ParseRouteTemplate ( String routeTemplate , IDictionary2 defaults , IDictionary2 constraints , IInlineConstraintResolver constraintResolver ) +488 System.Web.Mvc.Routing.DirectRouteFactoryContext.CreateBuilder ( String template , IInlineConstraintResolver constraintResolver ) +308 System.Web.Mvc.Routing.DirectRouteFactoryContext.CreateBuilderInternal ( String template ) +48 System.Web.Mvc.Routing.DirectRouteFactoryContext.CreateBuilder ( String template ) +44 System.Web.Mvc.RouteAttribute.System.Web.Mvc.Routing.IDirectRouteFactory.CreateRoute ( DirectRouteFactoryContext context ) +80 System.Web.Mvc.Routing.DefaultDirectRouteProvider.CreateRouteEntry ( String areaPrefix , String controllerPrefix , IDirectRouteFactory factory , IReadOnlyCollection1 actions , IInlineConstraintResolver constraintResolver , Boolean targetIsAction ) +115 System.Web.Mvc.Routing.DefaultDirectRouteProvider.CreateRouteEntries ( String areaPrefix , String controllerPrefix , IReadOnlyCollection1 factories , IReadOnlyCollection1 actions , IInlineConstraintResolver constraintResolver , Boolean targetIsAction ) +155 System.Web.Mvc.Routing.DefaultDirectRouteProvider.GetActionDirectRoutes ( ActionDescriptor actionDescriptor , IReadOnlyList1 factories , IInlineConstraintResolver constraintResolver ) +188 System.Web.Mvc.Routing.DefaultDirectRouteProvider.GetDirectRoutes ( ControllerDescriptor controllerDescriptor , IReadOnlyList1 actionDescriptors , IInlineConstraintResolver constraintResolver ) +245 System.Web.Mvc.Routing.AttributeRoutingMapper.AddRouteEntries ( SubRouteCollection collector , IEnumerable1 controllerTypes , IInlineConstraintResolver constraintResolver , IDirectRouteProvider directRouteProvider ) +234 System.Web.Mvc.Routing.AttributeRoutingMapper.MapAttributeRoutes ( RouteCollection routes , IEnumerable ` 1 controllerTypes , IInlineConstraintResolver constraintResolver , IDirectRouteProvider directRouteProvider ) +333 System.Web.Mvc.Routing.AttributeRoutingMapper.MapAttributeRoutes ( RouteCollection routes , IInlineConstraintResolver constraintResolver , IDirectRouteProvider directRouteProvider ) +398 System.Web.Mvc.Routing.AttributeRoutingMapper.MapAttributeRoutes ( RouteCollection routes , IInlineConstraintResolver constraintResolver ) +192 System.Web.Mvc.RouteCollectionAttributeRoutingExtensions.MapMvcAttributeRoutes ( RouteCollection routes ) +123 SocialManager.RouteConfig.RegisterRoutes ( RouteCollection routes ) in c : \Users\Naser Dostdar\Documents\Visual Studio 2013\Projects\SocialManager\SocialManager\App_Start\RouteConfig.cs:16 SocialManager.MvcApplication.Application_Start ( ) in c : \Users\Naser Dostdar\Documents\Visual Studio 2013\Projects\SocialManager\SocialManager\Global.asax.cs:18 [ HttpException ( 0x80004005 ) : The inline constraint resolver of type 'DefaultInlineConstraintResolver ' was unable to resolve the following inline constraint : 'string ' . ] System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode ( HttpContext context , HttpApplication app ) +9942821 System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS ( IntPtr appContext , HttpContext context , MethodInfo [ ] handlers ) +118 System.Web.HttpApplication.InitSpecial ( HttpApplicationState state , MethodInfo [ ] handlers , IntPtr appContext , HttpContext context ) +172 System.Web.HttpApplicationFactory.GetSpecialApplicationInstance ( IntPtr appContext , HttpContext context ) +352 System.Web.Hosting.PipelineRuntime.InitializeApplication ( IntPtr appContext ) +296 [ HttpException ( 0x80004005 ) : The inline constraint resolver of type 'DefaultInlineConstraintResolver ' was unable to resolve the following inline constraint : 'string ' . ] System.Web.HttpRuntime.FirstRequestInit ( HttpContext context ) +9924184 System.Web.HttpRuntime.EnsureFirstRequestInit ( HttpContext context ) +101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate ( IIS7WorkerRequest wr , HttpContext context ) +261And here is how my Route.Config file looks like : P.S : I did not defined any MVC Attribute route in my project as of yet , just want to test enabling the MVC Attribute routing feature.Web API Version : 2.2 public class RouteConfig { public static void RegisterRoutes ( RouteCollection routes ) { routes.IgnoreRoute ( `` { resource } .axd/ { *pathInfo } '' ) ; routes.MapMvcAttributeRoutes ( ) ; routes.MapRoute ( null , `` Page { page } '' , new { controller = `` Blogs '' , action = `` Index '' , category = ( string ) null } , new { page = @ '' \d+ '' } ) ; routes.MapRoute ( null , `` { category } '' , new { controller = `` Blogs '' , action = `` Edit '' , page = 1 } ) ; routes.MapRoute ( null , `` { category } /Page { page } '' , new { controller = `` Blogs '' , action = `` List '' } , new { page = @ '' \d+ '' } ) ; routes.MapRoute ( null , `` { controller } / { action } '' ) ; routes.MapRoute ( name : `` Default '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` Home '' , action = `` Index '' , id = UrlParameter.Optional } ) ; } }",How do I get rid of this error caused by MVCAttribute routing ? "C_sharp : I 'm working on a date-time system for a game . In the interest of reusability , I decided not to use the DateTime included in .NET . It reflects Earth time , whereas I 'd like to be able to have arbitrary values for things like hoursPerDay , and have , say , 10 months in a year , with any number of days each . For now I do n't care about things like leap years , or time zones.I 'm having trouble figuring out how to get the current day of the month ( MM-DD-YYYY ) . The code in question is the DayOfMonth property 's get method.A . The code above does n't work . It always returns a fixed value . B . The only way I can think of to accomplish this is to iterate through each month , adding up days until we reach each month 's day count , until we hit the total days elapsed . That does n't seem very efficient to me , especially with the redundant checking if ( d < TotalDays ) above.C . It seems like the more time that elapses , the longer it will take to find the DayOfMonth ( and perhaps other ) value ( s ) .I guess I 'm looking for a paradigm shift , because I think I might be painting myself in a corner.UpdateFor anyone who is interested in the ( somewhat ) working algorithms , I got this fixed by changing the DayOfMonth property to the following.The TotalMonths property needed a similar fix.which enables MonthOfYear : So far things seem to be in order . I suspect there 's a more elegant solution , perhaps involving Yield ( which I do n't yet understand ) , so if anyone comes up with something interesting I 'd love to hear about it . public sealed class Time { int _ticks = 0 ; int _ticksPerSecond = 30 ; int _secondsPerMinute = 60 ; int _minutesPerHour = 60 ; int _hoursPerDay = 24 ; readonly List < string > _days ; readonly Dictionary < string , int > _months ; // I have n't decided on ctor parameters yet , but we 'd define base units public Time ( ) { // What we call the days of the week . _days = new List < string > { `` Monday '' , `` Tuesday '' , `` Wednesday '' } ; // What we call the months of the year , and the number of days each . _months = new Dictionary < string , int > { { `` January '' , 31 } , { `` February '' , 28 } , { `` March '' , 31 } } ; } public void Advance ( int ticks ) { _ticks += ticks ; } // Number of ticks elapsed since epoch start public int TotalTicks { get { return _ticks ; } } // Number of ticks elapsed during the current second public int CurrentTicks { get { return _ticks % _ticksPerSecond ; } } public int TotalSeconds { get { return _ticks / _ticksPerSecond ; } } public int CurrentSeconds { get { return TotalSeconds % _secondsPerMinute ; } } public int TotalMinutes { get { return TotalSeconds / _secondsPerMinute ; } } public int CurrentMinutes { get { return TotalMinutes % _minutesPerHour ; } } public int TotalHours { get { return TotalMinutes / _minutesPerHour ; } } public int CurrentHours { get { return TotalHours % _hoursPerDay ; } } public List < string > Days { get { return _days ; } } public int TotalDays { get { return TotalHours / _hoursPerDay ; } } public int CurrentDay { get { return TotalDays % _days.Count ; } } public string DayOfWeek { get { return _days [ CurrentDay ] ; } } public int DayOfMonth { get { var d = 0 ; while ( d < TotalDays ) { foreach ( var month in Months ) { var daysInMonth = month.Value ; while ( daysInMonth > 0 & & d < TotalDays ) { d++ ; daysInMonth -- ; } } } return d ; } } public Dictionary < string , int > Months { get { return _months ; } } public int TotalMonths { get { return TotalDays / _months.Values.Sum ( ) ; } } public int CurrentMonth { get { return TotalMonths % Months.Count ; } } … } public int DayOfMonth { get { var d = TotalDays ; var found = false ; while ( ! found ) { foreach ( var month in _months ) { if ( d > month.Value ) d -= month.Value ; else { found = true ; break ; } } } return d ; } } public int TotalMonths { get { var d = TotalDays ; var found = false ; var m = 0 ; while ( ! found ) { foreach ( var month in _months ) { if ( d > month.Value ) { d -= month.Value ; m++ ; } else { found = true ; break ; } } } return m ; } } public string MonthOfYear { get { return _months.Keys.ToList ( ) [ CurrentMonth ] ; } }",Get the day of the month ( not using .NET DateTime ) "C_sharp : I have a .NET Remoting service which works fine most of the time . If an exception or error happens , it logs the error to a file but still continues to run.However , about once every two weeks the service stops responding to clients , which causes the client appication to crash with a SocketException with the following message : No exception or stack trace is written to our log file , so I ca n't figure out where the service is crashing at , which leads me to believe that it is somewhere outside of my code which is failing . What additional steps can I take to figure out the root cause of this crash ? I would imagine that it writes something to an EventLog somewhere , but I am not super familiar with Windows ' Event Logging system so I 'm not exactly sure where to look.Thanks in advance for any assistance with this.EDIT : Forgot to mention , stopping or restarting the service does nothing , the service never responds . I need to manually kill the process before I can start the service again.EDIT 2 : A connection attempt failed because the connected party did not properly respond after a period of time , or established connection failed because connected host has failed to respond public class ClientInfoServerSinkProvider : IServerChannelSinkProvider { private IServerChannelSinkProvider _nextProvider = null ; public ClientInfoServerSinkProvider ( ) { } public ClientInfoServerSinkProvider ( IDictionary properties , ICollection providerData ) { } public IServerChannelSinkProvider Next { get { return _nextProvider ; } set { _nextProvider = value ; } } public IServerChannelSink CreateSink ( IChannelReceiver channel ) { IServerChannelSink nextSink = null ; if ( _nextProvider ! = null ) { nextSink = _nextProvider.CreateSink ( channel ) ; } return new ClientIPServerSink ( nextSink ) ; } public void GetChannelData ( IChannelDataStore channelData ) { } } public class ClientIPServerSink : BaseChannelObjectWithProperties , IServerChannelSink , IChannelSinkBase { private IServerChannelSink _nextSink ; public ClientIPServerSink ( IServerChannelSink next ) { _nextSink = next ; } public IServerChannelSink NextChannelSink { get { return _nextSink ; } set { _nextSink = value ; } } public void AsyncProcessResponse ( IServerResponseChannelSinkStack sinkStack , Object state , IMessage message , ITransportHeaders headers , Stream stream ) { IPAddress ip = headers [ CommonTransportKeys.IPAddress ] as IPAddress ; CallContext.SetData ( `` ClientIPAddress '' , ip ) ; sinkStack.AsyncProcessResponse ( message , headers , stream ) ; } public Stream GetResponseStream ( IServerResponseChannelSinkStack sinkStack , Object state , IMessage message , ITransportHeaders headers ) { return null ; } public ServerProcessing ProcessMessage ( IServerChannelSinkStack sinkStack , IMessage requestMsg , ITransportHeaders requestHeaders , Stream requestStream , out IMessage responseMsg , out ITransportHeaders responseHeaders , out Stream responseStream ) { if ( _nextSink ! = null ) { IPAddress ip = requestHeaders [ CommonTransportKeys.IPAddress ] as IPAddress ; CallContext.SetData ( `` ClientIPAddress '' , ip ) ; ServerProcessing spres = _nextSink.ProcessMessage ( sinkStack , requestMsg , requestHeaders , requestStream , out responseMsg , out responseHeaders , out responseStream ) ; return spres ; } else { responseMsg = null ; responseHeaders = null ; responseStream = null ; return new ServerProcessing ( ) ; } }",".NET remoting service seemingly crashes , and stops responding to clients" C_sharp : I know I can use Linq to map fields from XML to fields in a pre-existing object . Are there any functions in the .NET Framework ( or other libraries ) that make this less manual.I would like to write ( and have the HydrateFromXml behave a little like AutoMapper does ) : Edit : Could I use the decorator pattern or a simple wrapper object here ? Deserialize directly into a type that is wrapped by an abstraction that permits the fine-grained construction control I need ? var myObject = new MyObject ( /*ctor args*/ ) ; myObject = myObject.HydrateFromXml ( string xml ) ;,C # - Hydrate existing object with XML "C_sharp : I have the following code : I need a base class to inherit from this class , like such : However , I do not want someone to be able to do : but only would like the following method : j.PushToNav ( ) ; //and any other public functionality in the base class to be availableEssentially , I want to force the child class to implement CRUD operations , without exposing them to the public . The ideal syntax I was hoping for is the following : public abstract class NavEntityController < ChildEntity > where ChildEntity : NavObservableEntity { public abstract void Delete ( ChildEntity line ) ; public abstract void Update ( ChildEntity line ) ; public abstract void Create ( ChildEntity line ) ; public void PushChangesToNav ( NavObservableCollection < ChildEntity > lines ) { foreach ( var line in lines ) { line.ErrorLastAction = false ; EntityState previousState = line.CurrentState ; try { switch ( line.CurrentState ) { case EntityState.Unchanged : break ; case EntityState.NeedsCreate : Create ( line ) ; line.CurrentState = EntityState.Unchanged ; break ; case EntityState.NeedsUpdate : Update ( line ) ; line.CurrentState = EntityState.Unchanged ; break ; case EntityState.NeedsDelete : Delete ( line ) ; line.CurrentState = EntityState.Deleted ; break ; } } catch ( Exception e ) { // ... } } } } public class NavJobController : NavEntityController < NavObservableJob > { public NavJobController ( { } public override void Delete ( NavObservableJob line ) { //Implementation here } public override void Update ( NavObservableJob line ) { //Implementation here } public override void Create ( NavObservableJob line ) { //Implementation here } //Other functionality } NavJobController j = new NavJobController ( ) ; j.Create ( new NavObservableJob ( ) ) ; private abstract void Delete ( ChildEntity line ) ; private abstract void Update ( ChildEntity line ) ; private abstract void Create ( ChildEntity line ) ;",Force child class to implement private method C_sharp : I am trying out signalR with a simple blog poster and i am unsure as to what would be best practice in implementing it.First Solution : Have the client invoke the post method on the server which will in turn either supply the data to the relevant web api or other method of uploading the data . my intention here to use the already open connection.Second Solution : Have the client do a ajax call to a web api which then calls the post method and broadcasts it back to the client . third solution : Another ( probably better ) method i have n't thought of.fourth Solution : I 'm horribly abusing how signalR should be used.Thanks in advance ! public class BlogHub : Hub { public void Post ( string text ) { //Internal Webapi call / other method of DB Update . Clients.All.BroadcastPost ( text ) ; } } public void PostPost ( string text ) //May have to call this method something different ... { db.posts.add ( new PostModel ( text ) ) ; db.SaveChanges ( ) ; Post ( string Text ) ; },Signal R Hub Conventions in regards to Web Api 's "C_sharp : What I am trying to do is to check whether the float input is a number or not . I am being asked to do so by using IsNumeric ( ) method . The problem is that I am using MonoDevelop and I ca n't figure out why this does n't work . It seems like I have added assembly reference which I need . So from scratch . How do I do this ? Do I have to add something to VB assembly reference ? And , If that will still work when I will try to work in school on VisualStudio ? The reference file with VB looks like this : Regards . And thank you for help.Some more info . On top of my page I do have : IsNumeric ( ) method is n't listed when I try to type it ( usually things are listed ) .Another edit . So I could do this this way ( but I do need to use the IsNumeric method so I wont loose any points from homework ) : static void getBookInfo ( Book book ) { Console.Write ( `` Enter Book Title : `` ) ; book.Title = Console.ReadLine ( ) ; Console.Write ( `` Enter Author 's First Name : `` ) ; book.AuthorFirstName = Console.ReadLine ( ) ; Console.Write ( `` Enter Author 's Last Name : `` ) ; book.AuthorLastName = Console.ReadLine ( ) ; Console.Write ( `` Enter Book Price : $ '' ) ; book.Price = float.Parse ( Console.ReadLine ( ) ) ; } public class VBCodeProvider : CodeDomProvider { // Constructors public VBCodeProvider ( ) ; public VBCodeProvider ( IDictionary < string , string > providerOptions ) ; // Methods public virtual ICodeCompiler CreateCompiler ( ) ; public virtual ICodeGenerator CreateGenerator ( ) ; public virtual TypeConverter GetConverter ( Type type ) ; public virtual void GenerateCodeFromMember ( CodeTypeMember member , TextWriter writer , CodeGeneratorOptions options ) ; // Properties public virtual string FileExtension { get ; } public virtual LanguageOptions LanguageOptions { get ; } } using Microsoft.VisualBasic ; static void getBookInfo ( Book book ) { bool isNumeric ; float number ; string numberInput ; Console.Write ( `` Enter Book Title : `` ) ; book.Title = Console.ReadLine ( ) ; Console.Write ( `` Enter Author 's First Name : `` ) ; book.AuthorFirstName = Console.ReadLine ( ) ; Console.Write ( `` Enter Author 's Last Name : `` ) ; book.AuthorLastName = Console.ReadLine ( ) ; Console.Write ( `` Enter Book Price : $ '' ) ; numberInput = Console.ReadLine ( ) ; isNumeric = float.TryParse ( numberInput , out number ) ; if ( isNumeric ) Console.WriteLine ( number.ToString ( ) ) ; else Console.WriteLine ( `` not number '' ) ; }",How to use IsNumeric method in MonoDevelop by using Microsoft.VisualBasic reference ? "C_sharp : I 've recently decided to refresh my memory regarding C # basics , so this might be trivial , but i 've bumped into the following issue : StringCollection was used in .NET v1.0 in order to create a strongly typed collection for strings as opposed to an object based ArrayList ( this was later enhanced by including Generic collections ) : Taking a quick glance at StringCollection definition , you can see the following : You can see it implements IList , which contains the following declaration ( among a few other declarations ) : But not : My first assumption was that it is possible due to the .NET framework covariance rules.So just to make sure , I tried writing my own class which implements IList and changedto retrieve a string type instead of an object type , but for my surprise , when trying to compile the project , I got an compile-time error : Any ideas what causes this ? Thanks ! // Summary : // Represents a collection of strings . [ Serializable ] public class StringCollection : IList , ICollection , IEnumerable { ... public int Add ( string value ) ; ... } int Add ( object value ) ; int Add ( string value ) ; int Add ( object value ) ; does not implement interface member 'System.Collections.IList.Add ( object ) '",C # Covariance and Contravariance when implementing interfaces "C_sharp : In C # There seem to be quite a few different lists . Off the top of my head I was able to come up with a couple , however I 'm sure there are many more.My question is when is it beneficial to use one over the other ? More specifically I am returning lists of unknown size from functions and I was wondering if there is a particular list that was better at this . List < String > Types = new List < String > ( ) ; ArrayList Types2 = new ArrayList ( ) ; LinkedList < String > Types4 = new LinkedList < String > ( ) ;",ASP.NET C # Lists Which and When ? "C_sharp : I am attempting to bridge between the VSSDK and Roslyn SDK in a Visual Studio extension package and have been having a hard time with this.The ActivePoint.AbsoluteCharOffset given from Visual Studio does not match the element I get from Roslyn when using FindToken ( offset ) . I 'm fairly sure this has to do with how each side counts EOL characters based on my current working hack but I 'm not 100 % that my hack is going to hold up in the long run.My hack is this line : charOffset += point.Line ; I add the number of lines onto the char offset , this seems to work so I 'm guessing I am adding in all the line break characters that are being ignored by activepoint counting.HelpersMain Part private VisualStudioWorkspace workspace = null ; public RoslynUtilities ( VisualStudioWorkspace workspace ) { this.workspace = workspace ; } public Solution Solution { get { return workspace.CurrentSolution ; } } public Document GetDocumentFromPath ( string fullPath ) { foreach ( Project proj in this.Solution.Projects ) { foreach ( Document doc in proj.Documents ) { if ( doc.FilePath == fullPath ) return doc ; } } return null ; } public SyntaxTree GetSyntaxTreeFromDocumentPath ( string fullPath ) { Document doc = GetDocumentFromPath ( fullPath ) ; if ( doc ! = null ) return doc.GetSyntaxTreeAsync ( ) .Result ; else return null ; } public SyntaxNode GetNodeByFilePosition ( string fullPath , int absoluteChar ) { SyntaxTree tree = GetSyntaxTreeFromDocumentPath ( fullPath ) ; if ( tree ! = null ) { var compUnit = tree.GetCompilationUnitRoot ( ) ; if ( compUnit ! = null ) { return compUnit.FindToken ( absoluteChar , true ) .Parent ; } } return null ; } private VisualStudioWorkspace GetRoslynWorkspace ( ) { var componentModel = ( IComponentModel ) GetGlobalService ( typeof ( SComponentModel ) ) ; return componentModel.GetService < VisualStudioWorkspace > ( ) ; } EnvDTE80.DTE2 applicationObject = ( EnvDTE80.DTE2 ) GetService ( typeof ( SDTE ) ) ; EnvDTE.TextSelection ts = applicationObject.ActiveWindow.Selection as EnvDTE.TextSelection ; if ( ts == null ) return ; EnvDTE.VirtualPoint point = ts.ActivePoint ; int charOffset = point.AbsoluteCharOffset ; charOffset += point.Line ; //HACK ALERTParse.Roslyn.RoslynUtilities roslyn = new Parse.Roslyn.RoslynUtilities ( GetRoslynWorkspace ( ) ) ; SyntaxNode node = roslyn.GetNodeByFilePosition ( applicationObject.ActiveDocument.FullName , charOffset ) ;",Get Roslyn SyntaxToken from Visual Studio Text Selection ( caret position ) "C_sharp : I have the following conceptual model : Then I try to use it in a way that conceptually is equivalent to this : I want to use the Get ( ) method on a FooService instance - no matter what type the selected FooService instance returns . However , this code results in the following exception : Unable to cast object of type 'WindowsFormsApplication7.FooService ` 1 [ System.DateTime ] ' to type 'WindowsFormsApplication7.FooService ` 1 [ System.Object ] '.Any suggestions on how to solve this problem would be greately appreciated . You could argue , why I made the FooService generic in the first place . However , this is done to secure type safety in a type safe environment . In this particular case , though , the FooService shall be used in a Web API controller to serve various types of Foo . It shall return a response with Foo of T disregarding the type of T . public interface IFoo < out T > { T Data { get ; } } public struct Foo < T > : IFoo < T > { public Foo ( T data ) : this ( ) { Data = data ; } public T Data { get ; private set ; } } public class FooService < T > { ... public Foo < T > Get ( string id ) { ... } } // Create and register a few FooService instancesServiceLocator.Register ( new FooService < DateTime > ( ) , `` someServiceId '' ) ; ServiceLocator.Register ( new FooService < double ? > ( ) , `` anotherServiceId '' ) ; // Retrieve a particular FooService instance and call the Get methodvar fooService = ( FooService < object > ) ServiceLocator.Get ( `` someServiceId '' ) ; var foo = fooService.Get ( `` someFooId '' ) ;",Unable to cast generic object "C_sharp : In delphi , I can create my own message like this , bu in c # I can do that like thisbut I do n't want to override WndProc ( ) , I want to create my own MyMessage ( ) function , and when I post message it will run.How can I do that ? Thanks . const MY_MESSAGE = WM_USER+100 ; procedure MyMessage ( var Msg : TMessage ) ; message MY_MESSAGE ; procedure TForm1.MyMessage ( var Msg : TMessage ) ; begin ... .end ; public static uint ms ; protected override void WndProc ( ref Message m ) { if ( m.Msg == ms ) MessageBox.Show ( `` example '' ) ; else base.WndProc ( ref m ) ; } void Button1Click ( object sender , EventArgs e ) { PostMessage ( HWND_BROADCAST , ms , IntPtr.Zero , IntPtr.Zero ) ; }",Does C # have an equivalent of Delphi 's message keyword ? "C_sharp : I 'm creating a VS extension , and I want to add a file to solution and set some properties . One of them is Copy to output directory , but I can not find a way of setting it . Setting Build action works fine , but the desired property is not even listed in array while debugging.How can I set the property for my newly added item ? private EnvDTE.ProjectItem AddFileToSolution ( string filePath ) { var folder = CurrentProject.ProjectItems.AddFolder ( Path.GetDirectoryName ( filePath ) ) ; var item = folder.ProjectItems.AddFromFileCopy ( filePath ) ; item.Properties.Item ( `` BuildAction '' ) .Value = `` None '' ; // item.Properties.Item ( `` CopyToOutputDirectory '' ) .Value = `` CopyAlways '' ; // does n't work - the dictionary does n't contain this item , so it throws an exception return item ; }",Visual Studio Extension - set `` Copy To Output Directory '' property "C_sharp : I 'm running an NHIbernate solution using SQL CE.I am mapping one the fields in a table as below . However , in order to run some data imports I need to be able to temporarily turn off identity so I can import the data with its existing keys , then turn identity back on once the import has finished.I 've tried running a SQL query directly from the solution like this : but this seems to have no effect.Is there any way to temporarily turn this on and off ? session.CreateSQLQuery ( @ '' SET IDENTITY_INSERT [ Article ] ON '' ) ; Property ( x = > x.ArticleId , m = > { m.NotNullable ( true ) ; m.UniqueKey ( `` UQ_Article_ArticleId '' ) ; m.Column ( cm = > cm.SqlType ( `` INT IDENTITY '' ) ) ; m.Generated ( PropertyGeneration.Insert ) ; m.Insert ( true ) ; m.Update ( false ) ; } ) ;",NHibernate -Temporarily turn off identity "C_sharp : I have an asp.net mvc 5 web api application where I need to convert a SqlGeography instance into a DbGeography instance for querying with Entity Framework 6 . I 'm using the following code to do so : The call to GeographyFromProviderValue throws the following exception : The specified provider value is not compatible with this spatial services implementation . A value is required of type 'Microsoft.SqlServer.Types.SqlGeography , Microsoft.SqlServer.Types , Version=11.0.0.0 , Culture=neutral , PublicKeyToken=89845dcd8080cc91 ' . Parameter name : providerValueSure enough , my SqlGeography instance is coming from the SQL Server 2014 types assembly ( Microsoft.SqlServer.Types , Version 12.0.0.0 ) .Digging into the Entity Framework source code shows this method to be the culprit : As you can see , the types assembly for SQL Server 2014 is not included . Does this mean that Entity Framework 6 does not support types from SQL Server 2014 ? Obviously I could find the Types assembly for SQL Server 2012 and use that instead , but I 'd rather not have to . Is there any other way around this issue ? SqlGeography geo = SqlGeography.STGeomFromText ( chars , Constants.SRID ) ; DbGeography dbGeo = DbSpatialServices.Default.GeographyFromProviderValue ( geo ) ; //EntityFramework.SqlServer.dll ( 6.0.0.0 ) System.Data.Entity.SqlServer.SqlTypesAssemblyLoaderpublic SqlTypesAssemblyLoader ( IEnumerable < string > assemblyNames = null ) { this._preferredSqlTypesAssemblies = ( assemblyNames ? ? ( ( IEnumerable < string > ) new string [ ] { `` Microsoft.SqlServer.Types , Version=11.0.0.0 , Culture=neutral , PublicKeyToken=89845dcd8080cc91 '' , `` Microsoft.SqlServer.Types , Version=10.0.0.0 , Culture=neutral , PublicKeyToken=89845dcd8080cc91 '' } ) ) ; this._latestVersion = new Lazy < SqlTypesAssembly > ( new Func < SqlTypesAssembly > ( this.BindToLatest ) , true ) ; } }",Does EF 6 support SQL Server 2014 Types ? "C_sharp : I am trying to enumerate through files on my computer using the below code but everytime it hits a file or dir that I do n't have permission to read it throws an exception . Is there any way I can continue searching after the exception has been thrown ? I know some people have had similar issues but is there any other way of doing this other than checking every file/folder individually ? Thanks for any help as this is driving me mad ! try { string [ ] files = Directory.GetFiles ( @ '' C : \ '' , * . * '' , SearchOption.AllDirectories ) ; foreach ( string file in files ) { Console.WriteLine ( file ) ; } } catch { }",Enumerating Files Throwing Exception "C_sharp : With Intellitest you can specify a type for Intellitest to use that fits an interface when generating unit tests , however I have a custom factory I wish to use instead.My custom factory : I would like to use this factory for all ILogic instances PEX tries to create.I tried adding the following attribute to PexAssemblyInfo.cs , and I also tried adding it above my test : but I still get this runtime warning when instrumenting code : will use Company.Logics.SpecificLogic as ILogicAnd so it seems it 's ignoring my factory every time . How can I force Intellitest to use my factory instead ? public static partial class LogicFactory { /// < summary > A factory for ILogic instances < /summary > [ PexFactoryMethod ( typeof ( ILogic ) ) ] public static ILogic Create ( string defaultUICulture , bool saveSuccessful ) { return Mock.Of < ILogic > ( x = > x.GetUICulture ( It.IsAny < string > ( ) ) == defaultUICulture & & x.Save ( It.IsAny < string > ( ) , It.IsAny < string > ( ) ) == saveSuccessful ) ; } } [ assembly : PexCreatableByClassFactory ( typeof ( ILogic ) , typeof ( LogicFactory ) ) ]",How do I specify the factory Intellitest should use for an interface ? "C_sharp : Edited with complete , working , code-example.In my IRC app , the application receives content from an IRC server . The content is sent in to a factory and the factory spits out an IMessage object that can be consumed by the presentation layer of the application . The IMessage interface and a single implementation is shown below.To receive the IMessage object , the presentation layer subscribes to notifications that are published within my domain layer . The notification system iterates over a collection of subscribers to a specified IMessage implementation and fires a callback method to the subscriber.In order to demonstrate how the above code works , I have a simple Console application that subscribes to notifications from the above ServerMessage type . The console app first publishes by passing the ServerMessage object in to the Publish < T > method directly . This works without any issues.The 2nd example has the app creating an IMessage instance using a factory method . The IMessage instance is then passed in to the Publish < T > method , causing my variance issue to throw an InvalidCastException.The exception states that I can not cast an INotification < IMessage > ( what the Publish method is understands the message being published to be ) in to an INotification < ServerMessage > .I have tried to mark the INotification interface generic as contravariant , like INotification < in TMessageType > but ca n't do that because I 'm consuming TMessageType as a parameter to the Register method 's callbacks . Should I split the interface in to two separate interfaces ? One that can register and one that can consume ? Is that the best alternative ? Any additional help on this would be great . public interface IMessage { object GetContent ( ) ; } public interface IMessage < out TContent > : IMessage where TContent : class { TContent Content { get ; } } public class ServerMessage : IMessage < string > { public ServerMessage ( string content ) { this.Content = content ; } public string Content { get ; private set ; } public object GetContent ( ) { return this.Content ; } } public interface ISubscription { void Unsubscribe ( ) ; } public interface INotification < TMessageType > : ISubscription where TMessageType : class , IMessage { void Register ( Action < TMessageType , ISubscription > callback ) ; void ProcessMessage ( TMessageType message ) ; } internal class Notification < TMessage > : INotification < TMessage > where TMessage : class , IMessage { private Action < TMessage , ISubscription > callback ; public void Register ( Action < TMessage , ISubscription > callbackMethod ) { this.callback = callbackMethod ; } public void Unsubscribe ( ) { this.callback = null ; } public void ProcessMessage ( TMessage message ) { this.callback ( message , this ) ; } } public class NotificationManager { private ConcurrentDictionary < Type , List < ISubscription > > listeners = new ConcurrentDictionary < Type , List < ISubscription > > ( ) ; public ISubscription Subscribe < TMessageType > ( Action < TMessageType , ISubscription > callback ) where TMessageType : class , IMessage { Type messageType = typeof ( TMessageType ) ; // Create our key if it does n't exist along with an empty collection as the value . if ( ! listeners.ContainsKey ( messageType ) ) { listeners.TryAdd ( messageType , new List < ISubscription > ( ) ) ; } // Add our notification to our listener collection so we can publish to it later , then return it . var handler = new Notification < TMessageType > ( ) ; handler.Register ( callback ) ; List < ISubscription > subscribers = listeners [ messageType ] ; lock ( subscribers ) { subscribers.Add ( handler ) ; } return handler ; } public void Publish < T > ( T message ) where T : class , IMessage { Type messageType = message.GetType ( ) ; if ( ! listeners.ContainsKey ( messageType ) ) { return ; } // Exception is thrown here due to variance issues . foreach ( INotification < T > handler in listeners [ messageType ] ) { handler.ProcessMessage ( message ) ; } } } class Program { static void Main ( string [ ] args ) { var notificationManager = new NotificationManager ( ) ; ISubscription subscription = notificationManager.Subscribe < ServerMessage > ( ( message , sub ) = > Console.WriteLine ( message.Content ) ) ; notificationManager.Publish ( new ServerMessage ( `` This works '' ) ) ; IMessage newMessage = MessageFactoryMethod ( `` This throws exception '' ) ; notificationManager.Publish ( newMessage ) ; Console.ReadKey ( ) ; } private static IMessage MessageFactoryMethod ( string content ) { return new ServerMessage ( content ) ; } }",foreach loop can not cast type to the interface it implements "C_sharp : My log4net configuration looks like this : In classes , I instantiate the logger withand call the Log.Error ( message ) ; only once but in my logs , all the errors are duplicated . Also , this method is being called in a controller class for a WebApi project . I 've read in other questions that it can happen when using multiple loggers and them propagating messages upto the root logger , however , I am only using the root logger in this instance . < log4net > < appender name= '' CloudWatchLogsAppender '' type= '' CloudWatchAppender.CloudWatchLogsAppender , CloudWatchAppender '' > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % date [ % thread ] % level % logger. % method - % message % newline '' / > < /layout > < groupName value= '' agroupname '' / > < streamName value= '' astreamname '' / > < /appender > < root > < level value= '' INFO '' / > < appender-ref ref= '' CloudWatchLogsAppender '' / > < /root > < logger name= '' Amazon '' > < level value= '' OFF '' / > < /logger > < /log4net > private static readonly ILog Log = LogManager.GetLogger ( MethodBase.GetCurrentMethod ( ) .DeclaringType ) ;",Log4net duplicate entries when only one ( root ) logger is used "C_sharp : Possible Duplicate : Compile-time and runtime casting c # As I understand it , the following code will always compile , and will additionally always fail at run-time by throwing an InvalidCastException . Example : My questions are ... If my assumptions are off , then can someone provide an example demonstrating how they 're off ? If my assumptions are correct , then why does n't the compiler warn against this error ? public class Post { } public class Question : Post { } public class Answer : Post { public void Fail ( ) { Post p = new Post ( ) ; Question q = ( Question ) p ; // This will throw an InvalidCastException } }",Why does n't the C # compiler catch an InvalidCastException "C_sharp : I 've written a source file with 1000 classes all inheriting from the one above : I get a StackOverflow exception on Class700 , however this changes every time I run it , but usually it 's around 700.Can anyone explain why at approximately level 700 , a StackOverflow occurs , and why this changes every time I run the program ? I 'm using Windows 8.1 Enterprise 64 bit . class Program { static void Main ( string [ ] args ) { Class700 class700 = new Class700 ( ) ; } } class Class1 { public Class1 ( ) { } } class Class2 : Class1 { public Class2 ( ) { } } class Class3 : Class2 { public Class3 ( ) { } } class Class4 : Class3 { public Class4 ( ) { } } class Class5 : Class4 { public Class5 ( ) { } } //class ClassN : ClassN-1 { public ClassN ( ) { } } where N = 2 to N = 1000",Max Level Of Inheritance "C_sharp : I have an event source that generates events that belong to certain groups . I would like to buffer these groups and send the groups ( in batches ) to storage . So far I have this : So there 's a nested subscribe to the events in a group . Somehow I think there 's a better way but I have n't been able to figure it out yet . eventSource .GroupBy ( event = > event.GroupingKey ) .Select ( group = > new { group.Key , Events = group } ) .Subscribe ( group = > group.Events .Buffer ( TimeSpan.FromSeconds ( 60 ) , 100 ) .Subscribe ( list = > SendToStorage ( list ) ) ) ;","Buffer group by groups with Reactive Extensions , nested subscribe" C_sharp : Is there a way to get the length of a fixed size buffer ? Something like : Is there any way to accomplish something like this ? public struct MyStruct { public unsafe fixed byte buffer [ 100 ] ; public int foo ( ) { return sizeof ( buffer ) ; // Compile error . } },How to get fixed buffer length ? "C_sharp : Very common scenario : I have a class with multiple instance variables and a constructor that accepts multiple parameters . Can I somehow bind one to the other ? Assigning all parameters to the instance variables is very verbose and is one of the situations that could be ( and should be ) covered by the convention-over-configuration principle . My example code looks like this : Is there an easy way to get rid of this and let C # do its magic automatically ? public class myClass { private object param1 ; private object param2 ; private object param3 ; private object param4 ; public myClass ( object param1 , object param2 , object param3 , object param4 ) { this.param1 = param1 ; this.param2 = param2 ; this.param3 = param3 ; this.param4 = param4 ; } }",C # Bind constructor parameters to instance variables "C_sharp : I have created a a project that reads different files and puts then in different sheets with a spreadsheet . I have used Open office calc spreadsheet therefore used the following code to open a blank file : I call a sheet to be used like so : where xComp is : However my problem is that file blank.ods needs to be set up with the number of sheets that will be required already inserted into the spreadsheet before the application is run . This is not ideal as the number of sheets needed is not always known . Is there a way of inserting sheets from within my application ? Any help would be appreciated . public XSpreadsheet getSpreadsheet ( int nIndex , XComponent xComp ) { XSpreadsheets xSheets = ( ( XSpreadsheetDocument ) xComp ) .getSheets ( ) ; XIndexAccess xSheetsIA = ( XIndexAccess ) xSheets ; XSpreadsheet xSheet = ( XSpreadsheet ) xSheetsIA.getByIndex ( nIndex ) .Value ; return xSheet ; } XSpreadsheet newSheet = getSpreadsheet ( sheetIndex , xComp ) ; string filePathway = @ '' file : ///c : /temp/blank.ods '' ; PropertyValue [ ] propVals = new PropertyValue [ 0 ] ; XComponent oCalcuDoc = oDesktop.loadComponentFromURL ( filePathway , `` _blank '' , 0 , propVals ) ;",Inserting Sheets in Spreadsheet through c # "C_sharp : I 've never really questioned this before until now . I 've got an input model with a number of fields , I wanted to present the string names of the properties through the input model so that my Grid can use them : Obviously , this gives the error : The type 'SomeGridRow ' already contains a definition for 'Code'Why can the CLR not cope with two properties of the same name which are , in my eyes , separate ? I 'm now just using a child class called Fields within my inputs now , so I can use SomeGridRow.Fields.Code . It 's a bit messy , but it works . public class SomeGridRow { public string Code { get ; set ; } public string Description { get ; set ; } public const string Code = `` Code '' ; } string code = gridRow.Code ; // Actual member from instantiated classstring codeField = SomeGridRow.Code ; // Static/Const",Why can a class not have a static or constant property and an instance property of the same name ? "C_sharp : I have an action as below : When I make the code jump into the else block ( when debugging ) it makes the redirection to EmailNotConfirmed action , which is in the same controller . But it does n't redirect to HomeController 's Index action . Instead , the browser stays at Account/SendEmailVerificationCode and displays a blank page.HomeController.Index is as below : I tried these : In the beginning SendEmailVerificationCode action was async but HomeController.Index was n't . So I declared them both as async.Then I deleted the async declaration from both of them.I tried return RedirectToAction ( `` Index '' , `` Home '' ) ; .SendEmailVerificationCode had HttpPost attribute ; I changed it to HttpGet.How can I make the redirection to an action in a different Controller ? Any help would be appreciated.P.S . : I have been doing research about this issue for a while now and I 've read the solutions for questions such as : MVC RedirectToAction is not working properlyRedirectToAction gets ignoredBut none of these or the questions regarding the action not being redirected after an ajax request have helped me.Thanks . [ HttpGet ] public IActionResult SendEmailVerificationCode ( int userId ) { SpaceUser user = userManager.FindByIdAsync ( userId ) .Result ; bool taskComleted = SendEmailVerificationLink ( userId ) .IsCompleted ; if ( taskComleted ) { AddToErrorData ( InfoMessages.EmailVerificationLinkSent_Params , user.Email ) ; return RedirectToAction ( nameof ( HomeController.Index ) , `` Home '' ) ; } else { return RedirectToAction ( `` EmailNotConfirmed '' , new { userId = user.Id } ) ; } } [ HttpGet ] public IActionResult Index ( ) { return View ( ) ; }",AspNetCore MVC - return RedirectToAction is getting ignored "C_sharp : Lets say that I have a particular way of deciding whether some strings `` match '' , like this : I would like to pull matches out of a database using Linq To Entities and this helper . However , when I try this : I get `` LINQ to Entities does not recognize the method ... '' If I re-write the code as : Which is logically equivalent , then things work fine . The problem is that the code is n't as readable , and I have to re-write it for each different entity I want to match.As far as I can tell from questions like this one , what I want to do is impossible at the moment , but I 'm hoping that I 'm missing something , am I ? public bool stringsMatch ( string searchFor , string searchIn ) { if ( string.IsNullOrEmpty ( searchFor ) ) { return true ; } return searchIn ! = null & & ( searchIn.Trim ( ) .ToLower ( ) .StartsWith ( searchFor.Trim ( ) .ToLower ( ) ) || searchIn.Contains ( `` `` + searchFor ) ) ; } IQueryable < Blah > blahs = query.Where ( b = > stringsMatch ( searchText , b.Name ) ; IQueryable < Blah > blahs = query.Where ( b = > string.IsNullOrEmpty ( searchText ) || ( b.Name ! = null & & ( b.Name.Trim ( ) .ToLower ( ) .StartsWith ( searchText.Trim ( ) .ToLower ( ) ) || b.Name.Contains ( `` `` + searchText ) ) ) ;",How to stay DRY whilst using LINQ to Entities and helper methods ? "C_sharp : I have created a generic search extension method for IQueryable that enables you to search for a single property to see if a search term is contained within it . http : //jnye.co/Posts/6/c % 23-generic-search-extension-method-for-iqueryableI now want to enable the user to select multiple properties to search within each , matching if any property contains the text.The code : The user enters the following code to perform this search : This will return any golf club with 'Essex ' in the Name or as the County.The errorIf I change the number of parameters supplied to 1 : I get a new error : UPDATEI have written a post on the work discussed in this question . Check it out on GitHub too . string searchTerm = `` Essex '' ; context.Clubs.Search ( searchTerm , club = > club.Name , club = > club.County ) //Note : If possible I would rather something closer to the following syntax ... context.Clubs.Search ( club = > new [ ] { club.Name , club.County } , searchTerm ) ; // ... or , even better , something similar to this ... context.Clubs.Search ( club = > new { club.Name , club.County } , searchTerm ) ; public static IQueryable < TSource > Search < TSource > ( this IQueryable < TSource > source , string searchTerm , params Expression < Func < TSource , string > > [ ] stringProperties ) { if ( String.IsNullOrEmpty ( searchTerm ) ) { return source ; } // The lamda I would like to reproduce : // source.Where ( x = > x . [ property1 ] .Contains ( searchTerm ) // || x . [ property2 ] .Contains ( searchTerm ) // || x. [ property3 ] .Contains ( searchTerm ) ... ) //Create expression to represent x . [ property1 ] .Contains ( searchTerm ) var searchTermExpression = Expression.Constant ( searchTerm ) ; //Build parameters var parameters = stringProperties.SelectMany ( prop = > prop.Parameters ) ; Expression orExpression = null ; //Build a contains expression for each property foreach ( var stringProperty in stringProperties ) { var checkContainsExpression = Expression.Call ( stringProperty.Body , typeof ( string ) .GetMethod ( `` Contains '' ) , searchTermExpression ) ; if ( orExpression == null ) { orExpression = checkContainsExpression ; } //Build or expression for each property orExpression = Expression.OrElse ( orExpression , checkContainsExpression ) ; } var methodCallExpression = Expression.Call ( typeof ( Queryable ) , `` Where '' , new Type [ ] { source.ElementType } , source.Expression , Expression.Lambda < Func < TSource , bool > > ( orExpression , parameters ) ) ; return source.Provider.CreateQuery < TSource > ( methodCallExpression ) ; } Expression.Lambda < Func < TSource , bool > > ( orExpression , parameters.First ( ) ) ) ;",Generic Expression tree with 'OR ' clause for each supplied property "C_sharp : I am implementing an Hybrid mobile application in which I have to represent our Desktop application written in C # .When rounding off a value , the value differs between Desktop and Mobile application.ExampleCode used in C # : Code used in JS : How can I change the JS code to represent the value as in C # .Note : We can make C # to represent the value as in JS , using Math.Round ( 7060.625 , 2 , MidpointRounding.AwayFromZero ) ; But I have no option to change in there.EDIT 1Rounding off decimals is not fixed . It is chosen by user in mobile application . Math.Round ( 7060.625 , 2 ) ; // prints 7060.62Math.Round ( 7060.624 , 2 ) ; // prints 7060.62Math.Round ( 7060.626 , 2 ) ; // prints 7060.63 + ( 7060.625 ) .toFixed ( 2 ) ; // prints 7060.63 ( value differs ) + ( 7060.624 ) .toFixed ( 2 ) ; // prints 7060.62+ ( 7060.626 ) .toFixed ( 2 ) ; // prints 7060.63",How to apply C # equivalent rounding method in Javascript "C_sharp : If I run this code : I get a ArgumentNullException but if I run this code : it runs just fine and the output is an empty string.Now the two piece look equivalent to me - they both pass a null reference into String.Format ( ) yet the behavior is different.How id different behavior possible here ? Console.WriteLine ( String.Format ( `` { 0 } '' , null ) ) ; String str = null ; Console.WriteLine ( String.Format ( `` { 0 } '' , str ) ) ;",Why do I get an exception when passing `` null '' constant but not when passing a `` null '' string reference ? "C_sharp : Re-initialization within `` using '' block is a bad idea , to be avoided at all times . Still i am going to ask this : Why does `` using '' call dispose on the original value and not on the last reference or re-initialization ( which happens if try finally block is used ) In the above code dispose will be called on original reference and not the newer referenced . This can be easily verified by printing something on console in the dispose method.However with try { } finally code the last reference dispose method is called.MSDN : The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.Basically `` using '' translates to : MyClass b = new MyClass ( ) ; // implements IdisposableMyClass c = new MyClass ( ) ; MyClass a ; using ( a = new MyClass ( ) ) { a = b ; a = c ; } try { a = new MyClass ( ) ; a = b ; a = c ; } finally { a.Dispose ( ) ; } using ( Font font1 = new Font ( `` Arial '' , 10.0f ) ) { byte charset = font1.GdiCharSet ; } { Font font1 = new Font ( `` Arial '' , 10.0f ) ; try { byte charset = font1.GdiCharSet ; } finally { if ( font1 ! = null ) ( ( IDisposable ) font1 ) .Dispose ( ) ; } }",C # : using block : object re-initialization "C_sharp : How to write to the database on a timer in the background . For example , check mail and add new letters to the database . In the example , I simplified the code just before writing to the database.The class names from the example in Microsoft . The recording class itself : Timer class : Startup : It seems everything is done as in the example , but nothing is added to the database , which is not so ? namespace EmailNews.Services { internal interface IScopedProcessingService { void DoWork ( ) ; } internal class ScopedProcessingService : IScopedProcessingService { private readonly ApplicationDbContext _context ; public ScopedProcessingService ( ApplicationDbContext context ) { _context = context ; } public void DoWork ( ) { Mail mail = new Mail ( ) ; mail.Date = DateTime.Now ; mail.Note = `` lala '' ; mail.Tema = `` lala '' ; mail.Email = `` lala '' ; _context.Add ( mail ) ; _context.SaveChangesAsync ( ) ; } } } namespace EmailNews.Services { # region snippet1internal class TimedHostedService : IHostedService , IDisposable { private readonly ILogger _logger ; private Timer _timer ; public TimedHostedService ( IServiceProvider services , ILogger < TimedHostedService > logger ) { Services = services ; _logger = logger ; } public IServiceProvider Services { get ; } public Task StartAsync ( CancellationToken cancellationToken ) { _logger.LogInformation ( `` Timed Background Service is starting . `` ) ; _timer = new Timer ( DoWork , null , TimeSpan.Zero , TimeSpan.FromMinutes ( 1 ) ) ; return Task.CompletedTask ; } private void DoWork ( object state ) { using ( var scope = Services.CreateScope ( ) ) { var scopedProcessingService = scope.ServiceProvider .GetRequiredService < IScopedProcessingService > ( ) ; scopedProcessingService.DoWork ( ) ; } } public Task StopAsync ( CancellationToken cancellationToken ) { _logger.LogInformation ( `` Timed Background Service is stopping . `` ) ; _timer ? .Change ( Timeout.Infinite , 0 ) ; return Task.CompletedTask ; } public void Dispose ( ) { _timer ? .Dispose ( ) ; } } # endregion } services.AddHostedService < TimedHostedService > ( ) ; services.AddScoped < IScopedProcessingService , ScopedProcessingService > ( ) ;",Background task of writing to the database by timer "C_sharp : I have an application written using C # on the top of ASP.NET Core 2.2 framework.I am using Identity to user management and user control . Currently , everytime a user closed his/her browser and open the app again , they are required to log in again.I want to change the login from a session into a cookie that expired after 15 minutes of being inactive.Here is what I have added to the Startup classAs you can see above , I added the following I am expecting the ExpireTimeSpan code to convert my session-based login to cookie-based . Also expecting the cookie after 15 minutes if the user is inactive . The SlidingExpiration should update the cookie expiry time on every HTTP request.How can I convert my session-based login to cookie-based ? public void ConfigureServices ( IServiceCollection services ) { services.AddDbContext < ApplicationDbContext > ( options = > options.UseSqlServer ( Configuration.GetConnectionString ( `` DefaultConnection '' ) ) ) ; services.AddDefaultIdentity < User ( ) .AddEntityFrameworkStores < ApplicationDbContext > ( ) .AddDefaultTokenProviders ( ) ; services.AddAuthentication ( ) .AddFacebook ( facebookOptions = > { facebookOptions.AppId = Configuration [ `` Authentication : Facebook : AppId '' ] ; facebookOptions.AppSecret = Configuration [ `` Authentication : Facebook : AppSecret '' ] ; } ) ; services.Configure < CookiePolicyOptions > ( options = > { // This lambda determines whether user consent for non-essential cookies is needed for a given request . options.CheckConsentNeeded = context = > true ; options.MinimumSameSitePolicy = SameSiteMode.None ; } ) ; // This code should be executed after the identity id registered to work services.ConfigureApplicationCookie ( config = > { config.SlidingExpiration = true ; config.ExpireTimeSpan = TimeSpan.FromMinutes ( 15 ) ; config.Cookie.HttpOnly = true ; config.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx = > { if ( ctx.Request.Path.StartsWithSegments ( `` /api '' , StringComparison.CurrentCultureIgnoreCase ) ) { ctx.Response.StatusCode = ( int ) HttpStatusCode.Unauthorized ; } else { ctx.Response.Redirect ( ctx.RedirectUri ) ; } return Task.FromResult ( 0 ) ; } } ; } ) ; services.AddMvc ( ) .SetCompatibilityVersion ( CompatibilityVersion.Version_2_2 ) ; } config.SlidingExpiration = true ; config.ExpireTimeSpan = TimeSpan.FromMinutes ( 15 ) ; config.Cookie.HttpOnly = true ;",How to keep the session alive after the browser is closed for 15 minutes using Identity in Core 2.2 ? "C_sharp : When defining a generic type parameter 's constraints , we have to put class ( ) at the front and new ( ) at the end , for example.Why is this , why ca n't I put my constraints in any order ? Are there any other restrictions on ordering besides class/struct first , new ( ) at the end ? Example : protected T Clone < T > ( ) where T : class , ICopyable < T > , new ( )",Why is some ordering enforced in generic parameter constraints ? "C_sharp : this has been an ongoing problem with me , ive been trying to make a custom drawn form with nice transparency.this is as close as i can get right now , i started it just a half hour ago..Edit : i make custom form designs and controls from scratch , like my latest , Sunilla http : //i.stack.imgur.com/rqvDe.png . and i was wanting to have a good drop shadow on it , or make another design that looks kinda like windows areo.it sets the form.opacity to 0 % then it grabs an image of the screen ( anything on the screen , current running programs , desktop , etc ) directly behind the form every 500 milliseconds as of now , and sets it as the background and brings the transparency back to 100 % . so i can draw anything on it and it looks perfect ! but the only problem i get is when it does the work , it flickers . and yes i tried it with DoubleBuffering set to true , no difference.hears the main code : note : the ExtDrawing2D is a separate class that does a lot of the heavy work with drawing almost perfect round corners . AND is not the problem , i developed it half a year ago and in all my projects never had problems with it . result : if there is a better way of stabbing at this overall problem , id gladly love to hear it , altho i 've been looking around the web for a long time . using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Drawing.Drawing2D ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace TTTest { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } private void Form1_Load ( object sender , EventArgs e ) { Opacity = 100 ; } private void button1_Click ( object sender , EventArgs e ) { timer1.Enabled = ! timer1.Enabled ; } private void timer1_Tick ( object sender , EventArgs e ) { Opacity = 0 ; Bitmap img = new Bitmap ( this.Width , this.Height ) ; Graphics gr = Graphics.FromImage ( img ) ; gr.CopyFromScreen ( Location , Point.Empty , Size ) ; this.BackgroundImage = img ; Opacity = 100 ; } private void Form1_Paint ( object sender , PaintEventArgs e ) { Graphics g = e.Graphics ; g.SmoothingMode = SmoothingMode.AntiAlias ; ExtDrawing2D.FillRoundRect ( g , new SolidBrush ( Color.FromArgb ( 100 , 255 , 255 , 255 ) ) , new RectangleF ( 1 , 1 , Width - 3 , Height - 3 ) , 4f ) ; g.DrawPath ( new Pen ( Color.FromArgb ( 100 , 0 , 0 , 0 ) ) , ExtDrawing2D.GetRoundedRect ( new RectangleF ( 0 , 0 , Width - 1 , Height - 1 ) , 5f ) ) ; g.DrawPath ( new Pen ( Color.FromArgb ( 100 , 255,255,255 ) ) , ExtDrawing2D.GetRoundedRect ( new RectangleF ( 1,1 , Width - 3 , Height - 3 ) , 4f ) ) ; } private void button2_Click ( object sender , EventArgs e ) { timer1_Tick ( sender , e ) ; } private void panel1_Paint ( object sender , PaintEventArgs e ) { Graphics g = e.Graphics ; g.SmoothingMode = SmoothingMode.AntiAlias ; ExtDrawing2D.FillRoundRect ( g , new SolidBrush ( Color.FromArgb ( 150 , 255,255,255 ) ) , new RectangleF ( 1 , 1 , panel1.Width - 3 , panel1.Height - 3 ) , 2f ) ; g.DrawPath ( new Pen ( Color.FromArgb ( 100 , 0 , 0 , 0 ) ) , ExtDrawing2D.GetRoundedRect ( new RectangleF ( 0 , 0 , panel1.Width - 1 , panel1.Height - 1 ) , 3f ) ) ; g.DrawPath ( new Pen ( Color.FromArgb ( 100 , 255 , 255 , 255 ) ) , ExtDrawing2D.GetRoundedRect ( new RectangleF ( 1 , 1 , panel1.Width - 3 , panel1.Height - 3 ) , 2f ) ) ; } } }",How can i reduce flickering on updates to my True Transparency WinForm ? or is there a better way to do this ? "C_sharp : Should I be filtering my IQueryable results from the Domain Service ? For example ... My 3 portals ( Websites ) access the same Domain Service Layer , depending on the type of user it is , I call a specific repository method and return the result , Current Repository Layer : Would it be best just to do this in the Repository Layer : Then within the Domain Service , I simple do the filter i.e.NOTE : I have a read only session and session which includes CRUD within the Repository Layer , so please keep that in mind when answering.Second question : Should I do any filtering at all in the domain service layer ? This very layer is the only layer than can amend the Entity i.e . Product.Price == 25.00 ; This is not delegated to the repository layer . IQueryable < Products > GetAllProductsForCrazyUserNow ( CrazyUser id ) ; Products GetAProductForCrazyUserNow ( CrazyUser id , product id ) ; IQueryable < Products > GetProductsForNiceUserNow ( NiceUser id ) ; Products GetProductsForNiceUserNow ( NiceUser id , product id ) ; IQueryable < Products > GetAllProducts ( ) ; Products GetAProduct ( product id ) ; var Niceman = IQueryable < Products > GetAllProducts ( ) .Where ( u= > u.Name == `` Nice '' ) ;",MVC - Domain Service takes charge of filtering or does Repository Layer ? "C_sharp : I came across a interview question which i did not know the answer ( little help : ) ) well it stated something of the sort :1 ) Does the object get finalized when no longer referenced after the next GC ? My answer was NO , because the finalization thread will be stuck on the infinite loop.2 ) What could be done in the Dispose to end the finalization and how many times will the loop continue before the object is Disposed ( with out taking in to account the time it will spend in the next Gen ) I am not particularly clear of the exact question ( 2 ) .I kinda ran out of time ... Not knowing the answer I put a static counter that gets to 3 and calls break and stated 3 which technically would work : ) , but that 's not the answer I 'm guessing it as something to do with GC.SupressFinalize ( ) ? maybe calling GC.SupressFinalize ( ) before entering the loop ? any ideas if not on the answer to the unclear question , more as to what they might of been aiming for ? Class SomeClass : IDisposable { public void Dispose ( ) { while ( true ) { } } ~SomeClass ( ) { Dispose ( ) ; } }",Finalizer stuck in infinite loop "C_sharp : Before you react from the gut , as I did initially , read the whole question please . I know they make you feel dirty , I know we 've all been burned before and I know it 's not `` good style '' but , are public fields ever ok ? I 'm working on a fairly large scale engineering application that creates and works with an in memory model of a structure ( anything from high rise building to bridge to shed , does n't matter ) . There is a TON of geometric analysis and calculation involved in this project . To support this , the model is composed of many tiny immutable read-only structs to represent things like points , line segments , etc . Some of the values of these structs ( like the coordinates of the points ) are accessed tens or hundreds of millions of times during a typical program execution . Because of the complexity of the models and the volume of calculation , performance is absolutely critical . I feel that we 're doing everything we can to optimize our algorithms , performance test to determine bottle necks , use the right data structures , etc . etc . I do n't think this is a case of premature optimization . Performance tests show order of magnitude ( at least ) performance boosts when accessing fields directly rather than through a property on the object . Given this information , and the fact that we can also expose the same information as properties to support data binding and other situations ... is this OK ? Remember , read only fields on immutable structs . Can anyone think of a reason I 'm going to regret this ? Here 's a sample test app : result : Direct field access : 3262Property access : 24248Total difference : 20986Average difference : 0.00020986It 's only 21 seconds , but why not ? struct Point { public Point ( double x , double y , double z ) { _x = x ; _y = y ; _z = z ; } public readonly double _x ; public readonly double _y ; public readonly double _z ; public double X { get { return _x ; } } public double Y { get { return _y ; } } public double Z { get { return _z ; } } } class Program { static void Main ( string [ ] args ) { const int loopCount = 10000000 ; var point = new Point ( 12.0 , 123.5 , 0.123 ) ; var sw = new Stopwatch ( ) ; double x , y , z ; double calculatedValue ; sw.Start ( ) ; for ( int i = 0 ; i < loopCount ; i++ ) { x = point._x ; y = point._y ; z = point._z ; calculatedValue = point._x * point._y / point._z ; } sw.Stop ( ) ; double fieldTime = sw.ElapsedMilliseconds ; Console.WriteLine ( `` Direct field access : `` + fieldTime ) ; sw.Reset ( ) ; sw.Start ( ) ; for ( int i = 0 ; i < loopCount ; i++ ) { x = point.X ; y = point.Y ; z = point.Z ; calculatedValue = point.X * point.Y / point.Z ; } sw.Stop ( ) ; double propertyTime = sw.ElapsedMilliseconds ; Console.WriteLine ( `` Property access : `` + propertyTime ) ; double totalDiff = propertyTime - fieldTime ; Console.WriteLine ( `` Total difference : `` + totalDiff ) ; double averageDiff = totalDiff / loopCount ; Console.WriteLine ( `` Average difference : `` + averageDiff ) ; Console.ReadLine ( ) ; } }",Are public fields ever OK ? "C_sharp : I want to create an ASP.Net Web Application , and I want to write unit tests for it . But my unit test project ca n't see any of the types in my web application 's App_Code directory.Steps to reproduce ( skip down past the images if you already know how to create a default webforms web application and add an app_code folder ) Open Visual Studio . Choose File- > New- > Project.Choose Templates - > Visual C # - > Web . Choose ASP.Net Web Application . Choose `` OK '' .Choose `` Web Forms '' . Check `` Add unit tests '' . Click OK.In the solution explorer , right-click on the web application and choose `` Add - > Add ASP.Net Folder - > App_Code '' .Add a new item to App_Code , named `` Util.cs '' . Add a function to the file so the contents are : In the Unit Testing project , change UnitTest1.cs to : Then build the project.Expected behavior : The solution should build . If we attempt to test , the test should succeed.Actual behavior : The solution fails to build with The type or namespace name 'App_Code ' does not exist in the namespace 'WebApplication1 ' ( are you missing an assembly reference ? ) Other notesI looked at Unit Testing ASP.net Web Site Project code stored in App_Code , but I do n't think the problem exactly matches my circumstances because they 're testing a website and I 'm testing a web application . Some answers specifically suggest switching to a web application , implying that it would no longer be a problem : However , if you have the option of segregating the code into binaries ( class libraries ) or just using a web application , I 'd suggest that as a better alternative . I would either move this logic out to its own class library project or change the project type to Web Application , as Fredrik and Colin suggest . And as the OP stated it 's also possible to move to a Web App project , which i would say is cleaner as wellThe advice `` try using a web application '' does n't apply to me , because I 'm already using a web application , and it still does n't work.The answers also suggest `` Try moving the code out to its own project '' , and I do expect that would work , but in my actual solution I have dozens of files in the App_Code directory . I would prefer not to perform any serious structural changes before I can establish a testing framework first . using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; namespace WebApplication1.App_Code { public class Util { public static int getMeaningOfLife ( ) { return 42 ; } } } using System ; using Microsoft.VisualStudio.TestTools.UnitTesting ; namespace WebApplication1.Tests { [ TestClass ] public class UnitTest1 { [ TestMethod ] public void TestMethod1 ( ) { int result = WebApplication1.App_Code.Util.getMeaningOfLife ( ) ; if ( result ! = 42 ) { Assert.Fail ( ) ; } } } }",Unit Testing the App_Code of an ASP.Net Web Application "C_sharp : The simple demo below captures what I am trying to do . In the real program , I have to use the object initialiser block since it is reading a list in a LINQ to SQL select expression , and there is a value that that I want to read off the database and store on the object , but the object does n't have a simple property that I can set for that value . Instead it has an XML data store.It looks like I ca n't call an extension method in the object initialiser block , and that I ca n't attach a property using extension methods.So am I out of luck with this approach ? The only alternative seems to be to persuade the owner of the base class to modify it for this scenario.I have an existing solution where I subclass BaseDataObject , but this has problems too that do n't show up in this simple example . The objects are persisted and restored as BaseDataObject - the casts and tests would get complex.One of the answers ( from mattlant ) suggests using a fluent interface style extension method . e.g . : But will this work in a LINQ query ? public class BaseDataObject { // internal data store private Dictionary < string , object > attachedData = new Dictionary < string , object > ( ) ; public void SetData ( string key , object value ) { attachedData [ key ] = value ; } public object GetData ( string key ) { return attachedData [ key ] ; } public int SomeValue { get ; set ; } public int SomeOtherValue { get ; set ; } } public static class Extensions { public static void SetBarValue ( this BaseDataObject dataObject , int barValue ) { /// Can not attach a property to BaseDataObject ? dataObject.SetData ( `` bar '' , barValue ) ; } } public class TestDemo { public void CreateTest ( ) { // this works BaseDataObject test1 = new BaseDataObject { SomeValue = 3 , SomeOtherValue = 4 } ; // this does not work - it does not compile // can not use extension method in the initialiser block // can not make an exension property BaseDataObject test2 = new BaseDataObject { SomeValue = 3 , SomeOtherValue = 4 , SetBarValue ( 5 ) } ; } } // fluent interface stylepublic static BaseDataObject SetBarValueWithReturn ( this BaseDataObject dataObject , int barValue ) { dataObject.SetData ( `` bar '' , barValue ) ; return dataObject ; } // this worksBaseDataObject test3 = ( new BaseDataObject { SomeValue = 3 , SomeOtherValue = 4 } ) .SetBarValueWithReturn ( 5 ) ;",Is there any way to use an extension method in an object initializer block in C # "C_sharp : I 'm writing very processor-intensive cryptography code ( C # ) , so I 'm looking for any performance gains , no matter how small . I 've heard opinions both ways on this subject.Is there any performance benefit at all toover this ? Does the compiler do this already ? int smallPrime , spGen ; for ( int i = 0 ; i < numSmallPrimes ; i++ ) { smallPrime = smallPrimes [ i ] ; spGen = spHexGen [ i ] ; [ ... ] } for ( int i = 0 ; i < numSmallPrimes ; i++ ) { int smallPrime = smallPrimes [ i ] ; int spGen = spHexGen [ i ] ; [ ... ] }",Does moving variable declaration outside of a loop actually increase performance ? "C_sharp : I have the following setup ( which works fine ) . Using CodeFirst ( CTP4 ) . A template has a list of influences , each influence gives a value to a trait . Template is configured like this.This works but I 'd rather avoid the extra 'influences ' table . Essentially , 'Influences ' is simply an object and there does n't need to be a central store for them . In fact , it is more beneficial to the design I am trying to approach if there is not a central table for them . I wish to setup a scenario like this for the Template table ... Basically Influences do n't have their own table , they 're just mapped by Trait/Value where they are used.When I try to do it this way , I get the exception on the Template Mapping . System.InvalidOperationException was unhandled The given expression includes an unrecognized pattern 'influence.Trait.Id ' . Below is the entire project code , if needed . public class Template { public virtual int Id { get ; set ; } public virtual ICollection < Influence > Influences { get ; set ; } } public class Influence { public virtual int Id { get ; set ; } public virtual Trait Trait { get ; set ; } public virtual int Value { get ; set ; } } public class Trait { public virtual int Id { get ; set ; } public virtual string Name { get ; set ; } } public class TemplateConfiguration : EntityConfiguration < Template > { public TemplateConfiguration ( ) { HasKey ( o = > o.Id ) ; Property ( o = > o.Id ) .IsIdentity ( ) ; HasMany ( o = > o.Influences ) .WithRequired ( ) .Map ( `` templates.influences '' , ( template , influence ) = > new { Template = template.Id , Influence = influence.Id } ) ; MapSingleType ( o = > new { o.Id } ) ; } } public TemplateConfiguration ( ) { HasMany ( u = > u.Influences ) .WithMany ( ) .Map ( `` templates.influences '' , ( template , influence ) = > new { Template = template.Id , Trait = influence.Trait.Id , Value = influence.Value } ) ; MapSingleType ( c = > new { c.Id } ) .ToTable ( `` templates '' ) ; } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Data.Objects ; using System.Data.EntityClient ; using System.Data.Entity.ModelConfiguration ; using System.Data.Entity ; using System.Data.Entity.Infrastructure ; namespace EFTest { class Program { static void Main ( string [ ] args ) { Database.SetInitializer < SampleDataContext > ( new AlwaysRecreateDatabase < SampleDataContext > ( ) ) ; var builder = new ModelBuilder ( ) ; builder.Configurations.Add ( new TraitConfiguration ( ) ) ; builder.Configurations.Add ( new InfluenceConfiguration ( ) ) ; builder.Configurations.Add ( new TemplateConfiguration ( ) ) ; var model = builder.CreateModel ( ) ; using ( var context = new SampleDataContext ( model ) ) { var traits = new List < Trait > { new Trait { Name = `` Years '' } , new Trait { Name = `` Days '' } } ; traits.ForEach ( x = > { context.Traits.Add ( x ) ; } ) ; context.SaveChanges ( ) ; var templates = new List < Template > { new Template { Influences = new List < Influence > { new Influence { Trait = context.Traits.Single ( i = > i.Name == `` Years '' ) , Value = 5 } , new Influence { Trait = context.Traits.Single ( i = > i.Name == `` Days '' ) , Value = 15 } } } } ; templates.ForEach ( x = > { context.Templates.Add ( x ) ; } ) ; context.SaveChanges ( ) ; } } } public class SampleDataContext : DbContext { public SampleDataContext ( DbModel model ) : base ( model ) { } public DbSet < Trait > Traits { get ; set ; } public DbSet < Influence > Influences { get ; set ; } public DbSet < Template > Templates { get ; set ; } } public class Trait { public virtual int Id { get ; set ; } public virtual string Name { get ; set ; } } public class TraitConfiguration : EntityConfiguration < Trait > { public TraitConfiguration ( ) { HasKey ( o = > o.Id ) ; Property ( o = > o.Id ) .IsIdentity ( ) ; MapSingleType ( o = > new { o.Id , o.Name } ) ; } } public class Influence { public virtual int Id { get ; set ; } public virtual Trait Trait { get ; set ; } public virtual int Value { get ; set ; } } public class InfluenceConfiguration : EntityConfiguration < Influence > { public InfluenceConfiguration ( ) { HasKey ( o = > o.Id ) ; Property ( o = > o.Id ) .IsIdentity ( ) ; HasRequired ( o = > o.Trait ) ; Property ( o = > o.Value ) ; MapSingleType ( o = > new { o.Id , Trait = o.Trait.Id , o.Value } ) ; } } public class Template { public virtual int Id { get ; set ; } public virtual ICollection < Influence > Influences { get ; set ; } } public class TemplateConfiguration : EntityConfiguration < Template > { public TemplateConfiguration ( ) { HasKey ( o = > o.Id ) ; Property ( o = > o.Id ) .IsIdentity ( ) ; HasMany ( o = > o.Influences ) .WithRequired ( ) .Map ( `` templates.influences '' , ( template , influence ) = > new { Template = template.Id , Influence = influence.Id } ) ; MapSingleType ( o = > new { o.Id } ) ; } } }","Many to Many Relationships without Double Junction Tables , Entity Framework" "C_sharp : I have a handler for Application.ThreadException , but I 'm finding that exceptions are n't always getting passed to it correctly . Specifically , if I throw an exception-with-inner-exception from a BeginInvoke callback , my ThreadException handler does n't get the outer exception -- it only gets the inner exception.Example code : If I uncomment the throw outer ; line and click the button , then the messagebox shows the outer exception ( along with its inner exception ) : System.Exception : Outer -- - > System.Exception : Inner -- - End of inner exception stack trace -- - at WindowsFormsApplication1.Form1.button1_Click ( Object sender , EventArgs e ) in C : \svn\trunk\Code Base\Source.NET\WindowsFormsApplication1\Form1.cs : line 55 at System.Windows.Forms.Control.OnClick ( EventArgs e ) at System.Windows.Forms.Button.OnClick ( EventArgs e ) at System.Windows.Forms.Button.OnMouseUp ( MouseEventArgs mevent ) at System.Windows.Forms.Control.WmMouseUp ( Message & m , MouseButtons button , Int32 clicks ) at System.Windows.Forms.Control.WndProc ( Message & m ) at System.Windows.Forms.ButtonBase.WndProc ( Message & m ) at System.Windows.Forms.Button.WndProc ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage ( Message & m ) at System.Windows.Forms.Control.ControlNativeWindow.WndProc ( Message & m ) at System.Windows.Forms.NativeWindow.Callback ( IntPtr hWnd , Int32 msg , IntPtr wparam , IntPtr lparam ) But if the throw outer ; is inside a BeginInvoke call , as in the above code , then the ThreadException handler only gets the inner exception . The outer exception gets stripped away before ThreadException is called , and all I get is : System.Exception : Inner ( There 's no call stack here because inner never got thrown . In a more realistic example , where I caught one exception and wrapped it to re-throw , there would be a call stack . ) The same thing happens if I use SynchronizationContext.Current.Post instead of BeginInvoke : the outer exception is stripped off , and the ThreadException handler only gets the inner exception.I tried wrapping more layers of exceptions around the outside , in case it was just stripping off the outermost exception , but it did n't help : apparently somewhere there 's a loop doing something along the lines of while ( e.InnerException ! = null ) e = e.InnerException ; .I 'm using BeginInvoke because I 've got code that needs to throw an unhandled exception to be immediately handled by ThreadException , but this code is inside a catch block higher up the call stack ( specifically , it 's inside the action for a Task , and Task will catch the exception and stop it from propagating ) . I 'm trying to use BeginInvoke to delay the throw until the next time messages are processed in the message loop , when I 'm no longer inside that catch . I 'm not attached to the particular solution of BeginInvoke ; I just want to throw an unhandled exception.How can I cause an exception -- including its inner exception -- to reach ThreadException even when I 'm inside somebody else 's catch-all ? ( I ca n't call my ThreadException-handler method directly , due to assembly dependencies : the handler is hooked by the EXE 's startup code , whereas my current problem is in a lower-layer DLL . ) public Form1 ( ) { InitializeComponent ( ) ; Application.ThreadException += ( sender , e ) = > MessageBox.Show ( e.Exception.ToString ( ) ) ; } private void button1_Click ( object sender , EventArgs e ) { var inner = new Exception ( `` Inner '' ) ; var outer = new Exception ( `` Outer '' , inner ) ; //throw outer ; BeginInvoke ( new Action ( ( ) = > { throw outer ; } ) ) ; }",Prevent outer exception from being discarded when thrown from BeginInvoke "C_sharp : I have got following code : I have a enum : and m using this enum like this : please tell me what is keyword `` default '' is doing here ? what is the use of it ? public enum HardwareInterfaceType { Gpib = 1 , Vxi = 2 , GpibVxi = 3 , } HardwareInterfaceType type = default ( HardwareInterfaceType ) ;",Please tell me what is use of `` default '' keyword in c # .net C_sharp : In the following example when the `` Submit '' button is clicked the value of the static variable Count is incremented . But is this operation thread safe ? Is using Appliation object the proper way of doing such operation ? The questions are applicable to Web form application s as well.The count always seem to increase as I click the Submit button.View ( Razor ) : Controller : Static Class : @ { Layout = null ; } < html > < body > < form > < p > @ ViewBag.BeforeCount < /p > < input type= '' submit '' value= '' Submit '' / > < /form > < /body > < /html > public class HomeController : Controller { public ActionResult Index ( ) { ViewBag.BeforeCount = StaticVariableTester.Count ; StaticVariableTester.Count += 50 ; return View ( ) ; } } public class StaticVariableTester { public static int Count ; },Is this operation thread safe ? C_sharp : For example : How would this translate once it is compiled ? What happens behind the scenes ? var query = from c in db.Cars select c ; foreach ( Car aCar in query ) { Console.WriteLine ( aCar.Name ) ; },How is LINQ compiled into the CIL ? "C_sharp : I 'm using the following code : Where IsValidToken ( ) compares the public key token of the assembly being loaded against a list of authorized public key tokens hardcoded in my application as byte arrays . Is this a good security measure to prevent code injection attacks ? Also , is this necessary given the fact that I will later obfuscate my application using NetReactor ? I 'm trying to prevent any `` snooping '' into my application , not only coming from the Snoop tool , but from any external undesired sources as well . AppDomain.CurrentDomain.AssemblyLoad += ( sender , args ) = > { var token = args.LoadedAssembly.GetName ( ) .GetPublicKeyToken ( ) ; if ( ! IsValidToken ( token ) ) { Process.GetCurrentProcess ( ) .Kill ( ) ; } } ;",Prevent external assembly injection via PublicKeyToken "C_sharp : What is the use of the private keyword if everything , by default , is private ? Would n't both of the above be private ? If they 're both private then why the need for the keyword itself ? public class A { object someObject ; private object someOtherObject ; }",private keyword vs no private keyword "C_sharp : I have my tags desinged like this in my database : if I wanted to know the count of each tag such as how stackoverflow counts their tags how would I do it ? What kind of query would I perform . I am open to both regular sql and linq Table : Item Columns : ItemID , Title , Content Table : Tag Columns : TagID , Title Table : ItemTag Columns : ItemID , TagID//example -- this is the right sidebar of stackoverflowc # × 59279sql × 14885asp.net-mvc × 9123linq × 4337tags × 339",How to implement tag counting C_sharp : Is there any difference between below two statementsandIf both treated same which will be preferable ? if ( null ! = obj ) if ( obj ! = null ),Conditional Statements difference "C_sharp : I have a console app written in C # . I need to get some of the information from a SharePoint site . This instance of SharePoint is part of Office 365 ( i.e . SharePoint Online ) . My challenge is , I ca n't use the helper library . I have to use the REST-based APIs since I 'm using .NET Core.To begin , I registered my console app with Azure Active Directory . This console app is created in the same Azure Active Directory that my Office 365 environment is part of . I 've also granted the `` Read items in all site collections '' delegated permission for the `` Office 365 SharePoint Online '' API to my console app . In my situation , I have a console app sitting on a server . I 've set up a test user with a username/password on my SharePoint tenant . I also have the Client ID for the console app I registered with Azure Active Directory and a Redirect URL.At this time , I have some code that looks like this : I feel like I 'm close since I 'm getting an access token . I just ca n't seem to figure out how to get the title of the site . How do I get the title of a SharePoint Site from my C # code ? var accessToken = await GetToken ( ) ; // retrieves a token from Active Directoryusing ( var client = new HttpClient ( ) ) { client .DefaultRequestHeaders .Clear ( ) ; client .DefaultRequestHeaders .Authorization = new AuthenticationHeaderValue ( `` Bearer '' , accessToken ) ; client .DefaultRequestHeaders .Accept .Add ( new MediaTypeWithQualityHeaderValue ( `` application/json '' ) ) ; var apiUrl = `` https : // [ mySite ] .sharepoint.com/_api/web '' ; // how do I get the title of the site at the apiUrl variable ? }",Get Title of SharePoint Site from Console App "C_sharp : I 've got an extension method that used to take a strongly typed Expression < Func < > > parameter however for implementation reasons I had to change it to use a weakly type version . This has had a strange affect on the expression parameter as it now seems to be wrapping the lambda expression in an explicit call to a 'Convert ' method.Previously the paramters would look like : And now it looks like the following : I have replicated the issue with the following example code : The output of which is as follows : I am guessing it has something to do with auto boxing the value type into an object type . Can anyone confirm this or does anyone know what is going on ? Also does anyone know where the Convert method is declared ? Calling the compile method on the weak typed expression gives the following : m = > m.Data m = > Convert ( m.Data ) using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Linq.Expressions ; namespace ConsoleApplication { static class Program { static void Main ( string [ ] args ) { Model model = new Model ( ) { Data = 123 } ; Test ( m = > m.Data , m = > m.Data ) ; Console.ReadLine ( ) ; } public static void Test < TProperty > ( Expression < Func < Model , TProperty > > strongTyped , Expression < Func < Model , object > > weakTyped ) { Console.WriteLine ( `` Strong Typed : { 0 } '' , strongTyped ) ; Console.WriteLine ( `` Weak Typed : { 0 } '' , weakTyped ) ; } } public class Model { public int Data { get ; set ; } } } Strong Typed : m = > m.DataWeak Typed : m = > Convert ( m.Data ) weakTyped.Compile ( ) .Method { System.Object lambda_method ( System.Runtime.CompilerServices.Closure , ConsoleApplication.Model ) } [ System.Reflection.Emit.DynamicMethod.RTDynamicMethod ] : { System.Object lambda_method ( System.Runtime.CompilerServices.Closure , ConsoleApplication.Model ) } base { System.Reflection.MethodBase } : { System.Object lambda_method ( System.Runtime.CompilerServices.Closure , ConsoleApplication.Model ) } MemberType : Method ReturnParameter : null ReturnType : { Name = `` Object '' FullName = `` System.Object '' } ReturnTypeCustomAttributes : { System.Reflection.Emit.DynamicMethod.RTDynamicMethod.EmptyCAHolder }",Lambda Expression Delegate Strong Type vs Weak Type implicit Convert Method C_sharp : I 'd like to dynamically set a list of custom event handlers something like this in pseudo-code : I ca n't find the right syntax can you ? FieldInfo [ ] fieldInfos = this.GetType ( ) .GetFields ( BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly ) ; foreach ( FieldInfo fieldInfo in fieldInfos ) { if this.fieldInfo.GetType ( ) = TypeOf ( CustomEventHandler < this.fieldInfo.Name > ) { this.fieldInfo.Name += new CustomEventHandler < this.fieldInfo.Name > ( OnChange < this.fieldInfo.Name > ) ; } },How to set an event handler dynamically using Reflection "C_sharp : I wanted to add some cool characters to the names and added in my web.config a picture of a cow , like this.However , when I start the application , I get an exception on this line in my _Layout.cshtml nagging about localization and such.I 'm not sure how to handle this . Apparently , the MVC hates cows but what can I do about it ? I 've tried to follow the suggested syntax according to the standard . I also added UTF-16 at the top of the config file . < add key= '' SenderName '' value= '' & # x1f3eb ; Mr Mooo '' / > @ Styles.Render ( `` ~/Content/css '' )",How to allow unicode characters in web.config for my MVC application ? "C_sharp : I 'm trying to create a new SQL Server with the Azure Fluent API ( https : //github.com/Azure/azure-sdk-for-net/tree/Fluent ) but I always get a Microsoft.Rest.Azure.CloudException . Everything else ( Creating Storage Account , App Services , Resource Groups ) works fine - it 's just the SQL part which does not work.But when trying to create the server I got an exception : ISqlServer sqlServer = await Azure.SqlServers .Define ( serverName ) .WithRegion ( regionName ) .WithExistingResourceGroup ( rgName ) .WithAdministratorLogin ( administratorLogin ) .WithAdministratorPassword ( administratorPassword ) .WithNewElasticPool ( elasticPoolName , elasticPoolEdition ) .CreateAsync ( ) ; { Microsoft.Rest.Azure.CloudException : Invalid value for header ' x-ms-request-id ' . The header must contain a single valid GUID . at Microsoft.Azure.Management.Sql.Fluent.ServersOperations. < CreateOrUpdateWithHttpMessagesAsync > d__10.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.Management.Sql.Fluent.ServersOperationsExtensions. < CreateOrUpdateAsync > d__11.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.Management.Sql.Fluent.SqlServerImpl. < CreateResourceAsync > d__53.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.Creatable ` 4. < Microsoft-Azure-Management-ResourceManager-Fluent-Core-ResourceActions-IResourceCreator < IResourceT > -CreateResourceAsync > d__15.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.Management.ResourceManager.Fluent.Core.DAG.CreatorTaskItem ` 1. < ExecuteAsync > d__6.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at Microsoft.Azure.Management.ResourceManager.Fluent.Core.DAG.TaskGroupBase ` 1. < ExecuteNodeTaskAsync > d__14.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter ` 1.GetResult ( ) at XircuitAPI.Controllers.AzureSqlServerController. < Create > d__9.MoveNext ( ) in C : \Users\ThimoBuchheister\Documents\Code\Xircuit\xircuit\XircuitAPI\Controllers\AzureSqlServerController.cs : line 235 }",Azure Fluent API Error creating SQL Server - Missing x-ms-request-id header C_sharp : Is there a good reason ( advantage ) for programming this stylevsI have seen it many times but to me it just seem overly verbose XmlDocument doc = null ; doc = xmlDocuments [ 3 ] ; XmlDocument doc = xmlDocuments [ 3 ] ;,C # programming style question - Assignment of Null Before Real Assignment "C_sharp : I am struggling to find an easy and efficient solution to calculating the week day of a month . For example , if a given date is the first Monday Monday 5th March 2018 then I want to get the date for each first Monday of a month for the next 6 months e.g : Monday 2nd April 2018 and Monday 3rd May 2018 and so on . I have tried to use the following code from this question . However , the code below only returns the week number I would like it to return the whole date . But I am confused and do n't know how I can modify the above code to solve this issue . Any help will be appreciated . static class DateTimeExtensions { static GregorianCalendar _gc = new GregorianCalendar ( ) ; public static int GetWeekOfMonth ( this DateTime time ) { DateTime first = new DateTime ( time.Year , time.Month , 1 ) ; return time.GetWeekOfYear ( ) - first.GetWeekOfYear ( ) + 1 ; } static int GetWeekOfYear ( this DateTime time ) { return _gc.GetWeekOfYear ( time , CalendarWeekRule.FirstDay , DayOfWeek.Monday ) ; } }",Calculate the Week day of months from given date ? "C_sharp : What I have is simple switch statementIn this situation compiler tells me that local variable myControl might not be initialized before accessingSo , what is the best way to avoid this situation ? One option is to initialize myControl before switch statement . But in this case I do one more unnecessary initalization.CASE 1 : Next option is to change second case with default . After that compiler will `` understand '' that myControl will be anyway initialized and will not throw exception.CASE 2 : But this case does n't look so good , because after adding some new properties to my enum it will do default for all other types ( developer can easily forget to change code here or it can be not necessary to initialize myControl for other enum types ) .What is best approach in such situations ? Control myControl ; switch ( x ) { case TabType.Edit : { myControl= ... ; } case TabType.View : { myControl= ... ; } } myPageView.Controls.Add ( myControl ) ; Control myControl = null ; switch ( x ) { case TabType.Edit : { myControl= ... ; } case TabType.View : { myControl= ... ; } } myPageView.Controls.Add ( myControl ) ; Control myControl ; switch ( x ) { case TabType.Edit : { myControl= ... ; } default : { myControl= ... ; } } myPageView.Controls.Add ( myControl ) ;",Variable initialization issue in switch statement "C_sharp : I have an interface defined as IStore , with two methods : I want an event to be raised on the success of Put ( for reference , Put could store a row in a db , or file on the file system etc ... ) So , a class implementing Istore for type of Product would look a bit like this : What i 'm after , is a way of ensuring that every implementation of IStore raises the event -should i have an abstract class instead , or as well as , the interface ? public interface IStore < TEntity > { TEntity Get ( object identifier ) ; void Put ( TEntity entity ) ; } class MyStore : IStore < Product > { public Product Get ( object identifier ) { //whatever } public void Put ( Product entity ) { //Store the product in db //RAISE EVENT ON SUCCESS } }",C # - Interfaces / Abstract class - ensure event is raised on method "C_sharp : When I call a method of my WCF Soap service , an error is thrown and a error appears in the svlog file : Type 'xxx.ActiveDirectoryService.classes.WCF.Message ' with data contract name 'Message : http : //schemas.datacontract.org/2004/07/xxx.ActiveDirectoryService.classes.WCF ' is not expected . Consider using a DataContractResolver or add any types not known statically to the list of known types - for example , by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.I tried to use KnownType here and there but with no success ( I must admit I 'm not too sure I got its usage 100 % right ) .Here are my Interface/classes : Edit : 12AM35 GMT+1I added Dummy ( ) method.Calling Dummy from client works fine.Calling Dummy2 from client works fine.Calling Dummy3 from client causes the same error.Edit 12AM39 GMT+1Making the following changes did n't help.Edit : 13AM31 GMT+1If I set Dummy3 return type to Message , calls to Dummy3 in client code work.There 's something odd with WCF + Polymorphism ... [ ServiceContract ] public interface IActiveDirectory { [ OperationContract ] [ WebGet ] void Dummy ( ) ; [ OperationContract ] [ WebGet ] AbstractMessage Dummy2 ( ) ; [ OperationContract ] [ WebGet ] AbstractMessage Dummy3 ( ) ; [ OperationContract ] [ WebGet ] AbstractMessage SetPassWord ( string customer , string customerPassword , string userLogin , string userPassword ) ; } [ DataContract ] public abstract class AbstractMessage { [ DataMember ] public virtual bool IsError { get ; set ; } [ DataMember ] public virtual string ErrorMessage { get ; set ; } [ DataMember ] public virtual string ReturnValue { get ; set ; } } public class Message : AbstractMessage { < ... > } [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.Single , ConcurrencyMode = ConcurrencyMode.Multiple ) ] [ KnownType ( typeof ( AbstractMessage ) ) ] public class ActiveDirectory : IActiveDirectory { public void Dummy ( ) { } public AbstractMessage Dummy2 ( ) { return new AbstractMessage ( ) ; } public AbstractMessage Dummy3 ( ) { return new Message ( ) ; } public AbstractMessage SetPassWord ( string customer , string customerPassword , string userLogin , string userPassword ) { < ... > return message ; // message is of type Message } } [ DataContract ] [ KnownType ( typeof ( AbstractMessage ) ) ] public class Message : AbstractMessage [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.Single , ConcurrencyMode = ConcurrencyMode.Multiple ) ] [ KnownType ( typeof ( AbstractMessage ) ) ] [ KnownType ( typeof ( Message ) ) ] public class ActiveDirectory : IActiveDirectory",WCF trouble with Types ? "C_sharp : I need to know how to create API 's dynamically by calling another API then passing [ API name ] and [ API parameters ] , let 's we assume that we have this API , like the one shown here : Here are the models : Now what needs to be done , is to create dynamic API in controller.So then we would have the API created they can be called from their URL like this Can you please provide me some insight of this . [ HttpPost ( `` GenerateApi '' ) ] [ ProducesResponseType ( 200 ) ] [ ProducesResponseType ( 500 ) ] public IActionResult GenerateApi ( RootObject ro ) { //Here I need piece of code to create API dynamically return Ok ( new { ro.apiName , ro.parameters } ) ; } public class RootObject { public string apiName { get ; set ; } public List < parameter > parameters { get ; set ; } } public class parameter { public string parameterName { get ; set ; } public dynamic parameterType { get ; set ; } } www.example.com/api/v1/ [ controller ] / [ apiName ] / { [ parameter1_value ] } / { [ parameter2_value ] }",How can I create dynamic API 's in ASP.net Core 2 "C_sharp : When building a view model in asp.net 's MVC3 , where should the code go to instantiate the objects of that view model ? I am doing it mostly in the controller right now , aside from the code to query the database . Here is an example in code : View Model : Controller Code : Generic Select List is a simple class to hold the data that goes in the helper @ html.dropdownfor 's SelectList . I build these selectlist 's , and also build similar data configurations for view models inside of the controller code . The controller hosting this code has a total of 109 lines of code , so it is not huge or out of control . However , I am always striving to reduce redundancy and sometimes the code in //build employee list ends up being copy pasted ( ugh , i hate copy paste ) into other controllers.Is there a better place to have this code ? Should I maybe be using the factory pattern to build the data for these selectlists / other view data objects ? EDITThanks for all your help . Here is what I ended up doing . I ended up making a method inside the generic select list class very similar to the .ToSelectList ( ... ) suggested by Richard and Jesse : public class WorkListVM { //list for employees [ Display ( Name = `` Select A Employee '' ) ] [ Required ] public int ? EmployeeId { get ; set ; } public GenericSelectList EmployeeList { get ; set ; } } //build view model var vm = new WorkListVM ( ) ; //build employee list vm.EmployeeList = new GenericSelectList ( 0 , '' -- Select Employee -- '' ) ; var employees = new List < Employee > ( ) ; using ( var gr = new GenericRepo < Employee > ( ) ) { employees = gr.Get ( ) .ToList ( ) ; } foreach ( var employee in employees ) { var gl = new GenericListItem ( ) ; gl.Id = employee.EmployeeId ; gl.DisplayFields = employee.FirstName + `` `` + employee.LastName ; vm.EmployeeList.Values.Add ( gl ) ; } public class GenericSelectList { public List < GenericListItem > Values { get ; set ; } public int StartValue { get ; set ; } public string Message { get ; set ; } public GenericSelectList ( int StartValue = 0 , string Message = `` select '' ) { Values = new List < GenericListItem > ( ) ; this.StartValue = StartValue ; this.Message = Message ; } public void BuildValues < T > ( List < T > items , Func < T , int > value , Func < T , string > text ) where T : class { this.Values = items.Select ( f = > new GenericListItem ( ) { Id = value ( f ) , DisplayFields = text ( f ) } ) .ToList ( ) ; } }",Where should code to build view models go ? "C_sharp : There 's something unclear to me about the inner workings of TaskCompletionSource < > .When creating a simple Task < > using the Factory , I expect this task to be enqueued in a thread pool , unless I specify TaskCreationOptions.LongRunning , where it will run in a new thread instead.My understanding of TaskCompletionSource , is that I am responsible of triggering when a task ends , or fails , and I have full control on how to manage threads.However , the ctor of TaskCompletionSource allows me to specify a TaskCreationOptions , and this confuse me , since I was expecting the Scheduler not being able to handle the task itself.What is the purpose of TaskCreationOptions in the context of a TaskCompletionSource < > ? Here is an example of use : public Task < WebResponse > Download ( string url ) { TaskCompletionSource < WebResponse > tcs = new TaskCompletionSource < WebResponse > ( TaskCreationOptions.LongRunning ) ; var client = ( HttpWebRequest ) HttpWebRequest.Create ( url ) ; var async = client.BeginGetResponse ( o = > { try { WebResponse resp = client.EndGetResponse ( o ) ; tcs.SetResult ( resp ) ; } catch ( Exception ex ) { tcs.SetException ( ex ) ; } } , null ) ; return tcs.Task ; }",What is the purpose of TaskCreationOptions with a TaskCompletionSource ? "C_sharp : I have a base abstract class that also implements a particular interface.Then I have inherited classes some of which have to override interface implementation methods of the base class.My interface methods return the same object instance after it 's moved so I can use chaining or do something directly in return statement without using additional variables.QuestionAs you can see in my example my overrides in child class returns base class type instead of running class . This may require me to cast results , which I 'd like to avoid.How can I define my interface and implementations so that my overrides will return the actual type of the executing instance ? public interface IMovable < TEntity , T > where TEntity : class where T : struct { TEntity Move ( IMover < T > moverProvider ) ; } public abstract class Animal : IMovable < Animal , int > { ... public virtual Animal Move ( IMover < int > moverProvider ) { // performs movement using provided mover } } public class Snake : Animal { ... public override Animal Move ( IMover < int > moverProvider ) { // perform different movement } } // I do n't want this if methods would be void typedvar s = GetMySnake ( ) ; s.Move ( provider ) ; return s ; // I do n't want this either if at all possiblereturn ( Snake ) GetMySnake ( ) .Move ( provider ) ; // I simply want thisreturn GetMySnake ( ) .Move ( provider ) ; public Snake Move ( IMover < int > moverProvider ) { }",Avoid explicit type casting when overriding inherited methods "C_sharp : I would like to have a nice clean LINQ code that can get an array of the index values of the top 1000 largest values inside an array.For example : The code is obviously bogus it is just to illustrate what I need.UPDATEI totally forgot to say that I need a second functionality . I have a second array , and I need to retrieve all the values in the second array which has the same indexes as contained inside the IndexArray.I can do it easily using loops and all that but the code is big , and I want to learn to use LINQ more often but at the moment LINQ is still very foreign to me.I have gone through similar questions asked here but I was not able to modify the code to suite my needs , since people usually only need the values and not the indexes of the values.Thanks for the help ! int [ ] IndexArray = ArrayWithValues.Return_Indexes_Of_1000_Biggest_Values",Get array index values of the top 1000 largest entries inside an array using LINQ "C_sharp : I 'm trying to convert some code from just creating a new thread to run a function to making it use a Thread Pool or even the Task Paralleling Library . I 'm doing this since I know that despite the Worker Thread 's Function may run indefinitely ( in theory ) , each thread will spend most of it 's time doing nothing . I also want something to minimize the overhead for the creation and destruction of the Worker Threads , as connections may timeout or new ones get created . That - and seeing CLRProfiler show 7836 threads were finalized in/after a 62 hour test run is a little unnerving , with a single ( if finicky ) device sending a message.Here 's what I want to do : Main Thread.1 . ) Have a TCPListener accept a TcpClient2 . ) Fire off a Worker Thread which uses that TcpClient3 . ) Go back to step 1 if we have n't been told to stop.Worker Thread ( To used in the Pool/Tasks ) 1 . ) Check to see if we have a message from the TcpClient2 . ) If so , parse message , send off to database , and sleep for 1 second.3 . ) Otherwise , sleep for 1 millisecond.4 . ) Go back to step 1 if we have n't been told to stop and have not timed out.Here 's the original approach : I 've tried replacing the universalListener.BeginAcceptTcpClient ( ... ) et . all withas well as removing the AutoResetEvent connectionWaitHandle code , but the Worker Thread seemed to only fire once.I 'm also a little unsure if I should even try to use a Thread Pool or a Task , as everything I could find about Thread Pools and Tasks ( official documentation or otherwise ) seems to indicate they should be used with threads that have an extremely short lifespan.My questions are : Is the Thread Pool or even Tasks from the Task Parallel Library appropriate for Long-lived , but mostly wheel spinning , Threads ? If so , how would I best implement the correct pattern ? If so , did I have the right idea on using TaskFactory.FromAsync ( ... ) .ContinueWith ( ... ) ? private AutoResetEvent connectionWaitHandle = new AutoResetEvent ( false ) ; private static bool stop = false ; private void MainThread ( ) { TcpListener universalListener = new TcpListener ( IPAddress.Any , currentSettings.ListeningPort ) ; universalListener.Start ( ) ; while ( ! stop ) { IAsyncResult result = universalListener.BeginAcceptTcpClient ( WorkerThread , universalListener ) ; connectionWaitHandle.WaitOne ( ) ; connectionWaitHandle.Reset ( ) ; } } private void WorkerThread ( IAsyncResult result ) { TcpListener listener = result.AsyncState as TcpListener ; if ( listener == null ) { connectionWaitHandle.Set ( ) ; return ; } TcpClient client = listener.EndAcceptTcpClient ( result ) ; connectionWaitHandle.Set ( ) ; NetworkStream netStream = null ; bool timedout = false ; try { while ( ! timedout & & ! stop ) { if ( client.Available > 0 ) { netStream = client.GetStream ( ) ; //Get and Parse data here , no need to show this code //The absolute fastest a message can come in is 2 seconds , so we 'll sleep for one second so we are n't checking when we do n't have to . Thread.Sleep ( 1000 ) ; } else { //Sleep for a millisecond so we do n't completely hog the computer 's resources . Thread.Sleep ( 1 ) ; } if ( /*has timed out*/ ) { timedout = true ; } } } catch ( Exception exception ) { //Log Exception } finally { client.Close ( ) ; } } ( new Task.TaskFactory.FromAsync < TCPClient > ( universalListener.BeginAcceptTcpClient , universalListener.EndAcceptTcpClient , universalListener ) .ContinueWith ( WorkerThread ) ;",Would a ThreadPool or a Task be the correct thing to use for a server ? "C_sharp : I have a requirement to return a 400 error from an ASP.NET Web API Post request when the request Json contains duplicate keys.For instance if the request wasthen I would want the error to be thrown due to there being two `` key2 '' keys.My controller method looks something likeand my RequestModel model likeIn the example above the Json serializer seems happy to accept the request and populate Key2 with 2000 , or whatever the last instance of the key is.I am thinking I need to do something involving the JsonSerializerSettings class , or implement a custom JsonConverter , however I am unsure how to proceed . { `` key1 '' : `` value1 '' , `` key2 '' : 1000 , `` key2 '' : 2000 , `` key3 '' : `` value3 '' } [ HttpPost ] public IHttpActionResult PostMethod ( [ FromBody ] RequestModel request ) { ... .. } public class RequestModel { [ Required ] public string Key1 { get ; set ; } [ Required ] public int Key2 { get ; set ; } public string Key3 { get ; set ; } }",How to detect duplicate keys in Web Api Post request Json "C_sharp : I am working with some legacy TCP server code that works with sockets directly as it was written in .NET 2.0 and earlier . The server has a feature to 'stop ' and 'start ' accepting client connections.To troubleshoot the issue I run the server in the console mode as admin user . On top of that I have eliminated the socket accept thread from the equation and all the code does is something like : andThis called from different methods . I have debugged the code and I am pretty sure the code executes only once . However , the issue is that call to Stop does not actually releases the socket address and subsequent call to Start therefore fails with the error `` Only one usage of each socket address ( protocol/network address/port ) is normally permitted '' . I can also confirm from the ProcessExplorer that the server is still listening on the server port.When I write a small console app that uses the same code snippets everything works fine . I have even tried tracing the .NET network and socket libraries , but there is no error or anything to indicate problems there.It is not clear to me why call to Stop does not release the socket address ? Update : After more investigation it turns out that there is some strange effect of child process launch to the TcpListener . I have made a 'bare bone ' sample code that illustrates the issue : As you can see from the code if I launch the child process before creating a listener everything is fine , if I do it after listener restart fails . This has something to do with the UseShellExecute = false option for the child process.Not sure if this is .NET bug or some special behavior I was not aware of ? tcpListener = new TcpListener ( IPAddress.Any , this.Port ) ; tcpListener.Start ( ) ; tcpListener.Stop ( ) ; using System ; using System.Diagnostics ; using System.Net ; using System.Net.Sockets ; using System.Reflection ; using System.Threading ; namespace TcpListenerStartStop { class MyTcpListener { public static void Main ( string [ ] args ) { Int32 port = 13000 ; if ( args.Length > 0 ) // indicates child process { Thread.Sleep ( 4000 ) ; // as a child do nothing and wait for a few seconds } else // parent will play with the TcpListener { //LaunchChildProcess ( ) ; // launch child here and listener restart is fine ? ! ? var tcpListener = new TcpListener ( IPAddress.Any , port ) ; tcpListener.Start ( ) ; Console.WriteLine ( `` Starting test in 2 seconds ... '' ) ; Thread.Sleep ( 2000 ) ; LaunchChildProcess ( ) ; // launch child here and listener restart is not fine ? ! ? tcpListener.Stop ( ) ; Console.WriteLine ( `` Stopped . `` ) ; Thread.Sleep ( 1000 ) ; tcpListener.Start ( ) ; Console.WriteLine ( `` Started '' ) ; } Console.WriteLine ( `` All is good , no exceptions : ) '' ) ; } private static void LaunchChildProcess ( ) { Process process = new Process ( ) ; var processStartInfo = new ProcessStartInfo { CreateNoWindow = true , FileName = Assembly.GetExecutingAssembly ( ) .Location , UseShellExecute = false , // comment out this line out listener restart is fine ? ! ? Arguments = `` child '' } ; process.StartInfo = processStartInfo ; process.Start ( ) ; } } }",.NET TcpListener Stop method does not stop the listener when there is a child process "C_sharp : I saw many questions about this and Marc Gravell 's explanations of why he does n't want to continue playing with the multiple grid on dapper.But I just want to understand somethingIn this case the QueryMultiple takes around 3 seconds to execute ( which is the pretty much the execution time on the SQL ) and the read of the grid which has 2 queries takes 3 seconds at first and then 9 seconds on the second.There are around 50k rows on each and only 5 columns which 2 are int , 2 double ( float on sql ) and a datetime.I tried to turn off buffering and it did n't help.Is this because Dapper first Queries the database just to get the queries executed . Then connects to the database again upon request for the read and gets all the data for the specific read ? Would it be better to just create a few async tasks that run together with a single query each ? var grid = context.QueryMultiple ( string.Join ( `` ; `` , selectCommands ) ) ; return queries.Select ( q = > grid.Read < T > ( ) ) .AsList ( ) ;",Dapper Multiple Query Read is slow "C_sharp : How do I ask for an elevation for Registry access to HKLM ? I 'd like to add EnableLinkedConnections to `` HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ '' . I also do n't want to use a manifest file . Ive tried the below code but it does n't seem to help.Can anyone tell me what I 'm doing wrong please ? Thanks RegistryPermission f = new RegistryPermission ( RegistryPermissionAccess.Create , @ '' HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\ Policies\System\EnableLinkedConnections\1 '' ) ; f.Demand ( ) ;",How do I ask for an elevation for Registry access to HKLM ? "C_sharp : I have two examples . In the first case , debugger catches the unhandled exception : And the exception has full stacktrace : The second case : At the breakpoint the exception has short stacktrace : Why stacktraces are cut to the containing method in the second case , and how to prevent it ? I need full stacktrace for bugreports , otherwise it 's not possible sometimes to find there the problem is , without full stacktrace . static void Main ( string [ ] args ) { Exec ( ) ; } static void Exec ( ) { throw new Exception ( ) ; } at ConsoleApplication28.Program.Exec ( ) at ConsoleApplication28.Program.Main ( String [ ] args ) at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) static void Main ( string [ ] args ) { Exec ( ) ; } static void Exec ( ) { try { throw new Exception ( ) ; } catch ( Exception ex ) { } // Breakpoint } at ConsoleApplication28.Program.Exec ( )",Exceptions lose part of stacktrace in try/catch context "C_sharp : I 've seen lots of answers to the typedef problem in C # , which I 've used , so I have : and this works well . I can change the definition ( esp . change Bar = > Zoo etc ) and everything that uses Foo changes . Great.Now I want this to work : but C # does n't seem to like Foo in the second line , even though I 've defined it in the first.Is there a way of using an existing alias as part of another ? Edit : I 'm using VS2008 using Foo = System.Collections.Generic.Queue < Bar > ; using Foo = System.Collections.Generic.Queue < Bar > ; using FooMap = System.Collections.Generic.Dictionary < char , Foo > ;",Nesting aliases in C # "C_sharp : I 'm quite new to IoC frameworks so please excuse the terminology.So what I have is a MVC project with the Nininject MVC references.I have other class libarys in my project e.g . Domain layer , I would like to be able to use the Ninject framework in there but all of my bindings are in the NinjectWebCommon.cs under the App_Start folder in the MVC project : Currently in my class library I am using constructor injection but sometime I am having to hardcode the dependencies : When I would like to be able to do the following : I have not been doing the following because I do not have any modules ? All of the documentation I have read is mainly aimed at the regular Ninject library and not the MVC version.What do I need to do , and how can I use the regular Ninject library with the MVC version ? UpdateThis is what I have tried : The aim of this is so that each project can load the module and get the current injected interface.App_Start/NinjectWebCommon.cs ( In MVC Project ) IoCModules.cs ( In Project.Ioc project ) CoreModule.cs ( In Project.IoC.Modules project ) < -- This is where all the references to all projects are , this get 's around any circular dependency issues.But I am currently getting the following : Error activating IHardwareService No matching bindings are available , and the type is not self-bindable . Activation path : 2 ) Injection of dependency IHardwareService into parameter service of constructor of type DashboardController 1 ) Request for DashboardController Suggestions : 1 ) Ensure that you have defined a binding for IHardwareService . 2 ) If the binding was defined in a module , ensure that the module has been loaded into the kernel . 3 ) Ensure you have not accidentally created more than one kernel . 4 ) If you are using constructor arguments , ensure that the parameter name matches the constructors parameter name . 5 ) If you are using automatic module loading , ensure the search path and filters are correct . private static void RegisterServices ( IKernel kernel ) { kernel.Bind < IHardwareService > ( ) .To < WindowsHardwareService > ( ) ; kernel.Bind < IStatusApi > ( ) .To < StatusApiController > ( ) ; } var service = new WindowsHardwareService ( ) ; IKernel kernel = new StandardKernel ( ... .. ) ; var context = kernel.Get < IHardwareService > ( ) ; private static void RegisterServices ( IKernel kernel ) { var modules = new IoCModules ( ) ; var newKernal = modules.GetKernel ( ) ; kernel = newKernal ; } public class IoCModules { public IKernel GetKernel ( ) { var modules = new CoreModule ( ) ; return modules.Kernel ; } } public class CoreModule : NinjectModule { public override void Load ( ) { Bind < IHardwareService > ( ) .To < WindowsHardwareService > ( ) ; Bind < IStatusApi > ( ) .To < StatusApiController > ( ) ; } }",Using Nininject MVC with class libraries "C_sharp : I have a Silverlight app that adds a Path to the LayoutRoot grid of a UserControl . The path geometry is a simple rectangle.I would like to be able to add a TextBlock that is contained within the Path that was added to the LayoutRoot grid.I am also using a custom Adorner to allow me to resize the Path on the screen and move it around.Basically , I want the TextBlock 's parent to be the path , so that whenever I move the Path around , the TextBlock moves with it , and , also , the text within the TextBlock can never go outside the boundaries of the Path.Here is an example of what I currently have : Here is the constructor for the Shape class : Where ' o ' is the Path object and ' u ' is the TextBlock ... Does anyone have any ideas as to how this might be achieved ? Thanks . var shape = new ShapeClass ( ( o , u ) = > { LayoutRoot.Children.Add ( o ) ; LayoutRoot.Children.Add ( u ) ; } ) ; public ShapeClass ( Action < Path , TextBlock > insert ) { }",How to add a TextBlock within a Path ? "C_sharp : I have 2 classes both non-static . I need to access a method on one class to return an object for processing . But since both classes is non-static , I cant just call the method in a static manner . Neither can I call the method in a non-static way because the program doesnt know the identifier of the object.Before anything , if possible , i would wish both objects to remain non-static if possible . Otherwise it would require much restructuring of the rest of the code.Heres the example in code class Foo { Bar b1 = new Bar ( ) ; public object MethodToCall ( ) { /*Method body here*/ } } Class Bar { public Bar ( ) { /*Constructor here*/ } public void MethodCaller ( ) { //How can i call MethodToCall ( ) from here ? } }",How can a non-static class call another non-static class 's method ? C_sharp : I know I can force `` this . '' qualifier for instance member with Resharper code cleanup.Can I force redundant name qualifier for static methods ? Would be forced to this : public class Foo { public void Bar ( ) { StaticMethod ( ) ; } private static void StaticMethod ( ) { } } public class Foo { public void Bar ( ) { Foo.StaticMethod ( ) ; } private static void StaticMethod ( ) { } },Force redundant name qualifier for static methods in Resharper "C_sharp : I 'm working on a game , and we have been storing our level information in JSON format . These levels are quite large , so we switched to just storing them in plain C # : A top level method has a switch statement for the name of the level/objectThere are several auto-generated methods that `` new up '' our object tree with standard property inititalizersExample : Except these methods are very large and have nested lists/dictionaries of other objects , etc.This has sped up the time of loading a level from 2-3 seconds to fractions of a second ( on Windows ) . The size of our data is also considerable smaller , as compiled IL compared to JSON.The problem is when we compile these in MonoDevelop for MonoTouch , we get : mtouch exited with code 1With -v -v -v turned on , we can see the error : Is there a limit to the number of lines in a method , when compiling for AOT ? Is there some argument we can pass to mtouch to fix this ? Some files work fine , but one in particular that causes the error has a 3,000 line method . Compiling for the simulator works fine no matter what.This is still an experiment , so we realize this is a pretty crazy situation . private OurObject Autogenerated_Object1 ( ) { return new OurObject { Name = `` Object1 '' , X = 1 , Y = 2 , Width = 200 , Height = 100 } ; } MONO_PATH=/Users/jonathanpeppers/Desktop/DrawAStickman/Game/Code/iOS/DrawAStickman.iPhone/bin/iPhone/Release/DrawAStickmaniPhone.app /Developer/MonoTouch/usr/bin/arm-darwin-mono -- aot=mtriple=armv7-darwin , full , static , asmonly , nodebug , outfile=/var/folders/4s/lcvdj54x0g72nrsw9vzq6nm80000gn/T/tmp54777849.tmp/monotouch.dll.7.s `` /Users/jonathanpeppers/Desktop/DrawAStickman/Game/Code/iOS/DrawAStickman.iPhone/bin/iPhone/Release/DrawAStickmaniPhone.app/monotouch.dll '' AOT Compilation exited with code 134 , command : MONO_PATH=/Users/jonathanpeppers/Desktop/DrawAStickman/Game/Code/iOS/DrawAStickman.iPhone/bin/iPhone/Release/DrawAStickmaniPhone.app /Developer/MonoTouch/usr/bin/arm-darwin-mono -- aot=mtriple=armv7-darwin , full , static , asmonly , nodebug , outfile=/var/folders/4s/lcvdj54x0g72nrsw9vzq6nm80000gn/T/tmp54777849.tmp/DrawAStickmanCore.dll.7.s `` /Users/jonathanpeppers/Desktop/DrawAStickman/Game/Code/iOS/DrawAStickman.iPhone/bin/iPhone/Release/DrawAStickmaniPhone.app/DrawAStickmanCore.dll '' Mono Ahead of Time compiler - compiling assembly /Users/jonathanpeppers/Desktop/DrawAStickman/Game/Code/iOS/DrawAStickman.iPhone/bin/iPhone/Release/DrawAStickmaniPhone.app/DrawAStickmanCore.dll* Assertion : should not be reached at ../../../../../mono/mono/mini/mini-arm.c:2758",MonoTouch AOT Compiler - large methods fail "C_sharp : Given a class : ... and an IObservable < Foo > , with guaranteed monotonically increasing Timestamps , how can I generate an IObservable < IList < Foo > > chunked into Lists based on those Timestamps ? I.e . each IList < Foo > should have five seconds of events , or whatever . I know I can use Buffer with a TimeSpan overload , but I need to take the time from the events themselves , not the wall clock . ( Unless there a clever way of providing an IScheduler here which uses the IObservable itself as the source of .Now ? ) If I try to use the Observable.Buffer ( this IObservable < Foo > source , IObservable < Foo > bufferBoundaries ) overload like so : ... then the IList instances contain the item that causes the window to be closed , but I really want this item to go into the next window/buffer.E.g . with timestamps [ 0 , 1 , 10 , 11 , 15 ] you will get blocks of [ [ 0 ] , [ 1 , 10 ] , [ 11 , 15 ] ] instead of [ [ 0 , 1 ] , [ 10 , 11 ] , [ 15 ] ] class Foo { DateTime Timestamp { get ; set ; } } IObservable < Foo > foos = // ... ; var pub = foos.Publish ( ) ; var windows = pub.Select ( x = > new DateTime ( x.Ticks - x.Ticks % TimeSpan.FromSeconds ( 5 ) .Ticks ) ) .DistinctUntilChanged ( ) ; pub.Buffer ( windows ) .Subscribe ( x = > t.Dump ( ) ) ) ; // linqpadpub.Connect ( ) ;",How to window/buffer IObservable < T > into chunks based on a Func < T > "C_sharp : As explained here , if WeakReference 's IsAlive returns true , then it can not be trusted . Now , I 'm trying to understand the correct way to use this : Incorrect : Correct : My question is , is there any difference from the point of view of the GC , between if ( origDog ! = null and dogRef.Target ! = null ? Suppose , I did not need to invoke methods of the Dog class but just needed to check if the target was alive . Should I always cast the target to a class instance or is it okay to check Target against null ? I ask this because I want to execute some logic if the object is alive that does not involve the object itself . WeakReference dogRef = new WeakReference ( dog ) ; // Later , try to ref original Dogif ( dogRef.IsAlive ) { // Oops - garbage collection on original Dog could occur here ( ( Dog ) dogRef.Target ) .Bark ( ) ; } WeakReference dogRef = new WeakReference ( dog ) ; // Later , try to ref original DogDog origDog = ( Dog ) dogRef.Target ; if ( origDog ! = null ) { origDog.Bark ( ) ; }",C # : Properly using WeakReference IsAlive property "C_sharp : I have millions of lines generated from data updated every second which look like this : The column on the left represents time ( hhmmss format ) , and the column on the right is data which is updated second-by-second . As you can see however , it is n't actually second-by-second , and there are some missing times ( 10:45:04 , 10:45:07 , 10:45:08 are missing in this example ) . My goal is to add in the missing seconds , and to use the data from the previous second for that missing second , like this : I do n't want the `` -- '' in the result , I just put those there to mark the added lines . So far I 've tried to accomplish this using StreamReader and StreamWriter , but it does n't seem like they 're going to get me what I want . I 'm a newbie programmer and a newbie to C # , so if you could just point me in the right direction , that would be great . I 'm really just wondering if this is even possible to do in C # ... I 've spent a lot of time on MSDN and here on SO looking for a solution to this , but so far have n't found any . Edit : The lines are in a text file , and I want to store the newly created data in a new text file . 104500 4783104501 8930104502 21794104503 21927104505 5746104506 9968104509 5867104510 46353104511 7767104512 4903 104500 4783104501 8930104502 21794104503 21927104504 21927 -- 104505 5746104506 9968104507 9968 -- 104508 9968 -- 104509 5867104510 46353104511 7767104512 4903",Manipulating lines of data "C_sharp : Am using the following code to split a string into a List < int > , however occasionally the string includes non integer values , which are handled differently.An example string might be like : 1,2,3,4 , xcode looks like : The problem is as soon as it hits the ' x ' it throws an error because ' x ' ca n't be parsed as an integer.How can I make it ignore non integer values ? I 'm sure I should be able to do something with int.TryParse but ca n't quite figure it out.Thanks List < int > arrCMs = new List < int > ( strMyList.Split ( ' , ' ) .Select ( x = > int.Parse ( x ) ) ) ;",Split string into List < int > ignore none int values "C_sharp : I am making an HTTP POST method to get data . I have an idea to create a method to get a specific arguments but when I do n't have idea to get the arguments taken . In HTTP GET , arguments are in the URL and is more easy to get the arguments . How do I create a method to take all the data in HTTP Post ? In PHP for example when you show the var $ _POST you show all data in the body post . How can I do this in C # ? My method is this : [ HttpPost ] [ AllowAnonymous ] public IHttpActionResult Test ( ) { // Get URL Args for example is var args = Request.RequestUri.Query ; // But if the arguments are in the body i do n't have idea . }",Arguments HTTP Post c # "C_sharp : I like using implicit typing for almost everything because it 's clean and simple . However , when I need to wrap a try ... catch block around a single statement , I have to break the implicit typing in order to ensure the variable has a defined value . Here 's a contrived hypothetical example : Is there a way I can call GetData ( ) with exception handling , but without having to explicitly define the type of the result variable ? Something like GetData ( ) .NullOnException ( ) ? var s = `` abc '' ; // I want to avoid explicit typing hereIQueryable < ABC > result = null ; try { result = GetData ( ) ; } catch ( Exception ex ) { } if ( result ! = null ) return result.Single ( ) .MyProperty ; else return 0 ;",Implicitly-Typed Variables in try ... catch "C_sharp : I wonder if anyone has got any further than me using the new Search Analytics functions of the Google Webmaster Tools API via .Net ? I am using the Google.Apis.Webmasters.v3 Nuget package and have got as far as authenticating and connecting ( using a Service Account ) However I 'm struggling to get anywhere with Search Analytics.I could n't find any code samples online so have been guided by the Class info at https : //developers.google.com/resources/api-libraries/documentation/webmasters/v3/csharp/latest/annotated.html and a lot of guesswork.Here is the code I am using : It runs OK until the Execute method when I get `` An Error occurred , but the error response could not be deserialized '' . Exception detail below ... Newtonsoft.Json.JsonReaderException { `` Error parsing NaN value . Path `` , line 0 , position 0 . `` } Any help or code samples would be very gratefully received ! SearchanalyticsResource mySearchanalyticsResource = new SearchanalyticsResource ( service ) ; SearchAnalyticsQueryRequest myRequest = new SearchAnalyticsQueryRequest ( ) ; myRequest.StartDate = `` 2015-08-01 '' ; myRequest.EndDate = `` 2015-08-31 '' ; myRequest.RowLimit = 10 ; SearchanalyticsResource.QueryRequest myQueryRequest = mySearchanalyticsResource.Query ( myRequest , site.SiteUrl ) ; SearchAnalyticsQueryResponse myQueryResponse = myQueryRequest.Execute ( ) ;",.Net struggles with Webmaster Tools ( Google.Apis.Webmasters.v3 Nuget package ) "C_sharp : I have an Expression < Func < Entity , string > > that can be either a property or a nested property accessoror I am building up an expression tree dynamically and would like to get an InvokeExpression like thisI 'm pretty sure I can unwrap the Expression body , then partially apply the x ParameterExpression to it but I ca n't figure out the magical incantations to make this happenSo I have something likeEdit : Here is the full thing I 'm trying to do along with the error y = > y.SearchColumn y = > y.SubItem.SubColumn x = > x.SearchColumn.Contains ( `` foo '' ) ; x = > x.Sub.SearchColumn.Contains ( `` foo '' ) ; Expression < Func < Entity , string > > createContains ( Expression < Func < Entity , string > > accessor ) { var stringContains = typeof ( String ) .GetMethod ( `` Contains '' , new [ ] { typeof ( String ) } ) ; var pe = Expression.Parameter ( typeof ( T ) , `` __x4326 '' ) ; return Expression.Lambda < Func < Entity , bool > > ( Expression.Call ( curryExpression ( accessor.Body , pe ) , stringContains , Expression.Constant ( `` foo '' ) ) , pe ) ; } static Expression curryExpression ( Expression from , ParameterExpression parameter ) { // this does n't handle the sub-property scenario return Expression.Property ( parameter , ( ( MemberExpression ) from ) .Member.Name ) ; //I thought this would work but it does not //return Expression.Lambda < Func < Entity , string > > ( from , parameter ) .Body ; }",How to re-wrap a Linq Expression Tree "C_sharp : I 'm trying to use delegates for reflection in dotNet core web application . Below is the sample of the code.Compiler gives the following error : Is there any work around for creating delegates in .net Core ? Action action = ( Action ) Delegate.CreateDelegate ( typeof ( Action ) , method ) 'Delegate ' does not contain a definition for 'CreateDelegate ' ConsoleApp2..NETCoreApp , Version=v1.0 '",Delegate does not contain a definition for CreateDelegate in .net core "C_sharp : When using the ServiceHost.AddServiceEndpoint to add the custom ProtoEndpointBehavior I get the following exception : System.ArgumentNullException : Value can not be null . Parameter name : key at System.Collections.Generic.Dictionary2.FindEntry ( TKey key ) at System.Collections.Generic.Dictionary2.ContainsKey ( TKey key ) at System.ServiceModel.ServiceHostBase.ImplementedContractsContractResolver.ResolveContract ( String contractName ) at System.ServiceModel.ServiceHostBase.ServiceAndBehaviorsContractResolver.ResolveContract ( String contractName ) at System.ServiceModel.Description.ConfigLoader.LookupContractForStandardEndpoint ( String contractName , String serviceName ) at System.ServiceModel.Description.ConfigLoader.LookupContract ( String contractName , String serviceName ) at System.ServiceModel.ServiceHostBase.AddServiceEndpoint ( ServiceEndpoint endpoint ) at My.Service.Business.ServiceHandler.StartService ( Type serviceType , String uri , SecureConnectionSettings secureConnectionSettings ) in C : \My\Produkter\My Utveckling\Solution\My.Service.Business\ServiceHandler.cs : line 150This is how the code looks like : I use to set this in config file like this : Now I need to add it in code instead.What is wrong ? ServiceHost serviceHost = null ; Console.WriteLine ( `` Creating service `` + serviceType.FullName ) ; serviceHost = new MyServiceHost ( serviceType , new Uri ( uri ) ) ; var endPointAddress = `` '' ; HttpBindingBase binding = null ; if ( secureConnectionSettings ! = null & & secureConnectionSettings.Enabled ) { Console.WriteLine ( `` Setting certificates '' ) ; X509Store store = new X509Store ( secureConnectionSettings.CertificateStore , secureConnectionSettings.CertificateLocation ) ; store.Open ( OpenFlags.ReadOnly ) ; X509Certificate2Collection certs = store.Certificates.Find ( X509FindType.FindByThumbprint , secureConnectionSettings.Thumbprint , true ) ; store.Close ( ) ; if ( certs.Count > 0 ) serviceHost.Credentials.ServiceCertificate.SetCertificate ( secureConnectionSettings.CertificateLocation , secureConnectionSettings.CertificateStore , X509FindType.FindByThumbprint , secureConnectionSettings.Thumbprint ) ; else throw new Exception ( `` Could not finde certificate with thumbprint `` + secureConnectionSettings.Thumbprint ) ; endPointAddress = uri + `` /BinaryHttpsProto '' ; binding = CreateNetHttpsBinding ( secureConnectionSettings ) ; } else { endPointAddress = uri + `` /BinaryHttpProto '' ; binding = CreateNetHttpBinding ( ) ; } var endpoint = new System.ServiceModel.Description.ServiceEndpoint ( new System.ServiceModel.Description.ContractDescription ( typeof ( IMyClientService ) .FullName ) , binding , new EndpointAddress ( endPointAddress ) ) ; endpoint.EndpointBehaviors.Add ( new ProtoBuf.ServiceModel.ProtoEndpointBehavior ( ) ) ; serviceHost.AddServiceEndpoint ( endpoint ) ; Console.WriteLine ( `` Starting service ... '' ) ; serviceHost.Open ( ) ; Console.WriteLine ( `` Service started successfully ( `` + uri + `` ) '' ) ; return serviceHost ; < endpointBehaviors > < behavior name= '' protoEndpointBehavior '' > < protobuf / > < /behavior > < /endpointBehaviors >",AddServiceEndpoint throws key is null ? "C_sharp : I 'm currently trying to find out the best way to organize a project I 'm currently working on . It 's going to be an SDK that people can use.However , I 'm a little bit strugling with organizing the project . I 'm having a few namespaces and a few projects . These projects compile into different DLL's.When I compile all I have the following assemblies : However , in those assemblies are still a few different namespaces , likeSo as you can see I 'm not being very consistent with this . I 'm not creating a different assembly for every namespace , because I feel it adds no value having 10+ dll's.But I have a few questions about this here so I can make a decision on how I 'm going to do it.What are the advantages of using different assemblies for different parts of the application , in stead of using just 1 DLL that contains ALL.Is it a good idea to seperate the DAL from the logic , by using a different project ( cq assembly/dll ) . Do you perhaps have some sources of information about project organisation in VisualStudio or SDK design.Cheers , Timo ApplicationApplication.EntitiesApplication.DataAccess Application.DataAccess.SourceProvidersApplication.DataAccess.SourceParser",What 's the best way to organize this project ? "C_sharp : Consider the following code : When the writer stream is beeing disposed it disposes internally the FileStream stream . Is there any other desgin for this other than the MSDN recommendation to dispose the external used stream in the finally clause : using ( Stream stream = new FileStream ( `` file.txt '' , FileMode.OpenOrCreate ) ) { using ( StreamWriter writer = new StreamWriter ( stream ) ) { // Use the writer object ... } } Stream stream = null ; try { stream = new FileStream ( `` file.txt '' , FileMode.OpenOrCreate ) ; using ( StreamWriter writer = new StreamWriter ( stream ) ) { stream = null ; // Use the writer object ... } } finally { if ( stream ! = null ) stream.Dispose ( ) ; }",Preventing to dispose objects multiple times "C_sharp : I ’ ve come to realise that using a touchscreen ( one that generates stylus & touch events and not just mouse events ) seems to cause significant overhead on the UI thread in a WPF application . Even a simple application can be brought to a halt if I place enough fingers on the screen , over the application , and move them about a bit on certain machines . It seems quite peculiar and on the face of it , mostly outside of my control . Using a profiler revealed a lot of time spent mainly in StylusLogic/InputManager code ( Windows.Input ) and the Dispatcher.GetMessage routine.I haven ’ t been able to find any “ best practices ” for this sort of thing and the closest solution I could come to was to disable touch support wholly ( MSDN : Disabling the RealTimeStylus ) and hook into WM_TOUCH messages myself , generating my own PreviewTouchDown/PreviewMouseDown events ( sort of described here under “ Another WPF only way ” : CodeProject : WPF and multi touch ) but this isn ’ t without its own issues at times and doesn ’ t strike me as a long-term sensible solution . I also tried flagging events as handled early on to prevent them tunnelling/bubbling ; I flagged every PreviewStylusMove event ( the most frequent event ) as handled at the main window view as an experiment and this didn ’ t seem to provide a huge gain . While the codeproject link above states that there was ( or is ) a bug in WPF for multi-touch , I have found that even single-touch on a less powerful PC than my developer setup ( with some actual business software I work on ) will lag and stall for seconds at a time and you can still observe an unusual amount of work using task manager / a profiler to observe the CPU performance with single-touch.Can I do anything to reduce the frequency of these events ( E.G . PreviewStylusMove ) ? Do I have other options or is it all out of my control ? Obviously , I can work on trying to improve the efficiency of the application in general , but stylus/touch seems like such a big initial performance hit that it would be good to know what I can do to mitigate that.Full disclosure : This is a .NET 4.5 application . I have tried this on different models/brands of touchscreen with no visible differences . My computer and application are set up with the expectation that push-and-hold behaviour is identical to holding down a left mouse button , NOT generating a right click event . I have tested this on both Windows 7 and Windows 8.1 machines with no differences.The example below is a simple application I used to test this . When I place 10 fingers on the application window it stalls momentarily or skip frames on certain computers I 've used ( others may be too fast to display lag but the load increase can be observed in something like task manager ) : Does n't lag on my machine with an i7-2600 3.4GHz processor , but it does lag on my machine with a Core 2 Duo 2.93GHz processor . < Window x : Class= '' SimpleApplication.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : SimpleApplication '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < Grid > < Rectangle Fill= '' Aqua '' Width= '' 150 '' Height= '' 150 '' RenderTransformOrigin= '' 0.5 , 0.5 '' > < Rectangle.RenderTransform > < RotateTransform / > < /Rectangle.RenderTransform > < Rectangle.Triggers > < EventTrigger RoutedEvent= '' Loaded '' > < BeginStoryboard > < Storyboard > < DoubleAnimation Storyboard.TargetProperty= '' ( Rectangle.RenderTransform ) . ( RotateTransform.Angle ) '' To= '' -360 '' Duration= '' 0:0:2 '' RepeatBehavior= '' Forever '' / > < /Storyboard > < /BeginStoryboard > < /EventTrigger > < /Rectangle.Triggers > < /Rectangle > < /Grid >",Can I lessen the overhead of stylus/touch input in a WPF application ? "C_sharp : I 'm trying to understand the reason why is it bad to do : ( notice , context here is asp.net , regardless the plain reason that async void ca n't be tracked ) Well , after investigating a bit I saw few different reasons : Damian Edwards Says here that : Async void event handlers in web forms are only supported on certain events , as you 've found , but are really only intended for simplistic tasks . We recommend using PageAsyncTask for any async work of any real complexity.Levi Says here that : Async events in web applications are inherently strange beasts . Async void is meant for a fire and forget programming model . This works in Windows UI applications since the application sticks around until the OS kills it , so whenever the async callback runs there is guaranteed to be a UI thread that it can interact with . In web applications , this model falls apart since requests are by definition transient . If the async callback happens to run after the request has finished , there is no guarantee that the data structures the callback needs to interact with are still in a good state . Thus why fire and forget ( and async void ) is inherently a bad idea in web applications . That said , we do crazy gymnastics to try to make very simple things like Page_Load work , but the code to support this is extremely complicated and not well-tested for anything beyond basic scenarios . So if you need reliability I ’ d stick with RegisterAsyncTask.This site says : As we know our page life cycle has a set of events that gets fired in a predefined order and next event will be fired only when the last event completes . So if we use the above way of async Page_Load , this event will be fired during page life cycle event once it reaches to async , current thread gets free and a another thread got assigned to complete the task asynchronously , but the ASP.NET can not execute the next event in life cycle because Page_Load has not been completed yet . And underlying synchronization context waits till the asynchronous activity completes . Then only the next event of page lifecycle will be fired which makes the whole process in synchronous mode only.This site says when the return type is void , the caller might assume the method is complete by the time it returns . This problem can crop up in many unexpected ways . It ’ s usually wrong to provide an async implementation ( or override ) of a void-returning method on an interface ( or base class ) . Some events also assume that their handlers are complete when they return.I see here very different ( non-overlapping ) reasons.Question : What is the glory/true reason for which we should n't write public async void Page_Load ( object sender , EventArgs e ) ? nb , I also do n't know why it is a problem since 4.5 does use the UseTaskFriendlySynchronizationContext which its aim is to support : protected async void Page_Load ( object sender , EventArgs e ) { ... } public async void Page_Load ( object sender , EventArgs e ) { ... }",async void event handlers - clarification ? "C_sharp : I am experimenting with async/await and progress reporting and therefore have written an async file copy method that reports progress after every copied MB : In a console application a create I file with random content of 10MB and then copy it using the method above : After the application has executed , both files are identical , so the copy process is carried out in the correct order . However , the Console output is something like : The order differs every time I call the application . I do n't understand this behaviour . If I put a Breakpoint to the event handler and check each value , they are in the correct order . Can anyone explain this to me ? I want to use this later in a GUI application with a progress bar and do n't want to have it jumping back and forward all the time . public async Task CopyFileAsync ( string sourceFile , string destFile , CancellationToken ct , IProgress < int > progress ) { var bufferSize = 1024*1024 ; byte [ ] bytes = new byte [ bufferSize ] ; using ( var source = new FileStream ( sourceFile , FileMode.Open , FileAccess.Read ) ) { using ( var dest = new FileStream ( destFile , FileMode.Create , FileAccess.Write ) ) { var totalBytes = source.Length ; var copiedBytes = 0 ; var bytesRead = -1 ; while ( ( bytesRead = await source.ReadAsync ( bytes , 0 , bufferSize , ct ) ) > 0 ) { await dest.WriteAsync ( bytes , 0 , bytesRead , ct ) ; copiedBytes += bytesRead ; progress ? .Report ( ( int ) ( copiedBytes * 100 / totalBytes ) ) ; } } } } private void MainProgram ( string [ ] args ) { Console.WriteLine ( `` Create File ... '' ) ; var dir = Path.GetDirectoryName ( typeof ( MainClass ) .Assembly.Location ) ; var file = Path.Combine ( dir , `` file.txt '' ) ; var dest = Path.Combine ( dir , `` fileCopy.txt '' ) ; var rnd = new Random ( ) ; const string chars = ( `` ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 '' ) ; var str = new string ( Enumerable .Range ( 0 , 1024*1024*10 ) .Select ( i = > letters [ rnd.Next ( chars.Length -1 ) ] ) .ToArray ( ) ) ; File.WriteAllText ( file , str ) ; var source = new CancellationTokenSource ( ) ; var token = source.Token ; var progress = new Progress < int > ( ) ; progress.ProgressChanged += ( sender , percent ) = > Console.WriteLine ( $ '' Progress : { percent } % '' ) ; var task = CopyFileAsync ( file , dest , token , progress ) ; Console.WriteLine ( `` Start Copy ... '' ) ; Console.ReadLine ( ) ; } Create File ... Start Copy ... Progress : 10 % Progress : 30 % Progress : 20 % Progress : 60 % Progress : 50 % Progress : 70 % Progress : 80 % Progress : 40 % Progress : 90 % Progress : 100 %",C # async/await progress reporting is not in expected order "C_sharp : I am developing a windows 8 app and I have the following page , a contact picker page where i have a submit button with the following code my AddTask page has the follwoing methodnow I m getting an error in layout aware page during button click as PageKey is null in its onnavigatedfrom event as such Pls help me out customContact = ( CustomContacts ) contactView.SelectedItem ; this.Frame.Navigate ( typeof ( AddTask ) , customContact ) ; protected override void OnNavigatedTo ( NavigationEventArgs e ) { if ( e.Parameter == null ) { code logic } } protected override void OnNavigatedFrom ( NavigationEventArgs e ) { var frameState = SuspensionManager.SessionStateForFrame ( this.Frame ) ; var pageState = new Dictionary < String , Object > ( ) ; this.SaveState ( pageState ) ; frameState [ _pageKey ] = pageState ; }",Pagekey becomes null in OnNavigatedFrom in layoutawarepage "C_sharp : I am making a role playing game for fun and attempting to use TDD while developing it . Many of the TDD examples I see focus on creating the test first , then creating objects that are needed to get the test to pass.For example : So based on this I 'll create the character class and appropriate properties/methods . This seems fine and all but should my class design really come out of continually refining my tests ? Is that better than mapping out the possible objects that my game will need ahead of time ? For example , I would normally think of a base Character class , then subclasses such as Wizard , Fighter , Theif . Or is a balanced approach the way to go ? One where I map out the possible classes and hierarchy I 'll need but writing tests first to verify they are actually needed ? [ Test ] public void Character_WhenHealthIsBelowZero_IsDead ( ) { // create default character with 10 health Character character = new Character ( ) ; character.SubtractHealth ( 20 ) ; Assert.That ( character.IsAlive , Is.EqualTo ( false ) ) ; }",Does TDD mean not thinking about class design ? "C_sharp : I 'm using C # 4.0 . `` Optimize code '' in Visual Studio is turned on.Consider the following code , in a class : Here , a call to IncrementDictionary does one of two things : If no value exists for key , then a value is created and initialized to 1.If a value exists , the value is incremented by 1.Now watch what happens when I use ILSpy to decompile the result : Note : In the actual production code using this , the optimizer/compiler also creates : int key2 = key ; and uses key2 in the final line.Ok , var has been replaced by Dictionary < int , int > , which is expected . And the if statement was simplified to add a return instead of using an else.But why the heck was a new reference to the original dictionary created ? Dictionary < int , int > dictionary = new Dictionary < int , int > ( ) ; public void IncrementDictionary ( int key ) { if ( ! dictionary.ContainsKey ( key ) ) { dictionary [ key ] = 1 ; } else { dictionary [ key ] ++ ; } } Dictionary < int , int > dictionary = new Dictionary < int , int > ( ) ; public void IncrementDictionary ( int key ) { if ( ! dictionary.ContainsKey ( key ) ) { dictionary [ key ] = 1 ; return ; } Dictionary < int , int > dictionary2 ; ( dictionary2 = dictionary ) [ key ] = dictionary2 [ key ] + 1 ; }","What is the point of this C # Dictionary < , > optimization ?" "C_sharp : How do I write unit tests for classes that depend on Azure Table Storage , i.e . Microsoft.Azure.Cosmos.Table.CloudTableClient ? I found this GitHub issue , Azure Storage is still hard to unit test / mock , but I did n't find any clues in it other than methods are now virtual.MyService takes a dependency on CloudTableClient and internally gets a reference to a CloudTable to query the table . In my example here I 'm doing a simple lookup by partition and row key : public MyService ( CloudTableClient tableClient , ILogger < MyService > logger ) { } public async Task < MyMapping > GetMappingAsync ( string rowKey ) { var table = GetTable ( ) ; var retrieveOp = TableOperation.Retrieve < MyMapping > ( `` MyPartitionKey '' , rowKey ) ; var tableResult = await table.ExecuteAsync ( retrieveOp ) ; return tableResult.Result as MyMapping ; } private CloudTable GetTable ( ) { return tableClient.GetTableReference ( `` FakeTable '' ) ; }",CloudTableClient Unit Testing "C_sharp : Given an object o , how can I tell if it 's a mocked or a real object ? The only way I can see doing this looks a bit hacky : Please tell me there 's a better way ! public bool IsMockedObject ( object o ) { try { o.GetMockRepository ( ) ; return true ; } catch ( InvalidOperationException ) { return false ; } }",Rhino Mocks : How to tell if object is mocked or real ? "C_sharp : I 'm very new to working with JSON and am dealing wtih a return from an API which I ca n't change the formatting of . The return example is : ( actual urls have been removed ) I am using the Newtonsoft.Json library with MVC 3 , in VS2010.My class is : I 'm deserializing it with : However I 'm trying to get the value of linkurl , which is an indexed array within Link.How would I access this information ? { `` body '' : { `` link '' : { `` linkurl '' : [ `` www.google.com '' ] } } , '' error '' : null , '' message '' : `` Data Retrieved successfully '' , '' status '' : true } [ JsonObject ( MemberSerialization.OptIn ) ] public class LinksJSON { [ JsonProperty ] public string link { get ; set ; } [ JsonProperty ] public string message { get ; set ; } [ JsonProperty ] public string error { get ; set ; } [ JsonProperty ] public bool status { get ; set ; } } private static T _download_serialized_json_data < T > ( string url ) where T : new ( ) { using ( var w = new WebClient ( ) ) { var json_data = string.Empty ; // attempt to download JSON data as a string try { json_data = w.DownloadString ( url ) ; } catch ( Exception ) { } // if string with JSON data is not empty , deserialize it to class and return its instance return ! string.IsNullOrEmpty ( json_data ) ? JsonConvert.DeserializeObject < T > ( json_data ) : new T ( ) ; } } public string CheckJSONLink ( ) { var url = `` < api url-removed for security > '' ; var outObj = _download_serialized_json_data < LinksJSON > ( url ) ; return outObj.Link ; }",Deserializing JSON with indexed array in c # "C_sharp : I use in my project Owin and Katana for OAuth authorization . And all work good but in global.asax.cs file I have some code for IOC container : I added this code in Startup.cs file but after it I catch next exception : An exception of type 'Bootstrap.Extensions.Containers.NoContainerException ' occurred in Bootstrapper.dll but was not handled in user code Additional information : Unable to continue . The container has not been initialized.and if I call someone api methods I catch next exception : Unable to continue . The container has not been initialized . Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : Bootstrap.Extensions.Containers.NoContainerException : Unable to continue . The container has not been initialized . Source Error : Line 21 : public Startup ( ) Line 22 : { Line 23 : Bootstrapper.IncludingOnly.Assembly ( Assembly.Load ( `` Dashboard.Rest '' ) ) .With.SimpleInjector ( ) .With.ServiceLocator ( ) .Start ( ) ; Line 24 : Container container = Bootstrapper.Container as Container ; Line 25 : GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver ( container ) ; I do n't know how to fix it . Help me please . Thanks.UPDATEI have some SimpleInjectorRegisterTypes class for connect my interfaces and services : And I have service where I write logic for API.And in my controllers I create constructor for call my method with help interfaces : Bootstrapper.IncludingOnly.Assembly ( Assembly.Load ( `` Dashboard.Rest '' ) ) .With.SimpleInjector ( ) .With.ServiceLocator ( ) .Start ( ) ; Container container = Bootstrapper.Container as Container ; GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver ( container ) ; public class SimpleInjectorRegisterTypes : ISimpleInjectorRegistration { public void Register ( Container container ) container.RegisterSingle < IApplication , ApplicationService > ( ) ; } } public class ApplicationController : ApiController { private readonly IApplication _application ; public ApplicationController ( IApplication application ) { _application = application ; } [ HttpGet ] public IHttpActionResult GetAllApps ( ) { var apps = _application.GetAllApps ( ) ; return apps == null ? ( IHttpActionResult ) Ok ( new Application ( ) ) : Ok ( apps ) ; } ... .",OWIN and Global.asax.cs file "C_sharp : I 'm trying to self-host a singleton instance of a service and I 'm obviously getting lost at a level of indirection ... I 've got a base address of http : //localhost:8050/ . I 'm not too bothered where the service endpoint is as long as it 's predictable . For the moment , I 'm trying to use /Manage/.I 'm able to browse to the base address and see a wsdl . If I scan through the wsdl , it points at /Manage/..When I consume the wsdl using the WcfTestClient , it lists all the correct methods , but calling any of them throw the following exception System.ServiceModel.EndpointNotFoundException : There was no endpoint listening at http : //localhost:8050/Manage that could accept the message . This is often caused by an incorrect address or SOAP action . See InnerException , if present , for more details.Log messages show my instance methods never get called . The service does n't enter a faulted state , it just looks like it 's not there.I 'm listening as follows : And calling the Listen ( ) method as follows : How can I track down what the problem is/debug further ? Additional info : The Service contract and minimal implementation : And the implementation : The test client can see the service and methods but throws the exception above when I click Invoke ... Edit : localhost resolves to IPv6 by default so I 've tried using 127.0.0.1 explicitly at both ends . No difference.I 've tried taking the above code into a new project and get the same issue . Running the whole thing on someone else 's machine did n't help either.Service Trace viewerRunning a service trace on the server side , then examining the results in the viewer gives : Failed to lookup a channel to receive an incoming message . Either the endpoint or the SOAP action was not found.Config file : Since I need the executable to be able to make a decision about which Wcf service to present at runtime , I do n't have any Wcf-related code in the config file . < wsdl : service name= '' EngineService '' > < wsdl : port name= '' BasicHttpBinding_IEngineService '' binding= '' tns : BasicHttpBinding_IEngineService '' > < soap : address location= '' http : //localhost:8050/Manage/ '' / > < /wsdl : port > < /wsdl : service > Server stack trace : at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException ( WebException webException , HttpWebRequest request , HttpAbortReason abortReason ) at System.ServiceModel.Channels.HttpChannelFactory ` 1.HttpRequestChannel.HttpChannelRequest.WaitForReply ( TimeSpan timeout ) at System.ServiceModel.Channels.RequestChannel.Request ( Message message , TimeSpan timeout ) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request ( Message message , TimeSpan timeout ) at System.ServiceModel.Channels.ServiceChannel.Call ( String action , Boolean oneway , ProxyOperationRuntime operation , Object [ ] ins , Object [ ] outs , TimeSpan timeout ) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService ( IMethodCallMessage methodCall , ProxyOperationRuntime operation ) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke ( IMessage message ) Exception rethrown at [ 0 ] : at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage ( IMessage reqMsg , IMessage retMsg ) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke ( MessageData & msgData , Int32 type ) at IEngineService.SupportedAgents ( ) at EngineServiceClient.SupportedAgents ( ) Inner Exception : The remote server returned an error : ( 404 ) Not Found . at System.Net.HttpWebRequest.GetResponse ( ) at System.ServiceModel.Channels.HttpChannelFactory ` 1.HttpRequestChannel.HttpChannelRequest.WaitForReply ( TimeSpan timeout ) public static ServiceHost Listen < TServiceContract > ( TServiceContract instance , int port , string name ) { //Added this for debugging , was previously just `` name '' string endpoint = String.Format ( `` http : //localhost : { 0 } / { 1 } / '' , port , name ) ; var svcHost = new ServiceHost ( instance , new Uri [ ] { new Uri ( String.Format ( `` http : //localhost : { 0 } / '' , port ) ) } ) ; /* Snip : Add a Faulted handler but it 's never called */ ServiceEndpoint serviceHttpEndpoint = svcHost.AddServiceEndpoint ( typeof ( TServiceContract ) , new BasicHttpBinding { HostNameComparisonMode = HostNameComparisonMode.WeakWildcard } , endpoint ) ; /*Using name instead of endpoint makes no difference beyond removing the trailing slash */ /* Snip : Add a ServiceDebugBehavior with IncludeExceptionDetailInFaults = true */ /* Snip : Add a ServiceMetadataBehavior with HttpGetEnabled = true */ try { log.Trace ( `` Opening endpoint '' ) ; svcHost.Open ( ) ; } catch ( ) { /* Lots of catches for different problems including Exception * None of them get hit */ } log.Info ( `` Service contract { 0 } ready at { 1 } '' , typeof ( TServiceContract ) .Name , svcHost.BaseAddresses.First ( ) ) ; return svcHost ; IEngineService wcfInstance = Resolver.Resolve < IEngineService > ( ) ; service = WcfHoster.Listen ( wcfInstance , 8050 , `` Manage '' ) ; [ ServiceContract ] interface IEngineService { [ OperationContract ] List < string > Agents ( ) ; [ OperationContract ] string Test ( ) ; [ OperationContract ] List < string > SupportedAgents ( ) ; [ OperationContract ] string Connect ( string AgentStrongName , string Hostname ) ; } [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.Single ) ] class EngineService : IEngineService { IAgentManager agentManager ; public EngineService ( IAgentManager AgentManager ) { log.Debug ( `` Engine webservice instantiating '' ) ; this.agentManager = AgentManager ; } public string Connect ( string AgentStrongName , string Hostname ) { log.Debug ( `` Endpoint requested for [ { 0 } ] , [ { 1 } ] '' , Hostname , AgentStrongName ) ; return agentManager.GetSession ( AgentStrongName , Hostname ) ; } public List < string > Agents ( ) { log.Debug ( `` Current agents queried '' ) ; throw new NotImplementedException ( ) ; } public List < string > SupportedAgents ( ) { log.Debug ( `` Supported agents queried '' ) ; return agentManager.SupportedAgents ( ) .ToList ( ) ; } public string Test ( ) { log.Warn ( `` Test query '' ) ; return `` Success ! `` ; } }",Self hosted Wcf serves wsdl but 404 's when invoked "C_sharp : In C # : This throws a FormatException , which seems like it should n't : This does not , which seems normal : And surprisingly , this parses just fine : My local culture is EN-US , so , is the default thousands separator char.Main question : Why the inconsistency ? Also : Why does Parse ( `` 1,2,3,4 '' ) work ? It appears to just be removing all instances of the local separator char before parsing . I know there would be extra runtime overhead in a regex check or something like that , but when would the numeric literal `` 1,2,3,4 '' not be a typo ? Related : C # Decimal.Parse issue with commas Int32.Parse ( `` 1,234 '' ) ; Single.Parse ( `` 1,234 '' ) ; Single.Parse ( `` 1,2,3,4 '' ) ; //Returns 1234","Int32.Parse vs Single.Parse - ( `` 1,234 '' ) and ( `` 1,2,3,4 '' ) . Why do int and floating point types parse separator chars differently ?" "C_sharp : I 'm reading the book Real-world functional programming by Tomas Petricek and Jon Skeet and I 'm having a hard time digesting the section on computation expressions1 ) ( aka monads ) .Through this book , I learnt that — contrary to my previous experiences — LINQ query expressions are n't restricted to IEnumerable < T > , but can work on other custom types as well . This seems very interesting to me , and I am wondering if there are scenarios where the query expression syntax ( from x in ... select ... ) would be a nice fit.Some background info : Apparently , such custom types are called computation types , which are portrayed as being essentially the same thing as monads in Haskell . I have never been able to grasp what exactly monads are , but according to the book , they are defined through two operations called bind and return.In functional programming , the type signatures of these two operations would be ( I think ) : where M is the monadic type 's name.In C # , this corresponds to : It turns out that LINQ 's Enumerable.Select ( the projection operator ) has exactly the same signature as the bind operation with M : = IEnumerable.My custom LINQ computation type : Using this knowledge , I can now write a custom computation type which is not IEnumerable : And now I can use Wrapped < T > in LINQ query expressions , e.g . : Of course this example is not very useful , but it demonstrates how query expressions can be made to do something else than working with collections , e.g . wrapping and unwrapping values with some type.Question : The above computation type does n't seem very useful . Therefore I wonder , what other reasonable uses ( besides processing collections ) could there be that make use of LINQ query expressions ? 1 ) Section 12.4 : `` Introducing alternative workflows '' , starting on page 334 . // Bind : M < A ' > - > ( A ' - > B ' ) - > M < B ' > //// Return : A ' - > M < A ' > Func < M < A > , Func < A , B > , M < B > > Bind ; Func < A , M < A > > Return ; // my custom computation type : class Wrapped < A > { // this corresponds to the Return operation : public Wrapped ( A value ) { this.Value = value ; } public readonly A Value ; } static class Wrapped { // this corresponds to the Bind operation : public static Wrapped < B > Select < A , B > ( this Wrapped < A > x , Func < A , B > selector ) { return new Wrapped < B > ( selector ( x.Value ) ) ; } } Wrapped < int > wrapped = new Wrapped < int > ( 41 ) ; Wrapped < int > answer = from x in wrapped // works on int values instead select x + 1 ; // of Wrapped < int > values !",LINQ query expressions that operate on types ( monads ? ) other than IEnumerable < T > -- Possible uses ? "C_sharp : Based on information from here . I found how deleting orphans with Entity Framework.I was wondering how to make generic function for this part because it might be used often : I thought about something like this : But of course it does n't work . Any advice ? public void SaveChanges ( ) { context.ReportCards .Local .Where ( r = > r.Student == null ) .ToList ( ) .ForEach ( r = > context.ReportCards.Remove ( r ) ) ; context.SaveChanges ( ) ; } context.ReportCards .Local .Where ( r = > r.Student == null ) .ToList ( ) .ForEach ( r = > context.ReportCards.Remove ( r ) ) ; public void SaveChanges ( ) { RemoveOrphans ( Student , ReportCards ) context.SaveChanges ( ) ; } private void RemoveOrphans < T > ( T sourceContext , T orphan ) { context.orphan .Local .Where ( r = > r.sourceContext == null ) .ToList ( ) .ForEach ( r = > context.orphan .Remove ( r ) ) ; }",How to make generic function using LINQ ? "C_sharp : I know generics are in C # to fulfill a role similar to C++ templates but I really need a way to generate some code at compile time - in this particular situation it would be very easy to solve the problem with C++ templates.Does anyone know of any alternatives ? Perhaps a VS plug-in that preprocesses the code or something like that ? It does n't need to be very sophisticated , I just need to generate some methods at compile time.Here 's a very simplified example in C++ ( note that this method would be called inside a tight loop with various conditions instead of just `` Advanced '' and those conditions would change only once per frame - using if 's would be too slow and writing all the alternative methods by hand would be impossible to maintain ) . Also note that performance is very important and that 's why I need this to be generated at compile time . template < bool Advanced > int TraceRay ( Ray r ) { do { if ( WalkAndTestCollision ( r ) ) { if ( Advanced ) return AdvancedShade ( collision ) ; else return SimpleShade ( collision ) ; } } while ( InsideScene ( r ) ) ; }",Templates in C # "C_sharp : I am trying to get recent 200 tweets using TweetSharp but it is returning 12 for some reason . Any ideas why would that be ? ThanksUpdateFollowing How to fetch maximum 800 tweets from ListTweetOnHomeTimeline ( ) method of TweetSharp ? tweet2 is empty . var service = new TwitterService ( _consumerKey , _consumerSecret , tokenClaim , tokenSecret ) ; IAsyncResult result = service.BeginListTweetsOnUserTimeline ( new ListTweetsOnUserTimelineOptions { Count = 200 } IEnumerable < TwitterStatus > tweets = service.EndListTweetsOnUserTimeline ( result ) ; IAsyncResult result = _twitterService.BeginListTweetsOnUserTimeline ( new ListTweetsOnUserTimelineOptions { Count = 200 } ) ; IEnumerable < TwitterStatus > tweets = _twitterService.EndListTweetsOnUserTimeline ( result ) .ToArray ( ) ; var tweet2 = _twitterService.ListTweetsOnUserTimeline ( new ListTweetsOnUserTimelineOptions { Count = 200 , MaxId = tweets.Last ( ) .Id } ) ; return tweet2 ;",Return recent n number of tweets using TweetSharp "C_sharp : So.. i have a class that has has a List . I pass it to the view like the code below : And then the View will receive it like this : My problem is that it will be rendered like this [ 0 ] .subj and that wo n't allow me to bind because it should be something like name [ 0 ] .subj . I 've been experimenting and trying new methods , are there any ways for me to bind them properly ? i want to use Html Helpers and as much as possible , i do n't want to re-implement a custom one just for this part.This is the function where they are supposed to be bound . This class has a List of students ( the one that i converted to IPagedList ) And this is how my View looks like . I am using CheckBoxFor for selections.Extra question : How come my navigation looks so ugly ? [ HttpGet ] [ Authorize ( Roles= '' user '' ) ] [ CustomChecker ] public ActionResult Index ( int ? page , int id=0 ) { EmployeeContext emp = new EmployeeContext ( ) ; student st = emp.students.Single ( x= > x.id ==id ) ; @ ViewBag.id = st.id ; return View ( st.subjSel.ToPagedList ( page ? ? 1 , 4 ) ) ; } @ using PagedList ; @ using PagedList.Mvc ; @ model PagedList < MvcApplication6.Models.subject > < div style= '' font-family : Arial '' > < fieldset > < legend > < h3 > Open Classes < /h3 > < /legend > @ using ( Html.BeginForm ( `` Test '' , `` Enrollment '' ) ) { < input type= '' hidden '' name= '' id '' value= '' @ ViewBag.id '' / > < table border= '' 1 '' > < tr > < th > @ Html.LabelFor ( model = > model [ 0 ] .subj ) < /th > < th > @ Html.LabelFor ( model = > model [ 0 ] .days ) < /th > < th > @ Html.LabelFor ( model = > model [ 0 ] .cstart ) < /th > < th > @ Html.LabelFor ( model = > model [ 0 ] .cend ) < /th > < th > @ Html.LabelFor ( model = > model [ 0 ] .professor ) < /th > < th > @ Html.LabelFor ( model = > model [ 0 ] .units ) < /th > < th > @ Html.CheckBox ( `` test '' ) Select all < /th > < /tr > @ for ( int i = 0 ; i < Model.Count ; i++ ) { < tr > @ Html.HiddenFor ( model = > model [ i ] .id ) < td > @ Html.DisplayFor ( m = > m [ i ] .subj ) @ Html.HiddenFor ( m = > m [ i ] .subj ) < /td > < td > @ Html.DisplayFor ( m = > m [ i ] .days ) @ Html.HiddenFor ( m = > m [ i ] .days ) < /td > < td > @ Html.DisplayFor ( m = > m [ i ] .cstart ) @ Html.HiddenFor ( m = > m [ i ] .cstart ) < /td > < td > @ Html.DisplayFor ( m = > m [ i ] .cend ) @ Html.HiddenFor ( m = > m [ i ] .cend ) < /td > < td > @ Html.DisplayFor ( m = > m [ i ] .professor ) @ Html.HiddenFor ( m = > m [ i ] .professor ) < /td > < td > @ Html.DisplayFor ( m = > m [ i ] .units ) @ Html.HiddenFor ( m = > m [ i ] .units ) < /td > < td > @ Html.CheckBoxFor ( m = > m [ i ] .isSelected ) < /td > < /tr > } < /table > < br / > < br / > < table > < tr > < td align= '' center '' width= '' 500px '' > < /td > < /tr > < tr > < td align= '' center '' width= '' 500px '' > < input type= '' submit '' value= '' submit '' / > | < input type= '' button '' value= '' clear '' / > < /td > < /tr > < /table > < br / > < br / > } < /fieldset > < /div > @ Html.PagedListPager ( Model , page = > Url.Action ( `` Index '' , `` Enrollment '' , new { page , id = Request.QueryString [ `` id '' ] } ) ) [ HttpPost ] [ Authorize ( Roles= '' user '' ) ] public ActionResult Test ( student st )",Binding IPagedList with checkbox as List "C_sharp : I am getting following FxCop error : CA1820 : Microsoft.Performance : Replace the call to 'string.operator == ( string , string ) ' in 'Program.Main ( ) ' with a call to 'String.IsNullOrEmpty ' . static void Main ( ) { string str = `` abc '' ; switch ( str ) { case `` '' : Console.WriteLine ( `` Hello '' ) ; break ; } Console.ReadLine ( ) ; }",How to resolve CA1820 for switch statement "C_sharp : An article in MSDN Magazine discusses the notion of Read Introduction and gives a code sample which can be broken by it.Notice this `` May throw a NullReferenceException '' comment - I never knew this was possible.So my question is : how can I protect against read introduction ? I would also be really grateful for an explanation exactly when the compiler decides to introduce reads , because the article does n't include it . public class ReadIntro { private Object _obj = new Object ( ) ; void PrintObj ( ) { Object obj = _obj ; if ( obj ! = null ) { Console.WriteLine ( obj.ToString ( ) ) ; // May throw a NullReferenceException } } void Uninitialize ( ) { _obj = null ; } }",Read Introduction in C # - how to protect against it ? "C_sharp : I have the following code written in both C++ and C # After this C # compiler brings an errorBut C++ compiler generate this code with no error and I got a result 11 for value of i . What 's the reason of this difference ? int i=0 ; ++i = 11 ; The left-hand side of an assignment must be a variable , property or indexer",++i operator difference in C # and C++ "C_sharp : perhaps I 'm misinterpreting this part of Windows ' Task Scheduler UI , but the following options suggest ( to me ) that a program is first asked nicely to stop , and then forcefully quit when that fails : from the deepest corners of my mind , I remembered that Windows applications can respond to requests to quit ; with that in mind , I was able to google up AppDomain.CurrentDomain.ProcessExit . however , it appears that Task Scheduler 's `` stop the task ... '' and AppDomain.CurrentDomain.ProcessExit do not work together as I had hoped ; here is an example program I threw together that does not work : tl ; dr my question is : can a program be written to respond to Task Scheduler stopping it ? ( or does Task Scheduler force-quit tasks in the rudest way possible ? ) if a program can be written in this way , how is the correct way to do so ? ( the way I tried is clearly not correct . ) am I over-thinking all of this , and it would just be better to have the program time itself in a parallel thread ? ( perhaps with a max time set in app.config , or whatever . ) [ edit ] tried this variant , at Andrew Morton 's request , with similar results : after Task Scheduler stops the task , the .log file contains `` Hello ! '' but not `` Goodbye ! '' using System ; using System.Threading ; using System.Windows.Forms ; namespace GimmeJustASec { class Program { static void Main ( string [ ] args ) { AppDomain.CurrentDomain.ProcessExit += new EventHandler ( SuddenCleanup ) ; while ( true ) { Thread.Sleep ( 1000 ) ; } } static void SuddenCleanup ( object sender , EventArgs e ) { MessageBox.Show ( `` Hello ! `` ) ; } } } using System ; using System.Threading ; using System.Windows.Forms ; using System.IO ; namespace GimmeJustASec { class Program { private static StreamWriter _log ; static void Main ( string [ ] args ) { _log = File.CreateText ( `` GimmeJustASec.log '' ) ; _log.AutoFlush = true ; _log.WriteLine ( `` Hello ! `` ) ; AppDomain.CurrentDomain.ProcessExit += new EventHandler ( SuddenCleanup ) ; while ( true ) { Thread.Sleep ( 1000 ) ; } } static void SuddenCleanup ( object sender , EventArgs e ) { _log.WriteLine ( `` Goodbye ! `` ) ; } } }",can I write a C # program that - when run as a scheduled task - detects when Task Scheduler tries to stop it "C_sharp : Warning : this question uses an analogy to RPG as an example.Let 's say I 'm making this RPG I 've been dreaming of , using C # .When the player enters battle , there is some kind of battlefield appearing , that holds references to every elements relevant to the battle , like the various opponents and items available on the battlefield.Now all those elements have one but several roles : for instance , an Ally ( which is a Fighter through direct inheritance ) is able to move on the battlefield , to issue commands or to be targeted by ennemies.Now that mighty sword in the stone has also a few roles in battle . Obviously it ca n't move nor issue commands , but it can still be targeted , and it can ( hopefully ) be lifted or used.All these behaviors are represented by interfaces in my code , so that all objects with the same behaviors can be used regardless of the object that implements it.Code example : Now my question is the following : How should my Battlefield class holds its references to all these objects ? I came up with two possible solutions , but at this point it 's not clear which one is the best , and whether better solutions are to be found.Solution A : Reference several time , access directly : Using this solution , each object is referenced once per interface it implements , so my battlefield class would look like below : and the Battlefield.Update method could look this way : This solution allows us to have a direct access to the objects ' various behavior , but it introduces redundancy , as an Ally would have to be referenced into movables , targets and actors.This redundancy means a bigger memory footprint and will make adding and removing an object to the battlefield a lot more complicated ( each type should now from which collections it has to be added/removed ) .Also , adding a new interface means adding a new collection to hold the item and manage the corresponding code.Solution B : Reference once , filter access : Using this solution , all objects derive from a single class or interface ( something akin to IBattleElement ) , and are stored in one single collection.When using the elements , they are filtered according to their types : There . No more redundancy , but I dislike using a `` typeof '' construct and I generally try to avoid it . Obviously this is worse regarding runtime performance.I implemented solution A in my toy project , but there is nothing performance critical in this project.The answer should consider not only performance ( both memory wise and CPU wise ) , but also what offers the best design for the operations me or my designers might have to perform , such as adding new classes of BattleElement or new interfaces for new behaviors , adding and removing instances of objects from a Battlefield , and more generally use them in the game logic.I apologize for the general silliness of my examples , I hope my English is good enough , and that my question carries at least a little bit of interest and does n't indicate an overall silliness in the design itself . public class Ally : Fighter , IMovable , IActor , ITarget { // IMovable implementation public void Move ( ... ) { ... } // IActor implementation public bool HasInitiative { get { ... } } public ICommand IssueCommand ( ... ) { ... } // ITarget implementation public void OnTarget ( ... ) { ... } // other code ... } public class MightySword : ITarget , ILiftable , IUsable { // ITarget implementation public void OnTarget ( ... ) { ... } // ... other interface implementation // other code ... } public class Battlefield : ... { IList < IMovable > movables ; IList < ITarget > targets ; IList < IActor > actors ; // ... and so on } Update ( ... ) { // Say every actor needs to target somebody else // it has nothing to do in the Update method , // but this is an example foreach ( IActor actor in actors ) { if ( actor.HasInitiative ) { ITarget target = targets [ actor.TargetIndex ] ; target.OnTarget ( actor.IssueCommand ( ... ) ) ; } } } Update ( ... ) { IList < IActor > actors = elements.OfType < Actor > ( ) ; foreach ( IActor actor in actors ) { ITarget target = elements.OfType < Target > ( ) [ actor.TargetIndex ] ; target.OnTarget ( actor.IssueCommand ( ... ) ) ; } }",Referencing the same object in several collections by interface C_sharp : I m using MediaElement to play a web video . When I left the page I noticed in the Task Manager that my app was still using 10 % of network and did n't drop till it finished downloading video.I tried doing the following but no luck.Also tried to set the source to a dummy link but still no luck.I thought that opening the Link as a Stream and use mediaElement.SetSource ( ) could work but I have n't found anything on that ... maybe I m not searching correct . Thank you . //open link ; mediaElement.Source = welcomeVideoURL ; //when I leave the page OnNavigatedFrom ( ) mediaElement.Stop ( ) ; mediaElement.ClearValue ( MediaElement.SourceProperty ) ; mediaElement.Source = null ;,MediaElement web Video does n't stop buffering "C_sharp : I 'm building a .NET 4.0 application that uses ADO.NET , so I can not use async/await.I do n't want a solution for that , but I do want to know what of the following implementations is best and why . My unit tests pass for all three implementations , but I want to know the difference between these three. # 1 Nesting tasksIn my first implementation I wrap a task in another task . I think spinning up two tasks is bad for performance , but I 'm not sure. # 2 Using TaskCompletionSourceThen I tried wrapping the result in a TaskCompletionSource so I just have one task. # 3 returning Task directlyMy final solution is to directly return the task I created instead of wrapping it.So basically my question is : What option should I use or is there a better way to do this ? public virtual Task < IDataReader > ExecuteReaderAsync ( IDbCommand dbCommand , CancellationToken cancellationToken ) { return Task.Factory.StartNew ( ( ) = > { var sqlCommand = CheckIfSqlCommand ( dbCommand ) ; PrepareExecuteReader ( dbCommand ) ; return Task < IDataReader > .Factory .FromAsync ( sqlCommand.BeginExecuteReader , sqlCommand.EndExecuteReader , null ) .Result ; } , cancellationToken ) ; } public virtual Task < IDataReader > ExecuteReaderAsync ( IDbCommand dbCommand , CancellationToken cancellationToken ) { var taskCompletionSource = new TaskCompletionSource < IDataReader > ( ) ; var sqlCommand = CheckIfSqlCommand ( dbCommand ) ; PrepareExecuteReader ( dbCommand ) ; var reader = Task < IDataReader > .Factory .FromAsync ( sqlCommand.BeginExecuteReader , sqlCommand.EndExecuteReader , null ) .Result ; taskCompletionSource.SetResult ( reader ) ; return taskCompletionSource.Task ; } public virtual Task < IDataReader > ExecuteReaderAsync ( IDbCommand dbCommand , CancellationToken cancellationToken ) { var sqlCommand = CheckIfSqlCommand ( dbCommand ) ; PrepareExecuteReader ( dbCommand ) ; return Task < IDataReader > .Factory .FromAsync ( sqlCommand.BeginExecuteReader , sqlCommand.EndExecuteReader , null ) ; }",Should I wrap a task in another task or should I just return the created task ? "C_sharp : I 'm using the T4 TextTemplating service from a VSPackage : Normally if a template is referencing types in an external assembly you can use the assembly directive . However , I do n't know the assembly until runtime , so is there anyway of adding assembly references to the T4 engine programmatically ? var t4 = this.GetService ( typeof ( STextTemplating ) ) as ITextTemplating ;",How do you add an assembly reference programmatically ? "C_sharp : I have a collection of documents `` WineDocument '' on the form : I need to make a query to find all unique values of the `` Country '' field . I have been trying to create an index looking something like : The index gets created ok and I try to use it with the following code : But this gives an JsonSerializationException : `` Can not deserialize JSON object into type 'System.String'. '' . I guess it is because the Json parser can not parse { Key = `` Italy } to a string . But I do n't know how to make a map/reduce return just a string . { `` Name '' : `` Barbicato Morellino Di Scansano '' , `` Country '' : `` Italy '' , `` Region '' : `` Tuscany '' , } class WineCountriesIndex : AbstractIndexCreationTask < WineDocument , string > { public BeverageCountriesIndex ( ) { Map = wines = > from wine in wines where wine.Country ! = null select new { Key = wine.Country } ; Reduce = results = > from result in results group result by result into g select new { Key = g.Key } ; } } IList < string > countries = session.Query < string , WineCountriesIndex > ( ) .ToList ( ) ;",How to create a RavenDB index that returns a list of strings ? "C_sharp : I do n't understand what is happening here : Both of these lines compile : But this does n't : There is n't an implicit operator on LambdaExpression or Expression < TDelegate > that converts a delegate to the expression , so something else must be happening to make the assignment work . What is it ? Func < object > func = ( ) = > new object ( ) ; Expression < Func < object > > expression = ( ) = > new object ( ) ; expression = func ;",How is a Func < T > implicitly converted to Expression < Func < T > > ? "C_sharp : I am using the WeakEventManager < TEventSource , TEventArgs > class in order to subscribe to events in C # . Event subscription works fine , however calling WeakEventManager < TEventSource , TEventArgs > .RemoveHandler from a Task does not always remove the handler - most ( but not all ) of the time the handler is still executed when the event fires.This is illustrated in the following example.The handler is removed all of the time , however in most cases the event is still handled.Am I making an error in the way that these methods are called ? Do these methods support being called asynchronously ? Is there an alternative approach that would work ? Many thanks for your help in advance . public class EventSource { public event EventHandler Fired = delegate { } ; public void FireEvent ( ) { Fired ( this , EventArgs.Empty ) ; } } class Program { private static bool added , removed , handled ; static void Main ( string [ ] args ) { for ( int i = 1 ; i < = 100 ; i++ ) { added = removed = handled = false ; var source = new EventSource ( ) ; AddHandlerAsync ( source ) .Wait ( ) ; RemoveHandlerAsync ( source ) .Wait ( ) ; source.FireEvent ( ) ; if ( removed & & handled ) Console.WriteLine ( `` Event handled after removal ! `` ) ; else Console.WriteLine ( `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- '' ) ; } Console.ReadKey ( ) ; } private async static Task AddHandlerAsync ( EventSource source ) { await Task.Run ( ( ) = > { System.Windows.WeakEventManager < EventSource , EventArgs > .AddHandler ( source , `` Fired '' , HandleEvent ) ; added = true ; } ) ; } private async static Task RemoveHandlerAsync ( EventSource source ) { await Task.Run ( ( ) = > { System.Windows.WeakEventManager < EventSource , EventArgs > .RemoveHandler ( source , `` Fired '' , HandleEvent ) ; removed = true ; } ) ; } private static void HandleEvent ( object sender , EventArgs e ) { handled = true ; } }",WeakEventManager RemoveHandler does not always work when called asynchronously "C_sharp : If you employ a using clause to dispose of a connection , are other items within the clause that implement IDisposable also automatically disposed ? If not , how do you handle making sure all IDisposable items are automatically disposed ? public static DataTable ReturnDataTable ( string ConnectionString , string CommandTextString , CommandType CommandType , int CommandTimeout , List < System.Data.SqlClient.SqlParameter > ParameterList = null ) { using ( System.Data.SqlClient.SqlConnection Connection = new System.Data.SqlClient.SqlConnection ( ) ) { Connection.ConnectionString = ConnectionString ; System.Data.SqlClient.SqlCommand Command = new System.Data.SqlClient.SqlCommand ( ) ; Command.Connection = Connection ; Command.CommandText = CommandTextString ; Command.CommandType = CommandType ; Command.CommandTimeout = CommandTimeout ; if ( ParameterList ! = null ) { if ( ParameterList.Count > 0 ) { foreach ( SqlParameter parameter in ParameterList ) { Command.Parameters.AddWithValue ( parameter.ParameterName , parameter.Value ) ; } } } System.Data.DataTable DataTable = new System.Data.DataTable ( ) ; System.Data.SqlClient.SqlDataAdapter DataAdapter = new System.Data.SqlClient.SqlDataAdapter ( ) ; DataAdapter.SelectCommand = Command ; DataAdapter.Fill ( DataTable ) ; return DataTable ; } }",C # 'using ' statement question "C_sharp : I am using LINQ with entity framework in my application . I have repository method to get a page of data like this : I would like to have another repository method so that I can retrieve the page on which a sample is . The method signature would be something like : I am struggling to find a way to do it in LINQ . The only idea I have for now is to fetch the pages one after one until I find the needed sample . I know it is not efficient but the requirement is that there are no more than 500 samples and the page size is 25.How I could do this more efficiently ? public IEnumerable < Sample > GetPageData ( int orderId , int page , int itemsPerPage ) { var samples = _context.Set < Sample > ( ) .Where ( s = > s.OrderId == orderId ) .OrderBy ( s = > s.Id ) .Skip ( itemsPerPage * page ) .Take ( itemsPerPage ) ; return samples ; } public int GetPage ( int orderId , int sampleId , int itemsPerPage ) { // ? ? ? }",Find out which page an item is on "C_sharp : Say you have a class with an event property . If you instantiate this class in a local context , without outside references , would assigning a lambda expression to the event prevent the instance from becoming garbage collected ? { var o = new MyClass ( ) ; o.MyClassEvent += ( args ) = > { } ; } // Will ' o ' be eligible for garbage collection here ?",Do lambdas assigned to an event prevent garbage collection of the owning object ? "C_sharp : I 'm working on a hacker rank problem and I believe my solution is correct . However , most of my test cases are being timed out . Could some one suggest how to improve the efficiency of my code ? The important part of the code starts at the `` Trie Class '' .The exact question can be found here : https : //www.hackerrank.com/challenges/contactsEDIT : I did some suggestions in the comments but realized that I ca n't replace s.Substring ( 1 ) with s [ 0 ] ... because I actually need s [ 1..n ] . AND s [ 0 ] returns a char so I 'm going to need to do .ToString on it anyways.Also , to add a little more information . The idea is that it needs to count ALL names after a prefix for example . using System ; using System.Collections.Generic ; using System.IO ; class Solution { static void Main ( String [ ] args ) { int N = Int32.Parse ( Console.ReadLine ( ) ) ; string [ , ] argList = new string [ N , 2 ] ; for ( int i = 0 ; i < N ; i++ ) { string [ ] s = Console.ReadLine ( ) .Split ( ) ; argList [ i , 0 ] = s [ 0 ] ; argList [ i , 1 ] = s [ 1 ] ; } Trie trie = new Trie ( ) ; for ( int i = 0 ; i < N ; i++ ) { switch ( argList [ i , 0 ] ) { case `` add '' : trie.add ( argList [ i , 1 ] ) ; break ; case `` find '' : Console.WriteLine ( trie.find ( argList [ i , 1 ] ) ) ; break ; default : break ; } } } } class Trie { Trie [ ] trieArray = new Trie [ 26 ] ; private int findCount = 0 ; private bool data = false ; private char name ; public void add ( string s ) { s = s.ToLower ( ) ; add ( s , this ) ; } private void add ( string s , Trie t ) { char first = Char.Parse ( s.Substring ( 0 , 1 ) ) ; int index = first - ' a ' ; if ( t.trieArray [ index ] == null ) { t.trieArray [ index ] = new Trie ( ) ; t.trieArray [ index ] .name = first ; } if ( s.Length > 1 ) { add ( s.Substring ( 1 ) , t.trieArray [ index ] ) ; } else { t.trieArray [ index ] .data = true ; } } public int find ( string s ) { int ans ; s = s.ToLower ( ) ; find ( s , this ) ; ans = findCount ; findCount = 0 ; return ans ; } private void find ( string s , Trie t ) { if ( t == null ) { return ; } if ( s.Length > 0 ) { char first = Char.Parse ( s.Substring ( 0 , 1 ) ) ; int index = first - ' a ' ; find ( s.Substring ( 1 ) , t.trieArray [ index ] ) ; } else { for ( int i = 0 ; i < 26 ; i++ ) { if ( t.trieArray [ i ] ! = null ) { find ( `` '' , t.trieArray [ i ] ) ; } } if ( t.data == true ) { findCount++ ; } } } } Input : `` He '' Trie Contains : '' Hello '' '' Help '' '' Heart '' '' Ha '' '' No '' Output : 3",How can I make my trie more efficient ? "C_sharp : I 'm using a MediaPlayerLauncher to show movietrailers in my WP7 application , like this : This works just fine , except one thing : if the user is already listening to music in the background , and launch a trailer , the music is not resumed after the trailer is done playing ( or if the user closes the video ) . Does anyone know how i can resume the previously playing music/media , if even possible ? MediaPlayerLauncher mpl = new MediaPlayerLauncher ( ) ; mpl.Media = new Uri ( trailerUrl , UriKind.Absolute ) ; mpl.Controls = MediaPlaybackControls.All ; mpl.Show ( ) ;",MediaPlayerLauncher on WP7 - how to resume previously playing media ? "C_sharp : I have n't found anything useful either on Google or Stack Overflow or simply no answers ( or maybe I just do n't know what to search for ) -- the closest question I can get to is this one : The reason behind slow performance in WPFBut I want to get to the bottom of this lag in this simple program , maybe I 'm just not doing something right.I 'm rendering about 2000 points with lines between them in the OnRender ( ) of a UI Element , essentially creating a line graph . That 's okay , but I want to pan the graph with MouseMove . That works fine , but it is the LAG that is the problem . Whenever dragging with the mouse I 'd expect a smooth update , I 'd think that redrawing 2000 points with lines between them would be a walk in the park for an i5 CPU . But it is incredibly slow , even at low resolutions on my laptop at home . So I checked the Performance Profiler . The OnRender ( ) function hardly uses any CPU.It turns out it 's the Layout that 's changing and using so much CPU . `` Layout '' is taking the most time to completeNow , I 've heard the term Visual Tree kicking about , but there is hardly any visuals in this simple project . Just a UI Element on a Main Window . And it 's using a drawing context , I 'd have thought that the drawing context drew like a bitmap , or is it drawing UI elements with their own events/hit boxes etc ? Because all I want is the UIElement to act like an image but also handle mouse events so I can drag the whole thing ( or zoom with mousewheel ) .So Questions : If Layout is causing the slowness/lag , how can I prevent this ? I also Notice a lot of garbage collection which makes sense , but I do n't want it to happen during Rendering . I 'd rather do that while it 's idle . but how ? Here is the source : .cs file.XAML file using System ; using System.Collections.Generic ; using System.Globalization ; using System.Windows ; using System.Windows.Media ; namespace SlowChart { public class SlowChartClass : UIElement { List < Point > points = new List < Point > ( ) ; double XAxis_Width = 2000 ; double XAxis_LeftMost = 0 ; double YAxis_Height = 300 ; double YAxis_Lowest = -150 ; Point mousePoint ; double XAxis_LeftMostPan = 0 ; double YAxis_LowestPan = 0 ; public SlowChartClass ( ) { for ( int i = 0 ; i < 2000 ; i++ ) { double cos = ( float ) Math.Cos ( ( ( double ) i / 100 ) * Math.PI * 2 ) ; cos *= 100 ; points.Add ( new Point ( i , cos ) ) ; } MouseDown += SlowChartClass_MouseDown ; MouseUp += SlowChartClass_MouseUp ; MouseMove += SlowChartClass_MouseMove ; } private void SlowChartClass_MouseMove ( object sender , System.Windows.Input.MouseEventArgs e ) { if ( IsMouseCaptured ) { XAxis_LeftMost = XAxis_LeftMostPan - ( e.GetPosition ( this ) .X - mousePoint.X ) ; YAxis_Lowest = YAxis_LowestPan + ( e.GetPosition ( this ) .Y - mousePoint.Y ) ; InvalidateVisual ( ) ; } } private void SlowChartClass_MouseUp ( object sender , System.Windows.Input.MouseButtonEventArgs e ) { ReleaseMouseCapture ( ) ; } private void SlowChartClass_MouseDown ( object sender , System.Windows.Input.MouseButtonEventArgs e ) { mousePoint = e.GetPosition ( this ) ; XAxis_LeftMostPan = XAxis_LeftMost ; YAxis_LowestPan = YAxis_Lowest ; CaptureMouse ( ) ; } double translateYToScreen ( double Y ) { double y = RenderSize.Height - ( RenderSize.Height * ( ( Y - YAxis_Lowest ) / YAxis_Height ) ) ; return y ; } double translateXToScreen ( double X ) { double x = ( RenderSize.Width * ( ( X - XAxis_LeftMost ) / XAxis_Width ) ) ; return x ; } protected override void OnRender ( DrawingContext drawingContext ) { bool lastPointValid = false ; Point lastPoint = new Point ( ) ; Rect window = new Rect ( RenderSize ) ; Pen pen = new Pen ( Brushes.Black , 1 ) ; // fill background drawingContext.DrawRectangle ( Brushes.White , null , window ) ; foreach ( Point p in points ) { Point screenPoint = new Point ( translateXToScreen ( p.X ) , translateYToScreen ( p.Y ) ) ; if ( lastPointValid ) { // draw from last to this one drawingContext.DrawLine ( pen , lastPoint , screenPoint ) ; } lastPoint = screenPoint ; lastPointValid = true ; } // draw axis drawingContext.DrawText ( new FormattedText ( XAxis_LeftMost.ToString ( `` 0.0 '' ) + `` , '' + YAxis_Lowest.ToString ( `` 0.0 '' ) , CultureInfo.InvariantCulture , FlowDirection.LeftToRight , new Typeface ( `` Arial '' ) ,12 , Brushes.Black ) , new Point ( 0 , RenderSize.Height-12 ) ) ; } } } < Window x : Class= '' SlowChart.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : SlowChart '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < Grid > < local : SlowChartClass/ > < /Grid > < /Window >",WPF MouseMove InvalidateVisual OnRender update VERY SLOW "C_sharp : In my below code , I 'm locking the guid , to try and make it thread safe.With my example application , I will get a `` duplicate key '' about every 10 times I run the program . Aka , I get a duplicate , which is not what I need.Is there anyway to make the `` .NextGuid '' thread safe ? My code is a combination of : Making Guid properties threadsafeIncrement Guid in C # Since I 'm getting `` Why not use Guid.NewGuid '' questions , I 'll provide the reason here : I have a parent process that has a uniqueidentifier which is created by Guid.NewGuid ( ) . I 'll refer to this as the `` parent guid '' . That parent process will create N number of files . If I were writing from scratch , I would just append the `` N '' at the end of the filename . So if the parent Guid was `` 11111111-1111-1111-1111-111111111111 '' for example , I would write files , etc , etc . However , via the existing `` contract '' with the client : : : the filename must have a ( unique ) Guid in it and not have that `` N '' ( 1,2 , etc , etc ) value in the filename ( this `` contract '' has been in existence for years , so its set in stone pretty much ) . With the functionality laid out here , I 'll be able to keep the `` contract '' , but have file names that are loosely tied to the `` parent '' Guid ( which again the parent is generated by Guid.NewGuid ( ) ) . Collision is NOT an issue with the filenames ( they are put under a distinct folder for the 'process ' execution ) . Collision is an issue with the `` parent '' Guid . But again , that is already handled with Guid.NewGuid.So with a starting Guid of `` 11111111-1111-1111-1111-111111111111 '' , I 'll be able to write filenames like : So in my example above , the `` parent guid '' is represented by `` this.StartingGuid '' ... .and then I get `` incremented '' guid 's off of that.And also . I can write better unit-tests , because now I will know the filenames ahead of time.APPEND : Final Code Version : and UnitTests : using System ; namespace MyConsoleOne.BAL { public class GuidStore { private static object objectlock = new object ( ) ; private Guid StartingGuid { get ; set ; } private Guid ? LastGuidHolder { get ; set ; } public GuidStore ( Guid startingGuid ) { this.StartingGuid = startingGuid ; } public Guid ? GetNextGuid ( ) { lock ( objectlock ) { if ( this.LastGuidHolder.HasValue ) { this.LastGuidHolder = Increment ( this.LastGuidHolder.Value ) ; } else { this.LastGuidHolder = Increment ( this.StartingGuid ) ; } } return this.LastGuidHolder ; } private Guid Increment ( Guid guid ) { byte [ ] bytes = guid.ToByteArray ( ) ; byte [ ] order = { 15 , 14 , 13 , 12 , 11 , 10 , 9 , 8 , 6 , 7 , 4 , 5 , 0 , 1 , 2 , 3 } ; for ( int i = 0 ; i < 16 ; i++ ) { if ( bytes [ order [ i ] ] == byte.MaxValue ) { bytes [ order [ i ] ] = 0 ; } else { bytes [ order [ i ] ] ++ ; return new Guid ( bytes ) ; } } throw new OverflowException ( `` Guid.Increment failed . `` ) ; } } } using MyConsoleOne.BAL ; using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace MyConsoleOne { class Program { static void Main ( string [ ] args ) { GuidStore gs = new GuidStore ( Guid.NewGuid ( ) ) ; for ( int i = 0 ; i < 1000 ; i++ ) { Console.WriteLine ( i ) ; Dictionary < Guid , int > guids = new Dictionary < Guid , int > ( ) ; Parallel.For ( 0 , 1000 , j = > { Guid ? currentGuid = gs.GetNextGuid ( ) ; guids.Add ( currentGuid.Value , j ) ; Console.WriteLine ( currentGuid ) ; } ) ; // Parallel.For } Console.WriteLine ( `` Press ENTER to Exit '' ) ; Console.ReadLine ( ) ; } } } `` 11111111-1111-1111-1111-111111111111_1.txt '' '' 11111111-1111-1111-1111-111111111111_2.txt '' '' 11111111-1111-1111-1111-111111111111_3.txt '' OTHERSTUFF_111111111-1111-1111-1111-111111111112_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-111111111113_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-111111111114_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-111111111115_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-111111111116_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-111111111117_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-111111111118_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-111111111119_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-11111111111a_MORESTUFF.txtOTHERSTUFF_111111111-1111-1111-1111-11111111111b_MORESTUFF.txt public class GuidStore { private static object objectlock = new object ( ) ; private static int [ ] byteOrder = { 15 , 14 , 13 , 12 , 11 , 10 , 9 , 8 , 6 , 7 , 4 , 5 , 0 , 1 , 2 , 3 } ; private Guid StartingGuid { get ; set ; } private Guid ? LastGuidHolder { get ; set ; } public GuidStore ( Guid startingGuid ) { this.StartingGuid = startingGuid ; } public Guid GetNextGuid ( ) { return this.GetNextGuid ( 0 ) ; } public Guid GetNextGuid ( int firstGuidOffSet ) { lock ( objectlock ) { if ( this.LastGuidHolder.HasValue ) { this.LastGuidHolder = Increment ( this.LastGuidHolder.Value ) ; } else { this.LastGuidHolder = Increment ( this.StartingGuid ) ; for ( int i = 0 ; i < firstGuidOffSet ; i++ ) { this.LastGuidHolder = Increment ( this.LastGuidHolder.Value ) ; } } return this.LastGuidHolder.Value ; } } private static Guid Increment ( Guid guid ) { var bytes = guid.ToByteArray ( ) ; var canIncrement = byteOrder.Any ( i = > ++bytes [ i ] ! = 0 ) ; return new Guid ( canIncrement ? bytes : new byte [ 16 ] ) ; } } public class GuidStoreUnitTests { [ TestMethod ] public void GetNextGuidSimpleTest ( ) { Guid startingGuid = new Guid ( `` 11111111-1111-1111-1111-111111111111 '' ) ; GuidStore gs = new GuidStore ( startingGuid ) ; List < Guid > guids = new List < Guid > ( ) ; const int GuidCount = 10 ; for ( int i = 0 ; i < GuidCount ; i++ ) { guids.Add ( gs.GetNextGuid ( ) ) ; } Assert.IsNotNull ( guids ) ; Assert.AreEqual ( GuidCount , guids.Count ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111112 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111113 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111114 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111115 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111116 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111117 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111118 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-111111111119 '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-11111111111a '' ) ) ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-11111111111b '' ) ) ) ; } [ TestMethod ] public void GetNextGuidWithOffsetSimpleTest ( ) { Guid startingGuid = new Guid ( `` 11111111-1111-1111-1111-111111111111 '' ) ; GuidStore gs = new GuidStore ( startingGuid ) ; List < Guid > guids = new List < Guid > ( ) ; const int OffSet = 10 ; guids.Add ( gs.GetNextGuid ( OffSet ) ) ; Assert.IsNotNull ( guids ) ; Assert.AreEqual ( 1 , guids.Count ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == new Guid ( `` 11111111-1111-1111-1111-11111111111c '' ) ) ) ; } [ TestMethod ] public void GetNextGuidMaxRolloverTest ( ) { Guid startingGuid = new Guid ( `` ffffffff-ffff-ffff-ffff-ffffffffffff '' ) ; GuidStore gs = new GuidStore ( startingGuid ) ; List < Guid > guids = new List < Guid > ( ) ; const int OffSet = 10 ; guids.Add ( gs.GetNextGuid ( OffSet ) ) ; Assert.IsNotNull ( guids ) ; Assert.AreEqual ( 1 , guids.Count ) ; Assert.IsNotNull ( guids.FirstOrDefault ( g = > g == Guid.Empty ) ) ; } [ TestMethod ] public void GetNextGuidThreadSafeTest ( ) { Guid startingGuid = Guid.NewGuid ( ) ; GuidStore gs = new GuidStore ( startingGuid ) ; /* The `` key '' of the ConcurrentDictionary must be unique , so this will catch any duplicates */ ConcurrentDictionary < Guid , int > guids = new ConcurrentDictionary < Guid , int > ( ) ; Parallel.For ( 0 , 1000 , j = > { Guid currentGuid = gs.GetNextGuid ( ) ; if ( ! guids.TryAdd ( currentGuid , j ) ) { throw new ArgumentOutOfRangeException ( `` GuidStore.GetNextGuid ThreadSafe Test Failed '' ) ; } } ) ; // Parallel.For } [ TestMethod ] public void GetNextGuidTwoRunsProduceSameResultsTest ( ) { Guid startingGuid = Guid.NewGuid ( ) ; GuidStore gsOne = new GuidStore ( startingGuid ) ; /* The `` key '' of the ConcurrentDictionary must be unique , so this will catch any duplicates */ ConcurrentDictionary < Guid , int > setOneGuids = new ConcurrentDictionary < Guid , int > ( ) ; Parallel.For ( 0 , 1000 , j = > { Guid currentGuid = gsOne.GetNextGuid ( ) ; if ( ! setOneGuids.TryAdd ( currentGuid , j ) ) { throw new ArgumentOutOfRangeException ( `` GuidStore.GetNextGuid ThreadSafe Test Failed '' ) ; } } ) ; // Parallel.For gsOne = null ; GuidStore gsTwo = new GuidStore ( startingGuid ) ; /* The `` key '' of the ConcurrentDictionary must be unique , so this will catch any duplicates */ ConcurrentDictionary < Guid , int > setTwoGuids = new ConcurrentDictionary < Guid , int > ( ) ; Parallel.For ( 0 , 1000 , j = > { Guid currentGuid = gsTwo.GetNextGuid ( ) ; if ( ! setTwoGuids.TryAdd ( currentGuid , j ) ) { throw new ArgumentOutOfRangeException ( `` GuidStore.GetNextGuid ThreadSafe Test Failed '' ) ; } } ) ; // Parallel.For bool equal = setOneGuids.Select ( g = > g.Key ) .OrderBy ( i = > i ) .SequenceEqual ( setTwoGuids.Select ( g = > g.Key ) .OrderBy ( i = > i ) , new GuidComparer < Guid > ( ) ) ; Assert.IsTrue ( equal ) ; } } internal class GuidComparer < Guid > : IEqualityComparer < Guid > { public bool Equals ( Guid x , Guid y ) { return x.Equals ( y ) ; } public int GetHashCode ( Guid obj ) { return 0 ; } }",Building a thread-safe GUID increment'er "C_sharp : I have a console app , and I want to capture Control-C and shutdown gracefully.I have the following code : And the output windows shows : 6/16/2010 3:24:34 PM : Control+C hit . Shutting down . ^CIs there a way to prevent the control-c character ^C from appearing ? It 's not a huge deal , but for some reason Ill be fixated on it because I 'm anal like that . Console.CancelKeyPress += new ConsoleCancelEventHandler ( ( o , e ) = > { Logger.Log ( `` Control+C hit . Shutting down . `` ) ; resetEvent.Set ( ) ; } ) ;",C # Console Application : Preventing Control-C from being printed ? "C_sharp : Using C # , .NET 4.5.2 , Entity Framework 6.1.3 and System.Linq I have encountered a confusing exception . The exception itself does not seem to contain useful information to determined why it is being raised.The following line of code when executed results in a NullReferenceException : dbCtx.Customers.ToList ( ) ; However , the following line runs without exception and returns the correct result : ( dbCtx.Customers ) .ToList ( ) ; Running the parenthesis surrounded expression first will allow both forms to execute without exception : I would also like to note that adding entities works as expected : Customer entity class : BaseEntity class : DbContext class : What could possibly be causing this behavior ? EDIT : This problem occurs with any entity when anything like .ToList ( ) , .Count ( ) , etc is invoked.Exception Details : EDIT 2 : After experimentation I 've narrowed it down to a call to dbCtx.Database.CompatibleWithModel ( bool ) . Whether the argument supplied is true or false makes no difference . When I commented it out no NullReferenceException is raised later in the code . I have no idea why . Calling dbCtx.Database.Exists ( ) works fine.In addition , dbCtx.Database.Initialize ( false ) ; Also reliably produces the error ( not at callsite , but on xyz.ToList ( ) ) . var result1 = ( dbCtx.Customers ) .ToList ( ) ; var result2 = dbCtx.Customers.ToList ( ) ; dbCtx.Customers.Add ( new Customer ( ) { Enabled = true , Name = `` Test '' } ) ; public sealed class Customer : BaseEntity { public bool Enabled { get ; set ; } [ Required ] public string Name { get ; set ; } } public abstract class BaseEntity { [ Key ] [ DatabaseGeneratedAttribute ( DatabaseGeneratedOption.Identity ) ] public int Id { get ; set ; } } public class MyDbContext : DbContext { public MyDbContext ( ) : base ( @ '' Server=.\SQLExpress ; Database=MyDatabase ; Trusted_Connection=Yes ; '' ) { Configuration.LazyLoadingEnabled = true ; } public virtual DbSet < Customer > Customers { get ; set ; } } System.NullReferenceException occurred HResult=0x80004003 Message=Object reference not set to an instance of an object . Source=EntityFramework StackTrace : at System.Data.Entity.Internal.Linq.InternalSet ` 1.get_Expression ( ) at System.Data.Entity.Infrastructure.DbQuery ` 1.System.Linq.IQueryable.get_Expression ( ) at MyProjTests.Test1.Test ( MyDbContext dbCtx ) in E : \ProgrammingProjects\WorkInProgress\MyProjRoot\MyProjTests\Test1.cs : line 51 at MyProjTests.Test1.TestMethod1 ( ) in E : \ProgrammingProjects\WorkInProgress\MyProjRoot\MyProjTests\Test1.cs : line 43",EF6 NullReferenceException with any ToList ( ) "C_sharp : A table in my database has stored pictures , documents , dll halyards and so on . How do I implement the mapping of all this for a user ? I bind these data to a data table , and want to have hyperlinks in each cell , which when clicked , invokes/opens the corresponding item from the database.In DB next atributes : i_id ( number ) , i_objecttype_id ( number ) , s_code ( nvarchar ) , s_name ( nvarchar ) , m_content ( blob ) , m_description ( nvarchar ) On client I see next : i_id ( number ) , i_objecttype_id ( number ) , s_code ( nvarchar ) , s_name ( nvarchar ) , m_description ( nvarchar ) .Without atribute m_content . OracleCommand oracleCom = new OracleCommand ( ) ; oracleCom.Connection = oraConnect ; oracleCom.CommandText = `` Select * From `` + Session [ `` tableNameIns '' ] ; OracleDataAdapter adapter = new Oraenter code herecleDataAdapter ( ) ; DataTable tableD = new DataTable ( ) ; tableD.Locale = System.Globalization.CultureInfo.InvariantCulture ; adapter.SelectCommand = oracleCom ; adapter.Fill ( tableD ) ; changeTableAtributs ( tableD ) ; tableResults.DataSource = tableD.AsDataView ( ) ; tableResults.DataBind ( ) ;",How to display different objects in gridview ? "C_sharp : I have access to the .com zone files . A zone file is a text file with a list of domain names and their nameservers . It follows a format such as : As you can see , there can be multiple lines for each domain ( when there are multiple nameservers ) , and the file is NOT in alpha order.These files are about 7GB in size.I 'm trying to take the previous file and the new file , and compare them to find : What domains have been AddedWhat domains have been Removed What domains have had nameservers changedSince 7GB is too much to load the entire file into memory , Obviously I need to read in a stream . The method I 've currently thought up as the best way to do it is to make several passes over both files . One pass for each letter of the alphabet , loading all the domains in the first pass that start with ' a ' for example.Once I 've got all the ' a ' domains from the old and new file , I can do a pretty simple comparison in memory to find the changes.The problem is , even reading char by char , and optimizing as much as I 've been able to think of , each pass over the file takes about 200-300 seconds , with collecting all the domains for the current pass 's letter . So , I figure in its current state I 'm looking at about an hour to process the files , without even storing the changes in the database ( which will take some more time ) . This is on a dual quad core xeon server , so throwing more horsepower at it is n't much of an option for me.This timing may not be a dealbreaker , but I 'm hoping someone has some bright ideas for how to speed things up ... Admittedly I have not tried async IO yet , that 's my next step.Thanks in advance for any ideas ! mydomain NS ns.mynameserver.com.mydomain NS ns2.mynameserver.com.anotherdomain NS nameservers.com.notinalphadomain NS ns.example.com.notinalphadomain NS ns1.example.com.notinalphadomain NS ns2.example.com .",Finding Changes between 2 HUGE zone ( text ) files "C_sharp : Why does this work in VB.Net : But this is throwing an error in C # : Stream is a Type , which is not valid in the current contextTo be honest , I 'm not 100 % clued up on converting types , I 've only ever used them in code snippets and now I 'm trying to convert a simple VB code snippet to a C # version ... Dim ClipboardStream As New StreamReader ( CType ( ClipboardData.GetData ( DataFormats.CommaSeparatedValue ) , Stream ) ) ClipboardStream = new StreamReader ( Convert.ChangeType ( ClipboardData.GetData ( DataFormats.CommaSeparatedValue ) , Stream ) ) ;",VB vs C # — CType vs ChangeType "C_sharp : Take this bit of code : Of course it fails when assigning 1 to an enum-type variable . ( Slap an explicit cast and it 'll work . ) My question is : why does it NOT fail when assigning 0 ? enum En { val1 , val2 , } void Main ( ) { En plop = 1 ; //error : Can not implicitly convert type 'int ' to 'En ' En woop = 0 ; //no error }",C # enum - why does *implicit* casting from 0 work ? "C_sharp : I was playing around with a code golf question yesterday for building a christmas tree which came around last year and I threw together a quick recursive algorithm to do the job : I got to wondering if I could do the same thing with a Func : This would do the job except that the recursive part does n't recognize that the call to f is actually a call to itself . This would lead me to conclude that a Func ca n't call itself recursively - but I wonder if I 'm drawing false conclusions or if it can be done but requires a different approach.Any ideas ? static string f ( int n , int r ) { return `` \n '' .PadLeft ( 2 * r , '* ' ) .PadLeft ( n + r ) + ( r < n ? f ( n , ++r ) : `` * '' .PadLeft ( n ) ) ; } Func < int , int , string > f = ( n , r ) = > { return `` \n '' .PadLeft ( 2 * r , '* ' ) .PadLeft ( n + r ) + ( r < n ? f ( n , ++r ) : `` * '' .PadLeft ( n ) ) ; } ;",Can a Func < > call itself recursively ? "C_sharp : My setup : ASP.NET 4.5 web api ( on Azure ) saving data to SQL db ( also on Azure ) AngularJS web front end ( another Azure web site ) When a user first signs up , I show them a `` getting started intro '' . The intro is only supposed to run once - I log the timestamp of the intro launch date as a custom field in the ASP.NET user table . Imagine my surprise when I log in ( as a user would ) and see the intro TWICE.The AngularJS front end is properly sending the `` intro viewed '' message to the ASP.NET api , and the api responds with a success message . However , when I look at the raw data in the db , the timestamp is most definitely NOT updated . Consequently , the user will see the intro a second time ( at which point the timestamp gets recorded in the db properly ) .I have a crappy workaround . After the client requests an OAuth Bearer token from my server , the client then requests user information ( to decide whether or not to show the tour ) . Waiting 100ms and then sending the `` tour viewed '' message back to the server masks the issue.I 've not seen ANY other issues storing data at any point . Because our db is on Azure , I ca n't hook up Profiler and the built in auditing does n't give me any clues.Is there something about requesting the token that leaves ASP.NET identity in a funny state ? And it takes a brief wait before you can write to the table ? Are custom fields that extend the base Identity setup prone to problems like this ? Is the UserManager possibly doing something weird in its black box ? Does anyone have suggestions for how to continue debugging this problem ? Or ever hear of anything like it ? Here 's the relevant code that should be updating the `` tour viewed '' timestamp in the db : UPDATE ********* 4/18I 've also tried to move completely away from UserManager stuff . I 've tried the following modifications ( pulling the user data from a table like I would access any other data ) , but it still behaves the same . I 'm starting to think that putting custom fields on the ApplicationUser object is a bad idea ... New db retrieve and save looks like this : [ HttpPost , Route ( `` UserInfo '' ) ] public async Task < IHttpActionResult > UpdateUserInfo ( UpdateBindingModel model ) { var currentUser = UserManager.FindById ( User.Identity.GetUserId ( ) ) ; if ( model.FirstName ! = null ) { currentUser.FirstName = model.FirstName ; } if ( model.LastName ! = null ) { currentUser.LastName = model.LastName ; } if ( model.SetIntroViewCompleteDate ) { currentUser.IntroViewCompleteDate = DateTime.UtcNow ; } if ( model.SetIntroViewLaunchDate ) { currentUser.IntroViewLaunchDate = DateTime.UtcNow ; } if ( model.SetTipTourCompleteDate ) { currentUser.TipTourCompleteDate = DateTime.UtcNow ; } if ( model.SetTipTourLaunchDate ) { currentUser.TipTourLaunchDate = DateTime.UtcNow ; } IdentityResult result = await UserManager.UpdateAsync ( currentUser ) ; if ( result.Succeeded ) { var data = new UserInfoViewModel { FirstName = currentUser.FirstName , LastName = currentUser.LastName , IntroViewLaunchDate = currentUser.IntroViewLaunchDate } ; return Ok ( data ) ; } return InternalServerError ( ) ; } ApplicationDbContext newContext = new ApplicationDbContext ( ) ; var currentUser = await ( from c in newContext.Users where c.Email == User.Identity.Name select c ) .SingleOrDefaultAsync ( ) ; //update some values await newContext.SaveChangesAsync ( ) ;",SQL write to ASP.NET user table does n't save "C_sharp : Should you consider the use of Properties.Settings.Default within a class as a dependency , and therefore inject it ? e.g. : .. or would you consider the use of Settings as an application wide global as good practice ? e.g . : public class Foo { private _settings ; private bool _myBool ; public Foo ( Settings settings ) { this._settings = settings ; this._myBool = this._settings.MyBool ; } } public class Foo { private bool _myBool ; public Foo ( ) { this._myBool = Properties.Settings.Default.MyBool ; } }",Use dependency injection for Properties.Settings.Default ? "C_sharp : I 'm porting a C++ application to C # , and have run across templates . I 've read up a little on these , and I understand that some templates are akin to .Net generics . I read the SO answer to this case which nicely summed it up.However , some uses of c++ templating do n't seem to be directly related to generics . In the below example from Wikipedia 's Template metaprogramming article the template seems to accept a value , rather than a type . I 'm not quite sure how this would be ported to C # ? Clearly for this example I could do : but this seems to me to be a refactoring to a function , rather than a port to semantically similar code . template < int N > struct Factorial { enum { value = N * Factorial < N - 1 > : :value } ; } ; template < > struct Factorial < 0 > { enum { value = 1 } ; } ; // Factorial < 4 > : :value == 24// Factorial < 0 > : :value == 1void foo ( ) { int x = Factorial < 4 > : :value ; // == 24 int y = Factorial < 0 > : :value ; // == 1 } public int Factorial ( int N ) { if ( N == 0 ) return 1 ; return Factorial ( N - 1 ) ; }",Porting C++ to C # - templates "C_sharp : F # is giving me some trouble with its type inference rules . I 'm writing a simple computation builder but ca n't get my generic type variable constraints right.The code that I would want looks as follows in C # : The best ( but non-compiling code ) I 've come up with for the F # version so far is : Unfortunately , I have no clue how I would translate the where TA : TZ type constraint on the Bind method . I thought it should be something like ′a when ′a : > ′z , but the F # compiler does n't like this anywhere and I always end up with some generic type variable constrained to another.Could someone please show me the correct F # code ? Background : My goal is to be able to write an F # custom workflow like this : class FinallyBuilder < TZ > { readonly Action < TZ > finallyAction ; public FinallyBuilder ( Action < TZ > finallyAction ) { this.finallyAction = finallyAction ; } public TB Bind < TA , TB > ( TA x , Func < TA , TB > cont ) where TA : TZ { // ^^^^^^^^^^^^^ try // this is what gives me a headache { // in the F # version return cont ( x ) ; } finally { finallyAction ( x ) ; } } } type FinallyBuilder < ′z > ( finallyAction : ′z - > unit ) = member this.Bind ( x : ′a ) ( cont : ′a - > ′b ) = try cont x finally finallyAction ( x : > ′z ) // cast illegal due to missing constraint// Note : ' changed to ′ to avoid bad syntax highlighting here on SO . let cleanup = new FinallyBuilder ( fun x - > ... ) cleanup { let ! x = ... // x and y will be passed to the above lambda function at let ! y = ... // the end of this block ; x and y can have different types ! }",How do I translate a ` where T : U ` generic type parameter constraint from C # to F # ? "C_sharp : I have the following line of codeand it sets the value of i to 20 . Now my question is , are the two statements same ? and Both the statements will set the values as i = 20 and a = 20 . What 's the difference ? If they are same then why are there braces for equating the value ? int i = ( i = 20 ) ; int a = 0 ; int i = ( a = 20 ) ; int a = 0 ; int i = a = 20 ;",Initialization expression in c # "C_sharp : I am trying to compile a `` cookie aware '' version of the WebClient class - but I ca n't seem to get over some of the hurdles of using the Add-Type cmdlet added in PowerShell v2 . Here is the code I am trying to compile : It ca n't seem to find the CookieContainer type ca n't be found ( though it is fully qualified ... ) - clearly I am blind on something.Edit : Updated the sample code to be correct and copy-n-pasteable , thanks ! PS C : \ > $ def = @ '' public class CookieAwareWebClient : System.Net.WebClient { private System.Net.CookieContainer m_container = new System.Net.CookieContainer ( ) ; protected override System.Net.WebRequest GetWebRequest ( System.Uri address ) { System.Net.WebRequest request = base.GetWebRequest ( address ) ; if ( request is System.Net.HttpWebRequest ) { ( request as System.Net.HttpWebRequest ) .CookieContainer = m_container ; } return request ; } } '' @ PS C : \ > Add-Type -TypeDefinition $ def",Compiling new type in PowerShell v2 - Cookie Aware WebClient "C_sharp : After the recent Windows 10 Update ( Fall Creators Update ) the performance of our .NET c # 4.0 application had decreased a lot . I think there are various issues and one of them is log4net ( or disk IO ) . Our application is very complex ( various WCF applications and a ASPNET MVC 3.0 app ) and in development there are a lot of log4net traces . Loading the first page in startup lasts 4 or 5 minutes and before the updates lasts a minute , If I deactivate log4net the performance.I 've done a test with two cloned virtual machines , logging after a regex operation , and the diferrences are significant.The code : I 've done tests with log4net 1.2.1 and 2.0.8 : average beforeUpdate - > TOTAL Elapsed time : 600msaverage afterUpdate - > TOTAL Elapsed time : 1000msIt 's a very important issue for us , and I have n't found any info on the net. -- UPDATE -- I 've found another ( unanswered ) thread on stackoverflow : log4net became very slow with caller location information after Windows 10 Fall Creators Update ( 1709 ) I 've ran a disk benchmark on both environments and there 's no significant differences on read/write rates . I 've tested the application disabling completely log4net ( log4net threshold= '' OFF '' ) and now the timings are very similar , so , as @ DalmTo comments , there a lot of possibilities that it would be due to log4net , I 'll try to put an issue there , although there is already a related microsoft issue : https : //connect.microsoft.com/VisualStudio/feedback/details/3143189/after-installing-windows-10-1709-update-creating-a-stacktrace-class-has-become-a-magnitude-slower static void Main ( string [ ] args ) { Log.Info ( `` Log4net1 '' ) ; DateTime start = DateTime.Now ; for ( int i = 0 ; i < 50 ; i++ ) { DoTheThing ( ) ; } TimeSpan elapsedTime = DateTime.Now - start ; Log.DebugFormat ( `` TOTAL Elapsed time : { 0 } '' , elapsedTime.TotalMilliseconds ) ; Console.ReadKey ( ) ; } private static void DoTheThing ( ) { DateTime start = DateTime.Now ; Regex.Replace ( TEXT , `` nec `` , m = > { return `` ( word nec ) `` ; } ) ; TimeSpan elapsedTime = DateTime.Now - start ; Log.DebugFormat ( `` Elapsed time : { 0 } '' , elapsedTime.TotalMilliseconds ) ; }",Fall creators update performance issues "C_sharp : I am currently trying to write some code which turns C # Expressions into text.To do this , I need to not only walk through the Expression tree , but also evaluate just a little part of it - in order to get the current value of a local variable.I am finding very hard to put into words , so here is the pseudo-code instead . The missing part is in the first method : I have started investigating this using code like : but once I get to that MethodCallExpression level then I am feeling a bit lost about how to parse it and to then get the actual instance.Any pointers/suggestions on how to do this very much appreciated . public class Program { private static void DumpExpression ( Expression expression ) { // how do I dump out here some text like : // set T2 = Perform `` ExternalCalc '' on input.T1 // I can easily get to : // set T2 = Perform `` Invoke '' on input.T1 // but how can I substitute Invoke with the runtime value `` ExternalCalc '' ? } static void Main ( string [ ] args ) { var myEvaluator = new Evaluator ( ) { Name = `` ExternalCalc '' } ; Expression < Func < Input , Output > > myExpression = ( input ) = > new Output ( ) { T2 = myEvaluator.Invoke ( input.T1 ) } ; DumpExpression ( myExpression ) ; } } class Evaluator { public string Name { get ; set ; } public string Invoke ( string input ) { throw new NotImplementedException ( `` Never intended to be implemented '' ) ; } } class Input { public string T1 { get ; set ; } } class Output { public string T2 { get ; set ; } } foreach ( MemberAssignment memberAssignment in body.Bindings ) { Console.WriteLine ( `` assign to { 0 } '' , memberAssignment.Member ) ; Console.WriteLine ( `` assign to { 0 } '' , memberAssignment.BindingType ) ; Console.WriteLine ( `` assign to { 0 } '' , memberAssignment.Expression ) ; var expression = memberAssignment.Expression ; if ( expression is MethodCallExpression ) { var methodCall = expression as MethodCallExpression ; Console.WriteLine ( `` METHOD CALL : `` + methodCall.Method.Name ) ; Console.WriteLine ( `` METHOD CALL : `` + expression.Type.Name ) ; var target = methodCall.Object ; // ? } }",Extracting the current value of an instance variable while walking an Expression C_sharp : I tried this : But that give me : But I do n't have the directory AppData there only : How do I get the Videos directory without the AppData ? userVideosDirectory = Directory.GetParent ( Environment.GetFolderPath ( Environment.SpecialFolder.ApplicationData ) ) .FullName + `` \\Videos '' ; C : \Users\username\AppData\Videos C : \Users\username\Videos,How to get user videos directory ? "C_sharp : ( This is kind of a follow-up to my question `` How to use C # 6 with Web Site project type ? `` ) I 'm trying to use C # 7 features with Visual Studio 2017.For this , I 've updated the Microsoft.Net.Compilers NuGet package to v2.0.0-rc4 in my existing ASP.NET WebForms 4.6.2 application.It seems to work well from inside Visual Studio 2017.When deployed to my website , all I see is a yellow screen of death : Compiler error with error code 255 . [ Detailed compiler output ] Version information : Microsoft .NET Framework version : 4.0.30319 ; ASP.NET version : 4.6.1590.0The full compiler source is too long to be posted here ( more than 30k chars ) , I 've uploaded it to Pastebin.My question : Is there any chance to use the latest Roslyn compiler within an ASP.NET WebForms Web Application ? Update 1 : Of course , I 've included the Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package and web.config entries , as described here.I 've even tried to change the /langversion:6 parameter in above 's XML to /langversion:7 with no different result.Update 2 : Probably the question and answer would be similar for using C # 7 features from within ASP.NET MVC views inside .cshtml Razor files.Update 3 : I 've dug through the Event Log and found these ( German system , sorry ) : and : < system.codedom > < compilers > < compiler language= '' c # ; cs ; csharp '' extension= '' .cs '' type= '' Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider , Microsoft.CodeDom.Providers.DotNetCompilerPlatform , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 '' warningLevel= '' 4 '' compilerOptions= '' /langversion:6 /nowarn:1659 ; 1699 ; 1701 '' / > < compiler language= '' vb ; vbs ; visualbasic ; vbscript '' extension= '' .vb '' type= '' Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider , Microsoft.CodeDom.Providers.DotNetCompilerPlatform , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=31bf3856ad364e35 '' warningLevel= '' 4 '' compilerOptions= '' /langversion:14 /nowarn:41008 /define : _MYTYPE=\ & quot ; Web\ & quot ; /optionInfer+ '' / > < /compilers > < /system.codedom > Anwendung : csc.exe Frameworkversion : v4.0.30319 Beschreibung : Der Prozess wurde aufgrund einer unbehandelten Ausnahme beendet . Ausnahmeinformationen : System.IO.FileLoadException bei Microsoft.CodeAnalysis.CommandLine.BuildClient.GetCommandLineWindows ( System.Collections.Generic.IEnumerable ' 1 < System.String > ) bei Microsoft.CodeAnalysis.CommandLine.DesktopBuildClient.Run ( System.Collections.Generic.IEnumerable ' 1 < System.String > , System.Collections.Generic.IEnumerable ' 1 < System.String > , Microsoft.CodeAnalysis.CommandLine.RequestLanguage , Microsoft.CodeAnalysis.CommandLine.CompileFunc , Microsoft.CodeAnalysis.IAnalyzerAssemblyLoader ) bei Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main ( System.String [ ] , System.String [ ] ) bei Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main ( System.String [ ] ) Exception information : Exception type : HttpCompileException Exception message : Eine externe Komponente hat eine Ausnahme ausgelöst . bei System.Web.Compilation.AssemblyBuilder.Compile ( ) bei System.Web.Compilation.BuildProvidersCompiler.PerformBuild ( ) bei System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly ( VirtualPath virtualDir , CodeDirectoryType dirType , String assemblyName , StringSet excludedSubdirectories , Boolean isDirectoryAllowed ) bei System.Web.Compilation.BuildManager.CompileCodeDirectory ( VirtualPath virtualDir , CodeDirectoryType dirType , String assemblyName , StringSet excludedSubdirectories ) bei System.Web.Compilation.BuildManager.CompileResourcesDirectory ( ) bei System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled ( ) bei System.Web.Compilation.BuildManager.CallAppInitializeMethod ( ) bei System.Web.Hosting.HostingEnvironment.Initialize ( ApplicationManager appManager , IApplicationHost appHost , IConfigMapPathFactory configMapPathFactory , HostingEnvironmentParameters hostingParameters , PolicyLevel policyLevel , Exception appDomainCreationException )",How to use C # 7 within Web Application ASPX code-before pages ? "C_sharp : Given a method like this : can I write a comment such that Visual Studio will correctly display it , if T1 is an int and T2 is a string , for example ? Or , am I stuck with T1 and T2 appearing in the comment ? Said differently : is there something I can do so that in Visual Studio , the tooltip on this method shows the actual type names ? Edit : I seem to have not explained what I 'm actually interested in knowing . Suppose I have a class called Widget < T1 , T2 > . Suppose I have a method like the one above.Then , when I doEdit 2 : Someone commented here a moment ago but their comment was deleted . They suggested I use Which is what I 'm using now . This is fine . My question , phrased differently for the third time now , is Visual Studio smart enough to infer what T1 and T2 are from a constructor ? I can figure out what T1 and T2 are from the method signature , and I thought maybe Visual Studio could do the same and support this in the comment.My gut feeling is no , but hence the question . /// < summary > /// Given a < see cref= '' T1 '' / > , return a < see cref= '' T2 '' / > ./// < /summary > public T2 ExampleMethod ( T1 t1 ) { // omitted } Widget < int , string > myExample = new Widget < int , string > ( ) ; myExample.ExampleMethod ( ... ) ; // HERE - if I mouse over the method // I get a tooltip . Is there something I can do to the comment in my // example method above that will allow me to say // `` Given a System.Int32 , return a System.String '' ? ///Given a < see cref= '' T1 '' / > , return a < see cref= '' T2 '' / > .",Commenting Generics - Is it possible to refer to generic type parameter not as T but as its actual type ? "C_sharp : Consider this code : I have a switch case that has default.So if the number is not 1,2 or 3 result to be Failed.So i convert the code to delegate dictionary : How can I set default for delegate dictionary pattern ? switch ( number ) { case 1 : Number = ( int ) SmsStatusEnum.Sent ; break ; case 2 : Number = ( int ) SmsStatusEnum.Delivered ; break ; case 3 : Number = ( int ) SmsStatusEnum.Failed ; break ; default : Number = ( int ) SmsStatusEnum.Failed ; break ; } return Number ; var statuses = new Dictionary < int , Func < SmsStatusEnum > > { { 1 , ( ) = > SmsStatusEnum.Sent } , { 2 , ( ) = > SmsStatusEnum.Delivered } , { 3 , ( ) = > SmsStatusEnum.Failed } , } ;",Default for delegate dictionary pattern "C_sharp : I 'm trying to use ToUpperInvariant ( ) within a LINQ query with RavenDB . I 'm getting an InvalidOperationException : Can not understand how to translate server.Name.ToUpperInvariant ( ) .The query is below . What needs to happen in order for me to be able to match by name here ? Is this possible within a query using RavenDB ? public ApplicationServer GetByName ( string serverName ) { return QuerySingleResultAndCacheEtag ( session = > session.Query < ApplicationServer > ( ) .Where ( server = > server.Name.ToUpperInvariant ( ) == serverName.ToUpperInvariant ( ) ) .FirstOrDefault ( ) ) as ApplicationServer ; } protected static EntityBase QuerySingleResultAndCacheEtag ( Func < IDocumentSession , EntityBase > func ) { if ( func == null ) { throw new ArgumentNullException ( `` func '' ) ; } using ( IDocumentSession session = Database.OpenSession ( ) ) { EntityBase entity = func.Invoke ( session ) ; if ( entity == null ) { return null ; } CacheEtag ( entity , session ) ; return entity ; } }",RavenDB Linq Invalid Operation .ToUpperInvariant ( ) "C_sharp : I 'm using the native C # HTTP client with a handler to process Windows Authentication and I 'm having ObjectDisposedException.Any idea ? using ( var httpClientHandler = new HttpClientHandler { Credentials = CredentialCache.DefaultNetworkCredentials } ) { bool disposeHandler = true ; //Setting true or false does not fix the problem using ( var httpClient = new HttpClient ( httpClientHandler , disposeHandler ) ) { using ( var content = new ByteArrayContent ( Encoding.UTF8.GetBytes ( `` Hello '' ) ) ) { // Commenting/uncommenting the line below does not fix the problem // httpRequestMessage.Headers.Connection.Add ( `` Keep-Alive '' ) ; using ( var httpResponseMessage = await httpClient.PostAsync ( `` http : //SomeUrl '' , content ) ) // This line throws an ObjectDisposedException { } } } }",C # HttpClient and Windows Authentication : Can not access a closed Stream "C_sharp : I ran into this piece of code : Is there any point in making this a .forEach delegate , or could it be just a normal foreach loop ? As long as the function that contains the loop is in is async , this would be async by default ? items.ForEach ( async item = > { doSomeStuff ( ) ; await mongoItems.FindOneAndUpdateAsync ( mongoMumboJumbo ) ; await AddBlah ( SqlMumboJumbo ) ; } ) ;",Any point to List < T > .ForEach ( ) with Async ? "C_sharp : I 'm trying to pass .NET array to COM VB6 library . I have an object which is COM wrapper of VB6 object . It has method with the following signature : but when I call it I get an ArgumentException with the following message : Value does not fall within the expected range.The type of exception and its description does n't even depend on passed element.Does anybody know how to go around this issue ? UPD : I removed .NET wrapper assemblies and referrenced source .COM libraries . No changes had happened . [ MethodImpl ( MethodImplOptions.InternalCall , MethodCodeType = MethodCodeType.Runtime ) ] void AddEx ( [ MarshalAs ( UnmanagedType.Struct ) ] object vSafeArrayOfItems ) ;",Passing C # array of COM objects to VB6 "C_sharp : In my app , I 'm storing Bitmap data in a two-dimensional integer array ( int [ , ] ) . To access the R , G and B values I use something like this : I 'm using integer arrays instead of an actual System.Drawing.Bitmap because my app runs on Windows Mobile devices where the memory available for creating bitmaps is severely limited.I 'm wondering , though , if it would make more sense to declare a structure like this : ... and then use an array of RGB instead of an array of int . This way I could easily read and write the separate R , G and B values without having to do bit-shifting and BitConverter-ing . I vaguely remember something from days of yore about byte variables being block-aligned on 32-bit systems , so that a byte actually takes up 4 bytes of memory instead of just 1 ( but maybe this was just a Visual Basic thing ) .Would using an array of structs ( like the RGB example ` above ) be faster than using an array of ints , and would it use 3/4 the memory or 3 times the memory of ints ? // read : int i = _data [ x , y ] ; byte B = ( byte ) ( i > > 0 ) ; byte G = ( byte ) ( i > > 8 ) ; byte R = ( byte ) ( i > > 16 ) ; // write : _data [ x , y ] = BitConverter.ToInt32 ( new byte [ ] { B , G , R , 0 } , 0 ) ; public struct RGB { public byte R ; public byte G ; public byte B ; }",Integer array or struct array - which is better ? "C_sharp : I am new to IOC in general and I 'm struggling a little to understand whether what I am trying to do makes any sense . I have a web forms application in which I want to create one module to define some bindings for me . The bindings will be used to inject repositories into my business manager classes , allowing me to unit test the business managers . Also I would like to use the container to inject the Entity Framework context into my repositories that way they all share the same context per http request . So here is what I am wondering : I understand that I need to have the same kernel instance manage my object creation and their lifetime . For example if I want a one-per-httprequest type scenario I need the instance of the kernel to be available for that period of time . What if I need a singleton ? Then it has to be application scoped somehow . So where exactly do I store the IKernel instance ? It seems that I might want to make it a static in my Global.asax , is that the right approach and is thread safety a concern ? Since I am using Bind < > to define my bindings , how do I go about making that definition in the Web/UI layer when I should n't be referencing my data access layer from the UI ? My references look like .Web -- > .Business -- > DataAccess . It seems like I want to tell the kernel `` hey manage my data access instances , but do n't have a reference to them at compile time . '' A binding such as this : I feel like I might be approaching this incorrectly , thank you . //Any object requesting an instance of AdventureWorksEntities will get an instance per request Bind < AdventureWorksEntities > ( ) .ToSelf ( ) .InRequestScope ( ) ;",Where to store Ninject IKernel in a web application ? "C_sharp : I 'm receiving a multipart content response that belongs to an OAuth batch request : If I read its content as full text : This is what it contains : I need to get all these contents as objects ( like classics HttpResponseMessage , not simple strings ) , in order to get the HTTP return code , the JSON content , etc . as properties and be able to treat them.I know how to read separatly all these contents , but I ca n't figure how to get them as objects , I 've only succeeded in getting a string content : In my example , testString contains : I ca n't just imagine to parse manually this string ... So if someone has a clue or can explain me the good way to read the content , it would be nice.Thanks , Max // batchRequest is a HttpRequestMessage , http is an HttpClientHttpResponseMessage response = await http.SendAsync ( batchRequest ) ; string fullResponse = await response.Content.ReadAsStringAsync ( ) ; -- batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16Content-Type : application/httpContent-Transfer-Encoding : binaryHTTP/1.1 200 OKDataServiceVersion : 3.0 ; Content-Type : application/json ; odata=minimalmetadata ; streaming=true ; charset=utf-8 { \ '' odata.metadata\ '' : \ '' https : //graph.windows.net/XXX.onmicrosoft.com/ $ metadata # directoryObjects/ @ Element\ '' , \ '' odata.type\ '' : \ '' Microsoft.DirectoryServices.User\ '' , \ '' objectType\ '' : \ '' User\ '' , \ '' objectId\ '' : \ '' 5f6851c3-99cc-4a89-936d-4bb44fa78a34\ '' , \ '' deletionTimestamp\ '' : null , \ '' accountEnabled\ '' : true , \ '' signInNames\ '' : [ ] , \ '' assignedLicenses\ '' : [ ] , \ '' assignedPlans\ '' : [ ] , \ '' city\ '' : null , \ '' companyName\ '' : null , \ '' country\ '' : null , \ '' creationType\ '' : null , \ '' department\ '' : \ '' NRF\ '' , \ '' dirSyncEnabled\ '' : null , \ '' displayName\ '' : \ '' dummy1 Test\ '' , \ '' facsimileTelephoneNumber\ '' : null , \ '' givenName\ '' : \ '' dummy1\ '' , \ '' immutableId\ '' : null , \ '' isCompromised\ '' : null , \ '' jobTitle\ '' : \ '' test\ '' , \ '' lastDirSyncTime\ '' : null , \ '' mail\ '' : null , \ '' mailNickname\ '' : \ '' dummy1test\ '' , \ '' mobile\ '' : null , \ '' onPremisesSecurityIdentifier\ '' : null , \ '' otherMails\ '' : [ ] , \ '' passwordPolicies\ '' : null , \ '' passwordProfile\ '' : { \ '' password\ '' : null , \ '' forceChangePasswordNextLogin\ '' : true , \ '' enforceChangePasswordPolicy\ '' : false } , \ '' physicalDeliveryOfficeName\ '' : null , \ '' postalCode\ '' : null , \ '' preferredLanguage\ '' : null , \ '' provisionedPlans\ '' : [ ] , \ '' provisioningErrors\ '' : [ ] , \ '' proxyAddresses\ '' : [ ] , \ '' refreshTokensValidFromDateTime\ '' : \ '' 2016-12-02T08:37:24Z\ '' , \ '' showInAddressList\ '' : null , \ '' sipProxyAddress\ '' : null , \ '' state\ '' : \ '' California\ '' , \ '' streetAddress\ '' : null , \ '' surname\ '' : \ '' Test\ '' , \ '' telephoneNumber\ '' : \ '' 666\ '' , \ '' thumbnailPhoto @ odata.mediaEditLink\ '' : \ '' directoryObjects/5f6851c3-99cc-4a89-936d-4bb44fa78a34/Microsoft.DirectoryServices.User/thumbnailPhoto\ '' , \ '' usageLocation\ '' : null , \ '' userPrincipalName\ '' : \ '' dummy1test @ XXX.onmicrosoft.com\ '' , \ '' userType\ '' : \ '' Member\ '' } -- batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16Content-Type : application/httpContent-Transfer-Encoding : binaryHTTP/1.1 200 OKDataServiceVersion : 3.0 ; Content-Type : application/json ; odata=minimalmetadata ; streaming=true ; charset=utf-8 { \ '' odata.metadata\ '' : \ '' https : //graph.windows.net/XXX.onmicrosoft.com/ $ metadata # directoryObjects/ @ Element\ '' , \ '' odata.type\ '' : \ '' Microsoft.DirectoryServices.User\ '' , \ '' objectType\ '' : \ '' User\ '' , \ '' objectId\ '' : \ '' dd35d761-e6ed-44e7-919f-f3b1e54eb7be\ '' , \ '' deletionTimestamp\ '' : null , \ '' accountEnabled\ '' : true , \ '' signInNames\ '' : [ ] , \ '' assignedLicenses\ '' : [ ] , \ '' assignedPlans\ '' : [ ] , \ '' city\ '' : null , \ '' companyName\ '' : null , \ '' country\ '' : null , \ '' creationType\ '' : null , \ '' department\ '' : null , \ '' dirSyncEnabled\ '' : null , \ '' displayName\ '' : \ '' Max Admin\ '' , \ '' facsimileTelephoneNumber\ '' : null , \ '' givenName\ '' : null , \ '' immutableId\ '' : null , \ '' isCompromised\ '' : null , \ '' jobTitle\ '' : null , \ '' lastDirSyncTime\ '' : null , \ '' mail\ '' : null , \ '' mailNickname\ '' : \ '' maxadmin\ '' , \ '' mobile\ '' : null , \ '' onPremisesSecurityIdentifier\ '' : null , \ '' otherMails\ '' : [ ] , \ '' passwordPolicies\ '' : null , \ '' passwordProfile\ '' : null , \ '' physicalDeliveryOfficeName\ '' : null , \ '' postalCode\ '' : null , \ '' preferredLanguage\ '' : null , \ '' provisionedPlans\ '' : [ ] , \ '' provisioningErrors\ '' : [ ] , \ '' proxyAddresses\ '' : [ ] , \ '' refreshTokensValidFromDateTime\ '' : \ '' 2016-12-05T15:11:51Z\ '' , \ '' showInAddressList\ '' : null , \ '' sipProxyAddress\ '' : null , \ '' state\ '' : null , \ '' streetAddress\ '' : null , \ '' surname\ '' : null , \ '' telephoneNumber\ '' : null , \ '' thumbnailPhoto @ odata.mediaEditLink\ '' : \ '' directoryObjects/dd35d761-e6ed-44e7-919f-f3b1e54eb7be/Microsoft.DirectoryServices.User/thumbnailPhoto\ '' , \ '' usageLocation\ '' : null , \ '' userPrincipalName\ '' : \ '' maxadmin @ XXX.onmicrosoft.com\ '' , \ '' userType\ '' : \ '' Member\ '' } -- batchresponse_e42a30ca-0f3a-4c17-8672-22abc469cd16 -- var multipartContent = await response.Content.ReadAsMultipartAsync ( ) ; foreach ( HttpContent currentContent in multipartContent.Contents ) { var testString = currentContent.ReadAsStringAsync ( ) ; // How to get this content as an exploitable object ? } HTTP/1.1 200 OKDataServiceVersion : 3.0 ; Content-Type : application/json ; odata=minimalmetadata ; streaming=true ; charset=utf-8 { \ '' odata.metadata\ '' : \ '' https : //graph.windows.net/XXX.onmicrosoft.com/ $ metadata # directoryObjects/ @ Element\ '' , \ '' odata.type\ '' : \ '' Microsoft.DirectoryServices.User\ '' , \ '' objectType\ '' : \ '' User\ '' , \ '' objectId\ '' : \ '' 5f6851c3-99cc-4a89-936d-4bb44fa78a34\ '' , \ '' deletionTimestamp\ '' : null , \ '' accountEnabled\ '' : true , \ '' signInNames\ '' : [ ] , \ '' assignedLicenses\ '' : [ ] , \ '' assignedPlans\ '' : [ ] , \ '' city\ '' : null , \ '' companyName\ '' : null , \ '' country\ '' : null , \ '' creationType\ '' : null , \ '' department\ '' : \ '' NRF\ '' , \ '' dirSyncEnabled\ '' : null , \ '' displayName\ '' : \ '' dummy1 Test\ '' , \ '' facsimileTelephoneNumber\ '' : null , \ '' givenName\ '' : \ '' dummy1\ '' , \ '' immutableId\ '' : null , \ '' isCompromised\ '' : null , \ '' jobTitle\ '' : \ '' test\ '' , \ '' lastDirSyncTime\ '' : null , \ '' mail\ '' : null , \ '' mailNickname\ '' : \ '' dummy1test\ '' , \ '' mobile\ '' : null , \ '' onPremisesSecurityIdentifier\ '' : null , \ '' otherMails\ '' : [ ] , \ '' passwordPolicies\ '' : null , \ '' passwordProfile\ '' : { \ '' password\ '' : null , \ '' forceChangePasswordNextLogin\ '' : true , \ '' enforceChangePasswordPolicy\ '' : false } , \ '' physicalDeliveryOfficeName\ '' : null , \ '' postalCode\ '' : null , \ '' preferredLanguage\ '' : null , \ '' provisionedPlans\ '' : [ ] , \ '' provisioningErrors\ '' : [ ] , \ '' proxyAddresses\ '' : [ ] , \ '' refreshTokensValidFromDateTime\ '' : \ '' 2016-12-02T08:37:24Z\ '' , \ '' showInAddressList\ '' : null , \ '' sipProxyAddress\ '' : null , \ '' state\ '' : \ '' California\ '' , \ '' streetAddress\ '' : null , \ '' surname\ '' : \ '' Test\ '' , \ '' telephoneNumber\ '' : \ '' 666\ '' , \ '' thumbnailPhoto @ odata.mediaEditLink\ '' : \ '' directoryObjects/5f6851c3-99cc-4a89-936d-4bb44fa78a34/Microsoft.DirectoryServices.User/thumbnailPhoto\ '' , \ '' usageLocation\ '' : null , \ '' userPrincipalName\ '' : \ '' dummy1test @ XXX.onmicrosoft.com\ '' , \ '' userType\ '' : \ '' Member\ '' }","C # OAuth batch multipart content response , how to get all the contents not as string objects" "C_sharp : We just found these in our code : As you can see , these have the same signature except for the params.And they 're being used in several ways , one of them : which , strangely enough to me , resolves to the first overload.Q1 : Why does n't this produce a compile error ? Q2 : Why does the C # compiler resolve the above call to the first method ? Edit : Just to clarify , this is C # 4.0 , .Net 4.0 , Visual Studio 2010 . public static class ObjectContextExtensions { public static T Find < T > ( this ObjectSet < T > set , int id , params Expression < Func < T , object > > [ ] includes ) where T : class { ... } public static T Find < T > ( this ObjectSet < T > set , int id , params string [ ] includes ) where T : class { ... } } DBContext.Users.Find ( userid.Value ) ; //userid being an int ? ( Nullable < int > )",params overload apparent ambiguity - still compiles and works ? "C_sharp : I need to load a number of xhtml files that have this at the top : Each file will be loaded into a separate System.Xml.XmlDocument . Because of the DOCTYPE declaration they take a very long time to load . I tried setting XmlResolver = null , but then I get XmlException thrown because I have invalid entities ( e.g. , ” ) . So I thought I could download the DTD just for the first XmlDocument and in some way reuse it for the subsequent XmlDocuments ( and thus avoid the performance hit ) , but I have no idea how to do this.I 'm using .Net 3.5.Thanks . < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.1//EN '' `` http : //www.w3.org/TR/xhtml11/DTD/xhtml11.dtd '' >",How to speed up loading DTD through DOCTYPE "C_sharp : Design -- in a perfect worldI have one abstract base class A with property Value , and two derived classes W and R. It is always possible to read the Value ( and the method is always the same -- reading stored value ) , so I would put getter directly to A.However writing to Value is not always possible , and thus there are W and R. W provides also a setter , while R does not -- it just relies on features that come from A.The problem is , no matter what I tried , I can not make such design come to life in C # . I can not override Value property in W because there is no setter in base class ( and there is not , because adding a setter to base class means it would `` leak '' to R as well ) .Reality -- the ugly workaround ( dont't read ) I added a setter in A which throws an exception . In W I override setter while in R I do nothing.This is ugly , because of the design , because setter in R is public and because now such code compiles : The questionSo how to make a property with only getter in base class , and add a setter in derived class ? The storyBecause there is always at least one curious soul , I explain -- those classes are data holders/managers . The R class is dynamic data `` holder '' -- it computes value using given formula ( similar to Lazy Eval class ) . Most of of stuff is common among W and R -- filtering values , sending notifications , and so on . The only difference is in R you can not set the value directly , because the formula in one-way ( similar to WPF converter with only one method defined , Convert ) .SolutionThank to Marc I solved this issue , here is the code : The difference to Marc version is lack of setter in base class ( it was the whole point of the question ) , the difference to my workaround is shadowing the property , not overriding it . Small , but crucial piece.Thank you Marc for enlightenment : - ) . R reader ; reader.Value = 5 ; abstract class A { public int Value { get { return ... } } } class R : A { } class W : A { new public int Value { get { return base.Value ; } set { ... . } } }",How to make partial virtual property ? "C_sharp : I 'm running into the following problem when migrating my app from ASP.NET Core 2.2 to ASP.NET Core 3.0 : I have a class which should log an error message under certain circumstances . This is done by calling LogError on ILogger < MyClass > .I used to verifiy this with the following snippet from my unit test : Now here lies the problem : In ASP.NET Core 2.2 , the 3rd parameter ( Mocked via It.IsAny < object > ( ) ) was of an internal type FormattedLogValues . This was a class , so It.IsAny < object > ( ) worked . In ASP.NET Core 3.0 it was changed to a struct , so It.IsAny < object > ( ) no longer matches it.How can I get my Verify ( ) call to work in ASP.NET Core 3.0 ? Is there an It.IsAny ( ) version that matches any struct type ? Edit : Here is a fully runnable snippet that fails on ASP.NET Core 3.0 and succeeds on ASP.NET Core 2.2 . Mock < ILogger < MyClass > > loggerMock = ... ; MyClass myClass = ... ; myClass.MethodThatLogsTestException ( ) ; loggerMock.Verify ( l = > l.Log ( It.IsAny < LogLevel > ( ) , It.IsAny < EventId > ( ) , It.IsAny < object > ( ) , It.IsAny < TestException > ( ) , It.IsAny < Func < object , Exception , string > > ( ) ) ) ; public class Test { public class Impl { private readonly ILogger < Impl > logger ; public Impl ( ILogger < Impl > logger ) { this.logger = logger ; } public void Method ( ) { logger.LogError ( new Exception ( ) , `` An error occurred . `` ) ; } } [ Fact ] public void LogsErrorOnException ( ) { var loggerMock = new Mock < ILogger < Impl > > ( ) ; var sut = new Impl ( loggerMock.Object ) ; sut.Method ( ) ; loggerMock.Verify ( l = > l.Log ( It.IsAny < LogLevel > ( ) , It.IsAny < EventId > ( ) , It.IsAny < object > ( ) , It.IsAny < Exception > ( ) , It.IsAny < Func < object , Exception , string > > ( ) ) ) ; } }",Verifying method call with any struct parameter in Moq "C_sharp : I have been working on reading c # ( dll ) function from java through jni4net and in core java I have succeeded in getting the value from the dll function but now I have created one Dynamic Web Project and tried to use same functionality in servlet . But now only the dll file is loaded succesfully , the function is not called succesfuly . Below is what I tried till now : My Servlet : The only difference when I made this in core java was that I did n't used complete path instead I used only `` lib/ADHelper.j4n.dll '' for path but somehow it was not working in servlet so I changed it to complete path . Anyways the dll file is loaded succesfully.ADHelper.generated.csThe underdscore was mingled to the name ADHelper class when I ran proxygen command . in dll file there are two classes named ADHelper and ADHelperThe function Login ( ) was also changed to Login2 ( ) but Login2 ( ) is not recognized by my servlet whereas Login ( ) is recognized.Generated Java class ADHelper.javaAll the mapping is correct but my Login function is giving unsatisfiedLinkError . Thanks for having patience while reading , please give solution to my problem.Following error is coming on console : public class LoginProcess extends HttpServlet { private static final long serialVersionUID = 1L ; protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { try { Bridge.setVerbose ( true ) ; Bridge.init ( ) ; Console.WriteLine ( `` Hello .NET world ! \n '' ) ; Bridge.LoadAndRegisterAssemblyFrom ( new File ( `` C : /Users/ashish.it/workspace/FinalJniWeb/WebContent/WEB-INF/lib/ADHelper.j4n.dll '' ) ) ; } catch ( IOException e ) { e.printStackTrace ( ) ; } Enum output ; output=ADHelper.Login ( `` user '' , `` pass '' ) ; System.out.println ( output ) ; } } namespace ADHelper { public partial class ADHelper_ { methods.Add ( global : :net.sf.jni4net.jni.JNINativeMethod.Create ( @ __type , `` Login '' , `` Login2 '' , `` ( Ljava/lang/String ; Ljava/lang/String ; ) Lsystem/Enum ; '' ) ) ; private static global : :net.sf.jni4net.utils.JniHandle Login2 ( global : :System.IntPtr @ __envp , global : :net.sf.jni4net.utils.JniLocalHandle @ __class , global : :net.sf.jni4net.utils.JniLocalHandle UserName , global : :net.sf.jni4net.utils.JniLocalHandle Password ) { // ( Ljava/lang/String ; Ljava/lang/String ; ) Lsystem/Enum ; // ( LSystem/String ; LSystem/String ; ) LADHelper/ADHelper+LoginResult ; global : :net.sf.jni4net.jni.JNIEnv @ __env = global : :net.sf.jni4net.jni.JNIEnv.Wrap ( @ __envp ) ; global : :net.sf.jni4net.utils.JniHandle @ __return = default ( global : :net.sf.jni4net.utils.JniHandle ) ; try { @ __return = global : :net.sf.jni4net.utils.Convertor.StrongC2Jp < global : :ADHelper.ADHelper.LoginResult > ( @ __env , global : :ADHelper.ADHelper.Login ( global : :net.sf.jni4net.utils.Convertor.StrongJ2CString ( @ __env , UserName ) , global : :net.sf.jni4net.utils.Convertor.StrongJ2CString ( @ __env , Password ) ) ) ; } catch ( global : :System.Exception __ex ) { @ __env.ThrowExisting ( __ex ) ; } return @ __return ; } } package adhelper ; @ net.sf.jni4net.attributes.ClrTypepublic class ADHelper extends system.Object { private static system.Type staticType ; protected ADHelper ( net.sf.jni4net.inj.INJEnv __env , long __handle ) { super ( __env , __handle ) ; } @ net.sf.jni4net.attributes.ClrConstructor ( `` ( ) V '' ) public ADHelper ( ) { super ( ( ( net.sf.jni4net.inj.INJEnv ) ( null ) ) , 0 ) ; adhelper.ADHelper.__ctorADHelper0 ( this ) ; } @ net.sf.jni4net.attributes.ClrMethod ( `` ( LSystem/String ; LSystem/String ; ) LADHelper/ADHelper+LoginResult ; '' ) public native static system.Enum Login ( java.lang.String UserName , java.lang.String Password ) ; public static system.Type typeof ( ) { return adhelper.ADHelper.staticType ; } private static void InitJNI ( net.sf.jni4net.inj.INJEnv env , system.Type staticType ) { adhelper.ADHelper.staticType = staticType ; } } *All Dll file loaded message*Jun 3 , 2015 10:56:39 AM org.apache.catalina.core.StandardWrapperValve invokeSEVERE : Servlet.service ( ) for servlet LoginProcess threw exceptionjava.lang.UnsatisfiedLinkError : adhelper.ADHelper.Login ( Ljava/lang/String ; Ljava/lang/String ; ) Lsystem/Enum ; at adhelper.ADHelper.Login ( Native Method ) at com.karvy.login.LoginProcess.doGet ( LoginProcess.java:62 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:617 ) at javax.servlet.http.HttpServlet.service ( HttpServlet.java:723 ) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:290 ) at org.apache.catalina.core.ApplicationFilterChain.doFilter ( ApplicationFilterChain.java:206 ) at org.apache.catalina.core.StandardWrapperValve.invoke ( StandardWrapperValve.java:233 ) at org.apache.catalina.core.StandardContextValve.invoke ( StandardContextValve.java:191 ) at org.apache.catalina.core.StandardHostValve.invoke ( StandardHostValve.java:127 ) at org.apache.catalina.valves.ErrorReportValve.invoke ( ErrorReportValve.java:103 ) at org.apache.catalina.core.StandardEngineValve.invoke ( StandardEngineValve.java:109 ) at org.apache.catalina.connector.CoyoteAdapter.service ( CoyoteAdapter.java:293 ) at org.apache.coyote.http11.Http11Processor.process ( Http11Processor.java:861 ) at org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process ( Http11Protocol.java:606 ) at org.apache.tomcat.util.net.JIoEndpoint $ Worker.run ( JIoEndpoint.java:489 ) at java.lang.Thread.run ( Thread.java:662 )",UnsatisfiedLinkError exception while working with dll and java jni4net "C_sharp : I 'm frequently using asserts to detect unexpected program states . I thought an assert is a conditional message box the immediately stops all threads so that ( on pressing `` Retry '' ) I can inspect the current application state.This is not the case ! While the assert message is open , my wpf application continues processing events . It is absurd , as on breaking into the debugger the situation might be totally different compared to what the assert `` saw '' initially . You can have the case that the check for the assert to fire changes through the assert itself , you can have recursive execution of methods - with the consequence of multiple asserts or states in which the program would never come normally.As far as I understand the assert-function , this is a problem by design . The dialog runs on the same GUI thread as the application itself and hence needs to process messages for its own purpose . But this often has the described side-effects . So I 'm searching for an assert alternative that fulfills the requirement to stop all running threads when invoked . As workaround , I sometimes use `` Debugger.Break ( ) ; '' which has ( unfortunately ) no effect if started without debugger.For illustrating the problem , please see the following code snipped that in the most simplified manner produces some phenomenons : On running the code , watch the output panel of the developer studio . You will see the numbers go up to 5 , then the assert fires . But while the dialog is open , the numbers are still increasing . Hence the condition of the assert changes while the assert is open ! Now check the main window –it ’ s still responsive . Set a breakpoint at “ base.OnLocationChanged ( e ) ; “ and move the main window = > you will hit the break point . But mind the callstack : This clearly shows that arbitrary code can be executed while the assert is open.So I 'm searching for an assert like mechanism that stopps all existing threads and runns in it 's own ( thread- ) context.Any ideas ? public partial class MainWindow : Window { int _count = 0 ; public MainWindow ( ) { InitializeComponent ( ) ; } private void onLoaded ( object sender , RoutedEventArgs e ) { test ( ) ; } protected override void OnLocationChanged ( EventArgs e ) { base.OnLocationChanged ( e ) ; } void test ( ) { ++_count ; Dispatcher.BeginInvoke ( DispatcherPriority.ApplicationIdle , new Action ( ( ) = > { test ( ) ; } ) ) ; Trace.TraceInformation ( _count.ToString ( ) ) ; Debug.Assert ( _count ! = 5 ) ; } } MainWindow.OnLocationChanged ( System.EventArgs e ) ( … ) System.dll ! Microsoft.Win32.SafeNativeMethods.MessageBox ( System.IntPtr System.dll ! System.Diagnostics.AssertWrapper.ShowMessageBoxAssert ( striSystem.dll ! System.Diagnostics.DefaultTraceListener.Fail ( string message , str System.dll ! System.Diagnostics.DefaultTraceListener.Fail ( string message ) System.dll ! System.Diagnostics.TraceInternal.Fail ( string message ) System.dll ! System.Diagnostics.Debug.Assert ( bool condition ) MainWindow.test ( ) MainWindow.test.AnonymousMethod__0 ( )",Debug.Assert ( ) has unexpected side effects - searching for alternatives "C_sharp : I 'm using Task and TaskCompletionSource code in my application in scenarios that are frequently invoked , such as downloading a images from the Internet asynchronously from a 'scrolling table view ' . This allows me to write async/await code without touching the UI thread for downloading/caching operations.e.g . : The GetCachedImage is invoked multiple times because a table view may have lots of images to be downloaded and the user may scroll the table view as well.The Task itself does not take too long to be performed ( in some cases the result is returned synchronously ) , so I 'd expect that the system create a lot of threads but also REUSE them . However I 'm seeing in the console the following output : Thread finished : < Thread Pool > # 149The number of threads always get bigger and I 'm worried my application is creating too many threads and may get stuck because of that after a long period of usage . What does the Thread finished : < Thread Pool > # 149 mean ? Are threads being created and destroyed ? Are threads being reused ? Does my application have # 149 live threads ? Can ( should ) I limit the max number of threads ? EDITAs suggested by @ usr I ran my application again and stopped the debugger to see how many threads were there , see the screenshots : Looks like 38 threads were created , but some of them were destroyed , I am right ? Does that mean that the Thread finished : < Thread Pool > # ... message will always appear with a bigger number as long as the application is running ? Why are n't threads re-used ? public override Task < object > GetCachedImage ( string key ) { UIImage inMemoryImage = sdImageCache.ImageFromMemoryCache ( key ) ; // // Return synchronously since the image was found in the memory cache . if ( inMemoryImage ! = null ) { return Task.FromResult ( ( object ) inMemoryImage ) ; } TaskCompletionSource < object > tsc = new TaskCompletionSource < object > ( ) ; // // Query the disk cache asynchronously , invoking the result asynchronously . sdImageCache.QueryDiskCache ( key , ( image , cacheType ) = > { tsc.TrySetResult ( image ) ; } ) ; return tsc.Task ; }",Number of Threads in Monotouch application "C_sharp : I need a little more help to `` get '' how a DI framework like Ninject moves past the basics . Take the Ninject sample : Without a DI framework ( i.e . the [ Inject ] references above ) a referencing class would look something like : ... where you 're newing up everything . Yes , you 've removed the dependency in Samurai , but now you 've got a dependency one step further up the chain . Simple.With Ninject , you get rid of newing up everything by : HOWEVER , this is my area of confusion : without making some kind of service locater to take care of efficiently newing up the applicable kernel and module ( i.e . .IoC.TypeResolver.Get < > ( ) ) , what is a ) the best way to not have to new up kernels everywhere ( service locater references everywhere ? ) , and b ) more importantly , when you 've got a big long chain with dependencies with dependencies of their own , you take it to the extreme of passing injections all the way up in something that I 'm sure is a serious anti-pattern ( a friend called it `` hot-potato dependency injection '' anti-pattern ) .In other words , I thought part of the DI framework magic is that you do n't have to keep inserting dependencies all the way up the chain ( i.e . your your first reference containing 10 parameters in its constructor , none of which have anything to do with anything until much further along the chain ) - where 's the magic or the solution to my confusion so that dependencies do n't either continually get referenced up and up the chain , or service locater references spread everywhere.Further muddying the waters for me is if using a DI framework , what 's the best way to deal with a scenario where a referenced class needs an IList which would typically be put in the constructor ( i.e . new ReferencedClass ( myList ) ) as that , other than in simple cases like a string database connection string , does n't fly . Just make a property and set it after newing it up/DI Framework service locating ? I.e . All in all , I think this is a post I 'll likely be embarrassed about after I get it , but right now , I 've hit my head too many times against the wall trying to determine the best approach . class Samurai { private IWeapon _weapon ; [ Inject ] public Samurai ( IWeapon weapon ) { _weapon = weapon ; } public void Attack ( string target ) { _weapon.Hit ( target ) ; } } class Program { public static void Main ( ) { Samurai warrior1 = new Samurai ( new Shuriken ( ) ) ; Samurai warrior2 = new Samurai ( new Sword ( ) ) ; warrior1.Attack ( `` the evildoers '' ) ; warrior2.Attack ( `` the evildoers '' ) ; } } class Program { public static void Main ( ) { IKernel kernel = new StandardKernel ( new WarriorModule ( ) ) ; Samurai warrior = kernel.Get < Samurai > ( ) ; warrior.Attack ( `` the evildoers '' ) ; } } var referencedClass = IoC.Get < IReferencedClass > ( ) ; referencedClass.MyList = myList ;","DI Framework : how to avoid continually passing injected dependencies up the chain , and without using a service locator ( specifically with Ninject )" "C_sharp : I 'm hoping someone can point me in the right direction with the following problem . I am working on a project where the types are generated using Reflection.Emit , all has been working fine until a requirement arose where I needed to pass a Func < > into a constructor of a new object as below.Using Linqpad I can see the IL output is as follows : The problem I have is that I 'm not sure how to define the delegate within IL.I have tried the followingThen trying to create the delegate the following throws `` Not Supported Exception '' with the error `` Derived classes must provide an implementation . `` I have also tried using Delegate.CreateDelegate and DynamicMethod which both require the type to have been created before using them.Any suggestion on what I might be doing wrong are greatly appreciated . public class SearchTerm : IEntity { private readonly NavigationProperty < Item > _item ; public SearchTerm ( ) { _item = new NavigationProperty < Item > ( ( ) = > ItemIds ) ; } public string [ ] ItemIds { get ; set ; } } SearchTerm. < .ctor > b__0 : IL_0000 : ldarg.0 IL_0001 : call UserQuery+SearchTerm.get_ItemIdsIL_0006 : stloc.0 // CS $ 1 $ 0000IL_0007 : br.s IL_0009IL_0009 : ldloc.0 // CS $ 1 $ 0000IL_000A : ret SearchTerm..ctor : IL_0000 : ldnull IL_0001 : stloc.0 IL_0002 : ldarg.0 IL_0003 : call System.Object..ctorIL_0008 : nop IL_0009 : nop IL_000A : ldarg.0 IL_000B : ldloc.0 IL_000C : brtrue.s IL_001DIL_000E : ldarg.0 IL_000F : ldftn UserQuery+SearchTerm. < .ctor > b__0IL_0015 : newobj System.Func < System.Collections.Generic.IEnumerable < System.String > > ..ctorIL_001A : stloc.0 IL_001B : br.s IL_001DIL_001D : ldloc.0 IL_001E : newobj UserQuery < UserQuery+Item > +NavigationProperty ` 1..ctorIL_0023 : stfld UserQuery+SearchTerm._itemIL_0028 : nop IL_0029 : ret var method = typeBuilder.DefineMethod ( `` func '' , MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual , typeof ( IEnumerable < string > ) , Type.EmptyTypes ) ; var methodIl = method.GetILGenerator ( ) ; methodIl.Emit ( OpCodes.Ldarg_0 ) ; methodIl.Emit ( OpCodes.Call , dictionary [ `` get_ItemIds '' ] ) ; methodIl.Emit ( OpCodes.Ret ) ; var funcType = typeof ( Func < , > ) .MakeGenericType ( typeBuilder , typeof ( IEnumerable < string > ) ) ; method.CreateDelegate ( funcType ) ;",Create a constructor call using Reflection Emit that passes a Func < > as a parameter "C_sharp : I have two classes : As Question inherits IDisposable and IEquatable , does SessionQuestion implicitly inherit those interfaces as well ? public class Question : IDisposable , IEquatable < Question > { } public class SessionQuestion : Question , IDisposable , IEquatable < SessionQuestion > { }",Does a class that inherits another class inherit that classes inherited classes/interfaces ? "C_sharp : I 'm refactoring code in an aging windows application , and I 've come across a pattern of sorts , that I 'm not sure I like : A class has got global color variables , like the following : There are a bunch of these , and they are being passed around by ref to methods responsible for setting up certain parts of the UI . I gather that a Color is a struct , and that each color is therefore passed by ref in order to avoid creating new copies of it each time a method is called . IE something like : I ca n't help feeling that this usage of ref throughout this class and related classes is bad . It feels like a `` code smell '' , though I ca n't really put my finger on why . I 've seen a couple of posts on similar issues , with recommendations like `` use a class containing colors , which is then passed as a value type '' , but it is not entirely clear how it would be best to do this.What I would like to do is create something similar to the following : This would let me retain control of the colors , but the implications on memory are a little unclear to me ; if I created an instance of this class and passed that around to the methods needing info about the contained colors , would not a copy of a color ( with it being a struct ) be created as soon as an implementing method makes use of it ? Am I correct in assuming that this code would create a new copy , and thus be less effective ... ... than this code , which would only make use of the existing struct ? : I 'm currently leaning toward a solution similar to the following , in which i gather the colors in a separate class and reorganize the code a bit , but keep using ref . In this case , however , MyColor will have to be a public field in ColorContainer , which means I will have less control over who can set it 's value : Is this a good solution , or are there better strategies to handle resources like this ? private Color myForegroundColor = Color.Azure ; private Color myBackgroundColor = Color.Empty ; // ... etc . // Avoid creating a copy of myForgroundColor inside SetUpButton ( ) : MyHelperClass.SetUpButton ( ref myForegroundColor ) ; public class ColorContainer { public UiSettingsContainer ( ) { MyColor = Color.Black ; MyNextColor = Color.Blue ; // ..etc ... } public Color MyColor { get ; private set ; } // ... etc ... . } // Assumption : This creates a new copy of color in memory.public void SetSomeColor ( Color col ) { someComponent.color = col ; } // Calling it : SetSomeColor ( myColorContainerInstance.MyColor ) ; // Question : Does this avoid creating a new copy of MyColor in memory ? public void SetSomeColor ( ColorContainer container ) { someComponent.color = container.MyColor ; } // Calling it : SetSomeColor ( myColorContainerInstance ) ; // Assumption : This creates a new copy of color in memory.public void SetSomeColor ( ref Color col ) { someComponent.color = col ; } // Calling it : SetSomeColor ( ref myColorContainerInstance.MyColor ) ;",Strategies for passing colors around ( avoiding ref ? ) C_sharp : Is there a quick way to grab everything left of the question mark ? http : //blah/blah/ ? blahto http : //blah/blah/,extract left of the question mark "C_sharp : EF is generating different SQL for the for two similar statements listed belowGenerated SQL : I am using the above statements at multiple places with different Where condition ; to consolidate logic in one place I am passing the condition as a parameterI am calling the function asGenerated SQL : If you look at the second SQL , it is quite alarming : it is pulling all info ( columns and rows ) . It does n't have where clause and selecting all columns.The where condition is being applied after the results were returned from DB.The only difference in the second statement is I am passing condition as parameter instead of having condition inside where clause.Can anyone explain why the difference ? var test = dbcontext.Persons.GetAll ( ) .Where ( c = > c.PersonID == 2 ) .Select ( c = > c.PersonName ) .FirstOrDefault ( ) ; ` SELECT [ Limit1 ] . [ PersonName ] AS [ PersonName ] FROM ( SELECT TOP ( 1 ) [ Extent1 ] . [ PersonName ] AS [ PersonName ] FROM [ dbo ] . [ ApplicationRequest ] AS [ Extent1 ] WHERE [ Extent1 ] . [ PersonID ] = @ p__linq__0 ) AS [ Limit1 ] ' , N ' @ p__linq__0 uniqueidentifier ' , @ p__linq__0= `` 2 '' Public Void PassPredicate ( Func < ApplicationRequest , bool > ReqFunc ) { var test = dbcontext.Persons.GetAll ( ) .Where ( ReqFunc ) .Select ( c = > c.PersonName ) .FirstOrDefault ( ) ; } PassPredicate ( c = > c.PersonID == 2 ) ; SELECT [ Extent1 ] . [ PersonID ] AS [ PersonID ] , [ Extent1 ] . [ PersonName ] AS [ PersonName ] , [ Extent1 ] . [ DOB ] AS [ Dob ] , [ Extent1 ] . [ Height ] AS [ Height ] , [ Extent1 ] . [ BirthCity ] AS [ BirthCity ] , [ Extent1 ] . [ Country ] AS [ Country ] , FROM [ dbo ] . [ Person ] AS [ Extent1 ]",EF SQL changed when passing predicate as Parameter to Where Clause "C_sharp : I 'm working on a website that I 'd like to use in-place compilation on in order to make the first hit faster . I 'd like to use the ClientBuildManager.CompileFile method to do the in-place compilation so that I have control of the compiling process . For a variety of reasons , this is the ideal way to compile this website.Why Does IIS Build to a Different Subdirectory under `` Temporary ASP.NET Files '' ? When I compile a website file by file via ClientBuildManager.CompileFile method in an exe built for this purpose , the output goes to a Subdirectory under `` Temporary ASP.NET Files '' . However , when the website is hit later , IIS rebuilds the controls under a different subdirectory under `` Temporary ASP.NET Files '' rendering the previous in-place compilation worthless . Note : The assemblies created during in-place compilation under `` Temporary ASP.NET Files '' are left alone ( still exist ) .Note : Both the in-place compilation assemblies folder and IIS generated assemblies folder are under the same `` Temporary ASP.NET Files '' dir.Example : C : \Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\2ba591b9\ [ in-place compilation folder name ] C : \Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\2ba591b9\ [ IIS generated assemblies for website ] \ClientBuildManager.CompileFile ConfigurationWhere RootVirtualPath is simply `` '' for the default website . RootPhysicalPath points to the location on disk of the website . relativeVirtualPath is of the form `` ~/myFile.aspx '' . The callback is used to track progress . var buildParameter = new ClientBuildManagerParameter { PrecompilationFlags = PrecompilationFlags.Default , } ; var clientBuildManager = new ClientBuildManager ( RootVirtualPath , RootPhysicalPath , null , buildParameter ) ; ... clientBuildManager.CompileFile ( relativeVirtualPath , callback ) ;",In-Place Compilation using ClientBuildManager.CompileFile "C_sharp : I currently have a method which is quite simple and calculates a list of CurveValue ( custom object ) , the issue I have is I need to calculate the parameter and pass a decimal back without actually changing the parameter.I tried to AddRange ( ) into a new object so the parameter curve would not be affected but it seems the reference still exists and after the ForEach ( ) is performed both curve , and curveA have changed.I 'm assuming it is still referenced but is there an easy way of doing this without enumerating through the parameter curve and adding it to curveA ? public decimal Multiply ( List < CurveValue > curve , decimal dVal ) { List < CurveValue > curveA = new List < CurveValue > ( ) ; curveA.AddRange ( curve ) ; curveA.ForEach ( a = > a.Value = decimal.Round ( a.Value , 4 ) * dVal ) ; return Sum ( curveA ) ; } public decimal Sum ( List < CurveValue > curveA ) { return curveA.Sum ( x = > x.Value ) ; }",AddRange ( ) and LINQ copying issue "C_sharp : Lets say I have a simple table that only contains two columns : MailingListUser - PK ID ( int ) - FK UserID ( int ) I have a method called UpdateMailList ( IEnumerable < int > userIDs ) . How do I , in LINQ , make inserts for the userIDs that are present in the passed in parameter but do n't exist in the db , delete the ones that are in the db but no longer in UserIDs , and leave the ones that are already in both the db and userIDs alone ? A user is presented with a checkbox list , and when it first loads it has the existing members selected for the maillist checked.The user can then check and uncheck various users and hit `` save '' . Once this happens , I need to update the state of the database with the state of the checklist.Here is what I 'm doing now : Is there a better way than simply deleting all entries in the MailingListUser table , and re-inserting all the userIDs values ? public void UpdateMailList ( IEnumerable < int > userIDs ) { using ( MainDataContext db = new MainDataContext ( ) ) { var existingUsers = ( from a in db.MailListUsers select a ) ; db.MailListUsers.DeleteAllOnSubmit ( existingUsers ) ; db.SubmitChanges ( ) ; var newUsers = ( from n in userIDs select new MailListUser { UserID = n } ) ; db.MailListUsers.InsertAllOnSubmit ( newUsers ) ; db.SubmitChanges ( ) ; } } } }",How do I update a table with LINQ-to-SQL without having to delete all the existing records ? "C_sharp : I am trying to build a bot using LUIS but it is a lot harder than I thought.So far I have managed to create my LUIS application and create an Intent and an Entity and I have created a few Utterances that seem to work fine.I then created my bot and have hooked it up to Luis . When I test my bot it is working as expected.Now , for the fun part . I want to handle parameters . On Luis I added an action to my Intent : As you can see I have added a prompt.My code in my bot currently looks like this : I think you can guess where I am going with this . If the user types Help me buy a camera , it will get to Choose category Intent and will have the correct Entity selected.But if they type Help me buy , it will still go to the correct Intent , but it will not have a selected Entity . I would like my bot to see that and use the text in the Prompt I created in LUIS and when the user selects their entity I want it to go back to LUIS with that parameter.I have no idea how to do this and I ca n't find any tutorials on this.Any help would be appreciated ( even links ! ) /// < summary > /// Tries to find the category/// < /summary > /// < param name= '' result '' > The Luis result < /param > /// < param name= '' alarm '' > < /param > /// < returns > < /returns > public string TryFindCategory ( LuisResult result ) { // Variable for the title EntityRecommendation title ; // If we find our enenty , return it if ( result.TryFindEntity ( PiiiCK.Category , out title ) ) return title.Entity ; // Default fallback return null ; } [ LuisIntent ( `` Choose category '' ) ] public async Task ChooseCategory ( IDialogContext context , LuisResult result ) { // Get our category var category = TryFindCategory ( result ) ; var response = `` The category you have chosen is not in the system just yet . `` ; switch ( category ) { case `` camera '' : response = $ '' You need help buying a { category } , is this correct ? `` ; this.started = true ; break ; default : if ( ! string.IsNullOrEmpty ( category ) ) response = $ '' Sorry , PiiiCK does not deal with { category.Pluralise ( ) } just yet . `` ; break ; } // Post our response back to the user await context.PostAsync ( response ) ; // Execute the message recieved delegate context.Wait ( MessageReceived ) ; }","Microsoft Bot Framework , LUIS and Action parameters" "C_sharp : I have a form that should be shown by clicking on a button in main form and I want when users close the second form , main form be shown again on center of the screen . I used below codes to do this : these commands do what I want , but the problem is that after closing the second form , the main form be shown with a small jump , like a blink ! ( It 's not continuous , it 's just at the first . ) What I want is do this smoothly , without any blink at the first . How is it possible ? Thanks in advance . private void button_Click ( object sender , EventArgs e ) { this.Hide ( ) ; //Hides the main form . form2.ShowDialog ( ) ; //Shows the second form . this.Show ( ) ; // Re-shows the main form after closing the second form ( just in the taskbar , not on the screen ) . this.StartPosition = FormStartPosition.CenterScreen ; // I write this code because I want to show the main form on the screen , not just in the taskbar . }",How to show a form `` smoothly '' for second time in winforms ? "C_sharp : I 'm trying to determine the differences between two collections.SomeObject implements IEquatable < SomeObject > I 'm using the following to determine if my two collections have any differences : The _cachedObjectList collection will not change . You are able to Add , Remove , Or Modify an object in the _objectList collection.How can i return a new list that contains any newly added , deleted , or otherwise modified object from the two collections.Any help would be greatly appreciated ! IEquatable Implementation for SomeObject : EDIT : I only want the changes , if the _objectList contains a modified object , based on the IEquatable.Equals ( ) then I 'd like it returned . Otherwise , return new objects or removed objects in the list . private ObservableCollection < SomeObject > _objectList = null ; private ObservableCollection < SomeObject > _cachedObjectList = null ; this._objectList.ToList ( ) .OrderBy ( x = > x.Id ) .SequenceEqual ( this._cachedObjectList.ToList ( ) .OrderBy ( x = > x.Id ) ) ; public class SomeObject : IEquatable < SomeObject > { public int GetHashCode ( SomeObject object ) { return base.GetHashCode ( ) ; } public bool Equals ( SomeObject other ) { bool result = true ; if ( Object.ReferenceEquals ( other , null ) ) { result = false ; } //Check whether the compared objects reference the same data . if ( Object.ReferenceEquals ( this , other ) ) { result = true ; } else { // if the reference is n't the same , we can check the properties for equality if ( ! this.Id.Equals ( other.Id ) ) { result = false ; } if ( ! this.OtherList.OrderBy ( x = > x.Id ) .ToList ( ) .SequenceEqual ( other.OtherList.OrderBy ( x = > x.Id ) .ToList ( ) ) ) { result = false ; } } return result ; } } }",Returning the differences between two enumerables "C_sharp : I have code like this to emit IL code that loads integer or string values . But I do n't know how to add the decimal type to that . It is n't supported in the Emit method . Any solutions to this ? Not working : Edit : Okay , so here 's what I did : But it does n't generate a newobj opcode , but instead nop and stloc.0 . The constructor is found and passed to the Emit call . What 's wrong here ? Obviously an InvalidProgramException is thrown when trying to execute the generated code because the stack is completely messed up . ILGenerator ilGen = methodBuilder.GetILGenerator ( ) ; if ( type == typeof ( int ) ) { ilGen.Emit ( OpCodes.Ldc_I4 , Convert.ToInt32 ( value , CultureInfo.InvariantCulture ) ) ; } else if ( type == typeof ( double ) ) { ilGen.Emit ( OpCodes.Ldc_R8 , Convert.ToDouble ( value , CultureInfo.InvariantCulture ) ) ; } else if ( type == typeof ( string ) ) { ilGen.Emit ( OpCodes.Ldstr , Convert.ToString ( value , CultureInfo.InvariantCulture ) ) ; } else if ( type == typeof ( decimal ) ) { ilGen.Emit ( OpCodes.Ld_ ? ? ? , Convert.ToDecimal ( value , CultureInfo.InvariantCulture ) ) ; } else if ( type == typeof ( decimal ) ) { decimal d = Convert.ToDecimal ( value , CultureInfo.InvariantCulture ) ; // Source : https : //msdn.microsoft.com/en-us/library/bb1c1a6x.aspx var bits = decimal.GetBits ( d ) ; bool sign = ( bits [ 3 ] & 0x80000000 ) ! = 0 ; byte scale = ( byte ) ( ( bits [ 3 ] > > 16 ) & 0x7f ) ; ilGen.Emit ( OpCodes.Ldc_I4 , bits [ 0 ] ) ; ilGen.Emit ( OpCodes.Ldc_I4 , bits [ 1 ] ) ; ilGen.Emit ( OpCodes.Ldc_I4 , bits [ 2 ] ) ; ilGen.Emit ( sign ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0 ) ; ilGen.Emit ( OpCodes.Ldc_I4 , scale ) ; var ctor = typeof ( decimal ) .GetConstructor ( new [ ] { typeof ( int ) , typeof ( int ) , typeof ( int ) , typeof ( bool ) , typeof ( byte ) } ) ; ilGen.Emit ( OpCodes.Newobj , ctor ) ; }",Emit IL code to load a decimal value "C_sharp : I know that shadowing members in class implementations can lead to situations where the `` wrong '' member can get called depending on how I have cast my instances , but with interfaces I do n't see that this can be a problem and I find myself writing interfaces like this quite often : I have places in my code that only know about INode so children should also be of type INode.In other places I want to know about the specific types - in the implementation of my example IAlpha & IBeta interfaces I want the children to be typed the same as their parent.So I implement a NodeBase class like so : No shadowing in the actual implementation , only in the interfaces.Specific instances of IAlpha & IBeta look like this : Again , no shadowing in the implementations.I can now access these types like so : Each of these variables now have the correct , strongly-type Children collection.So , my questions are simple . Is the shadowing of interface members using this kind of pattern good , bad or ugly ? And why ? public interface INode { IEnumerable < INode > Children { get ; } } public interface INode < N > : INode where N : INode < N > { new IEnumerable < N > Children { get ; } } public interface IAlpha : INode < IAlpha > { } public interface IBeta : INode < IBeta > { } public abstract class NodeBase < N > : INode < N > where N : INode < N > { protected readonly List < N > _children = new List < N > ( ) ; public IEnumerable < N > Children { get { return _children.AsEnumerable ( ) ; } } IEnumerable < INode > INode.Children { get { return this.Children.Cast < INode > ( ) ; } } } public class Alpha : NodeBase < Alpha > , IAlpha { IEnumerable < IAlpha > INode < IAlpha > .Children { get { return this.Children.Cast < IAlpha > ( ) ; } } } public class Beta : NodeBase < Beta > , IBeta { IEnumerable < IBeta > INode < IBeta > .Children { get { return this.Children.Cast < IBeta > ( ) ; } } } var alpha = new Alpha ( ) ; var beta = new Beta ( ) ; var alphaAsIAlpha = alpha as IAlpha ; var betaAsIBeta = beta as IBeta ; var alphaAsINode = alpha as INode ; var betaAsINode = beta as INode ; var alphaAsINodeAlpha = alpha as INode < Alpha > ; var betaAsINodeBeta = beta as INode < Beta > ; var alphaAsINodeIAlpha = alpha as INode < IAlpha > ; var betaAsINodeIBeta = beta as INode < IBeta > ; var alphaAsNodeBaseAlpha = alpha as NodeBase < Alpha > ; var betaAsNodeBaseBeta = beta as NodeBase < Beta > ;","Shadowing Inherited Generic Interface Members in .NET : good , bad or ugly ?" "C_sharp : Let 's say you have a simple class like this : I could use this class in a multi-threaded manner : My question is : will I ever see this ( or other similar multi-threaded code ) throw an exception ? I often see reference to the fact that non-volatile writes might not immediately be seen by other threads . Thus , it seems like this could fail because the write to the value field might happen before the writes to a and b . Is this possible , or is there something in the memory model that makes this ( quite common ) pattern safe ? If so , what is it ? Does readonly matter for this purpose ? Would it matter if a and b were a type that ca n't be atomically written ( e. g. a custom struct ) ? class MyClass { private readonly int a ; private int b ; public MyClass ( int a , int b ) { this.a = a ; this.b = b ; } public int A { get { return a ; } } public int B { get { return b ; } } } MyClass value = null ; Task.Run ( ( ) = > { while ( true ) { value = new MyClass ( 1 , 1 ) ; Thread.Sleep ( 10 ) ; } } ) ; while ( true ) { MyClass result = value ; if ( result ! = null & & ( result.A ! = 1 || result.B ! = 1 ) ) { throw new Exception ( ) ; } Thread.Sleep ( 10 ) ; }",Why is ( or is n't ) setting fields in a constructor thread-safe ? "C_sharp : I am using WSO2 as my Identity Provider ( IDP ) . It is putting the JWT in an header called `` X-JWT-Assertion '' . To feed this into the ASP.NET Core system , I added an OnMessageReceived event . This allows me to set the token to the value supplied in the header.Here is the code that I have to do that ( the key part is the last 3 lines of non-bracket code ) : This all works perfectly except for the very first call after the service starts up . To be clear , every call , except for the first one works exactly as I want it to . ( It puts the token in and updates the User object like I need . ) But for the first call , the OnMessageReceived is not hit . And the User object in my controller is not setup.I checked HttpContext for that first call , and the `` X-JWT-Assertion '' header is in the Request.Headers list ( with the JWT in it ) . But , for some reason , the OnMessageReceived event is not called for it.How can I get OnMessageReceived to be called for the first invocation of a service operation for my service ? IMPORTANT NOTE : I figured out that the issue was async await in AddJwtBearer . ( See my answer below . ) That is what I really wanted out of this question . However , since a bounty can not be cancled , I will still award the bounty to anyone who can show a way to use AddJwtBearer with async await where it is awaiting an actual HttpClient call . Or show documentation of why async await is not supposed to be used with AddJwtBearer . services.AddAuthentication ( options = > { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme ; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme ; } ) .AddCookie ( ) .AddJwtBearer ( async options = > { options.TokenValidationParameters = await wso2Actions.JwtOperations.GetTokenValidationParameters ( ) ; options.Events = new JwtBearerEvents ( ) { // WSO2 sends the JWT in a different field than what is expected . // This allows us to feed it in . OnMessageReceived = context = > { context.Token = context.HttpContext.Request.Headers [ `` X-JWT-Assertion '' ] ; return Task.CompletedTask ; } } } ;",JwtBearerEvents.OnMessageReceived not Called for First Operation Invocation "C_sharp : Clarification of question : I am not looking for answers on how to solve this issue ( several are listed below ) , but as to why it is happening.I expect the following code to compile : However the following compile time error is thrown at // *** : Use of unassigned local variable 'beta ' I can make the program compile under the following situations : If I change the signature to be static object Foo ( Alice alice ) Explicitly casting on the lines // * and // ** , e.g . : ! long.TryParse ( ( string ) alice.Beta , out beta ) .Removing the decimal.TryParse on line // *.Replacing the short circuit or || with | . Thanks to HansPassantSwapping the TryParses aroundPulling the results of the TryParses into bools Thanks to ChrisAssigning a default value to betaAm I missing something obvious , or is there something subtle going on , or is this a bug ? struct Alice { public string Alpha ; public string Beta ; } struct Bob { public long Gamma ; } static object Foo ( dynamic alice ) { decimal alpha ; long beta ; if ( ! decimal.TryParse ( alice.Alpha , out alpha ) // * || ! long.TryParse ( alice.Beta , out beta ) ) // ** { return alice ; } var bob = new Bob { Gamma = beta } ; // *** // do some stuff with alice and bob return alice ; }",Unexpected compile time error with dynamic "C_sharp : I have a domain model with an aggregate root : The Children collection tends to get very large and I will be lazy loading it when an IAggregateRoot instance is retrieved through the IAggregateRootRepository . My problem is this ; if I want to add an IChildEntity to an IAggregateRoot 's Children collection , how can my repository allow me avoid persisting the entire aggregate ? For example , let 's say my IAggregateRootRepository were to look like the following : Then I could add to the Children collection by getting an IAggregateRoot instance through IAggregateRootRepository.GetById ( ) , adding the child to the Children collection , then persisting it all through IAggregateRootRepository.AddOrUpdate ( ) . That would , however , persist the entire aggregate root , along with its massive collection of children , every time I add a child entity . I guess I could get around that if my repository looked like : But , as I have understood the repository pattern , a repository should only deal with aggregate roots and the solution above certainly breaks that requirement.Are there other , better , ways of avoiding this problem ? public interface IAggregateRoot { public string Id { get ; } public string Foo { get ; set ; } public int Bar { get ; set ; } public IList < IChildEntity > Children { get ; } } public interface IAggregateRootRepository { public IAggregateRoot GetById ( string id ) ; public void AddOrUpdate ( IAggregateRoot root ) ; } public interface IAggregateRootRepository { public IAggregateRoot GetById ( string id ) ; public void AddOrUpdate ( IAggregateRoot root ) ; public void AddOrUpdate ( IChildEntity child ) ; }",How to avoid persisting entire aggregate root when adding child entity ? "C_sharp : I 'm trying to override the DbContext.Set < TEntity > ( ) method.It 's signature is : First I tried this : ... but I get the error : The type 'TEntity ' must be a reference type in order to use it as parameter 'TEntity ' in the generic type or method 'System.Data.Entity.DbContext.Set ( ) ' ... so I then tried specifiying it was a reference type : ... and I now get : Constraints for override and explicit interface implementation methods are inherited from the base method , so they can not be specified directly ... . and if I take it away , I 'm back to the first error.So what does the C # compiler want me to do ? public virtual DbSet < TEntity > Set < TEntity > ( ) where TEntity : class public override DbSet < TEntity > Set < TEntity > ( ) { return base.Set < TEntity > ( ) ; } public override DbSet < TEntity > Set < TEntity > ( ) where TEntity : class { return base.Set < TEntity > ( ) ; }",Overriding virtual method with generics and constraints "C_sharp : I 'm wondering if the following is possible : The method Regex.Match can receive an enum , so I can specify : What if I need to specify more than just one ? ( eg . I want my regex to be Multiline and I want it to ignore the pattern whitespace ) .Could I use | operator like in C/C++ ? RegexOptions.IgnoreCaseRegexOptions.IgnorePatternWhiteSpaceRegexOptions.Multiline",How can I pass more than one enum to a method that receives only one ? "C_sharp : I am currently developing an application in C # ( .NET 4.0 ) that should have as a part of its functionality the ability to determine the percentage of fragmentation on a particular volume . All the other features have been tested and are working fine but I ’ ve hit a snag trying to access this data . I would ideally prefer to use WMI as this matches the format I ’ m using for the other features but at this point I ’ m willing to use anything that can be efficiently integrated into the application , even if I have to use RegEx to filter the data . I am currently doing the development on a Windows 7 Professional ( x64 ) machine . I have tested the following Powershell snippet using Administrator rights and it works flawlessly.This is the method I ’ m using in C # to accomplish the same thing , but the InvokeMethod keeps returning 11 ( 0xB ) .I have even added the following line to the app.manifest but still nothing.Could somebody please tell me what I ’ m overlooking ? Failure is not an option for me on this , so if it can not be done using C # I don ’ t mind creating a DLL in another language ( even if I have to learn it ) , that will give me the results I need . Ideally the application should be able work on any OS from XP upwards and must be totally transparent to the user.These are the resources I have already used . I wanted to add the jeffrey_wall blog on msdn as well but as a new user I can only add 2 hyperlinks at a time . Thanks again.http : //www.codeproject.com/Messages/2901324/Re-the-result-of-DefragAnalysis-method-in-csharp.aspxhttp : //social.technet.microsoft.com/Forums/vi-VN/winserverfiles/thread/9d56bfad-dcf5-4258-90cf-4ba9247200da $ drive = Get-WmiObject -Class Win32_Volume -Namespace root\CIMV2 -ComputerName . | Where-Object { $ _.DriveLetter -eq 'D : ' } $ drive.DefragAnalysis ( ) .DefragAnalysis public static Fragmentation GetVolumeFragmentationAnalysis ( string drive ) { //Fragmenation object initialization removed for simplicity try { ConnectionOptions mgmtConnOptions = new ConnectionOptions { EnablePrivileges = true } ; ManagementScope scope = new ManagementScope ( new ManagementPath ( string.Format ( @ '' \\ { 0 } \root\CIMV2 '' , Environment.MachineName ) ) , mgmtConnOptions ) ; ObjectQuery query = new ObjectQuery ( string.Format ( @ '' SELECT * FROM Win32_Volume WHERE Name = ' { 0 } \\ ' '' , drive ) ) ; scope.Connect ( ) ; using ( ManagementObjectSearcher searcher = new ManagementObjectSearcher ( scope , query ) ) { object [ ] outputArgs = new object [ 2 ] ; foreach ( ManagementObject moVolume in searcher.Get ( ) ) { // Execution stops at this line as the result is always 11 UInt32 result = ( UInt32 ) moVolume.InvokeMethod ( `` DefragAnalysis '' , outputArgs ) ; if ( result == 0 ) { Console.WriteLine ( `` Defrag Needed : = { 0 } \n '' , outputArgs [ 0 ] ) ; ManagementBaseObject mboDefragAnalysis = outputArgs [ 1 ] as ManagementBaseObject ; if ( null ! = mboDefragAnalysis ) { Console.WriteLine ( mboDefragAnalysis [ `` TotalPercentFragmentation '' ] .ToString ( ) ) ; } } else { Console.WriteLine ( `` Return Code : = { 0 } '' , result ) ; } } } } catch ( Exception ex ) { Console.WriteLine ( `` Could not acquire fragmentation data.\n '' + ex ) ; } return result ; } < requestedExecutionLevel level= '' requireAdministrator '' uiAccess= '' false '' / >",How to obtain DefragAnalysis using C # C_sharp : I need to pass test data on class level but Theory and InlineData attributes can only be used on methods . Is there a way to achieve something similar in xUnit.net ? public class ContainerTests : TestFixture { private IContainer _container ; public ContainerTests ( string containerName ) { _container = CreateContainer ( containerName ) ; } [ Fact ] public void ResolveJobFactory ( ) { IJobFactory jobFactory = _container.Resolve < IJobFactory > ( ) ; } private IContainer CreateContainer ( string containerName ) { if ( containerName == `` CastleWindsor '' ) { return new WindsorContainerAdapter ( ) ; } //other adapters throw new NotImplementedException ( ) ; } },Testing multiple implementations of an interface in a single test class "C_sharp : I have this code : In many articles stands that when I call BeginInvoke , all Exceptions ( here from method threaded ) wait until I call EndInvoke and will be thrown there . But it does n't work , the Exception ( `` Kaboom '' ) is `` unhandled '' and the program crashes.Can you help me ? Thanks ! using System ; using System.Runtime.Remoting.Messaging ; class Program { static void Main ( string [ ] args ) { new Program ( ) .Run ( ) ; Console.ReadLine ( ) ; } void Run ( ) { Action example = new Action ( threaded ) ; IAsyncResult ia = example.BeginInvoke ( new AsyncCallback ( completed ) , null ) ; // Option # 1 : /* ia.AsyncWaitHandle.WaitOne ( ) ; try { example.EndInvoke ( ia ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message ) ; } */ } void threaded ( ) { throw new ApplicationException ( `` Kaboom '' ) ; } void completed ( IAsyncResult ar ) { // Option # 2 : Action example = ( ar as AsyncResult ) .AsyncDelegate as Action ; try { example.EndInvoke ( ar ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message ) ; } } }",Delegate - Exceptions do n't wait until calling EndInvoke ( ) "C_sharp : I would like to know why this happens ? EDIT : If i debug the 'as ' keyword statement , i never get a null reference ( object always assigned properly ) . However the ( ) cast creates exceptions unless it has the if statment . EDIT : After about 15 runs through the class i was able to get a null . Seems like it took more runs to find a null compared to how fast the ( ) cast would catch an exception.OLD : When there is a debug at the 'as ' statement every time the class runs the break point hits - never null.When tthere is a debug in the ' ( ) ' statement within the if , every time the break point hits the cast works properly . Werid //always works , returning a valid object into _page _page = _httpContext.Handler as System.Web.UI.Page ; //Fails throwing the exception : Unable to cast object of type 'System.Web.DefaultHttpHandler ' to type 'System.Web.UI.Page ' _page = ( System.Web.UI.Page ) _httpContext.Handler ; //Fixes the problem if ( _httpContext.Handler is System.Web.UI.Page ) _page = ( System.Web.UI.Page ) _httpContext.Handler ;",Why does the 'as ' keyword work while the ( ) cast does not "C_sharp : I have a method which calls another method exactly 4 times , each time with different parameters . I thought of writing 4 different unit test cases to check method is called with a specific value for each call.Here is how my method looks : And here is my test method : Here is seems that I ca n't ignore other calls and just verify that the third call is called with a specific argument ( or for that matter any other call in the sequence ) . It seems that I have to call the `` AssertWasCalled '' four times and check individual argument in order . So how I can achieve this ? Or am I missing something here ? public void MainMethod ( ) { IServiceProvider serviceProvider = GetServiceProvider ( ) ; string value1 = GetValueFromStorage ( `` SomeArg1 '' ) ; // Call AnotherMethod serviceProvider.AnotherMethod ( value1 ) ; string value2 = GetValueFromStorage ( `` SomeArg2 '' ) ; // Call AnotherMethod serviceProvider.AnotherMethod ( value2 ) ; string value3 = GetValueFromStorage ( `` SomeArg3 '' ) ; // Call AnotherMethod serviceProvider.AnotherMethod ( value3 ) ; string value4 = GetValueFromStorage ( `` SomeArg4 '' ) ; // Call AnotherMethod serviceProvider.AnotherMethod ( value4 ) ; } public void TestMainMethod ( ) { // Stub storage IDataStorage dataStorage = MockRepository.GenerateStub < IDataStorage > ( ) ; // Stub serviceProvider IServiceProvider dataStorage = MockRepository.GenerateStub < IServiceProvider > ( ) ; // stub for SomeArg1 dataStorage.Stub ( x = > x.GetValueFromStorage ( null ) .IgnoreArguments ( ) .Return ( `` Value1 '' ) ) .Repeat.Once ( ) ; // stub for SomeArg2 dataStorage.Stub ( x = > x.GetValueFromStorage ( null ) .IgnoreArguments ( ) .Return ( `` Value2 '' ) ) .Repeat.Once ( ) ; // stub for SomeArg3 dataStorage.Stub ( x = > x.GetValueFromStorage ( null ) .IgnoreArguments ( ) .Return ( `` Value3 '' ) ) .Repeat.Once ( ) ; // stub for SomeArg4 dataStorage.Stub ( x = > x.GetValueFromStorage ( null ) .IgnoreArguments ( ) .Return ( `` Value4 '' ) ) .Repeat.Once ( ) ; // call MainMethod MainMethod ( ) ; // Assert that third call is called with `` Value3 '' serviceProvider.AssertWasCalled ( x = > x.AnotherMethod ( `` Value3 '' ) ) ; }","RhinoMocks - when a method is called n times , how to test its parameters in the n - k call" "C_sharp : I 'm investigating the topic of DI in ASP.NET 5 , and I faced such a problem - I do n't understand how to create a new instance of a service per request.I use the code : And inside my middlewares I grab the value : Full code is available hereAnd my problem is : while I expect this service to be renewed on each request , it does n't happen , and it behaves as if it was registered as AddSingleton ( ) .Am I doing anything wrong ? services.AddScoped < ValueStore > ( ) ; var someValueStore = app.ApplicationServices.GetService < ValueStore > ( ) ;",Per-request scope with ASP.NET 5 and built-in DI container "C_sharp : I am seeing something odd with storing doubles in a dictionary , and am confused as to why.Here 's the code : The second if statement works as expected ; 1.0 is not less than 1.0 . Now , the first if statement evaluates as true . The very odd thing is that when I hover over the if , the intellisense tells me false , yet the code happily moves to the Console.WriteLine.This is for C # 3.5 in Visual Studio 2008.Is this a floating point accuracy problem ? Then why does the second if statement work ? I feel I am missing something very fundamental here.Any insight is appreciated.Edit2 ( Re-purposing question a little bit ) : I can accept the math precision problem , but my question now is : why does the hover over evaluate properly ? This is also true of the immediate window . I paste the code from the first if statement into the immediate window and it evaluates false.UpdateFirst of all , thanks very much for all the great answers.I am also having problems recreating this in another project on the same machine . Looking at the project settings , I see no differences . Looking at the IL between the projects , I see no differences . Looking at the disassembly , I see no apparent differences ( besides memory addresses ) . Yet when I debug the original project , I see : The immediate window tells me the if is false , yet the code falls into the conditional.At any rate , the best answer , I think , is to prepare for floating point arithmetic in these situations . The reason I could n't let this go has more to do with the debugger 's calculations differing from the runtime . So thanks very much to Brian Gideon and stephentyrone for some very insightful comments . Dictionary < string , double > a = new Dictionary < string , double > ( ) ; a.Add ( `` a '' , 1e-3 ) ; if ( 1.0 < a [ `` a '' ] * 1e3 ) Console.WriteLine ( `` Wrong '' ) ; if ( 1.0 < 1e-3 * 1e3 ) Console.WriteLine ( `` Wrong '' ) ;",How does a C # evaluate floating point in hover over and immediate window versus compiled ? "C_sharp : While coding earlier I noticed something strange about SHA256 , in that it seems to generate more integers than letters for the hash . At first I thought I was just imagining it , so I put together a quick test to make sure . Astonishingly , my test seems to prove that SHA256 favors integer values in the hash that it generates . I want to know why this is . Should n't the difference between a hash index being a letter and a number be the exact same ? Here is my testing example : and my checksum/hashing class : I have ran my test multiple times , and every time it seems that more integers are generated within the hash than letters . Here are 3 test runs : Does anyone know why SHA256 seems to favor numbers instead of an equal distribution of both letters and numbers ? namespace TestingApp { static class Program { private static string letters = `` abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 '' ; private static char [ ] characters = letters.ToCharArray ( ) ; private static Random _rng = new Random ( ) ; static void Main ( string [ ] args ) { int totalIntegers = 0 ; int totalLetters = 0 ; for ( int testingIntervals = 0 ; testingIntervals < 3000 ; testingIntervals++ ) { string randomString = NextString ( 10 ) ; string checksum = DreamforceChecksum.GenerateSHA256 ( randomString ) ; int integerCount = checksum.Count ( Char.IsDigit ) ; int letterCount = checksum.Count ( Char.IsLetter ) ; Console.WriteLine ( `` String : `` + randomString ) ; Console.WriteLine ( `` Checksum : `` + checksum ) ; Console.WriteLine ( `` Integers : `` + integerCount ) ; Console.WriteLine ( `` Letters : `` + letterCount ) ; totalIntegers += integerCount ; totalLetters += letterCount ; } Console.WriteLine ( `` Total Integers : `` + totalIntegers ) ; Console.WriteLine ( `` Total Letters : `` + totalLetters ) ; Console.Read ( ) ; } private static string NextString ( int length ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < length ; i++ ) { builder.Append ( characters [ _rng.Next ( characters.Length ) ] ) ; } return builder.ToString ( ) ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Security.Cryptography ; using System.Text ; using System.Threading.Tasks ; namespace DreamforceFramework.Framework.Cryptography { public static class DreamforceChecksum { private static readonly SHA256Managed _shaManagedInstance = new SHA256Managed ( ) ; private static readonly StringBuilder _checksumBuilder = new StringBuilder ( ) ; public static string GenerateSHA256 ( string text ) { byte [ ] bytes = Encoding.UTF8.GetBytes ( text ) ; byte [ ] hash = _shaManagedInstance.ComputeHash ( bytes ) ; _checksumBuilder.Clear ( ) ; for ( int index = 0 ; index < hash.Length ; index++ ) { _checksumBuilder.Append ( hash [ index ] .ToString ( `` x2 '' ) ) ; } return _checksumBuilder.ToString ( ) ; } public static byte [ ] GenerateSHA256Bytes ( string text ) { byte [ ] bytes = Encoding.UTF8.GetBytes ( text ) ; byte [ ] hash = _shaManagedInstance.ComputeHash ( bytes ) ; _checksumBuilder.Clear ( ) ; for ( int index = 0 ; index < hash.Length ; index++ ) { _checksumBuilder.Append ( hash [ index ] .ToString ( `` x2 '' ) ) ; } return Encoding.UTF8.GetBytes ( _checksumBuilder.ToString ( ) ) ; } public static bool ValidateDataIntegrity ( string data , string targetHashcode ) { return GenerateSHA256 ( data ) .Equals ( targetHashcode ) ; } } }",Does SHA256 favor integers ? "C_sharp : I 'm writing a microformats parser in C # and am looking for some refactoring advice . This is probably the first `` real '' project I 've attempted in C # for some time ( I program almost exclusively in VB6 at my day job ) , so I have the feeling this question may become the first in a series ; - ) Let me provide some background about what I have so far , so that my question will ( hopefully ) make sense.Right now , I have a single class , MicroformatsParser , doing all the work . It has an overloaded constructor that lets you pass a System.Uri or a string containing a URI : upon construction , it downloads the HTML document at the given URI and loads it into an HtmlAgilityPack.HtmlDocument for easy manipulation by the class.The basic API works like this ( or will , once I finish the code ... ) : The use of generics here is intentional . I got my inspiration from the way that the the Microformats library in Firefox 3 works ( and the Ruby mofo gem ) . The idea here is that the parser does the heavy lifting ( finding the actual microformat content in the HTML ) , and the microformat classes themselves ( HCard in the above example ) basically provide the schema that tells the parser how to handle the data it finds.The code for the HCard class should make this clearer ( note this is a not a complete implementation ) : The attributes here are used by the parser to determine how to populate an instance of the class with data from an HTML document . The parser does the following when you call GetAll < T > ( ) : Checks that the type T has a ContainerName attribute ( and it 's not blank ) Searches the HTML document for all nodes with a class attribute that matches the ContainerName . Call these the `` container nodes '' .For each container node : Uses reflection to create an object of type T.Get the public fields ( a MemberInfo [ ] ) for type T via reflectionFor each field 's MemberInfoIf the field has a PropertyName attributeGet the value of the corresponding microformat property from the HTMLInject the value found in the HTML into the field ( i.e . set the value of the field on the object of type T created in the first step ) Add the object of type T to a List < T > Return the List < T > , which now contains a bunch of microformat objectsI 'm trying to figure out a better way to implement the step in bold . The problem is that the Type of a given field in the microformat class determines not only what node to look for in the HTML , but also how to interpret the data.For example , going back to the HCard class I defined above , the `` email '' property is bound to the EmailAddresses field , which is a List < string > . After the parser finds all the `` email '' child nodes of the parent `` vcard '' node in the HTML , it has to put them in a List < string > . What 's more , if I want my HCard to be able to return phone number information , I would probably want to be able to declare a new field of type List < HCard.TelephoneNumber > ( which would have its own ContainerName ( `` tel '' ) attribute ) to hold that information , because there can be multiple `` tel '' elements in the HTML , and the `` tel '' format has its own sub-properties . But now the parser needs to know how to put the telephone data into a List < HCard.TelephoneNumber > .The same problem applies to FloatS , DateTimeS , List < Float > S , List < Integer > S , etc.The obvious answer is to have the parser switch on the type of field , and do the appropriate conversions for each case , but I want to avoid a giant switch statement . Note that I 'm not planning to make the parser support every possible Type in existence , but I will want it to handle most scalar types , and the List < T > versions of them , along with the ability to recognize other microformat classes ( so that a microformat class can be composed from other microformat classes ) .Any advice on how best to handle this ? Since the parser has to handle primitive data types , I do n't think I can add polymorphism at the type level ... My first thought was to use method overloading , so I would have a series of a GetPropValue overloads like GetPropValue ( HtmlNode node , ref string retrievedValue ) , GetPropValue ( HtmlNode , ref List < Float > retrievedValue ) , etc . but I 'm wondering if there is a better approach to this problem . MicroformatsParser mp = new MicroformatsParser ( `` http : //microformats.org '' ) ; List < HCard > hcards = mp.GetAll < HCard > ( ) ; foreach ( HCard hcard in hcards ) { Console.WriteLine ( `` Full Name : { 0 } '' , hcard.FullName ) ; foreach ( string email in hcard.EmailAddresses ) Console.WriteLine ( `` E-Mail Address : { 0 } '' , email ) ; } [ ContainerName ( `` vcard '' ) ] public class HCard { [ PropertyName ( `` fn '' ) ] public string FullName ; [ PropertyName ( `` email '' ) ] public List < string > EmailAddresses ; [ PropertyName ( `` adr '' ) ] public List < Address > Addresses ; public HCard ( ) { } }",How would you refactor a `` switch on Type '' to be polymorphic if you do n't control the types involved ? "C_sharp : I have an ASP.NET , MVC4 , C # application which I have developed in Visual Studio 2012 . Up to now I have deployed successfully to an Azure website using the VS Publish facility.I have now successfully set up Git publishing on the Azure Website and linked it with a GitHub repository . I have initialized a repository on my local machine and pushed the whole lot to the GitHub repo . Azure immediately pulled all this as it should . Now , I was expecting that in the absence of a .gitignore file this would n't work perfectly and I was right . So my question is : What , from my local Visual Studio working directory should I be omitting from the repository ? I.e . what should be in my .gitignore ? Also , are there any other factors I should be thinking about in trying to get the application working on the Azure Website ? Notes:1 . I had a good look at https : //gist.github.com/2589150 but it does n't seem to tally with what I am seeing in the VS working directory.2 . https : //github.com/github/gitignore/blob/master/CSharp.gitignore seems nearer and I am currently working through this trying to understand which bits of it apply to my situation . For example , if I exclude bin/* then the application fails to deploy on Azure . UPDATE:1 ) I switched off custom errors by modifying my web.config file as suggested by @ levelnis : I found my problem was the database connection string which was no longer being converted to Azure by the VS Publish facility . I had to modify this directly and commit to the repo . Top tip : I found the correct string by simply looking at what the VS Publish facility put up on Azure by publishing to a temporary Azure website with a different publish profile . This fixed the problem and the deployment went very smoothly . 2 ) By this time I had the following as my .gitignore file : It seems that I can probably cut out a lot more for tidiness sake , but this was not affecting the correct operation of deploying via GitHub which now actually works extremely smoothly . Lastly , the handy git command for removing files from the repo without deleting them . A couple of examples : And then obviously add these to .gitignore before adding , committing and pushing . < configuration > < system.web > < customErrors mode= '' Off '' / > < /system.web > < /configuration > # Build Folders obj/ # User-specific files *.user # SQL Server files App_Data/*.mdf App_Data/*.ldf git rm -r -- cached obj/* git rm -r -- cached */*.user",Deploying an MVC4 C # application to Azure via GitHub . What should be in my .gitignore ? C_sharp : Say I have this class : [ AttributeUsage ( AttributeTargets.Method ) ] public class MyAttribute : Attribute { public MyAttribute ( ) { // Do stuff } ~MyAttribute ( ) { // When is this called ? When the function ends ? Whenever the GC feels like ? } },When is the desctructor called for a custom attribute class ? "C_sharp : There is no direct support for variant types ( aka tagged unions , discriminated unions ) in C # . However one can go with a visitor pattern that enables discrimination via double-dispatching and guarantees that all cases are addressed at the compile time . However it 's tedious to implement . I wonder if there is more effortless way to get : some sort of variants with a discrimination mechanism that guarantees that all cases of a union are addressed at the compile time in C # ? // This is a variant type . At each single time it can only hold one case ( a value ) // from a predefined set of cases . All classes that implement this interface// consitute the set of the valid cases of the variant . So at each time a variant can// be an instance of one of the classes that implement this interface . In order to// add a new case to the variant there must be another class that implements// this interface.public interface ISomeAnimal { // This method introduces the currently held case to whoever uses/processes // the variant . By processing we mean that the case is turned into a resulting // value represented by the generic type TResult . TResult GetProcessed < TResult > ( ISomeAnimalProcessor < TResult > processor ) ; } // This is the awkward part , the visitor that is required every time we want to// to process the variant . For each possible case this processor has a corresponding// method that turns that case to a resulting value.public interface ISomeAnimalProcessor < TResult > { TResult ProcessCat ( Cat cat ) ; TResult ProcessFish ( Fish fish ) ; } // A case that represents a cat from the ISomeAnimal variant.public class Cat : ISomeAnimal { public CatsHead Head { get ; set ; } public CatsBody Body { get ; set ; } public CatsTail Tail { get ; set ; } public IEnumerable < CatsLeg > Legs { get ; set ; } public TResult GetProcessed < TResult > ( ISomeAnimalProcessor < TResult > processor ) { // a processor has a method for each case of a variant , for this // particular case ( being a cat ) we always pick the ProcessCat method return processor.ProcessCat ( this ) ; } } // A case that represents a fish from the ISomeAnimal variant.public class Fish : ISomeAnimal { public FishHead Head { get ; set ; } public FishBody Body { get ; set ; } public FishTail Tail { get ; set ; } public TResult GetProcessed < TResult > ( ISomeAnimalProcessor < TResult > processor ) { // a processor has a method for each case of a variant , for this // particular case ( being a fish ) we always pick the ProcessCat method return processor.ProcessFish ( this ) ; } } public static class AnimalPainter { // Now , in order to process a variant , in this case we want to // paint a picture of whatever animal it prepresents , we have to // create a new implementation of ISomeAnimalProcessor interface // and put the painting logic in it . public static void AddAnimalToPicture ( Picture picture , ISomeAnimal animal ) { var animalToPictureAdder = new AnimalToPictureAdder ( picture ) ; animal.GetProcessed ( animalToPictureAdder ) ; } // Making a new visitor every time you need to process a variant : // 1 . Requires a lot of typing . // 2 . Bloats the type system . // 3 . Makes the code harder to maintain . // 4 . Makes the code less readable . private class AnimalToPictureAdder : ISomeAnimalProcessor < Nothing > { private Picture picture ; public AnimalToPictureAdder ( Picture picture ) { this.picture = picture ; } public Nothing ProcessCat ( Cat cat ) { this.picture.AddBackground ( new SomeHouse ( ) ) ; this.picture.Add ( cat.Body ) ; this.picture.Add ( cat.Head ) ; this.picture.Add ( cat.Tail ) ; this.picture.AddAll ( cat.Legs ) ; return Nothing.AtAll ; } public Nothing ProcessFish ( Fish fish ) { this.picture.AddBackground ( new SomeUnderwater ( ) ) ; this.picture.Add ( fish.Body ) ; this.picture.Add ( fish.Tail ) ; this.picture.Add ( fish.Head ) ; return Nothing.AtAll ; } } }",Is there a way to have variants in C # besides using the visitor pattern ? "C_sharp : In to following tutorial : http : //www.albahari.com/threading/They say that the following code : is non deterministic and can produce the following answer : 0223557799I thought that when one uses lambda expressions the compiler creates some kind of anonymous class that captures the variables that are in use by creating members like them in the capturing class.But i is value type , so i thought that he should be copied by value.where is my mistake ? It will be very helpful if the answer will explain how does closure work , how do it hold a `` pointer '' to a specific int , what code does generated in this specific case ? for ( int i = 0 ; i < 10 ; i++ ) new Thread ( ( ) = > Console.Write ( i ) ) .Start ( ) ;",How closure in c # works when using lambda expressions ? "C_sharp : I have specified a couple of interfaces , which I am implementing as entities using Entity Framework 4 . The simplest demonstration code I can come up with is : I receive the following compiler error from the above : 'Demo.ConcreteContainer ' does not implement interface member 'Demo.IContainer.Children ' . 'Demo.ConcreteContainer.Children ' can not implement 'Demo.IContainer.Children ' because it does not have the matching return type of 'System.Collections.Generic.IEnumerable'My current understanding is that this is because IEnumerable ( which is implemented by EntityCollection ) is covariant but presumably not contravariant : This type parameter is covariant . That is , you can use either the type you specified or any type that is more derived . For more information about covariance and contravariance , see Covariance and Contravariance in Generics.Am I correct , & if so , is there any way I can achieve my goal of specifying the IContainer interface purely in terms of other interfaces rather than using concrete classes ? Or , am I misunderstanding something more fundamental ? public class ConcreteContainer : IContainer { public EntityCollection < ConcreteChild > Children { get ; set ; } } public class ConcreteChild : IChild { } public interface IContainer { IEnumerable < IChild > Children { get ; set ; } } public interface IChild { }",Contravariance and Entity Framework 4.0 : how to specify EntityCollection as IEnumerable ? "C_sharp : I 've written the following extension method to concatenate two IBuffer objects in a Windows Runtime application : Is this the most efficient way to handle this ? Is there a better or easier way ? I 've reviewed Best way to combine two or more byte arrays in C # but I do n't think I should be converting to and from byte arrays . public static IBuffer Concat ( this IBuffer buffer1 , IBuffer buffer2 ) { var capacity = ( int ) ( buffer1.Length + buffer2.Length ) ; var result = WindowsRuntimeBuffer.Create ( capacity ) ; buffer1.CopyTo ( result ) ; buffer2.CopyTo ( 0 , result , buffer1.Length , buffer2.Length ) ; return result ; }",What is the best way to concatenate two Windows Runtime Buffers ? "C_sharp : I have the following class to manage access to a resource : Usage : Now it allows not more than 20 shared usages.How to modify this class to allow not more than N shared usages per unit of time ( for example , not more than 20 per second ) ? class Sync : IDisposable { private static readonly SemaphoreSlim Semaphore = new SemaphoreSlim ( 20 ) ; private Sync ( ) { } public static async Task < Sync > Acquire ( ) { await Semaphore.WaitAsync ( ) ; return new Sync ( ) ; } public void Dispose ( ) { Semaphore.Release ( ) ; } } using ( await Sync.Acquire ( ) ) { // use a resource here }",Timed semaphore "C_sharp : I 'm using a Frame control on a Xamarin Forms Shared project.I just have some styles : and a simple Frame control in XAML page : and i get somthing like this : now , if i try to change the background color at run time : the frame control loses the border roundness : I do n't understand this behavior , i need to change the back color , but i would like to keep the rounded edges.Thanks to anyone who gave me a hand < Color x : Key= '' Info '' > # 0060ac < /Color > ... < Style x : Key= '' LabelContainer '' TargetType= '' Frame '' > < Setter Property= '' Padding '' Value= '' 5 '' / > < Setter Property= '' HorizontalOptions '' Value= '' Fill '' / > < /Style > < Style x : Key= '' LabelContainer-Info '' TargetType= '' Frame '' BasedOn= '' { StaticResource LabelContainer } '' > < Setter Property= '' BackgroundColor '' Value= '' { DynamicResource Info } '' / > < /Style > < Frame x : Name= '' CreditCardPaymentResultFrame '' Style= '' { StaticResource LabelContainer-Info } '' Padding= '' 0 '' > < Label x : Name= '' PaymentErrorLabel '' Text= '' Lorem ipsum '' IsVisible= '' True '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' FillAndExpand '' VerticalTextAlignment= '' Center '' HorizontalTextAlignment= '' Center '' FontSize= '' 18 '' TextColor= '' White '' > < /Label > < /Frame > CreditCardPaymentResultFrame.BackgroundColor = Color.FromHex ( `` # ed3700 '' ) ;",Setting Frame.BackgroundColor loses rounded corner on Xamarin forms "C_sharp : This is a philosophical question about C # fundamentals : I am wondering how close an interface may be simulated by fully abstract class . Assume we have following interface : And following abstract class : They are having so much in common , are n't they ? The differences I know are that : Multiple inheritance does not work for abstract classesExplicit implementation does not work abstract classesCan these restrictions be skipped by using reflection or something like this ? I realize that interface and abstract class are different in root : interface declares a condition of `` can behave like '' , abstract class - `` is a kind of '' , but even this seems to be so close that a low level differences between these entities have to be discussed . This question can even sound like `` What would you do to make an interface in C++ '' . public interface INativeInterface { void PerformAction ( ) ; String Property { get ; set ; } } public abstract class ISimulatedInterface { public abstract void PerformAction ( ) ; public abstract String Property { get ; set ; } }",C # hack : low level difference between interface and abstract class "C_sharp : I know it might not be worth it but just for education purposes I want to know if there is a way to inject your own keywords to .NET languages.For example I thought it 's good to have C++ asm keyword in C # .Remember I 'm not talking about how to implement asm keyword but a general way to add keyword to C # . My imagined code : So is there a way to achieve this ? The answers which cover implementing keyword { } suits enough for this question . asm { mov ax,1 add ax,4 }",Is it possible to add keyword to C # or VB.NET ? "C_sharp : While I can upcast a string to an object , I can not upcast an IList of strings to an IList of objects . How come ? What to do now other that coping all items to a new IList ? static void ThisWorks ( ) { IList < object > list = new List < object > ( ) ; list.Add ( `` I can add a string since string : object '' ) ; } static void ThisDoesNotWork ( ) { // throws an invalid cast exception IList < object > list = ( IList < object > ) new List < string > ( ) ; list.Add ( `` I 'm never getting here ... why ? `` ) ; }",C # : No casting within Generics ? "C_sharp : When my AABB physics engine resolves an intersection , it does so by finding the axis where the penetration is smaller , then `` push out '' the entity on that axis.Considering the `` jumping moving left '' example : If velocityX is bigger than velocityY , AABB pushes the entity out on the Y axis , effectively stopping the jump ( result : the player stops in mid-air ) .If velocityX is smaller than velocitY ( not shown in diagram ) , the program works as intended , because AABB pushes the entity out on the X axis.How can I solve this problem ? Source code : public void Update ( ) { Position += Velocity ; Velocity += World.Gravity ; List < SSSPBody > toCheck = World.SpatialHash.GetNearbyItems ( this ) ; for ( int i = 0 ; i < toCheck.Count ; i++ ) { SSSPBody body = toCheck [ i ] ; body.Test.Color = Color.White ; if ( body ! = this & & body.Static ) { float left = ( body.CornerMin.X - CornerMax.X ) ; float right = ( body.CornerMax.X - CornerMin.X ) ; float top = ( body.CornerMin.Y - CornerMax.Y ) ; float bottom = ( body.CornerMax.Y - CornerMin.Y ) ; if ( SSSPUtils.AABBIsOverlapping ( this , body ) ) { body.Test.Color = Color.Yellow ; Vector2 overlapVector = SSSPUtils.AABBGetOverlapVector ( left , right , top , bottom ) ; Position += overlapVector ; } if ( SSSPUtils.AABBIsCollidingTop ( this , body ) ) { if ( ( Position.X > = body.CornerMin.X & & Position.X < = body.CornerMax.X ) & & ( Position.Y + Height/2f == body.Position.Y - body.Height/2f ) ) { body.Test.Color = Color.Red ; Velocity = new Vector2 ( Velocity.X , 0 ) ; } } } } } public static bool AABBIsOverlapping ( SSSPBody mBody1 , SSSPBody mBody2 ) { if ( mBody1.CornerMax.X < = mBody2.CornerMin.X || mBody1.CornerMin.X > = mBody2.CornerMax.X ) return false ; if ( mBody1.CornerMax.Y < = mBody2.CornerMin.Y || mBody1.CornerMin.Y > = mBody2.CornerMax.Y ) return false ; return true ; } public static bool AABBIsColliding ( SSSPBody mBody1 , SSSPBody mBody2 ) { if ( mBody1.CornerMax.X < mBody2.CornerMin.X || mBody1.CornerMin.X > mBody2.CornerMax.X ) return false ; if ( mBody1.CornerMax.Y < mBody2.CornerMin.Y || mBody1.CornerMin.Y > mBody2.CornerMax.Y ) return false ; return true ; } public static bool AABBIsCollidingTop ( SSSPBody mBody1 , SSSPBody mBody2 ) { if ( mBody1.CornerMax.X < mBody2.CornerMin.X || mBody1.CornerMin.X > mBody2.CornerMax.X ) return false ; if ( mBody1.CornerMax.Y < mBody2.CornerMin.Y || mBody1.CornerMin.Y > mBody2.CornerMax.Y ) return false ; if ( mBody1.CornerMax.Y == mBody2.CornerMin.Y ) return true ; return false ; } public static Vector2 AABBGetOverlapVector ( float mLeft , float mRight , float mTop , float mBottom ) { Vector2 result = new Vector2 ( 0 , 0 ) ; if ( ( mLeft > 0 || mRight < 0 ) || ( mTop > 0 || mBottom < 0 ) ) return result ; if ( Math.Abs ( mLeft ) < mRight ) result.X = mLeft ; else result.X = mRight ; if ( Math.Abs ( mTop ) < mBottom ) result.Y = mTop ; else result.Y = mBottom ; if ( Math.Abs ( result.X ) < Math.Abs ( result.Y ) ) result.Y = 0 ; else result.X = 0 ; return result ; }",Platform jumping problems with AABB collisions "C_sharp : The MSDN documentation for the Flag attribute says that you should : Define enumeration constants in powers of two , that is , 1 , 2 , 4 , 8 , and so on . This means the individual flags in combined enumeration constants do not overlap ... .and of course I always try to remember to do that . However , nothing enforce that and if you just create an enumeration the 'basic ' way like ... ... it wo n't behave as expected . To combat this , I 'm looking for some kind of static code analysis ( like FxCop ) that can warn me when an enum like the one above exists in my code . The closest such warning I could find was 'CA1008 : Enums should have zero value ' - which is also helpful for designing flags enumeration correctly but is n't enough.What is the best way to find incorrectly designed flags enums in my code ? The more automated the solution , the better . [ Flags ] public enum BrokenEnum { None , FirstOption , SecondOption , ThirdOption }",Flag enums without power of two values "C_sharp : I asked a question like this in an interview for a entry level programmer : The applicant responded with `` hello '' , `` bye '' as the output.Some of my co-workers said that `` pointers '' are not that important anymore or that this question is not a real judge of ability.Are they right ? EDIT : The point was made that MyObject could have been a struct . That is a Good point . However , I did not post the full question I gave the interviewee . The full question had a class that was clearly a class ( not a struct ) . It can be found here . var instance1 = new MyObject { Value = `` hello '' } var instance2 = instance1 ; instance1.Value = `` bye '' ; Console.WriteLine ( instance1.Value ) ; Console.WriteLine ( instance2.Value ) ;",At What point should you understand References ? "C_sharp : I have the following C # code that i need to convert to javascript : i see that javascript has a split ( ) function as well but i wanted to see if there is built in support for the other checks or i have to do an additional loop around the array afterwards to `` clean up '' the data ? static private string [ ] ParseSemicolon ( string fullString ) { if ( String.IsNullOrEmpty ( fullString ) ) return new string [ ] { } ; if ( fullString.IndexOf ( ' ; ' ) > -1 ) { return fullString.Split ( new [ ] { ' ; ' } , StringSplitOptions.RemoveEmptyEntries ) .Select ( str = > str.Trim ( ) ) .ToArray ( ) ; } else { return new [ ] { fullString.Trim ( ) } ; } }",What is the best way to do split ( ) in javascript and ignore blank entries ? "C_sharp : I have a CHM helpfile for my WPF Application . My CHM file contains `` htm '' files for each page of my application . I want to open the help file for the corresponding page when the user presses F1 on that page . Right now I am able to locate the page and open that page by using the following code : where keywordText contains the URL of my htm file for the selected page.But the problem is , that the panel on the left side ( contents tab in a tree view ) is not expanded to the page that opened in the right window . The panel on the left side always remains the same . How Can I expand the tree view on the left side to the selected page ? Help.ShowHelp ( this , helpfile , keywordText ) ;",How to set the Selected item in the tree view on the Left side of CHM file C_sharp : In our code there is a regular expression of the following form : What does the `` ( ? i ) '' at the beginning of the regex match/do ? I 've looked through the .NET regex documentation and ca n't seem to figure out what ( ? i ) would mean . Thanks ! string regex = @ '' ( ? i ) foo= ( BAR ? - [ A-Z ] + ( 33|34 ) ? ) '' ;,What does ( ? i ) in a .NET regular expression mean ? "C_sharp : I made a small test application in C # that sets DateTime.Now and starts a StopWatch . Every ten seconds I print _stopwatch.Elapsed.TotalMilliseconds and ( DateTime.Now - _startTime ) .TotalMilliseconds.While I do n't expect the two to be identical , I was surprised to see them diverge linearly by about one millisecond per 20 seconds . I assume DateTime.Now calls the system clock , while the StopWatch does some kind of accumulation ? Sample output : Full source : https : //gist.github.com/knatten/86529563122a342de6bbOutput : https : //gist.github.com/knatten/84f9be9019ee63119ee2 StopWatch : 0,2 DateTime : 1,0 Diff : 0,81StopWatch : 10000,5 DateTime : 10002,6 Diff : 2,04 ( ... ) StopWatch : 2231807,5 DateTime : 2231947,7 Diff : 140,13StopWatch : 2241809,5 DateTime : 2241950,2 Diff : 140,70",Why does DateTime.Now and StopWatch drift ? "C_sharp : I need some help implementing Dijkstra 's Algorithm and was hoping someone would be able to assist me . I have it so that it is printing some of routes but it is n't capturing the correct costs for the path.Here is my node structure : Here is my algorithm : This is what the graph looks like : The graph list node is essentially Node -- Neighbor NodesSo for example : Node = Olympia , Neighbor Nodes = Lacey and Tacoma class Node { public enum Color { White , Gray , Black } ; public string Name { get ; set ; } //city public List < NeighborNode > Neighbors { get ; set ; } //Connected Edges public Color nodeColor = Color.White ; public int timeDiscover { get ; set ; } //discover time public int timeFinish { get ; set ; } // finish time public Node ( ) { Neighbors = new List < NeighborNode > ( ) ; } public Node ( string n , int discover ) { Neighbors = new List < NeighborNode > ( ) ; this.Name = n ; timeDiscover = discover ; } public Node ( string n , NeighborNode e , decimal m ) { Neighbors = new List < NeighborNode > ( ) ; this.Name = n ; this.Neighbors.Add ( e ) ; } } class NeighborNode { public Node Name { get ; set ; } public decimal Miles { get ; set ; } //Track the miles on the neighbor node public NeighborNode ( ) { } public NeighborNode ( Node n , decimal m ) { Name = n ; Miles = m ; } } public void DijkstraAlgorithm ( List < Node > graph ) { List < DA > _algorithmList = new List < DA > ( ) ; //track the node cost/positioning Stack < Node > _allCities = new Stack < Node > ( ) ; // add all cities into this for examination Node _nodeToExamine = new Node ( ) ; //this is the node we 're currently looking at . decimal _cost = 0 ; foreach ( var city in graph ) // putting these onto a stack for easy manipulation . Probably could have just made this a stack to start { _allCities.Push ( city ) ; _algorithmList.Add ( new DA ( city ) ) ; } _nodeToExamine = _allCities.Pop ( ) ; //pop off the first node while ( _allCities.Count ! = 0 ) // loop through each city { foreach ( var neighbor in _nodeToExamine.Neighbors ) //loop through each neighbor of the node { for ( int i = 0 ; i < _algorithmList.Count ; i++ ) //search the alorithm list for the current neighbor node { if ( _algorithmList [ i ] .Name.Name == neighbor.Name.Name ) //found it { for ( int j = 0 ; j < _algorithmList.Count ; j++ ) //check for the cost of the parent node { if ( _algorithmList [ j ] .Name.Name == _nodeToExamine.Name ) //looping through { if ( _algorithmList [ j ] .Cost ! = 100000000 ) //not infinity _cost = _algorithmList [ j ] .Cost ; //set the cost to be the parent cost break ; } } _cost = _cost + neighbor.Miles ; if ( _algorithmList [ i ] .Cost > _cost ) // check to make sure the miles are less ( better path ) { _algorithmList [ i ] .Parent = _nodeToExamine ; //set the parent to be the top node _algorithmList [ i ] .Cost = _cost ; // set the weight to be correct break ; } } } } _cost = 0 ; _nodeToExamine = _allCities.Pop ( ) ; } }",Dijkstra 's Algorithm implementation giving incorrect results "C_sharp : I 'm struggling with some concurrency issues in relation subscribing to an Observable.FromEventPattern ( ) on the TaskPoolScheduler.Let me illustrate with a code example : My issue is that , when any new items are emitted by the original observable Observable.FromEventPattern ( ) ( i.e . when the DataStore object raises new DataChanged events ) , then they appear to be blocked waiting for the previous items to finish flowing through the entire pipeline.Since the subscribing is done on the TaskPoolScheduler I had expected every new item emitted to simply spin up a new task , but actually , the source of the event instead seems to block on the event invocation if the pipeline is busy.How can I accomplish a subscription that executes every new emitted item ( raised event ) on it 's own task/thread , such that the source object never blocks on its internal DataChangedEvent.Invoke ( ) call ? ( Except of course the Subscribe ( ) lambda which should execute on the UI thread - which is already the case . ) As a side-note : @ jonstodle mentioned in the # rxnet Slack channel that the TaskPoolScheduler might have different semantics than what I assumed . Specifically he said it probably creates one task and does both the subscribing and the producing of values in an event loop inside of that one task . But if that 's the case , then I find it a bit strange that the first event invocation does n't block ( since the second one does ) . Seems to me that if the task pool task doing the subscription is asynchronous enough that the souce does n't have to block on the first invocation , there should n't be a need to make it block on the second call either ? var dataStore = new DataStore ( ) ; Observable.FromEventPattern < DataChangedEventArgs > ( dataStore , nameof ( dataStore.DataChanged ) ) .SubscribeOn ( TaskPoolScheduler.Default ) .Select ( x = > x.EventArgs ) .StartWith ( new DataChangedEventArgs ( ) ) .Throttle ( TimeSpan.FromMilliseconds ( 25 ) ) .Select ( x = > { Thread.Sleep ( 5000 ) ; // Simulate long-running calculation . var result = 42 ; return result ; } ) .ObserveOn ( new SynchronizationContextScheduler ( SynchronizationContext.Current ) ) .Subscribe ( result = > { // Do some interesting work with the result . // ... // Do something that makes the DataStore raise another event . dataStore.RaiseDataChangedEvent ( ) ; // < - DEADLOCK ! } ) ; dataStore.RaiseDataChangedEvent ( ) ; // < - Returns immediately , i.e . does NOT wait for long-running calculation.dataStore.RaiseDataChangedEvent ( ) ; // < - Blocks while waiting for the previous long-running calculation to complete , then returns eventually .",How can I avoid any blocking when using Observable.FromEventPattern in Reactive Extensions for .NET ? "C_sharp : Is there some way to intercept the HTML output stream in asp.net and make modifications ? Eg using httpmodules or something ? I know this is possible using java servlets and assume there must be an elegant way to do this with asp.net.My purpose is to combine the many javascript files into one composite script which has been minified/packed , to make the page load faster.Eg , if my page normally outputs the following in the page head : I want to replace that with the following : ( also i realise i 'll have to create all.js somehow ) .Thanks ! < script type= '' text/javascript '' src= '' /scripts/blah.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/yada.js '' > < /script > < script type= '' text/javascript '' src= '' /scripts/all.js '' > < /script >","Is there some way to intercept and modify the html output stream in asp.net , to combine the javascript ?" "C_sharp : Consider the following code : On the Name=Name.ToUpper ( ) I get a warning that Name is a possible null reference , which is clearly incorrect . I can cure this warning by inlining HasName so the condition is if ( Name ! = null ) .Is there any way I can instruct the compiler that a true response from HasName implies a non-nullability constraint on Name ? This is important because HasName might actually test a lot more things , and I might want to use it in several places , or it might be a public part of the API surface . There are many reasons to want to factor the null check into it 's own method , but doing so seems to break the nullable reference checker . # nullable enableclass Foo { public string ? Name { get ; set ; } public bool HasName = > Name ! = null ; public void NameToUpperCase ( ) { if ( HasName ) { Name = Name.ToUpper ( ) ; } } }",Can I tell C # nullable references that a method is effectively a null check on a field "C_sharp : In C # how do i specify regex to replace multiple groups . For example i would like to replace more than one instance of either \r\n or \r\r with a environment newline . I logically wrote this regex , but i know it is wrong . Please correct and explain how it works.Input textWhere each line may be separated either by \r\n or \r\r . Expected outcome after regex replace is below System.Text.RegularExpressions.Regex.Replace ( task.Message , @ '' ( \r\n ) { 2 , } ( \r\r ) { 2 , } '' , System.Environment.NewLine ) ; StackoverflowStackExchangeUser Experience Stackoverflow StackExchange User Experience",Regex replace multiple new lines "C_sharp : I 'm reading Effective C # and there is a comment about Object.GetHashCode ( ) that I did n't understand : Object.GetHashCode ( ) uses an internal field in the System.Object class to generate the hash value . Each object created is assigned a unique object key , stored as an integer , when it is created . These keys start at 1 and increment every time a new object of any type gets created . The object identity field is set in the System.Object constructor and can not be modified later . Object.GetHashCode ( ) returns this value as the hash code for a given object.I tried to look at the documentation of Object.GetHashCode ( ) and did n't find any information about this.I wrote the simple piece of code to print the hash code of newly generated objects : The first few numbers that were printed were : Which did n't seem to fit that These keys start at 1 and increment every time a new object of any type gets created ... Object.GetHashCode ( ) returns this valueThen , in order to find this `` internal field in the System.Object '' I tried using ReSharper decompiled sources but the code I found was and again using decompiled sources I found that RuntimeHelpers.GetHashCode was implemented as following the MethodImpl attribute it seems that I ca n't view the implementation and this is a dead end for me.Can someone please explain the comment by the author ( the first quote ) ? What is the internal field within the Object class and how it is used for the implementation of the Object.GetHashCode ( ) ? using System ; namespace TestGetHashCode { class Program { static void Main ( string [ ] args ) { for ( int i = 0 ; i < 100 ; i++ ) { object o = new object ( ) ; Console.WriteLine ( o.GetHashCode ( ) ) ; } } } } 37121646,45592480,57352375,2637164,41014879,3888474,25209742,26966483,31884011 [ TargetedPatchingOptOut ( `` Performance critical to inline across NGen image boundaries '' ) ] [ __DynamicallyInvokable ] public virtual int GetHashCode ( ) { return RuntimeHelpers.GetHashCode ( this ) ; } [ SecuritySafeCritical ] [ __DynamicallyInvokable ] [ MethodImpl ( MethodImplOptions.InternalCall ) ] public static int GetHashCode ( object o ) ;",Implementation of Object.GetHashCode ( ) "C_sharp : What is the best way to create acronym from upper letters in C # ? Example : Alfa_BetaGameDelta_EpsilonExpected result : ABGDEMy solution works , but it 's not nice var classNameAbbreviationRegex = new Regex ( `` [ A-Z ] + '' , RegexOptions.Compiled ) ; var matches = classNameAbbreviationRegex.Matches ( enumTypeName ) ; var letters = new string [ matches.Count ] ; for ( var i = 0 ; i < matches.Count ; i++ ) { letters [ i ] = matches [ i ] .Value ; } var abbreviation = string.Join ( string.Empty , letters ) ;",Is there a better way to create acronym from upper letters in C # ? "C_sharp : I have a set of interfaces and classes that look something like this : The problem I run into is when I try use Linq on my ItemCollection , it gets confused because there are two IEnumerable interfaces.I get the following error message : The type arguments for method 'System.Linq.Enumerable.Where ( ... ) can not be inferred from the usage . Try specifying the type arguments explicitly.Is there any way to hide the `` more primitive '' IEnumerable < IItem > interface so it will always choose the IEnumerable < TItem > when dealing with the ItemCollection < , > , but still provide the IEnumerable < IItem > interface when dealing with IItemCollection interface ? ( As I 'm about to post this , I realized that there 's a workaround , to implement it like this : But I still want to know if there 's a way to hide an interface . ) public interface IItem { // interface members } public class Item < T > : IItem { // class members , and IItem implementation } public interface IItemCollection : IEnumerable < IItem > { // This should be enumerable over all the IItems } // We can not implement both IItemCollection and IEnumerable < TItem > at// the same time , so we need a go between class to implement the// IEnumerable < IItem > interface explicitly : public abstract class ItemCollectionBase : IItemCollection { protected abstract IEnumerator < IItem > GetItems ( ) ; IEnumerator < IItem > IEnumerable < IItem > .GetEnumerator ( ) { return GetItems ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetItems ( ) ; } } public class ItemCollection < TKey , TItem > : ItemCollectionBase , IEnumerable < TItem > where TItem : class , IItem , new ( ) { private Dictionary < TKey , TItem > dictionary ; protected override GetItems ( ) { return dictionary.Values ; } public IEnumerator < TItem > GetEnumerator ( ) { return dictionary.Values ; } } public interface IItemCollection { IEnumerable < IItem > Items { get ; } }",C # can you hide an inherited interface ? "C_sharp : Been having a `` heated debate '' with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a `` throw '' in it e.g.My thought was to not even bother ( assuming you do n't need to do anything at this point ) - the exception would bubble to the next exception handler in a parent member.The only argument that sounded plausible was that sometimes exceptions were n't caught and your code stopped ( in debug mode ) with the current line highlighted in green ... and that this may be something to do with multiple threads ? Best practice does state `` an exception handler for each thread '' but mostly we work single-threaded.The good thing may be it could be useful in debug mode to not suddenly pop out to a parent member ( yes , Joel ! ) - you 'd move to the `` throw '' statement and be able to examine your locals.But then your code would be `` littered with try/catch/throws '' ( to quote another thread here ) ? And what sort of overhead would be involved in adding try/catch/throws everywhere if no exception occurs ( i.e . should you avoid try/catches in tight loops ) ? Private sub foo ( ) try 'Do something ' catch throw 'And nothing else ! ' End TryEnd Sub",Is there a benefit to JUST a `` throw '' in a catch ? "C_sharp : I have got a DataSet filled with two Tables : And then I have got a DataRelation for these two tables.So I want to print the Student with his ID , Name and the Name of his town.That 's why I create a DataRelation.However , when I add the DataSet to my DataGridView I always get the TownId instead of the TownName . dbSet = new DataSet ( ) ; //DataTable and DataRelationDataTable dtStudent = new DataTable ( `` Student '' ) ; //fill datatable 1dtStudent.Columns.Add ( `` Id '' , typeof ( int ) ) ; dtStudent.Columns.Add ( `` Name '' , typeof ( string ) ) ; dtStudent.Columns.Add ( `` TownId '' , typeof ( int ) ) ; dtStudent.Rows.Add ( new object [ ] { 1 , `` Arthur '' , 1 } ) ; dtStudent.Rows.Add ( new object [ ] { 2 , `` Stefan '' , 2 } ) ; DataTable dtTown = new DataTable ( `` Town '' ) ; dtTown.Columns.Add ( `` Id '' , typeof ( int ) ) ; dtTown.Columns.Add ( `` Name '' , typeof ( string ) ) ; dtTown.Rows.Add ( new object [ ] { 1 , `` KW '' , } ) ; dtTown.Rows.Add ( new object [ ] { 2 , `` Perg '' , } ) ; dbSet.Tables.Add ( dtStudent ) ; dbSet.Tables.Add ( dtTown ) ; //DataRelationDataColumn parentCol , childCol ; childCol = dbSet.Tables [ `` Town '' ] .Columns [ `` Id '' ] ; parentCol = dbSet.Tables [ `` Student '' ] .Columns [ `` TownId '' ] ; DataRelation dr ; dr = new DataRelation ( `` DataRelation '' , parentCol , childCol ) ; dbSet.Relations.Add ( dr ) ; dgv.DataSource = dbSet ; dgv.DataMember = `` Student '' ;",DataRelation in a DataGridView "C_sharp : I 've written a simple .Net client that connects to a hardware device ( FPGA ) over TCP/IP . When I click a button in the client it sends a small ( 4 byte ) `` request '' to the device , then immediately reads a block of data ( approx 32kb ) that the device responds with . The client code looks something like this : -Using a Stopwatch in the above code typically reports 2-3ms to read the entire 32kb response back , and this timing remains consistent if I repeatedly click the button slowly ( e.g . once per second ) . If I start clicking the button more rapidly ( e.g . every half a second ) then after a few seconds the timings suddenly drop to around 12ms and stay there , even if I go back to clicking the button slowly . If I close then reopen the connection on the client and try again , it 's back to 2-3ms times.WireShark shows 3-4 ACKs coming out of the PC during the faster responses , but this increases to a dozen or more once the timing drops to 12ms . In both cases the number and size of packets coming from the FPGA is the same . I 'm as confident as I can be that it 's not a problem in the code on the client or FPGA ( neither can get much simpler ) - gut feeling is that it 's a protocol or network thing . Any thoughts ? var stream = _tcpClient.GetStream ( ) ; stream.Write ( requestData , 0 , requestData.Length ) ; using ( var ms = new MemoryStream ( ) ) { var tempBuffer = new byte [ 65535 ] ; do { var numBytesRead = stream.Read ( tempBuffer , 0 , tempBuffer.Length ) ; ms.Write ( tempRead , 0 , numBytesRead ) ; } while ( ms.Length < ExpectedResponseSize ) ; _hardwareResponse = ms.ToArray ( ) ; }",Slow down in TCP/IP receive speed C_sharp : Is there anyway to explicitly cast/coerce sbyte [ ] or byte [ ] to a bool [ ] char [ ] to a short [ ] /ushort [ ] In CIL you regularly see something such as which is doing pArray [ 1 ] = true where pArray is a one-dimensional array of type bool [ ] . I want to replicate this in c # by doing Unfortunately this is not allowed by the C # compiler . stelem Type sbyte ( ldloc pArray ) ldc_i4 1 ldc_i4 0 ( sbyte [ ] ) pArray [ 1 ] = 1 ;,Casting sbyte [ ] to bool [ ] and a char [ ] to short [ ] C_sharp : In delphi I can declare a type of class like soWhich is the C # equivalent for this declaration ? type TFooClass = class of TFoo ; TFoo=class end ;,which is the C # declaration equivalent of delphi `` class of `` ( type of class ) ? "C_sharp : First of all , sorry about the title -- I could n't figure out one that was short and clear enough.Here 's the issue : I have a list List < MyClass > list to which I always add newly-created instances of MyClass , like this : list.Add ( new MyClass ( ) ) . I do n't add elements any other way.However , then I iterate over the list with foreach and find that there are some null entries . That is , the following code : will sometimes throw an exception.I should point out that the list.Add ( new MyClass ( ) ) are performed from different threads running concurrently . The only thing I can think of to account for the null entries is the concurrent accesses . List < > is n't thread-safe , after all . Though I still find it strange that it ends up containing null entries , instead of just not offering any guarantees on ordering.Can you think of any other reason ? Also , I do n't care in which order the items are added , and I do n't want the calling threads to block waiting to add their items . If synchronization is truly the issue , can you recommend a simple way to call the Add method asynchronously , i.e. , create a delegate that takes care of that while my thread keeps running its code ? I know I can create a delegate for Add and call BeginInvoke on it . Does that seem appropriate ? Thanks.EDIT : A simple solution based on Kevin 's suggestion : I only need to control Add operations and I just need this for debugging ( it wo n't be in the final product ) , so I just wanted a quick fix.Thanks everyone for your answers . foreach ( MyClass entry in list ) if ( entry == null ) throw new Exception ( `` null entry ! `` ) ; public class AsynchronousList < T > : List < T > { private AddDelegate addDelegate ; public delegate void AddDelegate ( T item ) ; public AsynchronousList ( ) { addDelegate = new AddDelegate ( this.AddBlocking ) ; } public void AddAsynchronous ( T item ) { addDelegate.BeginInvoke ( item , null , null ) ; } private void AddBlocking ( T item ) { lock ( this ) { Add ( item ) ; } } }",List with non-null elements ends up containing null . A synchronization issue ? "C_sharp : If an API has a synchronous method T DoSomething < T > ( ) ; , what is the naming convention for the corresponding asynchronous method if it returns Task < T > ? oror something else ? Task < T > DoSomethingTask < T > ( ) ; Task < T > DoSomethingAsync < T > ( ) ;",Should methods in an API that return Task end with Task or Async "C_sharp : I think I 've got a good one for you.I 've got some C # code that encrypts and decrypts strings . It looks something like this : When I encrypt or decrypt in C # it works like a charm . In php I have a decryption algorithm that looks like this : The commented out code is just some of the attempts I 've made to get the string decoded correctly . The strange part , is that sometimes it works and sometimes it does n't even without strange characters . For example : Herp Derp with key : Red worksMessage Herp Derp with key swordfish does not work.Long messages with the key red do no work.No message with key swordfish works.Could that mean that the length of the message key is part of the problem ? I have ensured that the message and the key are correctly transmitted between the php and the C # it is definitely a problem with the encoding/decoding , and based on the garbage that 's spit out I think it has to do with UTF8 encoding . I suspect the padding mode as a possible culprit as well , any ideas ? Edit : I did n't notice the 1 or 2 missing pluses that would foobar the whole string , Sorry Stack : \ * Does anyone know how to fix it ? Edit After changing to key size , no strings work.With message Herp Derp and password red , php outputs decrypted as .�ʇ ' y-�US2~h\�0�nAZ=�\2/�����|�a���R� ` �/������nY� < [ B�NB� @ �M_f�E�� > 7� . Does anyone know what character encoding that might be ? Comparing bytes of just encrypted cypertext in C # and just decrypted PHP , I getC # php and then c # Which would indicate the mcrypt call is not working , but how would I fix it ? Edit I have changed the packing mode to zero 's , in an attempt to further simplify the problem.Solved I 'll post the solution shortly . public static string EncryptString ( String toEncrypt , String key ) { Debug.WriteLine ( `` Encrypting string : `` + toEncrypt + `` & key : '' + key ) ; Rijndael AES = Rijndael.Create ( ) ; AES.KeySize = 128 ; AES.BlockSize = 128 ; AES.Mode = CipherMode.ECB ; AES.Padding = PaddingMode.Zeros ; MD5CryptoServiceProvider Hasher = new MD5CryptoServiceProvider ( ) ; AES.Key = Hasher.ComputeHash ( UTF8Encoding.UTF8.GetBytes ( key ) ) ; ICryptoTransform crypto = AES.CreateEncryptor ( AES.Key , AES.IV ) ; byte [ ] txt = UTF8Encoding.UTF8.GetBytes ( HEADER + toEncrypt ) ; byte [ ] cipherText = crypto.TransformFinalBlock ( txt , 0 , txt.Length ) ; return Convert.ToBase64String ( cipherText ) ; ; } if ( $ msg ! = `` '' & & $ key ! = `` '' ) { $ msg = parseMsg ( $ msg ) ; mcrypt_get_key_size ( MCRYPT_RIJNDAEL_128 , MCRYPT_MODE_ECB ) ; $ decrypted = mcrypt_decrypt ( MCRYPT_RIJNDAEL_128 , md5 ( $ key , true ) , base64_decode ( $ msg ) , MCRYPT_MODE_ECB ) ; $ headerLoc = strpos ( $ decrypted , $ correctHeader ) ; /* $ decrypted = str_replace ( $ correctHeader , '' '' , $ decrypted ) ; for ( $ x = 0 ; $ x < 31 ; $ x++ ) { // an attempt at getting rid of control characters $ decrypted = str_replace ( chr ( $ x ) , '' '' , $ decrypted ) ; } */ }",Character encoding problem with decryption in PHP from C # "C_sharp : I would appreciate suggestions as to how to implement the following with Ninject : I have a multi-threaded application . It runs approximately 20 very independent threads concurrently . Upon the application startup , I bind an interface to an object via Ninject by using InThreadScope ( ) and all works well . Each thread receives object specific to its thread ( constructor of each object instantiates a number of thread-specific flags ) .Most of the work that each thread does , is waiting for data-storage to finish process . So , in order to optimize the threads even further , we 've implemented Parallel.ForEach logic inside the main 20 threads . I would like for threads generated by Paralell.ForEach to get the same binding as their parent thread . However , I can not simply re-bind the interface to appropriate object inside the Parallel.ForEach , I simply do not know what the bound object is - inside Paralell.ForEach I can only work with the interface.What 's the proper way to retrieve bindings from the Kernel at runtime , before Paralell.ForEach starts and re-bind them generically inside the loop ? Edit : attempting to include detailed logic/pseudocode : Each thread once started does something like this : However , when Parallel.ForEach ( ) kicks in , from inside the individual threads , I no longer have access to Application1LoggingContext object and can not rebind the ILoggingContext to it . This is because the Parallel.ForEach ( ) is running from a base class and knows not what Application LoggingContext it needs to be bound to . That is done inside each application , upon starting of the big 20 threads.I 'd like to modify the base class , the one that spins up Parallel.ForEach ( ) and ensure inside of each newly created by Parallel.ForEach thread , that ILoggingContext is still bound to Application1LoggingContext - generically , so that I can perform the following : Kernel.Bind < ILoggingContext > ( ) .To < Application1LoggingContext > ( ) .InThreadScope ( ) ; var ctx = Kernel.Get < ILoggingContext > ( ) ;","Ninject , Parallel.ForEach and InThreadScope ( )" "C_sharp : I have a child class Bicycle that inherits from Agent . The agent has a property which depends on the bicycle to define it . Namely , the physics model for the agent needs to be initialised with the velocity and acceleration constraints which are defined on a per-bicycle-basis and would be different for another type of agent.The problem I have is that I can not pass the parameters I need to calculate ( the velocity/acceleration require calculations to draw them from a theoretical distribution ) for this in the base ( ) constructor because of course the child class has n't yet been instantiated.The calculations are done once per bicycle instance but are used multiple times so a simple static method wo n't do the job . I can just call a protected method in the parent after they 're calculated but AFAIK there 's no way to enforce this in the child , or more particularly in any future children which I might not write.So for example , I could : or I could : I 'd rather not do either of those as there 's no compile-time way to ensure that the child initialises PluginPhysics that I can think of , and I 'd rather PluginPhysics not be able to be changed once it 's been initialised . I 'd also rather not have the parts of the parameters that need to go into Physicsoutside the Bicycle class . I appreciate that all these things might not be simultaneously possible.So short of strongly worded documentation or a bunch of run-time null checks in the parent class before any of the relevant class objects are called on , is there an obvious C # -ish way I 'm missing of forcing a child to initialise a parent class field before use if you ca n't do it in the constructor ? public abstract class Agent { protected IPhysics PluginPhysics { get ; set ; } protected Agent ( ... ) { } } public class Bicycle : Agent { private double maxA ; public Bicycle ( Object anotherParameter ) : base ( ... ) { maxA = ComputationOfMaxA ( ) ; this.PluginPhysics = new Physics ( anotherParameter , maxA ) ; } private static double ComputationOfMaxA ( ) { ... } ... } public abstract class Agent { protected IPhysics PluginPhysics { get ; private set ; } protected Agent ( ... ) { } protected void SetupPhysics ( Physics physics ) { this.PluginPhysics = physics ; } } public class Bicycle : Agent { private double maxA ; public Bicycle ( Object anotherParameter ) : base ( ... ) { maxA = ComputationOfMaxA ( ) ; SetupPhysics ( new Physics ( anotherParameter , maxA ) ) ; } private static double ComputationOfMaxA ( ) { ... } ... }",Force a child class to initialise a parent property after computation "C_sharp : I 'm trying to write an extension method that will add the function HasFactor to the class int in C # . This works wonderfully , like so : This works great because variable i in the Main ( ) method above is declared as an int . However , if i is declared as an Int16 or an Int64 , the extension method does not show up unless it is explicitly cast as an int or Int32.I now would like to apply the same HasFactor method to Int16 and Int64 . However , I 'd rather not write separate extension methods for each type of int . I could write a single method for Int64 and then explicitly cast everything as an Int64 or long in order for the extension method to appear . Ideally , I 'd prefer to have the same extension method apply to all three types without having to copy and paste a lot of code.Is this even possible in C # ? If not , is there a recommended best-practice for this type of situation ? static class ExtendInt { public static bool HasFactor ( this int source , int factor ) { return ( source % factor == 0 ) ; } } class Program { static void Main ( ) { int i = 50 ; int f = 2 ; bool b = i.HasFactor ( f ) ; Console.WriteLine ( `` Is { 0 } a factor of { 1 } ? { 2 } '' , f , i , b ) ; Console.ReadLine ( ) ; } }",Is there a way to write an Extension Method that applies to multiple types ? "C_sharp : Several windows services can share one process . In C # they will start as : The call of run method blocks the thread where main ( ) executes . At the same time events of services are handled . So where are they executed ? Do they use Asynchronous Procedure Call in the `` main '' process that is not just blocked but is in alertable waiting ? If it 's so , the sharing a process for multiple services has drawback in performance . Do handlers run in separate threads ? Are they executed outside of the process containing the Run ( ) call ? ServiceBase.Run ( new MyService1 ( ) , new MyService2 ( ) ) ;",Architecture of windows services from .Net point of view "C_sharp : I have the following method for adding or updating an entity of type Item for some User . This method is a part of a Service class a new instance of which is created for each request.The problem is that two concurrent requests may create two items for the same user which is not valid . For me it looks like a pretty common piece of code and I wonder what is the default way of dealing with this kind of concurrency issue . public async Task SaveItem ( int userId , string name ) { var item = await _context.Items.Where ( i = > i.UserId == userId ) .SingleOrDefaultAsync ( ) ; if ( item == null ) { item = new Item { UserId = userId , Name = name } ; _context.Items.Add ( item ) ; } else { item.Name = name ; _context.Entry ( item ) .State = System.Data.Entity.EntityState.Modified ; } await _context.SaveChangesAsync ( ) ; }",ASP.NET Web API - Thread safe logic for updating an entity "C_sharp : I am trying to patch a .net web application that after years of working started failing to get UPS shipping quotes , which is impacting web business dramatically . After much trial and error , I found the following code that works just fine in a console application : This runs in Visual Studio just fine and gets a nice little response from UPS that the XML is , of course , malformed.But , if I paste this function into the web application without changing a single character , an exception is thrown on request.GetRequestStream ( ) : Authentication failed because the remote party has closed the transport stream . I tried it in a couple of different place in the application with the same result.What is there about the web application environment that would affect the request ? static string FindUPSPlease ( ) { string post_data = `` < xml data string > '' ; string uri = `` https : //onlinetools.ups.com/ups.app/xml/Rate '' ; HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( uri ) ; request.Method = `` POST '' ; request.KeepAlive = false ; request.ProtocolVersion = HttpVersion.Version10 ; byte [ ] postBytes = Encoding.ASCII.GetBytes ( post_data ) ; request.ContentType = `` application/x-www-form-urlencoded '' ; request.ContentLength = postBytes.Length ; Stream requestStream = request.GetRequestStream ( ) ; requestStream.Write ( postBytes , 0 , postBytes.Length ) ; requestStream.Close ( ) ; // get response and send to console HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ; Console.WriteLine ( new StreamReader ( response.GetResponseStream ( ) ) .ReadToEnd ( ) ) ; Console.WriteLine ( response.StatusCode ) ; return `` done '' ; }",https request fails only in .net web app "C_sharp : I 'm getting some behaviour which I can not understand when throwing exceptions in async methods.The following code will throw an exception immediately when calling the ThrowNow method . If I comment that line out and throw the exception directly then the exception is swallowed and not raised in the Unobserved event handler.Something a little more confusing , if I remove the async keyword from the ThrowNow method , the exception is swallowed yet again.I thought async methods run synchronously until reaching a blocking method . In this case , it seems that removing the async keyword is making it behave asynchronously . public static async void ThrowNow ( Exception ex ) { throw ex ; } public static async Task TestExAsync ( ) { ThrowNow ( new System.Exception ( `` Testing '' ) ) ; // Throws exception immediately //throw new System.Exception ( `` Testing '' ) ; // Exception is swallowed , not raised in unobserved event await Task.Delay ( 1000 ) ; } void Main ( ) { var task = TestExAsync ( ) ; }",Async method throws exception instantly but is swallowed when async keyword is removed "C_sharp : I started working with C # a few weeks ago and I 'm now in a situation where I need to build up a `` bit set '' flag to handle different cases in an algorithm . I have thus two options : Or : I could have used something as ( ( eye.X > maxCorner.X ) < < 1 ) but C # does not allow implicit casting from bool to int and the ternary operator was similar enough . My question now is : is there any performance improvement in using the first version over the second ? Thank youTommaso enum RelativePositioning { LEFT = 0 , RIGHT = 1 , BOTTOM = 2 , TOP = 3 , FRONT = 4 , BACK = 5 } pos = ( ( eye.X < minCorner.X ? 1 : 0 ) < < ( int ) RelativePositioning.LEFT ) + ( ( eye.X > maxCorner.X ? 1 : 0 ) < < ( int ) RelativePositioning.RIGHT ) + ( ( eye.Y < minCorner.Y ? 1 : 0 ) < < ( int ) RelativePositioning.BOTTOM ) + ( ( eye.Y > maxCorner.Y ? 1 : 0 ) < < ( int ) RelativePositioning.TOP ) + ( ( eye.Z < minCorner.Z ? 1 : 0 ) < < ( int ) RelativePositioning.FRONT ) + ( ( eye.Z > maxCorner.Z ? 1 : 0 ) < < ( int ) RelativePositioning.BACK ) ; enum RelativePositioning { LEFT = 1 , RIGHT = 2 , BOTTOM = 4 , TOP = 8 , FRONT = 16 , BACK = 32 } if ( eye.X < minCorner.X ) { pos += ( int ) RelativePositioning.LEFT ; } if ( eye.X > maxCorner.X ) { pos += ( int ) RelativePositioning.RIGHT ; } if ( eye.Y < minCorner.Y ) { pos += ( int ) RelativePositioning.BOTTOM ; } if ( eye.Y > maxCorner.Y ) { pos += ( int ) RelativePositioning.TOP ; } if ( eye.Z > maxCorner.Z ) { pos += ( int ) RelativePositioning.FRONT ; } if ( eye.Z < minCorner.Z ) { pos += ( int ) RelativePositioning.BACK ; }",Any significant performance improvement by using bitwise operators instead of plain int sums in C # ? "C_sharp : I just downloaded a huge JSON file with all current MTG sets/cards , and am looking to deserialize it all.I 've gotten most of each set deserialized , but I 'm running into a snag when trying to deserialize the booster object within each Set : As you can see from the above two pictures , in each booster object there is a list of strings , but for some booster objects there is also an additional array of more strings . Deserializing an array of exclusively strings is n't a problem . My issue arises when I run into those instances where there is an array of strings within the booster object that need deserializing.Currently the property I have set up to handle this deserialization is : But when I run into those cases where there 's another array within booster I get an exception thrown , where Newtonsoft.Json complains it does n't know how to handle the deserialization.So , my question then becomes : how can I go about deserializing an array of strings contained within an array of strings ? And what would an object need to look like in C # code to handle that sort of deserialization ? public IEnumerable < string > booster { get ; set ; }",Deserialize array within array "C_sharp : I making 2D game , the problem is that when the first player creates and appears in the room his camera is working normally , but when a new player enters the room , the first player sees everything through the camera of the second player . Further , if a third player connects , the first and second players see everything through the third player ’ s camera and so on.Player prefab instantiated in the GameManager class which is only on the game sceneSimple camera controllerUPD Found a solutionI moved the script of the camera controller to the player ’ s camera , and in the player ’ s instance I search for this camera , turn it on and transfer the player ’ s transform to it.Not sure about this method , but it at least works.Here is that monsterAnd Camera Controller public class GameManager : MonoBehaviourPunCallbacks { public GameObject playerPrefab ; public Transform spawnPoint ; public void Start ( ) { GameObject player = PhotonNetwork.Instantiate ( this.playerPrefab.name , spawnPoint.position , Quaternion.identity ) ; player.GetComponent < FireFighterHeroController > ( ) .enabled = true ; player.GetComponent < CameraControler > ( ) .enabled = true ; player.GetComponent < CameraControler > ( ) .SetTarget ( player.transform ) ; } # region PUN Callbacks public override void OnLeftRoom ( ) { SceneManager.LoadScene ( 1 ) ; } # endregion # region Custom Methods public void OnClickLeaveRoom_Btn ( ) { PhotonNetwork.LeaveRoom ( ) ; } # endregion } public class CameraControler : MonoBehaviour { private Transform target ; public GameObject camera ; public Vector3 offset ; public void SetTarget ( Transform target ) { this.target = target ; } public void LateUpdate ( ) { camera.transform.position = target.position + offset ; } } public class GameManager : MonoBehaviourPunCallbacks { public Transform spawnPoint ; public void Start ( ) { GameObject player = PhotonNetwork.Instantiate ( `` Player '' , spawnPoint.position , Quaternion.identity ) ; if ( ! player.GetPhotonView ( ) .IsMine ) return ; player.GetComponent < FireFighterHeroController > ( ) .enabled = true ; player.transform.Find ( `` Camera '' ) .gameObject.GetComponent < CameraControler > ( ) .enabled = true ; player.transform.Find ( `` Camera '' ) .gameObject.GetComponent < CameraControler > ( ) .SetTarget ( player.transform ) ; player.transform.Find ( `` Camera '' ) .gameObject.SetActive ( true ) ; } } public class CameraControler : MonoBehaviour { private Transform target ; public Vector3 offset ; public void SetTarget ( Transform target ) { this.target = target ; } public void LateUpdate ( ) { gameObject.transform.position = target.position + offset ; } }",How to initialize the camera for players in Photon "C_sharp : I must be missing something here.I create a brand new WPF application in VS2015 . I create a resource 'String1 ' and set the value to 'fksdlfdskfs ' . I update the default MainWindow.xaml.cs so that the constructor has : And run the application , and it works fine , my window title is fksdlfdskfs.In the AssemblyInfo.cs file I see the below comments : So I add the following into my WpfApplication5.csproj file and reload the project in VS : < UICulture > en-US < /UICulture > And then uncommented the following line in AssemblyInfo.cs : If I now go to run the application , the application no longer runs and I get the following exception on the line where I read the resource : System.Resources.MissingManifestResourceException : Could not find any resources appropriate for the specified culture or the neutral culture . Make sure `` WpfApplication5.Properties.Resources.en-US.resources '' was correctly embedded or linked into assembly `` WpfApplication5 '' at compile time , or that all the satellite assemblies required are loadable and fully signed.If I change UltimateResourceFallbackLocation.Satellite to UltimateResourceFallbackLocation.MainAssembly in the AssemblyInfo.cs file , I get the following exception instead : System.IO.IOException : Can not locate resource 'mainwindow.xaml'What am I doing wrong or what am I missing ? public MainWindow ( ) { InitializeComponent ( ) ; this.Title = Properties.Resources.String1 ; } //In order to begin building localizable applications , set // < UICulture > CultureYouAreCodingWith < /UICulture > in your .csproj file//inside a < PropertyGroup > . For example , if you are using US english//in your source files , set the < UICulture > to en-US . Then uncomment//the NeutralResourceLanguage attribute below . Update the `` en-US '' in//the line below to match the UICulture setting in the project file.// [ assembly : NeutralResourcesLanguage ( `` en-US '' , UltimateResourceFallbackLocation.Satellite ) ] [ assembly : NeutralResourcesLanguage ( `` en-US '' , UltimateResourceFallbackLocation.Satellite ) ]",Localising a WPF application does n't work ? "C_sharp : There is in operator in SQLIs there similar sintax in C # , I mean SELECT * FROM MyTable WHERE id IN ( 1 , 2 , 3 , 4 , 5 ) if ( variable in ( 1 , 2 , 3 , 4 , 5 ) ) { }",C # analog for sql in operator "C_sharp : A few days back , while writing an answer for this question here on overflow I got a bit surprised by the C # compiler , who wasn ’ t doing what I expected it to do . Look at the following to code snippets : First : Second : The only difference in code between the two snippets is the cast to ICollection < object > . Because object [ ] implements the ICollection < object > interface explicitly , I expected the two snippets to compile down to the same IL and be , therefore , identical . However , when running performance tests on them , I noticed the latter to be about 6 times as fast as the former.After comparing the IL from both snippets , I noticed the both methods were identical , except for a castclass IL instruction in the first snippet.Surprised by this I now wonder why the C # compiler isn ’ t ‘ smart ’ here . Things are never as simple as it seems , so why is the C # compiler a bit naïve here ? object [ ] array = new object [ 1 ] ; for ( int i = 0 ; i < 100000 ; i++ ) { ICollection < object > col = ( ICollection < object > ) array ; col.Contains ( null ) ; } object [ ] array = new object [ 1 ] ; for ( int i = 0 ; i < 100000 ; i++ ) { ICollection < object > col = array ; col.Contains ( null ) ; }",C # compiler doesn ’ t optimize unnecessary casts "C_sharp : Let 's say I 've defined a class MyDisposable : IDisposable . I know I can provide a hard-coded list of IDisposable objects to the using statement : Now let 's say I have a few methods that perform operations on a collection of my disposable objects , and I want to do this inside a using statement . It might look like this ( but this does n't work of course because the using block expects one or more IDisposable objects and I 'm passing a single collection object ) : Here are the other methods just for clarity : Is there some way I can accomplish this with the using statement ? Or do I do just have to throw out the statement and manually dispose ? using ( MyDisposable firstDisposable = new MyDisposable ( ) , secondDisposable = new MyDisposable ( ) ) { // do something } using ( var myDisposables = GetMyDisposables ( ) ) { foreach ( var myDisposable in myDisposables ) { DoSomething ( myDisposable ) ; DoSomethingElse ( myDisposable ) ; } } static List < MyDisposable > GetMyDisposables ( ) { throw new NotImplementedException ( ) ; // return a list of MyDisposable objects } static void DoSomething ( MyDisposable withMyDisposable ) { // something } static void DoSomethingElse ( MyDisposable withMyDisposable ) { // something else }",Is there a way to have a using statement with dynamically-created targets ? "C_sharp : I 'm writing an AIR app that launches a C # console application and they need to communicate . I 'd like to use standard input/standard output for this , however I ca n't seem to get it to work . When the C # app gets input from standard input it 's supposed to send it back via standard output , and if it receives `` exit '' then it quits . I can test this from the command line and it works correctly . When I send a string from AIR , I get no response from the C # app . I 'm sending an argument when I launch the C # app , and I do get a response from that , so my AIR app is at least able to receive messages from standard output , it 's just standard input that is not working . When I send a message from AIR via standardInput I get a progress event with bytesLoaded = 3 when I send the keycode , and bytesLoaded = 5 when I send the `` exit '' command.Here is the C # code : And here is the AS3 code : static void Main ( string [ ] args ) { if ( args.Length > 0 ) { Console.WriteLine ( args [ 0 ] ) ; } while ( true ) { string incoming = Console.ReadLine ( ) ; string outgoing = `` received : `` + incoming ; Console.WriteLine ( outgoing ) ; if ( incoming == `` exit '' ) return ; } } private function init ( e : Event=null ) : void { this.removeEventListener ( Event.ADDED_TO_STAGE , init ) ; NativeApplication.nativeApplication.addEventListener ( Event.EXITING , onAppClose ) ; var info : NativeProcessStartupInfo = new NativeProcessStartupInfo ( ) ; var file : File = File.applicationDirectory.resolvePath ( `` test.exe '' ) ; info.executable = file ; process = new NativeProcess ( ) ; info.arguments.push ( `` native process started '' ) ; process.addEventListener ( ProgressEvent.STANDARD_OUTPUT_DATA , onOutputData ) ; process.addEventListener ( ProgressEvent.STANDARD_ERROR_DATA , onErrorData ) ; process.addEventListener ( ProgressEvent.STANDARD_INPUT_PROGRESS , onInputProgress ) ; process.addEventListener ( Event.STANDARD_OUTPUT_CLOSE , onOutputClose ) ; process.addEventListener ( Event.STANDARD_ERROR_CLOSE , onErrorClose ) ; process.addEventListener ( IOErrorEvent.STANDARD_ERROR_IO_ERROR , onIOError ) ; process.addEventListener ( IOErrorEvent.STANDARD_INPUT_IO_ERROR , onIOError ) ; process.addEventListener ( IOErrorEvent.STANDARD_OUTPUT_IO_ERROR , onIOError ) ; stage.addEventListener ( KeyboardEvent.KEY_UP , onKeyUp ) ; process.start ( info ) ; } private function onKeyUp ( e : KeyboardEvent ) : void { if ( e.keyCode == Keyboard.ESCAPE ) process.standardInput.writeUTFBytes ( `` exit\n '' ) ; else { var msg : String = e.keyCode + `` \n '' ; process.standardInput.writeUTFBytes ( msg ) ; } } private function onOutputData ( e : ProgressEvent ) : void { var data : String = process.standardOutput.readUTFBytes ( process.standardOutput.bytesAvailable ) ; trace ( `` Got : `` , data ) ; }",AIR NativeProcess standardInput not connecting to app "C_sharp : After spending much time researching about this on Google , I could not come across an example of converting a Wbmp image to Png format in C # I have download some Wbmp images from the internet and I am viewing them using a Binary Editor.Does anyone have an algorithm that will assist me in doing so or any code will also help.Things I know so far : First byte is type* ( 0 for monochrome images ) Second byte is called a “ fixed-header ” and is 0Third byte is the width of the image in pixels* Fourth byte is the height of the image in pixels*Data bytes arranged in rows – one bit per pixel : Where the row length is not divisible by 8 , the row is 0-padded to the byte boundaryI am fully lost so any help will be appreciatedSome of the other code : AndProcess : Did research on Wbmp Open up X.wbmp to check details firstWork out how you find the width and height of the WBMP file ( so that you can later write the code ) . Note that the simplest way to convert a collection of length bytes ( once the MSB is cleared ) is to treat the entity as base-128 . Look at sample code I updated . I am trying to create an empty Bitmap object and set its width and height to what we worked out in ( 3 ) For every bit of data , will try and do a SetPixel on the Bitmap object created . Padded 0s when the WBMP width is not a multiple of 8.Save Bitmap using the Save ( ) method.Example usage of the application . It is assumed that the application is called Wbmp2Png . In command line : The application converts each of IMG_0001.wbmp , IMG_0002.wbmp , and IMG_0003.wbmp to PNG files . using System.Drawing ; using System.IO ; class GetPixel { public static void Main ( string [ ] args ) { foreach ( string s in args ) { if ( File.Exists ( s ) ) { var image = new Bitmap ( s ) ; Color p = image.GetPixel ( 0 , 0 ) ; System.Console.WriteLine ( `` R : { 0 } G : { 1 } B : { 2 } '' , p.R , p.G , p.B ) ; } } } } class ConfigChecker { public static void Main ( ) { string drink = `` Nothing '' ; try { System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader ( ) ; drink = ( ( string ) ( configurationAppSettings.GetValue ( `` Drink '' , typeof ( string ) ) ) ) ; } catch ( System.Exception ) { } System.Console.WriteLine ( `` Drink : `` + drink ) ; } // Main } // class ConfigChecker Wbmp2Png IMG_0001.wbmp IMG_0002.wbmp IMG_0003.wbmp",How to convert Wbmp to Png ? "C_sharp : It 's been given by Microsoft as a framework design guideline that properties should be independent of one another and not rely upon being set in any specific order . Assume you have a triangle class that needs to support dimmensions and an area calculation . How would you model this ? This is of course the design that is considered gauche because Area is dependent on Base and Height being set first : Assuming you use a constructor , you can ensure defaults for this case but is this the correct approach ? You still have a property that has a dependency on other properties . In order to be a purist I can see only a few approaches ( I guess they could be combined ) : Make Base/Height have readonly members that can only be set in the constructorMake the Area calculation into a method.Use some kind of factory pattern + readonly members to ensure that although the dependency may exist , the values can only be set by the method that instantiates the Triangle class.Questions : Is the guideline practical ( do you have to model a lot of complexity into your classes in order to support it ) ? [ for example , a SqlConnection class allows you to initialize the connection string property but lets you change individual pieces of it such as command timeout ] How do you manage keeping your properties independent of each other ? Extra for people who use Silverlight / MVVM type architecture , do you accept dependencies in properties because of the way databinding works to a object ? For example , binding a triangle instance that shows height , base and area on screen . class Triangle { public double Base { get ; set ; } public double Height { get ; set ; } public double Area { get { return ( Base * Height ) / 2 ; } } } class Triangle { public Triangle ( double b , double h ) { Base = b ; Height = h ; } public double Base { get ; set ; } public double Height { get ; set ; } public double Area { get { return ( Base * Height ) / 2 ; } } }",C # Basics Making Properties Atomic "C_sharp : I have already done research into this , and though the below questions are similar , I have tried them all , but none seems to solve my issue.Proper way of getting a data from an Access Databaseusing parameters inserting data into access databaseGetting Data from Access into a text box in C # by clicking a buttonUPDATE query on Access Database not working C # .NETpassing parameter to access query from c # Parameterized query for inserting valuesHere is the part of the code that is relevant : I have declared the following class variables accordingly : This is my current situation : The issue is , that the code within LoadDetails ( ) works just fine , and it is run upon the form loading . That code can be used again and again as of now without issues , but when I try to run the other queries , they `` fail '' . Not as in failing outright and throwing exceptions , but rather , the Parameterized Queries I am using within that area ( tagSearchButton_Click and nameSearchButton_Click ) , would n't replace the parameters . This has me confused , since it is doing what it should in LoadDetails ( ) method . If I manually changed the command text during debugging , by replacing the parameter manually with the value , then the program works as it should , and returns the values returned by using the statement . What is causing the OleDbCommand.Parameter.AddWithValue function to not work as intended ? More Details : For example , I am using this line : Therefore it would give the command this string for now : SELECT * from tagsTbl WHERE leName= ' @ name'What the Parameterized Query should be doing is to change the @ name to what is in the namesTextBox , as below : Let 's say I gave the textbox an input value of `` Jane_Smith '' . Therefore it should change the command to : SELECT * from tagsTbl WHERE leName='Jane_Smith'But it instead does nothing , so the command is still : SELECT * from tagsTbl WHERE leName= ' @ name'Other possibly relevant information : I have also just read this question , but it is not the issue I am facing . I am using Microsoft Access 2013 . I am opting to use a MS Access database for my program in view of the fact it is easier to run `` standalone '' , with the client only requiring to install a free Access Database Engine , if they do not have MS Office installed . This program works offline.Problem Solved Thanks to Rumit Parakhiya ! ( I have also learnt that MySQL query format and the OleDb query format for MS Access is different too . I was using the MySQL query format originally . ) private void LoadDetails ( int index ) { try { connection.Open ( ) ; command = new OleDbCommand ( `` SELECT * from tagsTbl WHERE ID= @ 1 '' , connection ) ; command.Parameters.AddWithValue ( `` @ 1 '' , index ) ; reader = command.ExecuteReader ( ) ; while ( reader.Read ( ) ) { nameTextBox.Text = reader [ `` leName '' ] .ToString ( ) ; altTextBox.Text = reader [ `` altName '' ] .ToString ( ) ; unitTextBox.Text = reader [ `` currUnit '' ] .ToString ( ) ; tagTextBox.Text = reader [ `` currTag '' ] .ToString ( ) ; oldTextBox.Text = reader [ `` oldTag '' ] .ToString ( ) ; descTextBox.Text = reader [ `` currDesc '' ] .ToString ( ) ; } connection.Close ( ) ; } catch { connection.Close ( ) ; MessageBox.Show ( errortxt ) ; Application.Exit ( ) ; } } private void testWin_Load ( object sender , EventArgs e ) { loadFileDialog.ShowDialog ( ) ; connection = new OleDbConnection ( strConn ) ; if ( ! blnLoaded ) Application.Exit ( ) ; else { errortxt = `` Attempt to establish connection to database failed ! `` ; LoadDetails ( testInt ) ; this.Show ( ) ; } } private void loadFileDialog_FileOk ( object sender , CancelEventArgs e ) { strConnPath = loadFileDialog.FileName ; strConn = @ '' Provider=Microsoft.ACE.OLEDB.12.0 ; Data Source= '' + strConnPath ; blnLoaded = true ; } private void prevButton_Click ( object sender , EventArgs e ) { if ( testInt > 1 ) testInt -- ; LoadDetails ( testInt ) ; gotoNumericUpDown.Value = testInt ; } private void nextButton_Click ( object sender , EventArgs e ) { testInt++ ; errortxt = `` You can not go higher than that ! `` ; try { LoadDetails ( testInt ) ; gotoNumericUpDown.Value = testInt ; } catch { testInt -- ; } } private void gotoButton_Click ( object sender , EventArgs e ) { try { testInt = ( int ) gotoNumericUpDown.Value ; LoadDetails ( testInt ) ; } catch { } } private void nameSearchButton_Click ( object sender , EventArgs e ) { try { connection.Open ( ) ; command = new OleDbCommand ( `` SELECT * from tagsTbl WHERE leName= ' @ name ' '' , connection ) ; command.CommandType = CommandType.Text ; command.Parameters.AddWithValue ( `` @ name '' , namesTextBox.Text ) ; reader = command.ExecuteReader ( ) ; while ( reader.Read ( ) ) { nameTextBox.Text = reader [ `` leName '' ] .ToString ( ) ; altTextBox.Text = reader [ `` altName '' ] .ToString ( ) ; unitTextBox.Text = reader [ `` currUnit '' ] .ToString ( ) ; tagTextBox.Text = reader [ `` currTag '' ] .ToString ( ) ; oldTextBox.Text = reader [ `` oldTag '' ] .ToString ( ) ; descTextBox.Text = reader [ `` currDesc '' ] .ToString ( ) ; } connection.Close ( ) ; } catch { connection.Close ( ) ; } } private void tagSearchButton_Click ( object sender , EventArgs e ) { try { command = new OleDbCommand ( `` SELECT * from tagsTbl WHERE currTag= ' @ 1 ' '' , connection ) ; command.Parameters.AddWithValue ( `` @ 1 '' , tagsTextBox.Text ) ; connection.Open ( ) ; MessageBox.Show ( command.CommandText ) ; reader = command.ExecuteReader ( ) ; while ( reader.Read ( ) ) { nameTextBox.Text = reader [ `` leName '' ] .ToString ( ) ; altTextBox.Text = reader [ `` altName '' ] .ToString ( ) ; unitTextBox.Text = reader [ `` currUnit '' ] .ToString ( ) ; tagTextBox.Text = reader [ `` currTag '' ] .ToString ( ) ; oldTextBox.Text = reader [ `` oldTag '' ] .ToString ( ) ; descTextBox.Text = reader [ `` currDesc '' ] .ToString ( ) ; } connection.Close ( ) ; } catch { connection.Close ( ) ; } } private string strConnPath = `` '' ; private string strConn = `` '' ; private bool blnLoaded = false ; OleDbConnection connection ; OleDbDataReader reader ; OleDbCommand command ; private string errortxt = `` '' ; int testInt = 1 ; command = new OleDbCommand ( `` SELECT * from tagsTbl WHERE leName= ' @ name ' '' , connection ) ; command.Parameters.AddWithValue ( `` @ name '' , namesTextBox.Text ) ;",C # Microsoft Access Parameterized Queries not doing its job "C_sharp : I 'm scratching my head about this as I can not understand why the following happens the way it does : What is happening with products 1 and 2 that makes them not behave like products 5 and 6 ? '//VB.NETDim product1 = New With { .Name = `` paperclips '' , .Price = 1.29 } Dim product2 = New With { .Name = `` paperclips '' , .Price = 1.29 } 'compare product1 and product2 and you get false returned.Dim product3 = New With { Key .Name = `` paperclips '' , Key .Price = 1.29 } Dim product4 = New With { Key .Name = `` paperclips '' , Key .Price = 1.29 } 'compare product3 and product4 and you get true returned . '//C # var product5 = new { Name = `` paperclips '' , Price = 1.29 } ; var product6 = new { Name = `` paperclips '' , Price = 1.29 } ; //compare products 5 and 6 and you get true .",How do VB.NET anonymous types without key fields differ from C # anonymous types when compared ? "C_sharp : I have a many-to-many relationship between Agents and AgentGroups ( psuedocode , abbreviated ) .At some point in the code , I want to get all AgentGroups , and I want to prefetch/include the Agents for each group . I also want to pre-fill the AgentGroups collection on the Agents . This was working in EF 6 beta , but no longer works in EF 6 rc1 : The error message I get is Invalid object name 'dbo.AgentAgentGroups'.And in fact , there is n't a table AgentAgentGroups , the table is dbo.AgentGroupAgents . Any ideas on getting this to work again ? I currently have no annotations and am not using the fluent API , it 's all strictly the default code first conventions . public class Agent { public virtual List < AgentGroup > AgentGroups { get ; set ; } } public class AgentGroup { public virtual List < Agent > Agents { get ; set ; } } List < AgentGroup > allGroups = context.AgentGroups.Include ( `` Agents '' ) .Include ( `` Agents.AgentGroups '' ) .ToList ( ) ;",EntityFramework 6 RC1 Include on Many-to-Many property fails "C_sharp : 1 ) into keyword creates temporary identifier for storing results of join , group or select clauses.I assume into keyword can only be used as part of group , join or select clauses ? 2 ) a ) I 've read that when into is used as a part of group or select clauses , it splices the query in two halves and because of that range variables declared in first half of the query ALWAYS go out of scope in the second half of the query . Correct ? b ) But when into is used as part of the join clause , rangle variables NEVER go out of the scope within the query ( unless query also contains group ... into or select ... into ) . I assume this is due to into not splicing the query in two halves when used with join clause ? c ) A query expression consists of a from clause followed by optional query body ( from , where , let clauses ) and must end with either select of group clause . d ) If into indeed splices query into two halves , is in the following example group clause part of the body : thank youReply to Ufuk : a ) After a group by you get a sequence of like this IEnumerable > Does n't a GroupBy operator return a result of type IEnumerable < IGrouping < Key , Foo > > and not IEnumerable < Key , IEnumerable < Foo > > b ) Could n't we arguee that group ... by ... into or join ... into do splice the query in a sense that first half of the query at least conceptually must run before the second half of the query can run ? Reply to Robotsushi : the more I 'm thinking about it , the more I get the feeling that my question is pretty pointless since it has no practical value what so ever . Still ... When you say it gets split . Do you mean the scope of the variables gets split or the sql query generated gets splitHere is the quote : In many cases the range variables on one side of this divide can not be mixed with the range variables on the other side . The into keyword that is part of this group-by clause is used to link or splice the two halves of this query . As such , it marks the boundary in the midst of the query over which range variables typically can not climb . The range variables above the into keyword go out of scope in the last part of this query.My question is whether both halves are still considered a single query and as such the entire query still consists of just three parts . If that is the case , then in my code example ( under d ) ) group clause is part of the body . But if both halves are considered two queries , then each of the two queries will consist of three parts2 . reply to Robotsushi : This chunk of your query is evaluated as one data pull.I 'm not familiar with the term `` data pull '' , so I 'm going to guess that what you were trying to say is that first half of the query executes/evaluates as a unit , and then second half of the query takes the results from the first half and uses the results in its execution/evaluation ? In other words , conceptually we have two queries ? var result = from c1 in a1 group c1 by c1.name into GroupResult select ...",Having some trouble understanding Linq 's INTO keyword "C_sharp : I was just messing around to answer someone 's question here on Stack Overflow , when I noticed a static verification warning from inside my Visual Studio ( 2008 ) : I 'm getting the message requires unproven source ! = null . It seems pretty obvious to me that this is not the case . This is just one example of course . On the other side , some pretty nifty stuff seems to be working fairly well.I 'm using the 1.2.20518.12 release ( May 18th ) . I find code contracts very interesting , but has anyone else had cases like this ? Do you consider the current implementation usable in practice , or would you consider them purely academic at this point ? I 've made this a community wiki , but I 'd like to hear some opinions : ) string [ ] source = { `` 1 '' , `` A '' , `` B '' } ; var sourceObjects = Array.ConvertAll ( source , c = > new Source ( c ) ) .ToArray ( ) ;",.NET code contracts : can it get more basic than this ? "C_sharp : Consider the following serializable classes : I want the serialized output to look like : Notice the element names ItemValues and ItemValue does n't match the class names Item and Items , assuming I ca n't change the Item or Items class , is there any why to specify the element names I want , by modifying the MyClass Class ? class Item { ... } class Items : List < Item > { ... } class MyClass { public string Name { get ; set ; } public Items MyItems { get ; set ; } } < MyClass > < Name > string < /Name > < ItemValues > < ItemValue > < /ItemValue > < ItemValue > < /ItemValue > < ItemValue > < /ItemValue > < /ItemValues > < /MyClass >",.net XML serialization : how to specify an array 's root element and child element names "C_sharp : Which static class initializes first if we have one more static classes in our project ? For example : Below code gives null exception.If you pay attention , you will see that if First class will initialize itself so secondArray field of Second would be null . But if Second class would initialize first so Second class firstArray would be null . I am trying to tell that which initialize first makes different results.I think that it is abstract question about my project . I encounter it while trying to understand why I am getting unexpected results . class Program { static void Main ( string [ ] args ) { First.Write ( ) ; Second.Write ( ) ; } } static class First { public static int [ ] firstArray = new int [ 20 ] ; public static int [ ] secondArray = Second.secondArray ; public static void Write ( ) { Console.WriteLine ( firstArray.ToString ( ) ) ; Console.WriteLine ( secondArray.ToString ( ) ) ; } } static class Second { public static int [ ] firstArray = First.firstArray ; public static int [ ] secondArray = new int [ 30 ] ; public static void Write ( ) { Console.WriteLine ( firstArray.ToString ( ) ) ; Console.WriteLine ( secondArray.ToString ( ) ) ; } }",Which static class initializes first ? "C_sharp : In most examples that you find on the web when explicitly not using `` using '' , the pattern looks something like : If you do use `` using '' and look at the generated IL code , you can see that it generates the check for nullI understand why the IL gets translated to check for null ( does n't know what you did inside the using block ) , but if you 're using try..finally and you have full control of how the IDisposable object gets used inside the try..finally block , do you really need to check for null ? if so , why ? SqlConnection c = new SqlConnection ( @ '' ... '' ) ; try { c.Open ( ) ; ... } finally { if ( c ! = null ) // < == check for null c.Dispose ( ) ; } L_0024 : ldloc.1 L_0025 : ldnull L_0026 : ceq L_0028 : stloc.s CS $ 4 $ 0000L_002a : ldloc.s CS $ 4 $ 0000L_002c : brtrue.s L_0035L_002e : ldloc.1 L_002f : callvirt instance void [ mscorlib ] System.IDisposable : :Dispose ( ) L_0034 : nop L_0035 : endfinally",IDisposable : is it necessary to check for null on finally { } ? "C_sharp : Does Enumerable.Concat always append at the end of the first collection ? Example : Is it guaranteed that the item will be int not float after Concat on every use ? That means : The MSDN says nothing about element order in resulting collection , however examples show that the order is elements from first collection then elements from second collection . object someObject = new object ( ) ; List < object > listA = new List < object > ( ) ; listA.Add ( new int ( ) ) ; object item = listA.Concat ( new object [ ] { ( object ) new float ( ) } ) .FirstOrDefault ( ) ; [ 0 ] int [ 1 ] float",Does Enumerable.Concat always append at the end of the first collection ? "C_sharp : So Resharper is putting a line break before the `` new '' in my code when re-formatting it as follows : But I 'd really like it too do this : I 've delved though all the settings I have in my .DotSettings file ( s ) and I ca n't work out what is causing it ... Any help would be most appreciated : ) EDIT 2 ( UPDATED ) Here are the R # settings that seem to be getting me close to what I have listed , you 'll still see the new line after then equals sign ( with the listed configuration ) unless you select `` chop always '' for `` wrap invocation arguments '' and `` wrap object and collection initializer '' ( as suggested by Kristian ) .The problem with `` chop always '' is that you 'll have really short method calls and object/collection initializers also chopping all the time , which looks bad , so I think what we want is : Do n't put a new line after the equals sign for method calls / object/collection initializers ( but I ca n't find that setting anywhere , so it could be a bug or feature of R # ) .I 'll try to raise it on the R # forums / support and report back my findings . var foo = new Foo { Bar = null , Baz = new Baz { Bap = null , Bork = null , Help = new PweaseHelp { Korben = null , Dallas = null , Multipass = null } , Me = new ClearlyMyAbilityToUnderstandResharperSettingsIs ( null ) , } } ; var foo = new Foo { Bar = null , Baz = new Baz { Bap = null , Bork = null , Help = new PweaseHelp { Korben = null , Dallas = null , Multipass = null } , Me = new ClearlyMyAbilityToUnderstandResharperSettingsIs ( null ) , } } ; < s : Boolean x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_ARRAY_AND_OBJECT_INITIALIZER/ @ EntryValue '' > False < /s : Boolean > < s : String x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/ANONYMOUS_METHOD_DECLARATION_BRACES/ @ EntryValue '' > NEXT_LINE < /s : String > < s : String x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/CASE_BLOCK_BRACES/ @ EntryValue '' > NEXT_LINE < /s : String > < s : Int64 x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/CONTINUOUS_INDENT_MULTIPLIER/ @ EntryValue '' > 1 < /s : Int64 > < s : String x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/EMPTY_BLOCK_STYLE/ @ EntryValue '' > TOGETHER_SAME_LINE < /s : String > < s : Boolean x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_ANONYMOUS_METHOD_BLOCK/ @ EntryValue '' > True < /s : Boolean > < s : String x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/INITIALIZER_BRACES/ @ EntryValue '' > NEXT_LINE < /s : String > < s : Int64 x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_CODE/ @ EntryValue '' > 1 < /s : Int64 > < s : Int64 x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_DECLARATIONS/ @ EntryValue '' > 1 < /s : Int64 > < s : Boolean x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/LINE_FEED_AT_FILE_END/ @ EntryValue '' > True < /s : Boolean > < s : Boolean x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AFTER_TYPECAST_PARENTHESES/ @ EntryValue '' > False < /s : Boolean > < s : Boolean x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_BEFORE_TRAILING_COMMENT/ @ EntryValue '' > True < /s : Boolean > < s : Boolean x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_WITHIN_SINGLE_LINE_ARRAY_INITIALIZER_BRACES/ @ EntryValue '' > True < /s : Boolean > < s : String x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_ARGUMENTS_STYLE/ @ EntryValue '' > CHOP_IF_LONG < /s : String > < s : Int64 x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LIMIT/ @ EntryValue '' > 150 < /s : Int64 > < s : String x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_OBJECT_AND_COLLECTION_INITIALIZER_STYLE/ @ EntryValue '' > CHOP_IF_LONG < /s : String > < s : String x : Key= '' /Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_PARAMETERS_STYLE/ @ EntryValue '' > CHOP_IF_LONG < /s : String >",Resharper C # Formatting Style shows `` new '' on new line instead of same line when chopping long lines "C_sharp : I 've run into a compiler error when attempting to implement an interface twice for the same class like so : The error : 'Mapper ' can not implement both 'IMapper ' and 'IMapper ' because they may unify for some type parameter substitutions.Why does this workaround work ? I 'm wondering if I 've solved the problem or just tricked the compiler.EDIT : I 've updated MyClass , MyClassBase , and IMyInterface to Mapper , MapperBase , and IMapper to represent a more real-world scenario where this issue may present itself . public class Mapper < T1 , T2 > : IMapper < T1 , T2 > , IMapper < T2 , T1 > { /* implementation for IMapper < T1 , T2 > here . */ /* implementation for IMapper < T2 , T1 > here . */ } public class Mapper < T1 , T2 > : MapperBase < T1 , T2 > , IMapper < T1 , T2 > { /* implementation for IMapper < T1 , T2 > here . */ } public class MapperBase < T1 , T2 > : IMapper < T2 , T1 > { /* implementation for IMapper < T2 , T1 > here . */ }",Interface implemented twice `` types may unify '' ; why does this workaround work ? "C_sharp : Reading this blog post it mentions you can get your DI container to automatically subscribe to events if it implements IHandle < > . That is exactly what I 'm trying to accomplish.Here is what I have so far.While this code is successfully subscribing MainWindowViewModel to receive published messages , come time to actually receive messages nothing happens . If I manually subscribe all works as expected.Here is my MainWindowViewModel class.How can I tell Windsor to automatically subscribe if any class inherits IHandle < > ? I ended up coming up with this custom facility that subscribes.Looking at the EventAggregator class provided by Caliburn.Micro I 'm able to see that the subcription is successful , however if another class publishes a message the MainWindowViewModel class is n't getting getting handled . Manually subscribing still works but I 'd like to automate this process . I have a feeling that it 's not subscribing the correct instance . Not sure how to fix that , though.I 've also tried using every other event exposed by the Kernel property . Most of them ca n't resolve IEventAggregator.What am I missing ? container.Register ( Component .For < MainWindowViewModel > ( ) .ImplementedBy < MainWindowViewModel > ( ) .LifeStyle.Transient .OnCreate ( ( kernel , thisType ) = > kernel.Resolve < IEventAggregator > ( ) .Subscribe ( thisType ) ) ) ; public class MainWindowViewModel : IHandle < SomeMessage > { private readonly FooViewModel _fooViewModel ; private readonly IEventAggregator _eventAggregator ; public MainWindowViewModel ( FooViewModel fooViewModel , IEventAggregator eventAggregator ) { _fooViewModel = fooViewModel ; _eventAggregator = eventAggregator ; //_eventAggregator.Subscribe ( this ) ; _fooViewModel.InvokeEvent ( ) ; } public void Handle ( SomeMessage message ) { Console.WriteLine ( `` Received message with text : { 0 } '' , message.Text ) ; } } public class EventAggregatorFacility : AbstractFacility { protected override void Init ( ) { Kernel.DependencyResolving += Kernel_DependencyResolving ; } private void Kernel_DependencyResolving ( ComponentModel client , DependencyModel model , object dependency ) { if ( typeof ( IHandle ) .IsAssignableFrom ( client.Implementation ) ) { var aggregator = Kernel.Resolve < IEventAggregator > ( ) ; aggregator.Subscribe ( client.Implementation ) ; } } }",Using Windsor to automatically subscribe to event aggregator with custom facility "C_sharp : Consider the following async method that I 'm going to wait synchronously . Wait a second , I know . I know that it 's considered bad practice and causes deadlocks , but I 'm fully conscious of that and taking measures to prevent deadlocks via wrapping code with Task.Run.This code will definitely deadlock ( in environments with SyncronizationContext that schedules tasks on a single thread like ASP.NET ) if called like that : BadAssAsync ( ) .Result.The problem I face is that even with this `` safe '' wrapper it still occasionally deadlocks.These `` WriteInfo '' lines there in purpose . These debug lines allowed me to see that the reason why it occasionally happens is that the code within Task.Run , by some mystery , is executed by the very same thread that started serving request . It means that is has AspNetSynchronizationContext as SyncronizationContext and will definitely deadlock.Here is debug output : Notice as code within Task.Run ( ) continues on the very same thread with TID=48.The question is why is this happening ? Why Task.Run runs code on the very same thread allowing SyncronizationContext to still have an effect ? Here is the full sample code of WebAPI controller : https : //pastebin.com/44RP34Ye and full sample code here.UPDATE . Here is the shorter Console Application code sample that reproduces root cause of the issue -- scheduling Task.Run delegate on the calling thread that waits . How is that possible ? private async Task < string > BadAssAsync ( ) { HttpClient client = new HttpClient ( ) ; WriteInfo ( `` BEFORE AWAIT '' ) ; var response = await client.GetAsync ( `` http : //google.com '' ) ; WriteInfo ( `` AFTER AWAIT '' ) ; string content = await response.Content.ReadAsStringAsync ( ) ; WriteInfo ( `` AFTER SECOND AWAIT '' ) ; return content ; } private T Wait1 < T > ( Func < Task < T > > taskGen ) { return Task.Run ( ( ) = > { WriteInfo ( `` RUN '' ) ; var task = taskGen ( ) ; return task.Result ; } ) .Result ; } *** ( worked fine ) START : TID : 17 ; SCTX : System.Web.AspNetSynchronizationContext ; SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerRUN : TID : 45 ; SCTX : & ltnull > SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerBEFORE AWAIT : TID : 45 ; SCTX : & ltnull > SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerAFTER AWAIT : TID : 37 ; SCTX : & ltnull > SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerAFTER SECOND AWAIT : TID : 37 ; SCTX : & ltnull > SCHEDULER : System.Threading.Tasks.ThreadPoolTaskScheduler*** ( deadlocked ) START : TID : 48 ; SCTX : System.Web.AspNetSynchronizationContext ; SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerRUN : TID : 48 ; SCTX : System.Web.AspNetSynchronizationContext ; SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerBEFORE AWAIT : TID : 48 ; SCTX : System.Web.AspNetSynchronizationContext ; SCHEDULER : System.Threading.Tasks.ThreadPoolTaskScheduler static void Main ( string [ ] args ) { WriteInfo ( `` \n***\nBASE '' ) ; var t1 = Task.Run ( ( ) = > { WriteInfo ( `` T1 '' ) ; Task t2 = Task.Run ( ( ) = > { WriteInfo ( `` T2 '' ) ; } ) ; t2.Wait ( ) ; } ) ; t1.Wait ( ) ; } BASE : TID : 1 ; SCTX : & ltnull > SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerT1 : TID : 3 ; SCTX : & ltnull > SCHEDULER : System.Threading.Tasks.ThreadPoolTaskSchedulerT2 : TID : 3 ; SCTX : & ltnull > SCHEDULER : System.Threading.Tasks.ThreadPoolTaskScheduler",Task.Run continues on the same thread causing deadlock "C_sharp : I 'm trying to use WCF client to connect to Java based web servicesCertificates I have been provided ( self-signed ) work perfectly in SOAPUI . Here is my setup : However , I 'm having problems using WCF client . My app.configUsing Keystore Explorer I export both certificates from JKS as : public_test_hci_cert.cer test_soap_ui.p12Web service call : The request arrives perfectly at the server but it seems that WCF does n't understand the response since I get this exception : Service Trace gives : UPDATE1 : simplified the task by using the same certificate for signing and encryption . Same message . UPDATE2 : I wrote CustomTextMessageEncoder where I manually decrypt the message body and it works . However returning it in ReadMessage still throws the error . < bindings > < customBinding > < binding name= '' Example_TestBinding '' > < security defaultAlgorithmSuite= '' TripleDesRsa15 '' authenticationMode= '' MutualCertificate '' requireDerivedKeys= '' false '' includeTimestamp= '' false '' messageProtectionOrder= '' SignBeforeEncrypt '' messageSecurityVersion= '' WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 '' requireSignatureConfirmation= '' false '' > < localClientSettings detectReplays= '' true '' / > < localServiceSettings detectReplays= '' true '' / > < /security > < textMessageEncoding messageVersion= '' Soap11 '' / > < httpsTransport authenticationScheme= '' Basic '' manualAddressing= '' false '' maxReceivedMessageSize= '' 524288000 '' transferMode= '' Buffered '' / > < /binding > < /customBinding > < /bindings > < client > < endpoint address= '' https : //blabla.hana.ondemand.com/Example_Test '' binding= '' customBinding '' bindingConfiguration= '' Example_TestBinding '' contract= '' WebServiceTest.Example_Test '' name= '' Example_Test '' / > < /client > var client = new Example_TestClient ( ) ; client.ClientCredentials.UserName.UserName = `` user '' ; client.ClientCredentials.UserName.Password = `` pass '' ; X509Certificate2 certClient = new X509Certificate2 ( certClientPath , certClientPassword ) ; client.ClientCredentials.ClientCertificate.Certificate = certClient ; X509Certificate2 certService= new X509Certificate2 ( certServicePath ) ; client.ClientCredentials.ServiceCertificate.DefaultCertificate = certService ; var response = client.Example_Test ( requestObj ) ; `` The EncryptedKey clause was not wrapped with the required encryption token 'System.IdentityModel.Tokens.X509SecurityToken ' . '' at System.ServiceModel.Security.WSSecurityJan2004.WrappedKeyTokenEntry.CreateWrappedKeyToken ( String id , String encryptionMethod , String carriedKeyName , SecurityKeyIdentifier unwrappingTokenIdentifier , Byte [ ] wrappedKey , SecurityTokenResolver tokenResolver ) \r\n ... The security protocol can not verify the incoming message public override Message ReadMessage ( ArraySegment < byte > buffer , BufferManager bufferManager , string contentType ) { var msgContents = new byte [ buffer.Count ] ; Array.Copy ( buffer.Array , buffer.Offset , msgContents , 0 , msgContents.Length ) ; bufferManager.ReturnBuffer ( buffer.Array ) ; var message = Encoding.UTF8.GetString ( msgContents ) ; //return ReadMessage ( Decryptor.DecryptBody ( message ) , int.MaxValue ) ; var stream = new MemoryStream ( Encoding.UTF8.GetBytes ( message ) ) ; return ReadMessage ( stream , int.MaxValue ) ; } public static MemoryStream DecryptBody ( string xmlResponse ) { X509Certificate2 cert = new X509Certificate2 ( clientCertPath , certPass ) ; SymmetricAlgorithm algorithm = new TripleDESCryptoServiceProvider ( ) ; XmlDocument xmlDoc = new XmlDocument ( ) ; xmlDoc.PreserveWhitespace = true ; xmlDoc.LoadXml ( xmlResponse ) ; XmlElement encryptedKeyElement = xmlDoc.GetElementsByTagName ( `` EncryptedKey '' , XmlEncryptionStrings.Namespace ) [ 0 ] as XmlElement ; XmlElement keyCipherValueElement = encryptedKeyElement.GetElementsByTagName ( `` CipherValue '' , XmlEncryptionStrings.Namespace ) [ 0 ] as XmlElement ; XmlElement encryptedElement = xmlDoc.GetElementsByTagName ( `` EncryptedData '' , XmlEncryptionStrings.Namespace ) [ 0 ] as XmlElement ; var key = Convert.FromBase64String ( keyCipherValueElement.InnerText ) ; EncryptedData edElement = new EncryptedData ( ) ; edElement.LoadXml ( encryptedElement ) ; EncryptedXml exml = new EncryptedXml ( ) ; algorithm.Key = ( cert.PrivateKey as RSACryptoServiceProvider ) .Decrypt ( key , false ) ; byte [ ] rgbOutput = exml.DecryptData ( edElement , algorithm ) ; exml.ReplaceData ( encryptedElement , rgbOutput ) ; //var body = Encoding.UTF8.GetString ( rgbOutput ) ; MemoryStream ms = new MemoryStream ( ) ; xmlDoc.Save ( ms ) ; return ms ; }",WCF : The EncryptedKey clause was not wrapped with the required encryption token 'System.IdentityModel.Tokens.X509SecurityToken ' "C_sharp : PrefaceFor some time now I 've been using the readonly modifier for nearly all class fields . I use it for List < T > members , IDisposeable members , ints , strings , etc ... everything but value types I intend to change . I tend to do this even when I would normally like to null a member on Dispose ( ) . IMHO The advantages of not needing the if statements to test for null or disposed conditions greatly outweigh the 'potential ' for trouble in objects that 'could ' be disposed multiple times . The QuestionWhen do you use readonly , or do you ? Do you or your company have any best-practices and/or coding standards regarding the use of readonly ? I 'm curious to hear your thoughts on the following sample class , is the general concept a good practice or not ? class FileReaderWriter : IFileReaderWriter , IDisposable { private readonly string _file ; private readonly Stream _io ; public FileReaderWriter ( string path ) { _io = File.Open ( _file = Check.NotEmpty ( path ) , FileMode.OpenOrCreate , FileAccess.ReadWrite , FileShare.None ) ; } public void Dispose ( ) { _io.Dispose ( ) ; } ... }",Thoughts on the use of readonly for any/all instance members of a class ? "C_sharp : I develop a web application with ASP.NET MVC . I have problem with route.I need a route like this.http : //localhost/content-name/23.htmlI 've defined a route for this as followsBut the route does n't work . IIS is showing me 404 page . When i remove .html extension so the route works . How can i solve this ? Thank you //i need this route but it 's not workroutes.MapRoute ( `` GetContent '' , '' { sefLink } / { contentId } .html '' , new { controller = `` Content '' , action = `` GetContent '' } , new [ ] { `` CanEcomm.Controllers '' } ) ; //this route is working . i just remove `` .html '' extensionroutes.MapRoute ( `` GetContent '' , `` { sefLink } / { contentId } '' , new { controller = `` Content '' , action = `` GetContent '' } , new [ ] { `` CanEcomm.Controllers '' } ) ;",ASP.NET MVC Route Does n't Work With .html Extension "C_sharp : I have a Windows Phone 8 App , which uses Background agent to : Get data from internet ; Generate image based on a User Control that uses the data from step 1 as data source ; In the User Control I have Grid & StackPanel & some Text and Image controls ; When some of the Images use local resources from the installation folder ( /Assets/images/ ... ) One of them which I used as a background is selected by user from the phone 's photo library , so I have to set the source using C # code behind.However , when it runs under the background , it get the OutOfMemoryException , some troubleshooting so far : When I run the process in the `` front '' , everything works fine ; If I comment out the update progress , and create the image directly , it also works fine ; If I do n't set the background image , it also works fine ; The OutOfMemoryException was thrown out during var bmp = new WriteableBitmap ( 480 , 800 ) ; I already shrink the image size from 1280*768 to 800*480 , I think it is the bottom line for a full screen background image , is n't it ? After some research , I found out this problem occurs because it exceeded the 11 MB limitation for a Periodic Task.I tried use the DeviceStatus.ApplicationCurrentMemoryUsage to track the memory usage: -- the limitation is 11,534,336 ( bit ) -- when background agent started , even without any task in it , the memory usage turns to be 4,648,960 -- When get update from internet , it grew up to 5,079,040 -- when finished , it dropped back to 4,648,960 -- When the invoke started ( to generate image from the User Control ) , it grew up to 8,499,200Well , I guess that 's the problem , there is little memory available for it to render the image via WriteableBitmap.Any idea how to work out this problem ? Is there a better method to generate an image from a User Control / or anything else ? Actually the original image might only be 100 kb or around , however , when rendering by WriteableBitmap , the file size ( as well as the required memory size I guess ) might grew up to 1-2MB.Or can I release the memory from anywhere ? ==============================================================BTW , when this Code Project article says I can use only 11MB memory in a Periodic Task ; However , this MSDN article says that I can use up to 20 MB or 25MB with Windows Phone 8 Update 3 ; Which is correct ? And why am I in the first situation ? ==============================================================Edit : Speak of the debugger , it also stated in the MSDN article : When running under the debugger , memory and timeout restrictions are suspended.But why would I still hit the limitation ? ==============================================================Edit : Well , I found something seems to be helpful , I will check on them for now , suggestions are still welcome.http : //writeablebitmapex.codeplex.com/http : //suchan.cz/2012/07/pro-live-tiles-for-windows-phone/http : //notebookheavy.com/2011/12/06/microsoft-style-dynamic-tiles-for-windows-phone-mango/==============================================================The code to generate the image : The XAML code for the ImageUserControl : The C # code behind the ImageUserControl : When DataInfo is another Class within the settings page that hold data get from the internet : Deployment.Current.Dispatcher.BeginInvoke ( ( ) = > { var customBG = new ImageUserControl ( ) ; customBG.Measure ( new Size ( 480 , 800 ) ) ; var bmp = new WriteableBitmap ( 480 , 800 ) ; //Thrown the **OutOfMemoryException** bmp.Render ( customBG , null ) ; bmp.Invalidate ( ) ; using ( var isf = IsolatedStorageFile.GetUserStoreForApplication ( ) ) { filename = `` /Shared/NewBackGround.jpg '' ; using ( var stream = isf.OpenFile ( filename , System.IO.FileMode.OpenOrCreate ) ) { bmp.SaveJpeg ( stream , 480 , 800 , 0 , 100 ) ; } } } < UserControl blabla ... d : DesignHeight= '' 800 '' d : DesignWidth= '' 480 '' > < Grid x : Name= '' LayoutRoot '' > < Image x : Name= '' nBackgroundSource '' Stretch= '' UniformToFill '' / > //blabla ... < /Grid > < /UserControl > public ImageUserControl ( ) { InitializeComponent ( ) ; LupdateUI ( ) ; } public void LupdateUI ( ) { DataInfo _dataInfo = new DataInfo ( ) ; LayoutRoot.DataContext = _dataInfo ; try { using ( var isoStore = IsolatedStorageFile.GetUserStoreForApplication ( ) ) { using ( var isoFileStream = isoStore.OpenFile ( `` /Shared/BackgroundImage.jpg '' , FileMode.Open , FileAccess.Read ) ) { BitmapImage bi = new BitmapImage ( ) ; bi.SetSource ( isoFileStream ) ; nBackgroundSource.Source = bi ; } } } catch ( Exception ) { } } public class DataInfo { public string Wind1 { get { return GetValueOrDefault < string > ( `` Wind1 '' , `` N/A '' ) ; } set { if ( AddOrUpdateValue ( `` Wind1 '' , value ) ) { Save ( ) ; } } } public string Wind2 { get { return GetValueOrDefault < string > ( `` Wind2 '' , `` N/A '' ) ; } set { if ( AddOrUpdateValue ( `` Wind2 '' , value ) ) { Save ( ) ; } } } //blabla ... }",OutOfMemoryException @ WriteableBitmap @ background agent "C_sharp : I 'm querying Sharepoint server-side and getting back results as Xml . I want to slim down the Xml into something more lightweight before sending it to jQuery through a WebMethod.However my XPath query is n't working . I thought the following code would return all Document nodes , but it returns nothing . I 've used XPath a little before , I thought //Document do the trick.C # XPath queryXML being queried XmlDocument xmlResults = new XmlDocument ( ) ; xmlResults.LoadXml ( xml ) ; // XML is a string containing the XML source shown belowXmlNodeList results = xmlResults.SelectNodes ( `` //Document '' ) ; < ResponsePacket xmlns= '' urn : Microsoft.Search.Response '' > < Response domain= '' QDomain '' > < Range > < StartAt > 1 < /StartAt > < Count > 2 < /Count > < TotalAvailable > 2 < /TotalAvailable > < Results > < Document relevance= '' 126 '' xmlns= '' urn : Microsoft.Search.Response.Document '' > < Title > Example 1.doc < /Title > < Action > < LinkUrl size= '' 32256 '' fileExt= '' doc '' > http : //hqiis99/Mercury/Mercury documents/Example 1.doc < /LinkUrl > < /Action > < Description / > < Date > 2010-08-19T14:44:56+01:00 < /Date > < /Document > < Document relevance= '' 31 '' xmlns= '' urn : Microsoft.Search.Response.Document '' > < Title > Mercury documents < /Title > < Action > < LinkUrl size= '' 0 '' fileExt= '' aspx '' > http : //hqiis99/mercury/Mercury documents/Forms/AllItems.aspx < /LinkUrl > < /Action > < Description / > < Date > 2010-08-19T14:49:39+01:00 < /Date > < /Document > < /Results > < /Range > < Status > SUCCESS < /Status > < /Response > < /ResponsePacket >",Why does n't this XPath query returns any nodes ? "C_sharp : I always use If statement ( In C # ) as ( 1 . Alternative ) ; I know that there is no need to write `` == true '' as ( 2 . Alternative ) ) ; But , I use it because it is more readable and cause no performance issue . Of course , this is my choice and I know many software developers prefer first alternative . What is the best usage , and Why ? if ( IsSuccessed == true ) { // } if ( IsSuccessed ) { // }",Confusing If Statement ? "C_sharp : What 's the most efficient way to write a method that will compare n lists and return all the values that do not appear in all lists , so thatso that lists.GetNonShared ( ) ; returns 1 , 5 , 8 , 9 , 10I had But I was n't sure if that was efficient . Order does not matter . Thanks ! var lists = new List < List < int > > { new List < int > { 1 , 2 , 3 , 4 } , new List < int > { 2 , 3 , 4 , 5 , 8 } , new List < int > { 2 , 3 , 4 , 5 , 9 , 9 } , new List < int > { 2 , 3 , 3 , 4 , 9 , 10 } } ; public IEnumerable < T > GetNonShared ( this IEnumerable < IEnumerable < T > > lists ) { // ... fast algorithm here } public IEnumerable < T > GetNonShared ( this IEnumerable < IEnumerable < T > > lists ) { return list.SelectMany ( item = > item ) .Except ( lists.Aggregate ( ( a , b ) = > a.Intersect ( b ) ) ; }",Linq get values not shared across multiple lists "C_sharp : I have the following classA photo can have multiple Tags associated with it , and the same Tag can be used in any number of different Photos.What I ultimately want to do is to retrieve a list of distinct tags , with a count of how many photos are assigned to each tag.I have no control over the underlying data - I am using an API which has a Search method that I 'm using to retrieve a collection of Photos , but there is no method to get a list of distinct tags.So my question is , if I have a large collection of Photos , how can I use LINQ to get a distinct list of the tags contained within this list , and get the count ( of photos ) for each of those tags ? public class Photo { public int Id { get ; set ; } public string Caption { get ; set ; } public Collection < string > Tags { get ; set ; } }",LINQ distinct with corresponding counts based on a List property "C_sharp : I 've got the following code that does not produce an CA1804 warning ( declared variable is never used ) from code analysis ( VS2010 Premium ) : When I remove the ErrorProvider.SetError ( ... ) lines , the CA1804 warning is shown , but why is this not the case in the code sample above ? ( Btw : The code itself is not too great and just shown to illustrate my question . ) Any ideas what might be causing this behaviour ? I guess this might be down to the fact that the IL code is optimised in a way that puts the declaration outside the if , which in turn would mean that the warning should indeed not show up in an example like the one above , but I 'm not sure whether this is true.Thanks in advanceG . ... if ( boolVariable ) { string errorText = `` Bla Bla Bla '' ; // Never used ErrorProvider.SetError ( SomeControl , `` Some Warning '' ) ; } else { string errorText = `` Acme Acme Acme '' ; // Used below ErrorProvider.SetError ( SomeControl , errorText ) ; } ...",Code Analysis does not show CA1804 warning despite unused local string variable in C # ( VS2010 Premium ) "C_sharp : is it possible to do something like the following : so that if somebody tried to do this , struct test { this { get { /*do something*/ } set { /*do something*/ } } } test tt = new test ( ) ; string asd = tt ; // intercept this and then return something else",Can I create accessors on structs to automatically convert to/from other datatypes ? "C_sharp : I 've got a number of classes which implement IDessertPlugin . These are found in various DLLs which I use MEF to spin up instances of them to use as plug-in functionality in my application.So what I 'm wanting to do is display the version number of the DLLs from which I 've loaded plugins using MEF . One or more plugins are defined in one or more DLLs which I load up in my application.Right now I do something like so : And that will load up plugins just fine from the Plugins subdirectory where my application runs.Doing something like just returns `` System.ComponentModel.Composition , Version=4.0.0.0 , ... '' What I was hoping to be able to know was that I 've got Version 1.0 of CakePlugins.dll and Version 1.1 of IceCreamPlugins.dll . The plugins themselves do n't have a version attribute about them - I 'm wanting to rely upon the version of the DLL . Hope that makes sense.I have n't figured out to know which DLLs I 'm using there so that I can call Assembly.GetName ( ) .Version on them.Ideas ? Solution : So , the solution to my problem was pretty straightforward after the parts have been composed.My plugin managing code has an entry like so : and once the container parts composition has taken place , I could iterate through my plug-ins like so : var catalog = new AggregateCatalog ( ) ; catalog.Catalogs.Add ( new DirectoryCatalog ( Path.Combine ( Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ) .location ) , `` Plugins '' ) ) ) ; var container = new CompositionContainer ( catalog ) ; container.ComposeParts ( this ) ; catalog.Catalogs.First ( ) .Parts.First ( ) .GetType ( ) .Assembly.FullName [ ImportMany ( typeof ( IDessertPlugin ) ] private IEnumerable < IDessertPluing > dessertPlugins ; foreach ( var plugin in dessertPlugins ) { Console.WriteLine ( Assembly.GetAssembly ( plugin.GetType ( ) ) .GetName ( ) .Version.ToString ( ) ) ; }",How do I get the version number of each DLL that has my MEF plugins ? "C_sharp : I am working on an application that needs to match two sets of data based on various criteria , including the sum of any number of items from each set . I 've distilled the problem down to this statement : Given a set of items and transactions , find the smallest set of items where the sum is equal to the sum of the smallest set of transactions . ( There ’ s some complexity I ’ m ignoring for this post , but for now I ’ m only concerned about the total amounts matching , not dates , descriptions , clearing differences , etc . ) Or , mathematically : Given two sets of numbers , find the smallest set from each where the sums are equal.The other similar SO questions I 've run across assume you know the sum ahead of time , or know the quantity from each set that you are going for.And here is a test that ( I think ) illustrates what I 'm going for.I 'm looking for an elegant solution that will make this pass , but will take any pseudocode or suggestion that gets me there ; ) [ TestMethod ] public void StackOverflowTest ( ) { var seta = new [ ] { 10 , 20 , 30 , 40 , 50 } ; var setb = new [ ] { 45 , 45 , 100 , 200 } ; var result = Magic ( seta , setb ) ; Assert.AreEqual ( new [ ] { 40,50 } , result.SetA ) ; Assert.AreEqual ( new [ ] { 45 , 45 } , result.SetB ) ; } class MagicResult { public int [ ] SetA { get ; set ; } public int [ ] SetB { get ; set ; } } private MagicResult Magic ( int [ ] seta , int [ ] setb ) { throw new NotImplementedException ( ) ; }","Given two sets of numbers , find the smallest set from each where the sum is equal" "C_sharp : Possible Duplicate : Finally Block Not Running ? ? I have a question regarding finally block in c # . I wrote a small sample code : As I far as I know , finally block suppose to run deterministicly , whether or not an exception was thrown . Now , if the user enters `` Y '' - NullReferenceException is thrown , execution moves to the catch clock and then to the finally block as I expected.But if the input is something else - ArgumentException is thrown . There is no suitable catch block to catch this exception , so I thought execution should move the the finally block - but it doesnt . Could someone please explain me why ? thanks everyone : ) public class MyType { public void foo ( ) { try { Console.WriteLine ( `` Throw NullReferenceException ? `` ) ; string s = Console.ReadLine ( ) ; if ( s == `` Y '' ) throw new NullReferenceException ( ) ; else throw new ArgumentException ( ) ; } catch ( NullReferenceException ) { Console.WriteLine ( `` NullReferenceException was caught ! `` ) ; } finally { Console.WriteLine ( `` finally block '' ) ; } } } class Program { static void Main ( string [ ] args ) { MyType t = new MyType ( ) ; t.foo ( ) ; } }",finally block in c # "C_sharp : I am using this tutorial as base for my code in 32bit unmanaged DLLhttps : //code.msdn.microsoft.com/CppHostCLR-e6581ee0Let 's say I want to call TestIntPtrHow can I pass IntPtr parameter if on C++ side it represents handle ? TestInt works , but for TestIntPtr I get the error that the method is not found . This is because the type of parameter is wrong.In code from tutorial for TestInt I use The question is what is correct code for TestIntPtrI have tried : Maybe CLR expects IUNKNOWN of IntPtr there ? But how to construct such instance ? I have tried to call IntPtr constructor with this API but it returns variant of type V_INTEGER , so this is closed loop.I know I can expose C # library using COM and how to use DllExports hack , I also can change C # part to accept just int or uint . But all these ways are not related to the question.Currently it works for me with following C # helperand in c++ . But this is ugly because I need this helper for the library I can not influence . public class IntPtrTester { public static void TestIntPtr ( IntPtr p ) { MessageBox.Show ( `` TestIntPtr Method was Called '' ) ; } public static void TestInt ( int p ) { MessageBox.Show ( `` TestInt Method was Called '' ) ; } } // HDC dc ; // The static method in the .NET class to invoke . bstr_t bstrStaticMethodName ( L '' TestInt '' ) ; SAFEARRAY *psaStaticMethodArgs = NULL ; variant_t vtIntArg ( ( INT ) dc ) ; variant_t vtLengthRet ; ... psaStaticMethodArgs = SafeArrayCreateVector ( VT_VARIANT , 0 , 1 ) ; LONG index = 0 ; hr = SafeArrayPutElement ( psaStaticMethodArgs , & index , & vtIntArg ) ; if ( FAILED ( hr ) ) { wprintf ( L '' SafeArrayPutElement failed w/hr 0x % 08lx\n '' , hr ) ; goto Cleanup ; } // The static method in the .NET class to invoke . // HDC dc ; bstr_t bstrStaticMethodName ( L '' TestIntPtr '' ) ; SAFEARRAY *psaStaticMethodArgs = NULL ; variant_t vtIntArg ( ( INT ) dc ) ; // what do I have to write here ? variant_t vtLengthRet ; variant_t vtIntArg ( ( INT ) dc ) ; variant_t vtIntArg ( ( UINT ) dc ) ; variant_t vtIntArg ( ( long ) dc ) ; variant_t vtIntArg ( ( UINT32 ) dc ) ; variant_t vtIntArg ( ( INT32 ) dc ) ; public class Helper { public static void help ( int hdc ) { IntPtrTester.TestIntPtr ( new IntPtr ( hdc ) ) ; } } variant_t vtIntArg ( ( INT32 ) dc ) ;",How to pass IntPtr to method from unmanaged C++ CLR hosting code ? "C_sharp : I drew the following grid : The above grid is drawn using the following two methods , one to calculate the grid and the other to calculate the centers for each cell : My question is how to make this grid appear as in the following picture and how to place the nodes at different cells ( random deployment ) in such grid.I need the grid to be drawn in a 3D view in which I have z as well as x and y ! //makes grid in picture boxprivate void drawGrid ( int numOfCells , int cellSize , Graphics gr ) { Pen p = new Pen ( Color.SteelBlue ) ; for ( int i = 0 ; i < Math.Sqrt ( numOfCells ) + 1 ; i++ ) { // Vertical gr.DrawLine ( p , i * cellSize + 300 , 200 , i * cellSize + 300 , 700 ) ; // Horizontal gr.DrawLine ( p , 300 , i * cellSize+200 , 800 , i * cellSize+200 ) ; } this.topology.SendToBack ( ) ; } //draw the center point for each cell of the grid private void drawCenters ( Graphics gr ) { for ( int j = 0 ; j < rows ; j++ ) { for ( int i = 0 ; i < columns ; i++ ) { gr.FillRectangle ( Brushes.IndianRed , cellsCenters [ 0 , i ] , cellsCenters [ 1 , j ] , 3 , 3 ) ; } } }",How to use the projection/camera technique in c # "C_sharp : I 'm having some trouble getting this to work correctly . I have two classes : I then set up the following mappings : I now have four mappings set up , and will test the following scenarios : In a test class , I then use the mappings like this : The only projection I would expect not to work at this stage would be TestClassA = > TestClassB , since I can see how AutoMapper may not know what to do with the int ? in cases where the value is null . Sure enough , that 's exactly the case . So I set up a mapping for int ? = > int like so : This is where things become strange . As soon as I add this mapping , the mapping from TestClassB = > TestClassB fails to even create . It gives this error message : Expression of type 'System.Int32 ' can not be used for assignment to type 'System.Nullable ` 1 [ System.Int32 ] ' I find this message incredibly strange as TestClassB does not have an int ? on it at all . So what 's going on here ? I feel like I must be misunderstanding something about how AutoMapper needs these projections to be handled . I realise the various bits of code may be tricky to piece together so here 's the entire test class for reference : public class TestClassA { public int ? NullableIntProperty { get ; set ; } } public class TestClassB { public int NotNullableIntProperty { get ; set ; } } cfg.CreateMap < TestClassA , TestClassB > ( ) .ForMember ( dest = > dest.NotNullableIntProperty , opt = > opt.MapFrom ( src = > src.NullableIntProperty ) ) ; cfg.CreateMap < TestClassA , TestClassA > ( ) .ForMember ( dest = > dest.NullableIntProperty , opt = > opt.MapFrom ( src = > src.NullableIntProperty ) ) ; cfg.CreateMap < TestClassB , TestClassA > ( ) .ForMember ( dest = > dest.NullableIntProperty , opt = > opt.MapFrom ( src = > src.NotNullableIntProperty ) ) ; cfg.CreateMap < TestClassB , TestClassB > ( ) .ForMember ( dest = > dest.NotNullableIntProperty , opt = > opt.MapFrom ( src = > src.NotNullableIntProperty ) ) ; int ? = > intint = > int ? int = > intint ? = > int ? var testQueryableDest = testQueryableSrc.ProjectTo < ... > ( _mapper.ConfigurationProvider ) ; cfg.CreateMap < int ? , int > ( ) .ProjectUsing ( src = > src ? ? default ( int ) ) ; [ TestClass ] public class BasicTests { private readonly IMapper _mapper ; public BasicTests ( ) { var config = new MapperConfiguration ( cfg = > { cfg.CreateMap < int ? , int > ( ) .ProjectUsing ( src = > src ? ? default ( int ) ) ; cfg.CreateMap < TestClassA , TestClassB > ( ) .ForMember ( dest = > dest.IntProperty , opt = > opt.MapFrom ( src = > src.NullableIntProperty ) ) ; cfg.CreateMap < TestClassA , TestClassA > ( ) .ForMember ( dest = > dest.NullableIntProperty , opt = > opt.MapFrom ( src = > src.NullableIntProperty ) ) ; cfg.CreateMap < TestClassB , TestClassA > ( ) .ForMember ( dest = > dest.NullableIntProperty , opt = > opt.MapFrom ( src = > src.IntProperty ) ) ; cfg.CreateMap < TestClassB , TestClassB > ( ) .ForMember ( dest = > dest.IntProperty , opt = > opt.MapFrom ( src = > src.IntProperty ) ) ; } ) ; _mapper = new Mapper ( config ) ; } [ TestMethod ] public void CanMapNullableIntToInt ( ) { var testQueryableSource = new List < TestClassA > { new TestClassA { NullableIntProperty = null } } .AsQueryable ( ) ; var testQueryableDestination = testQueryableSource.ProjectTo < TestClassB > ( _mapper.ConfigurationProvider ) ; } [ TestMethod ] public void CanMapNullableIntToNullableInt ( ) { var testQueryableSource = new List < TestClassA > { new TestClassA { NullableIntProperty = null } } .AsQueryable ( ) ; var testQueryableDestination = testQueryableSource.ProjectTo < TestClassA > ( _mapper.ConfigurationProvider ) ; } [ TestMethod ] public void CanMapIntToNullableInt ( ) { var testQueryableSource = new List < TestClassB > { new TestClassB { IntProperty = 0 } } .AsQueryable ( ) ; var testQueryableDestination = testQueryableSource.ProjectTo < TestClassA > ( _mapper.ConfigurationProvider ) ; } [ TestMethod ] public void CanMapIntToInt ( ) { var testQueryableSource = new List < TestClassB > { new TestClassB { IntProperty = 0 } } .AsQueryable ( ) ; var testQueryableDestination = testQueryableSource.ProjectTo < TestClassB > ( _mapper.ConfigurationProvider ) ; } }",How to correctly configure ` int ? ` to ` int ` projections using AutoMapper ? "C_sharp : Why does running a hundred async tasks take longer than running a hundred threads ? I have the following test class : As far as can tell , TestMethod1 and TestMethod2 should do exactly the same . One uses TPL , two uses plain vanilla threads . One takes 1:30 minutes , two takes 0.54 seconds.Why ? public class AsyncTests { public void TestMethod1 ( ) { var tasks = new List < Task > ( ) ; for ( var i = 0 ; i < 100 ; i++ ) { var task = new Task ( Action ) ; tasks.Add ( task ) ; task.Start ( ) ; } Task.WaitAll ( tasks.ToArray ( ) ) ; } public void TestMethod2 ( ) { var threads = new List < Thread > ( ) ; for ( var i = 0 ; i < 100 ; i++ ) { var thread = new Thread ( Action ) ; threads.Add ( thread ) ; thread.Start ( ) ; } foreach ( var thread in threads ) { thread.Join ( ) ; } } private void Action ( ) { var task1 = LongRunningOperationAsync ( ) ; var task2 = LongRunningOperationAsync ( ) ; var task3 = LongRunningOperationAsync ( ) ; var task4 = LongRunningOperationAsync ( ) ; var task5 = LongRunningOperationAsync ( ) ; Task [ ] tasks = { task1 , task2 , task3 , task4 , task5 } ; Task.WaitAll ( tasks ) ; } public async Task < int > LongRunningOperationAsync ( ) { var sw = Stopwatch.StartNew ( ) ; await Task.Delay ( 500 ) ; Debug.WriteLine ( `` Completed at { 0 } , took { 1 } ms '' , DateTime.Now , sw.Elapsed.TotalMilliseconds ) ; return 1 ; } }",Why does running a hundred async tasks take longer than running a hundred threads ? "C_sharp : I 'm currently writing integration tests using nunit for a previously untested server that was written in C # using ApiController and Entity Framework . Most of the tests run just fine , but I 've ran into two that always cause the database to time out . The error messages look something like this : System.Data.Entity.Infrastructure.DbUpdateException : An error occurred while updating the entries . See the inner exception for details . System.Data.Entity.Core.UpdateException : An error occurred while updating the entries . See the inner exception for details . System.Data.SqlClient.SqlException : Timeout expired . The timeout period elapsed prior to completion of the operation or the server is not responding . System.ComponentModel.Win32Exception : The wait operation timed out The first test that 's timing out : The other test that 's timing out : These are the controller methods that these tests are using : The timeout always happens on the first call to await db.SaveChangesAsync ( ) within the controller . Other controller methods that are being tested also call SaveChangesAsync without any problem . I 've also tried calling SaveChangesAsync from within the failing tests and it works fine there . Both of these methods they are calling work normally when called from within the controller , but time out when called from the tests.Other code that might be relevant : The model being used is just a normal code-first Entity Framework class : To keep the database clean between tests , I 'm using this custom attribute to wrap each one in a transaction ( from http : //tech.trailmax.info/2014/03/how-we-do-database-integration-tests-with-entity-framework-migrations/ ) : The database connection and controller being tested is build in setup methods before each test : [ TestCase , WithinTransaction ] public async Task Patch_EditJob_Success ( ) { var testJob = Data.SealingJob ; var requestData = new Job ( ) { ID = testJob.ID , Name = `` UPDATED '' } ; var apiResponse = await _controller.EditJob ( testJob.ID , requestData ) ; Assert.IsInstanceOf < StatusCodeResult > ( apiResponse ) ; Assert.AreEqual ( `` UPDATED '' , testJob.Name ) ; } [ TestCase , WithinTransaction ] public async Task Post_RejectJob_Success ( ) { var rejectedJob = Data.SealingJob ; var apiResponse = await _controller.RejectJob ( rejectedJob.ID ) ; Assert.IsInstanceOf < OkResult > ( apiResponse ) ; Assert.IsNull ( rejectedJob.Organizations ) ; Assert.AreEqual ( rejectedJob.JobStatus , JobStatus.OnHold ) ; _fakeEmailSender.Verify ( emailSender = > emailSender.SendEmail ( rejectedJob.Creator.Email , It.Is < string > ( emailBody = > emailBody.Contains ( rejectedJob.Name ) ) , It.IsAny < string > ( ) ) , Times.Once ( ) ) ; } [ HttpPatch ] [ Route ( `` editjob/ { id } '' ) ] public async Task < IHttpActionResult > EditJob ( int id , Job job ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } if ( id ! = job.ID ) { return BadRequest ( ) ; } Job existingJob = await db.Jobs .Include ( databaseJob = > databaseJob.Regions ) .FirstOrDefaultAsync ( databaseJob = > databaseJob.ID == id ) ; existingJob.Name = job.Name ; // For each Region find if it already exists in the database // If it does , use that Region , if not one will be created for ( var i = 0 ; i < job.Regions.Count ; i++ ) { var regionId = job.Regions [ i ] .ID ; var foundRegion = db.Regions.FirstOrDefault ( databaseRegion = > databaseRegion.ID == regionId ) ; if ( foundRegion ! = null ) { existingJob.Regions [ i ] = foundRegion ; db.Entry ( existingJob.Regions [ i ] ) .State = EntityState.Unchanged ; } } existingJob.JobType = job.JobType ; existingJob.DesignCode = job.DesignCode ; existingJob.DesignProgram = job.DesignProgram ; existingJob.JobStatus = job.JobStatus ; existingJob.JobPriority = job.JobPriority ; existingJob.LotNumber = job.LotNumber ; existingJob.Address = job.Address ; existingJob.City = job.City ; existingJob.Subdivision = job.Subdivision ; existingJob.Model = job.Model ; existingJob.BuildingDesignerName = job.BuildingDesignerName ; existingJob.BuildingDesignerAddress = job.BuildingDesignerAddress ; existingJob.BuildingDesignerCity = job.BuildingDesignerCity ; existingJob.BuildingDesignerState = job.BuildingDesignerState ; existingJob.BuildingDesignerLicenseNumber = job.BuildingDesignerLicenseNumber ; existingJob.WindCode = job.WindCode ; existingJob.WindSpeed = job.WindSpeed ; existingJob.WindExposureCategory = job.WindExposureCategory ; existingJob.MeanRoofHeight = job.MeanRoofHeight ; existingJob.RoofLoad = job.RoofLoad ; existingJob.FloorLoad = job.FloorLoad ; existingJob.CustomerName = job.CustomerName ; try { await db.SaveChangesAsync ( ) ; } catch ( DbUpdateConcurrencyException ) { if ( ! JobExists ( id ) ) { return NotFound ( ) ; } else { throw ; } } return StatusCode ( HttpStatusCode.NoContent ) ; } [ HttpPost ] [ Route ( `` { id } /reject '' ) ] public async Task < IHttpActionResult > RejectJob ( int id ) { var organizations = await db.Organizations .Include ( databaseOrganization = > databaseOrganization.Jobs ) .ToListAsync ( ) ; // Remove job from being shared with organizations foreach ( var organization in organizations ) { foreach ( var organizationJob in organization.Jobs ) { if ( organizationJob.ID == id ) { organization.Jobs.Remove ( organizationJob ) ; } } } var existingJob = await db.Jobs.FindAsync ( id ) ; existingJob.JobStatus = JobStatus.OnHold ; await db.SaveChangesAsync ( ) ; await ResetJob ( id ) ; var jobPdfs = await DatabaseUtility.GetPdfsForJobAsync ( id , db ) ; var notes = `` '' ; foreach ( var jobPdf in jobPdfs ) { if ( jobPdf.Notes ! = null ) { notes += jobPdf.Name + `` : `` + jobPdf.Notes + `` \n '' ; } } // Rejection email var job = await db.Jobs .Include ( databaseJob = > databaseJob.Creator ) .SingleAsync ( databaseJob = > databaseJob.ID == id ) ; _emailSender.SendEmail ( job.Creator.Email , job.Name + `` Rejected '' , notes ) ; return Ok ( ) ; } public class Job { public Job ( ) { this.Regions = new List < Region > ( ) ; this.ComponentDesigns = new List < ComponentDesign > ( ) ; this.MetaPdfs = new List < Pdf > ( ) ; this.OpenedBy = new List < User > ( ) ; } public int ID { get ; set ; } public string Name { get ; set ; } public List < Region > Regions { get ; set ; } // etc ... } public class WithinTransactionAttribute : Attribute , ITestAction { private TransactionScope _transaction ; public ActionTargets Targets = > ActionTargets.Test ; public void BeforeTest ( ITest test ) { _transaction = new TransactionScope ( ) ; } public void AfterTest ( ITest test ) { _transaction.Dispose ( ) ; } } [ TestFixture ] public class JobsControllerTest : IntegrationTest { // ... private JobsController _controller ; private Mock < EmailSender > _fakeEmailSender ; [ SetUp ] public void SetupController ( ) { this._fakeEmailSender = new Mock < EmailSender > ( ) ; this._controller = new JobsController ( Database , _fakeEmailSender.Object ) ; } // ... } public class IntegrationTest { protected SealingServerContext Database { get ; set ; } protected TestData Data { get ; set ; } [ SetUp ] public void SetupDatabase ( ) { this.Database = new SealingServerContext ( ) ; this.Data = new TestData ( Database ) ; } // ... }",Integration test causes Entity Framework to time out "C_sharp : Delphi : C # : It 's not consistent either . Some dates will add up the same , ie..The total amount of seconds is actually being used to encode data , and I 'm trying to port the application to C # , so even one second completely throws everything off.Can anybody explain the disparity ? And is there a way to get c # to match delphi ? Edit : In response to suggestions that it might be leap second related : Both date ranges contain the same amount of leap seconds ( 2 ) , so you would expect a mismatch for both . But instead we 're seeing inconsistency SecondsBetween ( StrToDateTime ( '16/02/2009 11:25:34 p.m. ' ) , StrToDateTime ( ' 1/01/2005 12:00:00 a.m. ' ) ) ; 130289133 TimeSpan span = DateTime.Parse ( `` 16/02/2009 11:25:34 p.m. '' ) .Subtract ( DateTime.Parse ( `` 1/01/2005 12:00:00 a.m. '' ) ) ; 130289134 TimeSpan span = DateTime.Parse ( `` 16/11/2011 11:25:43 p.m. '' ) .Subtract ( DateTime.Parse ( `` 1/01/2005 12:00:00 a.m. '' ) ) ; SecondsBetween ( StrToDateTime ( '16/11/2011 11:25:43 p.m. ' ) , StrToDateTime ( ' 1/01/2005 12:00:00 a.m. ' ) ) ; both give216905143 16/02/2009 - 1/01/2005 = Delphi and C # calculate a different total seconds16/11/2011 - 1/01/2005 = They calculate the same total seconds",Disparity between date/time calculations in C # versus Delphi "C_sharp : I have a custom attribute in C # : MyAttr.And I have a method that expects a delegate as parameter.I now pass in a lambda expression to that method : That DoSomething ( ) method uses relfection to get information about the calling method ( in this case lambda expression ) . But it ca n't find the needed information , becauce the lambda expression does not have an attribute : - ( What I want to do is one of the following : Is it possible at all to put an attribute to a lambda expression ? SomeMethod ( ( object o ) = > { DoSomething ( ) ; } ) ; // This does not work : SomeMethod ( [ MyAttr ] ( object o ) = > { DoSomething ( ) ; } ) ; // Thos does not work , too : SomeMethod ( ( object o ) = > [ MyAttr ] { DoSomething ( ) ; } ) ;",How to add an Attribute to Lambda function in C # ? "C_sharp : I 'm designing a class library for discrete mathematics , and I ca n't think of a way to implement an infinite set.What I have so far is : I have an abstract base class , Set , which implements the interface ISet . For finite sets , I derive a class FiniteSet , which implements each set method . I can then use it like this : Now I want to represent an infinite set . I had the idea of deriving another abstract class from set , InfiniteSet , and then developers using the library would have to derive from InfiniteSet to implement their own classes . I 'd supply commonly used sets , such as N , Z , Q , and R.But I have no idea how I 'd implement methods like Subset and GetEnumerator - I 'm even starting to think it 's impossible . How do you enumerate an infinite set in a practical way , so that you can intersect/union it with another infinite set ? How can you check , in code , that N is a subset of R ? And as for the issue of cardinality.. Well , that 's probably a separate question.All this leads me to the conclusion that my idea for implementing an infinite set is probably the wrong way to go . I 'd very much appreciate your input : ) .Edit : Just to be clear , I 'd also like to represent uncountably infinite sets.Edit2 : I think it 's important to remember that the ultimate goal is to implement ISet , meaning that any solution has to provide ( as it should ) ways to implement all of ISet 's methods , the most problematic of which are the enumeration methods and the IsSubsetOf method . FiniteSet < int > set1 = new FiniteSet < int > ( 1 , 2 , 3 ) ; FiniteSet < int > set2 = new FiniteSet < int > ( 3 , 4 , 5 ) ; Console.WriteLine ( set1 ) ; // { 1 , 2 , 3 } Console.WriteLine ( set2 ) ; // { 3 , 4 , 5 } set1.UnionWith ( set2 ) ; Console.WriteLine ( set1 ) ; // { 1 , 2 , 3 , 4 , 5 }",How can I implement an infinite set class ? "C_sharp : Inspired by this question.Short version : Why ca n't the compiler figure out the compile-time type of M ( dynamic arg ) if there is only one overload of M or all of the overloads of M have the same return type ? Per the spec , §7.6.5 : An invocation-expression is dynamically bound ( §7.2.2 ) if at least one of the following holds : The primary-expression has compile-time type dynamic.At least one argument of the optional argument-list has compile-time type dynamic and the primary-expression does not have a delegate type.It makes sense that forthe compiler ca n't figure out the compile-time type ofbecause it wo n't know until runtime which overload of M is invoked.However , why ca n't the compiler figure out the compile-time type if M has only one overload or all of the overloads of M return the same type ? I 'm looking to understand why the spec does n't allow the compiler to type these expressions statically at compile time . class Foo { public int M ( string s ) { return 0 ; } public string M ( int s ) { return String.Empty ; } } dynamic d = // dynamicvar x = new Foo ( ) .M ( d ) ;",Why does a method invocation expression have type dynamic even when there is only one possible return type ? "C_sharp : Suppose I have some code like this : Of course , this code is equivalent to this : I think the first version is more readable and that 's how I 'm writing my code , even thought I 'm using a variable when I know I could avoid it.My question is this : does the compiler compile the code in the same way ( ie same performance ) or is the second option really better in terms of performance.Thanks . public string SomeMethod ( int Parameter ) { string TheString = `` '' ; TheString = SomeOtherMethod ( Parameter ) ; return TheString ; } public string SomeMethod ( int Parameter ) { return SomeOtherMethod ( Parameter ) ; }",c # avoiding variable declaration C_sharp : When I use this : It runs just fine.But when I add the Style tag : It does n't compile saying : The property 'Content ' is set more than once < Label Grid.Column= '' 2 '' Grid.Row= '' 8 '' Content= '' { x : Static res : Strings.ToolPanelEditView_Validation_MandatoryField } '' > < /Label > < Label Grid.Column= '' 2 '' Grid.Row= '' 8 '' Content= '' { x : Static res : Strings.ToolPanelEditView_Validation_MandatoryField } '' > < Style > < Setter Property= '' Label.Margin '' Value= '' 0 '' / > < /Style > < /Label >,The property 'Content ' is set more than once when I add Style "C_sharp : Is the following code thread safe ? var dict = new Dictionary < int , string > ( ) { { 0 , `` '' } , { 1 , `` '' } , { 2 , `` '' } , { 3 , `` '' } } ; var nums = dict.Keys.ToList ( ) ; Parallel.ForEach ( nums , num = > { dict [ num ] = LongTaskToGenerateString ( ) ; } ) ; return dict ;",Dictionary Update Thread-Safety "C_sharp : Is there a way to tell when a DataGridView columns is a PRIMARY KEY or a FOREIGN KEY ? The reason I ask is because I 'd like to set these DataGridViewDataColumns to be ReadOnly.After loading a DataTable , I can see SQL-like properties like AllowDBNull , AutoIncrement , and Unique ; but how do I tell which columns are keys ? The test in that last line above ( ! tblC.AllowDBNull & & tblC.AutoIncrement & & tblC.Unique ) is a hack , and I know it only works in some cases.I found the post How to determine a primary key for a table in SQL Server ? showing how to write an SQL Query to determine this , but can I tell somehow using the DataTable that I supply to the DataGridView ? I also saw the post C # Linq-to-SQL : Refectoring this Generic GetByID method using Linq-to-SQL , but ( though I try ) I just do n't understand that Linq jibberish.If determining the key is not supported , what would be the best approach ? Two queries , one for schema and the other for the data , then go through the data using the schema collected ? EDIT : I noticed that when looking at the data table 's schema using : I am returned a COLUMN_FLAGS value . The table I am looking at shows a value of 18 for my Primary Key on this table . Is that a good test ? private void GetData ( string tableName , SqlConnection con ) { bool wasOpen = ( con.State == ConnectionState.Open ) ; DataTable table = new DataTable ( tableName ) ; string sqlText = string.Format ( SQL_SELECT_COMMAND , tableName ) ; SqlCommand cmd = new SqlCommand ( sqlText , con ) ; if ( ! wasOpen ) { con.Open ( ) ; } table.Load ( cmd.ExecuteReader ( ) ) ; if ( ! wasOpen ) { con.Close ( ) ; } dataGridView1.DataSource = table.DefaultView ; for ( int i = 0 ; i < table.Columns.Count ; i++ ) { DataColumn tblC = table.Columns [ i ] ; DataGridViewColumn dgvC = dataGridView1.Columns [ i ] ; dgvC.ReadOnly = ( ! tblC.AllowDBNull & & tblC.AutoIncrement & & tblC.Unique ) ; } } SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Table1 '",DataGridView : Determine SQL Key Values or Relationships ? "C_sharp : Consider this ( edited-down ) Style , designed for a Button whose Content is a String : The intention in this example is to turn the button text red if it equals the word `` Test '' 1 . But it does n't work , because the trigger 's TemplatedParent binding resolves to null instead of to the Button the Style is applied to . However , the TextBlock named `` demo '' will have its Text set to `` System.Windows.Controls.Button : [ ButtonText ] '' as expected , which means TemplatedParent works correctly at that level . Why does n't it work inside the DataTrigger ? 1 I know there are other ways to achieve that , but I 'm trying to understand why the binding does n't work the way I expect it to . < Style x : Key= '' Test '' TargetType= '' Button '' > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' Button '' > < StackPanel > < TextBlock x : Name= '' text '' Text= '' { TemplateBinding Content } '' / > < TextBlock x : Name= '' demo '' Text= '' { Binding RelativeSource= { RelativeSource TemplatedParent } } '' / > < /StackPanel > < ControlTemplate.Triggers > < DataTrigger Binding= '' { Binding RelativeSource= { RelativeSource TemplatedParent } , Path=Content } '' > < DataTrigger.Value > < system : String > Test < /system : String > < /DataTrigger.Value > < Setter TargetName= '' test '' Property= '' Foreground '' Value= '' Red '' / > < /DataTrigger > < /ControlTemplate.Triggers > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style >",TemplatedParent is null when used inside a ControlTemplate 's DataTrigger "C_sharp : I 'm trying to figure out how to write unit tests for a server application that requieres sockets in C # . I need to read from a socket in order to proccess the request . In Java I could avoid sockets by using Streams , so when writing unit tests i could easily convert a string into a stream.I only found NetworkStream ( ) but it also requires a socket.How can I achieve this in C # so i can create Streams without sockets ? And how can I write to a Stream and read it again to see if the message is correct ? // ====== Input ======InputStream socketInputStream = new InputStream ( socket.getInputStream ( ) ) ; // or using string instead like thisInputStream socketInputStream = new ByteArrayInputStream ( `` string '' .getBytes ( ) ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( socketInputStream ) ) ; // ====== Output ======OutputStream socketOutputStream = new OutputStream ( socket.getOutputStream ( ) ) ; // I need to write byte [ ] to the streamBufferedOutputStream out = new BufferedOutputStream ( socketOutputStream ) ;",c # unit tests using sockets "C_sharp : In my search for the meaning of life , I stumbled upon a blog post that mentioned that your deployment strategy is not your architecture , it is simply an implementation detail , and as such we need to design for allowing different deployment patterns , whether you want to deploy your system to 1 node or multi-node , or another type of structure . Do the latest versions of Visual Studio provide some kind of flexibility ( besides azure ) to be able to deploy services in a variety of strategies ? For example , let 's say I have a solutionI want to be able to deploy this entire solution as 1 solution , or I would like to be able to deploy 3 separate binaries , one for each microservice.What does Visual Studio give you in terms of flexibility of deployment configuration ? Acme Solution -- Acme Startup Proj -- Acme Service A.csproj -- Acme Service B.csproj -- Acme Service C.csproj AcmeServiceA.exeAcmeServiceb.exeAcmeServicec.exe",How to allow for multiple types deployment ? "C_sharp : I 'm trying to generalize the following IL ( from Reflector ) : However , when I try and reproduce this IL with DynamicMethod : I get an exception of `` Operation could destabilize the runtime '' . The IL seems identical to me , any ideas ? ValueSource is a value type , which is why I 'm doing a ref parameter here.EDITHere 's the ValueSource type : .method private hidebysig instance void SetValue ( valuetype Test.TestFixture/ValueSource & thing , string 'value ' ) cil managed { .maxstack 8 L_0000 : nop L_0001 : ldarg.1 L_0002 : ldarg.2 L_0003 : call instance void Test.TestFixture/ValueSource : :set_Value ( string ) L_0008 : nop L_0009 : ret } [ Test ] public void Test_with_DynamicMethod ( ) { var sourceType = typeof ( ValueSource ) ; PropertyInfo property = sourceType.GetProperty ( `` Value '' ) ; var setter = property.GetSetMethod ( true ) ; var method = new DynamicMethod ( `` Set '' + property.Name , null , new [ ] { sourceType.MakeByRefType ( ) , typeof ( string ) } , true ) ; var gen = method.GetILGenerator ( ) ; gen.Emit ( OpCodes.Ldarg_1 ) ; // Load input to stack gen.Emit ( OpCodes.Ldarg_2 ) ; // Load value to stack gen.Emit ( OpCodes.Call , setter ) ; // Call the setter method gen.Emit ( OpCodes.Ret ) ; var result = ( SetValueDelegate ) method.CreateDelegate ( typeof ( SetValueDelegate ) ) ; var source = new ValueSource ( ) ; result ( ref source , `` hello '' ) ; source.Value.ShouldEqual ( `` hello '' ) ; } public delegate void SetValueDelegate ( ref ValueSource source , string value ) ; public struct ValueSource { public string Value { get ; set ; } }",`` Operation could destablize the runtime '' and DynamicMethod with value types "C_sharp : I have a list of extensions each with it 's own checkbox that user needs to choose from : In the end I need to have a List or an ObservableCollection of all the extensions chosen . Doing this non-MVVM is quite straight forward . I create the event of Checked or Unchecked , and I add the content of the sender.View : Code Behind : If I want to do this MVVM style , as far as I know - I have to create a property for each one of the checkboxes and bind them to the UI . This is a lot of work . Is there any simpler way ? < CheckBox Checked= '' ToggleButton_OnChecked '' Unchecked= '' ToggleButton_OnUnchecked '' > exe < /CheckBox > private void ToggleButton_OnChecked ( object sender , RoutedEventArgs e ) { var ext = ( ( CheckBox ) sender ) .Content.ToString ( ) ; Model.FirstRun.ExcludeExt.Add ( ext ) ; } private void ToggleButton_OnUnchecked ( object sender , RoutedEventArgs e ) { var ext = ( ( CheckBox ) sender ) .Content.ToString ( ) ; Model.FirstRun.ExcludeExt.Remove ( ext ) ; }",How to handle many checkboxes in MVVM ( WPF ) ? "C_sharp : I was often wondering about the right way to do this : For example , in my program I have around 100 constants ( or enums ) that are used in some calculation . They should preferrably be stored in one place . They can be grouped hierarchically , for example : Naturally , I want those values to be accessible while coding , so storing them in some kind of ressource is not really an option.As far as I could tell , this can be done with : very long constant namesnesting classesnamespacesUsing names is quite ugly , and it 's not really well maintainable . I find nesting classes a nice way to do it , but some stylecop/fxcop rules forbid that , so this must be `` bad '' in some way . Lastly , I find the suggested alternative , using namespaces , not terribly nice neither . Imho it creates masses of folders and files that each contain almost nothing . And I do n't like when 50 sub-namespaces pop up in the assembly reflector.So.. how do you do this kind of task ? What would you suggest ? System3 / Rules / Rule7 / ParameterXY / MaxAverageValue",Store hierarchical Const data "C_sharp : I 'm using `` yyyy-MM-dd '' several time in the code for date formattingFor example : Is it possible to declare the format as constant , so that use of the code again and again can be avoided var targetdate = Date.ToString ( `` yyyy-MM-dd '' ) ;",How to use date format as constant in C # ? "C_sharp : I do n't understand , why does the following regular expression : Match the string `` 127.0.0.1 '' ? Using Regex.IsMatch ( `` 127.0.0.1 '' , `` ^* $ '' ) ; Using Expresso , it does not match , which is also what I would expect . Using the expression ^ . * $ does match the string , which I would also expect.Technically , ^* $ should match the beginning of a string/line any number of times , followed by the ending of the string/line . It seems * is implicitly treated as a . *What am I missing ? EDIT : Run the following to see an example of the problem.I do not wish to have ^* $ match my string , I am wondering why it does match it . I would think that the expression should result in an exception being thrown , or at least a non-match.EDIT2 : To clear up any confusion . I did not write this regex with the intention of having it match `` 127.0.0.1 '' . A user of our application entered the expression and wondered why it matched the string when it should not . After looking at it , I could not come up with an explanation for why it matched - especially not since Expresso and .NET seems to handle it differently.I guess the question is answered by it being due to the .NET implementation avoiding throwing an exception , even thought it 's technically an incorrect expression . But is this really what we want ? ^* $ using System ; using System.Text.RegularExpressions ; namespace RegexFubar { class Program { static void Main ( string [ ] args ) { Console.WriteLine ( Regex.IsMatch ( `` 127.0.0.1 '' , `` ^* $ '' ) ) ; Console.Read ( ) ; } } }",Why ^* $ matches `` 127.0.0.1 '' "C_sharp : I 've run into an interesting problem when converting API data to a C # class in UWP.I have an API that returns image dimensions , like this : I also have a class with properties that match the JSON data , generated by json2csharp.com.And I am converting the JSON to a C # class using something like this : However , if the API does not know the height or width , it returns null instead of an int , like this : This obviously causes an exception to throw , specifically this error message : Newtonsoft.Json.JsonSerializationException : Error converting value { null } to type 'System.Int32'Is there some way to work around this or handle this scenario ? { `` height '' : `` 25 '' , `` width '' : `` 25 '' } public class Image { public int height { get ; set ; } public Uri url { get ; set ; } public int width { get ; set ; } } dynamic JsonData = JObject.Parse ( JsonString ) ; Image img = JsonData.ToObject < Image > ( ) ; { `` height '' : null , `` width '' : `` 25 '' }",Handling possible null value when converting JSON to C # class "C_sharp : Sorry hard to formulate . I need to round like this : Twisting my head , but ca n't see how to make this . Must work for any n number of digits . Anyone got an elegant method for it ? c # or vb.net 12 - > 10152 - > 2001538 - > 200025000 - > 30000etc .",Round any n-digit number to ( n-1 ) zero-digits "C_sharp : I 've debugging some problem with a Paint.Net plugin and I 've stumbled with some issue with the Random class , when several threads call a method from a single instance.For some strange reason , it seems that if I do not prevent concurrent access , by synchronizing the called method , my Random instance starts to behave ... randomly ( but in the bad sense ) .In the following example , I create several hundred threads that call repeteadly a single Random object . And when I run it , I sometimes ( not always , but nearly ) get clearly wrong results . The problem NEVER happens if I uncomment the Synchronized method annotation.An example ouput ( with the above values ) : Is this some known issue ? Is it incorrect to call a Random object from several threads without sync ? UPDATE : As per answers , the docs state that Random methods are not thread safe - mea culpa , I should have read that . Perhaps I had read that before but did n't think it so important - one could ( sloppily ) think that , in the rare event of two threads entering the same method concurrently , the worst that could happen is that those calls get wrong results - not a huge deal , if we are not too concerned about random number quality ... But the problem is really catastrophic , because the object is left in an inconsistent state , and from that on it returns keeps returning zero - as noted here . using System ; using System.Threading ; using System.Runtime.CompilerServices ; namespace testRandom { class RandTest { static int NTIMES = 300 ; private long ac=0 ; public void run ( ) { // ask for random number 'ntimes ' and accumulate for ( int i=0 ; i < NTIMES ; i++ ) { ac+=Program.getRandInt ( ) ; System.Threading.Thread.Sleep ( 2 ) ; } } public double getAv ( ) { return ac/ ( double ) NTIMES ; // average } } class Program { static Random random = new Random ( ) ; static int MAXVAL = 256 ; static int NTREADS = 200 ; // [ MethodImpl ( MethodImplOptions.Synchronized ) ] public static int getRandInt ( ) { return random.Next ( MAXVAL+1 ) ; // returns a value between 0 and MAXVAL ( inclusive ) } public static void Main ( string [ ] args ) { RandTest [ ] tests = new RandTest [ NTREADS ] ; Thread [ ] threads = new Thread [ NTREADS ] ; for ( int i=0 ; i < NTREADS ; i++ ) { tests [ i ] = new RandTest ( ) ; threads [ i ] = new Thread ( new ThreadStart ( tests [ i ] .run ) ) ; } for ( int i=0 ; i < NTREADS ; i++ ) threads [ i ] .Start ( ) ; threads [ 0 ] .Join ( ) ; bool alive=true ; while ( alive ) { // make sure threads are finished alive = false ; for ( int i=0 ; i < NTREADS ; i++ ) { if ( threads [ i ] .IsAlive ) alive=true ; } } double av=0 ; for ( int i=0 ; i < NTREADS ; i++ ) av += tests [ i ] .getAv ( ) ; av /= NTREADS ; Console.WriteLine ( `` Average : { 0 , 6 : f2 } Expected : { 1 , 6 : f2 } '' , av , MAXVAL/2.0 ) ; Console.Write ( `` Press any key to continue . . . `` ) ; Console.ReadKey ( true ) ; } } } Average : 78.98 Expected:128.00Press any key to continue . . .",Concurrency issues with Random in .Net ? "C_sharp : I have the following C # classesAs you can see they both have optional nullable parameters as part of their constructors , the only difference is that BadClass has the parameter default set to something other than null.If I attempt to create an instance of these classes in F # this is what I get : This works fine : This throws a NullReferenceException : And this throws an AccessViolationExceptionAny idea why this is ? EDITUsing ILSpy to decompile it this is the output of the F # The C # classes are in an assembly called InteopTest [ sic ] ILSpy to C # and this is the IL public class BadClass { public BadClass ( int ? bad = 1 ) { } } public class GoodClass { public GoodClass ( int ? good = null ) { } } let g = GoodClass ( ) let b = BadClass ( ) let asyncB = async { return BadClass ( ) } | > Async.RunSynchronously GoodClass g = new GoodClass ( null ) ; BadClass b = new BadClass ( 1 ) ; FSharpAsyncBuilder defaultAsyncBuilder = ExtraTopLevelOperators.DefaultAsyncBuilder ; FSharpAsync < BadClass > fSharpAsync = defaultAsyncBuilder.Delay < BadClass > ( new Program.asyncB @ 10 ( defaultAsyncBuilder ) ) ; FSharpAsync < BadClass > computation = fSharpAsync ; BadClass asyncB = FSharpAsync.RunSynchronously < BadClass > ( computation , null , null ) ; FSharpFunc < string [ ] , Unit > fSharpFunc = ExtraTopLevelOperators.PrintFormatLine < FSharpFunc < string [ ] , Unit > > ( new PrintfFormat < FSharpFunc < string [ ] , Unit > , TextWriter , Unit , Unit , string [ ] > ( `` % A '' ) ) ; fSharpFunc.Invoke ( argv ) ; return 0 ; .method public static int32 main ( string [ ] argv ) cil managed { .custom instance void [ FSharp.Core ] Microsoft.FSharp.Core.EntryPointAttribute : :.ctor ( ) = ( 01 00 00 00 ) // Method begins at RVA 0x2050 // Code size 92 ( 0x5c ) .maxstack 5 .entrypoint .locals init ( [ 0 ] class [ InteopTest ] InteopTest.GoodClass g , [ 1 ] valuetype [ mscorlib ] System.Nullable ` 1 < int32 > , [ 2 ] class [ InteopTest ] InteopTest.BadClass b , [ 3 ] class [ InteopTest ] InteopTest.BadClass asyncB , [ 4 ] class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsync ` 1 < class [ InteopTest ] InteopTest.BadClass > , [ 5 ] class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsyncBuilder builder @ , [ 6 ] class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsync ` 1 < class [ InteopTest ] InteopTest.BadClass > , [ 7 ] class [ FSharp.Core ] Microsoft.FSharp.Core.FSharpFunc ` 2 < string [ ] , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit > , [ 8 ] string [ ] ) IL_0000 : nop IL_0001 : ldloca.s 1 IL_0003 : initobj valuetype [ mscorlib ] System.Nullable ` 1 < int32 > IL_0009 : ldloc.1 IL_000a : newobj instance void [ InteopTest ] InteopTest.GoodClass : :.ctor ( valuetype [ mscorlib ] System.Nullable ` 1 < int32 > ) IL_000f : stloc.0 IL_0010 : ldc.i4.1 IL_0011 : newobj instance void [ InteopTest ] InteopTest.BadClass : :.ctor ( valuetype [ mscorlib ] System.Nullable ` 1 < int32 > ) IL_0016 : stloc.2 IL_0017 : call class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsyncBuilder [ FSharp.Core ] Microsoft.FSharp.Core.ExtraTopLevelOperators : :get_DefaultAsyncBuilder ( ) IL_001c : stloc.s builder @ IL_001e : ldloc.s builder @ IL_0020 : ldloc.s builder @ IL_0022 : newobj instance void Program/asyncB @ 10 : :.ctor ( class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsyncBuilder ) IL_0027 : callvirt instance class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsync ` 1 < ! ! 0 > [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsyncBuilder : :Delay < class [ InteopTest ] InteopTest.BadClass > ( class [ FSharp.Core ] Microsoft.FSharp.Core.FSharpFunc ` 2 < class [ FSharp.Core ] Microsoft.FSharp.Core.Unit , class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsync ` 1 < ! ! 0 > > ) IL_002c : stloc.s 4 IL_002e : ldloc.s 4 IL_0030 : stloc.s 6 IL_0032 : ldloc.s 6 IL_0034 : ldnull IL_0035 : ldnull IL_0036 : call ! ! 0 [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsync : :RunSynchronously < class [ InteopTest ] InteopTest.BadClass > ( class [ FSharp.Core ] Microsoft.FSharp.Control.FSharpAsync ` 1 < ! ! 0 > , class [ FSharp.Core ] Microsoft.FSharp.Core.FSharpOption ` 1 < int32 > , class [ FSharp.Core ] Microsoft.FSharp.Core.FSharpOption ` 1 < valuetype [ mscorlib ] System.Threading.CancellationToken > ) IL_003b : stloc.3 IL_003c : ldstr `` % A '' IL_0041 : newobj instance void class [ FSharp.Core ] Microsoft.FSharp.Core.PrintfFormat ` 5 < class [ FSharp.Core ] Microsoft.FSharp.Core.FSharpFunc ` 2 < string [ ] , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit > , class [ mscorlib ] System.IO.TextWriter , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit , string [ ] > : :.ctor ( string ) IL_0046 : call ! ! 0 [ FSharp.Core ] Microsoft.FSharp.Core.ExtraTopLevelOperators : :PrintFormatLine < class [ FSharp.Core ] Microsoft.FSharp.Core.FSharpFunc ` 2 < string [ ] , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit > > ( class [ FSharp.Core ] Microsoft.FSharp.Core.PrintfFormat ` 4 < ! ! 0 , class [ mscorlib ] System.IO.TextWriter , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit > ) IL_004b : stloc.s 7 IL_004d : ldarg.0 IL_004e : stloc.s 8 IL_0050 : ldloc.s 7 IL_0052 : ldloc.s 8 IL_0054 : callvirt instance ! 1 class [ FSharp.Core ] Microsoft.FSharp.Core.FSharpFunc ` 2 < string [ ] , class [ FSharp.Core ] Microsoft.FSharp.Core.Unit > : :Invoke ( ! 0 ) IL_0059 : pop IL_005a : ldc.i4.0 IL_005b : ret } // end of method Program : :main",F # interop with C # class that has an optional nullable parameter set to anything but null causes NullReferenceException / AccessViolationException "C_sharp : I have a List . For valid reasons , I duplicate the List many times and use it for different purposes . At some point I need to check if the contents of all these collections are same . Well , I know how to do this . But being a fan of `` short hand '' coding ( linq ... ) I would like to know if I can check this EFFICIENTLY with the shortest number of lines of code.UPDATECodeinchaos pointed out certain senarios I havent thought of ( duplicates and order of list ) .Though sequenceequal will take care of duplicates the order of the list can be a problem . So I am changing the code as follows . I need to copy the Lists for this.UPDATE2Thanks to Eric-using a HashSet can be very efficient as follows . This wont cover duplicates though.UPDATE3Thanks to Eric - The original code in this post with SequenceEqual will work with sorting . As Sequenceequal will consider the order of collections , the collections need to be sorted before calling sequenceequal . I guess this is not much of a probelm as sorting is pretty fast ( nlogn ) .UPDATE4As per Brian 's suggestion , I can use a lookup for this.Thank you all for your responses . List < string > original , duplicate1 , duplicate2 , duplicate3 , duplicate4 = new List < string ( ) ; // ... some code ... .. bool isequal = duplicate4.sequenceequal ( duplicate3 ) & & duplicate3.sequenceequal ( duplicate2 ) & & duplicate2.sequenceequal ( duplicate1 ) & & duplicate1.sequenceequal ( original ) ; //can we do it better than this List < List < string > > copy = new List < List < int > > { duplicate1 , duplicate2 , duplicate3 , duplicate4 } ; bool iseqaul = ( original.All ( x = > ( copy.All ( y = > y.Remove ( x ) ) ) ) & & copy.All ( n = > n.Count == 0 ) ) ; List < HashSet < string > > copy2 =new List < HashSet < string > > { new HashSet < string > ( duplicate1 ) , new HashSet < string > ( duplicate2 ) , new HashSet < string > duplicate3 ) , new HashSet < string > ( duplicate4 ) } ; HashSet < string > origninalhashset = new HashSet < string > ( original ) ; bool eq = copy2.All ( x = > origninalhashset.SetEquals ( x ) ) ; var originallkup = original.ToLookup ( i = > i ) ; var lookuplist = new List < ILookup < int , int > > { duplicate4.ToLookup ( i= > i ) , duplicate3.ToLookup ( i= > i ) , duplicate2.ToLookup ( i= > i ) , duplicate1.ToLookup ( i= > i ) } ; bool isequal = ( lookuplist.Sum ( x = > x.Count ) == ( originallkup.Count * 4 ) ) & & ( originallkup.All ( x = > lookuplist.All ( i = > i [ x.Key ] .Count ( ) == x.Count ( ) ) ) ) ;",how to check contents of collections ( > 2 ) are same "C_sharp : I 'm having trouble representing Persian ( Solar Hijri Calendar ) dates as DateTime in C # , specifically on certain days of particular months , for example 31/04 where in the Gregorian calendar such a date is meaningless : The above code will result in an ArgumentOutOfRangeException saying : Year , Month , and Day parameters describe an un-representable DateTime.Which is expected.How can I represent Persian Dates as DateTimes in .NET taking into accounts dates such as 30/02 and 31/04 ? System.Globalization.PersianCalendar p = new System.Globalization.PersianCalendar ( ) ; DateTime date = new DateTime ( 2013,7,22 ) ; int year = p.GetYear ( date ) ; int month = p.GetMonth ( date ) ; int day = p.GetDayOfMonth ( date ) ; DateTime d1 = new DateTime ( year , month , day ) ;",Is it possible to represent non gregorian dates as DateTime in .NET ? "C_sharp : In the Roslyn Pattern Matching spec it states that : The scope of a pattern variable is as follows : If the pattern appears in the condition of an if statement , its scope is the condition and controlled statement of the if statement , but not its else clause.However the latest Microsoft `` What 's new '' posts and presentations are showing this example : Which shows the pattern match i variable used outside the if level scope of the pattern match.Is this an oversight , or has the scoping been changed from the spec ? public void PrintStars ( object o ) { if ( o is null ) return ; // constant pattern `` null '' if ( ! ( o is int i ) ) return ; // type pattern `` int i '' WriteLine ( new string ( '* ' , i ) ) ; }",Pattern match variable scope "C_sharp : I 'm trying to make a WPF app that loads fullscreen , and have the F11 key toggle between fullscreen and windowed.With the following code , it first appears on the screen properly in fullscreen mode . The toggle pulls it back down to a regular window.Then the subsequent toggle it almost goes into fullscreen mode but seems shifted up by ~10 pixels , so half the taskbar is visible . I 'm able to reproduce this in a new WPF project with an empty main window . Is this a bug in the framework ? I ca n't imagine it would have gone unnoticed until now but I 've no idea what I 'm doing wrong . These are the properties that are supposed to do the job , and they 're almost working but not quite . I 've tried messing around with other Window settings but no luck . Any ideas ? public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; this.WindowState = WindowState.Maximized ; this.WindowStyle = WindowStyle.None ; this.ResizeMode = ResizeMode.NoResize ; this.Topmost = true ; this.PreviewKeyDown += ( s , e ) = > { if ( e.Key == Key.F11 ) { if ( this.WindowStyle == WindowStyle.None ) { this.WindowState = WindowState.Normal ; this.WindowStyle = WindowStyle.SingleBorderWindow ; this.ResizeMode = ResizeMode.CanResize ; this.Topmost = false ; } else { this.WindowState = WindowState.Maximized ; this.WindowStyle = WindowStyle.None ; this.ResizeMode = ResizeMode.NoResize ; this.Topmost = true ; } } } ; } }",WPF Fullscreen toggle still showing part of desktop "C_sharp : Will the .NET compiler optimize this : to execute with the same number of instructions/memory as this : Or will the local variable result in extra time and memory being spent to create a reference ( newObject ) to the MyObject only destroy it the next line once it 's out of scope.I ask because , performance all the same , I find the first to be more readable as a local variable name can often give the next developer some context as to what we 're doing here . public MyObject GetNewObject ( ) { var newCurrentObject = myObjectFactory.CreateNew ( DateTime.Now , `` Frank '' , 41 , secretPassword ) ; return newCurrentObject ; } public MyObject GetNewObject ( ) { return myObjectFactory.CreateNew ( DateTime.Now , `` Frank '' , 41 , secretPassword ) ; }",.NET return value optimization "C_sharp : Our existing application reads some floating point numbers from a file . The numbers are written there by some other application ( let 's call it Application B ) . The format of this file was fixed long time ago ( and we can not change it ) . In this file all the floating point numbers are saved as floats in binary representation ( 4 bytes in the file ) . In our program as soon as we read the data we convert the floats to doubles and use doubles for all calculations because the calculations are quite extensive and we are concerned with the spread of rounding errors.We noticed that when we convert floats via decimal ( see the code below ) we are getting more precise results than when we convert directly . Note : Application B also uses doubles internally and only writes them into the file as floats . Let 's say Application B had the number 0.012 written to file as float . If we convert it after reading to decimal and then to double we get exactly 0.012 , if we convert it directly , we get 0.0120000001043081 . This can be reproduced without reading from a file - with just an assignment : Is it always beneficial to convert from float to double via decimal , and if not , under what conditions is it beneficial ? EDIT : Application B can obtain the values which it saves in two ways : Value can be a result of calculationsValue can be typed in by user as a decimal fraction ( so in the example above the user had typed 0.012 into an edit box and it got converted to double , then saved to float ) float readFromFile = 0.012f ; Console.WriteLine ( `` Read from file : `` + readFromFile ) ; //prints 0.012 double forUse = readFromFile ; Console.WriteLine ( `` Converted to double directly : `` + forUse ) ; //prints 0.0120000001043081 double forUse1 = ( double ) Convert.ToDecimal ( readFromFile ) ; Console.WriteLine ( `` Converted to double via decimal : `` + forUse1 ) ; //prints 0.012",When is it beneficial to convert from float to double via decimal "C_sharp : I am trying to understand LINQ and become confident at using it . What I am struggling with are the parameters asked for . Example : words is an array collection . OrderBy 's intellisense says : A func executes a method , and a string is the value , TKey a key.In the example http : //msdn.microsoft.com/en-us/vcsharp/aa336756.aspx # thenBySimple ( ThenBy - Comparer ) , we compare length by saying a = > a.Length . I understand that syntax , but how is that related to what the intellisense is asking for ? I tend to find the method signature and intellisense unreadable because of all the generics.Thanks . var sortedWords = words.OrderBy ( a= > a.Length ) Func < string , TKey > keyselector",Confused about LINQ parameters "C_sharp : I have to call a Stored Procedure but passing a datatable ( an iEnumerable ) as parameter.My SP on the SQL server takes this parameter as : and the type is defined as : Then , on the caller side i create the parameters in this way : When i launch the project actually it stops with a KeyNotFoundException trying toin ServiceStackExtension.csHow can I achieve this ? @ LIST_USERS dbo.LIST_USERINFO_TYPE READONLY CREATE TYPE [ dbo ] . [ LIST_USERINFO_TYPE ] AS TABLE ( [ ID_USER ] [ int ] NOT NULL , [ ID_DATA ] [ int ] NOT NULL , [ HEADER_TXT ] [ varchar ] ( 100 ) NULL ) list.Add ( new UserInfoItem { IdUser = 401 , IdData = 3 , HeaderTxt = `` '' } ) ; list.Add ( new UserInfoItem { IdUser= 402 , IdData= 2 , HeaderTxt= `` gotcha '' } ) ; list.Add ( new UserInfoItem { IdUser= 403 , IdData= 1 , HeaderTxt= `` pacific rim '' } ) ; dbConn.StoredProcedure ( sp , new { LISTA_QUESTIONARIO = DomandeRisposteList } ) ; name.DbType = OrmLiteConfig.DialectProvider.GetColumnDbType ( propertyInfo.PropertyType ) ;",Passing a DataTable to a SP with ServiceStack ORMLite "C_sharp : I have static class that holds some infoAnd when I refresh page I want SampleDataCache to keep its data.Can I achieve this in simple way ? public static class SampleDataCache { private static Dictionary < string , SampleData > cacheDict = new Dictionary < string , object > ( ) public static Get ( string key ) { if ( ! cacheDict.Contains [ key ] ) cacheDict.Add ( key , new SampleData ( ) ) ; return cacheDict [ key ] ; } }",Cache static class 's Data in Silverlight "C_sharp : For this question , I 'm using ASP.NET Web Forms in C # , a web service and jQuery . I read this post about using an array to pass in a bunch of parameters to a web method using jQuery AJAX . I 'm wondering if it 's possible to do the same thing without using indices . The problem with indices is that order matters and making an update is a hassle since it involves updating the client-script and web method 's arguments . I 'm currently using named arguments , but this is very tedious . My largest web method has 20 arguments ! Yuck ! I 'm looking for a shortcut here without having to care about order . Is this possible ? UPDATE : Thanks to all who answered . Using your answers and some other Stack questions , I was finally able to piece together a working demo . I 'm pasting my proof of concept code here so anyone stuck with the same problem can see how it 's done . var obj = { } ; // Iterate through each table row and add the editor field data to an object. $ ( '.addressRow ' ) .each ( function ( ) { var row = $ ( this ) ; var addressField = row.find ( '.addressField ' ) ; var attr = addressField.attr ( 'addressFieldName ' ) ; var val = addressField.val ( ) obj [ attr ] = val ; } ) ; $ .ajax ( { type : 'POST ' , url : '/WebServices/AddressService.asmx/SaveAddress ' , data : JSON.stringify ( obj ) , contentType : 'application/json ; charset=utf-8 ' , dataType : 'json ' , success : function ( response ) { alert ( 'address saved ' ) ; } , error : function ( response ) { alert ( 'error ' ) ; } } ) ; [ WebMethod ] public void SaveAddress ( string streetAddress1 , string streetAddress2 , string apartmentNumber , string city , strng state , string zipCode , string country ) { // save address ... } < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head runat= '' server '' > < title > Web Service Demo < /title > < style type= '' text/css '' > * { font-family : `` Segoe UI '' ; font-size : 12px ; color : # 444444 ; } # result1 { padding : 10px 0px ; } < /style > < script type= '' text/javascript '' src= '' Scripts/jquery.js '' > < /script > < script type= '' text/javascript '' > $ ( document ) .ready ( function ( ) { $ ( 'button ' ) .click ( function ( ) { // NOTE : When using JavaScript objects , the properties MUST match the C # properties EXACTLY ( casing and seplling ) . // I.e . in employee.FirstName , FirstName maps EXACTLY to the FirstName in the C # Employee object . // Create a employee object using the assigning to properties method . var employee1 = { } ; employee1.ID = 5416 ; employee1.FirstName = 'Fred ' ; employee1.LastName = 'Baker ' ; employee1.BirthDate = '07/18/1982 ' ; employee1.StreetAddress = '947 River Street ' ; employee1.City = 'Somnerville ' ; employee1.State = 'AR ' ; employee1.ZipCode = '41370 ' ; // A property has the ability to be a list or complex type . In this example , employee1 uses a list of access codes and employee2 does not . employee1.AccessCodes = new Array ( ) ; employee1.AccessCodes [ 0 ] = 512 ; employee1.AccessCodes [ 1 ] = 887 ; // Create a employee object using the associative array method . var employee2 = { ID : 3316 , FirstName : 'Jason ' , LastName : 'Masters ' , BirthDate : '11/19/1980 ' , StreetAddress : '11 South Crane Avenue ' , City : 'New York ' , State : 'NY ' , ZipCode : '01147 ' // employee2 does no use any access codes . AccessCodes in the C # web method is a list and by excluding it from the JavaScript // object , the C # code defaults the list to the null . } ; // In order to pass a complex JavaScript object to a web method as a complex type , the JavaScript object needs to be JSONified . // The name of the argument in the C # web method MUST be included here in single quotes EXACTLY ( casing and spelling ) the same way // the argument is specified in the C # code . In this example , the web method is `` public string GetEmployeeData ( Employee employee ) '' . The // complex argument is 'employee ' . IT IS VITALLY IMPORTANT that , when using the JSON.stringify ( ) function , the name of the web method // argument is included here exactly the same way as specified in the C # code . I know I 'm being redundant by repeating myself , but // it took me hours to figure out how to do this and the error message from doing this improperly is completely useless ! var data1 = JSON.stringify ( { 'employee ' : employee1 } ) ; // 'employee ' is the web method argument and employee1 is the JavaScript object from above . var data2 = JSON.stringify ( { 'employee ' : employee2 } ) ; // 'employee ' is the web method argument and employee2 is the JavaScript object from above . // Send employee1 to the web method . $ .ajax ( { type : 'POST ' , url : '/WebServices/WebService1.asmx/GetEmployeeData ' , data : data1 , contentType : 'application/json ; charset=utf-8 ' , dataType : 'json ' , success : function ( response ) { $ ( ' # result1 ' ) .html ( response.d ) ; } , error : function ( response ) { $ ( ' # result1 ' ) .html ( 'web service call failure\n ' + response.responseText ) ; } } ) ; // Send employee2 to the web method . $ .ajax ( { type : 'POST ' , url : '/WebServices/WebService1.asmx/GetEmployeeData ' , data : data2 , contentType : 'application/json ; charset=utf-8 ' , dataType : 'json ' , success : function ( response ) { $ ( ' # result2 ' ) .html ( response.d ) ; } , error : function ( response ) { $ ( ' # result2 ' ) .html ( 'web service call failure\n ' + response.responseText ) ; } } ) ; } ) ; } ) ; < /script > < /head > < body > < form id= '' form1 '' runat= '' server '' > < div > < p > This demo shows how to pass a complex JSON object to a web method and get a reponse back from the web method. < /p > < p > 1 ) It creates two JavaScript objects. < /p > < p > 2 ) The JavaScript objects are JSONified and sent to the web method. < /p > < p > 3 ) The web method receives the complex objects and uses them to create response text. < /p > < p > 4 ) When the callback function fires , it displays the text returned from the web service. < /p > < button type= '' button '' > Call Web Service < /button > < div id= '' result1 '' > < /div > < div id= '' result2 '' > < /div > < /div > < /form > < /body > < /html > [ WebService ( Namespace = `` http : //tempuri.org/ '' ) ] [ WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 ) ] [ ToolboxItem ( false ) ] [ ScriptService ] public class WebService1 : WebService { [ WebMethod ] public string GetEmployeeData ( Employee employee ) { var output = string.Format ( `` Employee # { 0 } : { 1 } { 2 } lives at { 3 } in { 4 } , { 5 } with a zip code of { 6 } and was born on { 7 } . `` , employee.ID , employee.FirstName , employee.LastName , employee.StreetAddress , employee.City , employee.State , employee.ZipCode , employee.BirthDate.ToShortDateString ( ) ) ; if ( employee.AccessCodes ! = null ) { output += string.Format ( `` Employee # { 0 } has access codes : `` , employee.ID ) ; foreach ( var accessCode in employee.AccessCodes ) { output += accessCode + `` , `` ; } output = output.Substring ( 0 , output.Length - 2 ) ; } else { output += string.Format ( `` Employee # { 0 } does not have any has access codes . `` , employee.ID ) ; } return output ; } } public class Employee { public int ID { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public DateTime BirthDate { get ; set ; } public string StreetAddress { get ; set ; } public string City { get ; set ; } public string State { get ; set ; } public string ZipCode { get ; set ; } public List < int > AccessCodes { get ; set ; } }",Shortening The Number Of Arguments In A Web Method Using jQuery AJAX "C_sharp : With mutable types , the difference in behaviour between value and reference types is clear : With immutable types however , this difference is less clear cut : Immutable reference types often use value semantics too ( e.g . the canonical example System.String ) : Eric Lippert has discussed before on his blog ( e.g . here ) that the fact that value types are often ( when does n't really matter for this discussion ) allocated on the stack is an implementation detail and that it should n't generally dictate whether you make an object a value or reference type.Given this blurred distinction in behaviour for immutable types , what criteria does this leave for us to decide whether to make an immutable type a reference type or a value type ? Also , with the immutable emphasis on values vs variables , should immutable types always implement value semantics ? // Mutable value typePointMutStruct pms1 = new PointMutStruct ( 1 , 2 ) ; PointMutStruct pms2 = pms1 ; // pms1 == ( 1 , 2 ) ; pms2 == ( 1 , 2 ) ; pms2.X = 3 ; MutateState ( pms1 ) ; // Changes the X property to 4.// pms1 == ( 1 , 2 ) ; pms2 == ( 3 , 2 ) ; // Mutable reference typePointMutClass pmc1 = new PointMutClass ( 1 , 2 ) ; PointMutClass pmc2 = pmc1 ; // pmc1 == ( 1 , 2 ) ; pmc2 == ( 1 , 2 ) ; pmc2.X = 3 ; MutateState ( pmc1 ) ; // Changes the X property to 4.// pmc1 == ( 4 , 2 ) ; pmc2 == ( 4 , 2 ) ; // Immutable value typePointImmStruct pis1 = new PointImmStruct ( 1 , 2 ) ; PointImmStruct pis2 = pis1 ; // pis1 == ( 1 , 2 ) ; pis2 == ( 1 , 2 ) ; pis2 = new PointImmStruct ( 3 , pis2.Y ) ; // Ca n't mutate pis1// pis1 == ( 1 , 2 ) ; pis2 == ( 3 , 2 ) ; // Immutable reference typePointImmClass pic1 = new PointImmClass ( 1 , 2 ) ; PointImmClass pic2 = pic1 ; // pic1 == ( 1 , 2 ) ; pic2 == ( 1 , 2 ) ; pic2 = new PointImmClass ( 3 , pic2.Y ) ; // Ca n't mutate pic1 either// pic1 == ( 1 , 2 ) ; pic2 == ( 3 , 2 ) ; string s1 = GenerateTestString ( ) ; // Generate identical non-interned stringsstring s2 = GenerateTestString ( ) ; // by dynamically creating them// object.ReferenceEquals ( strA , strB ) ) == false ; // strA.Equals ( strB ) == true// strA == strB",When to use value and reference types for immutable types ? ( .NET ) "C_sharp : WPF Pack URIs use three consecutive commas , for example : Is the , , , part supposed to mean anything ? Is it just a delimiter ? Can anything go between the commas ? pack : //application : , , ,/myFolder/myPic.bmp",Commas in WPF Pack URIs "C_sharp : I read some articles and do n't managed solved my problem , My problem is in the moment when I try obtain the value of the controls ( CheckBox and ComboBox ) added dynamically into Windows Form , I need know when the CheckBox is checked ( or unchecked ) and if the ComboBox is empty ( or not ) when I press a button , this button call a method in which I validate if all components are empty , I add the controls the following way : '' I add the values from database in the case of the ComboBox , I omitted this part . `` I try obtain the value with a foreach : The problem is I do n't have idea how to know if the Control ( CheckBox and ComboBox ) is checked or empty ( as the case ) .Really thanks for any help , I appreciate your time . CheckBox box ; ComboBox cmBox ; for ( int i = 1 ; i < = sumOfRegisters ; i++ ) { box = new CheckBox ( ) ; box.Name = `` CheckBox '' + i ; box.Text = `` Some text '' ; box.AutoSize = true ; box.Location = new Point ( 10 , i * 25 ) ; //vertical cmBox = new ComboBox ( ) ; cmBox.Name = `` ComboBox '' + i ; cmBox.Size = new System.Drawing.Size ( 302 , 21 ) ; cmBox.TabIndex = i ; cmBox.Text = `` Some Text '' ; cmBox.Location = new Point ( 270 , i * 25 ) ; this.groupBox.Controls.Add ( cmBox ) ; this.groupBox.Controls.Add ( box ) ; } foreach ( Control ctrl in groupBox.Controls )",How to obtain the value of a control added dynamically into Windows Form c # ? "C_sharp : I am using registry key to set my application to load on Windows Startup ( after a user login ) .My Code : So with this code , my application load at startup , however the working directory is C : \Windows\System32Does anyone know why ? This does not work for me because that program needs couple of files within the same directory as that one to operate . If the program loaded on my chosen directory ( `` C : \Users\Name\Desktop '' ) then the problem would not exist.Anyone has any suggestion for this ? RegistryKey RegKey = Registry.LocalMachine ; RegKey = RegKey.OpenSubKey ( @ '' SOFTWARE\Microsoft\Windows\CurrentVersion\Run '' , true ) ; RegKey.SetValue ( `` AppName '' , `` \ '' '' + @ '' C : \Users\Name\Desktop '' + `` \ '' '' ) ; RegKey.Close ( ) ;","Starting application on start-up , using the wrong path to load" "C_sharp : My goal is to simulate `` infinite scrolling '' in a WPF ListView . I have achieved this task with some less-than-ideal methods , and I 'm sure there is a better way to do it.by `` infinite scrolling '' I mean the following : Let 's say a ListView has 20 items ( ordered 1 , 2 , 3 , 4 , ... 17 , 18 , 19 , 20 ) . When the user scrolls down one item , the item at the top of the ListView is removed and placed at the end of the ListView so the order of the items is 2 , 3 , 4 , 5 , ... 18 , 19 , 20 , 1 . Now if the user scrolls down two items , the top two items are removed and placed at the end so the order of the items is 4 , 5 , 6 , 7 , ... 20 , 1 , 2 , 3 . Now , similarly , if the user scrolls up one item , the item at the bottom of the ListView is removed and placed at the beginning so the order of the items is 3 , 4 , 5 , 6 , ... 19 , 20 , 1 , 2.I have achieved this task with the following function assigned to the ScrollChanged event of the ScrollViewer I wish to be `` infinite '' : Notice the variable handle_scroll . I put this in place because the call to sv.ScrollToVerticalOffset will cause the entire inf_scroll function to be called recursively if it was not there.I know it is bad practice to scroll the ScrollViewer in a ScrollChanged event handler , so that 's why I 'm asking : is there a better way to do this ? How can I prevent the recursive calls to inf_scroll ? Is there a better way to simulate `` infinite scrolling '' ? // sv - the ScrollViewer to which this event handler is listening// lv - the ListView associated with `` sv '' bool handle_scroll = true ; private void inf_scroll ( object sender , ScrollChangedEventArgs e ) { if ( handle_scroll ) { for ( int i = 0 ; i < e.VerticalChange ; i++ ) { object tmp = lv.Items [ 0 ] ; lv.Items.RemoveAt ( 0 ) ; lv.Items.Add ( tmp ) ; handle_scroll = false ; } for ( int i = 0 ; i > e.VerticalChange ; i -- ) { object tmp = lv.Items [ lv.Items.Count - 1 ] ; lv.Items.RemoveAt ( lv.Items.Count - 1 ) ; lv.Items.Insert ( 0 , tmp ) ; handle_scroll = false ; } if ( ! handle_scroll ) { sv.ScrollToVerticalOffset ( sv.VerticalOffset - e.VerticalChange ) ; } } else { handle_scroll = true ; } }",`` Infinite Scrolling '' in a ListView / Avoiding Re-entrant Scroll Events "C_sharp : Given the following class hierarchyI would have thought that I could do the followingHow would I determine in code that BobGeneric inherits from MyGenericClass ? public abstract class MyGenericClass < T1 , T2 > { public T1 Foo { get ; set ; } public T2 Bar { get ; set ; } } public class BobGeneric : MyGenericClass < int , string > { } public class JimGeneric : MyGenericClass < System.Net.Cookie , System.OverflowException > { } //All types in the assembly containing BobGeneric and JimGenericvar allTypes = _asm.GetTypes ( ) ; //This works for interfaces , but not here var specialTypes = allTypes.Where ( x = > typeof ( MyGenericClass < , > ) .IsAssignableFrom ( x ) ) //This also failstypeof ( BobGeneric ) .IsSubclassOf ( typeof ( MyGenericClass < , > ) ) .Dump ( ) ;",Determine if class is a subclass of a type with multiple generic parameters "C_sharp : I use both C++ and C # and something that 's been on my mind is whether it 's possible to use generics in C # to elide virtual function calls on interfaces . Consider the following : Inside Foo1 , every access to list.Count and list [ i ] causes a virtual function call . If this were C++ using templates , then in the call to Foo2 the compiler would be able to see that the virtual function call can be elided and inlined because the concrete type is known at template instantiation time.But does the same apply to C # and generics ? When you call Foo2 ( l ) , it 's known at compile-time that T is a List and therefore that list.Count and list [ i ] do n't need to involve virtual function calls . First of all , would that be a valid optimization that does n't horribly break something ? And if so , is the compiler/JIT smart enough to make this optimization ? int Foo1 ( IList < int > list ) { int sum = 0 ; for ( int i = 0 ; i < list.Count ; ++i ) sum += list [ i ] ; return sum ; } int Foo2 < T > ( T list ) where T : IList < int > { int sum = 0 ; for ( int i = 0 ; i < list.Count ; ++i ) sum += list [ i ] ; return sum ; } /* ... */var l = new List < int > ( ) ; Foo1 ( l ) ; Foo2 ( l ) ;",Can C # generics be used to elide virtual function calls ? "C_sharp : This is my predicate expression , where on some certain conditions I will append expressions with it.LikewiseNow my question is if this expression does n't pass by this condition then would there be any expression ? and how would I know if it returns no expression with it.Simply I want to do-if ( predicate==null ) or if ( predicate contains no expression ) var predicate = PredicateBuilder.True < o_order > ( ) ; if ( ! string.IsNullOrEmpty ( param.sSearch ) ) predicate = predicate.And ( s = > s.OrderID.ToString ( ) .Contains ( param.sSearch ) ) ;",How to check if predicate expression was changed ? "C_sharp : Ok so I have a dice throw app ... When I step through the code it functions normally and 'results ' contains the correct number of throw results and they appear to be random , when I leave the code to run and do exactly the same thing it produces a set of identical numbers.I 'm sure this is a logical error I can not see but fiddling with it for hours hasnt improved the situation , so any help is much appriciated . : ) class Dice { public int [ ] Roll ( int _throws , int _sides , int _count ) { Random rnd = new Random ( ) ; int [ ] results = new int [ _throws ] ; // for each set of dice to throw pass data to calculate method for ( int i = 0 ; i < _throws ; i++ ) { int thisThrow = Calculate ( _sides , _count ) ; //add each throw to a new index of array ... repeat for every throw results [ i ] = thisThrow ; } return results ; } private int Calculate ( int _sides , int _count ) { Random rnd = new Random ( ) ; int [ ] result = new int [ _count ] ; int total = 0 ; //for each dice to throw put data into result for ( int i = 0 ; i < _count ; i++ ) { result [ i ] = rnd.Next ( 1 , _sides ) ; } //count the values in result for ( int x = 0 ; x < _count ; x++ ) { total = total + result [ x ] ; } //return total of all dice to Roll method return total ; } }",C # code only gives expected results on step through ? C_sharp : I was trying to get some of the old code properly styled with stylecop . It asks for putting the using statements inside . It workedwell for all but one . I have reduced the problem to the below code . this gives compilation error Error `` The type or namespace name 'Hidden ' could not be found ( are you missing a using directive or an assembly reference ? ) '' . If I move using B.C ; above the namespace A.B.C then it builds properly . The class Hidden is developed by different team and we can not modify it . namespace B.C { using System ; public class Hidden { public void SayHello ( ) { Console.WriteLine ( `` Hello '' ) ; } } } namespace A.B.C { using B.C ; public class Program { static void Main ( string [ ] args ) { new Hidden ( ) .SayHello ( ) ; } } },Putting using statement inside the namespace fails "C_sharp : The following C # code : produces the following output : Unless I 'm misreading the documentation : The string that remains after all occurrences of the characters in the trimChars parameter are removed from the start and end of the current String object . If trimChars is null or an empty array , white-space characters are removed instead.should n't the trailing double-quote be trimmed from the second string in that output ? using System ; namespace TrimTest { class Program { static void Main ( string [ ] args ) { Console.WriteLine ( Environment.CommandLine ) ; Console.WriteLine ( Environment.CommandLine.Trim ( ' '' ' ) ) ; Console.ReadKey ( false ) ; } } } `` D : \Projects\TrimTest\TrimTest\bin\Debug\TrimTest.vshost.exe '' D : \Projects\TrimTest\TrimTest\bin\Debug\TrimTest.vshost.exe ''",Why does Environment.CommandLine.Trim ( ' '' ' ) not remove the trailing quote ? "C_sharp : I would like to be able to get the actual state or seed or whatever of System.Random so I can close an app and when the user restarts it , it just `` reseeds '' it with the stored one and continues like it was never closed.Is it possible ? Using Jon 's idea I came up with this to test it ; static void Main ( string [ ] args ) { var obj = new Random ( ) ; IFormatter formatter = new BinaryFormatter ( ) ; Stream stream = new FileStream ( `` c : \\test.txt '' , FileMode.Create , FileAccess.Write , FileShare.None ) ; formatter.Serialize ( stream , obj ) ; stream.Close ( ) ; for ( var i = 0 ; i < 10 ; i++ ) Console.WriteLine ( obj.Next ( ) .ToString ( ) ) ; Console.WriteLine ( ) ; formatter = new BinaryFormatter ( ) ; stream = new FileStream ( `` c : \\test.txt '' , FileMode.Open , FileAccess.Read , FileShare.Read ) ; obj = ( Random ) formatter.Deserialize ( stream ) ; stream.Close ( ) ; for ( var i = 0 ; i < 10 ; i++ ) Console.WriteLine ( obj.Next ( ) .ToString ( ) ) ; Console.Read ( ) ; }",Is there a way to grab the actual state of System.Random ? "C_sharp : I am working in an ISP company . We are developing a speed tester for our customers , but running into some issues with TCP speed testing.One client had a total time duration on 102 seconds transferring 100 MB with a packet size of 8192 . 100.000.000 / 8192 = 12.202 packets . If the client sends an ACK every other packet that seems like a lot of time just transmitting the ACKs . Say the client sends 6000 ACKs and the RTT is 15ms - that 's 6000 * 7.5 = 45.000ms = 45 seconds just for the ACKs ? If I use this calculation for Mbit/s : I will get the result in Mbp/s , but then the higher the TTL is between the sender and the client the lower the Mbp/s speed will become.To simulate that the user is closer to the server , would it be `` legal '' to remove the ACK response time in the final result on the Mbp/s ? This would be like simulating the enduser is close to the server ? So I would display this calculation to the end user : Is that valid ? ( ( ( sizeof_download_in_bytes / durationinseconds ) /1000 ) /1000 ) * 8 = Mbp/s ( ( ( sizeof_download_in_bytes / ( durationinseconds - 45sec ) ) /1000 ) /1000 ) * 8 = Mbp/s",TCP speed tester algorithm question "C_sharp : I have tried to come up with the simplest code to reproduce what I am seeing . The full program is below , but I will describe it here . Suppose I have class named ListData that just has some properties . Then suppose I have a MyList class that has a member List < ListData > m_list . Suppose m_list gets initialized in the MyList constructor . In the main method I simply create one of these MyList objects , add a few ListData to it , then let it go out of scope . I take a snapshot in dotMemory after the ListData have been added , then I take another snapshot after the MyList object goes out of scope . In dotMemory I can see that the MyList object has been reclaimed as expected . I also see that the two ListData objects that I created also got reclaimed as expected . What I do not understand is why is there a ListData [ ] that survived ? Here is a screen shot of this : I open survived objects on the newest snapshot for the ListData [ ] then I view Key Retention Paths , this is what I see . I am new to .NET memory management and I created this sample app to help me explore it . I downloaded the trial version of JetBrains dotMemory version 4.3 . I am using Visual Studio 2013 Professional . I have to learn memory management so I can fix the memory issues we have at work . Here is the full program that can be used to reproduce this . It is just a quick and dirty app but it will get the thing I am asking about if you profile it . Steps : Build above code in release . In dotMemory , select to profile astandalone app . Browse to the release exe . Select the option to start collecting allocation data immediately . Click Run.Take a snapshot immediately and name it `` before '' . This is before anyListData have been added . In the app , type a and add two ListData . In dotMemory , take another snapshot and name it `` added 2 '' because we added two ListData . In the app , type q to quit ( the MyList will go out of scope ) . Before typing Enter again to exit the app , go take another snapshot in dotMemory . Name it `` out of scope '' .In the app , type Enter to close the app.In dotMemory , compare the `` added 2 '' and the `` out of scope '' snapshots . Group by namespace . You will see the ListData [ ] that I am referring to.Notice that the MyList and the two ListData objects did get garbage collected but the ListData [ ] did not . Why is there a ListData [ ] hanging around ? How can I make it get garbage collected ? using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication1 { class ListData { public ListData ( string name , int n ) { Name = name ; Num = n ; } public string Name { get ; private set ; } public int Num { get ; private set ; } } class MyList { public MyList ( ) { m = new List < ListData > ( ) ; } public void AddString ( ListData d ) { m.Add ( d ) ; } private List < ListData > m ; } class Program { static void Main ( string [ ] args ) { { MyList l = new MyList ( ) ; bool bRunning = true ; while ( bRunning ) { Console.WriteLine ( `` a or q '' ) ; string input = Console.ReadLine ( ) ; switch ( input ) { case `` a '' : { Console.WriteLine ( `` Name : `` ) ; string strName = Console.ReadLine ( ) ; Console.WriteLine ( `` Num : `` ) ; string strNum = Console.ReadLine ( ) ; l.AddString ( new ListData ( strName , Convert.ToInt32 ( strNum ) ) ) ; break ; } case `` q '' : { bRunning = false ; break ; } } } } Console.WriteLine ( `` good bye '' ) ; Console.ReadLine ( ) ; } } }",What is this `` pinning handle object [ ] '' that I see in Jetbrains dotMemory when I use a List < T > ? "C_sharp : Could someone advice me on what approach to take when writing C # constructors ? In other languages , like C++ , everything is fine - you usually do n't make the internal fields visible and provide getters / setters for them.This means , you could provide your class with constructors , which initialize all / some of your local members and be happy.C # , however , has properties , which allows us to write something like : This allows chaining for the object construction and , as I assume , can remove a lot of constructors , which would be required if we did n't have properties.Combining this with default values for properties , as I assume , we can completely get rid of non-specialized constructors , which actually do some work.Now - is it okay to remove redundant constructors and allow object constructing via field initializing ? What are the drawbacks of this approach ? Could someone give general recommendations about combining the usage of fields and constructors , some rules of thumb , probably ? Thank you . Class x = new Class { Field1 = new Field1 ... . , Field2 = new Field2 }",C # constructors "C_sharp : I had asked this question previously . The idea is same except that I have to find all the common time within certain TimeSpan.BackgroundLets suppose , I want to meet some peoples , and I say I want to meet certain peoples between Datetime X ( 2014-02-16 09:00:00.000 ) to DateTime Y ( 2014-02-26 05:00:00.000 ) . And I say I want to the meeting to last for at least N number of hours.Then the peoples i want to meet with will reply saying i will be available in following dates : and so on . Objective I then have to find if there exists a time range that includes in all the user 's response.Lets consider these are the responses Attendee1 ( Some GuidId ) : Response1 : Start Time=2014-02-23 09:00 AM , EndTime = 2014-02-23 11:00 AM , Response2 : Start Time=2014-02-24 10:00 AM , EndTime = 2014-02-24 12:00 PM , Response3 : Start Time=2014-02-25 10:00 AM , EndTime = 2014-02-25 11:00 AM , Response4 : Start Time=2014-02-23 01:00 PM , EndTime = 2014-02-17 5:00 PM Attendee2 ( Some GuidId ) : Response1 : Start Time=2014-02-22 09:00 AM , EndTime = 2014-02-22 05:00 PM , Response2 : Start Time=2014-02-23 09:00 AM , EndTime = 2014-02-23 05:00 PM , Response3 : Start Time=2014-02-25 09:00 AM , EndTime = 2014-02-25 12:00 PM , Attendee3 ( Some GuidId ) : Response1 : Start Time=2014-02-22 11:00 AM , EndTime = 2014-02-22 02:00 PM , Response2 : Start Time=2014-02-23 04:00 PM , EndTime = 2014-02-23 03:00 PM , Response3 : Start Time=2014-02-23 4:30 PM , EndTime = 2014-02-23 05:30 PM , Response4 : Start Time=2014-02-24 02:00 AM , EndTime = 2014-02-24 05:00 PM , Response5 : Start Time=2014-02-25 11:00 AM , EndTime = 2014-02-25 12:00 PM , So , if possible , I should come up with something that will say here are the matches found , if not then just find if the common time exists for all the user 's or not.Time X to Time Y ( Difference between X and Y should be at least the TimeSpan mentioned ) : Number of Attendee in this match = N ( type = int , 1 or 2 or as many match as found ) ... etc.PS : It is a MVC 5.1 application and database is created using code first approach.So in database there is table called Appointment which stores the StartDateTime and EndDateTimeHere are my DataModelsand between these dates people ( Attendee ) attending will give their response . Each person ( who will respond ) , their information is stored in database table called AttendeesAnd for each user their response is stored in Responses table whose model would look likeThis is what I have done but it does n't work.So in this case if Attendee X ( with some Guid Id ) gives his/her availability asand Attendee Y gives his/her availibility asthis is the common match I getWhich is not what I want as I explained.So , what should I do to get what I want.Edit : Based upon Answer from Zachein repositoryStartDate : 2/24/2014 11:30:00 AM//that I set while creating appointmentEndDate : 2/25/2014 11:30:00 AMWhen the first user responds with following data : matches result : when second attendee responds with following datamatches resultHere the common matches should have been : Date1 ( Certain date from certain start time to certain end time ) , Date2 ( certain date from certain time to certain time ) , ... Time A to Time B : Number of Attendee in this match = N public class Appointment { [ Key ] public Guid Id { get ; set ; } public virtual ICollection < Attendee > Attendees { get ; set ; } public DateTime StartDateTime { get ; set ; } public DateTime EndDateTime { get ; set ; } public TimeSpan MinAppointmentDuration { get ; set ; } } public class Attendee { public Guid AttendeeId { get ; set ; } public virtual ICollection < Response > Responses { get ; set ; } } public class Response { [ Key ] [ DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public int Id { get ; set ; } public Guid AttendeeId { get ; set ; } public DateTime StartDateTime { get ; set ; } public DateTime EndDateTime { get ; set ; } } public class CommonTime { public DateTime Start { get ; set ; } public DateTime End { get ; set ; } public TimeSpan MinAppointmenttime { get ; set ; } public int NumAttendees { get { return Responses.Select ( x = > x.AttendeeId ) .Distinct ( ) .Count ( ) ; } } public List < DataModels.Response > Responses { get ; set ; } public CommonTime ( DataModels.Response response , TimeSpan time ) { Responses = new List < DataModels.Response > ( ) ; Start = response.StartDateTime ; End = response.EndDateTime ; MinAppointmenttime = time ; } public void MergeCommonTime ( DataModels.Response response ) { if ( Start < = response.StartDateTime & & response.EndDateTime < =End ) { Start = response.StartDateTime ; End = response.EndDateTime ; if ( ( End-Start ) > =MinAppointmenttime ) { Responses.Add ( response ) ; } } } public List < CommonTime > FindCommonMatches ( Guid appointmentId ) { var appointment = _db.Appointments.Find ( appointmentId ) ; var attendees = appointment.Attendees.ToList ( ) ; var matches = new List < CommonTime > ( ) ; bool isFirstAttendee = true ; foreach ( var attendee in attendees ) { if ( isFirstAttendee ) { foreach ( var response in attendee.Responses ) { matches.Add ( new CommonTime ( response , appointment.MinAppointmentDuration ) ) ; } isFirstAttendee = false ; } else { foreach ( var response in attendee.Responses ) { matches.ForEach ( x = > x.MergeCommonTime ( response ) ) ; } } } return matches ; } } public class Meeting { public DateTime Start { get ; set ; } public DateTime End { get ; set ; } public List < DataModels.Attendee > Attendees { get ; set ; } } public class Requirement { public DateTime Start { get ; set ; } public DateTime End { get ; set ; } public TimeSpan MinHours { get ; set ; } public int MinAttendees { get ; set ; } public IEnumerable < Meeting > Meetings ( ) { var possibleMeetings = new List < Meeting > ( ) ; var availableHours = ( End - Start ) .TotalHours ; for ( var i = 0 ; i < availableHours - MinHours.Hours ; i++ ) yield return new Meeting { Start = Start.AddHours ( i ) , End = Start.AddHours ( i+MinHours.Hours ) } ; } } public class Scheduler { public IEnumerable < Meeting > Schedule ( Requirement req , List < DataModels.Attendee > attendees ) { var fullMatches = new List < Meeting > ( ) ; var partialMatches = new List < Meeting > ( ) ; foreach ( var m in req.Meetings ( ) ) { foreach ( var a in attendees ) { if ( fullMatches.Any ( ) ) { if ( a.Responses.Any ( r = > r.StartDateTime < = m.Start & & r.EndDateTime > = m.End ) ) { if ( m.Attendees == null ) { m.Attendees = new List < DataModels.Attendee > { a } ; } else { m.Attendees.Add ( a ) ; } } else { break ; // If we found one full match we are n't interested in the partials anymore . } } else { if ( a.Responses.Any ( r = > r.StartDateTime < = m.Start & & r.EndDateTime > = m.End ) ) { if ( m.Attendees == null ) { m.Attendees = new List < DataModels.Attendee > { a } ; } else { m.Attendees.Add ( a ) ; } } } } if ( m.Attendees ! = null ) { if ( m.Attendees.Count == attendees.Count ) fullMatches.Add ( m ) ; else if ( m.Attendees.Count > = req.MinAttendees ) partialMatches.Add ( m ) ; } } return fullMatches.Any ( ) ? fullMatches : partialMatches ; } } } public IEnumerable < Meeting > FindCommonMatches ( Guid appointmentId ) { var appointment = _db.Appointments.Find ( appointmentId ) ; var attendees = appointment.Attendees.Where ( a = > a.HasResponded == true ) .ToList ( ) ; var req = new Requirement { Start = appointment.StartDateTime , End = appointment.EndDateTime , MinHours = appointment.MinAppointmentDuration , MinAttendees = 1 } ; var schedule = new Scheduler ( ) ; var schedules = schedule.Schedule ( req , attendees ) ; return schedules ; } Match1 : 2/24/2014 10:00:00 AM to 2/24/2014 11:00:00 AM Match2 : 2/25/2014 9:00:00 AM to 2/25/2014 11:00:00 AM",Find all the common time from List of time provided by each user "C_sharp : I have this code to extract a table to computer in a .xls file : And I have seen that this is not a real .xls file . I can open it in Notepad and see my standart html table codes.Now I understand that defining ContentType is not enough . So what else can I do to generate a pure .xls or .xlsx file ? Or Should I certainly use Excel Libraries like OpenXML , Interop , etc . ? // I have a string which contains HTML table codes , named as excelTableHttpResponse response = HttpContext.Current.Response ; response.Clear ( ) ; response.AddHeader ( `` Content-Disposition '' , String.Format ( `` Attachment ; Filename=file.xls '' , ) ) ; response.Buffer = true ; response.ContentEncoding = System.Text.Encoding.Default ; response.ContentType = `` application/vnd.ms-excel '' ; response.Write ( excelTable ) ; response.End ( ) ;",How to make a real XLS file on asp.net c # ? "C_sharp : Sometimes when I launch my MVC 3 project it attempts to load the fully qualified URL for the view being rendered instead of the action within the controller ( Which gives me a 404 error ) . Other times it works fine and actually hits the controller action like it 's supposed to , but it 's about 50/50.The URL it hits sometimes is : http : //localhost : xxxx/Views/Account/LogOn.cshtmlHere is the default route setup in the Global.asax file : I also tried removing the / { id } parameter from the route as I do n't feel it 's needed for the logon screen.Any ideas ? Currently the project is setup pretty simply with the default action method LogOn in the AccountController etc . The only thing I did was change the controller and action in the global.asax file . routes.MapRoute ( `` Default '' , // Route name `` { controller } / { action } / { id } '' , // URL with parameters new { controller = `` Account '' , action = `` LogOn '' , id = UrlParameter.Optional } ) ;",MVC 3 tries to launch URL to View instead of controller action "C_sharp : I 'm loading a List < Image > from a folder of about 250 images . I did a DateTime comparison and it takes a full 11 second to load those 250 images . That 's slow as hell , and I 'd very much like to speed that up.The images are on my local harddrive , not even an external one.The code : EDIT : yes , I need all the pictures . The thing I 'm planning is to take the center 30 pixelcolums of each and make a new image out of that . Kinda like a 360 degrees picture . Only right now , I 'm just testing with random images.I know there are probably way better frameworks out there to do this , but I need this to work first.EDIT2 : Switched to a stopwatch , the difference is just a few milliseconds . Also tried it with Directory.EnumerateFiles , but no difference at all.EDIT3 : I am running .NET 4 , on a 32-bit Win7 client . DialogResult dr = imageFolderBrowser.ShowDialog ( ) ; if ( dr == DialogResult.OK ) { DateTime start = DateTime.Now ; //Get all images in the folder and place them in a List < > files = Directory.GetFiles ( imageFolderBrowser.SelectedPath ) ; foreach ( string file in files ) { sourceImages.Add ( Image.FromFile ( file ) ) ; } DateTime end = DateTime.Now ; timeLabel.Text = end.Subtract ( start ) .TotalMilliseconds.ToString ( ) ; }",Speeding up the loading of a List of images "C_sharp : I 'm currently working on three-way merging on syntax trees using Roslyn . I have a matching between all children on a a ClassDeclerationSyntax node , and want to perform a merge on the children , and then create a new tree based on that merge.O is the input ClassDeclerationSyntax , and matching has three members ( A , O , B ) of the type MemberDeclerationSyntax.This does not work . In the second iteration ReplaceNode returns a completely unmodified node ( oldUpdated == updated is true ) .It seems that after the first iteration of the loop , all children have been reconstructed as new objects , and the original children-objects stored in my matching can no longer be found in the children list ( updated.ChildNodes ( ) .Where ( x = > x == m.O ) is empty ) .What would a good way be to do this ? var updated = O ; foreach ( var m in matching ) { if ( m.A ! = null & & m.B ! = null & & m.O ! = null ) { var merge = Merge ( m.A , m.O , m.B ) ; var oldUpdated = updated ; updated = updated.ReplaceNode ( m.O , merge ) ; } else if ( m.A == null & & m.O == null & & m.B ! = null ) updated = updated.AddMembers ( m.B ) ; else if ( m.A ! = null & & m.O == null & & m.B == null ) updated = updated.AddMembers ( m.A ) ; }","Replacing several nodes in the same tree , using SyntaxNode.ReplaceNode" "C_sharp : I 've found plenty of examples of writing code that executes when a WPF or Windows Forms app terminates , but not for a UWP app . Is there any special C # method you can override , or an event handler you can use to contain cleanup code ? Here is the WPF code I tried but did not work in my UWP app : App.xaml.cs ( without the boilerplate usings and namespace declaration ) App.xamlI tried to use Process.Exited , but VS2015 could not recognize Process inside of System.Diagnostics . public partial class App : Application { void App_SessionEnding ( object sender , SessionEndingCancelEventArgs e ) { MessageBox.Show ( `` Sorry , you can not log off while this app is running '' ) ; e.Cancel = true ; } } < Application x : Class= '' SafeShutdownWPF.App '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : SafeShutdownWPF '' StartupUri= '' MainWindow.xaml '' SessionEnding= '' App_SessionEnding '' > < Application.Resources > < /Application.Resources > < /Application >",Code to run when app closes "C_sharp : Based on this question I decided to sign emails send from ASP.NET.MVC to decrease SPAM score of emails , but I have some bug somewhere.Code : I check the result on http : //www.isnotspam.com , the output is following : My DNS record is : UPDATE : I fix some issues in DNS record and I have found better online checker at dkimcore.orgI still face validation issue of my public key . I generated 1024 RSA using puttyGen ( ppk ) and convert it to RSA format . The original file from PuttyGen is : So I just copy the content ( except the commented lines ) to DNS record and I got following output from checker : public void SendEmail ( MailMessage mailMessage ) { string domain = `` kup-nemovitost.cz '' ; var message = MimeMessage.CreateFromMailMessage ( mailMessage ) ; HeaderId [ ] headers = new HeaderId [ ] { HeaderId.From , HeaderId.Subject , HeaderId.Date } ; DkimCanonicalizationAlgorithm headerAlgorithm = DkimCanonicalizationAlgorithm.Relaxed ; DkimCanonicalizationAlgorithm bodyAlgorithm = DkimCanonicalizationAlgorithm.Relaxed ; string dkimPath = Path.Combine ( ConfigHelper.GetDataPath ( ) , `` DKIM '' ) ; string privateKey = Path.Combine ( dkimPath , `` kup-nemovitost.cz.private.rsa '' ) ; DkimSigner signer = new DkimSigner ( privateKey , domain , `` mail '' ) { SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha1 , AgentOrUserIdentifier = `` @ '' + domain , QueryMethod = `` dns/txt '' , } ; message.Prepare ( EncodingConstraint.SevenBit ) ; message.Sign ( signer , headers , headerAlgorithm , bodyAlgorithm ) ; using ( var client = new MailKit.Net.Smtp.SmtpClient ( ) ) { client.Connect ( `` localhost '' , 25 , false ) ; client.Send ( message ) ; client.Disconnect ( true ) ; } } DKIM check details : -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Result : invalidID ( s ) verified : header.From=no-reply @ kup-nemovitost.czSelector=maildomain=kup-nemovitost.czDomainKeys DNS Record=mail._domainkey.kup-nemovitost.cz @ IN TXT `` v=dkim1 ; s=mail ; p=migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdnov2pxnjmghdpxw5wpypk1rf7 kxs+5ouvh6f0hraryncku6wbvq+xovbgxz1kuddcb/s9o8wquftxrlffniik3wbm qc+upm+ndloxcxwy0bb2iktbgnmndjiexm/z0npaviwzebr2k6vqdzbp+lmcuece bwasqgw2fki5ospb4qidaqab '' -- -- BEGIN SSH2 PUBLIC KEY -- -- Comment : `` rsa-key-20170606 '' AAAAB3NzaC1yc2EAAAABJQAAAIEAiyEwx+Idlf/Qp2fTYrQMwV3MuF9W7yaKDMHkhzoH+MqWKtNDngQoJcmbyrkMeF0VLYo246ma3gPZh9cDL7i8ygOYKagbyUjgtZFzy+et0tY/+G/IZNaHiQp0QuG/J71uZrl4Jlgkq+0s5bZxpRR45aRpcG1HQMIm6Ku7lgmOt88= -- -- END SSH2 PUBLIC KEY -- -- p= AAAAB3NzaC1yc2EAAAABJQAAAIEAiyEwx+Idlf/Qp2fTYrQMwV3MuF9W7yaKDMHkhzoH+MqWKtNDngQoJcmbyrkMeF0VLYo246ma3gPZh9cDL7i8ygOYKagbyUjgtZFzy+et0tY/+G/IZNaHiQp0QuG/J71uZrl4Jlgkq+0s5bZxpRR45aRpcG1HQMIm6Ku7lgmOt88=This does n't seem to be a valid RSA public key : RSA.xs:178 : OpenSSL error : wrong tag at blib/lib/Crypt/OpenSSL/RSA.pm ( autosplit into blib/lib/auto/Crypt/OpenSSL/RSA/new_public_key.al ) line 91 .",Signing email in C # "C_sharp : I have a project using Entity Framework Code First version 6 with Lazy loading . At the model level it has a Course which has Modules . The course class is declared as follows : My Module class is declared as follows : The BaseEntity class they both inherit from is just to reduce code duplication for common application properties . It declares the primary key for all entities as such : I can include more details on it if relevant but I ca n't see how they 'd interfere and there is a bunch of off topic framework stuff there.When I load the view to edit a Course that already exists in the database the Modules property of the Course is always null when consumed in an MVC view even when there should be records . For example editing course with id 3 has a null Modules property despite the fact there are several modules with a Course ID of 3.The inverse navigation of the relationship DOES however work . If I go to the view to edit Module id 5 it 's Course property is set as expected and I can access the Course values . This module is linked to Course ID 3.My Entity Framework Code First is using default configuration i.e . Lazy Loading is enabled . I have verified this by inspecting the debugger values of the DBContext but also that explains why the Course property is working from the Module to the Course automatically.What are the possible causes of the relationship working from the Module to the Course but not from the Course to the Modules collection ? As you can see from the commented code in the Course class , I had it handling the null situation previously by ensuring the Modules property was never null but that only matters when there are no Modules for a course which is n't the case here so I have tried changing this back to the basic ICollection property to rule it out as a problem.I have also debugged when the DBContext is being disposed and it is definitely after the view code has run so there is no danger of the DBContext being disposed before the Collection is accessed.I am not interested in explicitly using Include statements . I want to use lazy loading and EF to automatically get the data and I am aware of the implications this has on performance etc.Ideally I do n't want to have to describe the relationship to Entity Framework beyond the use of the properties above . If I have to I can , but please explain why as I 'm sure I have successfully done this simple parent - Child , 1 - many relationship before without problem.UPDATE 1Controller action code is as followsIf I debug after the following line and inspect the property it gets automically populated as expected.As @ Zaphod commented it looks like the DB connection is closed before the view starts rendering . I do n't understand why that happens since we 're still server side and have n't yet returned the markup to the browser . Is there a way to enable lazy loading within views and only close the connection when the controller is disposed ? Update 2The actual GetID code : DbSet is correspondingly set in the constructor of the Controller to point to the DbSet on the DbContext : I ca n't see how the DbSet would somehow break queries between the last line of the controller action calling the view and the view starting to run.Update 3I should have included details of where the DbContext is created which is in the inherited controller constructor : This is only disposed once in the inherited controller 's Dispose method which is not being called until AFTER the view has rendered : I still do n't understand why the inverse relationship scenario would work fine as it should be lazy loading in the view for it as it all uses the same framework . public class Course : BaseEntity { public String Title { get ; set ; } public String Description { get ; set ; } public int Revision { get ; set ; } //private IList < Module > _modules ; //public virtual IList < Module > Modules // { // get { return _modules ? ? ( _modules = new List < Module > ( ) ) ; } // set { _modules = value ; } // } public virtual ICollection < Module > Modules { get ; set ; } } public class Module : BaseEntity { [ ForeignKey ( `` Course '' ) ] public Int64 CourseID { get ; set ; } public virtual Course Course { get ; set ; } public String Title { get ; set ; } public Int32 SequenceNo { get ; set ; } public override string HumanDisplay { get { return Title ; } } private IList < ModuleItem > _items ; public virtual IList < ModuleItem > Items { get { return _items ? ? ( _items = new List < ModuleItem > ( ) ) ; } set { _items = value ; } } } [ Key ] [ DatabaseGeneratedAttribute ( DatabaseGeneratedOption.Identity ) ] public Int64 Id { get ; set ; } public virtual ActionResult Edit ( long id = 0 ) { if ( Session.GetUser ( ) .GetCombinedPrivilegeForEntity ( Entity ) .CanRead ) { String saveSuccess = TempData [ `` successMessage '' ] as String ; currentModel = GetID ( id ) ; if ( currentModel == null ) throw new RecordNotFoundException ( id , typeof ( Model ) .Name ) ; currentVM = Activator.CreateInstance < ViewModel > ( ) ; currentVM.Model = currentModel ; currentVM.DB = DB ; currentVM.ViewMode = ViewMode.Edit ; currentVM.SuccessMessage = saveSuccess ; SetViewModelPermissions ( ) ; //Cache.AddEntry ( Session.SessionID , Entity , currentVM.Model.Id , currentVM ) ; if ( currentModel == null ) { return HttpNotFound ( ) ; } if ( ForcePartial || Request.IsAjaxRequest ( ) ) return PartialView ( GetViewName ( `` Edit '' ) , currentVM ) ; else return View ( GetViewName ( `` Edit '' ) , MasterName , currentVM ) ; } else { throw new PermissionException ( `` read '' , Entity ) ; } } currentModel = GetID ( id ) ; protected virtual Model GetID ( long id = 0 ) { return DbSet.Find ( id ) ; } public CourseController ( ) : base ( ) { this.DbSet = DB.Courses ; } public ApplicationCRUDController ( ) : base ( ) { this.DB = eLearn.Models.DbContext.CreateContext ( Session ) ; } protected override void Dispose ( bool disposing ) { if ( DB ! = null ) DB.Dispose ( ) ; base.Dispose ( disposing ) ; }",Entity Framework Code First Child Navigation Property null C_sharp : If I ask ReSharper to reformat the current code : Then it reformats it like this : I can at most coax it to line up the braces with the delegate keyword . Is there any way I can coax it into indenting it back to the original way ? SomeMethodThatIsGivenAnAnonymousMethod ( delegate { Test ( ) ; } ) ; SomeMethodThatIsGivenAnAnonymousMethod ( delegate { Test ( ) ; } ) ;,ReSharper configuration for indentation of anonymous methods ? "C_sharp : While I playing with the C # 4.0 dynamic , I found strange things happening with the code like this : Ok , it works but ... take a look at IntelliTrace window : screenshot http : //img717.imageshack.us/img717/4914/10435230.pngSo every invokation ( and other operations too on dynamic object ) causes throwing and catching strange exceptions twice ! I understand , that sometimes exceptions mechanism may be used for optimizations , for example first call to dynamic may be performed to some stub delegate , that simply throws exception - this may be like a signal to dynamic binder to resolve an correct member and re-point delegate . Next call to the same delegate will be performed without any checks.But ... behavior of the code above looks very strange . Maybe throwing and catching exceptions twice per any operation on DynamicObject - is a bug ? using System.Dynamic ; sealed class Foo : DynamicObject { public override bool TryInvoke ( InvokeBinder binder , object [ ] args , out object result ) { result = new object ( ) ; return true ; } static void Main ( ) { dynamic foo = new Foo ( ) ; var t1 = foo ( 0 ) ; var t2 = foo ( 0 ) ; var t3 = foo ( 0 ) ; var t4 = foo ( 0 ) ; var t5 = foo ( 0 ) ; } }",System.Dynamic bug ? C_sharp : is it possible to run some of my PLINQ AsParallel ( ) - Queries with a lower priority than others ? ( Or some with a higher priority than others ) Is this possible with PLinq or will I have to avoid PLINQ and do all the stuff on my own ? EDIT/UPDATE : Would it be possible to callinside the parallel executed method when I want to archive a lower priority ? Or is that a very bad practice/hack ? Thread.Sleep ( 0 ),PLINQ AsParallel ( ) with lower priority ? "C_sharp : I 've been looking for a solution for my problem since yesterday . Im building a problem with MVVM pattern.I got two usercontrol , which are both containing a listbox . The first usercontrol is called the SearchView which contains a listbox of project names , which the user can select and save to the applications local db.When the selected projects are added a event is fired which notify the 2nd usercontrol which is named `` ProjectView '' . This usercontrol simply shows which projects are saved locally . Seen at the picture below.The problem is that i want to be able sort the listbox ascending by name in the projectview . So that if the user first add `` Test Project 2 '' and afterwords add `` Test Project 1 '' the `` Test Project 1 '' is shown in the top of the listbox.I have tried to use ICollectionView and ListCollectionView but im very really confused at the moment.So now my Code looks like this , in the ProjectViewModel which needs to sort the listbox : XAML code : Thanks in advance public ProjectViewModel ( ) { this.collectionView = CollectionViewSource.GetDefaultView ( this.Projects ) ; } private ObservableCollection < ProjectWrapper > _project = new ObservableCollection < ProjectWrapper > ( ) ; public ObservableCollection < ProjectWrapper > Projects { get { return _project ; } set { _project = value ; OnPropertyChanged ( `` Projects '' ) ; } } < UserControl.Resources > < CollectionViewSource x : Key= '' cvs '' Source= '' { Binding Path=Projects } '' > < CollectionViewSource.SortDescriptions > < scm : SortDescription PropertyName= '' ProjectWrapper.Project.Name '' / > < /CollectionViewSource.SortDescriptions > < /CollectionViewSource > < /UserControl.Resources > < ListBox Name= '' ProjectsList '' ItemsSource= '' { Binding Source= { StaticResource cvs } } '' SelectedItem= '' { Binding Path=SelectedProject } '' HorizontalContentAlignment= '' Stretch '' BorderThickness= '' 0 '' Grid.Row= '' 1 '' Grid.RowSpan= '' 3 '' Margin= '' 0,0.4 , -0.2,27.8 '' > < ListBox.ItemTemplate > < DataTemplate > < DockPanel > < TextBlock Text= '' { Binding Path=ProjectModel.Name } '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Center '' Padding= '' 3,2,0,0 '' / > < CheckBox IsChecked= '' { Binding Path=IsSelected , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' HorizontalAlignment= '' Right '' VerticalAlignment= '' Center '' Padding= '' 0,2,5,0 '' Margin= '' 0,2.5,0,0 '' / > < /DockPanel > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox >",Sorting a listbox when a button gets clicked using MVVM "C_sharp : A while ago we started to replace our logger from log4net to Serilog in order to send our logs straight to our Elastic . In our project we are working with IOC using Autofac . As so , we initially created a wrapper class ( LogSerilog ) and a corresponding interface ( ILogSerilog ) which we added to our builder , when in the class LogSerilog we configured the root logger . After that I saw the autofac-serilog-integration Nuget which seem like the best solution for me.because it will wire all the context for us . The problem is that it seem it does n't work.Even more , the log4net sink ( we are still using log4net to have a copy of the logs in the machine ) does n't work as well ! I feel like I 'm doing some thing wrong here - but I 'm not sure how should I fix it . If I will remove the wrrapper class , where should I config the root logger ? Is the problem with the log4net sink has nothing to do with the wrapper class ? Any other tip if you see I 'm approaching it in the wrong way would be welcomed . public class LogSerilog : ILogSerilog { private readonly IElasticConfiguration configuration ; public LogSerilog ( IElasticConfiguration configuration ) { this.configuration = configuration ; Init ( ) ; } public void Init ( ) { var logger = new LoggerConfiguration ( ) .MinimumLevel.Information ( ) .Enrich.WithMachineName ( ) ; try { logger.WriteTo.Elasticsearch ( this.configuration.GetElasticPath ( ) , typeName : `` Serilog '' ) ; } catch ( Exception ) { //Swallow - Elastic is N/A do n't wa n't to crash . logging wo n't help since I do n't have logger yet : ) } logger.WriteTo.Log4Net ( ) ; Log.Logger = logger.CreateLogger ( ) ; } ... ... ... .",How to use Autofac with a Serilog wrapper class "C_sharp : Assume I have a table called Population that stores some demographic data . In T-SQL , to get the count of people over 50 , I might do something like this : I thought the following linq statement would work , but it just returns zero and I do n't understand why.In order for me to actually get the count , I have to do either of the following : Why are the above scenarios the case ? SELECT COUNT ( * ) FROM POPULATIONWHERE AGE > 50 var count = _context.Population.Count ( x = > x.Age > 50 ) ; var count = _context.Populaton.Where ( x = > x.Age > 50 ) .Count ( ) ; var count = _context.Population.Select ( x = > x.Age > 50 ) .Count ( ) ;",Does Linq retrieve all records first if I do a Count ? "C_sharp : I am working with Moles and mocking a System.Data.Linq.Table.I got it constructing fine , but when I use it , it wants IQueryable.Provider to be mocked ( moled ) as well.I just want it to use normal Linq To Objects . Any idea what that would be ? Here is the syntax I can use : MTable < User > userTable = new System.Data.Linq.Moles.MTable < User > ( ) ; userTable.Bind ( new List < User > { UserObjectHelper.TestUser ( ) } ) ; // this is the line that needs helpMolesDelegates.Func < IQueryProvider > provider = //Insert provider here ! ^userTable.ProviderSystemLinqIQueryableget = provider | | | what can I put here ? -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +",What to put as the Provider for a mocked IQueryable "C_sharp : I 'm using jqueryui autocomplete to assist user in an item selection . I 'm having trouble selecting the correct items from the objects ' subcollections.Object structure ( simplified ) isCurrently I 'm doing this with nested foreach loops , but is there a better way ? Current code : public class TargetType { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < SubCategory > SubCategories { get ; set ; } public TargetType ( ) { SubCategories = new HashSet < SubCategory > ( ) ; } } public class SubCategory { public int Id { get ; set ; } public string Name { get ; set ; } public virtual ICollection < SubTargetType > SubTargetTypes { get ; set ; } public SubCategory ( ) { SubTargetTypes = new HashSet < SubTargetType > ( ) ; } } List < SubTargetResponse > result = new List < SubTargetResponse > ( ) ; foreach ( SubCategory sc in myTargetType.SubCategories ) { foreach ( SubTargetType stt in sc.SubTargetTypes ) { if ( stt.Name.ToLower ( ) .Contains ( type.ToLower ( ) ) ) { result.Add ( new SubTargetResponse { Id = stt.Id , CategoryId = sc.Id , Name = stt.Name } ) ; } } }",LINQ select all items of all subcollections that contain a string "C_sharp : I use the following code for shutdown the own System.It was working Fine.And I need to shut down another System , which is connected in LAN Connection . I 'm unable to do it with this code . How to Shutdown another System using shutdown.exe ? My OS is windows7 . using System.Diagnostics ; protected void Button1_Click ( object sender , EventArgs e ) { Process.Start ( `` shutdown.exe '' , `` -s -t 00 '' ) ; }",Shutdown another System using shutdown.exe in C # ? C_sharp : I suppose this is a very silly question but I 've been looking around and could n't find answers on the following questions . Really appreciate answers shedding light on this.1 ) What happens to the previous object if instantiating a new one within the same method . Example:2 ) Same question as ( 1 ) but on static variable . Example : Thanks ! DataTable dataTable = new DataTable ( ) ; dataTable = new DataTable ( ) ; // Will the previously created object be destroyed and memory freed ? static private DataView dataView ; private void RefreshGridView ( ) { dataView = new DataView ( GetDataTable ( ) ) ; // Will the previously created objects be destroyed and memory freed ? BindGridView ( ) ; },Creating new objects repeatedly on same variable C_sharp : If I haveWill calls to new Child1 ( ) .Method1 ( ) and new Child2 ( ) .Method1 ( ) use the same lock ? abstract class Parent { static object staticLock = new object ( ) ; public void Method1 ( ) { lock ( staticLock ) { Method2 ( ) ; } } protected abstract Method2 ( ) ; } class Child1 : Parent { protected override Method2 ( ) { // Do something ... } } class Child2 : Parent { protected override Method2 ( ) { // Do something else ... } },Do static locks work across different children classes ? "C_sharp : I am getting started on the Moq framework and absolutely love it . I am writing some controller tests that have several services and interfaces to Arrange my controller for the test . I 'd love to modularize it a bit more , and thought this would be a trivial task , but it turns out to be a bit trickier than I thought . Here is one simple unit test that I have to show an example : What I 'd like to be able to do is take everything in the # region and extract that out into a helper method or [ Setup ] method , but if I do that , then I do n't have access to each mock service to setup expectations . Is there something I 'm missing here , or do I really have to copy-and-paste this chunk of Arrange code in each Unit test ? [ Test ] public void Get_SignIn_Should_Return_View ( ) { # region //TODO : figure out how to extract this out to avoid duplicate code // Arrange var membershipService = new Mock < IMembershipService > ( ) ; var formsService = new Mock < IFormsAuthenticationService > ( ) ; var userService = new Mock < IUserService > ( ) ; var dictService = new Mock < IDictionaryService > ( ) ; var shoppingBasketService = new Mock < IShoppingBasketService > ( ) ; //Create the service provider mock and pass in the IRepositoryFactory so that it is n't instantiating real repositories var repoFactory = new Mock < IRepositoryFactory > ( ) ; var serviceProvider = new Mock < ServiceProvider > ( ( IRepositoryFactory ) repoFactory.Object ) ; var context = new Mock < HttpContextBase > { DefaultValue = DefaultValue.Mock } ; var sessionVars = new Mock < SessionVars > ( ) ; AccountController controller = new AccountController ( serviceProvider.Object , sessionVars.Object ) { FormsService = formsService.Object , MembershipService = membershipService.Object , UserService = userService.Object , DictionaryService = dictService.Object , ShoppingService = shoppingBasketService.Object } ; controller.ControllerContext = new ControllerContext ( ) { Controller = controller , RequestContext = new RequestContext ( context.Object , new RouteData ( ) ) } ; # endregion // Act ActionResult result = controller.SignIn ( ) ; // Assert Assert.IsInstanceOf < ViewResult > ( result ) ; }",Moq controller tests with repeated setup C_sharp : Is there any way one can apply a function with signatureto an array of integers and return whether any given integer in that array is odd in a single instruction ? I know I can usebut that implies calling two methods and making a comparison ... Is n't there really a shorter way to achieve the same ? bool IsOdd ( int number ) ; return ( array.Where ( IsOdd ) .Count ( ) > 0 ) ;,Linq & Boolean Function "C_sharp : I 've the following classes : As you can see , I have a list of events inside a Sequence . I have a list of Sequence.I want to show a ListView with a GridView with the list of sequences . For each sequence I want to have 2 columns , one with the value of the property freq and the other one should have the list of events associated with that sequence . For example : where the first line is related to the first sequence . The color of the rectangle represents the event 's type . In the first sequence there are the following events : eserc 1 of type `` red '' eserc 2 of type `` red '' eserc 3 of type `` green '' eserc 4 of type `` red '' I know that I have to do the binding to display values , but I do n't know how to do it for the sequences , because I should bind the value of the column to the values of the Event objects within each single Sequence.That 's the code that I wrote for the ListView : Of course , Binding events is wrong because that would work only if it was a string , but that 's the idea . I searched on internet and I think that I should use something like DataTemplate , but I 'm not sure about that and I did n't understand well how that works . I understood that it works when the source is an object , but in this case it 's a List of objects and I do n't know how to get the information . class Event { int eserc { get ; set ; } int type { get ; set ; } } class Sequence { List < Event > events ; int freq { get ; set ; } } < ListView Name= '' resultsList '' Grid.Row= '' 5 '' Grid.Column= '' 1 '' Grid.ColumnSpan= '' 3 '' > < ListView.View > < GridView > < GridViewColumn Header= '' Sequence '' Width= '' 450 '' DisplayMemberBinding= '' { Binding events } '' / > < GridViewColumn Header= '' Frequence '' DisplayMemberBinding= '' { Binding freq } '' / > < /GridView > < /ListView.View > < /ListView >",Binding ListView field to a nested list WPF "C_sharp : I have a LINQ statement as follows : This fails because split function fails on IpAddresses as LINQ to Entities can not translate this query to SQL . This makes sense , but then what 's an equivalent way of accomplishing this elegantly ? The only way I 've thought of is to manually run a loop on the retrieved string then splitting it , but I 'd like to get it in one go . var playedBanDataList = from bannedPlayers in query select new PlayerBanData { Admin = bannedPlayers.Admin , BannedUntil = bannedPlayers.BannedUntil , IsPermanentBan = bannedPlayers.IsPermanentBan , PlayerName = bannedPlayers.PlayerName , Reason = bannedPlayers.Reason , IpAddresses = bannedPlayers.IpAddresses.Split ( new [ ] { `` , '' } , StringSplitOptions.RemoveEmptyEntries ) .ToList ( ) } ; return playedBanDataList.ToList ( ) ;",LINQ to Entities split string on result "C_sharp : I have written a custom configuration provider to load ASP.NET Core configuration from a database table as per the instructions here : ASP.Net Custom Configuration ProviderMy provider uses SqlDependency to reload configuration should the values in the database change.The documentation for SqlDependency states that : The Stop method must be called for each Start call . A given listener only shuts down fully when it receives the same number of Stop requests as Start requests.What I 'm not sure about is how to do this within a custom configuration provider for ASP.NET Core.Here we go with the code : DbConfigurationSourceBasically a container for IDbProvider which handles retrieving the data from the databaseDbConfigurationDataProviderThis is the class that creates and watches the SqlDependency and loads in the data from the database . This is also where the Dispose ( ) call is where I want to Stop ( ) the SqlDependency . Dispose ( ) is not currently called.DbConfigurationProviderThis class monitors the changeToken in DbConfigurationDataProvider and publishes the new configuration to the application.DbConfigurationExtensionsThe extension method called to set everything up . Finally , the call to set the whole thing up : To summarise : How do I ensure the Dispose ( ) method is called within the DbConfigurationDataProvider class ? The only information I have found so far is from here : https : //andrewlock.net/four-ways-to-dispose-idisposables-in-asp-net-core/Which covers how to dispose of objects : Within code blocks with the using statement ( Not Applicable ) At the end of a request ( Not Applicable ) Using the DI container ( Not Applicable - I do n't think ? ) When the application ends < -- Sounds promisingOption 4 looks like this : SingletonAddedManually in my case would be the DbConfigurationDataProvider class , but this is very much out of scope from the Startup class.More information on the IApplicationLifetime interface : https : //docs.microsoft.com/en-us/aspnet/core/fundamentals/host/web-host ? view=aspnetcore-2.2EDITThis example does n't even bother calling SqlDependency.Stop ( ) , maybe it is n't that important ? https : //docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqldependency-in-an-aspnet-app public class DbConfigurationSource : IConfigurationSource { /// < summary > /// Used to access the contents of the file . /// < /summary > public virtual IDbProvider DbProvider { get ; set ; } /// < summary > /// Determines whether the source will be loaded if the underlying data changes . /// < /summary > public virtual bool ReloadOnChange { get ; set ; } /// < summary > /// Will be called if an uncaught exception occurs in FileConfigurationProvider.Load . /// < /summary > public Action < DbLoadExceptionContext > OnLoadException { get ; set ; } public IConfigurationProvider Build ( IConfigurationBuilder builder ) { return new DbConfigurationProvider ( this ) ; } } public class DbConfigurationDataProvider : IDbProvider , IDisposable { private readonly string _applicationName ; private readonly string _connectionString ; private ConfigurationReloadToken _reloadToken ; public DbConfigurationDataProvider ( string applicationName , string connectionString ) { if ( string.IsNullOrWhiteSpace ( applicationName ) ) { throw new ArgumentNullException ( nameof ( applicationName ) ) ; } if ( string.IsNullOrWhiteSpace ( connectionString ) ) { throw new ArgumentNullException ( nameof ( connectionString ) ) ; } _applicationName = applicationName ; _connectionString = connectionString ; _reloadToken = new ConfigurationReloadToken ( ) ; SqlDependency.Start ( _connectionString ) ; } void OnDependencyChange ( object sender , SqlNotificationEventArgs e ) { var dependency = ( SqlDependency ) sender ; dependency.OnChange -= OnDependencyChange ; var previousToken = Interlocked.Exchange ( ref _reloadToken , new ConfigurationReloadToken ( ) ) ; previousToken.OnReload ( ) ; } public IChangeToken Watch ( ) { return _reloadToken ; } public List < ApplicationSettingDto > GetData ( ) { var settings = new List < ApplicationSettingDto > ( ) ; var sql = `` select parameter , value from dbo.settingsTable where application = @ application '' ; using ( var connection = new SqlConnection ( _connectionString ) ) { using ( var command = new SqlCommand ( sql , connection ) ) { command.Parameters.AddWithValue ( `` application '' , _applicationName ) ; var dependency = new SqlDependency ( command ) ; // Subscribe to the SqlDependency event . dependency.OnChange += OnDependencyChange ; connection.Open ( ) ; using ( var reader = command.ExecuteReader ( ) ) { var keyIndex = reader.GetOrdinal ( `` parameter '' ) ; var valueIndex = reader.GetOrdinal ( `` value '' ) ; while ( reader.Read ( ) ) { settings.Add ( new ApplicationSettingDto { Key = reader.GetString ( keyIndex ) , Value = reader.GetString ( valueIndex ) } ) ; } } } } Debug.WriteLine ( $ '' { DateTime.Now } : { settings.Count } settings loaded '' ) ; return settings ; } public void Dispose ( ) { SqlDependency.Stop ( _connectionString ) ; Debug.WriteLine ( $ '' { nameof ( WhsConfigurationProvider ) } Disposed '' ) ; } } public class DbConfigurationProvider : ConfigurationProvider { private DbConfigurationSource Source { get ; } public DbConfigurationProvider ( DbConfigurationSource source ) { Source = source ? ? throw new ArgumentNullException ( nameof ( source ) ) ; if ( Source.ReloadOnChange & & Source.DbProvider ! = null ) { ChangeToken.OnChange ( ( ) = > Source.DbProvider.Watch ( ) , ( ) = > { Load ( reload : true ) ; } ) ; } } private void Load ( bool reload ) { // Always create new Data on reload to drop old keys if ( reload ) { Data = new Dictionary < string , string > ( StringComparer.OrdinalIgnoreCase ) ; } var settings = Source.DbProvider.GetData ( ) ; try { Load ( settings ) ; } catch ( Exception e ) { HandleException ( e ) ; } OnReload ( ) ; } public override void Load ( ) { Load ( reload : false ) ; } public void Load ( List < ApplicationSettingDto > settings ) { Data = settings.ToDictionary ( s = > s.Key , s = > s.Value , StringComparer.OrdinalIgnoreCase ) ; } private void HandleException ( Exception e ) { // Removed for brevity } } public static class DbConfigurationExtensions { public static IConfigurationBuilder AddDbConfiguration ( this IConfigurationBuilder builder , IConfiguration config , string applicationName = `` '' ) { if ( string.IsNullOrWhiteSpace ( applicationName ) ) { applicationName = config.GetValue < string > ( `` ApplicationName '' ) ; } // DB Server and Catalog loaded from Environment Variables for now var server = config.GetValue < string > ( `` DbConfigurationServer '' ) ; var database = config.GetValue < string > ( `` DbConfigurationDatabase '' ) ; if ( string.IsNullOrWhiteSpace ( server ) ) { // Removed for brevity } if ( string.IsNullOrWhiteSpace ( database ) ) { // Removed for brevity } var sqlBuilder = new SqlConnectionStringBuilder { DataSource = server , InitialCatalog = database , IntegratedSecurity = true } ; return builder.Add ( new DbConfigurationSource { DbProvider = new DbConfigurationDataProvider ( applicationName , sqlBuilder.ToString ( ) ) , ReloadOnChange = true } ) ; } } public class Program { public static void Main ( string [ ] args ) { CreateWebHostBuilder ( args ) .Build ( ) .Run ( ) ; } public static IWebHostBuilder CreateWebHostBuilder ( string [ ] args ) = > WebHost.CreateDefaultBuilder ( args ) .ConfigureAppConfiguration ( ( hostingContext , config ) = > { config.AddDbConfiguration ( hostingContext.Configuration , `` TestApp '' ) ; } ) .UseStartup < Startup > ( ) ; } public void Configure ( IApplicationBuilder app , IApplicationLifetime applicationLifetime , SingletonAddedManually toDispose ) { applicationLifetime.ApplicationStopping.Register ( OnShutdown , toDispose ) ; // configure middleware etc } private void OnShutdown ( object toDispose ) { ( ( IDisposable ) toDispose ) .Dispose ( ) ; }",Stop SqlDependency in custom ASP.NET Core Configuration Provider "C_sharp : This is a resource-allocation problem . My goal is to run a query to fetch the top-priority shift for any time-slot.The dataset is very large . For this example , let ’ s say there are 100 shifts each for 1000 companies ( though the real dataset is even larger ) . They are all loaded into memory , and I need to run a single LINQ to Objects query against them : The problem is that without optimization , LINQ to Objects will compare each and every object in both sets , doing a cross-join of all 1,000 x 100 against 1,000 x 100 , which amounts to 10 billion ( 10,000,000,000 ) comparisons . What I want is to compare only objects within each company ( as if Company were indexed in a SQL table ) . This should result in 1000 sets of 100 x 100 objects for a total of 10 million ( 10,000,000 ) comparisons . The later would scale linearly rather than exponentially as the number of companies grows.Technologies like I4o would allow me to do something like this , but unfortunately , I don ’ t have the luxury of using a custom collection in the environment in which I ’ m executing this query . Also , I only expect to run this query once on any given dataset , so the value of a persistent index is limited . I ’ m expecting to use an extension method which would group the data by company , then run the expression on each group.Full Sample code : Sample output : 1000 Companies x 100 Shifts Populating data Completed in 10.00ms Computing Top Shifts Completed in 520,721.00ms Shifts : C 0 Id 0 T 0 P0 C 0 Id 1 T 0 P1 C 0 Id 2 T 0 P2 C 0 Id 3 T 1 P3 C 0 Id 4 T 1 P4 C 0 Id 5 T 1 P0 C 0 Id 6 T 2 P1 C 0 Id 7 T 2 P2 C 0 Id 8 T 2 P3 C 0 Id 9 T 3 P4 C 0 Id 10 T 3 P0 C 0 Id 11 T 3 P1 C 0 Id 12 T 4 P2 C 0 Id 13 T 4 P3 C 0 Id 14 T 4 P4 C 0 Id 15 T 5 P0 C 0 Id 16 T 5 P1 C 0 Id 17 T 5 P2 C 0 Id 18 T 6 P3 C 0 Id 19 T 6 P4 Top Shifts : C 0 Id 0 T 0 P0 C 0 Id 5 T 1 P0 C 0 Id 6 T 2 P1 C 0 Id 10 T 3 P0 C 0 Id 12 T 4 P2 C 0 Id 15 T 5 P0 C 0 Id 20 T 6 P0 C 0 Id 21 T 7 P1 C 0 Id 25 T 8 P0 C 0 Id 27 T 9 P2 Total Comparisons : 10,000,000,015.00 Any key to continueQuestions : How can I partition the query ( while still executing as a single LinQ query ) in order to get the comparisons down from 10 billion to 10 million ? Is there a more efficient way of solving the problem instead of a sub-query ? var topShifts = ( from s in shifts where ( from s2 in shifts where s2.CompanyId == s.CompanyId & & s.TimeSlot == s2.TimeSlot orderby s2.Priority select s2 ) .First ( ) .Equals ( s ) select s ) .ToList ( ) ; public struct Shift { public static long Iterations ; private int companyId ; public int CompanyId { get { Iterations++ ; return companyId ; } set { companyId = value ; } } public int Id ; public int TimeSlot ; public int Priority ; } class Program { static void Main ( string [ ] args ) { const int Companies = 1000 ; const int Shifts = 100 ; Console.WriteLine ( string.Format ( `` { 0 } Companies x { 1 } Shifts '' , Companies , Shifts ) ) ; var timer = Stopwatch.StartNew ( ) ; Console.WriteLine ( `` Populating data '' ) ; var shifts = new List < Shift > ( ) ; for ( int companyId = 0 ; companyId < Companies ; companyId++ ) { for ( int shiftId = 0 ; shiftId < Shifts ; shiftId++ ) { shifts.Add ( new Shift ( ) { CompanyId = companyId , Id = shiftId , TimeSlot = shiftId / 3 , Priority = shiftId % 5 } ) ; } } Console.WriteLine ( string.Format ( `` Completed in { 0 : n } ms '' , timer.ElapsedMilliseconds ) ) ; timer.Restart ( ) ; Console.WriteLine ( `` Computing Top Shifts '' ) ; var topShifts = ( from s in shifts where ( from s2 in shifts where s2.CompanyId == s.CompanyId & & s.TimeSlot == s2.TimeSlot orderby s2.Priority select s2 ) .First ( ) .Equals ( s ) select s ) .ToList ( ) ; Console.WriteLine ( string.Format ( `` Completed in { 0 : n } ms '' , timer.ElapsedMilliseconds ) ) ; timer.Restart ( ) ; Console.WriteLine ( `` \nShifts : '' ) ; foreach ( var shift in shifts.Take ( 20 ) ) { Console.WriteLine ( string.Format ( `` C { 0 } Id { 1 } T { 2 } P { 3 } '' , shift.CompanyId , shift.Id , shift.TimeSlot , shift.Priority ) ) ; } Console.WriteLine ( `` \nTop Shifts : '' ) ; foreach ( var shift in topShifts.Take ( 10 ) ) { Console.WriteLine ( string.Format ( `` C { 0 } Id { 1 } T { 2 } P { 3 } '' , shift.CompanyId , shift.Id , shift.TimeSlot , shift.Priority ) ) ; } Console.WriteLine ( string.Format ( `` \nTotal Comparisons : { 0 : n } '' , Shift.Iterations/2 ) ) ; Console.WriteLine ( `` Any key to continue '' ) ; Console.ReadKey ( ) ; } }",How to partition a LINQ to Objects query ? "C_sharp : While trying to familiarize myself with c++ and its concepts , I came across the and my simple code is as followsUsing Visual Studio 2015 Community , which uses intellisense , shows coutuses the following std : :ostream std : :coutAs a C # programmer , this confuses me slightly . Is this : std : :ostreambeing a return type while std : :coutbeing the method/parameter passed or is std : :ostreama dependancy of coutUPDATE ( after Archimaredes Answer ) In C # , one can use the following : oror one can use : Each case a object of type namely is assignable with a new object or a existing file or a networkstream.I tried the same after that which you mentioned ( excuse the C # mentality ) with the std : :ostream x = new std : ostream which returns a no default constructor.Could you just add how std : :ostream and std : :cout relate to each other , which creates/initalizes the other . THis concept is still a bit vague to me . using namespace std # include < iostream > # include `` stdafx.h '' # include `` ConsoleApplication5.h '' # include < iostream > int main ( ) { std : :cout < < `` hi '' ; return 0 ; } StreamWriter srWrite ; StreamWriter srWrite = new StreamWriter ( string filepath ) StreamWriter srWrite = new StreamWriter ( new NetworkStream ( Socket.GetStream ( ) ) ) ; StreamWriter",c++ - using std namespace and dependancies "C_sharp : I used the common impersonation code and it worked just fine , until I inserted random 'dggdgsdg ' in domain - and it worked nonetheless ... I used some TestUser on my domain , and it worked . I then switched domain , to random nonsense 'werwerhrg ' , and it impersonated the TestUser on my domain ! Why ? I would expect an exception to be thrown , why on earth is it working ? if ( LogonUser ( Username , Domain , Password , Logon32LogonInteractive , Logon32ProviderDefault , ref existingTokenHandle ) & & DuplicateToken ( existingTokenHandle , ( int ) SecurityImpersonationLevel.SecurityDelegation , ref duplicateTokenHandle ) ) { Identity = new WindowsIdentity ( duplicateTokenHandle ) ; ImpersonationContext = Identity.Impersonate ( ) ; } else { throw new Win32Exception ( Marshal.GetLastWin32Error ( ) ) ; } private const int Logon32LogonInteractive = 2 ; private const int Logon32ProviderDefault = 0 ; public enum SecurityImpersonationLevel { SecurityAnonymous = 0 , SecurityIdentification = 1 , SecurityImpersonation = 2 , SecurityDelegation = 3 } [ DllImport ( `` advapi32.dll '' , SetLastError = true , CharSet = CharSet.Unicode ) ] private static extern bool LogonUser ( String lpszUsername , String lpszDomain , String lpszPassword , int dwLogonType , int dwLogonProvider , ref IntPtr phToken ) ; [ DllImport ( `` kernel32.dll '' , CharSet = CharSet.Auto ) ] private extern static bool CloseHandle ( IntPtr handle ) ; [ DllImport ( `` advapi32.dll '' , CharSet = CharSet.Auto , SetLastError = true ) ] private static extern bool DuplicateToken ( IntPtr existingTokenHandle , int securityImpersonationLevel , ref IntPtr duplicateTokenHandle ) ;",Impersonating a user in wrong domain does n't throw exception "C_sharp : I have a C # app and I am accessing some data over REST so I pass in a URL to get a JSON payload back . I access a few different URLs programmatically and they all work fine using this code below except one call.Here is my code : where GetHTTPClient ( ) is using this code below : so as i said , the above code works fine but a bunch of different request but for one particular request , I am getting an exception inside of the call with the error : Unable to read data from the transport connection : An existing connection was forcibly closed by the remote hostI get that error after waiting for about 10 minutes . What is interesting is that if I put that same URL that is n't working into Internet Explorer directly I do get the JSON payload back ( after about 10 minutes as well ) . So i am confused at why It would work fine directly from the browser but fail when using the code above.It fails on this one request but other requests using the same code work fine programmatically.Any suggestions for things to try or things I should ask the owner of the server to check out on their end to help diagnose what is going on ? var url = `` http : //theRESTURL.com/rest/API/myRequest '' ; var results = GetHTTPClient ( ) .GetStringAsync ( url ) .Result ; var restResponse = new RestSharp.RestResponse ( ) ; restResponse.Content = results ; var _deserializer = new JsonDeserializer ( ) ; private HttpClient GetHTTPClient ( ) { var httpClient = new HttpClient ( new HttpClientHandler ( ) { Credentials = new System.Net.NetworkCredential ( `` usr '' , `` pwd '' ) , UseDefaultCredentials = false , UseProxy = true , Proxy = new WebProxy ( new Uri ( `` http : //myproxy.com:8080 '' ) ) , AllowAutoRedirect = false } ) ; httpClient.Timeout = new TimeSpan ( 0,0 , 3500 ) ; return httpClient ; } .GetStringAsync ( url ) .Result",Why would my C # app fail on this REST request but but works fine through a browser ? "C_sharp : In my unit test project I have installed AutoFixture ( v3.40.0 ) , NUnit ( v2.6.4 . ) and AutoFixtrue.NUnit2 ( v3.39.0 ) .I 'm using AutoData attribute on one of the dummy test cases , but when running the test I get the Is there anything I have n't installed or I 'm missing ? [ Test , AutoData ] public void IntroductoryTest ( int expectedNumber ) { } System.Reflection.TargetParameterCountException : Parameter count mismatch . at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck ( Object obj , BindingFlags invokeAttr , Binder binder , Object [ ] parameters , CultureInfo culture ) at System.Reflection.RuntimeMethodInfo.Invoke ( Object obj , BindingFlags invokeAttr , Binder binder , Object [ ] parameters , CultureInfo culture ) at NUnit.Core.Reflect.InvokeMethod ( MethodInfo method , Object fixture , Object [ ] args ) at NUnit.Core.TestMethod.RunTestMethod ( ) at NUnit.Core.TestMethod.RunTestCase ( TestResult testResult )",AutoFixture with NUnit and AutoData throws TargetParameterCountException "C_sharp : my web-service return json data as given below but i wanted is like as in 2nd CodeSnipts . my web-service and class as given below.but i want as my c # code for Webservice asclass ashere obj.NowShowingGetList ( ShowDate ) return ListThankyou in advance . { `` ShowID '' : 10107 , `` StartTime '' : `` 3:00 PM '' , `` MovieID '' : 13 , `` Movie '' : `` Bhaag Milkha Bhaag `` , `` Screen '' : `` CDC SCreen2 '' , `` MediaPath '' : `` bmb1_568962.jpg '' } , { `` ShowID '' : 115 , `` StartTime '' : `` 6:00 PM '' , `` MovieID '' : 13 , `` Movie '' : `` Bhaag Milkha Bhaag `` , `` Screen '' : `` CDC SCreen2 '' , `` MediaPath '' : `` bmb1_568962.jpg '' } , { `` ShowID '' : 110 , `` StartTime '' : `` 9:00 PM '' , `` MovieID '' : 13 , `` Movie '' : `` Bhaag Milkha Bhaag `` , `` Screen '' : `` CDC SCreen2 '' , `` MediaPath '' : `` bmb1_568962.jpg '' } { `` MovieID '' : 13 , `` Movie '' : `` Bhaag Milkha Bhaag `` , `` Screen '' : `` CDC SCreen2 '' , `` MediaPath '' : `` bmb1_568962.jpg '' , `` ShowInfo '' : [ { `` ShowID '' : 10107 , `` StartTime '' : `` 3:00 PM '' } , { `` ShowID '' : 115 , `` StartTime '' : `` 6:00 PM '' } , { `` ShowID '' : 110 , `` StartTime '' : `` 9:00 PM '' } ] } [ WebMethod ] public string NowShowingGetList ( DateTime ShowDate ) { HomeController obj = new HomeController ( ) ; JavaScriptSerializer js = new JavaScriptSerializer ( ) ; string retJSON = js.Serialize ( obj.NowShowingGetList ( ShowDate ) ) ; return retJSON ; } public class NowShowingInfo { public int ShowID { get ; set ; } public string StartTime { get ; set ; } public int MovieID { get ; set ; } public string Movie { get ; set ; } public string Screen { get ; set ; } public string MediaPath { get ; set ; } }",Convert Json format Response from webservice "C_sharp : I 'm having trouble with C # and generic type inference.I want to write a method that gets passed a method having any type , but the compiler is not able to infere the types of the method I 'm passing in . The compiler always complains with with the message Expected a method with ' ? ? ? TestFunc ( ? ? ? , ? ? ? ) ' signatureHere 's a testcase.Can anyone explain me what 's the problem ? using System ; public class Example { private interface ITest { int TestFunc ( string str , int i ) ; } private class Test : ITest { public int TestFunc ( string str , int i ) { return 0 ; } } public static void Main ( ) { ITest t = new Test ( ) ; DoWork ( t.TestFunc ) ; } public static void DoWork < T1 , T2 , TResult > ( Func < T1 , T2 , TResult > func ) { } }",Compiler ca n't figure out generic types when passing a method C_sharp : Is it considered a good practice to call an Async method that does some heavy lifting with server connections and data exchange during OnStart ( ) event of the application given that this method does not touch the UI thread ? Are all the components of the application properly initialized at the time of this event firing for the Async method to be able to execute ? protected override async void OnStart ( ) { sendHttpRequestAsync ( ) ; } private async void sendHttpRequestAsync ( ) { await ... },Xamarin Async method usage OnStart ( ) "C_sharp : Let 's say I want to convert a Double x to a Decimal y . There 's a lot of ways to do that : Functionally , all of the above do the same thing ( as far as I can tell ) . Other than personal taste and style , is there a particular reason to choose one option over the other ? EDIT : This is the IL generated by compiling the three C # options in a Release configuration : This is the IL generated by compiling the four VB options in a Release configuration : So , it all ends up in System.Decimal : :.ctor ( float64 ) 1. var y = Convert.ToDecimal ( x ) ; // Dim y = Convert.ToDecimal ( x ) 2. var y = new Decimal ( x ) ; // Dim y = new Decimal ( x ) 3. var y = ( decimal ) x ; // Dim y = CType ( x , Decimal ) 4 . -- no C # equivalent -- // Dim y = CDec ( x ) 1. call valuetype [ mscorlib ] System.Decimal [ mscorlib ] System.Convert : :ToDecimal ( float64 ) -- > which calls System.Decimal : :op_Explicit ( float64 ) -- > which calls System.Decimal : :.ctor ( float64 ) 2. newobj instance void [ mscorlib ] System.Decimal : :.ctor ( float64 ) 3. call valuetype [ mscorlib ] System.Decimal [ mscorlib ] System.Decimal : :op_Explicit ( float64 ) -- > which calls System.Decimal : :.ctor ( float64 ) 1. call valuetype [ mscorlib ] System.Decimal [ mscorlib ] System.Convert : :ToDecimal ( float64 ) -- > which calls System.Decimal : :op_Explicit ( float64 ) -- > which calls System.Decimal : :.ctor ( float64 ) 2. call instance void [ mscorlib ] System.Decimal : :.ctor ( float64 ) 3. newobj instance void [ mscorlib ] System.Decimal : :.ctor ( float64 ) 4. newobj instance void [ mscorlib ] System.Decimal : :.ctor ( float64 )",Convert numeric types : Which style to use ? "C_sharp : Give this a try . Setup a new Windows Forms application with a single button and the following code for the button click event : Then run the application and click the button rapidly . If your experience is anything like mine you ’ ll find that sometimes it works as expected , however , other times the Debug.Assert will fail.Based on my understanding of ConfigureAwait as explained on Stephen Cleary ’ s blog , passing false for continueOnCapturedContext should instruct the task to not sync back to the “ main ” context ( UI thread in this case ) and that execution should continue on the thread pool.Why then would the assert fail randomly ? I can only assume that ReadAsync will sometimes not complete on a background thread , i.e . it will complete synchronously.This behavior is in line with KB 156932 - Asynchronous Disk I/O Appears as Synchronous on Windows : Most I/O drivers ( disk , communications , and others ) have special case code where , if an I/O request can be completed `` immediately , '' the operation will be completed and the ReadFile or WriteFile function will return TRUE . In all ways , these types of operations appear to be synchronous . For a disk device , typically , an I/O request can be completed `` immediately '' when the data is cached in memory.Are my assumptions and test application correct ? Can the ReadAsync method sometimes complete synchronously ? Is there a way to guarantee that execution will always continue on a background thread ? This issue is wreaking havoc on my application which uses COM objects that require me to know which thread is executing at all times.Windows 7 64-bit , .NET 4.5.1 private async void button1_Click ( object sender , EventArgs e ) { using ( var file = File.OpenRead ( @ '' C : \Temp\Sample.txt '' ) ) { byte [ ] buffer = new byte [ 4096 ] ; int threadId = Thread.CurrentThread.ManagedThreadId ; int read = await file.ReadAsync ( buffer , 0 , buffer.Length ) .ConfigureAwait ( false ) ; Debug.Assert ( threadId ! = Thread.CurrentThread.ManagedThreadId ) ; } }",Does FileStream.ReadAsync sometimes complete synchronously ? "C_sharp : ReSharper is clever enough to know that a string.Format requires a not-null format argument so it warns me about it when I simply writewhere messageFormat can indeed be null . As soon as I add a condition for this variable : the warning disappears . Unfortunatelly it does n't when I use an extension method : My question is : is there a way to teach ReSharper that my extension method has the same meaning as ! string.IsNullOrEmpty ( messageFormat ) ? The extension is defined as : _message = string.Format ( messageFormat , args ) ; if ( ! string.IsNullOrEmpty ( messageFormat ) ) { _message = string.Format ( messageFormat , args ) ; } if ( messageFormat.IsNotNullOrEmpty ( ) ) { _message = string.Format ( messageFormat , args ) ; // possible 'null ' assignment warning } public static bool IsNotNullOrEmpty ( [ CanBeNull ] this string value ) = > ! IsNullOrEmpty ( value ) ;",Can I teach ReSharper a custom null check ? "C_sharp : I am using RazorEngine . I have some dynamic templates which I will bind with a view-model at run-time . My requirement is to run-code in a sandbox . So , only bindings will be allowed . RazorEngine allows me to run code in arbitrary app-domain using , If I run the app-domain with the following permission then it works , But If I run it using these permissions , I will get , Is there any special permission I need to grant ? using ( var service = new IsolatedTemplateService ( ( ) = > appDomain ) ) { return service.Parse ( newTemplate , model , null , null ) ; } var permissionSet = new PermissionSet ( PermissionState.Unrestricted ) ; var permissionSet = new PermissionSet ( PermissionState.None ) ; permissionSet.AddPermission ( new SecurityPermission ( PermissionState.Unrestricted ) ) ; permissionSet.AddPermission ( new ReflectionPermission ( PermissionState.Unrestricted ) ) ; [ SecurityException : Request failed . ] System.AppDomain.CreateInstance ( String assemblyName , String typeName , Boolean ignoreCase , BindingFlags bindingAttr , Binder binder , Object [ ] args , CultureInfo culture , Object [ ] activationAttributes ) +0 RazorEngine.Templating.IsolatedTemplateService..ctor ( Language language , Encoding encoding , IAppDomainFactory appDomainFactory ) +408 RazorEngine.Templating.IsolatedTemplateService..ctor ( Language language , Encoding encoding , Func ` 1 appDomainFactory ) +73 RazorEngine.Templating.IsolatedTemplateService..ctor ( Func ` 1 appDomainFactory ) +41",Executing arbitrary C # code in Sandbox mode ? "C_sharp : I hope this does n't come across as a stupid question but its something I have been wondering about . I wish to write unit test a method which contains some logic to check that certain values are not null.I want to test this by passing null values into the method . My question is should I create a unit test for each argument or can I create one unit test which checks what happens if I set value1 to null and then checks what happens if I set value2 to null.i.e.orOr does it make any difference ? I think I read somewhere that you should limit yourself to one assert per unit test . Is this correct ? Thanks in advanceZaps public void MyMethod ( string value1 , string value2 ) { if ( value1 ! = null ) { //do something ( throw exception ) } if ( value2 ! = null ) { //do something ( throw exception ) } //rest of method } [ TestMethod ] public void TestMyMethodShouldThrowExceptionIfValue1IsNull ( ) { //test } [ TestMethod ] public void TestMyMethodShouldThrowExceptionIfValue2IsNull ( ) { //test } [ TestMethod ] public void TestMyMethodWithNullValues ( ) { //pass null for value1 //check //pass null for value2 //check }",Unit testing - should I split up tests or have a single test ? "C_sharp : I have been looking at the standard Dispose pattern and I 'm just wondering what I need to write to free managed resources ? If these resources are 'managed ' already then surely I should n't need to do anything.If that 's the case , and my class does n't hold any unmanaged resources ( hence no need for it to be finalized by GC ) then do I only need to suppress finalization in my Dispose method ? : -so suppose this is my class : Do I actually need to free the managed resources here ? Thanks , public void Dispose ( ) { GC.SuppressFinalize ( this ) ; } public sealed class MyClass : IDisposable { IList < MyObject > objects ; // MyObject does n't hold any unmanaged resource private bool _disposed ; public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } private void Dispose ( bool disposing ) { if ( ! _disposed ) { // do I need to set the list to null and // call Dispose on each item in the list ? if ( disposing ) { foreach ( var o in objects ) o.Dispose ( ) ; objects = null ; } } _disposed = true ; } ~MyClass ( ) { Dispose ( false ) ; } }",When do I need to manage managed resources ? "C_sharp : I 've run into a peculiar case where I get the following error when creating certain types of string : Unexpected error writing debug information -- 'Error HRESULT E_FAIL has been returned from a call to a COM component . 'This error is not new to Stack Overflow ( see this question and this question ) , but the problems presented have nothing to do with this one.For me , this is happening when I create a const string of a certain length that includes a null-terminating character ( \0 ) somewhere near the beginning.To reproduce , first generate a string of appropriate length , e.g . using : Grab the resulting string at runtime ( e.g . Immediate Window or by hovering over the variable and copying its value ) . Then , make a const out of it : Finally , put a \0 in there somewhere : Some things I noticed : if you put the \0 near the end , the error does n't happen.Reproduced using .NET Framework 4.6.1 and 4.5Does n't happen if the string is short.Edit : even more precious info available in the comments below.Any idea why this is happening ? Is it some kind of bug ? Edit : Bug filed , including info from comments . Thanks everybody . var s = new string ( ' a ' , 3000 ) ; const string history = `` aaaaaa ... aaaaa '' ; const string history = `` aaaaaaaaaaaa\0aa ... aaaaa '' ;",C # wo n't compile a long const string with a \0 near the beginning "C_sharp : Look into following code block , In first case why I need to convert DataRow again into DataRow ? and Why second case not valid ? DataTable _table = new DataTable ( ) ; //1 ) Why I need to Convert DataRow again into DataRow by Casting ? List < DataRow > _rows = _table.Rows.Cast < DataRow > ( ) .Select ( a = > a ) .ToList ( ) ; //2 ) Why this is not valid ? List < DataRow > _rows = _table.Rows.Select ( a = > a ) .ToList ( ) ;",Why I need to convert DataRow again into DataRow ? "C_sharp : I am using pactNet to test an API which should return an array of a flexible length.If i call `` myApi/items/ '' it should return a list of items where the consumer does not know the exact size of.So the answer should look like this : or this : How do I create the contract for this interaction ? In the documentation is an example in Ruby , but I can not find the equivalent in C # .I am using pactNet version 2.1.1.Edit : Here is an example how it should look like . What I want to know is how do I declare that the body should contain an array of items with a flexible length . [ { `` id '' : `` 1 '' , `` description '' : `` foo '' } , { `` id '' : `` 2 '' , `` description '' : `` foo2 '' } , { `` id '' : `` 3 '' , `` description '' : `` foo3 '' } ] [ { `` id '' : `` 4 '' , `` description '' : `` foo4 '' } , { `` id '' : `` 2 '' , `` description '' : `` foo2 '' } ] [ Test ] public void GetAllItems ( ) { //Arrange _mockProviderService .Given ( `` There are items '' ) .UponReceiving ( `` A GET request to retrieve the items '' ) .With ( new ProviderServiceRequest { Method = HttpVerb.Get , Path = `` /items/ '' , Headers = new Dictionary < string , object > { { `` Accept '' , `` application/json '' } } } ) .WillRespondWith ( new ProviderServiceResponse { Status = 200 , Headers = new Dictionary < string , object > { { `` Content-Type '' , `` application/json ; charset=utf-8 '' } } , Body = // array of items with some attributes // ( somthing like : { `` id '' : `` 2 '' , `` description '' : `` foo '' } ) // with flexible length } ) ; var consumer = new ItemApiClient ( _mockProviderServiceBaseUri ) ; //Act var result = consumer.GetItems ( ) ; //Assert Assert.AreEqual ( true , result.Count > 0 ) ; _mockProviderService.VerifyInteractions ( ) ; data.Dispose ( ) ; }",PACT .NET consumer test : flexible length array "C_sharp : This is probably best explained with some code : The idea being that there 's no reason to actually query the db again if there are no currentlyHeldId 's to query on . LINQ to SQL will still query the db if currentlyHeldIds has no values . Is there anything wrong with this approach ? I realize there are some other concerns related to returning IQueryable in general , but those arguments aside , is there anything wrong with trying to circumvent the db call like this ? public IQueryable < DatabaseRecord > GetQueryableLinkedRecords ( ) { if ( this.currentlyHeldIds.Count ( ) == 0 ) { return Enumerable.Empty < DatabaseRecord > ( ) .AsQueryable ( ) ; } else { return from r in this.DBContext.DatabaseRecords where this.currentlyHeldIds.Contains ( r.Id ) select r ; } }",Returning Enumerable.Empty < T > ( ) .AsQueryable ( ) a bad idea ? "C_sharp : I have a class which needs to set an IPrinciple object on construction , based on the current authenticated user.I found some other code which I tried but it did n't work : And I configured Simple Injector like so : Apparently _principal is undefined/not set to an instance of an object when I try running this.I also tried : This allowed me to check _principal.Value.Identity.IsAuthenticated but was always returning false . private readonly Lazy < IPrincipal > _principal ; public MyService ( Lazy < IPrincipal > principal ) { _principal = principal ; } container.Register ( ( ) = > new Lazy < IPrincipal > ( ( ) = > HttpContext.Current.User ) ) ; container.Register ( ( ) = > new Lazy < IPrincipal > ( ( ) = > Thread.CurrentPrincipal ) ) ;",Configure Simple Injector to inject current authenticated user "C_sharp : I want to make a method like this , How can I do this ? What is the syntax for passing the conditions and method as parameters ? Also , does it make more sense to make the conditions a method and check the return value of it ? public dynamic Traverse ( dynamic entity , conditions , method ) { foreach ( var propInfo in GetTraversableProperties ( entity ) ) { if ( condition ) method ( propInfo.GetValue ( etc ) ) ; Traverse ( propInfo , condition , method ) ; } return entity ; }",How can I dynamically pass a condition and a method to a recursive method "C_sharp : this might be a very simple question , but I could not find an answer here on SO nor knew anyone I asked an answer : I can write an easy c # method like this : If the CIL-Code ( created by the compiler ) gets executed by the Common Language Runtime , it will create the following fields on top of the stack while the executing control is inside the method : But now , I extend the Method to access the field called `` a '' to this : Now the CLR has to access a field which is not on top of the stack , but according to the FILO ( first in , last out ) principle , it has to take care of all fields above the requested fields before accessing it.What happens to the field called `` b '' which is on the stack above the requested field `` a '' ? The CLR cant delete it , as it might be used by the executing method afterwards , so what happens to it ? AFAIK , there are only 2 ways to store a field , stack or heap . Moving it to the heap would'nt make much sense as this would take all the benefits from stacking from the CLR . Does the CLR create something like a second stack ? How does that work exactly ? -edit-Maybe I did n't explain my intentions clear enough.If i write a Method like this : The CLR first writes 2 fields on the stack and accesses them afterwards , but in reversed order.First , it has to access field `` a '' , but to get to it , the CLR has to take care of field `` b '' which lies above field `` a '' on the stack . It cant just remove field `` b '' from the stack as it has to access it afterwards.How does that work ? private void foo ( ) { int a = 1 ; int b = 5 ; } b = 5a = 1 private void foo ( ) { int a = 1 ; int b = 5 ; Console.WriteLine ( a ) ; } private void foo ( ) { int a = 1 ; int b = 5 ; Console.WriteLine ( a ) ; Console.WriteLine ( b ) ; }",How is the C # Stack accessed by the CLR ? "C_sharp : How are you formatting your try..catch.finally blocks ? Especially when only wrapping it around a small amount of code , it blows everything and makes code pretty unreadable and unsightly in my opinion.Such as : These 7 lines of code turned into a 16-line mess.Any suggestions on better try..catch..finally formatting ? try { MyService service = new Service ( ) ; service.DoSomething ( ) ; return something ; } catch ( Exception ex ) { LogSomething ( ) ; return somethingElse ; } finally { MarkAsComplete ( ) ; service.Dispose ( ) ; }",Formatting of hard to read try..catch..finally blocks ? "C_sharp : I am working on implementing OneSignal push-notification in Xamarin.Forms.I need to pass the string returned by OneSignal AdditionalData into the constructor of App ( ) .So I used HandleNotificationOpened ( OSNotificationOpenedResult result ) for handling the notification tap and fetching the string and then pass it to LoadApplication ( new App ( myData ) ) .So for this , I have written the code in MainActivity for Android and in AppDelegate for iOS.Everything is working fine for Android ; i.e . the HandleNotificationOpened ( ) fetched the additionalData and passes it toLoadApplication ( new App ( myData ) ) .But in iOS , when I opened the notification , the HandleNotificationOpened ( ) code is not called.AppDelegate.cs static string s = null ; public override bool FinishedLaunching ( UIApplication app , NSDictionary options ) { OneSignal.Current.StartInit ( `` MyKey '' ) .HandleNotificationOpened ( HandleNotificationOpened ) .EndInit ( ) ; if ( s ! =null ) { LoadApplication ( new App ( s ) ) ; } else { LoadApplication ( new App ( `` myUrl.lasso '' ) ) ; } return base.FinishedLaunching ( app , options ) ; } private static void HandleNotificationOpened ( OSNotificationOpenedResult result ) { OSNotificationPayload payload = result.notification.payload ; Dictionary < string , object > additionalData = payload.additionalData ; if ( additionalData ! = null ) { if ( additionalData.ContainsKey ( `` url_direct '' ) ) { s = additionalData [ `` url_direct '' ] .ToString ( ) ; System.Diagnostics.Debug.WriteLine ( `` We need to redirect it to : `` + s ) ; } } }",OneSignal : How to Handle notificationOpened in AppDelegate of a Xamarin.Forms app ? "C_sharp : in my Winforms application which is connected to a database via Linq to SQL I am saving images ( always *.png ) to a table which looks like this : Before I can store a picture I have to convert it to byte [ ] and this is how I do it : Afterwards if I want to load this very same image to a PictureBox in my application I convert it back with this method : It actually works , the only problem appears when I try to display an Image from the database in a Picturebox.So when I load this Image to the database : and later I try to display it . It suddenly looks like this : I already tried all the possible SizeMode settings for the PictureBox ( Normal , Stretchimage , AutoSize , CenterImage , Zoom ) and it still looks like this.Also here is how I load the Images from the database to the pictureBox : First I retrieve the all the Images belonging to a set via id : Also in my application I have a datagridview where Id 's are stored in the first column . So when I want to retrieve any Images belonging to the set I do it like this : When loaded from a local directory the Image looks fine in the pictureBox . I also tried to convert the initial picture to binary and back ( without loading it to the database ) , it still looked fine when displayed in the pictureBox.There is something else I realized while debugging the Image which came from the database . When looking into the ImageSize , width and height had both the value 16 . This is weird because the original image has totally different dimensions.Any ideas ? CREATE TABLE [ dbo ] . [ Images ] ( [ Id ] INT IDENTITY ( 1 , 1 ) NOT NULL , [ Bild ] IMAGE NOT NULL , PRIMARY KEY CLUSTERED ( [ Id ] ASC ) ) ; public static byte [ ] ImageToByteArray ( System.Drawing.Image imageIn ) { using ( MemoryStream ms = new MemoryStream ( ) ) { imageIn.Save ( ms , System.Drawing.Imaging.ImageFormat.Png ) ; return ms.ToArray ( ) ; } } public static Image ByteArrayToImage ( byte [ ] byteArrayIn ) { using ( MemoryStream ms = new MemoryStream ( byteArrayIn ) ) { Image returnImage = Image.FromStream ( ms ) ; return returnImage ; } } public static ImageList GetRezeptImages ( int rezeptId ) { using ( CookBookDataContext ctx = new CookBookDataContext ( ResourceFile.DBConnection ) ) { IEnumerable < RezeptBilder > bilder = from b in ctx.RezeptBilders where b.FKRezept == rezeptId select b ; ImageList imageList = new ImageList ( ) ; foreach ( RezeptBilder b in bilder ) { imageList.Images.Add ( Helper.ByteArrayToImage ( b.Bild.ToArray ( ) ) ) ; } return imageList ; } } private void dgvRezeptListe_CellClick ( object sender , DataGridViewCellEventArgs e ) { pbRezeptBild.Image = DBManager.GetRezeptImages ( Int32.Parse ( dgvRezeptListe.SelectedRows [ 0 ] .Cells [ 0 ] .Value.ToString ( ) ) ) .Images [ 0 ] ; }",Where does this quality loss on Images come from ? "C_sharp : Is it possible to mark a property in base class with some attribute that remains effective in child classes too ? Question might be very specific to Serialization , but I definitely think there can be other uses as well.Consider the following code : Above code returns : I thought IsValid_C1 will be ignored , though it is not so . Is there any way of achieving this other than marking the property as protected ? Edit : A quick code to show that XmlIgnore attibute is being inherited.http : //ideone.com/HH41TE using System ; using System.IO ; using System.Xml.Serialization ; namespace Code.Without.IDE { [ Serializable ] public abstract class C1 { [ XmlIgnore ] public abstract bool IsValid_C1 { get ; set ; } } [ Serializable ] public class C2 : C1 { public bool IsValid_C2 { get ; set ; } public override bool IsValid_C1 { get ; set ; } public C2 ( ) { IsValid_C1 = true ; IsValid_C2 = false ; } } public static class AbstractPropertiesAttributeTest { public static void Main ( string [ ] args ) { C2 c2 = new C2 ( ) ; using ( MemoryStream ms = new MemoryStream ( ) ) { XmlSerializer ser = new XmlSerializer ( typeof ( C2 ) ) ; ser.Serialize ( ms , c2 ) ; string result = System.Text.Encoding.UTF8.GetString ( ms.ToArray ( ) ) ; Console.WriteLine ( result ) ; } } } } -- -- -- C : \abhi\Code\CSharp\without IDE\AbstractPropertiesAttributeTest.exe < ? xml version= '' 1.0 '' ? > < C2 xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < IsValid_C2 > false < /IsValid_C2 > < IsValid_C1 > true < /IsValid_C1 > < /C2 > -- -- -- Process returned 0",Cascading the effect of an attribute to overridden properties in child classes "C_sharp : I was wondering if there is any difference between ending loop task with CancellationTokenSource and exit flagCancellationTokenSource : Exit flag : To me it does not make any sance to use CancellationTokenSource , btw is there any reason why cancellation token can be add as a parameter to Task factory ? Thank you very much for any kind of answer.Best ragards teamol CancellationTokenSource cancellationTokenSource ; Task loopTask ; void StartLoop ( ) { cancellationTokenSource = new CancellationTokenSource ( ) ; loopTask = Task.Factory.StartNew ( Loop , TaskCreationOptions.LongRunning ) ; } void Loop ( ) { while ( true ) { if ( cancellationTokenSource.IsCancellationRequested ) break ; Thread.Yield ( ) ; } } void StopLoop ( ) { cancellationTokenSource.Cancel ( ) ; loopTask = null ; cancellationTokenSource = null ; } volatile bool exitLoop ; Task loopTask ; void StartLoop ( ) { exitLoop = false ; loopTask = Task.Factory.StartNew ( Loop , TaskCreationOptions.LongRunning ) ; } void Loop ( ) { while ( true ) { if ( exitLoop ) break ; Thread.Yield ( ) ; } } void StopLoop ( ) { exitLoop = true ; loopTask = null ; }",Difference between CancellationTokenSource and exit flag for Task loop exit "C_sharp : I have the following function : However , intellisense is telling me string does not contain a definition for Where and that no extension method can be found . I have using System.Linq ; declared in the file . In a non-Xamarin project this code works fine.This is a Xamarin.Forms PCL project in VS2015 Community . What gives ? private static string SanitizeVersionStringFromUnit ( string version ) { var santizedString = new string ( version.Where ( char.IsLetterOrDigit ) .ToArray ( ) ) ; ; return santizedString ; }",LINQ not working for strings in Xamarin ? "C_sharp : I 'm implementing for Lexical parsing in Tamil Language.I need to replace a Text Element value by following conditionif any word having element from ugaramStrings and tamil vowel element by consecutive.Is need to be replace ugaram string and return the value.for eg.அமர்ந்*துஇ*னிது replaced as அமர்ந்*இ*னிது.i.e துஇ= > இI 've done it by checking next string element using TextElementEnumerator Class.Is it any possiblity is avail so that replace it by using RegularExpression string [ ] ugaramStrings = { `` கு '' , `` சு '' , `` டு '' , `` து '' , `` பு '' , `` று '' } ; string [ ] tamilvowels = { `` அ '' , // `` \u0b85 '' `` ஆ '' , // '' \u0b86 '' `` இ '' , // '' \u0b87 '' `` ஈ '' , // '' \u0b88 '' `` உ '' , // '' \u0b89 '' `` ஊ '' , // '' \u0b8A '' `` எ '' , // `` \u0b8E '' `` ஏ '' , // '' \u0b8F '' `` ஐ '' , // '' \u0b90 '' `` ஒ '' , // '' \u0b92 '' `` ஓ '' , // '' \u0b93 '' `` ஔ '' // '' \u0b94 '' } ;",Replace Unicode ( Tamil ) string using Regular Expression C # "C_sharp : I 'm looking to connect my bot on teams channel but i did n't know the way to secure this for use only in our domains ( organization ) . I have test to look ( authentication AAD ) for the Azure Web App but it 's does n't work on teams or on webchat because the endpoint adresse it 's not redirected . I have test to implement AUTH card but it does n't work on teams.Note : I 'm using botframework C # api BotBuilder 3.15.2.2I have look other `` ask '' like : AAD authentication in Microsoft teams for Bot FrameworkIs it possible to access custom tabs in 1:1 chats in MS Teams ? https : //docs.microsoft.com/en-us/microsoftteams/platform/concepts/authentication/auth-flow-bothttps : //docs.microsoft.com/en-us/microsoftteams/platform/concepts/authentication/auth-bot-AADhttps : //docs.microsoft.com/en-us/microsoftteams/platform/concepts/authentication/authenticationhttps : //tsmatz.wordpress.com/2016/09/06/microsoft-bot-framework-bot-with-authentication-and-signin-login/Sincerely , Pascal.Edit : I have implemented the solution sugested by Adrian , below was a piece of C # code that implement this on the MessasController.cs ( Post Function ) : Note == > Adding access for localhost use //https : //stackoverflow.com/questions/51090597/botframework-on-teams-channel-11-authentication-aad-integrated string tenantIdAAD = `` '' ; try { tenantIdAAD = activity.GetChannelData < TeamsChannelData > ( ) .Tenant.Id ; } catch ( Exception exception ) { tenantIdAAD = `` '' ; } ConnectorClient connector = new ConnectorClient ( new Uri ( activity.ServiceUrl ) ) ; if ( [ AAD_TenantID ] .TenantIdAAD.Equals ( tenantIdAAD ) || activity.ServiceUrl.StartsWith ( `` http : //localhost '' ) ) { await Conversation.SendAsync ( activity , ( ) = > new Dialogs.RootDialog ( ) .LogIfException ( ) ) ; } else { await connector.Conversations.ReplyToActivityAsync ( activity.CreateReply ( `` Access Denied '' ) ) ; }",botframework on teams channel 1:1 Authentication AAD integrated "C_sharp : We developed an app before for jellybean to nougat but now we 're having a problem after updating our xamarin in visual studio.Before , our apk is perfectly running in all Android version but now after update , it is now crashing ... but only in 5.1.1 . We already tested it with kitkat , lollipop 5.1 , marshmallow and nougat , and it is really running.We noticed that our app is crashing after the last curly bracket `` } '' in OnCreate method . It is launching an exception without prior detail.What can be the reason for this exception ? Or any solution if somebody already solved it.I do n't know if it 's just a setting that has been changed due to xamarin update.Exception only occur on OPPO phone as tested on other 5.1 and 5.1.1 versionException image is here and as I said , there is no single detailHere is the debugger output Example belowIf there is a user and is active . It will proceed to login . But same thing will happen . Will crash again on the last bracket of login.cs under OnCreate ( ) methodHere is the LogCat output , it 's hard to read for me since it 's my first time to see it . ** UPDATE FOR XML and Style **Here is my XML and here is my previous style** PROBLEM SOLVED **As suggested , I may need to change the parent of style from TextAppearance.AppCompat to Widget.Design.TextInputLayout . I tried and it works ! THANKS ALOT ! *Just for a note of testing for other codersIt 's just that , i 'm wondering why only in OPPO 5.1.1 . Other android versions I tried with and working are here-Marshmallow and Nougat with Asus 6.0 & 7.0-Kitkat and Marshmallow Starmobile 4.4 & 6.0-JellyBean , Kitkat and Marshmallow with Samsung 4.2 , 4.4 & 6.0-Other brand with 5.1 and 5.1.1 ( not the OPPO ) Android application is debugging . Mono Warning : option gen-compact-seq-points is deprecated . 07-14 10:37:16.613 W/monodroid ( 18119 ) : Trying to load sgen from : /data/app/RBOS_2.x_0.x_1.RBOS_2.x_0.x_1-1/lib/arm/libmonosgen-2.0.so07-14 10:37:16.613 W/monodroid-debug ( 18119 ) : Trying to initialize the debugger with options : -- debugger-agent=transport=dt_socket , loglevel=0 , address=127.0.0.1:29342 , server=y , embedding=1 07-14 10:37:16.953 W/monodroid-debug ( 18119 ) : Accepted stdout connection : 29 07-14 10:37:18.793 W/monodroid-gc ( 18119 ) : GREF GC Threshold : 46080 07-14 10:37:18.793 W/monodroid ( 18119 ) : Calling into managed runtime init Loaded assembly : RBOS 2.0.1.dll Loaded assembly : BusinessLogic.dll Loaded assembly : BusinessObject.dll Loaded assembly : DotNetCross.Memory.Unsafe.dll [ External ] Loaded assembly : Newtonsoft.Json.dll [ External ] Loaded assembly : Realm.dll [ External ] Loaded assembly : Remotion.Linq.dll [ External ] Loaded assembly : Xamarin.Android.Support.Animated.Vector.Drawable.dll [ External ] Loaded assembly : Xamarin.Android.Support.Design.dll [ External ] Loaded assembly : Xamarin.Android.Support.v4.dll [ External ] Loaded assembly : Xamarin.Android.Support.v7.AppCompat.dll [ External ] Loaded assembly : Xamarin.Android.Support.v7.CardView.dll [ External ] Loaded assembly : Xamarin.Android.Support.v7.RecyclerView.dll [ External ] Loaded assembly : Xamarin.Android.Support.Vector.Drawable.dll [ External ] Loaded assembly : UTILITIES.dll Loaded assembly : Mono.Android.dll [ External ] Loaded assembly : Java.Interop.dll [ External ] Loaded assembly : System.Core.dll [ External ] Loaded assembly : MonoDroidConstructors [ External ] Loaded assembly : System.dll [ External ] Loaded assembly : System.Data.dll [ External ] Loaded assembly : System.Xml.dll [ External ] 07-14 10:37:20.183 D/OpenGLRenderer ( 18119 ) : Use EGL_SWAP_BEHAVIOR_PRESERVED : true 07-14 10:37:20.193 D/Atlas ( 18119 ) : Validating map ... 07-14 10:37:20.303 W/ResourceType ( 18119 ) : Too many attribute references , stopped at : 0x01010099 07-14 10:37:20.303 W/ResourceType ( 18119 ) : Too many attribute references , stopped at : 0x0101009b 07-14 10:37:20.313 I/TextInputLayout ( 18119 ) : EditText added is not a TextInputEditText . Please switch to using that class instead . Loaded assembly : System.Web.Services.dll [ External ] Loaded assembly : Mono.Security.dll [ External ] 07-14 10:37:20.903 I/Adreno-EGL ( 18119 ) : < qeglDrvAPI_eglInitialize:379 > : EGL 1.4 QUALCOMM build : AU_LINUX_ANDROID_LA.BR.1.1.3.C8.05.01.00.115.092_msm8916_64_refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.3.C8.05.01.00.115.092__release_AU ( I6eddbfa548 ) 07-14 10:37:20.903 I/Adreno-EGL ( 18119 ) : OpenGL ES Shader Compiler Version : E031.25.03.04 07-14 10:37:20.903 I/Adreno-EGL ( 18119 ) : Build Date : 09/16/15 Wed 07-14 10:37:20.903 I/Adreno-EGL ( 18119 ) : Local Branch : 07-14 10:37:20.903 I/Adreno-EGL ( 18119 ) : Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.3.C8.05.01.00.115.092 07-14 10:37:20.903 I/Adreno-EGL ( 18119 ) : Local Patches : NONE 07-14 10:37:20.903 I/Adreno-EGL ( 18119 ) : Reconstruct Branch : NOTHING 07-14 10:37:20.903 I/OpenGLRenderer ( 18119 ) : Initialized EGL , version 1.4 07-14 10:37:20.923 D/OpenGLRenderer ( 18119 ) : Enabling debug mode 0 07-14 10:37:20.963 W/ResourceType ( 18119 ) : Too many attribute references , stopped at : 0x01010099 07-14 10:37:20.963 W/ResourceType ( 18119 ) : Too many attribute references , stopped at : 0x0101009b 07-14 10:37:20.963 D/AndroidRuntime ( 18119 ) : Shutting down VM An unhandled exception occured . protected override void OnCreate ( Bundle savedInstanceState ) { base.OnCreate ( savedInstanceState ) ; SetContentView ( Resource.Layout.RequestAccess ) ; # region Check if there is an active user - proceed to login , else proceed to request access UserAccountLogic.getAllUserAccountsFromDatabase ( listUserObject ) ; if ( listUserObject.Count > 0 & & listUserObject [ 0 ] .isActive ! =0 ) { //Call LoginActivity var intent = new Intent ( this , typeof ( Login ) ) ; StartActivity ( intent ) ; FinishAffinity ( ) ; } else { txtAccessCode = FindViewById < TextInputLayout > ( Resource.Id.layoutAccessCode ) ; button = FindViewById < Button > ( Resource.Id.btnSend ) ; button.Click += delegate { sendButtonClicked ( ) ; } ; } # endregion Android.Util.Log.Error ( `` L '' , `` Error Occured '' ) ; } //this is the place where exception occur in 5.1.1 . I do n't know why . E/L ( 6824 ) : Error Occured // I added a log tag here before the bracketV/WindowManager ( 866 ) : Adding window Window { 386088e1 u0 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.RequestAccess } at 7 of 14 ( before Window { 3031e02c u0 Starting RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 } ) V/WindowManager ( 866 ) : Changing focus from null to Window { 386088e1 u0 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.RequestAccess } Callers=com.android.server.wm.WindowManagerService.relayoutWindow:3410 com.android.server.wm.Session.relayout:202 android.view.IWindowSession $ Stub.onTransact:273 com.android.server.wm.Session.onTransact:130I/Adreno-EGL ( 6824 ) : < qeglDrvAPI_eglInitialize:379 > : EGL 1.4 QUALCOMM build : AU_LINUX_ANDROID_LA.BR.1.1.3.C8.05.01.00.115.092_msm8916_64_refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.3.C8.05.01.00.115.092__release_AU ( I6eddbfa548 ) I/Adreno-EGL ( 6824 ) : OpenGL ES Shader Compiler Version : E031.25.03.04I/Adreno-EGL ( 6824 ) : Build Date : 09/16/15 WedI/Adreno-EGL ( 6824 ) : Local Branch : I/Adreno-EGL ( 6824 ) : Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.BR.1.1.3.C8.05.01.00.115.092I/Adreno-EGL ( 6824 ) : Local Patches : NONEI/Adreno-EGL ( 6824 ) : Reconstruct Branch : NOTHINGI/OpenGLRenderer ( 6824 ) : Initialized EGL , version 1.4D/OpenGLRenderer ( 6824 ) : Enabling debug mode 0W/ResourceType ( 6824 ) : Too many attribute references , stopped at : 0x01010099W/ResourceType ( 6824 ) : Too many attribute references , stopped at : 0x0101009bD/AndroidRuntime ( 6824 ) : Shutting down VMI/KSO_STAT ( 1466 ) : App is in background , stop update end time , ready to start a new session.V/ExReceiver ( 32431 ) : revceive action =android.intent.action.BATTERY_CHANGEDE/QCOMSysDaemon ( 6861 ) : Ca n't find/open bootselect node : ( No such file or directory ) I/QCOMSysDaemon ( 6861 ) : Starting qcom system daemonE/Diag_Lib ( 6861 ) : Diag_LSM_Init : Failed to open handle to diag driver , error = 2E/QCOMSysDaemon ( 6861 ) : Diag_LSM_Init failed : 0I/Babel_ConcService ( 5697 ) : Acquired partial wake lock to keep ConcurrentService aliveI/Babel_ConcService ( 5697 ) : Released partial wake lock as ConcurrentService became idleI/KSO_STAT ( 1466 ) : App is in background , stop update end time , ready to start a new session.W/ActivityManager ( 866 ) : Launch timeout has expired , giving up wake lock ! V/ExReceiver ( 32431 ) : revceive action =android.intent.action.BATTERY_CHANGEDD/TelephonyProvider ( 1787 ) : simId = 0D/TelephonyProvider ( 1787 ) : simId = 0D/TelephonyProvider ( 1787 ) : query ( ) : mccmnc = 51503 spn = SMART Prepaid simId = 0D/PhoneInterfaceManager ( 1787 ) : [ PhoneIntfMgr ] getDataEnabled : subId=1 phoneId=0D/PhoneInterfaceManager ( 1787 ) : [ PhoneIntfMgr ] getDataEnabled : subId=1 retVal=trueE/QCOMSysDaemon ( 6864 ) : Ca n't find/open bootselect node : ( No such file or directory ) I/QCOMSysDaemon ( 6864 ) : Starting qcom system daemonE/Diag_Lib ( 6864 ) : Diag_LSM_Init : Failed to open handle to diag driver , error = 2E/QCOMSysDaemon ( 6864 ) : Diag_LSM_Init failed : 0E/AndroidRuntime ( 6824 ) : FATAL EXCEPTION : mainE/AndroidRuntime ( 6824 ) : Process : RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 , PID : 6824E/AndroidRuntime ( 6824 ) : android.view.InflateException : Binary XML file line # 24 : Error inflating class TextViewE/AndroidRuntime ( 6824 ) : at android.view.LayoutInflater.createViewFromTag ( LayoutInflater.java:763 ) E/AndroidRuntime ( 6824 ) : at android.view.LayoutInflater.rInflate ( LayoutInflater.java:806 ) E/AndroidRuntime ( 6824 ) : at android.view.LayoutInflater.rInflate ( LayoutInflater.java:809 ) E/AndroidRuntime ( 6824 ) : at android.view.LayoutInflater.rInflate ( LayoutInflater.java:809 ) E/AndroidRuntime ( 6824 ) : at android.view.LayoutInflater.inflate ( LayoutInflater.java:504 ) E/AndroidRuntime ( 6824 ) : at android.view.LayoutInflater.inflate ( LayoutInflater.java:414 ) E/AndroidRuntime ( 6824 ) : at android.view.LayoutInflater.inflate ( LayoutInflater.java:365 ) E/AndroidRuntime ( 6824 ) : at android.widget.OppoCursorController $ FloatPanelViewController. < init > ( OppoCursorController.java:1382 ) E/AndroidRuntime ( 6824 ) : at android.widget.OppoCursorController.createFloatPanelViewController ( OppoCursorController.java:122 ) E/AndroidRuntime ( 6824 ) : at android.widget.OppoCursorController $ InsertionPointCursorController. < init > ( OppoCursorController.java:197 ) E/AndroidRuntime ( 6824 ) : at android.widget.OppoCursorController.create ( OppoCursorController.java:75 ) E/AndroidRuntime ( 6824 ) : at android.widget.OppoEditor.getOppoInsertionController ( OppoEditor.java:410 ) E/AndroidRuntime ( 6824 ) : at android.widget.OppoEditor.onFocusChanged ( OppoEditor.java:298 ) E/AndroidRuntime ( 6824 ) : at android.widget.TextView.onFocusChanged ( TextView.java:8092 ) E/AndroidRuntime ( 6824 ) : at android.view.View.handleFocusGainInternal ( View.java:4963 ) E/AndroidRuntime ( 6824 ) : at android.view.View.requestFocusNoSearch ( View.java:7679 ) E/AndroidRuntime ( 6824 ) : at android.view.View.requestFocus ( View.java:7658 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2612 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2612 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2612 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2612 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2612 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2612 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2612 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.onRequestFocusInDescendants ( ViewGroup.java:2656 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewGroup.requestFocus ( ViewGroup.java:2615 ) E/AndroidRuntime ( 6824 ) : at android.view.View.requestFocus ( View.java:7625 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewRootImpl.performTraversals ( ViewRootImpl.java:2019 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewRootImpl.doTraversal ( ViewRootImpl.java:1116 ) E/AndroidRuntime ( 6824 ) : at android.view.ViewRootImpl $ TraversalRunnable.run ( ViewRootImpl.java:6084 ) E/AndroidRuntime ( 6824 ) : at android.view.Choreographer $ CallbackRecord.run ( Choreographer.java:773 ) E/AndroidRuntime ( 6824 ) : at android.view.Choreographer.doCallbacks ( Choreographer.java:586 ) E/AndroidRuntime ( 6824 ) : at android.view.Choreographer.doFrame ( Choreographer.java:556 ) E/AndroidRuntime ( 6824 ) : at android.view.Choreographer $ FrameDisplayEventReceiver.run ( Choreographer.java:759 ) E/AndroidRuntime ( 6824 ) : at android.os.Handler.handleCallback ( Handler.java:739 ) E/AndroidRuntime ( 6824 ) : at android.os.Handler.dispatchMessage ( Handler.java:95 ) E/AndroidRuntime ( 6824 ) : at android.os.Looper.loop ( Looper.java:150 ) E/AndroidRuntime ( 6824 ) : at android.app.ActivityThread.main ( ActivityThread.java:5408 ) E/AndroidRuntime ( 6824 ) : at java.lang.reflect.Method.invoke ( Native Method ) E/AndroidRuntime ( 6824 ) : at java.lang.reflect.Method.invoke ( Method.java:372 ) E/AndroidRuntime ( 6824 ) : at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run ( ZygoteInit.java:964 ) E/AndroidRuntime ( 6824 ) : at com.android.internal.os.ZygoteInit.main ( ZygoteInit.java:759 ) E/AndroidRuntime ( 6824 ) : Caused by : java.lang.RuntimeException : Failed to resolve attribute at index 24E/AndroidRuntime ( 6824 ) : at android.content.res.TypedArray.getColor ( TypedArray.java:401 ) E/AndroidRuntime ( 6824 ) : at android.widget.TextView. < init > ( TextView.java:709 ) E/AndroidRuntime ( 6824 ) : at android.widget.TextView. < init > ( TextView.java:645 ) E/AndroidRuntime ( 6824 ) : at android.support.v7.widget.AppCompatTextView. < init > ( AppCompatTextView.java:60 ) E/AndroidRuntime ( 6824 ) : at android.support.v7.widget.AppCompatTextView. < init > ( AppCompatTextView.java:56 ) E/AndroidRuntime ( 6824 ) : at android.support.v7.app.AppCompatViewInflater.createView ( AppCompatViewInflater.java:103 ) E/AndroidRuntime ( 6824 ) : at android.support.v7.app.AppCD/ActivityManager ( 866 ) : addErrorToDropBox processName = RBOS_2.x_0.x_1.RBOS_2.x_0.x_1W/ActivityManager ( 866 ) : Force finishing activity 1 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.RequestAccessW/ActivityManager ( 866 ) : Force finishing activity 2 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.LauncherW/DropBoxManagerService ( 866 ) : Dropping : data_app_crash ( 10 > 0 bytes ) V/WindowManager ( 866 ) : Changing focus from Window { 386088e1 u0 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.RequestAccess } to null Callers=com.android.server.wm.WindowManagerService.setFocusedApp:4259 com.android.server.am.ActivityManagerService.setFocusedActivityLocked:2553 com.android.server.am.ActivityStack.adjustFocusedActivityLocked:2873 com.android.server.am.ActivityStack.finishActivityLocked:3118D/DropBoxManagerService ( 866 ) : file : : /data/system/dropbox/data_app_crash @ 1501223953398.lostV/WindowManager ( 866 ) : Changing focus from null to Window { 18da7c8d u0 Application Error : RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 } Callers=com.android.server.wm.WindowManagerService.addWindow:2660 com.android.server.wm.Session.addToDisplay:173 android.view.ViewRootImpl.setView:582 android.view.WindowManagerGlobal.addView:300D/StatusBarManagerService ( 866 ) : manageDisableList userId=0 what=0x0 pkg=Window { 18da7c8d u0 Application Error : RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 } W/ActivityManager ( 866 ) : Dismiss app error dialog : RBOS_2.x_0.x_1.RBOS_2.x_0.x_1V/WindowManager ( 866 ) : Changing focus from Window { 18da7c8d u0 Application Error : RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 } to null Callers=com.android.server.wm.WindowManagerService.removeWindowLocked:2830 com.android.server.wm.WindowManagerService.removeWindowLocked:2739 com.android.server.wm.WindowManagerService.removeWindow:2729 com.android.server.wm.Session.remove:192I/Process ( 6824 ) : Sending signal . PID : 6824 SIG : 9V/Process ( 6824 ) : killProcess [ 6824 ] Callers=com.android.internal.os.RuntimeInit $ UncaughtHandler.uncaughtException:99 android.runtime.UncaughtExceptionHandler.n_uncaughtException : -2 android.runtime.UncaughtExceptionHandler.uncaughtException:37 java.lang.ThreadGroup.uncaughtException:693I/WindowState ( 866 ) : WIN DEATH : Window { 2ec5203a u0 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.Launcher } I/WindowState ( 866 ) : WIN DEATH : Window { 386088e1 u0 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.RequestAccess } D/WindowStateAnimator ( 866 ) : finishExit add win to mPendingRemove . win : Window { 386088e1 u0 RBOS_2.x_0.x_1.RBOS_2.x_0.x_1/md53392bfeb2a49aa0a04b6510289d0206f.RequestAccess } I/ActivityManager ( 866 ) : Process RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 ( pid 6824 ) has diedV/WindowManager ( 866 ) : Changing focus from null to Window { 8939001 u0 com.android.settings/com.android.settings.SubSettings } Callers=com.android.server.wm.WindowManagerService.relayoutWindow:3410 com.android.server.wm.Session.relayout:202 android.view.IWindowSession $ Stub.onTransact:273 com.android.server.wm.Session.onTransact:130D/StatusBarManagerService ( 866 ) : manageDisableList userId=0 what=0x0 pkg=Window { 8939001 u0 com.android.settings/com.android.settings.SubSettings } W/InputMethodManagerService ( 866 ) : Window already focused , ignoring focus gain of : com.android.internal.view.IInputMethodClient $ Stub $ Proxy @ 29eee4cb attribute=null , token = android.os.BinderProxy @ 129961e8D/AndroidRuntime ( 6867 ) : > > > > > > START com.android.internal.os.RuntimeInit uid 2000 < < < < < < D/AndroidRuntime ( 6867 ) : CheckJNI is OFFE/jniPro ( 6867 ) : protecteyesinit , try to dlopen arm32 so : /system/lib/libprotecteyes.soE/jniPro ( 6867 ) : protecteyesinit , dlopen arm32 so : /system/lib/libprotecteyes.so , open ***success**** , now dlerror info : ( null ) D/AndroidRuntime ( 6867 ) : Calling main entry com.android.commands.am.AmD/ActivityManager ( 866 ) : for debug : forceStopPackage [ pkg : RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 , userId : -1 ] , caller [ pid:6867 , uid:2000 ] I/ActivityManager ( 866 ) : Force stopping RBOS_2.x_0.x_1.RBOS_2.x_0.x_1 appid=10189 user=0 : from pid 6867D/AndroidRuntime ( 6867 ) : Shutting down VMI/KSO_STAT ( 1466 ) : App is in background , stop update end time , ready to start a new session.E/QCOMSysDaemon ( 6886 ) : Ca n't find/open bootselect node : ( No such file or directory ) I/QCOMSysDaemon ( 6886 ) : Starting qcom system daemonE/Diag_Lib ( 6886 ) : Diag_LSM_Init : Failed to open handle to diag driver , error = 2E/QCOMSysDaemon ( 6886 ) : Diag_LSM_Init failed : 0D/TaskPersister ( 866 ) : removeObsoleteFile : deleting file=354_task.xml < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : orientation= '' vertical '' android : alpha= '' 0.9 '' android : background= '' @ drawable/rbos_2 '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : weightSum= '' 100 '' > < LinearLayout android : layout_width= '' match_parent '' android : layout_weight= '' 55 '' android : gravity= '' center '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' > < ImageView android : src= '' @ drawable/dtglogo3 '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_gravity= '' center '' android : id= '' @ +id/imgLogo '' / > < /LinearLayout > < LinearLayout android : layout_width= '' match_parent '' android : layout_weight= '' 45 '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' android : gravity= '' top '' android : paddingLeft= '' 25dp '' android : paddingRight= '' 25dp '' > < android.support.design.widget.TextInputLayout android : id= '' @ +id/layoutAccessCode '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : theme= '' @ style/TextLabel '' android : background= '' @ android : color/transparent '' android : layout_marginTop= '' 15dp '' > < ! -- android : background= '' @ drawable/layouttextbox '' -- > < EditText android : id= '' @ +id/txtAccessCode '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' center '' android : layout_marginTop= '' 15dp '' android : layout_marginBottom= '' 5dp '' android : maxLength= '' 15 '' android : digits= '' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr‌​stuvwxyz0123456789 '' android : fontFamily= '' @ string/fontFamily '' android : inputType= '' textVisiblePassword|textNoSuggestions '' android : imeOptions= '' actionDone '' android : singleLine= '' true '' android : hint= '' Access Code '' / > < /android.support.design.widget.TextInputLayout > < Button android : id= '' @ +id/btnSend '' android : textAllCaps= '' false '' android : theme= '' @ style/button '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : text= '' Send '' android : layout_marginTop= '' 15dp '' android : fontFamily= '' @ string/fontFamily '' android : textSize= '' 20dp '' android : textColor= '' # e4ecd4 '' android : background= '' @ drawable/layoutbutton '' / > < /LinearLayout > < TextView android : text= '' @ string/versionName '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_gravity= '' bottom '' android : textSize= '' 6dp '' android : gravity= '' right '' android : padding= '' 5dp '' android : textColor= '' # 0d47a1 '' / > < /LinearLayout > < ! -- Input Layout -- > < style name= '' TextLabel '' parent= '' TextAppearance.AppCompat '' > < ! -- Hint color and label color in FALSE state -- > < item name= '' android : textColorHint '' > # 000000 < /item > < item name= '' android : textSize '' > 16sp < /item > < ! -- Label color in TRUE state and bar color FALSE and TRUE State -- > < item name= '' colorAccent '' > # 0d47a1 < /item > < item name= '' colorControlNormal '' > # 000000 < /item > < item name= '' colorControlActivated '' > # 0d47a1 < /item > < /style >",App launch is crashing on app launch with Android 5.1.1 lollipop after xamarin update in visual studio "C_sharp : What happened to ConvertTimeToUtc in .NET Core ? I know it 's not there anymore , but has it been replaced by anything else ? This is how I used to take a clients Date and Time input , and then convert it to UTC to store in database : This has worked great , until .NET Core . Any current examples I can find all seem to be using 'ConvertTime ' , but they are going from UTC to local , which is the opposite of what I am going for here . So can anyone out there tell me how I can accomplish this same feat in .NET Core ? I am currently using this framework setup in my project.json file : var timeZoneInfo=TimeZoneInfo.FindSystemTimeZoneById ( viewModel.EventTimeZone ) ; var completeStartDate=TimeZoneInfo.ConvertTimeToUtc ( viewModel.StartDate , timeZoneInfo ) ; `` frameworks '' : { `` netcoreapp1.0 '' : { `` imports '' : [ `` dotnet5.6 '' , `` portable-net45+win8 '' ] } } ,",.NET Core Replacement for ConvertTimeToUtc ? "C_sharp : I 've seen regex that can remove tags , which is great , but I also have stuff likeetc.This is n't actually from a HTML file . It 's actually from a string . I 'm pulling down data from SharePoint web services , which gives me the HTML users might use/get generated likeSo , I 'm parsing through 100-900 rows with 8-20 columns each . & nbsp ; < div > Hello ! Please remember to clean the break room ! ! ! & quot ; bob & quote ; < BR > < /div >",Strip ALL HTML from a String ? "C_sharp : My question have two parts1 ) I want to assign filename to FileUpload Control and then save it but the problem is that it is readonly Is there any other way ? OR2 ) I have Full path of one image at clients machine . I want to download that image.I searched on google but most of the question do it using ajax , javascript , multipart-form . i do n't have any such knowledge . Can i do it purely using C # . FileUpload1.FileName= '' ClientMachine\\Image1.jpeg '' ; FileUpload.SaveAs ( ServerMachine\\Image1.jpeg ) ;",Upload File from client on server `` programmatically '' using file name or `` programmatically '' assign filename to UploadFile Control "C_sharp : I 'm trying to understand if there is any difference between assigning null to an instance of a class and just declaring the class . For an example , I have a class : I declare two instances of the class : Is there any difference between Instance1 and Instance2 ? If yes , is it safe ? Is it a good habit to use the 'delcaration only ' style ( as is the case with Instance2 in the example above ) ? public class MyClass { public string FirstProperty { get ; set ; } public int SecondProperty { get ; set ; } } MyClass Instance1 = null ; MyClass Instance2 ; // just declaration",What is the difference between assigning null to an instance of a class and just declaration "C_sharp : I 'd like to know why the first call to Bar ( ref object ) does n't work and the second one does . Seems silly considering I 'm passing in a type object either way , and passing in an anonymous type to Foo ( object ) works fine . Why would ref , something that has to do with memory location influence the calls to Bar ( ) ? Consider the following snippet : I see in the answers below suggestions on how to make the code compile , but that 's not what I 'm after . I 'd like to know specifically why making it a ref parameter prevents compilation when passing in an anonymous type to Foo ( ) worked fine . static void Foo ( object obj ) { } static void Bar ( ref object obj ) { } static void Main ( ) { // Compiles var a = new { } ; Foo ( a ) ; // Does not compile var b = new { } ; Bar ( ref b ) ; // Compiles object c = new { } ; Bar ( ref c ) ; }",Can I pass an anonymous object into a method that expects a reference parameter of type object ? C_sharp : In C # we can do something like this : However the following will return null : Why is this ? I checked the documentation and got no clues as to why this happens.My results can be illustrated in the following piece of code : The output is : 0 True Int32 i = new Int32 ( ) ; typeof ( Int32 ) .GetConstructor ( new Type [ 0 ] ) using System ; public class Program { public static void Main ( ) { Int32 i = new Int32 ( ) ; Console.WriteLine ( i ) ; Console.WriteLine ( typeof ( Int32 ) .GetConstructor ( new Type [ 0 ] ) == null ) ; } },Why ca n't we find Int32 's Default Constructor using GetConstructor ? "C_sharp : Using Picasa Web API I retrieve a photo from my Google+ photo album and attempt to change the timestamp ( the time was wrong on my phone , so trying to fix it ) : Unfortunately , while the .Update method succeeds , the timestamp does n't change . I 've also tried to change the timezone of the photo ( e.g . same thing user does manually like this http : //i.imgur.com/pxYSi9S.png ) .Am I missing something simple ? Is there another way to accomplish the same thing ? I would also settle for changing the timezone of the photo . var service = new PicasaService ( `` exampleCo-exampleApp-1 '' ) ; service.setUserCredentials ( `` uid '' , `` pwd '' ) ; AlbumQuery query = new AlbumQuery ( PicasaQuery.CreatePicasaUri ( `` default '' ) ) ; PicasaFeed feed = service.Query ( query ) ; var entry = ( PicasaEntry ) feed.Entries.SingleOrDefault ( f = > f.Title.Text == `` Trip to Italy - ALL '' ) ; var ac = new AlbumAccessor ( entry ) ; var photoQuery = new PhotoQuery ( PicasaQuery.CreatePicasaUri ( `` default '' , ac.Id ) ) ; PicasaFeed photoFeed = service.Query ( photoQuery ) ; PicasaEntry picasaEntry = photoFeed.Entries [ 0 ] ; ulong timestamp = Convert.ToUInt64 ( picasaEntry.GetPhotoExtensionValue ( `` timestamp '' ) ) ; // deduct 9 hoursDateTime dt = FromUnixTime ( pa.Timestamp ) .AddHours ( -9 ) ; picasaEntry.SetPhotoExtensionValue ( `` timestamp '' , Convert.ToString ( ToUnixTime ( dt ) ) ) ; var updatedEntry = ( PicasaEntry ) picasaEntry.Update ( ) ;",How to update the timestamp on a photo or add the time zone on Google+ Photos ? "C_sharp : I have a NetworkStream which I read asynchronously ( using async/await ) Unfortunatly , an io exception sometimes occurs : `` The I/O operation has been aborted because of either a thread exit or an application request . `` I believe I hit a requirement documented in Socke.EndReceive : http : //msdn.microsoft.com/en-us/library/w7wtt64b.aspx . Which states : All I/O initiated by a given thread is canceled when that thread exits . A pending asynchronous operation can fail if the thread exits before the operation completes.Because the async method runs on the default scheduler , this requirement can not be assured.Is there a way around this ? Do I need to start a dedicated Thread to initiate I/O ? best regards , Dirk await Task < int > .Factory.FromAsync ( ( cb , state ) = > stream.BeginRead ( buffer , offset , readLen - offset ) , stream.EndRead , null ) ;",Asynchronous socket reading : the initiating thread must not be exited - what to do ? "C_sharp : Can someone explain to me what needs to be loaded into the stack prior to making a function call via reflection.emit ? I have a very simple method I want to generate the method in the following class dynamically ( forget the rest , I got them sorted out ) I have a copy of the above test , for reference , and I noticed the following opcodes were emitted , prior to the `` call '' .ldarg_1 ldarg_0 ldfldThe question is what 's ldarg_0 doing there ? I only need 2 arguments for the call , why does the CLR requires ldarg_0 to be pushed to the stack ? public static void Execute ( string 1 , string 2 ) public class Test { public string s1 ; public void Run ( string s2 ) { MyOtherClass.Execute ( s2 , s1 ) } }",Reflection emit stack and method call "C_sharp : I have a design question related to Entity Framework entities.I have created the following entity : This entity has as an example 30 columns . When I need to create a new entity this works great . I have all of the required fields in order to insert into the database.I have a few places in my app where I need to display some tabular data with some of the fields from SomeEntity , but I do n't need all 30 columns , maybe only 2 or 3 columns . Do I create an entirely new entity that has only the fields I need ( which maps to the same table as SomeEntity , but only retrieves the column I want ? ) Or does it make more sense to create a domain class ( like PartialEntity ) and write a query like this : I am not sure what the appropriate way to do this type of thing . Is it a bad idea to have two entities that map to the same table/columns ? I would never actually need the ability to create a PartialEntity and save it to the database , because it would n't have all of the fields that are required . public class SomeEntity { // full review details here } var partialObjects = from e in db.SomeEntities select new PartialEntity { Column1 = e.Column1 , Column2 = e.Column2 } ;",Entity Framework Design - Multiple `` Views '' for the data "C_sharp : I 'm playing around trying to get a simple MVC website working . In it I am using a database and Entity Framework to communicate with it ( as I have been doing for months on other projects ) .Everything has been going fine up until I tried to retrieve from a specific table in my database . If I query that , the select that EF generates mysteriously contains a column that does not exists in that table ( or any table in that database ) . This of course throws an exception complaining about the column not existing : Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : System.Data.SqlClient.SqlException : Invalid column name 'PerformerFolder_Id'.I 've created a UnitOfWork object that uses the repository pattern to retrieve the data , and to make it as simple as possible , I exposed the DataContext so I could manually query that for testing : The DAL.File is a class generated by the POCO generator : I do have a PerformerFolder that has an Id column as the primary key , but that is in no way connected to the file table.If I enable debug logging on the DataContext I see that it runs the following query : I 've tried searching all file for `` PerformerFolder '' and other than the logical places ( in the PerformerFolder class ) it did not turn up anything . It seems to be generated based on something , but I just ca n't figure out what or where.Does anyone have any suggestions ? var test = loUnitOfWork.Context.Set < DAL.File > ( ) ; public partial class File : BaseEntity { public int Id { get ; set ; } public string FilePath { get ; set ; } public string FileName { get ; set ; } public virtual ICollection < FilePerformer > FilePerformerCollection { get ; set ; } public virtual ICollection < FileProperty > FilePropertyCollection { get ; set ; } public File ( ) { FilePerformerCollection = new List < FilePerformer > ( ) ; FilePropertyCollection = new List < FileProperty > ( ) ; InitializePartial ( ) ; } partial void InitializePartial ( ) ; } SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ FilePath ] AS [ FilePath ] , [ Extent1 ] . [ FileName ] AS [ FileName ] , [ Extent1 ] . [ PerformerFolder_Id ] AS [ PerformerFolder_Id ] FROM [ dbo ] . [ File ] AS [ Extent1 ]",Wrong select query generated with Entity Framework ( mysterious extra column ) "C_sharp : Possible Duplicate : IEnumerable.Cast < > One can implicitly convert from int to double . Why does `` Specified cast is not valid . '' exception is raised here ? I have tried several `` versions '' of it . P.S . I know possible solutions like : But I 'm curious how Cast works = > why it does n't work in this example which looks so obvious . double [ ] a = Enumerable.Range ( 0 , 7 ) .Cast < double > ( ) .ToArray ( ) ; double [ ] a = Enumerable.Range ( 0 , 7 ) .Select ( x = > ( double ) x ) .ToArray ( ) ;",Convert int [ ] to double [ ] using Cast < T > ? "C_sharp : I was trying to find an answer but it seems it 's not directly discussed a lot . I have a composition root of my application where I create a DI-container and register everything there and then resolve needed top-level classes that gets all dependencies . As this is all happening internally - it becomes hard to unit test the composition root . You can do virtual methods , protected fields and so on , but I am not a big fan of introducing such things just to be able to unit test . There are no big problems with other classes as they all use constructor injection . So the question is - does it make much sense to test the composition root at all ? It does have some additional logic , but not much and in most cases any failures there would pop up during application start.Some code that I have : public void Initialize ( /*Some configuration parameters here*/ ) { m_Container = new UnityContainer ( ) ; /*Regestering dependencies*/ m_Distributor = m_Container.Resolve < ISimpleFeedMessageDistributor > ( ) ; } public void Start ( ) { if ( m_Distributor == null ) { throw new ApplicationException ( `` Initialize should be called before start '' ) ; } m_Distributor.Start ( ) ; } public void Close ( ) { if ( m_Distributor ! = null ) { m_Distributor.Close ( ) ; } }",Does composition root needs unit testing ? "C_sharp : I was doing some experimental calculations for fun , when I came across an interesting result : Which is not what I expected.System : Windows 7 64 , i3 2120 [ dual core , 4 threads ] , Visual Studio 2010.Build : Optimization 's on , Release mode [ no debugger ] , 32 Bit.Of secondary interest is the disappointing 64 bit performance . While it 's more inline of what I 'd expect in terms of ratio 's it accomplishes this by being slower across the board.The calculation is simple : For the indices x & y find the closest Vector3 and store it in 2D array.The question , if you dare , is to try to explain why the inline for loop is so slow . Bonus points for explaining the 64bit versions lack of performance.UPDATE : Thanks to the efforts of Drew Marsh we now have this super optimized version that inlines all the V3 operations.And it gives the following results : x86x64So the good news is that we can drastically increase the performance of this code - and get the single threaded version to be operating at a speed somewhat in keeping with its parallel cousin.The bad news is that this means ditching x64 entirely and manually in-lining all math.At this stage , I 'm very disappointed in the performance of the compilers - I expected them to be much better.ConclusionThis is fubar and sad ... and while we do n't really know why we can make an educated guess to it being caused by a stupid compiler/s . 24s to 3.8s simply by changing the compiler from x64 to x86 and doing some manual in-lining is not what I 'd expect . However I 've finished off the proof of concept I was writing , and thanks to a simple spacial hash I can compute a 1024 by 1024 image with 70,000 'points ' in 0.7s - ~340000 % faster than that of my original x64 scenario and with no threading or in-lining . As such I 've accepted an answer - the immediate need is gone , though I ' l be still looking into the issue.The code is available here and here - it generates a nice Voronoi diagram as a side effect : P Completed 1024x1024 pixels with 700 points in ... For Loop ( Inline ) : 19636msFor Loop : 12612msParallel.For Loop : 3835ms Completed 1024x1024 pixels with 700 points in ... For Loop ( Inline ) : 23409msFor Loop : 24373msParallel.For Loop : 6839ms using System ; using System.Diagnostics ; using System.Threading.Tasks ; namespace TextureFromPoints { class Program { const int numPoints = 700 ; const int textureSize = 1024 ; static Random rnd = new Random ( ) ; static void Main ( string [ ] args ) { while ( true ) { Console.WriteLine ( `` Starting '' ) ; Console.WriteLine ( ) ; var pointCloud = new Vector3 [ numPoints ] ; for ( int i = 0 ; i < numPoints ; i++ ) pointCloud [ i ] = new Vector3 ( textureSize ) ; var result1 = new Vector3 [ textureSize , textureSize ] ; var result2 = new Vector3 [ textureSize , textureSize ] ; var result3 = new Vector3 [ textureSize , textureSize ] ; var sw1 = Stopwatch.StartNew ( ) ; for ( int x = 0 ; x < textureSize ; x++ ) for ( int y = 0 ; y < textureSize ; y++ ) { var targetPos = new Vector3 ( x , y , 0 ) ; var nearestV3 = pointCloud [ 0 ] ; var nearestV3Distance = nearestV3.DistanceToPoint ( targetPos ) ; for ( int i = 1 ; i < numPoints ; i++ ) { var currentV3 = pointCloud [ i ] ; var currentV3Distance = currentV3.DistanceToPoint ( targetPos ) ; if ( currentV3Distance < nearestV3Distance ) { nearestV3 = currentV3 ; nearestV3Distance = currentV3Distance ; } } result1 [ x , y ] = nearestV3 ; } sw1.Stop ( ) ; var sw2 = Stopwatch.StartNew ( ) ; for ( int x = 0 ; x < textureSize ; x++ ) for ( int y = 0 ; y < textureSize ; y++ ) Computation ( pointCloud , result2 , x , y ) ; sw2.Stop ( ) ; var sw3 = Stopwatch.StartNew ( ) ; Parallel.For ( 0 , textureSize , x = > { for ( int y = 0 ; y < textureSize ; y++ ) Computation ( pointCloud , result3 , x , y ) ; } ) ; sw3.Stop ( ) ; Console.WriteLine ( `` Completed { 0 } x { 0 } pixels with { 1 } points in ... '' , textureSize , numPoints ) ; Console.WriteLine ( `` { 0 } : { 1 } ms '' , `` For Loop ( Inline ) '' , sw1.ElapsedMilliseconds ) ; Console.WriteLine ( `` { 0 } : { 1 } ms '' , `` For Loop '' , sw2.ElapsedMilliseconds ) ; Console.WriteLine ( `` { 0 } : { 1 } ms '' , `` Parallel.For Loop '' , sw3.ElapsedMilliseconds ) ; Console.WriteLine ( ) ; Console.Write ( `` Verifying Data : `` ) ; Console.WriteLine ( CheckResults ( result1 , result2 ) & & CheckResults ( result1 , result3 ) ? `` Valid '' : `` Error '' ) ; Console.WriteLine ( ) ; Console.WriteLine ( ) ; Console.ReadLine ( ) ; } } private static bool CheckResults ( Vector3 [ , ] lhs , Vector3 [ , ] rhs ) { for ( int x = 0 ; x < textureSize ; x++ ) for ( int y = 0 ; y < textureSize ; y++ ) if ( ! lhs [ x , y ] .Equals ( rhs [ x , y ] ) ) return false ; return true ; } private static void Computation ( Vector3 [ ] pointCloud , Vector3 [ , ] result , int x , int y ) { var targetPos = new Vector3 ( x , y , 0 ) ; var nearestV3 = pointCloud [ 0 ] ; var nearestV3Distance = nearestV3.DistanceToPoint ( targetPos ) ; for ( int i = 1 ; i < numPoints ; i++ ) { var currentV3 = pointCloud [ i ] ; var currentV3Distance = currentV3.DistanceToPoint ( targetPos ) ; if ( currentV3Distance < nearestV3Distance ) { nearestV3 = currentV3 ; nearestV3Distance = currentV3Distance ; } } result [ x , y ] = nearestV3 ; } struct Vector3 { public float x ; public float y ; public float z ; public Vector3 ( float x , float y , float z ) { this.x = x ; this.y = y ; this.z = z ; } public Vector3 ( float randomDistance ) { this.x = ( float ) rnd.NextDouble ( ) * randomDistance ; this.y = ( float ) rnd.NextDouble ( ) * randomDistance ; this.z = ( float ) rnd.NextDouble ( ) * randomDistance ; } public static Vector3 operator - ( Vector3 a , Vector3 b ) { return new Vector3 ( a.x - b.x , a.y - b.y , a.z - b.z ) ; } public float sqrMagnitude ( ) { return x * x + y * y + z * z ; } public float DistanceToPoint ( Vector3 point ) { return ( this - point ) .sqrMagnitude ( ) ; } } } } using System ; using System.Diagnostics ; using System.Threading.Tasks ; namespace TextureFromPoints { class RevisedProgram { const int numPoints = 700 ; const int textureSize = 1024 ; static Random rnd = new Random ( ) ; static void Main ( string [ ] args ) { while ( true ) { Console.WriteLine ( `` Starting REVISED '' ) ; Console.WriteLine ( ) ; var pointCloud = new Vector3 [ numPoints ] ; for ( int i = 0 ; i < numPoints ; i++ ) pointCloud [ i ] = new Vector3 ( textureSize ) ; var result1 = new Vector3 [ textureSize , textureSize ] ; var result2 = new Vector3 [ textureSize , textureSize ] ; var result3 = new Vector3 [ textureSize , textureSize ] ; var sw1 = Inline ( pointCloud , result1 ) ; var sw2 = NotInline ( pointCloud , result2 ) ; var sw3 = Parallelized ( pointCloud , result3 ) ; Console.WriteLine ( `` Completed { 0 } x { 0 } pixels with { 1 } points in ... '' , textureSize , numPoints ) ; Console.WriteLine ( `` { 0 } : { 1 } ms '' , `` For Loop ( Inline ) '' , sw1.ElapsedMilliseconds ) ; Console.WriteLine ( `` { 0 } : { 1 } ms '' , `` For Loop '' , sw2.ElapsedMilliseconds ) ; Console.WriteLine ( `` { 0 } : { 1 } ms '' , `` Parallel.For Loop '' , sw3.ElapsedMilliseconds ) ; Console.WriteLine ( ) ; Console.Write ( `` Verifying Data : `` ) ; Console.WriteLine ( CheckResults ( result1 , result2 ) & & CheckResults ( result1 , result3 ) ? `` Valid '' : `` Error '' ) ; Console.WriteLine ( ) ; Console.WriteLine ( ) ; Console.ReadLine ( ) ; } } private static Stopwatch Parallelized ( Vector3 [ ] pointCloud , Vector3 [ , ] result3 ) { var sw3 = Stopwatch.StartNew ( ) ; Parallel.For ( 0 , textureSize , x = > { for ( int y = 0 ; y < textureSize ; y++ ) Computation ( pointCloud , result3 , x , y ) ; } ) ; sw3.Stop ( ) ; return sw3 ; } private static Stopwatch NotInline ( Vector3 [ ] pointCloud , Vector3 [ , ] result2 ) { var sw2 = Stopwatch.StartNew ( ) ; for ( int x = 0 ; x < textureSize ; x++ ) for ( int y = 0 ; y < textureSize ; y++ ) Computation ( pointCloud , result2 , x , y ) ; sw2.Stop ( ) ; return sw2 ; } private static Stopwatch Inline ( Vector3 [ ] pointCloud , Vector3 [ , ] result1 ) { var sw1 = Stopwatch.StartNew ( ) ; for ( int x = 0 ; x < textureSize ; x++ ) for ( int y = 0 ; y < textureSize ; y++ ) { var targetPos = new Vector3 ( x , y , 0 ) ; var nearestV3 = pointCloud [ 0 ] ; Vector3 temp1 = new Vector3 ( nearestV3.x - targetPos.x , nearestV3.y - targetPos.y , nearestV3.z - targetPos.z ) ; var nearestV3Distance = temp1.x * temp1.x + temp1.y * temp1.y + temp1.z * temp1.z ; for ( int i = 1 ; i < numPoints ; i++ ) { var currentV3 = pointCloud [ i ] ; Vector3 temp2 = new Vector3 ( currentV3.x - targetPos.x , currentV3.y - targetPos.y , currentV3.z - targetPos.z ) ; var currentV3Distance = temp2.x * temp2.x + temp2.y * temp2.y + temp2.z * temp2.z ; if ( currentV3Distance < nearestV3Distance ) { nearestV3 = currentV3 ; nearestV3Distance = currentV3Distance ; } } result1 [ x , y ] = nearestV3 ; } sw1.Stop ( ) ; return sw1 ; } private static bool CheckResults ( Vector3 [ , ] lhs , Vector3 [ , ] rhs ) { for ( int x = 0 ; x < textureSize ; x++ ) for ( int y = 0 ; y < textureSize ; y++ ) if ( ! lhs [ x , y ] .Equals ( rhs [ x , y ] ) ) return false ; return true ; } private static void Computation ( Vector3 [ ] pointCloud , Vector3 [ , ] result , int x , int y ) { var targetPos = new Vector3 ( x , y , 0 ) ; var nearestV3 = pointCloud [ 0 ] ; Vector3 temp1 = new Vector3 ( nearestV3.x - targetPos.x , nearestV3.y - targetPos.y , nearestV3.z - targetPos.z ) ; var nearestV3Distance = temp1.x * temp1.x + temp1.y * temp1.y + temp1.z * temp1.z ; for ( int i = 1 ; i < numPoints ; i++ ) { var currentV3 = pointCloud [ i ] ; Vector3 temp2 = new Vector3 ( currentV3.x - targetPos.x , currentV3.y - targetPos.y , currentV3.z - targetPos.z ) ; var currentV3Distance = temp2.x * temp2.x + temp2.y * temp2.y + temp2.z * temp2.z ; if ( currentV3Distance < nearestV3Distance ) { nearestV3 = currentV3 ; nearestV3Distance = currentV3Distance ; } } result [ x , y ] = nearestV3 ; } struct Vector3 { public float x ; public float y ; public float z ; public Vector3 ( float x , float y , float z ) { this.x = x ; this.y = y ; this.z = z ; } public Vector3 ( float randomDistance ) { this.x = ( float ) rnd.NextDouble ( ) * randomDistance ; this.y = ( float ) rnd.NextDouble ( ) * randomDistance ; this.z = ( float ) rnd.NextDouble ( ) * randomDistance ; } } } } Completed 1024x1024 pixels with 700 points in ... For Loop ( Inline ) : 3820msFor Loop : 3962msParallel.For Loop : 1681ms Completed 1024x1024 pixels with 700 points in ... For Loop ( Inline ) : 10978msFor Loop : 10924msParallel.For Loop : 3073ms",5x Performance with Parallel.For ... on a Dual Core ? "C_sharp : I wish I could be more specific here , but unfortunately this might be hard . I basically hope this is some `` well '' -known timeout or setup issue.We have a website running an ( JS/html - ASP.net project ) website overview on a screen at a factory . This screen has no keyboard so it should keep refreshing the page forever - years perhaps ( though 1 week might be okay ) . ( It is used by factory workers to see incoming transports etc . ) This all works perfectly ; the site continuously updates itself and gets the new correct data.Then , sometimes , in the morning this `` overview '' screen has no data and the workers have to manually refresh the site using the simple refresh button or F5 - which fixes everything.I have tried a few things trying to reproduce the error myself including : Cutting the internet connection and MANY other ways of making it timeout ( breakpoints , stopping services etc . ) .Setting the refresh time of setInterval to 100ms and letting the site run 3-5 minutes . ( normal timer is 1 minute ) setInterval SHOULD run forever according to the internet searching I have done.Checked that `` JavaScript frequency '' has not been turned down in power saving settings.No matter what ; the site resumes correct function WITHOUT a refresh as soon as I plug in the internet cable or whatever again - I ca n't reproduce the error.The website is dependent on a backend WCF service and project integration , but since the workers are fixing this with a simple refresh I am assuming this has not crashed.EDIT : The browser I tried to reproduce the error in was IE/win7 . I will ask about the factory tomorrow , but I am guessing IE/win ? also.Is setInterval in fact really infinite or is there something else wrong here ? All help much appreciated.UPDATE : I came in this morning after leaving the website running in debug mode with a breakpoint in the catch clause of the site updating code.There was a 2 min . timeout error ( busy server cleanup during the night likely ) and THEN forever after that a null-reference error at this line : I fixed it with a refresh like the workers.I am now thinking it may be a session timeout all though we keep pinging the server..Of course my particular session timeout may have been caused by the breakpoint making it hang forever at the first timeout - still the behavior is the same as at the factory.I will make sure to update you guys with the final solution later.UPDATE 2 : Testing is ongoing.UPDATE 3 : The factory is IE 9 , their test machine is IE 7 and my machine is IE 9 . The error was seen on IE7 but NOT my IE9 after a weekends runtime.We tried turning off ajax cache during our critical data_binding code , but it did nothing.I tested for memory leaks and was able to create a decent leak IF I refresh 100 times per minute . I do n't think it was the problem though and a refresh cleaned the memory used.We will try the auto-refresh thing now . var showHistory = ( bool ) Session.Contents [ `` ShowHistory '' ] ;",Website running JavaScript setInterval starts to fail after ~1day "C_sharp : I have just taken over an ASP.NET MVC project and some refactoring is required , but I wanted to get some thoughts / advice for best practices.The site has an SQL Server backend and here is a review of the projects inside the solution : DomainObjects ( one class per database table ) DomainORM ( mapping code from objects to DB ) Models ( business logic ) MVC ( regular ASP.NET MVC web setup ) -- -- Controllers -- -- ViewModels -- -- Views -- -- ScriptsThe first `` issue '' I see is that while the Domain objects classes are pretty much POCO with some extra `` get '' properties around calculated fields , there is some presentation code in the Domain Objects . For example , inside the DomainObjects project , there is a Person object and I see this property on that class : so obviously having HTML-generated content inside the domain object seems wrong.Refactor Approaches : My first instinct was to move this to the ViewModel class inside the MVC project , but I see that there are a lot of views that hit this code so I do n't want to duplicate code in each view model.The second idea was to create PersonHTML class that was either:2a . A wrapper that took in a Person in the constructor or2b . A class that inherited from Person and then has all of these HTML rendering methods.The view Model would convert any Person object to a PersonHTML object and use that for all rendering code.I just wanted to see : If there is a best practice here as it seems like this is a common problem / pattern that comes upHow bad is this current state considered because besides feeling wrong , it is not really causing any major problems understanding the code or creating any bad dependencies . Any arguments to help describe why leaving code in this state is bad from a real practical sense ( vs. a theoretical separation of concerns argument ) would be helpful as well as there is debate in the team whether it 's worth it to change . public class Person { public virtual string NameIdHTML { get { return `` < a href='/People/Detail/ '' + Id + `` ' > '' + Name + `` < /a > ( `` + Id + `` ) '' ; } } }",What is the best way to refactor presentation code out of my domain objects in an ASP.NET MVC solution ? "C_sharp : In C # , I want to make `` smart '' enums , kind of like is possible in Java , where there 's more information attached to an enum value than just the underlying int . I happened upon a scheme of making a class ( instead of an enum ) , as in the following simple example : But when I run Visual Studio 's `` Code Analyzer '' on that , it gives me warning C2104 , `` Do not declare read only mutable reference types '' .I get why you generally would n't want to declare read only mutable reference types , but ... my class is not mutable , is it ? Reading the docs for the warning , it seems like they 're just kind of assuming that any read only reference type is mutable . For example , it says that if the type really is immutable , then feel free to suppress this warning . And in fact it gives me the same warning for the following even simpler class : So , OK , unless I 'm seriously misunderstanding mutability , CA2104 does n't understand it . And its recommendation is for me to suppress the warning for each line where it comes up , as long as I 'm sure the class is really immutable . But : ( 1 ) So unless I turn this check off entirely , I have to suppress it every single time I ever use an immutable read only member , which I might do HUNDREDS of times for any given enumeration ? ( 2 ) But worse , even if I do that , then someone can later accidentally introduce mutability , but someone else will still have the false sense of security given by the fact that someone manually put the suppression there saying `` I checked and this is immutable '' ? public sealed class C { public static readonly C C1 = new C ( 0 , 1 ) ; public static readonly C C2 = new C ( 2 , 3 ) ; private readonly int x ; private readonly int y ; private C ( int x , int y ) { this.x = x ; this.y = y ; } public int X { get { return this.x ; } } public int Y { get { return this.y ; } } } public sealed class C { public static readonly C C1 = new C ( ) ; public static readonly C C2 = new C ( ) ; private C ( ) { } }",C # mutability - VS Code Analysis giving me CA2104 ? Seems ... poor . Am I misunderstanding ? "C_sharp : Could you explain to me why after executing the following code the Selected property is not updated to true ? The ListItem type used comes from System.Web.UI.WebControls namespace and is a class ( not a struct . ) I believed the FirstOrDefault function returns a reference to an instance which I can update and pass around in the items enumerable.Is that because the enumerator is executed each time a foreach is called and thus creating new items instead of returning the set containing the item I updated ? // produce list items out of the communitiesIEnumerable < ListItem > items = communities.Select ( community = > new ListItem ( community.Name , community.Id.ToString ( ) ) ) ; // mark the right list item as selected , if neededif ( platform.CommunityId > 0 ) { string strCommunityId = platform.CommunityId.ToString ( ) ; ListItem selectedItem = items.FirstOrDefault ( item = > item.Value == strCommunityId ) ; if ( selectedItem ! = null ) selectedItem.Selected = true ; } // now items do not store any updated item !",Why is IEnumerable losing updated data ? "C_sharp : I have multiple methods with different input parameters and same outputs.I call Method1 with input type of number and then check its result , if the result is valid next method gets called ( this time with input type of string ) and so on.In this example i have three methods , but if i have 10 methods or 20 methods with different inputs and same outputs i have to write redundant code , how can i prevent these redundant codes ? this is sample of methods : And i call this methods as following : public ValidationResult Method1 ( int number , string family ) { var validationResult = new validationResult ( ) ; if ( number > 10 || family= '' akbari '' ) { validationResult.Errors.Add ( new ValidationFailure ( `` '' , `` Invalid Number '' ) ) ; } return validationResult ; } public ValidationResult Method1 ( string name ) { var validationResult = new validationResult ( ) ; if ( name.Length > 20 ) { validationResult.Errors.Add ( new ValidationFailure ( `` '' , `` Invalid name '' ) ) ; } return validationResult ; } public ValidationResult Method1 ( double average , string family ) { var validationResult = new validationResult ( ) ; if ( average < 14 ) { validationResult.Errors.Add ( new ValidationFailure ( `` '' , `` Invalid average '' ) ) ; } return validationResult ; } var validationResult = Method1 ( 20 , `` test '' ) ; if ( ! validationResult.IsValid ) { return validationResult.FirstError ( ) ; } validationResult = Method2 ( `` Samsung '' ) ; if ( ! validationResult.IsValid ) { return validationResult.FirstError ( ) ; } validationResult = Method3 ( 15.5 ) ; if ( ! validationResult.IsValid ) { return validationResult.FirstError ( ) ; }",Call multiple method with same out and different input in loop "C_sharp : They both do the same thing . Is one way better ? Obviously if I write the code I 'll know what I did , but how about someone else reading it ? OR if ( ! String.IsNullOrEmpty ( returnUrl ) ) { return Redirect ( returnUrl ) ; } return RedirectToAction ( `` Open '' , `` ServiceCall '' ) ; if ( ! String.IsNullOrEmpty ( returnUrl ) ) { return Redirect ( returnUrl ) ; } else { return RedirectToAction ( `` Open '' , `` ServiceCall '' ) ; }",What is the cleanest way to write this if..then logic ? "C_sharp : I need to render a 1027 * 768 bitmap to the client window ( same size ) and I do n't have more than 10-15 ms to complete this task . I am using bufferedGraphics allocated from a bufferedGraphicsContect object and still notice huge performance issues.I am using unsafe code to perform my copy operations and found unbelievable results . I know the Graphics / BufferedGraphics objects should have some sort of a drawing surface in memory . I was wondering if someone could point me in the right direction on how to write to this surface using Marshal or some other unsafe low level method.I am in the process of porting an older c # graphics application . I know c # is not designed for heavy graphics and that there are better tools than GDI+ available , unfortunately I do n't have those luxuries.This is what I have come up with so far ... Any insight what so ever is greatly apperciated.EDIT : Forgot to mention I 'm looking for a low level alternative to Graphics.DrawImage ( ) , preferrably writing to Graphics surface memory , using pointers ? Thanks again byte [ ] _argbs = null ; static readonly Bitmap _bmUnderlay = Properties.Resources.bg ; static Bitmap _bmpRender = new Bitmap ( 1024 , 768 , System.Drawing.Imaging.PixelFormat.Format24bppRgb ) ; int bmpHeight = Properties.Resources.bg.Height ; int bmpWidth = Properties.Resources.bg.Width ; static BufferedGraphicsContext _bgc = new BufferedGraphicsContext ( ) ; internal unsafe void FillBackBuffer ( Point cameraPos ) { // lock up the parts of the original image to read ( parts of it ) System.Drawing.Imaging.BitmapData bmd = _bmUnderlay.LockBits ( new Rectangle ( cameraPos.X , cameraPos.Y , 1024 , 768 ) , System.Drawing.Imaging.ImageLockMode.ReadOnly , System.Drawing.Imaging.PixelFormat.Format24bppRgb ) ; // get the address of the first line . IntPtr ptr = bmd.Scan0 ; //if ( _argbs == null || _argbs.Length ! = bmd.Stride * bmd.Height ) // _argbs = new byte [ bmd.Stride * bmd.Height ] ; if ( _argbs == null || _argbs.Length ! = 1024 * 3 * 768 ) _argbs = new byte [ 1024 * 3 * 768 ] ; // copy data out to a buffer Marshal.Copy ( ptr , _argbs , 0 , 1024 * 3 * 768 ) ; _bmUnderlay.UnlockBits ( bmd ) ; // lock the new image to write to ( all of it ) System.Drawing.Imaging.BitmapData bmdNew = _bmpRender.LockBits ( new Rectangle ( 0 , 0 , 1024 , 768 ) , System.Drawing.Imaging.ImageLockMode.ReadWrite , System.Drawing.Imaging.PixelFormat.Format24bppRgb ) ; // copy data to new bitmap Marshal.Copy ( _argbs , 0 , bmdNew.Scan0 , 1024 * 3 * 768 ) ; _bmpRender.UnlockBits ( bmdNew ) ; } private unsafe void _btnGo_Click ( object sender , EventArgs e ) { // less than 2 ms to complete ! ! ! ! ! ! ! ! FillBackBuffer ( new Point ( ) ) ; using ( BufferedGraphics bg = _bgc.Allocate ( CreateGraphics ( ) , ClientRectangle ) ) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch ( ) ; sw.Start ( ) ; ///// /// // This method takes over 17 ms to complete bg.Graphics.DrawImageUnscaled ( _bmpRender , new Point ( ) ) ; // /// ///// sw.Start ( ) ; this.Text = sw.Elapsed.TotalMilliseconds.ToString ( ) ; bg.Render ( ) ; } }",Write to buffered graphics surface via pointer manupilation "C_sharp : I 'm learning C # and a thought came up when coding . Is it possible to automaticly store parameters from a constructor to the fields in a simple way without having to write this.var = var on every variable to store them ? Example : Is there a way to avoid writing this.varX = varX and save all the variables to the fields if the names are the same ? class MyClass { int var1 ; int var2 ; int var3 ; int var4 ; public MyClass ( int var1 , int var2 , int var3 , int var4 ) { this.var1 = var1 ; this.var2 = var2 ; this.var3 = var3 ; this.var4 = var4 ; } }",How to store all ctor parameters in fields "C_sharp : For example in F # we can defineand to update it I can doThat 's brilliant and the fact that records automatically implement IStructuralEquality with no extra effort makes me wish for this in C # . However Perhaps I can define my records in F # but still be able to perform some updates in C # . I imagine an API likeIs there a way , and I do n't mind dirty hacks , to implement CopyAndUpdate as above ? The C # signiture for CopyAndUpdate would be type MyRecord = { X : int ; Y : int ; Z : int } let myRecord1 = { X = 1 ; Y = 2 ; Z = 3 ; } let myRecord2 = { myRecord1 with Y = 100 ; Z = 2 } MyRecord myRecord2 = myRecord .CopyAndUpdate ( p= > p.Y , 10 ) .CopyAndUpdate ( p= > p.Z , 2 ) T CopyAndUpdate < T , P > ( this T , Expression < Func < T , P > > selector , P value )",Can we get access to the F # copy and update feature from c # ? "C_sharp : I am trying to read in from a file where a folder path is specified using environment variable shortcuts , like the following : I get the following error when trying to use Path.Combine ( ) to concatenate this with a filename : Do I have to parse environment variables ( like % programfiles ( x86 ) % and % appdata % ) out and manually replace them , or is there a another way to have these resolved ? Seems like a common use case for copying files , e.g . patching . source destfilename.ext % programfiles ( x86 ) % \FolderName\ `` Could not find a part of the path % programfiles ( x86 ) % \FolderName\filename.ext ''",How to use environment variables in Path.Combine ( ) ? "C_sharp : I have a ASP.NET dynamic data site that has multiple filter controls built using metadata such as : How do I order these filters in a particular way . It seems very random . Can I use a metadata attribute or should I modify the page template , what 's the go ? [ ScaffoldTable ( true ) , MetadataType ( typeof ( Fees.Metadata ) ) ] public partial class Fees { public class Metadata { [ FilterUIHint ( `` DateRange '' ) ] public object InvoiceDate ; } {",How to change order of dynamic filter controls ? "C_sharp : I have a table that records what happens to a vehicle during a visit . For each visit , there is are multiple rows to denote what has been done . The table looks like thisI wish to construct a LINQ query capable of getting the amount of time a visit took . TotalTime is calculated by first finding the first and last ( lowest and highest ) ActionID , then last.EndTime - first.StartTime . Expected results : I can generate my expected results by doingI really do n't like the hack I used to get the last ActionID , and I would really like to be able to do this within 1 LINQ statement . What do I need to do to achieve this ? VisitID | ActionID | StartTime | EndTime 0 | 0 | 1/1/2013 | 1/2/2013 1 | 0 | 1/2/2013 | 1/4/2013 1 | 1 | 1/4/2013 | 1/7/2013 2 | 0 | 1/4/2013 | 1/5/2013 2 | 1 | 1/5/2013 | 1/6/2013 2 | 2 | 1/6/2013 | 1/7/2013 VisitID | TotalTime 0 | 1 1 | 5 2 | 3 var first = db.Visits.Where ( v = > v.ActionID == 0 ) var last = db.Visits.GroupBy ( x = > x.VisitID ) .Select ( g = > g.OrderByDescending ( x = > x.ActionID ) .First ( ) ) first.Join ( last , f = > f.VisitID , l = > l.VisitID , ( f , l ) new { VisitID = Key , TotalTime = l.EndTime - f.StartTime } ) ;",Calculating difference between different columns in different rows "C_sharp : I 'm working on a new game , and am trying to detect whether or not the player ( on a slope ) is colliding with a given mesh based off of their coordinates relative to the coordinates of the slope . I 'm using this function , which does n't seem to be working ( the slope seems too small or something ) Any suggestions ? Sample output:59.866976.225558 2761.33168.3019 degrees incline59.86698,46.1244559.866986.225558 2761.3320 degrees inclineEDIT : Partially fixed the problem . Slope detection works , but now I can walk through walls ? ? ? //Slopes float slopeY = max.Y-min.Y ; float slopeZ = max.Z-min.Z ; float slopeX = max.X-min.X ; float angle = ( float ) Math.Atan ( slopeZ/slopeY ) ; //Console.WriteLine ( OpenTK.Math.Functions.RadiansToDegrees ( ( float ) Math.Atan ( slopeZ/slopeY ) ) .ToString ( ) + '' degrees incline '' ) ; slopeY = slopeY/slopeZ ; float slopeZX = slopeY/slopeX ; //End slopes float surfaceposX = max.X-coord.X ; float surfaceposY = max.Y-coord.Y ; float surfaceposZ = min.Z-coord.Z ; min-=sval ; max+=sval ; //Surface coords //End surface coords //Y SHOULD = mx+b , where M = slope and X = surfacepos , and B = surfaceposZ if ( coord.X < max.X & coord.X > min.X & coord.Y > min.Y & coord.Y < max.Y & coord.Z > min.Z & coord.Z < max.Z ) { if ( slopeY ! =0 ) { Console.WriteLine ( `` Slope = `` +slopeY.ToString ( ) + '' SlopeZX= '' +slopeZX.ToString ( ) + '' surfaceposZ= '' +surfaceposZ.ToString ( ) ) ; Console.WriteLine ( surfaceposY- ( surfaceposY*slopeY ) ) ; //System.Threading.Thread.Sleep ( 40000 ) ; if ( surfaceposY- ( surfaceposZ*slopeY ) < 3 || surfaceposY- ( surfaceposX*slopeZX ) < 3 ) { return true ; } else { return false ; } } else { return true ; } } else { return false ; } //Slopes float slopeY = max.Y-min.Y ; float slopeZ = max.Z-min.Z ; float slopeX = max.X-min.X ; float angle = ( float ) Math.Atan ( slopeZ/slopeY ) ; //Console.WriteLine ( OpenTK.Math.Functions.RadiansToDegrees ( ( float ) Math.Atan ( slopeZ/slopeY ) ) .ToString ( ) + '' degrees incline '' ) ; slopeY = slopeY/slopeZ ; float slopey = slopeY+1/slopeZ ; float slopeZX = slopeY/slopeX ; //End slopes float surfaceposX = min.X-coord.X ; float surfaceposY = max.Y-coord.Y ; float surfaceposZ = min.Z-coord.Z ; min-=sval ; max+=sval ; //Surface coords //End surface coords //Y SHOULD = mx+b , where M = slope and X = surfacepos , and B = surfaceposZ if ( coord.X < max.X & coord.X > min.X & coord.Y > min.Y & coord.Y < max.Y & coord.Z > min.Z & coord.Z < max.Z ) { if ( slopeY ! =0 ) { Console.WriteLine ( `` Slope = `` +slopeY.ToString ( ) + '' SlopeZX= '' +slopeZX.ToString ( ) + '' surfaceposZ= '' +surfaceposZ.ToString ( ) ) ; Console.WriteLine ( surfaceposY- ( surfaceposY*slopeY ) ) ; //System.Threading.Thread.Sleep ( 40000 ) ; surfaceposZ = Math.Abs ( surfaceposZ ) ; if ( surfaceposY > ( surfaceposZ*slopeY ) & surfaceposY-2 < ( surfaceposZ*slopeY ) || surfaceposY > ( surfaceposX*slopeZX ) & surfaceposY-2 < ( surfaceposX*slopeZX ) ) { return true ; } else { return false ; } } else { return true ; } } else { return false ; }",Collision checking on slopes "C_sharp : We have a library that is being used by WPF and/or Winforms clients.We 've provided an asynchronous method similar to : We 've also ( unfortunately ) provided a synchronous wrapper method : which essentially just calls the asynchronous method and calls .Result on its task . We recently realized under certain circumstances some code in the GetIntAsync needs to run on the main UI thread ( it needs to use a legacy COM component that is marked as `` Single '' Threading model ( i.e . the component must run in the main STA thread not just any STA thread ) So the problem is that when GetInt ( ) is called on the main thread , it will deadlock since the .Result blocks the main thread , the code within GetIntAsync ( ) uses Dispatcher.Invoke to attempt to run on the main thread.The synchronous method is already being consumed so it would be a breaking change to remove it . So instead , we 've opted for using the WaitWithPumping in our synchronous GetInt ( ) method to allow the invoking to the main thread to work.This works fine except for clients that use GetInt ( ) from their UI code . Previously , they expected that using GetInt ( ) would leave their UI unresponsive -- that is , if they called GetInt ( ) from within a button 's click event handler , they would expect that no windows messages were processed until the handler returned . Now that messages are pumped , their UI is responsive and that same button can be clicked again ( and they probably did n't code their handler to be re-entrant ) .If there is a reasonable solution , we 'd like to not have our clients need to code against the UI being responsive during a call to GetIntQuestion : Is there a way to do a WaitWithPumping that will pump `` Invoke to main '' messages , but not pump other UI related messages ? It would suffice for our purposes if the client UI behaved as if a modal dialog were currently shown , albeit hidden ( i.e . user could n't access the other windows ) . But , from what I read , you can not hide a modal dialog.Other workarounds you can think of would be appreciated . Task < int > GetIntAsync ( ) int GetInt ( ) ;",Sync over Async avoiding deadlock and prevent UI from being responsive "C_sharp : So.. very odd problem.Using VS2015 and .net 4.52I developed this C # powershell code , it is running a script and catches the output . like this : Compiles and runs ( on a Windows 10 pro machine ) , no problems.Until I got a new machine ( surface pro 4 , so also windows 10 pro ) and tried to compile the code , I get this error : 'PSDataStreams ' does not contain a definition for 'Information ' and no extension method 'Information ' accepting a first argument of type 'PSDataStreams ' could be found ( are you missing a using directive or an assembly reference ? ) This is all TFS based , so I 'm sure it is the same code.If I goto definition on the two machines the problem becomes obvious : So , I commented out the not compiling code and ran it , to see what was happening runtime : So the property IS there.. Anybody got a good explanation for this ? BTW : the msdn documentation does not mention an Information property.. using ( PowerShell powerShellInstance = PowerShell.Create ( ) ) { powerShellInstance.AddScript ( scriptContents ) ; Collection < PSObject > PSOutput = powerShellInstance.Invoke ( ) ; if ( powerShellInstance.Streams.Information.Count > 0 ) { foreach ( var item in powerShellInstance.Streams.Information ) { //do something with info } } } }",`` Information '' property on Streams property of Powershell instance not available compiletime "C_sharp : In a repository , what is the best and most logical approach ? Deleting using the Entity or Deleting by ID ? I just wanted to know what is the best practice , should i delete by Entity ( achieved by finding the object first before deleting ) or delete by Id ( search the object on the method then delete ) . public void Delete ( Entity item ) ; VS.public void Delete ( int Id ) ;","Repository , Deleting Object , Model vs ID" "C_sharp : I want to premise that this question 's purpose is checking if there 's at least one way , even if through the most unsafe hack , to keep a reference to a non-blittable value type . I am aware that such a design type is comparable to a crime ; I would n't use it in any practical case , other than learning . So please accept reading heretic unsafe code for now.We know that a reference to a blittable type can be stored and increased this way : In terms of safety , the above class is comparable to a jump in the void ( no pun intended ) , but it works , as already mentioned here . If a variable allocated on the stack is passed to it and then the caller method 's scope terminates , you 're likely to run into a bug or an explicit access violation error . However , if you execute a program like this : The class wo n't be disposed until the relative application domain is unloaded , and so applies for the field . I honestly do n't know if fields in the high-frequency heap can be reallocated but I personally think not . But let 's put aside safety even more now ( if even possible ) . After reading this and this questions I was wondering if there was a way to create a similar approach for non-blittable static types , so I made this program , which actually works . Read the comments to see what it does.The actual problem/opportunity : We know that the compiler wo n't let us store a value passed by ref , but the __makeref keyword , as much undocumented and unadvised , offers the possibility of encapsulating and restoring a reference to blittable types . However , the return value of __makeref , TypedReference , is well protected . You ca n't store it in a field , you ca n't box it , you ca n't create an array of it , you ca n't use it in anonymous methods or lambdas . All that I managed to do was modifying the above code as follows : The above code works just as well and looks even worse than before but for the sake of knowledge , I wanted to do more with it , so I wrote the following : The Horror class is a combination of the Foo class and the above method , but as you 'll surely notice , it has one big problem . In the method Fix , the TypedReference tr is declared , its address is copied inside of the generic pointer _ptr , then the method ends and tr no longer exists . When the Clear method is called , the `` new '' tr is corrupted because _ptr points to an area of the stack which is no longer a TypedReference . So here comes the question : Is there any way to fool the compiler into keeping a TypedReference instance alive for an undetermined amount of time ? Any way to achieve the desired result will be considered good , even if it involves ugly , unsafe , slow code . A class implementing the following interface would be ideal : Please do n't judge the question as generic discussion because its purpose is to see if , after all , there is a way to store references to blittable types , as wicked as it may be.One last remark , I 'm aware of the possibilities to bind fields through FieldInfo , but it seemed to me that the latter method did n't support types deriving from Delegate very much.A possible solution ( bounty result ) I would 've marked AbdElRaheim 's answer as chosen as soon as he edited his post to include the solution which he provided in his comment , but I suppose it was n't very clear . Either way , among the techniques he provided , the one summed up in the following class ( which I modified slightly ) seemed the most `` reliable '' ( ironic to use that term , since we 're talking about exploiting a hack ) : What Fix does is , starting from the line marked as `` magic '' in the comment : Allocates memory in the process -- In the unmanaged part of it.Declares refPtr as a pointer to a TypedReference and sets it value to the pointer of the memory region allocated above . This is done , instead of using _ptr directly , because a field with type TypedReference* would throw an exception.Implicitly casts refPtr to void* and assigns the pointer to _ptr.Sets tr as the value pointed by refPtr and consequently _ptr.He also offered another solution , the one he originally wrote as an answer , but it seemed less reliable than the one above . On the other hand , there was also another solution provided by Peter Wishart , but it required accurate synchronization and each Horror instance would 've `` wasted '' a thread . I 'll take the chance to repeat that the above approach is in no way intended for real world usage , it was just an academic question . I hope it will be helpful for anyone reading this question . unsafe class Foo { void* _ptr ; public void Fix ( ref int value ) { fixed ( void* ptr = & value ) _ptr = ptr ; } public void Increment ( ) { var pointer = ( int* ) _ptr ; ( *pointer ) ++ ; } } static class Program { static int _fieldValue = 42 ; public static void Main ( string [ ] args ) { var foo = new Foo ( ) ; foo.Fix ( ref _fieldValue ) ; foo.Increment ( ) ; } } static class Program { static Action _event ; public static void Main ( string [ ] args ) { MakerefTest ( ref _event ) ; //The invocation list is empty again var isEmpty = _event == null ; } static void MakerefTest ( ref Action multicast ) { Action handler = ( ) = > Console.WriteLine ( `` Hello world . `` ) ; //Assigning a handler to the delegate multicast += handler ; //Executing the delegate 's invocation list successfully if ( multicast ! = null ) multicast ( ) ; //Encapsulating the reference in a TypedReference var tr = __makeref ( multicast ) ; //Removing the handler __refvalue ( tr , Action ) -= handler ; } } static void* _ptr ; static void MakerefTest ( ref Action multicast ) { Action handler = ( ) = > Console.WriteLine ( `` Hello world . `` ) ; multicast += handler ; if ( multicast ! = null ) multicast ( ) ; var tr = __makeref ( multicast ) ; //Storing the address of the TypedReference ( which is on the stack ! ) //inside of _ptr ; _ptr = ( void* ) & tr ; //Getting the TypedReference back from the pointer : var restoredTr = * ( TypedReference* ) _ptr ; __refvalue ( restoredTr , Action ) -= handler ; } unsafe class Horror { void* _ptr ; static void Handler ( ) { Console.WriteLine ( `` Hello world . `` ) ; } public void Fix ( ref Action action ) { action += Handler ; var tr = __makeref ( action ) ; _ptr = ( void* ) & tr ; } public void Clear ( ) { var tr = * ( TypedReference* ) _ptr ; __refvalue ( tr , Action ) -= Handler ; } } interface IRefStorage < T > : IDisposable { void Store ( ref T value ) ; //IDisposable.Dispose should release the reference } unsafe class Horror : IDisposable { void* _ptr ; static void Handler ( ) { Console.WriteLine ( `` Hello world . `` ) ; } public void Fix ( ref Action action ) { action += Handler ; TypedReference tr = __makeref ( action ) ; var mem = Marshal.AllocHGlobal ( sizeof ( TypedReference ) ) ; //magic var refPtr = ( TypedReference* ) mem.ToPointer ( ) ; _ptr = refPtr ; *refPtr = tr ; } public void Dispose ( ) { var tr = * ( TypedReference* ) _ptr ; __refvalue ( tr , Action ) -= Handler ; Marshal.FreeHGlobal ( ( IntPtr ) _ptr ) ; } }",Keep a TypedReference alive out of method block without returning it "C_sharp : I have the following code in a view model : One of the usings at the top of the code file is System , which contains Math.If I view Math.Sin ( Theta ) in the Watch window ( by selecting the code , right clicking , and choosing `` Add Watch '' ) , I get the following error : The name 'Math ' does not exist in the current context What I want to know is : Is this expected/default behavior for Visual Studio 2010 ? I could swear this never used to be a problem , but maybe it 's always worked that way and I somehow never noticed.If it 's not normal to get this error , any thoughts on what the problem could be ? There are a million settings in Visual Studio , and I would n't know where to begin.I should note this question is vaguely similar to this , but I 'm not having any issues mousing over my local variables , and I 'm not using PostSharp.EditI just tried resetting all my Visual Studio settings backs to default , and I 'm still getting the same error . If someone wants to try a simple test in Visual Studio , I just want to know if you get an error if you add a watch for Math.Sin ( 1 ) .Edit 2Here are a couple screen captures to show what I 'm experiencing : Edit 3Interestingly , intellisense works if I type Math . into the Watch window , but if I complete the expression , I still get the error : Edit 4To address BACON 's questions : I get the same behavior with QuickWatch and Immediate.Closing and reopening all the windows does not solve the problem.I 'm using Visual Studio 2010 Professional ( version 10.0.40219.1 SP1Rel ) I tried targeting .NET 4.0 Client Profile and full .NET 4.0 . Made no difference . I created a Console App ( rather than a WPF app ) targeting .NET 4.0 Client Profile , and finally , the error did not occur . So , WPF may be an issue ( or WPF with some third-party libraries ) . ( Will check on that next . ) public Point Location { get { var rangePixels = Range * PixelsPerMile ; var xCoordinate = OwnLocation.X * MapScale + rangePixels * Math.Cos ( Theta ) ; var yCoordinate = OwnLocation.Y * MapScale - rangePixels * Math.Sin ( Theta ) ; return new Point ( xCoordinate , yCoordinate ) ; } }",Visual Studio Watch window not taking into account usings "C_sharp : I would like to use substitution feature of donut caching . ... ... But I would like to pass additional parameter to callback function beside HttpContext.so the question is : How to pass additional argument to GetTime callback ? for instance , something like this : public static string GetTime ( HttpContext context ) { return DateTime.Now.ToString ( `` T '' ) ; } The cached time is : < % = DateTime.Now.ToString ( `` T '' ) % > < hr / > The substitution time is : < % Response.WriteSubstitution ( GetTime ) ; % > public static string GetTime ( HttpContext context , int newArgument ) { // i 'd like to get sth from DB by newArgument // return data depending on the db values // ... this example is too simple for my usage if ( newArgument == 1 ) return `` '' ; else return DateTime.Now.ToString ( `` T '' ) ; }",ASP .NET - Substitution and page output ( donut ) caching - How to pass custom argument to HttpResponseSubstitutionCallback delegate C_sharp : Let 's say I have the following class : Would this be a correct implementation of hashCode ? This is not how I usually do it ( I tend to follow Effective Java 's guide-lines ) but I always have the temptation to just do something like the above code.Thanks class ABC { private int myInt = 1 ; private double myDouble = 2 ; private String myString = `` 123 '' ; private SomeRandomClass1 myRandomClass1 = new ... private SomeRandomClass2 myRandomClass2 = new ... //pseudo code public int myHashCode ( ) { return 37 * myInt.hashcode ( ) * myDouble.hashCode ( ) * ... * myRandomClass.hashcode ( ) } },"is it incorrect to define an hashcode of an object as the sum , multiplication , whatever , of all class variables hashcodes ?" C_sharp : The string value is `` 90- '' . Why does the decimal parse it as `` -90 '' but double throws a FormatException ? var inputValue= `` 90- '' ; Console.WriteLine ( decimal.Parse ( inputValue ) ) ; Console.WriteLine ( double.Parse ( inputValue ) ) ;,Decimal Parse Issue "C_sharp : I have a function called `` CreateCriteriaExpression '' that takes a json string and creates a linq expression from it.This method is called by another called `` GetByCriteria '' , which calls the `` CreateCriteriaExpression '' method and then executes that expression against an entity framework context.For all of my entity framework objects , the `` GetByCriteria '' method is identical except for it 's types . So I am trying to convert it to use generics instead of hard coded types.When the `` GetByCriteria '' method gets to the point that it has to call the `` CreateCriteriaExpression '' method , I am having it use a factory class to determine the appropriate class/method to use . Then in the `` linq expression '' class , the linq expression for a particular type is created and returned.The problem I am having is that the linq expression has to be created for a specific type , but the return value is of the generic type and it wo n't automatically convert between the two , even though the one is a parent of the other ( covariance ) .Is there any way I can make this work ? Some example code : The `` GetByCriteria '' method : The JsonLinqParser class ( does not build ) : The JsonLinqParser base class : The factory class : /// < summary > /// Gets a < see cref= '' System.Collections.Generic.List '' / > of < see cref= '' TEntity '' / > /// objects that match the passed JSON string . /// < /summary > /// < param name= '' myCriteria '' > A list of JSON strings containing a key/value pair of `` parameterNames '' and `` parameterValues '' . < /param > /// < param name= '' myMatchMethod '' > Defines which matching method to use when finding matches on the < paramref name= '' myCriteria '' / > . < /param > /// < returns > /// A < see cref= '' System.Collections.Generic.List '' / > of < see cref= '' TEntity '' / > /// objects . /// < /returns > /// < seealso cref= '' TEntity '' / > /// /// < seealso cref= '' Common.MultipleCriteriaMatchMethod '' / > /// < remarks > /// This method takes a < see cref= '' System.Collections.Generic.List '' / > of JSON strings , and a < see cref= '' Common.MultipleCriteriaMatchMethod '' / > and returns a /// < see cref= '' System.Collections.Generic.List '' / > of all matching /// < see cref= '' TEntity '' / > objects from the back-end database . The < paramref name= '' myMatchMethod '' / > is used to determine how to match when multiple < paramref name= '' myCriteria '' / > are passed . You can require that any results must match on ALL the passed JSON criteria , or on ANY of the passed criteria . This is essentially an `` AND '' versus and `` OR '' comparison . /// < /remarks > [ ContractVerification ( true ) ] public static List < TEntity > GetByCriteria < TContext , TEntity > ( List < string > myCriteria , Common.MultipleCriteriaMatchMethod myMatchMethod ) where TContext : System.Data.Objects.ObjectContext , new ( ) where TEntity : System.Data.Objects.DataClasses.EntityObject { // Setup Contracts Contract.Requires ( myCriteria ! = null ) ; TContext db = new TContext ( ) ; // Intialize return variable List < TEntity > result = null ; // Initialize working variables // Set the predicates to True by default ( for `` AND '' matches ) var predicate = PredicateBuilder.True < TEntity > ( ) ; var customPropertiesPredicate = PredicateBuilder.True < TEntity > ( ) ; // Set the predicates to Falase by default ( for `` OR '' matches ) if ( myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAny ) { predicate = PredicateBuilder.False < TEntity > ( ) ; customPropertiesPredicate = PredicateBuilder.False < TEntity > ( ) ; } // Loop over each Criteria object in the passed list of criteria foreach ( string x in myCriteria ) { // Set the Criteria to local scope ( sometimes there are scope problems with LINQ ) string item = x ; if ( item ! = null ) { JsonLinqParser parser = JsonLinqParserFactory.GetParser ( typeof ( TEntity ) ) ; // If the designated MultipleCriteriaMatchMethod is `` MatchOnAll '' then use `` AND '' statements if ( myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAll ) { predicate = predicate.Expand ( ) .And < TEntity > ( parser.CreateCriteriaExpression < TEntity > ( item ) .Expand ( ) ) ; customPropertiesPredicate = customPropertiesPredicate.Expand ( ) .And < TEntity > ( parser.CreateCriteriaExpressionForCustomProperties < TEntity > ( item ) .Expand ( ) ) ; } // If the designated MultipleCriteriaMatchMethod is `` MatchOnAny '' then use `` OR '' statements else if ( myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAny ) { predicate = predicate.Expand ( ) .Or < TEntity > ( parser.CreateCriteriaExpression < TEntity > ( item ) .Expand ( ) ) ; customPropertiesPredicate = customPropertiesPredicate.Expand ( ) .Or < TEntity > ( parser.CreateCriteriaExpressionForCustomProperties < TEntity > ( item ) .Expand ( ) ) ; } } } // Set a temporary var to hold the results List < TEntity > qry = null ; // Set some Contract Assumptions to waive Static Contract warnings on build Contract.Assume ( predicate ! = null ) ; Contract.Assume ( customPropertiesPredicate ! = null ) ; // Run the query against the backend database qry = db.CreateObjectSet < TEntity > ( ) .AsExpandable < TEntity > ( ) .Where < TEntity > ( predicate ) .ToList < TEntity > ( ) ; //qry = db.CreateObjectSet < TEntity > ( ) .Where ( predicate ) .ToList < TEntity > ( ) ; // Run the query for custom properties against the resultset obtained from the database qry = qry.Where < TEntity > ( customPropertiesPredicate.Compile ( ) ) .ToList < TEntity > ( ) ; // Verify that there are results if ( qry ! = null & & qry.Count ! = 0 ) { result = qry ; } // Return the results return result ; } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using LinqKit ; using Newtonsoft.Json.Linq ; namespace DAL { internal class JsonLinqParser_Paser : JsonLinqParser { internal override System.Linq.Expressions.Expression < Func < TEntity , bool > > CreateCriteriaExpression < TEntity > ( string myCriteria ) { var predicate = PredicateBuilder.True < BestAvailableFIP > ( ) ; JObject o = JObject.Parse ( myCriteria ) ; // bmp decimal _bmp ; if ( o [ `` bmp '' ] ! = null & & decimal.TryParse ( ( string ) o [ `` bmp '' ] , out _bmp ) ) { predicate = predicate.And < BestAvailableFIP > ( x = > x.bmp == _bmp ) ; } // COUNTY if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` COUNTY '' ] ) ) { string _myStringValue = ( string ) o [ `` COUNTY '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.COUNTY.Contains ( _myStringValue ) ) ; } // emp decimal _emp ; if ( o [ `` emp '' ] ! = null & & decimal.TryParse ( ( string ) o [ `` emp '' ] , out _emp ) ) { predicate = predicate.And < BestAvailableFIP > ( x = > x.emp == _emp ) ; } // FIPSCO_STR if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` FIPSCO_STR '' ] ) ) { string _myStringValue = ( string ) o [ `` FIPSCO_STR '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.FIPSCO_STR.Contains ( _myStringValue ) ) ; } // FIPSCODE double _FIPSCODE ; if ( o [ `` FIPSCODE '' ] ! = null & & double.TryParse ( ( string ) o [ `` FIPSCODE '' ] , out _FIPSCODE ) ) { predicate = predicate.And < BestAvailableFIP > ( x = > x.FIPSCODE == _FIPSCODE ) ; } // FROMDESC if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` FROMDESC '' ] ) ) { string _myStringValue = ( string ) o [ `` FROMDESC '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.FROMDESC.Contains ( _myStringValue ) ) ; } // LANEMI decimal _LANEMI ; if ( o [ `` LANEMI '' ] ! = null & & decimal.TryParse ( ( string ) o [ `` LANEMI '' ] , out _LANEMI ) ) { predicate = predicate.And < BestAvailableFIP > ( x = > x.LANEMI == _LANEMI ) ; } // MPO_ABBV if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` MPO_ABBV '' ] ) ) { string _myStringValue = ( string ) o [ `` MPO_ABBV '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.MPO_ABBV.Contains ( _myStringValue ) ) ; } // owner if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` owner '' ] ) ) { string _myStringValue = ( string ) o [ `` owner '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.owner.Contains ( _myStringValue ) ) ; } // PASER decimal _PASER ; if ( o [ `` PASER '' ] ! = null & & decimal.TryParse ( ( string ) o [ `` PASER '' ] , out _PASER ) ) { predicate = predicate.And < BestAvailableFIP > ( x = > x.PASER == _PASER ) ; } // PASER_GROUP if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` PASER_GROUP '' ] ) ) { string _myStringValue = ( string ) o [ `` PASER_GROUP '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.PASER_GROUP.Contains ( _myStringValue ) ) ; } // pr decimal _pr ; if ( o [ `` pr '' ] ! = null & & decimal.TryParse ( ( string ) o [ `` pr '' ] , out _pr ) ) { predicate = predicate.And < BestAvailableFIP > ( x = > x.pr == _pr ) ; } // RDNAME if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` RDNAME '' ] ) ) { string _myStringValue = ( string ) o [ `` RDNAME '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.RDNAME.Contains ( _myStringValue ) ) ; } // SPDR_ABBV if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` SPDR_ABBV '' ] ) ) { string _myStringValue = ( string ) o [ `` SPDR_ABBV '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.SPDR_ABBV.Contains ( _myStringValue ) ) ; } // TODESC if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` TODESC '' ] ) ) { string _myStringValue = ( string ) o [ `` TODESC '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.TODESC.Contains ( _myStringValue ) ) ; } // TYPE if ( ! string.IsNullOrWhiteSpace ( ( string ) o [ `` TYPE '' ] ) ) { string _myStringValue = ( string ) o [ `` TYPE '' ] ; predicate = predicate.And < BestAvailableFIP > ( x = > x.TYPE.Contains ( _myStringValue ) ) ; } return predicate ; } internal override System.Linq.Expressions.Expression < Func < TEntity , bool > > CreateCriteriaExpressionForCustomProperties < TEntity > ( string myCriteria ) { var predicate = PredicateBuilder.True < TEntity > ( ) ; return predicate ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Linq.Expressions ; namespace DAL { abstract class JsonLinqParser { abstract internal Expression < Func < TEntity , bool > > CreateCriteriaExpression < TEntity > ( string myCriteria ) where TEntity : System.Data.Objects.DataClasses.EntityObject ; abstract internal Expression < Func < TEntity , bool > > CreateCriteriaExpressionForCustomProperties < TEntity > ( string myCriteria ) where TEntity : System.Data.Objects.DataClasses.EntityObject ; } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace DAL { internal static class JsonLinqParserFactory { internal static JsonLinqParser GetParser ( Type type ) { switch ( type.Name ) { case `` BestAvailableFIP '' : return new JsonLinqParser_Paser ( ) ; default : //if we reach this point then we failed to find a matching type . Throw //an exception . throw new Exception ( `` Failed to find a matching JsonLinqParser in JsonLinqParserFactory.GetParser ( ) - Unknown Type : `` + type.Name ) ; } } } }",Covariance/Contravariance with a linq expression "C_sharp : I 'm trying to learn the basics of creating a custom panel in a WinRT XAML app . I have defined an attached dependency property and it 's working as expected except i ca n't figure out how to get the property 's callback for a child element to trigger the arrange or measure of the container.What 's the proper way to for a child to let it 's container know that arrange and measure should be called again ? In my WPF 4 unleashed book they use the FrameworkPropertyMetadataOptions.AffectsParentArrange but that does n't seem to be available in WinRT . public class SimpleCanvas : Panel { # region Variables # region Left Property public static double GetLeft ( UIElement element ) { if ( element == null ) { throw new ArgumentNullException ( `` element '' ) ; } object value = element.GetValue ( LeftProperty ) ; Type valueType = value.GetType ( ) ; return Convert.ToDouble ( value ) ; } public static void SetLeft ( UIElement element , double value ) { if ( element == null ) { throw new ArgumentNullException ( `` element '' ) ; } element.SetValue ( LeftProperty , value ) ; } public static readonly DependencyProperty LeftProperty = DependencyProperty.RegisterAttached ( `` Left '' , typeof ( double ) , typeof ( SimpleCanvas ) , new PropertyMetadata ( 0 , OnLeftPropertyChanged ) ) ; public static void OnLeftPropertyChanged ( DependencyObject source , DependencyPropertyChangedEventArgs e ) { UIElement element = ( UIElement ) source ; // This does n't cause ArrangeOverride below to be called element.InvalidateArrange ( ) ; } # endregion # region Top Property public static double GetTop ( UIElement element ) { if ( element == null ) { throw new ArgumentNullException ( `` element '' ) ; } object value = element.GetValue ( TopProperty ) ; return ( value == null ) ? 0 : ( double ) value ; } public static void SetTop ( UIElement element , double value ) { if ( element == null ) { throw new ArgumentNullException ( `` element '' ) ; } element.SetValue ( TopProperty , value ) ; } public static readonly DependencyProperty TopProperty = DependencyProperty.RegisterAttached ( `` Top '' , typeof ( double ) , typeof ( SimpleCanvas ) , new PropertyMetadata ( 0 , OnTopPropertyChanged ) ) ; public static void OnTopPropertyChanged ( DependencyObject source , DependencyPropertyChangedEventArgs e ) { UIElement element = ( UIElement ) source ; // This does n't cause ArrangeOverride below to be called element.InvalidateArrange ( ) ; } # endregion # endregion public SimpleCanvas ( ) { } # region Methods protected override Size MeasureOverride ( Size availableSize ) { foreach ( UIElement child in this.Children ) { child.Measure ( new Size ( double.PositiveInfinity , double.PositiveInfinity ) ) ; } return new Size ( 0 , 0 ) ; } protected override Size ArrangeOverride ( Size finalSize ) { foreach ( UIElement child in this.Children ) { double x = 0 ; double y = 0 ; double left = GetLeft ( child ) ; double top = GetTop ( child ) ; if ( ! double.IsNaN ( left ) ) { x = left ; } if ( ! double.IsNaN ( top ) ) { y = top ; } child.Arrange ( new Rect ( new Point ( x , y ) , child.DesiredSize ) ) ; } return finalSize ; } # endregion }",How does a container know when a child has called InvalidateArrange ? C_sharp : I have a dictionary where the Key is an Id and the value is a stringI now have a List of person objects where each person has a CarIds property that is an I want to basically filter the list of objects to only include items where one of the properties is included in the dict.For example . something like this : Does something like this exist where I can do something similar to ContainsKey ( ) but check for any in a list of ints ? IEnumerable < int > var dictionary = GetDict ( ) ; var people = GetPeople ( ) ; people = people.Where ( r = > dictionary.ContainsAny ( r.CarIds ) ) .ToList ( ) ;,Does C # have a ContainsAny ( ) method for a dictionary ? C_sharp : Controller : View : From the code above @ item.Title can have special characters like '/ ' sample link is http : //localhost:39727/Home/Tool/C+Compiler+For+The+Pic10 % 2f12 % 2f16+Mcus when I try to navigate to that link Tool Controller was not called . I used @ Url.Encode but still Controller was not called . public ActionResult Tool ( string id ) { // Code goes here . . } < a href= '' /Home/ @ item.Type/ @ Url.Encode ( item.Title ) '' id= '' toolTitleLink '' > @ item.Title < /a >,How to Encode '/ ' in ASP.NET MVC Razor "C_sharp : I am reading Eric Liperts ' blog about Mutating Readonly Structs and I see many references here in SO to this blog as an argument why value types must be immutable . But still one thing is not clear , says that when you access value type you always get the copy of it and here is the example : And the question is this why when I change the to everything starts to work es expected.Please can you explain more clear why Value Types must be immutable . I know that it is good for thread safety , but in this case same can be applied to reference types . struct Mutable { private int x ; public int Mutate ( ) { this.x = this.x + 1 ; return this.x ; } } class Test { public readonly Mutable m = new Mutable ( ) ; static void Main ( string [ ] args ) { Test t = new Test ( ) ; System.Console.WriteLine ( t.m.Mutate ( ) ) ; System.Console.WriteLine ( t.m.Mutate ( ) ) ; System.Console.WriteLine ( t.m.Mutate ( ) ) ; } } public readonly Mutable m = new Mutable ( ) ; public Mutable m = new Mutable ( ) ;",immutable value types "C_sharp : I have been looking at .NET 's implementation of the dictionary , as I wanted to understand what makes the dictionary ContainsKey and lookup fast : http : //referencesource.microsoft.com/ # mscorlib/system/collections/generic/dictionary.cs,15debc34d286fdb3The ContainsKey function basically leads to the FindEntry listed below : buckets is an array of integers and entries is an array of Entry objects , which are structs containing HashCode , TKey and TValue.So I understand that this lookup is fast since it 's a simple array lookup . However I 'm trying to understand these 2 lines : 1 ) If I unerstand correctly 0x7FFFFFFF is there to ensure that we do n't get a negative value . So what does the first line return ? Is it a simple integer or a prime ? 2 ) In the second line why do we initialize i to buckets [ hashCode % buckets.Length ] ? private int FindEntry ( TKey key ) { if ( key == null ) { ThrowHelper.ThrowArgumentNullException ( ExceptionArgument.key ) ; } if ( buckets ! = null ) { int hashCode = comparer.GetHashCode ( key ) & 0x7FFFFFFF ; for ( int i = buckets [ hashCode % buckets.Length ] ; i > = 0 ; i = entries [ i ] .next ) { if ( entries [ i ] .hashCode == hashCode & & comparer.Equals ( entries [ i ] .key , key ) ) return i ; } } return -1 ; } int hashCode = comparer.GetHashCode ( key ) & 0x7FFFFFFF ; for ( int i = buckets [ hashCode % buckets.Length ] ; i > = 0 ; i = entries [ i ] .next )",FindEntry function in Dictionary.cs "C_sharp : In C # or else VB.Net , knowing the ubication of a visual theme .theme file , I would like to apply that visual theme in Windows , without depending on other applications such as RunDll32.exe , just P/Invoking , but avoiding weird/strange things such as opening the personalization window and then using FindWindow function to close it , the procedure should be automated from platform invoking not interacting with other windows.This question about how to apply a theme was asked before in S.O by many people ( Included by me , with a solution via registry modification plus service stoping/resuming that only works under Windows 7 ) , I think its time for an expert to illustrate us with a WinAPI approach that does not involve RunDll32.exe neither opening the personalization window.I wonder this could be done by setting some values on the registry key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager and then posting/sending a message via SendMessage or PostMessage or other function , or maybe notifying about an environment change via SendMessageTimeOut function or SHChangeNotify or SystemParametersInfo or another function , because in the uxtheme.dll library seems there is nothing usefull for this task , the question is what function and with what parameters to apply a visual theme change , there are some commercial applications that can do this , which are the steps to do it then ? , I tried all those functions without success.This is the solution I did for Windows 7 in the past , I remember that is not perfect because for some themes the colors were not applied properlly and only has beeen solved with an user session re-logon to affect changes properlly after modifications : In windows 8 I think because DWM composition changes just that code did n't worked anymore . Private Sub SetAeroTheme ( ByVal themeFile As String , Optional ByVal colorName As String = `` NormalColor '' , Optional ByVal sizeName As String = `` NormalSize '' ) Dim regKeyPath As String = `` Software\Microsoft\Windows\CurrentVersion\ThemeManager '' Using themeService As New ServiceController ( `` Themes '' ) If themeService.Status = ServiceControllerStatus.Running Then themeService.Stop ( ) themeService.WaitForStatus ( ServiceControllerStatus.Stopped ) End If Using regKey As RegistryKey = Registry.CurrentUser.OpenSubKey ( regKeyPath , writable : =True ) regKey.SetValue ( `` LoadedBefore '' , `` 0 '' , RegistryValueKind.String ) regKey.SetValue ( `` DllName '' , themeFile , RegistryValueKind.String ) regKey.SetValue ( `` ColorName '' , colorName , RegistryValueKind.String ) regKey.SetValue ( `` SizeName '' , sizeName , RegistryValueKind.String ) End Using If themeService.Status = ServiceControllerStatus.Stopped Then themeService.Start ( ) themeService.WaitForStatus ( ServiceControllerStatus.Running ) End If End UsingEnd Sub",How do I change a visual theme programatically in Windows 8/8.1 by P/Invoking ? "C_sharp : I 'm writing an WCF service based on the WSDL from an old soap service . I used svcutil to generate the the service contract and made a few changes to match the site I 'm hosting it on , but when I call the service from a test client , the request object is coming in as null.The response the service is returning is also getting serialized incorrectly which I 'm sure is related . But I ca n't figure why its not serializing and deserializing correctly.Here 's the service contract : And the Implementation : The Configuration : The request received by the service ( from OperationContext.Current.RequestContext.RequestMessage ) : The Response sent by the service ( which is serialized incorrectly ) : [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.ServiceModel '' , `` 4.0.0.0 '' ) ] [ System.ServiceModel.ServiceContractAttribute ( Namespace = ApuConstants.Namespace ) ] public interface IApuService { [ System.ServiceModel.OperationContractAttribute ( Action = `` * '' , ReplyAction = `` * '' ) ] [ System.ServiceModel.XmlSerializerFormatAttribute ( Style = System.ServiceModel.OperationFormatStyle.Rpc , Use = System.ServiceModel.OperationFormatUse.Encoded ) ] [ System.ServiceModel.ServiceKnownTypeAttribute ( typeof ( Part ) ) ] [ return : System.ServiceModel.MessageParameterAttribute ( Name = `` return '' ) ] Brock.Web.Apu.Response check ( Brock.Web.Apu.Request request ) ; } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` svcutil '' , `` 4.0.30319.33440 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.SoapTypeAttribute ( Namespace = ApuConstants.Namespace ) ] public partial class Request { private RequestHeader headerField ; private Lookup lookupField ; /// < remarks/ > public RequestHeader header { get { return this.headerField ; } set { this.headerField = value ; } } /// < remarks/ > public Lookup lookup { get { return this.lookupField ; } set { this.lookupField = value ; } } } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` svcutil '' , `` 4.0.30319.33440 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.SoapTypeAttribute ( Namespace = ApuConstants.Namespace ) ] public partial class RequestHeader { private string accountField ; private string idField ; /// < remarks/ > public string account { get { return this.accountField ; } set { this.accountField = value ; } } /// < remarks/ > public string id { get { return this.idField ; } set { this.idField = value ; } } } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` svcutil '' , `` 4.0.30319.33440 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.SoapTypeAttribute ( Namespace = ApuConstants.Namespace ) ] public partial class Part { private string oemField ; private string hicField ; private string skuField ; private string descField ; private int daysField ; private string availField ; private string branchField ; private float listField ; private float netField ; private string typeField ; private string certField ; private string statusField ; /// < remarks/ > public string oem { get { return this.oemField ; } set { this.oemField = value ; } } /// < remarks/ > public string hic { get { return this.hicField ; } set { this.hicField = value ; } } /// < remarks/ > public string sku { get { return this.skuField ; } set { this.skuField = value ; } } /// < remarks/ > public string desc { get { return this.descField ; } set { this.descField = value ; } } /// < remarks/ > public int days { get { return this.daysField ; } set { this.daysField = value ; } } /// < remarks/ > public string avail { get { return this.availField ; } set { this.availField = value ; } } /// < remarks/ > public string branch { get { return this.branchField ; } set { this.branchField = value ; } } /// < remarks/ > public float list { get { return this.listField ; } set { this.listField = value ; } } /// < remarks/ > public float net { get { return this.netField ; } set { this.netField = value ; } } /// < remarks/ > public string type { get { return this.typeField ; } set { this.typeField = value ; } } /// < remarks/ > public string cert { get { return this.certField ; } set { this.certField = value ; } } /// < remarks/ > public string status { get { return this.statusField ; } set { this.statusField = value ; } } } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` svcutil '' , `` 4.0.30319.33440 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.SoapTypeAttribute ( Namespace = ApuConstants.Namespace ) ] public partial class ResponseHeader { private string statusField ; private string reasonField ; private string accountField ; private string idField ; /// < remarks/ > public string status { get { return this.statusField ; } set { this.statusField = value ; } } /// < remarks/ > public string reason { get { return this.reasonField ; } set { this.reasonField = value ; } } /// < remarks/ > public string account { get { return this.accountField ; } set { this.accountField = value ; } } /// < remarks/ > public string id { get { return this.idField ; } set { this.idField = value ; } } } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` svcutil '' , `` 4.0.30319.33440 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.SoapTypeAttribute ( Namespace = ApuConstants.Namespace ) ] public partial class Response { private ResponseHeader headerField ; private Part [ ] itemsField ; /// < remarks/ > public ResponseHeader header { get { return this.headerField ; } set { this.headerField = value ; } } /// < remarks/ > public Part [ ] items { get { return this.itemsField ; } set { this.itemsField = value ; } } } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` svcutil '' , `` 4.0.30319.33440 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.SoapTypeAttribute ( Namespace = ApuConstants.Namespace ) ] public partial class Lookup { private string oemField ; private string hicField ; private int qtyField ; private string zipField ; /// < remarks/ > public string oem { get { return this.oemField ; } set { this.oemField = value ; } } /// < remarks/ > public string hic { get { return this.hicField ; } set { this.hicField = value ; } } /// < remarks/ > public int qty { get { return this.qtyField ; } set { this.qtyField = value ; } } /// < remarks/ > public string zip { get { return this.zipField ; } set { this.zipField = value ; } } } [ ServiceBehavior ( Namespace = ApuConstants.Namespace ) ] public class ApuService : IApuService { private readonly IApuServiceHandler _handler ; private readonly ISettingService _settingService ; public ApuService ( ) { _handler = EngineContext.Current.Resolve < IApuServiceHandler > ( ) ; _settingService = EngineContext.Current.Resolve < ISettingService > ( ) ; } public Response check ( Request request ) { if ( Authorized ( request ) ) return _handler.ProcessRequest ( request ) ; return _handler.ErrorResponse ( `` Invalid credentials '' ) ; } protected bool Authorized ( Request request ) { if ( request == null || request.header == null ) return false ; var settings = _settingService.LoadSetting < ApuSettings > ( 0 ) ; if ( ! string.Equals ( request.header.account , settings.Username , StringComparison.InvariantCultureIgnoreCase ) ) return false ; if ( ! string.Equals ( request.header.id , settings.Password ) ) return false ; return true ; } } < configuration > < system.web > < compilation targetFramework= '' 4.5.1 '' / > < /system.web > < system.serviceModel > < behaviors > < serviceBehaviors > < behavior name= '' ApuBehavior '' > < serviceMetadata httpGetEnabled= '' true '' httpsGetEnabled= '' true '' / > < serviceDebug includeExceptionDetailInFaults= '' true '' / > < /behavior > < /serviceBehaviors > < /behaviors > < bindings > < /bindings > < services > < service name= '' Apu.WebService.ApuService '' behaviorConfiguration= '' ApuBehavior '' > < endpoint address= '' '' binding= '' basicHttpBinding '' contract= '' Web.Apu.IApuService '' bindingNamespace= '' http : //www.testurl.com/apu '' / > < endpoint address= '' mex '' binding= '' mexHttpBinding '' contract= '' IMetadataExchange '' / > < /service > < /services > < /system.serviceModel > < /configuration > < Envelope xmlns= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < s : Header xmlns : s= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < To s : mustUnderstand= '' 1 '' xmlns= '' http : //schemas.microsoft.com/ws/2005/05/addressing/none '' > http : //localhost:15555/Plugins/Brock.Apu/Remote/ApuService.svc < /To > < /s : Header > < Body > < check xmlns= '' http : //www.testurl.com/apu '' > < request > < header > < account > apu < /account > < id > apu001 ! < /id > < /header > < lookup > < hic > 323-01327 < /hic > < oem > 5014351AB < /oem > < qty > 2 < /qty > < zip > 85304 < /zip > < /lookup > < /request > < /check > < /Body > < /Envelope > < s : Envelope xmlns : s= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < s : Body s : encodingStyle= '' http : //schemas.xmlsoap.org/soap/encoding/ '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < q1 : checkResponse xmlns : q1= '' http : //www.testurl.com/apu '' > < return href= '' # id1 '' / > < /q1 : checkResponse > < q2 : Response id= '' id1 '' xsi : type= '' q2 : Response '' xmlns : q2= '' http : //www.testurl.com/apu '' > < header href= '' # id2 '' / > < /q2 : Response > < q3 : ResponseHeader id= '' id2 '' xsi : type= '' q3 : ResponseHeader '' xmlns : q3= '' http : //www.testurl.com/apu '' > < status xsi : type= '' xsd : string '' > no < /status > < reason xsi : type= '' xsd : string '' > Invalid credentials < /reason > < account xsi : type= '' xsd : string '' / > < id xsi : type= '' xsd : string '' / > < /q3 : ResponseHeader > < /s : Body > < /s : Envelope >",WCF Service Request is Null when using XmlSerializerFormat "C_sharp : In my NinjectConfigurator I haveI have also triedBut I get this error : Error activating IClock using binding from IClock to SystemClock No constructor was available to create an instance of the implementation type . Activation path : 3 ) Injection of dependency IClock into parameter clock of constructor of type SystemManager 2 ) Injection of dependency ISystemManager into parameter systemManager of constructor of type AccountController 1 ) Request for AccountController Suggestions : 1 ) Ensure that the implementation type has a public constructor . 2 ) If you have implemented the Singleton pattern , use a binding with InSingletonScope ( ) instead.This is my class with the injection , same as all other working classes with IoC in my project : I could n't find anything to help me on this . Any help is much appreciated . container.Bind < IClock > ( ) .To < SystemClock > ( ) ; container.Bind < IClock > ( ) .To < SystemClock > ( ) .InSingletonScope ( ) ; private readonly IDateTime _dateTime ; private readonly IClock _clock ; public SystemManager ( IDateTime dateTime , IClock clock ) { this._dateTime = dateTime ; this._clock = clock ; }",How do I configure Ninject to inject the NodaTime IClock "C_sharp : I am trying to insert an image in my access database from C # winform . I am using the following code : When I run the code it show me an error : Syntax error in INSERT INTO statement.What is wrong here in my code ? I can successfully insert text to the fields of database by using the same query . private void button1_Click ( object sender , EventArgs e ) { OleDbConnection con = new OleDbConnection ( @ '' Provider=Microsoft.Jet.OLEDB.4.0 ; Data Source=C : \db1.mdb '' ) ; OleDbCommand cmd = con.CreateCommand ( ) ; cmd.CommandText = `` INSERT INTO Table1 ( Product , Manufacturer , Description , Price , Image ) VALUES ( 'Column1 ' , 'Column2 ' , 'Column3 ' , 'Column4 ' , @ img ) '' ; byte [ ] yourPhoto = imageToByteArray ( pictureBox1.Image ) ; cmd.Parameters.AddWithValue ( `` @ img '' , yourPhoto ) ; con.Open ( ) ; cmd.ExecuteNonQuery ( ) ; con.Close ( ) ; } public byte [ ] imageToByteArray ( System.Drawing.Image iImage ) { MemoryStream mMemoryStream = new MemoryStream ( ) ; iImage.Save ( mMemoryStream , System.Drawing.Imaging.ImageFormat.Png ) ; return mMemoryStream.ToArray ( ) ; }",What is wrong here ? In my code ( Inserting Image into Database - C # ) "C_sharp : In a Visual Studio Extension ( VSIX ) solution , I 'm using Roslyn to load a specific project from my current solution : The projct myProject is definitely loaded , but on inspection I see that : And yet , in Visual Studio I can see loads of documents.If I close the solution and open the same solution but from another TFS branch , then the same code returns : Any ideas ? Project myProject = this.CurrentComponentModel.GetService < VisualStudioWorkspace > ( ) .CurrentSolution.Projects .FirstOrDefault ( p = > p.Name == `` MyProject '' ) myProject.HasDocuments == falsemyProject.Documents is Empty myProject.HasDocuments == true myProject.Documents is not Empty",Roslyn load project documents failing "C_sharp : We 're using the following pattern to handle caching of universal objects for our asp.net application.The problem is that when under load ( ~100,000 users ) we see a huge jump in TTFB as the CacheItemUpdateCallback blocks all the other threads from executing until it has finished refreshing the cache from the database.So what I figured we needed is solution that when the first thread after an expiry of the cache attempts to access it , an asynchronous thread is fired off to update the cache but still allows all other executing threads to read from the old cache until it has sucessfully updated.Is there anything built into the .NET framework that can natively handle what I 'm asking , or will I have to write it from scratch ? Your thoughts please ... A couple of things ... The use of the HttpContext.Current.Cache is incidental and not necessarily essential as we 've got no problem using private members on a singleton to hold the cached data.Please do n't comment on the cache times , SPROC effeciency , why we 're caching in the first place etc as it 's not relevent . Thanks ! private object SystemConfigurationCacheLock = new object ( ) ; public SystemConfiguration SystemConfiguration { get { if ( HttpContext.Current.Cache [ `` SystemConfiguration '' ] == null ) lock ( SystemConfigurationCacheLock ) { if ( HttpContext.Current.Cache [ `` SystemConfiguration '' ] == null ) HttpContext.Current.Cache.Insert ( `` SystemConfiguration '' , GetSystemConfiguration ( ) , null , DateTime.Now.AddMinutes ( 1 ) , Cache.NoSlidingExpiration , new CacheItemUpdateCallback ( SystemConfigurationCacheItemUpdateCallback ) ) ; } return HttpContext.Current.Cache [ `` SystemConfiguration '' ] as SystemConfiguration ; } } private void SystemConfigurationCacheItemUpdateCallback ( string key , CacheItemUpdateReason reason , out object expensiveObject , out CacheDependency dependency , out DateTime absoluteExpiration , out TimeSpan slidingExpiration ) { dependency = null ; absoluteExpiration = DateTime.Now.AddMinutes ( 1 ) ; slidingExpiration = Cache.NoSlidingExpiration ; expensiveObject = GetSystemConfiguration ( ) ; } private SystemConfiguration GetSystemConfiguration ( ) { //Load system configuration }",How do I implement asynchrounous caching ? "C_sharp : I have 2 list which names are listA and listB.I want to remove strings in listB which are in listA , but I want to do this in this way : if listA contains : `` bar '' , `` bar '' , `` bar '' , `` foo '' and listB contains : `` bar '' it removes only 1 bar and the result will be : '' bar '' , `` bar '' , `` foo '' the code I wrote removes all `` bar '' : List < string > result = listA.Except ( listB ) .ToList ( ) ;",How to remove strings in list from another list ? "C_sharp : I 'm building a stress-testing client that hammers servers and analyzes responses using as many threads as the client can muster . I 'm constantly finding myself throttled by garbage collection ( and/or lack thereof ) , and in most cases , it comes down to strings that I 'm instantiating only to pass them off to a Regex or an Xml parsing routine . If you decompile the Regex class , you 'll see that internally , it uses StringBuilders to do nearly everything , but you ca n't pass it a string builder ; it helpfully dives down into private methods before starting to use them , so extension methods are n't going to solve it either . You 're in a similar situation if you want to get an object graph out of the parser in System.Xml.Linq . This is not a case of pedantic over-optimization-in-advance . I 've looked at the Regex replacements inside a StringBuilder question and others . I 've also profiled my app to see where the ceilings are coming from , and using Regex.Replace ( ) now is indeed introducing significant overhead in a method chain where I 'm trying to hit a server with millions of requests per hour and examine XML responses for errors and embedded diagnostic codes . I 've already gotten rid of just about every other inefficiency that 's throttling the throughput , and I 've even cut a lot of the Regex overhead out by extending StringBuilder to do wildcard find/replace when I do n't need capture groups or backreferences , but it seems to me that someone would have wrapped up a custom StringBuilder ( or better yet , Stream ) based Regex and Xml parsing utility by now . Ok , so rant over , but am I going to have to do this myself ? Update : I found a workaround which lowered peak memory consumption from multiple gigabytes to a few hundred megs , so I 'm posting it below . I 'm not adding it as an answer because a ) I generally hate to do that , and b ) I still want to find out if someone takes the time to customize StringBuilder to do Regexes ( or vice-versa ) before I do.In my case , I could not use XmlReader because the stream I am ingesting contains some invalid binary content in certain elements . In order to parse the XML , I have to empty out those elements . I was previously using a single static compiled Regex instance to do the replace , and this consumed memory like mad ( I 'm trying to process ~300 10KB docs/sec ) . The change that drastically reduced consumption was : I added the code from this StringBuilder Extensions article onCodeProject for the handy IndexOf method . I added a ( very ) crude WildcardReplace method that allows one wildcard character ( * or ? ) per invocation I replaced the Regex usage with a WildcardReplace ( ) call to empty the contents of the offending elementsThis is very unpretty and tested only as far as my own purposes required ; I would have made it more elegant and powerful , but YAGNI and all that , and I 'm in a hurry . Here 's the code : /// < summary > /// Performs basic wildcard find and replace on a string builder , observing one of two /// wildcard characters : * matches any number of characters , or ? matches a single character./// Operates on only one wildcard per invocation ; 2 or more wildcards in < paramref name= '' find '' / > /// will cause an exception./// All characters in < paramref name= '' replaceWith '' / > are treated as literal parts of /// the replacement text./// < /summary > /// < param name= '' find '' > < /param > /// < param name= '' replaceWith '' > < /param > /// < returns > < /returns > public static StringBuilder WildcardReplace ( this StringBuilder sb , string find , string replaceWith ) { if ( find.Split ( new char [ ] { '* ' } ) .Length > 2 || find.Split ( new char [ ] { ' ? ' } ) .Length > 2 || ( find.Contains ( `` * '' ) & & find.Contains ( `` ? '' ) ) ) { throw new ArgumentException ( `` Only one wildcard is supported , but more than one was supplied . `` , `` find '' ) ; } // are we matching one character , or any number ? bool matchOneCharacter = find.Contains ( `` ? `` ) ; string [ ] parts = matchOneCharacter ? find.Split ( new char [ ] { ' ? ' } , StringSplitOptions.RemoveEmptyEntries ) : find.Split ( new char [ ] { '* ' } , StringSplitOptions.RemoveEmptyEntries ) ; int startItemIdx ; int endItemIdx ; int newStartIdx = 0 ; int length ; while ( ( startItemIdx = sb.IndexOf ( parts [ 0 ] , newStartIdx ) ) > 0 & & ( endItemIdx = sb.IndexOf ( parts [ 1 ] , startItemIdx + parts [ 0 ] .Length ) ) > 0 ) { length = ( endItemIdx + parts [ 1 ] .Length ) - startItemIdx ; newStartIdx = startItemIdx + replaceWith.Length ; // With `` ? '' wildcard , find parameter length should equal the length of its match : if ( matchOneCharacter & & length > find.Length ) break ; sb.Remove ( startItemIdx , length ) ; sb.Insert ( startItemIdx , replaceWith ) ; } return sb ; }",Has anyone implemented a Regex and/or Xml parser around StringBuilders or Streams ? "C_sharp : I have a list of dates . I would like to query the list and return a list of pairs where the first item is a date and the second is the date which occurs just before the first date ( in the list ) . I know this could easily be achieved by sorting the list and getting the respective dates by index , I am curious how this could be achieved in LINQ . I 've done this in SQL with the following query : SELECT Date , ( SELECT MAX ( Date ) FROM Table AS t2 WHERE t2.Date < t1.Date ) AS PrevDateFROM Table AS t1",Nested LINQ query to select 'previous ' value in a list "C_sharp : I am playing around with the garbage collector in C # ( or rather the CLR ? ) trying to better understand memory management in C # .I made a small sample program that reads three larger files into a byte [ ] buffer . I wanted to see , if I actually need to to anything in order to handle memory efficientit has any impact when setting the byte [ ] to null after the end of the current iteration and finally if it would help when forcing a garbage collection via GC.Collect ( ) Disclaimer : I measured memory consumption with windows task manager and rounded it . I tried several times , but overall it remained about the same.Here is my simple sample program : For each test , I only changed the contents of the foreach loop . Then I ran the program , at each Console.ReadLine ( ) I stopped and checked the memory usage of the process in windows task manager . I took notes of the used memory and then continued the program with return ( I know about breakpoints ; ) ) . Just after the end of the loop , I wrote GC.CollectionCount ( 1 ) to the console in order to see how often the GC jumped in if at all.ResultsTest 1 : Result ( memory used ) : Test 2 : Result ( memory used ) : Test 3 : Result ( memory used ) : What I dont understand : In Test 1 , the memory increases with each iteration . Therefore I guess that the memory is NOT freed at the end of the loop . But the GC still says it collected 2 times ( GC.CollectionCount ) . How so ? In Test 2 , it obviously helps that buffer is set to null . The memory is lower then in Test 2 . But why does GC.CollectionCount output 2 and not 3 ? And why is the memory usage not as low as in Test 3 ? Test 3 uses the least memory . I would say it is so because 1. the reference to the memory is removed ( buffer is set to null ) and therefore when the garbage collector is called via GC.Collect ( ) it can free the memory . Seems pretty clear.If anyone with more experience could shed some light on some of the points above , it would really help me . Pretty interesting topic imho . static void Main ( string [ ] args ) { Loop ( ) ; } private static void Loop ( ) { var list = new List < string > { @ '' C : \Users\Public\Music\Sample Music\Amanda.wma '' , // Size : 4.75 MB @ '' C : \Users\Public\Music\Sample Music\Despertar.wma '' , // Size : 5.92 MB @ '' C : \Users\Public\Music\Sample Music\Distance.wma '' , // Size : 6.31 MB } ; Console.WriteLine ( `` before loop '' ) ; Console.ReadLine ( ) ; foreach ( string pathname in list ) { // ... code here ... Console.WriteLine ( `` in loop '' ) ; Console.ReadLine ( ) ; } Console.WriteLine ( GC.CollectionCount ( 1 ) ) ; Console.WriteLine ( `` end loop '' ) ; Console.ReadLine ( ) ; } foreach ( ... ) { byte [ ] buffer = File.ReadAllBytes ( pathname ) ; Console.WriteLine ... } before loop : 9.000 K 1. iteration : 13.000 K2 . iteration : 19.000 K3 . iteration : 25.000 Kafter loop : 25.000 KGC.CollectionCount ( 1 ) : 2 foreach ( ... ) { byte [ ] buffer = File.ReadAllBytes ( pathname ) ; buffer = null ; Console.WriteLine ... } before loop : 9.000 K 1. iteration : 13.000 K2 . iteration : 14.000 K3 . iteration : 15.000 Kafter loop : 15.000 KGC.CollectionCount ( 1 ) : 2 foreach ( ... ) { byte [ ] buffer = File.ReadAllBytes ( pathname ) ; buffer = null ; GC.Collect ( ) ; Console.WriteLine ... } before loop : 9.000 K 1. iteration : 8.500 K2 . iteration : 8.600 K3 . iteration : 8.600 Kafter loop : 8.600 KGC.CollectionCount ( 1 ) : 3",Could someone explain the behaviour of the garbage collector ? "C_sharp : I have a web service which uses Windows Authentication . Web Service is hosted on IIS . Is it possible to narrow access to that web service only to few specific users ? My current web config : By the way , I tried a solution similar to this , which I found over the Internet : It does not work though . : ( It let all domain users pass through . < services > < service name= '' LANOS.SplunkSearchService.SplunkSearch '' > < endpoint binding= '' basicHttpBinding '' bindingConfiguration= '' basicHttp '' contract= '' LANOS.SplunkSearchService.ISplunkSearch '' / > < endpoint address= '' mex '' binding= '' mexHttpBinding '' contract= '' IMetadataExchange '' / > < /service > < /services > < bindings > < basicHttpBinding > < binding name= '' basicHttp '' allowCookies= '' true '' maxBufferSize= '' 20000000 '' maxBufferPoolSize= '' 20000000 '' maxReceivedMessageSize= '' 20000000 '' > < readerQuotas maxDepth= '' 32 '' maxStringContentLength= '' 200000000 '' maxArrayLength= '' 200000000 '' / > < security mode= '' TransportCredentialOnly '' > < transport clientCredentialType= '' Windows '' / > < /security > < /binding > < /basicHttpBinding > < /bindings > < authentication mode= '' Windows '' / > < authorization > < allow roles= '' .\Developers '' / > < allow users= '' DOMAIN\ServiceAccount '' / > < deny users= '' * '' / > < /authorization >",How to give access to WCF web service hosted on IIS only for specific users ? "C_sharp : I 'm trying to create a NuGet package which has a dependency on System.Net.Http ( need the HttpClient ) . For framework version 4.5.1 , this assembly is a part of the BCL . Hoewever , in 4.0 it is not . I believe it having compiling correctly with the proper conditional statements in the csproj . The problem I 'm currently wrestling with is that when I reference this package in a 4.5.1 project , it pulls in the dependency on Microsoft.Net.Http . I really only want to depend on Microsoft.Net.Http for net40.Here 's my nuspec file : In VS , the NuGet package shows this : But again , I 'm those dependencies are also being pulled in when using a project with target framework 4.5.1 . Which I do n't want . Any help is appreciated . < ? xml version= '' 1.0 '' ? > < package > < metadata > < id > MyApp < /id > < version > $ version $ < /version > < title > MyApp < /title > < authors > Me < /authors > < owners > Me < /owners > < requireLicenseAcceptance > false < /requireLicenseAcceptance > < description > Description < /description > < releaseNotes > Initial release < /releaseNotes > < copyright > Copyright 2016 < /copyright > < dependencies > < group > < dependency id= '' Newtonsoft.Json '' version= '' 8.0.2 '' / > < /group > < group targetFramework= '' net40 '' > < dependency id= '' Microsoft.Bcl '' version= '' 1.1.10 '' / > < dependency id= '' Microsoft.Bcl.Build '' version= '' 1.0.14 '' / > < dependency id= '' Microsoft.Net.Http '' version= '' 2.2.29 '' / > < /group > < /dependencies > < /metadata > < files > < file src= '' bin\release\**\MyApp.dll '' target= '' lib '' / > < /files > < /package >",How can I specify different dependencies for different versions of the .NET framework in a custom NuGet package ? "C_sharp : I 'm tasked to create a `` Cinemagraph '' feature , the user must select a desired area using an InkCanvas to draw the selected pixels that should remain untouched for the rest of the animation/video ( or , to select the pixels that should be `` alive '' ) .Example : I 'm thinking about getting the Stroke collection from the InkCanvas and use that to clip the image and merge with the untouched one.How can I do that ? I can easily load the images from disk , but how can I clip an image based on a stroke ? More Details : After drawing and selecting the pixels that should remain static , I have a Stroke collection . I can get the Geometry of each individual Stroke , but I probably need to merge all geometries.Based on that merged Geometry , I need to invert ( the Geometry ) and use to clip my first frame , later with the clipped image ready , I need to merge with all other frames.My code so far : Is there any way to clip a BitmapSource without using an UIElement ? Maybe , MaybeI 'm thinking about OpacityMask and a brush ... but I ca n't use a UIElement , I need to apply the OpacityMask directly to the BitmapSource . //Gets the BitmapSource from a String path : var image = ListFrames [ 0 ] .ImageLocation.SourceFrom ( ) ; var rectangle = new RectangleGeometry ( new Rect ( new System.Windows.Point ( 0 , 0 ) , new System.Windows.Size ( image.Width , image.Height ) ) ) ; Geometry geometry = Geometry.Empty ; foreach ( Stroke stroke in CinemagraphInkCanvas.Strokes ) { geometry = Geometry.Combine ( geometry , stroke.GetGeometry ( ) , GeometryCombineMode.Union , null ) ; } //Inverts the geometry , to clip the other unselect pixels of the BitmapImage.geometry = Geometry.Combine ( geometry , rectangle , GeometryCombineMode.Exclude , null ) ; //This here is UIElement , I ca n't use this control , I need a way to clip the image without using the UI.var clippedImage = new System.Windows.Controls.Image ( ) ; clippedImage.Source = image ; clippedImage.Clip = geometry ; //I ca n't get the render of the clippedImage control because I 'm not displaying that control .",Clip BitmapImage using Strokes from a InkCanvas "C_sharp : I have a class what takes care of reading and holding the XML file.Right now a simple version of it looks like this : And there will be more later . so the problem is that if some element does not exist in xml i get System.NullReferenceException . So i need to check if the element is null or not . Heres one way to do this : But doing that for every element would be just too much . So i need some good ideas how to simplify this system so it would n't end up in 1000 lines of code.EDIT : Edited the last code snippet , the idea was not to set a default value , idea was to notify the user that this element whats null is missing from the xml . public class EstEIDPersoConfig { public bool LaunchDebugger { get ; set ; } public string Password { get ; set ; } public int Slot { get ; set ; } public string Reader { get ; set ; } public string TestInput { get ; set ; } public bool Logging { get ; set ; } public EstEIDPersoConfig ( ) { XElement xml = XElement.Load ( myxml.xml ) ; XElement Configuration = xml.Element ( `` Configuration '' ) ; LaunchDebugger = Convert.ToBoolean ( Configuration.Element ( `` LaunchDebugger '' ) .Value ) ; Password = Configuration.Element ( `` Password '' ) .Value ; Slot = Convert.ToInt32 ( Configuration.Element ( `` Slot '' ) .Value ) ; Reader = Configuration.Element ( `` Reader '' ) .Value ; TestInput = Configuration.Element ( `` TestInput '' ) .Value ; Logging = Convert.ToBoolean ( Configuration.Element ( `` Logging '' ) .Value ) ; } } var value = Configuration.Element ( `` LaunchDebugger '' ) .Value ; if ( value ! = null ) LaunchDebugger = Convert.ToBoolean ( value ) ; else throw new Exception ( `` LaunchDebugger element missing from xml ! `` ) ;",Check if XElement is null globally "C_sharp : I 'm building an extension method on IList to be able to output the specified properties of any object passed into it as a list , and output it as a CSV string . It looks like : Right now , I have to call this method like : Is there a better way to pass in my lambda expressions without having to explicitly declare the columns variable , something like : public static string OutputCSVString < T > ( this IList < T > list , List < Func < T , string > > properties ) { foreach ( var row in list ) { foreach ( var item in properties ) { // Do the output work , including calling item ( row ) . } // Output new line } } // Assuming I 've populated List < Product > ProductList up above ... var columns = new List < Func < Product , string > > ( ) ; columns.Add ( x = > x.Id ) ; columns.Add ( x = > x.Name ) ; string s = ProductList.OutputCSVString ( columns ) ; // This does n't compilestring s = Products.OutputCSVString ( new { p = > p.Id , p = > p.Name } ) ;",How to use lambda expressions for a function that takes a list of delegates "C_sharp : I imagine to use XML serialization like this : Edit : I know this code is wrong . It was just to display how I would like to use it.But this does not work at all : XmlSerializer is not generic . I have to cast from and to object on ( de ) serialization.Every property has to be fully public . Why are n't we just using Reflection to access private setters ? Private fields can not be serialized . I 'd like to decorate private fields with an attribute to have XmlSerializer include them.Did I miss something and XmlSerializer is actually offering the described possibilities ? Are there alternate serializers to XML that handle these cases more sophisticatedly ? If not : We 're in 2010 after all , and .NET has been around for many years . XML serialization is often used , totally standard and should be really easy to perform . Or is my understanding possibly wrong and XML serialization ought not to expose the described features for a good reason ? Edit : Legacy is not a good reason imo . Listwas nongeneric at first , too . ( Feel free to adjust caption or tags . If this should be CW , please just drop a note . ) class Foo { public Foo ( string name ) { Name1 = name ; Name2 = name ; } [ XmlInclude ] public string Name1 { get ; private set ; } [ XmlInclude ] private string Name2 ; } StreamWriter wr = new StreamWriter ( `` path.xml '' ) ; new XmlSerializer < Foo > ( ) .Serialize ( wr , new Foo ( `` me '' ) ) ;",Why is XmlSerializer so hard to use ? "C_sharp : I have a list of all distinct account name prefixes ( a-z ) which I acquire usingHowever what I want to do is instead of returning a distinct list is group the prefixes and return the number of accounts that start with that prefix , but I am unsure how to perform a group by using query over as it is not as straightforward as standard linq.The reason I am using QueryOver and not Query is because for some reason the substring function is being performed in memory and not on the database server.This is how I would usually do itEdit This is what I tried but I received the following errorUnrecognised method call in expression SqlFunction ( `` substring '' , NHibernateUtil.String , new [ ] { Property ( `` Name '' ) , Constant ( Convert ( 1 ) ) , Constant ( Convert ( 1 ) ) } ) var accounts = this.SessionManager.GetActiveSession ( ) .QueryOver < Account > ( ) ; var q = accounts.Select ( Projections.Distinct ( Projections.SqlFunction ( `` substring '' , NHibernateUtil.String , Projections.Property ( `` Name '' ) , Projections.Constant ( 1 ) , Projections.Constant ( 1 ) ) ) ) ; var prefixes = ( from acc in this.SessionManager.GetActiveSession ( ) .Query < Account > ( ) group acc by acc.Name.Substring ( 0 , 1 ) into grp select new { Prefix = grp.Key , Count = grp.Count ( ) } ) ; var accounts = this.SessionManager.GetActiveSession ( ) .QueryOver < Account > ( ) .Select ( Projections.Group < string > ( x = > Projections.SqlFunction ( `` substring '' , NHibernateUtil.String , Projections.Property ( `` Name '' ) , Projections.Constant ( 1 ) , Projections.Constant ( 1 ) ) ) , Projections.Count < string > ( x = > Projections.SqlFunction ( `` substring '' , NHibernateUtil.String , Projections.Property ( `` Name '' ) , Projections.Constant ( 1 ) , Projections.Constant ( 1 ) ) ) ) ;",GroupBy SqlFunction on QueryOver "C_sharp : I 'm really bothered by having to nest using blocks in C # . It 's not elegant and it takes up a lot of space . In some cases it appears to be unavoidable because I need to declare variables of different data types , but it seems like the single-type case should be possible to simplify . What I mean by `` the single-type case '' is when several variables of the same type are declared in series . Here 's an example of what I 'm talking about : The way I want this to work is that a is constructed before b , and that b is disposed before a . Unfortunately there does n't appear to be any direction in the C # specification as to how it should actually happen . It appears as though Microsoft 's C # compiler treats it like this , as this is the output of running the above program : However , I have no way of ensuring that this is deterministic behavior . Can someone either confirm or refute the idea that this sequence is deterministic ? References would be great . And obviously , if it 's prone to breakage ( undocumented , etc . ) it 's probably not useful , but that 's a good thing to know.There 's already a similar question about deterministic disposal that talks about the multiple-type case , and I understand that there 's no real solution there aside from clever syntax tricks . Most of the answers there miss the point , anyway . My question is just about the single-type case and whether this disposal is deterministic and dependable or not . Thanks . class Program { static void Main ( string [ ] args ) { using ( A a = new A ( `` a '' ) , b = new A ( `` b '' ) ) { } } class A : IDisposable { string n = null ; public A ( string name ) { n = name ; Console.WriteLine ( String.Format ( `` Creating { 0 } '' , n ) ) ; } public void Dispose ( ) { Console.WriteLine ( String.Format ( `` Disposing { 0 } '' , n ) ) ; } } } Creating aCreating bDisposing bDisposing a",Disposal Order in C # Using Blocks "C_sharp : Im working towards a dll file for a software 's SDK and i 'm trying to call a function to get information about the host of the software.there are two unsigned char variables ( HostMachineAddress , HostProgramVersion ) in the struct the function wants and it seems like i `` loose '' the last byte when i try to call it from c # ... if I change the SizeConst in the c # struct below to 5 i do get the missing byte , however it causes the other variable looses data.Could someone help me find a way to solve this issue ? also trying to use a class instead of struct causes system.stackoverflow errorC # StructC # [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Ansi ) ] public struct sHostInfo { public int bFoundHost ; public int LatestConfirmationTime ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 128 ) ] public string szHostMachineName ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 4 ) ] public string HostMachineAddress ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 128 ) ] public string szHostProgramName ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 4 ) ] public string HostProgramVersion ; } [ DllImport ( `` Cortex_SDK.dll '' ) ] public static extern int GetHostInfo ( out sHostInfo pHostInfo ) ;","P/Invoke , c # : unsigned char losing a byte" "C_sharp : I 've been reading this book from Joseph Albahari about threading : http : //www.albahari.com/threading/In Part 2 , I found this example : http : //www.albahari.com/threading/part2.aspx # _When_to_LockHere is the aforementioned example : Thread-safe version : I could n't understand why Assign method is not thread safe . Should n't integer assignment be atomic operation on both 32- and 64-bit architectures ? class ThreadUnsafe { static int _x ; static void Increment ( ) { _x++ ; } static void Assign ( ) { _x = 123 ; } } class ThreadSafe { static readonly object _locker = new object ( ) ; static int _x ; static void Increment ( ) { lock ( _locker ) _x++ ; } static void Assign ( ) { lock ( _locker ) _x = 123 ; } }",Why is this assignment not thread-safe ? "C_sharp : In Python , if I have a dict , and I want to get a value from a dict where the key might not be present I 'd do something like : where , if someKey is not present , then someDefaultValue is returned.In C # , there 's TryGetValue ( ) which is kinda similar : One gotcha with this though is that if someKey is null then an exception gets thrown , so you put in a null-check : Which , TBH , is icky ( 3 lines for a dict lookup ? ) Is there a more concise ( ie 1-line ) way that is much like Python 's get ( ) ? lookupValue = somedict.get ( someKey , someDefaultValue ) var lookupValue ; if ( ! somedict.TryGetValue ( someKey , lookupValue ) ) lookupValue = someDefaultValue ; var lookupValue = someDefaultValue ; if ( someKey ! = null & & ! somedict.TryGetValue ( someKey , lookupValue ) ) lookupValue = someDefaultValue ;",C # Dictionary equivalent to Python 's get ( ) method "C_sharp : When I use Resharper to refactor my code to use an Object initializer , it reformats the code correctly as thus , the following codebecomesI ca n't find anyplace in Resharper options where I can set it up to retain the parentheses as part of the constructor code ( which I prefer for consistency ) . Is it possible ? I would like Resharper to format it thus : var response = new Response ( ) ; response.Value = `` My value '' ; var response = new Response { Value = `` My value '' , } ; var response = new Response ( ) { Value = `` My value '' , } ;",Resharper - use object initializer refactor - how to retain parentheses on constructor call ? "C_sharp : I have a database table Item and access it with linq-to-sql.I can define a custom Method IsSpecial ( ) for Items which returns true if the square root of Item.id is even : Then I can use that property in a linq-to-sql query like this : Now for aesthetic reasons , I want to make IsSpecial nonstatic and modify it so I can call it like this : Ideally this would also allow combining of statements , which the above ( working ) snytax does not allow : What is the correct syntax for defining this method ? This does not work : edit : I am beginning to suspect that I am asking for something that the syntax simply does not allowI guess I can live with datacontext.Item.Where ( Item.IsSpecial ) .Where ( i = > i > 100 ) partial class Item { public static Expression < Func < Item , bool > > IsSpecial = ( i = > Math.Sqrt ( i.Id ) % 2==0 ) ; } datacontext.Item.Where ( Item.IsSpecial ) datacontext.Item.Where ( i = > i.IsSpecial ( ) ) datacontext.Item.Where ( i = > i.IsSpecial ( ) & & i.Id > 100 ) partial class Item { public Expression < Func < bool > > IsSpecial = ( ( ) = > Math.Sqrt ( this.Id ) % 2==0 ) ; // 'this ' keyword not available in current context }",Non-static Expression < Func < X > > with access to 'this ' C_sharp : I 'm trying to use IFormFile as a property in a nested ViewModel . I am running into issues trying to bind the ViewModel to the controller action at runtime . The AJAX request stalls and never reaches the action.This conceptual question is in reference to my specific issue at IFormFile property in .NET Core ViewModel causing stalled AJAX RequestViewModel : Nested ViewModel : Action : I am wondering if an IFormFile Property needs to be a direct property of the ViewModel you are binding to a controller action.The IFormFile Documentation does not seem to answer my question . public class ProductViewModel { public ProductDTO Product { get ; set ; } public List < ProductImageViewModel > Images { get ; set ; } } public class ProductImageViewModel { public ProductImageDTO ProductImage { get ; set ; } public IFormFile ImageFile { get ; set ; } } [ HttpPost ] public IActionResult SaveProduct ( [ FromForm ] ProductViewModel model ) { //save code },IFormFile as a Nested ViewModel Property "C_sharp : I am new to Rx . I can see some real benefits of using Hot Observables , however I was recently asked the question on what the difference was between a cold observable and an equivalent enumerable ( see code snippet below ) ... Can anyone explain very simply what the difference is between the two and what benefit I would get from the cold observable vs the enumerable . var resRx = Observable.Range ( 1 , 10 ) ; var resOb = Enumerable.Range ( 1 , 10 ) ;",Difference between cold observable in RX and normal Enumerable "C_sharp : There is a wall of size 4xN . We have infinite number of bricks of size 4x1 and 1x4 . What is the total number of ways in which the bricks can be arranged on the wall so that a new configuration arises every time ? For N = 1 , the brick can be laid in 1 format only . For N = 7 , one of the ways in which we can lay the bricks isThere are 5 ways of arranging the bricks for N = 7I solve this problem using dynamic programming : But it 's just a combination : a guess + intuition . I do n't understand this solution completely . Why table [ i ] = table [ i-1 ] + table [ i-4 ] ? Does n't it look like the coin change problem ? The number of ways to change amount a using n kinds of coins equals : the number of ways to change amount a using all but the first kind of coin , plus the number of ways to change amount a - d using all n kinds of coins , where d is the denomination of the first kind of coin.But I also do n't understand how we can use this idea to solve the original problem static int computeBricks ( int n ) { if ( n < = 3 ) { return 1 ; } int [ ] table = new int [ n+1 ] ; table [ 0 ] = 1 ; table [ 1 ] = 1 ; table [ 2 ] = 1 ; table [ 3 ] = 1 ; for ( int i = 4 ; i < = n ; ++i ) { table [ i ] = table [ i-1 ] + table [ i-4 ] ; } return table [ n ] ; }",What is the total number of ways in which the bricks can be arranged on the wall ? "C_sharp : Is it possible to get NServiceBus3 log to NLog ? and if so does anyone have any examples of how to do this ? EDIT : SolutionIf anyone is interested here 's my implementation of the appender , some of the log4net levels are probably not mapped to sensible NLog areas but it should give other people at least a start pointand heres how i wire it up in NServiceBus // Setup a custom formatter like the one below to get nice exception logging // < target name= '' YourLogFile '' xsi : type= '' File '' fileName= '' $ { basedir } /../logs/YourLogFile.log '' archiveFileName= '' $ { basedir } /../logs/archives/YourLogFile . { # # # # # } .log '' //layout= '' $ { longdate } | $ { level : uppercase=true } | $ { logger } | $ { message } $ { onexception : |EXCEPTION OCCURRED\ : $ { exception : format=type , message , method : maxInnerExceptionLevel=5 : innerFormat=shortType , message , method } } '' //archiveEvery= '' Day '' archiveNumbering= '' Sequence '' maxArchiveFiles= '' 14 '' / > public class NlogAppenderForLog4Net : AppenderSkeleton { protected override void Append ( log4net.Core.LoggingEvent loggingEvent ) { var Logger = LogManager.GetLogger ( loggingEvent.LoggerName ) ; if ( loggingEvent.Level == Level.Fatal ) { if ( loggingEvent.ExceptionObject ! = null ) { Logger.FatalException ( loggingEvent.RenderedMessage , loggingEvent.ExceptionObject ) ; } else { Logger.Fatal ( loggingEvent.RenderedMessage ) ; } } //if its an error else if ( loggingEvent.Level == Level.Error || loggingEvent.Level == Level.Critical || loggingEvent.Level == Level.Emergency ) { if ( loggingEvent.ExceptionObject ! = null ) { Logger.ErrorException ( loggingEvent.RenderedMessage , loggingEvent.ExceptionObject ) ; } else { Logger.Error ( loggingEvent.RenderedMessage ) ; } } //if its a warning else if ( loggingEvent.Level == Level.Warn ) { if ( loggingEvent.ExceptionObject ! = null ) { Logger.WarnException ( loggingEvent.RenderedMessage , loggingEvent.ExceptionObject ) ; } else { Logger.Warn ( loggingEvent.RenderedMessage ) ; } } //if its info else if ( loggingEvent.Level == Level.Info || loggingEvent.Level == Level.Notice ) { Logger.Info ( loggingEvent.RenderedMessage ) ; } else { Logger.Trace ( loggingEvent.RenderedMessage ) ; } } } .Log4Net < NlogAppenderForLog4Net > ( a = > { } )",Using NLog with NServiceBus 3 "C_sharp : I have the following class : And I 'm creating and Expression tree of type Expression < Func < Test , bool > > on this class . When I do it like this : I get the following debug view : note : there 's a & & for and-operation.When I do it like this : I get the following debug view : Note : there 's & for and-operation . Why do I get & in the second case ? How to modify predicate2 to get & & instead of & ? Thanks in advance ! public class Test { public string Text { get ; set ; } public int Number { get ; set ; } } Expression < Func < Test , bool > > predicate1 = x = > x.Text.Length > 5 & & x.Number > 0 ; .Lambda # Lambda1 < System.Func ` 2 [ NHLinqTest.Test , System.Boolean ] > ( NHLinqTest.Test $ x ) { ( $ x.Text ) .Length > 5 & & $ x.Number > 0 } var y = Expression.Parameter ( typeof ( Test ) ) ; var predicate2 = Expression.And ( Expression.GreaterThan ( Expression.Property ( Expression.Property ( y , `` Text '' ) , `` Length '' ) , Expression.Constant ( 5 ) ) , Expression.GreaterThan ( Expression.Property ( y , `` Number '' ) , Expression.Constant ( 0 ) ) ) ; ( $ var1.Text ) .Length > 5 & $ var1.Number > 0",Why Expression.And represents `` & '' but not `` & & '' "C_sharp : Is this documentation still valid or am I missing something ? http : //doc.xceedsoft.com/products/XceedWpfToolkit/Xceed.Wpf.Toolkit~Xceed.Wpf.Toolkit.PropertyGrid.PropertyGrid~SelectedObjects.htmlPropertyGrid control does not appear to have SelectedObjects or SelectedObjectsOverride members . I 'm using the latest version ( 2.5 ) of the Toolkit against .NET Framework 4.0.UPDATE @ faztp12 's answer got me through . For anyone else looking for a solution , follow these steps : Bind your PropertyGrid 's SelectedObject property to the first selected item . Something like this : Listen to PropertyValueChanged event of the PropertyGrid and use the following code to update property value to all selected objects.Hope this helps someone down the road . < xctk : PropertyGrid PropertyValueChanged= '' PG_PropertyValueChanged '' SelectedObject= '' { Binding SelectedObjects [ 0 ] } '' / > private void PG_PropertyValueChanged ( object sender , PropertyGrid.PropertyValueChangedEventArgs e ) { var changedProperty = ( PropertyItem ) e.OriginalSource ; foreach ( var x in SelectedObjects ) { //make sure that x supports this property var ProperProperty = x.GetType ( ) .GetProperty ( changedProperty.PropertyDescriptor.Name ) ; if ( ProperProperty ! = null ) { //fetch property descriptor from the actual declaring type , otherwise setter //will throw exception ( happens when u have parent/child classes ) var DeclaredProperty = ProperProperty.DeclaringType.GetProperty ( changedProperty.PropertyDescriptor.Name ) ; DeclaredProperty.SetValue ( x , e.NewValue ) ; } } }",WPF PropertyGrid supports multiple selection "C_sharp : I am terrible with databases so please bear with me.I have a program that gets some user information and adds it to a database table . I then later need to get more information for that table , and update it . To do so I have tried doing this : But I get this error : System.InvalidOperationException : Can not add an entity that already exists.I know this is because I already have an entry in the table , but I do n't know how to edit the code to update , and not try to make a new one ? Why does this not work ? Would n't submitting changes on a current item update that item and not make a new one ? public static void updateInfo ( string ID , string email , bool pub ) { try { //Get new data context MyDataDataContext db = GetNewDataContext ( ) ; //Creates a new data context //Table used to get user information User user = db.Users.SingleOrDefault ( x = > x.UserId == long.Parse ( ID ) ) ; //Checks to see if we have a match if ( user ! = null ) { //Add values user.Email = email ; user.Publish = publish ; } //Prep to submit changes db.Users.InsertOnSubmit ( user ) ; //Submit changes db.SubmitChanges ( ) ; } catch ( Exception ex ) { //Log error Log ( ex.ToString ( ) ) ; } }",How to update a database with new information "C_sharp : Using latest Closed XML ( 0.76 ) on Net 4.5.1Created a Worksheet with a table by : This is done inside a loop ( i.e . multiple tables in the `` Data '' sheet ) . A problem arises where the generated Excel document ca n't be opened if multiple pivot tables are created in a separate sheet.Any ideas why and how to debug ? DataTable Table = ... var DataWorkSheet = Workbook.Worksheets.Any ( x = > x.Name == `` Data '' ) ? Workbook .Worksheets .First ( x = > x.Name == `` Data '' ) : Workbook .Worksheets .Add ( `` Data '' ) ; int Start = ... // calculate cell start var Source = DataWorkSheet .Cell ( Start , 1 ) .InsertTable ( Table , Name , true ) ; var Range = Source.DataRange ; var PivotWorkSheet = Workbook .Worksheets .Add ( Name ) ; var Pivot = PivotWorkSheet .PivotTables .AddNew ( Name , PivotWorkSheet.Cell ( 1 , 1 ) , DataRange ) ;",Multiple Pivot tables ClosedXML "C_sharp : What is the purpose of the two parentheses and arrow service.GetDeviceLOV = ( ) = > I have been trying to figure out its function . Down below is the whole method which was used for unit testing . Hope this help give it context . //A test for GetDeviceTypes [ TestMethod ( ) ] [ HostType ( `` Moles '' ) ] public void GetDeviceTypesTest ( ) { SetUpMoles ( ) ; Login ( ) ; service.GetDeviceLOV = ( ) = > { return new List < DeviceLOV > ( ) { new DeviceLOV { DeviceType = `` Type 1 '' } , new DeviceLOV { DeviceType = `` Type 2 '' } , new DeviceLOV { DeviceType = `` Type 1 '' } } ; } ; List < string > actual ; actual = presenter.GetDeviceTypes ( ) ; Assert.AreEqual ( 2 , actual.Count , '' actual.Count Should = 2 '' ) ; }",What is the purpose of using two blank parentheses followed by the arrow in c # "C_sharp : I am trying to convert the following collection : SourceDestinationI 've researched it , and think that the answer lies somewhere with the SelectMany ( ) method but I can seem to pin down the answer.The problem is similar to : How do I select a collection within a collection using LINQ ? which denormalises the collection but it does n't show how to include the related columns ( columns 1 and 2 in my example ) .The difference is that I need to include the first two columns and also return a row where there are no entries in the collection . `` a '' , `` b '' , { 1,2,3 } '' d '' , `` f '' , { 1,2,2 } '' y '' , `` z '' , { } `` a '' , `` b '' , 1 '' a '' , `` b '' , 2 '' a '' , `` b '' , 3 '' d '' , `` f '' , 1 '' d '' , `` f '' , 2 '' d '' , `` f '' , 2 '' y '' , `` z '' , null",how to denormalize a collection which contains a collection using Linq "C_sharp : I am accessing appointment attendees from an EWS Calendar . I tried : cView.PropertySet = new PropertySet ( AppointmentSchema.Subject , AppointmentSchema.Start , AppointmentSchema.End ) ; But my appointments list entries each returned null Required/Optional Attendees fields , even though the test appointments had been accepted by several users . My assumption is that the PropertySet needs to include more ApplicationSchema properties like so : However this throws the following ServiceValidationException error on calendar.FindAppointments ( cView ) : Microsoft.Exchange.WebServices.Data.ServiceValidationException : The property RequiredAttendees ca n't be used in FindItem requests.How do I fix this so that appointments includes required/optional attendees ? cView.PropertySet = new PropertySet ( AppointmentSchema.Subject , AppointmentSchema.Start , AppointmentSchema.End , AppointmentSchema.RequiredAttendees , AppointmentSchema.OptionalAttendees ) ; ExchangeService service = new ExchangeService ( ExchangeVersion.Exchange2007_SP1 ) ; service.Credentials = new WebCredentials ( emailAddress , emailPassword ) ; // Initialize values for the start and end times , and the number of appointments to retrieve.DateTime startDate = DateTime.Now ; DateTime endDate = startDate.AddYears ( 1 ) ; const int NUM_APPTS = 4 ; // Initialize the calendar folder object with only the folder ID . CalendarFolder calendar = CalendarFolder.Bind ( service , WellKnownFolderName.Calendar , new PropertySet ( ) ) ; // Set the start and end time and number of appointments to retrieve.CalendarView cView = new CalendarView ( startDate , endDate , NUM_APPTS ) ; // Limit the properties returned to the appointment 's subject , start time , and end time.cView.PropertySet = new PropertySet ( AppointmentSchema.Subject , AppointmentSchema.Start , AppointmentSchema.End , AppointmentSchema.RequiredAttendees , AppointmentSchema.OptionalAttendees ) ; // Retrieve a collection of appointments by using the calendar view.FindItemsResults < Appointment > appointments = calendar.FindAppointments ( cView ) ;",Microsoft.Exchange.WebServices.Data.ServiceValidationException : The property RequiredAttendees ca n't be used in FindItem requests "C_sharp : I have a ServiceStack based Soap Client , which operates correctly for HTTP but when I try to use HTTPS it gives me this errorI am using a self signed certificate , but I am able to use curl to call my Soap service successfully . This to me indicates that the issue is at the client end.My code goes along the lines ofThe above shows example request/response DTO class usage . What do I have to do to make it work with HTTPS without using config files , only code ? ServiceStack.WebServiceException : The provided URI scheme 'https ' is invalid ; expected 'http'.Parameter name : via -- - > System.ArgumentException : The provided URI scheme 'https ' is invalid ; expected 'http'.Parameter name : via at System.ServiceModel.Channels.HttpChannelFactory ` 1.ValidateCreateChannelParameters ( EndpointAddress remoteAddress , Uri via ) at System.ServiceModel.Channels.HttpChannelFactory ` 1.OnCreateChannelCore ( EndpointAddress remoteAddress , Uri via ) at System.ServiceModel.Channels.ChannelFactoryBase ` 1.InternalCreateChannel ( EndpointAddress address , Uri via ) at System.ServiceModel.Channels.ServiceChannelFactory.ServiceChannelFactoryOverRequest.CreateInnerChannelBinder ( EndpointAddress to , Uri via ) at System.ServiceModel.Channels.ServiceChannelFactory.CreateServiceChannel ( EndpointAddress address , Uri via ) at System.ServiceModel.Channels.ServiceChannelFactory.CreateChannel ( Type channelType , EndpointAddress address , Uri via ) at System.ServiceModel.ChannelFactory ` 1.CreateChannel ( EndpointAddress address , Uri via ) at System.ServiceModel.ClientBase ` 1.CreateChannel ( ) at System.ServiceModel.ClientBase ` 1.CreateChannelInternal ( ) at System.ServiceModel.ClientBase ` 1.get_Channel ( ) at ServiceStack.WcfServiceClient.Send ( Message message ) at ServiceStack.WcfServiceClient.Send [ T ] ( Object request ) -- - End of inner exception stack trace -- - at ServiceStack.WcfServiceClient.Send [ T ] ( Object request ) at ElectronicServiceInterface.ESIClient.Login ( ) using ( var client = new Soap12ServiceClient ( Uri ) ) { var request = new MyRequestObject { Username = Username , Password = Password } ; var response = client.Send < MyResponseObject > ( request ) ; }",ServiceStack Soap 1.2 HTTPS Client "C_sharp : I need to display a live video stream in a UWP application.The video stream comes from a GoPro . It is transported by UDP messages . It is a MPEG-2 TS stream . I can play it successfully using FFPlay with the following command line : I would like to play it with MediaPlayerElement without using a third party library.According to the following page : https : //docs.microsoft.com/en-us/windows/uwp/audio-video-camera/supported-codecsUWP should be able to play it . ( I installed the `` Microsoft DVD '' application in the Windows Store ) .I receive the MPEG-2 TS stream with a UdpClient . It works well.I receive in each UdpReceiveResult a 12 bytes header , followed by 4 , 5 , 6 , or 7 MPEGTS packets ( each packet is 188 bytes , beginning with 0x47 ) .I created a MseStreamSource : This is how I send the messages to the MseStreamSource : The MediaPlayerElement displays the message `` video not supported or incorrect file name '' . ( not sure of the message , my Windows is in French ) .Is it a good idea to use the MseAppendMode.Sequence mode ? What should I pass to the AppendBuffer method ? The raw udp message including the 12 bytes header or each MPEGTS 188 bytes packet ? ffplay -fflags nobuffer -f : v mpegts udp : //:8554 _mseStreamSource = new MseStreamSource ( ) ; _mseStreamSource.Opened += ( _ , __ ) = > { _mseSourceBuffer = _mseStreamSource.AddSourceBuffer ( `` video/mp2t '' ) ; _mseSourceBuffer.Mode = MseAppendMode.Sequence ; } ; _mediaPlayerElement.MediaSource = MediaSource.CreateFromMseStreamSource ( _mseStreamSource ) ; UdpReceiveResult receiveResult = await _udpClient.ReceiveAsync ( ) ; byte [ ] bytes = receiveResult.Buffer ; mseSourceBuffer.AppendBuffer ( bytes.AsBuffer ( ) ) ;",Play MPEG-2 TS using MseStreamSource "C_sharp : I have a set of working imperative code in test and I 'm trying to boil it down to an essential test convention.My test looks like the following : I also have a customization that allows this to work , namely by setting the HttpConfiguration and HttpRequestMessage to default non-null values.First , this looks ugly , but if I use Build < > ( ) .omit ( ) .with ( config ) .with ( request ) , it shuts off the automoq customization which it needs to build those instances.Second , this only works for a SiteVersionController . I 'd much rather generalize this for all my ApiControllers ( maybe that 's a bad idea , but I wo n't know until I try ) .Essentially my convention would be as follows : for all ApiControllers , create them without auto properties but do set the http configuration and request message properties to default non-null values [ Theory , BasicConventions ] public void GetVersionOnSiteVersionControllerReturnsASiteVersion ( IFixture fixture ) { fixture.OmitAutoProperties = true ; SiteVersion expected = fixture.Create < SiteVersion > ( ) ; SiteVersion actual = null ; var sut = fixture.Create < SiteVersionController > ( ) ; var response = sut .GetSiteVersion ( ) .ExecuteAsync ( new CancellationToken ( ) ) .Result .TryGetContentValue < SiteVersion > ( out actual ) ; actual.AsSource ( ) .OfLikeness < SiteVersion > ( ) .ShouldEqual ( expected ) ; } public class ApiControllerCustomization : ICustomization { public void Customize ( IFixture fixture ) { var origin = fixture.OmitAutoProperties ; fixture.OmitAutoProperties = true ; var sut = fixture.Create < SiteVersionController > ( ) ; sut.Configuration = fixture.Create < HttpConfiguration > ( ) ; sut.Request = fixture.Create < HttpRequestMessage > ( ) ; fixture.Inject < SiteVersionController > ( sut ) ; fixture.OmitAutoProperties = origin ; } }",need to create convention for ApiControllers "C_sharp : I come from a python background , where it 's often said that it 's easier to apologize than to ask permission . Specifically given the two snippets : Then under most usage scenarios the second one will be faster when A is usually an integer ( assuming do_something needs an integer as input and will raise its exception fairly swiftly ) as you lose the logical test from every execution loop , at the expense of a more costly exception , but far less frequently . What I wanted to check was whether this is true in C # , or whether logical tests are fast enough compared to exceptions to make this a small corner case ? Oh and I 'm only interested in release performance , not debug.OK my example was too vague try this one : Naive solution : Logic based solution : Exception based solution : Examples using FSOs , database connections , or stuff over a network are better but a bit long-winded for a question . if type ( A ) == int : do_something ( A ) else : do_something ( int ( A ) ) try : do_something ( A ) except TypeError : do_something ( int ( A ) ) return float ( A ) % 20 # coerse A to a float so it 'll only fail if we actually do n't # have anything that can be represented as a real number . if isinstance ( A , Number ) : # This is cheaper because we 're not creating a new return A % 20 # object unless we really have to.else : return float ( A ) % 20 try : # Now we 're doing any logical tests in the 99 % of cases where A is a number return A % 20except TypeError : return float ( A ) % 20",To ask permission or apologize ? "C_sharp : I am trying to write a LINQ query to orderBy a dynamic property given by a string value.Here is what my original code was : When I tried to run this orderBy I got the following exception : LINQ to Entities does not recognize the method 'System.Object GetValue ( System.Object ) ' method , and this method can not be translated into a store expression.I am trying to work around this by creating an expression tree that will give me the same result . The code should be able to return any type depending on the parameter but I 'm having trouble with the return type . If I do n't convert the value I get a different error saying w Nullable DateTime ca n't be converted to Object . Here is the code that I have so far : and my new exception : Unable to cast the type 'System.Nullable ` 1 [ [ System.DateTime ] ] ' to type 'System.Object ' . LINQ to Entities only supports casting EDM primitive or enumeration types.How would I write this expression tree to do return a dynamic type ? Also is there a better way I should be doing this in LINQ ? Expression < Func < T , dynamic > > orderBy = i = > i.GetType ( ) .GetProperty ( `` PropertyName '' ) .GetValue ( null ) ; ParameterExpression pe = Expression.Parameter ( typeof ( T ) , `` s '' ) ; Expression < Func < T , dynamic > > orderByExpression = Expression.Lambda < Func < T , dynamic > > ( Expression.Convert ( Expression.Property ( pe , `` PropertyName '' ) , typeof ( object ) ) , pe ) ;",LINQ to Entities OrderBy Expression Tree "C_sharp : I used Brian Noyes 's Pluralsight course , `` WPF MVVM In Depth '' as my main source , and what he shows works excellently . However , instead of switching Views based on buttons clicked on the UtilitiesView , I want to switch Views based on a Toolbar button ( that forms part of a VS 2015 extension package ) where the user can choose a specific instance.The UtilitiesView is a user control on the window that is opened by the Package Extension.So here is the xaml in the UtilitiesView : ` As can be seen , there are two buttons that switch the View by binding to ChangeViewModelCommand and passing a string value ( either `` CalculationEngine '' or `` TAEngine '' ) through.Here is the UtilitiesViewModel.cs class : Here is BindableBase.cs : I use a simple ViewModelLocator class to link the Views with their ViewModels : As mentioned earlier , switching Views with the buttons defined on UtilitiesView.xaml works fine.The Toolbar buttons call the above-mentioned ChangeViewModel method in UtilitiesViewModel.cs from out of the Package.cs class , but then even though the CurrentEngineViewModel property is set differently , it does n't reflect on UtilitiesView.xaml.When I debug , then with both cases it goes correctly to the SetProperty of BindableBase , but then in the case of the ToolBar buttons , the AutoWireViewModelChanged method in the ViewModelLocator is never called . I do n't know why not . I would have thought that the binding in UtilitiesView with the property CurrentEngineViewModel of UtilitiesViewModel , would be enough ? I try to think of it as if I have made a change in the model-component , and the View should respond to that , even though I actually have the Toolbar buttons as part of what one would consider the view-component.This is how the ChangeViewModel method is called in the Package.cs class : I hope I have given enough detail.UPDATE 1With regards to gRex 's comments , I am thinking that perhaps there are two UtilitiesViewModel objects . This is what happens when the custom window of the Package Extension is opened : The AutoWireViewModelChanged method is called to link the UtilitiesViewModel to the UtilitiesView for the Content.In the Package.cs class , I have this field : and in the Initialize method I have : The uvm object is used as in the code snippet in the original post ( just above the UPDATE ) to call the ChangeViewModel method with the appropriate string parameter.This would give me two different objects , would n't it ? If so , and assuming that this could be the root cause of the problem , how can I improve this , must I make UtilitiesViewModel a singleton ? UPDATE 2I have added a solution to Github . The functionality is slightly changed so that I did n't need any interaction with the rest of the original solution.Thus , the Connect button ( on the Toolbar ) calls the ChangeViewModel method with the `` TAEngine '' parameter , and the Save button ( on the Toolbar ) does the same but with `` CalculationEngine '' as parameter . Currently the DataTemplates are still commented out , so one just sees the class name in text.Here is the link . In the experimental instance of Visual Studio , the window can be found at View - > Other Windows - > SymplexityCalculationUtilitiesWindow.You might need to download the Visual Studio SDK if you do n't have it already.Update 3I used the Unity IoC Container with a ContainerControlledLifetimeManager to ensure that I do n't have two distinct UtilitiesViewModels . After implementing this , the Toolbar buttons could navigate the correct View . < UserControl.Resources > < DataTemplate DataType= '' { x : Type engines : CalcEngineViewModel } '' > < engines : CalcEngineView/ > < /DataTemplate > < DataTemplate DataType= '' { x : Type engines : TAEngineViewModel } '' > < engines : TAEngineView/ > < /DataTemplate > < /UserControl.Resources > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' auto '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < Grid x : Name= '' NavContent '' > < Grid.ColumnDefinitions > < ColumnDefinition Width = '' * '' / > < ColumnDefinition Width = '' * '' / > < ColumnDefinition Width = '' * '' / > < /Grid.ColumnDefinitions > < Button Content= '' Calc '' Command = '' { Binding ChangeViewModelCommand } '' CommandParameter= '' CalculationEngine '' Grid.Column= '' 0 '' / > < Button Content= '' TA '' Command = '' { Binding ChangeViewModelCommand } '' CommandParameter= '' TAEngine '' Grid.Column= '' 1 '' / > < /Grid > < Grid x : Name= '' MainContent '' Grid.Row= '' 1 '' > < ContentControl Content= '' { Binding CurrentEngineViewModel } '' / > < /Grid > < /Grid > < /UserControl > ` public class UtilitiesViewModel : BindableBase { # region Fields public RelayCommand < string > ChangeViewModelCommand { get ; private set ; } private CalcEngineViewModel calcViewModel = new CalcEngineViewModel ( ) ; private TAEngineViewModel taViewModel = new TAEngineViewModel ( ) ; private BindableBase currentEngineViewModel ; public BindableBase CurrentEngineViewModel { get { return currentEngineViewModel ; } set { SetProperty ( ref currentEngineViewModel , value ) ; } } # endregion public UtilitiesViewModel ( ) { ChangeViewModelCommand = new RelayCommand < string > ( ChangeViewModel ) ; } # region Methods public void ChangeViewModel ( string viewToShow ) // ( IEngineViewModel viewModel ) { switch ( viewToShow ) { case `` CalculationEngine '' : CurrentEngineViewModel = calcViewModel ; break ; case `` TAEngine '' : CurrentEngineViewModel = taViewModel ; break ; default : CurrentEngineViewModel = calcViewModel ; break ; } } # endregion } public class BindableBase : INotifyPropertyChanged { protected virtual void SetProperty < T > ( ref T member , T val , [ CallerMemberName ] string propertyName = null ) { if ( object.Equals ( member , val ) ) return ; member = val ; PropertyChanged ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } public event PropertyChangedEventHandler PropertyChanged = delegate { } ; protected virtual void OnPropertyChanged ( string propertyName ) { PropertyChanged ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } public static class ViewModelLocator { public static bool GetAutoWireViewModel ( DependencyObject obj ) { return ( bool ) obj.GetValue ( AutoWireViewModelProperty ) ; } public static void SetAutoWireViewModel ( DependencyObject obj , bool value ) { obj.SetValue ( AutoWireViewModelProperty , value ) ; } // Using a DependencyProperty as the backing store for AutoWireViewModel . This enables animation , styling , binding , etc ... public static readonly DependencyProperty AutoWireViewModelProperty = DependencyProperty.RegisterAttached ( `` AutoWireViewModel '' , typeof ( bool ) , typeof ( ViewModelLocator ) , new PropertyMetadata ( false , AutoWireViewModelChanged ) ) ; private static void AutoWireViewModelChanged ( DependencyObject d , DependencyPropertyChangedEventArgs e ) { if ( DesignerProperties.GetIsInDesignMode ( d ) ) return ; var viewType = d.GetType ( ) ; var viewTypeName = viewType.FullName ; var viewModelTypeName = viewTypeName + `` Model '' ; var viewModelType = Type.GetType ( viewModelTypeName ) ; var viewModel = Activator.CreateInstance ( viewModelType ) ; ( ( FrameworkElement ) d ) .DataContext = viewModel ; } } if ( Config.Engine.AssemblyPath.Contains ( `` Engines.TimeAndAttendance.dll '' ) ) { uvm.ChangeViewModel ( `` TAEngine '' ) ; } else //Assume Calculation Engine { uvm.ChangeViewModel ( `` CalculationEngine '' ) ; } public class SymCalculationUtilitiesWindow : ToolWindowPane { /// < summary > /// Initializes a new instance of the < see cref= '' SymCalculationUtilitiesWindow '' / > class . /// < /summary > public SymCalculationUtilitiesWindow ( ) : base ( null ) { this.Caption = `` Sym Calculation Utilities '' ; this.ToolBar = new CommandID ( new Guid ( Guids.guidConnectCommandPackageCmdSet ) , Guids.SymToolbar ) ; // This is the user control hosted by the tool window ; Note that , even if this class implements IDisposable , // we are not calling Dispose on this object . This is because ToolWindowPane calls Dispose on // the object returned by the Content property . this.Content = new UtilitiesView ( ) ; } } private UtilitiesViewModel uvm ; uvm = new UtilitiesViewModel ( ) ;",MVVM : View Navigation not working correctly C_sharp : Consider the above example where I take a list of employees aged above 30 . What is the difference between Method 1 and Method 2 ? Which one would you prefer and why ? using ( DBEntities db = new DBEntities ( ) ) { var employeeAgedAbove30 = db.Employees.Where ( s = > s.Age > 30 ) .Count ( ) ; // Method 1 employeeAgedAbove30 = db.Employees.Count ( s = > s.Age > 30 ) ; // Method 2 },Difference between Where ( ) .Count ( ) and Count ( ) "C_sharp : One day I was trying to get a better understanding of threading concepts , so I wrote a couple of test programs . One of them was : I hoped I will be able to see outputs less than 2000000 . The model in my imagination was the following : more threads read variable a at the same time , all local copies of a will be the same , the threads increment it and the writes happen and one or more increments are `` lost '' this way.Although the output is against this reasoning . One sample output ( from a corei5 machine ) : If my reasoning were true I would see 2000000 occasionally and sometimes numbers a bit less . But what I see is 2000000 occasionally and numbers way less than 2000000 . This indicates that what happens behind the scenes is not just a couple of `` increment losses '' but something more is going on . Could somebody explain me the situation ? Edit : When I was writing this test program I was fully aware how I could make this thrad safe and I was expecting to see numbers less than 2000000 . Let me explain why I was surprised by the output : First lets assume that the reasoning above is correct . Second assumption ( this wery well can be the source of my confusion ) : if the conflicts happen ( and they do ) than these conflicts are random and I expect a somewhat normal distribution for these random event occurences . In this case the first line of the output says : from 500000 experiments the random event never occured . The second line says : the random event occured at least 167365 times . The difference between 0 and 167365 is just to big ( almost impossible with a normal distribution ) . So the case boils down to the following : One of the two assumptions ( the `` increment loss '' model or the `` somewhat normally distributed paralell conflicts '' model ) are incorrect . Which one is and why ? using System ; using System.Threading.Tasks ; class Program { static volatile int a = 0 ; static void Main ( string [ ] args ) { Task [ ] tasks = new Task [ 4 ] ; for ( int h = 0 ; h < 20 ; h++ ) { a = 0 ; for ( int i = 0 ; i < tasks.Length ; i++ ) { tasks [ i ] = new Task ( ( ) = > DoStuff ( ) ) ; tasks [ i ] .Start ( ) ; } Task.WaitAll ( tasks ) ; Console.WriteLine ( a ) ; } Console.ReadKey ( ) ; } static void DoStuff ( ) { for ( int i = 0 ; i < 500000 ; i++ ) { a++ ; } } } 2000000149790310263292000000128160413956341417712139730013960311285850109202710682051091915130049313570771133384148527912902721048169704754",Concurrency issue : parallel writes "C_sharp : See the following code : new Derived ( ) .Bang ( ) ; throws an exception . Inside the generated CIL of the method Bang I got : and the signature of the compiler generated method : I think the correct code should be ' < > n__FabricatedMethod1 ' < class T > . Is it a bug ? By the way , without using delegate { } ( lambda expression is the same ) , the code works fine with syntax sugars.EDIT I 'm using VS2012 RTMRel in windows8 RTM , .net framework 4.5EDIT This bug is now fixed . public abstract class Base { public virtual void Foo < T > ( ) where T : class { Console.WriteLine ( `` base '' ) ; } } public class Derived : Base { public override void Foo < T > ( ) { Console.WriteLine ( `` derived '' ) ; } public void Bang ( ) { Action bang = new Action ( delegate { base.Foo < string > ( ) ; } ) ; bang ( ) ; //VerificationException is thrown } } call instance void ConsoleApp.Derived : : ' < > n__FabricatedMethod1 ' < string > ( ) method private hidebysig instance void ' < > n__FabricatedMethod1 ' < T > ( ) cil managed { .custom instance void [ mscorlib ] System.Runtime.CompilerServices.CompilerGeneratedAttribute : :.ctor ( ) = ( 01 00 00 00 ) .maxstack 8 IL_0000 : ldarg.0 IL_0001 : call instance void ConsoleApp.Base : :Foo < ! ! T > ( ) IL_0006 : ret } Action good = new Action ( base.Foo < string > ( ) ) ; good ( ) ; //fine",Compiler generated incorrect code for anonymous methods [ MS BUG FIXED ] "C_sharp : I am running into a problem where I am unable to get nginx to work properly with gRPC . I am using .Net core 3.1 to server an API that supports both REST and gRPC.I am using below docker images : .Net Core 3.1 ( aspnet:3.1-alpine ) Nginx ( nginx : latest ) Client is running locally as I 'm just connecting via nginx to the docker container ( port 8080 and 443 mapped to host ) I have built the API image in a docker container and am using docker compose to spin everything up.My API is fairly straightforward when it comes to gRPC : I have nginx as a reverse proxy in front of my API and below is my nginx config . But the rpc calls do n't work . I ca n't connect to the gRPC service through a client and it returns a 502 request . I get a 2020/06/29 18:33:30 [ error ] 27 # 27 : *3 upstream sent too large http2 frame : 4740180 while reading response header from upstream , client : 172.20.0.1.. After adding separate kestral endpoints ( see my Edit1 below ) , I receive *1 upstream prematurely closed connection while reading response header from upstream when I look at Nginx logs.The actual request is never even received by the server as nothing is logged server side when i peek into the docker logs.There is little to no documentation on how to support gRPC through docker on .Net so unsure how to proceed . What needs to be configured/enabled further than what I have to get this working ? Note that the REST part of the API works fine without issues . Unsure if SSL needs to be carried all the way up to the upstream servers ( i.e . SSL at the API level at well ) .The documentation I 've seen on Nginx for gRPC has exactly what I have below . http_v2_module is enabled in Nginx and I can verify it works for the non gRPC part of the API through the response protocol.Edit1 : I 've also tried to spin up separate endpoints for REST/gRPC . From this piece of documentation , when insecure requests come in , its automatically assumed to be Http1 requests . I configured kestrel manually to have 2 separate endpoints , two ports - one for http1+http2 and other for http2 requests.In Nginx , I created a separate entries as well : This does not work either . I even tried upstream SSL via making the htt2 endpoint accept only ssl connections but no dice.Edit2I have also tried below : Upstream SSL in Nginx - i.e . SSL between backend and reverse proxyUsed Debian/Ubuntu based images instead of AlpineNone of them work either.Edit 3 : I was able to finally make this work : For whatever reason , the only configuration for nginx that works is using grpc_pass only . It 's not similar to proxy pass and the other configuration is not required . I am finally able to get this to work without having to do upstream SSL and just use the proxy like I meant to - terminate SSL at the proxy.I 'm still looking for a formal explanation otherwise I 'll mark my own solution as the answer as I have tested it successfully . app.UseEndpoints ( endpoints = > { endpoints.MapGrpcService < CartService > ( ) ; endpoints.MapControllers ( ) ; } ) ; http { upstream api { server apiserver:5001 ; } upstream function { server funcserver:5002 ; } # redirect all http requests to https server { listen 80 default_server ; listen [ : : ] :80 default_server ; return 301 https : // $ host $ request_uri ; } server { server_name api.localhost ; listen 443 http2 ssl ipv6only=on ; ssl_certificate /etc/certs/api.crt ; ssl_certificate_key /etc/certs/api.key ; location /CartCheckoutService/ValidateCartCheckout { grpc_pass grpc : //api ; proxy_buffer_size 512k ; proxy_buffers 4 256k ; proxy_busy_buffers_size 512k ; grpc_set_header Upgrade $ http_upgrade ; grpc_set_header Connection `` Upgrade '' ; grpc_set_header Connection keep-alive ; grpc_set_header Host $ host : $ server_port ; grpc_set_header X-Forwarded-For $ proxy_add_x_forwarded_for ; grpc_set_header X-Forwarded-Proto $ scheme ; } location / { proxy_pass http : //api ; proxy_http_version 1.1 ; proxy_set_header Upgrade $ http_upgrade ; proxy_set_header Connection `` Upgrade '' ; proxy_set_header Connection keep-alive ; proxy_set_header Host $ host : $ server_port ; proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for ; proxy_set_header X-Forwarded-Proto $ scheme ; proxy_cache_bypass $ http_upgrade ; } } server { server_name func.localhost ; listen 443 ssl ; ssl_certificate /etc/certs/func.crt ; ssl_certificate_key /etc/certs/func.key ; location / { proxy_pass http : //function ; proxy_http_version 1.1 ; proxy_set_header Upgrade $ http_upgrade ; proxy_set_header Connection keep-alive ; proxy_set_header Host $ host : $ server_port ; proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for ; proxy_set_header X-Forwarded-Proto $ scheme ; proxy_cache_bypass $ http_upgrade ; } } gzip on ; gzip_vary on ; gzip_proxied no-cache no-store private expired auth ; gzip_types text/plain text/css application/json application/xml ; } services.Configure < KestrelServerOptions > ( y = > { y.ListenAnyIP ( 5010 , o = > { o.Protocols = HttpProtocols.Http2 ; //o.UseHttps ( `` ./certs/backend.pfx '' , `` password1 '' ) ; } ) ; y.ListenAnyIP ( 5001 , o = > { o.Protocols = HttpProtocols.Http1AndHttp2 ; } ) ; } ) ; upstream api { server apiserver:5001 ; } upstream grpcservice { server apiserver:5010 ; } upstream function { server funcserver:5002 ; } location /CartCheckoutService/ValidateCartCheckout { grpc_pass grpc : //api ; }",How to enable nginx reverse proxy to work with gRPC in .Net core ? "C_sharp : In a WPF app I want to move a UserControl from a ContentControl to another one in code : in this case I get an error : Specified element is already the logical child of another element . Disconnect it first.In a ControlControl class description I can see a RemoveVisualChild method , but when I try to use it in code I get an Unknown method errorWhere am I wrong ? How to move a UserControl from a ContentControl to another one in code-behind ? myContentControl2.Content = myUserControl ; myContentControl1.RemoveVisualChild ( myUserControl ) ; //here I get an `` Unknown method '' error",Move a UserControl from a ContentControl to another one programmatically "C_sharp : I am trying to join two tables by first converting a comma separated values from a column `` SupplierId '' which I am doing successfully.However , the issue comes in when I try joining to another table 'Vendors ' with the Supplier names via a foreign key 'DCLink'.This is what I mean : The select statement for the Original Table , Gives this resultI am able to split the columns from SupplierId using this sql statementand get these resultsWhen I apply this bit of code to join the InquiryDetails table to the Vendor Table on supplier Name however , It gives me this very inconvenient result : I would wish for the join statement to show and flow as the original select statement.I am stuck and I can not seem to figure out where I am going wrong.Any pointers in the right direction ? SELECT InquiryId , SupplierId FROM Procure_InquiryDetails InquiryId SupplierId1 2,32 1753 170,2805 7 128 5,9 ; WITH CTE AS ( SELECT InquiryId , [ xml_val ] = CAST ( ' < t > ' + REPLACE ( SupplierId , ' , ' , ' < /t > < t > ' ) + ' < /t > ' AS XML ) FROM Procure_InquiryDetails ) SELECT InquiryId , [ SupplierId ] = col.value ( ' . ' , 'VARCHAR ( 100 ) ' ) FROM CTECROSS APPLY [ xml_val ] .nodes ( '/t ' ) CA ( col ) InquiryId SupplierId 1 2 1 3 2 175 3 170 3 280 5 7 12 8 5 8 9 ; WITH CTEAS ( SELECT InquiryId , [ xml_val ] = CAST ( ' < t > ' + REPLACE ( SupplierId , ' , ' , ' < /t > < t > ' ) + ' < /t > ' AS XML ) , Vendor.Name FROM Procure_InquiryDetails inner join Vendor on ' , ' + Procure_InquiryDetails.SupplierId + ' , ' like ' % , ' + cast ( Vendor.DCLink as nvarchar ( 20 ) ) + ' , % ' ) SELECT InquiryId , Name , [ SupplierId ] = col.value ( ' . ' , 'VARCHAR ( 100 ) ' ) FROM CTECROSS APPLY [ xml_val ] .nodes ( '/t ' ) CA ( col ) InquiryId Name SupplierId -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1 Accesskenya Group Ltd 21 Accesskenya Group Ltd 31 Aquisana Ltd 21 Aquisana Ltd 32 TOYOTA KENYA 1753 Institute of Chartered Shipbrokers ICS-USD 1703 Institute of Chartered Shipbrokers ICS-USD 2807 CMA CGM Kenya Ltd 128 Aon Kenya Insurance Brokers Ltd 58 Aon Kenya Insurance Brokers Ltd 98 Bill investments ltd 58 Bill investments ltd",How to join comma separated column values with another table as rows "C_sharp : Procedure I 'm going to:1 . Get a OrgUnit from the Google Directory API 2 . Read the OrgUnit and collect the required Data 3 . Try to delete the OrgUnit I just collected . This somehow results in a 404 [ Not Found ] Error Please keep in mind that the DirectoryService Class I am using , is working properly . I modified the code in this example to make it easy to read , for example : Exception handling is not included etc.The API1 . Get a OrgUnit from the Google Directory API2.Read the OrgUnit and collect the required Data3.Try to delete the OrgUnit I just collectedThe Exception GoogleApiException was unhandledAn unhandled exception of type 'Google.GoogleApiException ' occurred in Google.Apis.dll Additional information : Google.Apis.Requests.RequestError Org unit not found [ 404 ] using Google.Apis.Admin.Directory.directory_v1 DirectoryService directoryService = ServiceInitializers.InitializeDirectoryService ( ) ; OrgUnit oUnit = directoryService.Orgunits.List ( Settings.customerId ) .Execute ( ) .OrganizationUnits.FirstOrDefault ( ) ; string orgUnitPath = oUnit.OrgUnitPath ; var orgUnitDeleteResult = directoryService.Orgunits.Delete ( Settings.customerId , orgUnitPath ) .Execute ( ) ;",OrgUnit Not Found using Google Directory API "C_sharp : Consider the following code : ( ignore the class design ; I 'm not actually writing a calculator ! this code merely represents a minimal repro for a much bigger problem that took awhile to narrow down ) I would expect it to either : print `` 16 '' , ORthrow a compile time error if closing over a member field is not allowed in this scenarioInstead I get a nonsensical exception thrown at the indicated line . On the 3.0 CLR it 's a NullReferenceException ; on the Silverlight CLR it 's the infamous Operation could destabilize the runtime . using System ; namespace ConsoleApplication2 { class Program { static void Main ( string [ ] args ) { var square = new Square ( 4 ) ; Console.WriteLine ( square.Calculate ( ) ) ; } } class MathOp { protected MathOp ( Func < int > calc ) { _calc = calc ; } public int Calculate ( ) { return _calc ( ) ; } private Func < int > _calc ; } class Square : MathOp { public Square ( int operand ) : base ( ( ) = > _operand * _operand ) // runtime exception { _operand = operand ; } private int _operand ; } }",C # - closures over class fields inside an initializer ? "C_sharp : UI Image upload part is not working , I want to upload image path in Database but not working , and not bind correctly ca n't save it , can you please help me , Table to displayed upload image value is always FALSE ASPXCODEfull aspx gvArticle_rowdatabound < asp : TemplateField HeaderText= '' Images '' > < ItemTemplate > < asp : FileUpload runat= '' server '' AutoPostBack= '' True '' ID= '' fileupload '' CommandArgument= ' < % # Eval ( `` strImage '' ) % > ' ClientIDMode= '' Static '' / > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' '' > < ItemTemplate > < asp : Image ImageUrl= '' ~/Uploaded Images/Default.png '' runat= '' server '' ID= '' image '' Width= '' 40 '' Height= '' 40 '' / > < /ItemTemplate > < /asp : TemplateField > # region Detail Save1 private DataTable CreateDetailSave ( ) { DataTable dtDetailSave1 = new DataTable ( ) ; DataColumn dc1 ; dc1 = new DataColumn ( `` intArticleDetailId '' ) ; dtDetailSave1.Columns.Add ( dc1 ) ; dc1 = new DataColumn ( `` intSectionId '' ) ; dtDetailSave1.Columns.Add ( dc1 ) ; dc1 = new DataColumn ( `` intCompoundId '' ) ; dtDetailSave1.Columns.Add ( dc1 ) ; dc1 = new DataColumn ( `` decSectionWeight '' ) ; dtDetailSave1.Columns.Add ( dc1 ) ; dc1 = new DataColumn ( `` intMessageId '' ) ; dtDetailSave1.Columns.Add ( dc1 ) ; dc1 = new DataColumn ( `` strImage '' ) ; dtDetailSave1.Columns.Add ( dc1 ) ; foreach ( GridViewRow row in gvArticle.Rows ) { DataRow dr = dtDetailSave1.NewRow ( ) ; Label lblintArticleDetailId = ( Label ) row.FindControl ( `` lblArticleDetailId '' ) ; Label lblSectionId = ( Label ) row.FindControl ( `` lblSectionId '' ) ; DropDownList ddlCompound = ( DropDownList ) row.FindControl ( `` ddlCompoundId '' ) ; TextBox txtdecSectionWeighte = ( TextBox ) row.FindControl ( `` txtdecSectionWeighte '' ) ; DropDownList intMessage = ( DropDownList ) row.FindControl ( `` ddlMessage '' ) ; FileUpload fileupload = ( FileUpload ) row.FindControl ( `` fileupload '' ) ; dr [ `` intArticleDetailId '' ] = CurrentMode == `` Add '' ? -1 : Convert.ToInt32 ( lblintArticleDetailId.Text ) ; dr [ `` intSectionId '' ] = Convert.ToInt32 ( lblSectionId.Text ) ; dr [ `` intCompoundId '' ] = ddlCompound.SelectedValue ; dr [ `` decSectionWeight '' ] = txtdecSectionWeighte.Text.Trim ( ) ! = `` '' ? Convert.ToDecimal ( txtdecSectionWeighte.Text.Trim ( ) ) : 0 ; dr [ `` intMessageId '' ] = intMessage.SelectedValue ; dr [ `` strImage '' ] = fileupload.HasFile ; dtDetailSave1.Rows.Add ( dr ) ; } return dtDetailSave1 ; } # endregion # region pageload protected void Page_Load ( object sender , EventArgs e ) { if ( ! IsPostBack ) { ClearControls ( ) ; FillArticleDetails ( ) ; EnableControls ( false ) ; Session [ `` SearchPopup '' ] = false ; } else { if ( Session [ `` SearchPopup '' ] ! = null ) { SearchPopup = ( bool ) ( Session [ `` SearchPopup '' ] ) ; if ( SearchPopup ! = false ) { MyMPE.Show ( ) ; } else { MyMPE.Hide ( ) ; } } vAdSearchParaList = new List < SearchParametors > ( ) ; } } # endregion # region Create Article table private void createArticleDataTable ( ) { if ( dt.Columns.Count == 0 ) { dt.Columns.Add ( new DataColumn ( `` intArticleDetailId '' , typeof ( int ) ) ) ; dt.Columns.Add ( new DataColumn ( `` intSectionId '' , typeof ( int ) ) ) ; dt.Columns.Add ( new DataColumn ( `` strSectionName '' , typeof ( string ) ) ) ; dt.Columns.Add ( new DataColumn ( `` intCompoundId '' , typeof ( string ) ) ) ; dt.Columns.Add ( new DataColumn ( `` decSectionWeight '' , typeof ( string ) ) ) ; dt.Columns.Add ( new DataColumn ( `` intMessageId '' , typeof ( string ) ) ) ; dt.Columns.Add ( new DataColumn ( `` fileupload '' , typeof ( string ) ) ) ; } gvArticle.DataSource = dt ; gvArticle.DataBind ( ) ; } # endregion # region Compound Grid - Add empty row private void ArticleGridAddEmptyRow ( int newId ) { DataRow newDr = null ; newDr = dt.NewRow ( ) ; newDr [ `` intArticleDetailId '' ] = 1 ; newDr [ `` intSectionId '' ] = 1 ; newDr [ `` strSectionName '' ] = `` '' ; newDr [ `` intCompoundId '' ] = `` '' ; newDr [ `` decSectionWeight '' ] = `` '' ; newDr [ `` intMessageId '' ] = `` '' ; newDr [ `` strImage '' ] = `` '' ; dt.Rows.Add ( newDr ) ; if ( dtArticleDetails == null || dtArticleDetails.Rows.Count == 0 ) { dtArticleDetails = dt ; } else { dtArticleDetails.Merge ( dt ) ; gvArticle.DataSource = dt ; gvArticle.DataBind ( ) ; } } # endregionprotected void gvArticle_RowUpdating ( object sender , GridViewUpdateEventArgs e ) { GridViewRow row = gvArticle.Rows [ e.RowIndex ] ; FileUpload fu = row.Cells [ 0 ] .FindControl ( `` strImage '' ) as FileUpload ; if ( fu ! = null & & fu.HasFile ) { fu.SaveAs ( Server.MapPath ( `` ~/Uploaded Images '' + fu.FileName ) ) ; } } < asp : GridView ID= '' gvArticle '' ShowHeaderWhenEmpty= '' True '' CssClass= '' table table-bordered table-condensed table-hover '' AutoGenerateColumns= '' False '' runat= '' server '' AllowPaging= '' True '' PageSize= '' 15 '' OnRowDataBound= '' gvArticle_RowDataBound '' BackColor= '' White '' BorderColor= '' # CCCCCC '' BorderStyle= '' None '' BorderWidth= '' 1px '' CellPadding= '' 4 '' ForeColor= '' Black '' GridLines= '' Horizontal '' OnRowUpdating= '' gvArticle_RowUpdating '' > < % -- < HeaderStyle BackColor= '' # 3d4247 '' ForeColor= '' White '' / > -- % > < Columns > < asp : TemplateField HeaderText= '' intArticleDetail '' Visible= '' false '' > < ItemTemplate > < asp : Label ID= '' lblArticleDetailId '' Width= '' 2 '' Text= ' < % # Bind ( `` intArticleDetailId '' ) % > ' ClientIDMode= '' Static '' runat= '' server '' > < /asp : Label > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' SectionID '' Visible= '' false '' > < ItemTemplate > < asp : Label ID= '' lblSectionId '' Width= '' 2 '' Text= ' < % # Bind ( `` intSectionId '' ) % > ' ClientIDMode= '' Static '' runat= '' server '' > < /asp : Label > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' Section '' > < ItemTemplate > < asp : Label ID= '' lblSectionName '' Width= '' 100 '' Text= ' < % # Bind ( `` strSectionName '' ) % > ' ClientIDMode= '' Static '' runat= '' server '' > < /asp : Label > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' Compound '' > < EditItemTemplate > < asp : Label ID= '' lblItemTypeEdit '' Width= '' 50 '' Text= ' < % # Bind ( `` strCompoundName '' ) % > ' lientIDMode= '' Static '' AutoPostBack= '' true '' runat= '' server '' > < /asp : Label > < /EditItemTemplate > < ItemTemplate > < asp : DropDownList ID= '' ddlCompoundId '' Width= '' 200 '' CssClass= '' form-control my-DropDownThin '' lientIDMode= '' Static '' AutoPostBack= '' true '' runat= '' server '' > < /asp : DropDownList > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' Weight '' > < ItemTemplate > < asp : TextBox ID= '' txtdecSectionWeighte '' Width= '' 100 % '' Text= ' < % # Bind ( `` decSectionWeight '' ) % > ' lientIDMode= '' Static '' runat= '' server '' > < /asp : TextBox > < /ItemTemplate > < /asp : TemplateField > < % -- < asp : TemplateField HeaderText= '' Messagers '' > < ItemTemplate > < asp : TextBox ID= '' txtMessage '' Width= '' 100 % '' Text= ' < % # Bind ( `` intMessageId '' ) % > ' ClientIDMode= '' Static '' runat= '' server '' > < /asp : TextBox > < /ItemTemplate > < /asp : TemplateField > -- % > < asp : TemplateField HeaderText= '' Messagers '' > < EditItemTemplate > < asp : Label ID= '' lblMessageId '' Width= '' 50 '' Text= ' < % # Bind ( `` strMessage '' ) % > ' ClientIDMode= '' Static '' AutoPostBack= '' true '' runat= '' server '' > < /asp : Label > < /EditItemTemplate > < ItemTemplate > < asp : DropDownList ID= '' ddlMessage '' Width= '' 300 '' CssClass= '' form-control my-DropDownThin '' lientIDMode= '' Static '' AutoPostBack= '' true '' runat= '' server '' > < /asp : DropDownList > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' Images '' > < ItemTemplate > < asp : FileUpload runat= '' server '' AutoPostBack= '' True '' ID= '' uploadFImage '' CommandArgument= ' < % # Eval ( `` strImage '' ) % > ' ClientIDMode= '' Static '' / > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField HeaderText= '' '' > < ItemTemplate > < asp : Image ImageUrl= '' ~/Uploaded Images/Default.png '' runat= '' server '' ID= '' btnViewFImage '' Width= '' 40 '' Height= '' 40 '' / > < /ItemTemplate > < /asp : TemplateField > < /Columns > < FooterStyle BackColor= '' # CCCC99 '' ForeColor= '' Black '' / > < HeaderStyle BackColor= '' # 333333 '' Font-Bold= '' True '' ForeColor= '' White '' / > < PagerStyle BackColor= '' White '' ForeColor= '' Black '' HorizontalAlign= '' Right '' / > < SelectedRowStyle BackColor= '' # CC3333 '' Font-Bold= '' True '' ForeColor= '' White '' / > < SortedAscendingCellStyle BackColor= '' # F7F7F7 '' / > < SortedAscendingHeaderStyle BackColor= '' # 4B4B4B '' / > < SortedDescendingCellStyle BackColor= '' # E5E5E5 '' / > < SortedDescendingHeaderStyle BackColor= '' # 242121 '' / > < /asp : GridView > < /div > < /ContentTemplate > < Triggers > < asp : PostBackTrigger ControlID= '' gvArticle '' / > < /Triggers > < /asp : UpdatePanel > < /div > < /div > protected void gvArticle_RowDataBound ( object sender , GridViewRowEventArgs e ) { if ( e.Row.RowType == DataControlRowType.Footer ) { } else if ( e.Row.RowType == DataControlRowType.DataRow ) { { } DataTable CompoundCode = clsArticle.CompoundDataForGrid ( `` '' ) ; DropDownList ddlCompoundId = ( DropDownList ) e.Row.FindControl ( `` ddlCompoundId '' ) ; if ( ddlCompoundId ! = null ) { ddlCompoundId.DataTextField = `` Compound Code '' ; ddlCompoundId.DataValueField = `` Compound Id '' ; ddlCompoundId.DataSource = CompoundCode ; ddlCompoundId.DataBind ( ) ; string country = ( e.Row.FindControl ( `` ddlCompoundId '' ) as DropDownList ) .Text ; ddlCompoundId.Items.FindByValue ( country ) .Selected = true ; } DataTable MsgCode = clsArticle.MessageDataForGrid ( `` '' ) ; DropDownList ddlMessage = ( DropDownList ) e.Row.FindControl ( `` ddlMessage '' ) ; if ( ddlMessage ! = null ) { ddlMessage.DataTextField = `` Message Name '' ; ddlMessage.DataValueField = `` Message Id '' ; ddlMessage.DataSource = MsgCode ; ddlMessage.DataBind ( ) ; ddlMessage.Items.Insert ( 0 , new ListItem ( `` Please select '' ) ) ; string country = ( e.Row.FindControl ( `` ddlMessage '' ) as DropDownList ) .Text ; ddlMessage.Items.FindByValue ( country ) .Selected = true ; } // } } }",Image upload not working Always get the FALSE value "C_sharp : ProblemI 'm trying to find a flexible way to parse email content . Below is an example of dummy email text I 'm working with . I 'd also like to avoid regular expressions if at all possible . However , at this point of my problem solving process I 'm beginning to think it 's inevitable . Note that this is only a small dummy subset of a full email . What I need is to parse every field ( e.g . Ticket No , Cell Phone ) into their respective data types . Lastly , some fields are not guaranteed to be present in the email ( you 'll see in my current solution shown below why this is a problem ) .Current SolutionFor this simple example I 'm successfully able to parse most fields with the function below.Essentially , my idea was that I could parse the content between two fields . For example , I could the header code by doingThis approach however has many flaws . One big flaw being that the end field is not always present . As you can see there are some similar keys with identical keywords that do n't parse quite right , such as `` Contact '' and `` Secondary Contact '' . This causes the parser to fetch too much information . Also , if my end field is not present I 'll be getting some unpredictable result . Lastly , I can parse entire lines to then pass it to BetweenOperation < T > using this.We would use LineOperation in some cases where the field name is not unique ( e.g . Time ) and feed the result to BetweenOperation < T > .QuestionHow can parse the content shown above based on keys . Keys being `` Header Code '' and `` Cell Phone '' for example . Note that I do n't think that parsing based on spaces of tabs because some of fields can be several lines long ( e.g . Caller Address ) or contain no value at all ( e.g . Altern Phone ) .Thank you . Header Code : EMERGENCY Ticket No : 123456789 Seq . No : 2Update of : Original Call Date : 01/02/2011 Time : 11:17:03 AM OP : 1102Second Call Date : 01/02/2011 Time : 12:11:00 AM OP : Company : COMPANY NAMEContact : CONTACT NAME Contact Phone : ( 111 ) 111-1111Secondary Contact : SECONDARY CONTACTAlternate Contact : Altern . Phone : Best Time to Call : AFTER 4:30P Fax No : ( 111 ) 111-1111Cell Phone : Pager No : Caller Address : 330 FOO FOO AVENUE 123 private T BetweenOperation < T > ( string emailBody , string start , string end ) { var culture = StringComparison.InvariantCulture ; int startIndex = emailBody.IndexOf ( start , culture ) + start.Length ; int endIndex = emailBody.IndexOf ( end , culture ) ; int length = endIndex - startIndex ; if ( length < 0 ) return default ( T ) ; return ( T ) Convert.ChangeType ( emailBody.Substring ( startIndex , length ) .Trim ( ) , typeof ( T ) ) ; } // returns `` EMERGENCY '' BetweenOperation < string > ( `` email content '' , `` Header Code : '' , `` Ticket No : '' ) private string LineOperation ( string startWithCriteria ) { string [ ] emailLines = EmailBody.Split ( new [ ] { '\n ' } ) ; return emailLines.Where ( emailLine = > emailLine.StartsWith ( startWithCriteria ) ) .FirstOrDefault ( ) ; }",Flexible text parsing strategies "C_sharp : I have the following HAL+JSON sample : And the following models : Now , because of the _embbeded , I ca n't do an out-of-the-box serialization with Newtonsoft.Json , because then Company will be null ; I was hoping to see a native hal+json support by Json.NET , but it only has one recommendation to use a custom JsonConverter . I started to create a custom one by myself , but feels like `` reinventing the wheel '' for me.So , anyone knows a smart way to get out with this ? UPDATE : It 's important to not change the models/classes . I can add attributes , but never change it 's structures . { `` id '' : `` 4a17d6fe-a617-4cf8-a850-0fb6bc8576fd '' , `` country '' : `` DE '' , `` _embedded '' : { `` company '' : { `` name '' : `` Apple '' , `` industrySector '' : `` IT '' , `` owner '' : `` Klaus Kleber '' , `` _embedded '' : { `` emailAddresses '' : [ { `` id '' : `` 4a17d6fe-a617-4cf8-a850-0fb6bc8576fd '' , `` value '' : `` test2 @ consoto.com '' , `` type '' : `` Business '' , `` _links '' : { `` self '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } } } ] , `` phoneNumbers '' : [ { `` id '' : `` 4a17d6fe-a617-4cf8-a850-0fb6bc8576fd '' , `` value '' : `` 01670000000 '' , `` type '' : `` Business '' , `` _links '' : { `` self '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } } } ] , } , `` _links '' : { `` self '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } , `` phoneNumbers '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } , `` addresses '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } , } } , } , `` _links '' : { `` self '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } , `` legalPerson '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } , `` naturalPerson '' : { `` href '' : `` https : //any-host.com/api/v1/customers/1234 '' } } } public class Customer { public Guid Id { get ; set ; } public string Country { get ; set ; } public LegalPerson Company { get ; set ; } } public class LegalPerson { public string Name { get ; set ; } public string IndustrySector { get ; set ; } public string Owner { get ; set ; } public ContactInfo [ ] EmailAddresses { get ; set ; } public ContactInfo [ ] PhoneNumbers { get ; set ; } } public class ContactInfo { public Guid Id { get ; set ; } public string Type { get ; set ; } public string Value { get ; set ; } }",Deserialize hal+json to complex model "C_sharp : In ASP.NET Core 2.2 , I could set UseWebRoot ( ) like : But I do not know how I should do it today because there is no such method anymore . public static void Main ( string [ ] args ) { CreateWebHostBuilder ( args ) .UseUrls ( `` http : //*:5000 '' ) .UseWebRoot ( @ '' .\WebSite\wwwroot\ '' ) .Build ( ) .Run ( ) ; }",How to call UseWebRoot in ASP.NET Core 3.0 C_sharp : Let 's say I have a classThese methods do the same thing but one is static and one isn't.When i call these method I do this : and Which method is the best to use for performance etc ? public class product { public string GetName ( ) { return `` product '' ; } public static string GetStaticName ( ) { return `` product '' ; } } product p = new product ( ) ; string _ProductName = p.GetName ( ) ; string _ProductName = product.GetStaticName ( ) ;,Instantiate a class to call a method or use static methods ? "C_sharp : Righ now I have this that works , but its ugly and long : Is there a better way to do this ? I tried `` it.isDeleted ! = true '' and `` it.isDeleted ? ? false == false '' but they are not working . var details = dc.SunriseShipment .Where ( it = > ( it.isDeleted == null || it.isDeleted == false ) ) ;",How to check if nullable boolean is not true ? "C_sharp : what is the best practice to overload == operator that compares two instances of the same class when it comes to null reference comparison ? What is the best approach to handle null references in comparison ? MyObject o1 = null ; MyObject o2 = null ; if ( o1 == o2 ) ... static bool operator == ( MyClass o1 , MyClass o2 ) { // ooops ! this way leads toward recursion with stackoverflow as the result if ( o1 == null & & o2 == null ) return true ; // it works ! if ( Equals ( o1 , null ) & & Equals ( o2 , null ) ) return true ; ... }",C # : best practice to overload == operator when it comes to null references "C_sharp : I have a ( growing ) list of Data-Generators . The generator that I need is created by a factory class . The generators all implement a common Interface , which includes among other things a static string name.What I would like to do : Call the factory.Create method with a string parameter for the above mentioned name . The create method finds the generator with this name and returns a new instance of said generator.Bonus in my opinion of this way to do it : I only have to add new generator classes without having to edit the factory.Question : Is this a good way to handle this problem ? How can I find all generators ? Reflection over every implementation of the interface/every member of the namespace ( unique for the generators + their interface ) ? Is it correct to call this way of working a factory , or is this some different pattern ? In the end I would call the factory like this ( simplified ) : Should the magic GetImplementations ( ) in the factory be done via Reflection or somehow different ? Should I use a completely different approach ? Since answers refer to IoC and DI : This project uses NInject already , so it would be available.Switched from interface to abstract class . //Callerpublic DataModel GetData2 ( ) { var generator = new DataFactory ( ) .Create ( `` Gen.2 '' ) ; return generator.GetData ( ) ; } //Factorypublic class DataFactory { public AbstractDataGenerator Create ( string type ) { //Here the magic happens to find all implementations of IDataGenerator var allGenerators = GetImplementations ( ) ; var generator = allGenerators.FirstOrDefault ( f = > f.name == type ) ; if ( generator ! = null ) return ( AbstractDataGenerator ) Activator.CreateInstance ( generator ) ; else return null ; } } //Interfacepublic abstract class AbstractDataGenerator { public static string name ; public abstract DataModel GetData ( ) ; } //Data-Generatorspublic class DataGen1 : AbstractDataGenerator { public static string name = `` Gen.1 '' ; public DataModel GetData ( ) { return new DataModel ( `` 1 '' ) ; } } public class DataGen2 : AbstractDataGenerator { public static string name = `` Gen.2 '' ; public DataModel GetData ( ) { return new DataModel ( `` 2 '' ) ; } }","Factory Pattern , selecting by Property" "C_sharp : I intend to have one core module exposing interfaces so that other big modules ( different clients ) will communicate with . If , say , there are group of methods : to expose to one type of clients ( module `` X1 '' ) and : to expose to other type of clients ( module `` X2 '' ) and knowing that Method_A and Method_B should have the exact implementation ... then how can I best design the service ( s ) architecture ( in terms of services and contracts ) ? Is there any chance to implement Method_A and Method_B only once ( not 2 times in different contract implementations ) ? How shall I benefit of interface inheritance when using WCF ? Thank you all in advance and please let me know if I need to make it more clear ! @ marc_s ... I would really appreciate your point of view ... void Method_A ( ) ; void Method_B ( ) ; void Method_X1 ( ) ; void Method_A ( ) ; void Method_B ( ) ; void Method_X2 ( ) ;",WCF - looking for best practice when having multiple contracts sharing common methods "C_sharp : I 'm setting up a way to communicate between a server and a client . How I am working it at the moment , is that a stream 's first byte will contain an indicator of what is coming and then looking up that request 's class I can determine the length of the request : I 'm curious how to handle the case of when the class size is not known , of if after reading a known request the data is corrupt.I 'm thinking that I can insert in some sort of delimiter into the stream , but since a byte can only be between 0-255 , I 'm not sure how to go about creating a unique delimiter . Do I want to place a pattern into the stream to represent the end of a message ? How can I be sure that this pattern is unique enough to not be mistaken for actual data ? stream.Read ( message , 0 , 1 ) if ( message == < byte representation of a known class > ) { stream.Read ( message , 0 , Class.RequestSize ) ; }",How to place a delimiter in a NetworkStream byte array ? "C_sharp : When calling DoStuffToDictionary ( dictionaryTwo ) , is it safe to assume the operations within the method body including indexers , and LINQ extension methods will also be thread safe ? To phrase this question differently , could a cross thread exception or deadlock arise ? var dictionaryOne = new ConcurrentDictionary < int , int > ( ) ; var dictionaryTwo = new Dictionary < int , int > ( ) ; DoStuffToDictionary ( dictionaryOne ) ; DoStuffToDictionary ( dictionaryTwo ) ; void DoStuffToDictionary ( IDictionary < int , int > items ) { // Manipulate dictionary if ( items [ 0 ] == -1 ) { items [ 0 ] = 0 ; // Dumb example , but are indexers like this OK ? } }",Are the IDictionary members implemented in ConcurrentDictionary thread safe ? "C_sharp : I have read at different places people saying one should always use lock instead of volatile . I found that there are lots of confusing statements about Multithreading out there and even experts have different opinions on some things here.After lots of research I found that the lock statement also will insert MemoryBarriers at least.For example : But if I am not totally wrong , the JIT compiler is free to never actually read the variable inside the loop but instead it may only read a cached version of the variable from a register . AFAIK MemoryBarriers wo n't help if the JIT made a register assignment to a variable , it just ensures that if we read from memory that the value is current.Unless there is some compiler magic saying something like `` if a code block contains a MemoryBarrier , register assignment of all variables after the MemoryBarrier is prevented '' .Unless declared volatile or read with Thread.VolatileRead ( ) , if myBool is set from another Thread to false , the loop may still run infinite , is this correct ? If yes , would n't this apply to ALL variables shared between Threads ? public bool stopFlag ; void Foo ( ) { lock ( myLock ) { while ( ! stopFlag ) { // do something } } }",Is volatile still needed inside lock statements ? "C_sharp : https : //github.com/apache/log4netI am compiling log4net from the source above , but it does n't pass verification : [ IL ] : Error : [ log4net.dll : log4net.Plugin.RemoteLoggingServerPlugin : :Attach ] [ offset 0x00000029 ] Method is not visible.Code is ok : https : //github.com/apache/log4net/blob/trunk/src/Plugin/IPlugin.cshttps : //github.com/apache/log4net/blob/trunk/src/Plugin/PluginSkeleton.cshttps : //github.com/apache/log4net/blob/trunk/src/Plugin/RemoteLoggingServerPlugin.csInvestigation shows that it fails in calling RemotingServices.Marshal ( ) : But there is nothing crucial here . Moreover calling RemotingServices.Marshal ( ) with any type leads to the same problems : Even if I change the Attach ( ) to this : Can someone spot what is the problem ? public interface ILoggerRepository { ... } public interface IPlugin { void Attach ( ILoggerRepository repository ) ; } public abstract class PluginSkeleton : IPlugin { public virtual void Attach ( ILoggerRepository repository ) { } } public class RemoteLoggingServerPlugin : PluginSkeleton { override public void Attach ( ILoggerRepository repository ) { base.Attach ( repository ) ; ... } } override public void Attach ( ILoggerRepository repository ) { base.Attach ( repository ) ; // Create the sink and marshal it m_sink = new RemoteLoggingSinkImpl ( repository ) ; try { **RemotingServices.Marshal ( m_sink , m_sinkUri , typeof ( IRemoteLoggingSink ) ) ; ** } catch ( Exception ex ) { LogLog.Error ( declaringType , `` Failed to Marshal remoting sink '' , ex ) ; } } override public void Attach ( ILoggerRepository repository ) { RemotingServices.Marshal ( null , null , typeof ( int ) ) ; }",log4net does n't pass verification when compiling "C_sharp : Suppose that my Foo class has the following : So far , I have one unit test for the constructor where I pass in null to verify that an ArgumentNullException gets thrown . Do I need a second unit test for my constructor where I pass in a valid IService and verify that this.service gets set ( which would require a public accessor ) ? Or should I just rely on my unit test for the Start method to test this code path ? readonly IService service ; public Foo ( IService service ) { if ( service == null ) throw new ArgumentNullException ( `` service '' ) ; this.service = service ; } public void Start ( ) { service.DoStuff ( ) ; }",Unit testing constructor injection "C_sharp : Can someone please explain why the following program runs out of memory ? To be fair , the specific exception I get is a System.ComponentModel.Win32Exception , `` Not enough storage is available to process this command . '' The exception happens on the attempt to create a new MediaPlayer.MediaPlayer does not implement the IDisposable interface so I 'm not sure if there is other cleanup necessary . I certainly did n't find any in the MediaPlayer documentation . class Program { private static void ThreadRoutine ( ) { System.Windows.Media.MediaPlayer player = new System.Windows.Media.MediaPlayer ( ) ; } static void Main ( string [ ] args ) { Thread aThread ; int iteration = 1 ; while ( true ) { aThread = new Thread ( ThreadRoutine ) ; aThread.Start ( ) ; aThread.Join ( ) ; Console.WriteLine ( `` Iteration : `` + iteration++ ) ; } } }",Memory leak in MediaPlayer "C_sharp : Using .NET 4.0 I can quickly convert a struct to and from an array of bytes by making use of the Marshal class . For example , the following simple example will run at around 1 million times per second on my machine which is fast enough for my purposes ... But the Marshal class is not available under WinRT , which is reasonable enough for security reasons , but it means I need another way to achieve my struct to/from byte array . I am looking for an approach that works for any fixed size struct . I could solve the problem by writing custom code for each struct that knows how to convert that particular struct to and form a byte array but that is rather tedious and I can not help but feel there is some generic solution . [ StructLayout ( LayoutKind.Sequential ) ] public struct ExampleStruct { int i1 ; int i2 ; } public byte [ ] StructToBytes ( ) { ExampleStruct inst = new ExampleStruct ( ) ; int len = Marshal.SizeOf ( inst ) ; byte [ ] arr = new byte [ len ] ; IntPtr ptr = Marshal.AllocHGlobal ( len ) ; Marshal.StructureToPtr ( inst , ptr , true ) ; Marshal.Copy ( ptr , arr , 0 , len ) ; Marshal.FreeHGlobal ( ptr ) ; return arr ; }",WinRT and persisting struct to and from an array of bytes ? "C_sharp : I have an issue where a simple Rhino Mock stub method will work perfectly fine when I run a unit test , but will throw the exception Ca n't create mocks of sealed classes when executed in debug mode . I 've tried replacing the Do with a Return method , but that has n't changed the behaviour.Using C # with Rhino Mocks 3.6 , apologies for offending anyone by making an Add function subtract in a unit test ; ) InterfaceClassesUnit Test public interface ICalculator { int Add ( int value , int value2 ) ; } public class Calculator : ICalculator { public int Add ( int value , int value2 ) { return value + value2 ; } } public class Sums { private ICalculator calculator ; public Sums ( ICalculator calculatorArg ) { calculator = calculatorArg ; } public int Add ( int value , int value2 ) { return calculator.Add ( value , value2 ) ; } } [ TestMethod ( ) ] public void AddTest ( ) { //ARRANGE var calculatorArg = MockRepository.GenerateMock < ICalculator > ( ) ; Func < int , int , int > subtract = delegate ( int valueArg , int value2Arg ) { return valueArg - value2Arg ; } ; calculatorArg.Stub ( x = > x.Add ( -1 , -1 ) ) .IgnoreArguments ( ) .Do ( subtract ) ; Sums target = new Sums ( calculatorArg ) ; int value = 5 ; int value2 = 3 ; int expected = 2 ; //ACT int actual = target.Add ( value , value2 ) ; //ASSERT Assert.AreEqual ( expected , actual ) ; }",Rhino Mocks exhibits different behaviour in debug mode C_sharp : Why are we able to writeinstead of What is the difference between the two ? public int RetInt { get ; set ; } public int RetInt { get { return someInt ; } set { someInt=value ; } },properties in C # "C_sharp : I have a simple Window with button and second Window is opened when I click on the Button . Second Window has a Image control , which displays a .png-file . So if I use FileObject property for Binding all is OK , I can delete file from File Explorer . But if I use FileName property for Binding I can not delete file from File Explorer , I get OS exception . I can not do this even if I close second window , even if I invoke GC explicitly.What is the problem with FileName property ? Any ideas ? Win 7 , Net 4.0Window1Window2 < Grid > < Button Content= '' Ok '' Width= '' 100 '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Center '' Click= '' Click '' Padding= '' 0,2,0,2 '' IsDefault= '' True '' Name= '' _btnOk '' / > < /Grid > public partial class Window : Window { public Window ( ) { InitializeComponent ( ) ; DataContext = this ; } private void Click ( Object sender , RoutedEventArgs e ) { var window = new Window3 ( ) ; window.ShowDialog ( ) ; } } < Grid > < Image Source= '' { Binding FileObject } '' > < /Image > < /Grid > public partial class Window2 : Window { public Window2 ( ) { InitializeComponent ( ) ; DataContext = this ; FileName = `` D : /pdf/myfile.png '' ; Closing += Window2_Closing ; } public String FileName { get ; set ; } public Object FileObject { get { if ( String.IsNullOrEmpty ( FileName ) ) return null ; if ( ! File.Exists ( FileName ) ) return null ; var ms = new MemoryStream ( ) ; var bi = new BitmapImage ( ) ; using ( var fs = new FileStream ( FileName , FileMode.Open , FileAccess.Read ) ) { fs.CopyTo ( ms ) ; bi.BeginInit ( ) ; bi.StreamSource = ms ; bi.EndInit ( ) ; } return bi ; } } void Window2_Closing ( Object sender , System.ComponentModel.CancelEventArgs e ) { GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; } }",Wpf Image Control blocks the file "C_sharp : Let 's say I have two sequences returning integers 1 to 5.The first returns 1 , 2 and 3 very fast , but 4 and 5 take 200ms each.The second returns 1 , 2 and 3 with a 200ms delay , but 4 and 5 are returned fast.Unioning both these sequences give me just numbers 1 to 5.I can not guarantee which of the two methods has delays at what point , so the order of the execution can not guarantee a solution for me . Therefore , I would like to parallelise the union , in order to minimise the ( artifical ) delay in my example.A real-world scenario : I have a cache that returns some entities , and a datasource that returns all entities . I 'd like to be able to return an iterator from a method that internally parallelises the request to both the cache and the datasource so that the cached results yield as fast as possible.Note 1 : I realise this is still wasting CPU cycles ; I 'm not asking how can I prevent the sequences from iterating over their slow elements , just how I can union them as fast as possible.Update 1 : I 've tailored achitaka-san 's great response to accept multiple producers , and to use ContinueWhenAll to set the BlockingCollection 's CompleteAdding just the once . I just put it here since it would get lost in the lack of comments formatting . Any further feedback would be great ! public static IEnumerable < int > FastFirst ( ) { for ( int i = 1 ; i < 6 ; i++ ) { if ( i > 3 ) Thread.Sleep ( 200 ) ; yield return i ; } } public static IEnumerable < int > SlowFirst ( ) { for ( int i = 1 ; i < 6 ; i++ ) { if ( i < 4 ) Thread.Sleep ( 200 ) ; yield return i ; } } FastFirst ( ) .Union ( SlowFirst ( ) ) ; public static IEnumerable < TResult > SelectAsync < TResult > ( params IEnumerable < TResult > [ ] producer ) { var resultsQueue = new BlockingCollection < TResult > ( ) ; var taskList = new HashSet < Task > ( ) ; foreach ( var result in producer ) { taskList.Add ( Task.Factory.StartNew ( ( ) = > { foreach ( var product in result ) { resultsQueue.Add ( product ) ; } } ) ) ; } Task.Factory.ContinueWhenAll ( taskList.ToArray ( ) , x = > resultsQueue.CompleteAdding ( ) ) ; return resultsQueue.GetConsumingEnumerable ( ) ; }","Using Parallel Linq Extensions to union two sequences , how can one yield the fastest results first ?" "C_sharp : I expected the implementation of Enumerable.Empty ( ) to be just this : But the implementation is something like this : Why does the implementation is more complex than just one line of code ? Is there an advantage to return a cached array and not ( yield ) return no elements ? Note : I will never rely on the implementation details of a method , but I am just curious . public static IEnumerable < TResult > Empty < TResult > ( ) { yield break ; } public static IEnumerable < TResult > Empty < TResult > ( ) { return EmptyEnumerable < TResult > .Instance ; } internal class EmptyEnumerable < TElement > { private static volatile TElement [ ] instance ; public static IEnumerable < TElement > Instance { get { if ( EmptyEnumerable < TElement > .instance == null ) EmptyEnumerable < TElement > .instance = new TElement [ 0 ] ; return ( IEnumerable < TElement > ) EmptyEnumerable < TElement > .instance ; } } }",Why does Enumerable.Empty ( ) return an empty array ? "C_sharp : I have a question about how customizable the new async/await keywords and the Task class in C # 4.5 are.First some background for understanding my problem : I am developing on a framework with the following design : One thread has a list of `` current things to do '' ( usually around 100 to 200 items ) which are stored as an own data structure and hold as a list . It has an Update ( ) function that enumerates the list and look whether some `` things '' need to execute and does so . Basically its like a big thread sheduler . To simplify things , lets assume the `` things to do '' are functions that return the boolean true when they are `` finished '' ( and should not be called next Update ) and false when the sheduler should call them again next update.All the `` things '' must not run concurrently and also must run in this one thread ( because of thread static variables ) There are other threads which do other stuff . They are structured in the same way : Big loop that iterates a couple of hundret things to do in a big Update ( ) - function.Threads can send each other messages , including `` remote procedure calls '' . For these remote calls , the RPC system is returning some kind of future object to the result value . In the other thread , a new `` thing to do '' is inserted.A common `` thing '' to do are just sequences of RPCs chained together . At the moment , the syntax for this `` chaining '' is very verbose and complicated , since you manually have to check for the completion state of previous RPCs and invoke the next ones etc..An example : Now this all sound awefull like async and await of C # 5.0 can help me here . I have n't 100 % fully understand what it does under the hood ( any good references ? ) , but as I get it from some few talks I 've watched , it exactly does what I want with this nicely simple code : But I ca n't find a way how write my Update ( ) function to make something like this happen . async and await seem to want to use the Task - class which in turn seems to need real threads ? My closest `` solution '' so far : The first thread ( which is running SomeThingToDo ) calls their functions only once and stores the returned task and tests on every Update ( ) whether the task is completed.Remote1.CallF1 returns a new Task with an empty Action as constructor parameter and remembers the returned task . When F1 is actually finished , it calls RunSynchronously ( ) on the task to mark it as completed . That seems to me like a pervertion of the task system . And beside , it creates shared memory ( the Task 's IsComplete boolean ) between the two threads which I would like to have replaced with our remote messanging system , if possible.Finally , it does not solve my problem as it does not work with the await-like SomeThingToDo implementation above . It seems the auto-generated Task objects returned by an async function are completed immediately ? So finally my questions : Can I hook into async/await to use my own implementations instead of Task < T > ? If that 's not possible , can I use Task without anything that relates to `` blocking '' and `` threads '' ? Any good reference what exactly happens when I write async and await ? Future f1 , f2 ; bool SomeThingToDo ( ) // returns true when `` finished '' { if ( f1 == null ) f1 = Remote1.CallF1 ( ) ; else if ( f1.IsComplete & & f2 == null ) f2 = Remote2.CallF2 ( ) ; else if ( f2 ! = null & & f2.IsComplete ) return true ; return false ; } async Task SomeThingToDo ( ) // returning task is completed when this is finished . { await Remote1.CallF1 ( ) ; await Remote2.CallF2 ( ) ; }",async and await without `` threads '' ? Can I customize what happens under-the-hood ? "C_sharp : I 've seen a lot of warnings about writing code such as ... I 've read that its OK with Eventhandlers as they must return void . However partial methods must also return void . You can have the following code ... and then implement as ... But what will happen to the application if the implementation of MyCustomCode encounters an exception ? If it 's a no go , given how prevalent async / await is , does that mean partial methods are essentially obsolete ? Should code generation systems stop exposing partial methods in favour of events or perhaps better still empty protected virtual methods in a base class ? i.e.EDIT : OK so I 've made several updates to the code . After the original pseudo code I wrote did n't get well received . The code above I think demonstrates that there 's definitely an issue with async partial void MyPartialMethod as the call to MyCodeGeneratedMethod does seem to bring down the app domain , despite the try catch around the call . I 'm just wondering if there are better options than moving to protected virtual base class methods . public async void MyDangerousMethodWhichCouldCrashMyApp ... static void Main ( string [ ] args ) { MainAsync ( ) .Wait ( ) ; Console.ReadLine ( ) ; } async static Task MainAsync ( ) { MyCodeGeneratedClass c = new MyCodeGeneratedClass ( ) ; try { await c.MyCodeGeneratedMethod ( ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message ) ; } } public partial class MyCodeGeneratedClass { public async Task MyCodeGeneratedMethod ( ) { HttpClient client = new HttpClient ( ) ; Console.WriteLine ( await client.GetStringAsync ( `` http : //msdn.microsoft.com '' ) ) ; MyCustomCode ( ) ; } partial void MyCustomCode ( ) ; } partial class MyCodeGeneratedClass { async partial void MyCustomCode ( ) { HttpClient client = new HttpClient ( ) ; Console.WriteLine ( await client.GetStringAsync ( `` http : //msdn.microsoft.com '' ) ) ; throw new Exception ( `` Boom '' ) ; } } protected virtual Task MyCustomCode ( T foo ) { return Task.FromResult ( 0 ) ; }",Is async partial void MyPartialMethod ( ) dangerous ? "C_sharp : I read section 2.3.2 of Skeet 's book and , from my understanding , there is no such thing as a true reference in C # , like there is in C++ . It 's interesting to note that not only is the `` by reference '' bit of the myth innacurate , but so is the `` objects are passed '' bit . Objects themselves are never passed , either by reference or by value . When a reference type is involved , either the variable is passed by reference or the value of the argument ( the reference ) is passed by value.See , that 's different than C++ ( I come from a C++ background ) because in C++ you can use the ampersand to directly use an object in a parameter list -- no copies of anything , not even a copy of the memory address of the object : There is no equivalent of the above . The best you can get in C # is an equivalent of which is passing in the value of a sort of reference ( a pointer ) and of course is pointless in my example because all that 's being passed in is a small primitive ( int ) . From what I understand , there is no C # syntax that explicitly designates an element as being a reference , no equivalent of the & in my C++ example . The only way you know whether you 're dealing with a value or reference is by memorizing what types of elements are references when copied and what types are values . It 's like JavaScript in that regard . Please critique my understanding of this concept . bool isEven ( int & i ) { return i % 2 == 0 } ) int main ( ) { int x = 5 ; std : :cout < < isEven ( x ) ; // is the exact same as if I had written // std : :cout ( x % 2 == 0 ) return 0 ; } bool isEven ( int * i ) { return *i % 2 == 0 } ) int main ( ) { int x = 5 ; std : :cout < < isEven ( & x ) ; // is like // int * temp = & x ; // return *temp % 2 == 0 ; // ( garbage collect temp ) return 0 ; }",Read Jon Skeet 's chapter on references versus values . Still confused "C_sharp : Resharper wanted me to change this code : ... because it said , `` Possible 'System.NullReferencesException ' '' So it should be this : ? I do n't get this - how could a combobox 's Items be null , unless null == empty ? And if null == empty , then that 's exactly what they [ s , w ] ould be when this code is called . foreach ( var item in cmbxColor1.Items ) { cmbxColor2.Items.Add ( item ) ; . . . foreach ( var item in cmbxColor1.Items ) { if ( null ! = cmbxColor2.Items ) { cmbxColor2.Items.Add ( item ) ; . . .",Are a combobox 's items null when empty ? "C_sharp : While making everthing with goto 's is easy ( as evidenced by f.ex . IL ) , I was wondering if it is also possible to eliminate all goto statements with higher level expressions and statements - say - using everything that 's supported in Java . Or if you like : what I 'm looking for is 'rewrite rules ' that will always work , regardless of the way the goto is created.It 's mostly intended as a theoretical question , purely as interest ; not as a good/bad practices.The obvious solution that I 've thought about is to use something like this : While this will probably work and does fits my 'formal ' question , I do n't like my solution a single bit . For one , it 's dead ugly and for two , it basically wraps the goto into a switch that does exactly the same as a goto would do.So , is there a better solution ? Update 1Since a lot of people seem to think the question is 'too broad ' , I 'm going to elaborate a bit more ... the reason I mentioned Java is because Java does n't have a 'goto ' statement . As one of my hobby projects , I was attempting to transform C # code into Java , which is proving to be quite challenging ( partly because of this limitation in Java ) .That got me thinking . If you have f.ex . the implementation of the 'remove ' method in Open addressing ( see : http : //en.wikipedia.org/wiki/Open_addressing - note 1 ) , it 's quite convenient to have the 'goto ' in the exceptional case , although in this particular case you could rewrite it by introducing a 'state ' variable . Note that this is just one example , I 've implemented code generators for continuations , which produce tons and tons of goto 's when you 're attempting to decompile them.I 'm also not sure if rewriting in this matter will always eliminate the 'goto ' statement and if it is allowed in every case . While I 'm not looking for a formal 'proof ' , some evidence that elimination is possible in this matter would be great.So about the 'broadness ' , I challenge all the people that think there are 'too many answers ' or 'many ways to rewrite a goto ' to provide an algorithm or an approach to rewriting the general case please , since the only answer I found so far is the one I 've posted . while ( true ) { switch ( state ) { case [ label ] : // here 's where all your goto 's will be state = [ label ] ; continue ; default : // here 's the rest of the program . } }",Is it possible to always eliminate goto 's ? "C_sharp : I have the following code : When i bind against it from xaml , debug points in TryGetMember is not triggeret . Do i miss something ? The datacontext is set toand public class MyClass : DynamicObject , INotifyPropertyChanged { Dictionary < string , object > properties = new Dictionary < string , object > ( ) ; public override bool TryGetMember ( GetMemberBinder binder , out object result ) { if ( properties.ContainsKey ( binder.Name ) ) { result = properties [ binder.Name ] ; return true ; } else { result = `` Invalid Property ! `` ; return false ; } } public override bool TrySetMember ( SetMemberBinder binder , object value ) { properties [ binder.Name ] = value ; this.OnPropertyChanged ( binder.Name ) ; return true ; } public override bool TryInvokeMember ( InvokeMemberBinder binder , object [ ] args , out object result ) { dynamic method = properties [ binder.Name ] ; result = method ( args [ 0 ] .ToString ( ) , args [ 1 ] .ToString ( ) ) ; return true ; } /// ... . Rest of the class . } < DataTemplate x : Key= '' SearchResults '' > < Grid Width= '' 294 '' Margin= '' 6 '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < Border Background= '' { StaticResource ListViewItemPlaceholderBackgroundThemeBrush } '' Margin= '' 0,0,0,10 '' Width= '' 40 '' Height= '' 40 '' > < Image Source= '' { Binding Path=Banner } '' Stretch= '' UniformToFill '' / > < /Border > < StackPanel Grid.Column= '' 1 '' Margin= '' 10 , -10,0,0 '' > < TextBlock Text= '' { Binding SeriesName } '' Style= '' { StaticResource BodyTextStyle } '' TextWrapping= '' NoWrap '' / > < TextBlock Text= '' { Binding Subtitle } '' Style= '' { StaticResource BodyTextStyle } '' Foreground= '' { StaticResource ApplicationSecondaryForegroundThemeBrush } '' TextWrapping= '' NoWrap '' / > < TextBlock Text= '' { Binding Overview } '' Style= '' { StaticResource BodyTextStyle } '' Foreground= '' { StaticResource ApplicationSecondaryForegroundThemeBrush } '' TextWrapping= '' NoWrap '' / > < /StackPanel > < /Grid > < /DataTemplate > public ObservableCollection < dynamic > SearchResults { get ; set ; } ICollection col = item.SearchResults ; this.DefaultViewModel [ `` Results '' ] = col ; //this is the datacontext of the gridview",Can i bind against a DynamicObject in WinRT / Windows 8 Store Apps "C_sharp : I 'm trying to get a summary of confirmed/finalized purchases by querying a SaleConfirmation table , but I 'm having a lot of difficulty with the method syntax query.Database TableHere is the SaleConfirmation table structure that stores finalized sales.Id : Unique row ID.OfferId : Foreign key that links to a Offer/Saletable.ProdId : ID of the product in the products table.Qty : The quantity sold to the customer.SaleDate : The date when the sale was finalized.Controller ActionThe error in the select query is g.Sum ( ii = > ii.Qty ) and the error is below . Invalid anonymous type member declarator . Anonymous type members must be declared with a member assignment , simple name or member access . Id OfferId ProdId Qty SaleDate -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -10 7 121518 150 2013-03-14 00:00:00.00019 7 100518 35 2013-03-18 14:46:34.28720 7 121518 805 2013-03-19 13:03:34.02321 10 131541 10 2013-03-20 08:34:40.287 var confRollUps = db.SaleConfirmation .GroupBy ( c = > c.OfferId ) // Ensure we get a list of unique/distinct offers .Select ( g = > g.Select ( i = > new { i.OfferId , i.Product.Variety , // `` Category '' of product , will be the same across products for this offer . i.Product is a SQL Server Navigation property . i.Offer.Price , // The price of the product , set per offer . i.Offer is a SQL Server Navigation property . i.Offer.Quantity , // The quantity of items that are expected to be sold before the offer expires i.Offer.DateClose , // Date of when the offer expires g.Sum ( ii = > ii.Qty ) // Sum up the Qty column , we do n't care about ProdIds not matching } ) ) ;",Entity Framework 5 Method Query Roll Up "C_sharp : Taking the following code , what happens in a multithreaded environment : In a multithreaded environment this method and property can be accessed in the same time by different threads . Is it thread safe to assign a new object to a static variable that is accessible in different threads ? What can go wrong ? Is there a moment in time when Events can be null ? ? If 2 threads call in the same time Events and ResetDictionary ( ) for example . static Dictionary < string , string > _events = new Dictionary < string , string > ( ) ; public static Dictionary < string , string > Events { get { return _events ; } } public static void ResetDictionary ( ) { _events = new Dictionary < string , string > ( ) ; }",is it thread safe to assign a new value to a static object in c # "C_sharp : How do you mock AsNoTracking or is there a better workaround for this Problem ? Example : My test : Every time I run this Test , the Exception that is thrown in isContact ( String firstName , String lastName ) at AsNoTracking ( ) is : Exception.Message : There is no method 'AsNoTracking ' on type 'Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions ' that matches the specified argumentsException.StackTrace : My attempts : Trying to mock AsNoTracking like suggested in stackoverflow : mock-asnotracking-entity-framework : results in ASP.NET Core in a System.NotSupportedException : 'Invalid setup on an extension method : m = > m.AsNoTracking ( ) ' mockSet.Setup ( m = > m.AsNoTracking ( ) ) .Returns ( mockSet.Object ) ; After taking a better look at Microsoft.EntityFrameworkCore EntityFrameworkQueryableExtensions EntityFrameworkCore EntityFrameworkQueryableExtensions.cs at AtNoTracking ( ) : Since the mocked DbSet < > i provide during the test , the Provider is IQueryable the function AsNoTracking should return the input source since `` source.Provider is EntityQueryProvider '' is false.The only thing I could n't check was Check.NotNull ( source , nameof ( source ) ) ; since I could not find what it does ? if some has a explanation or code showing what it does I would appreciate it if you could share it with me.Workaround : The only workaround i found in the internet is from @ cdwaddell in the thread https : //github.com/aspnet/EntityFrameworkCore/issues/7937 who basically wrote his own gated version of AsNoTracking ( ) . Using the workaround leads to success , but I would n't want to implement it as it seems to not check for something ? So , my questions : Is with my workaround the only way to test stuff like this ? Is there a possibility to Mock this ? What does Check.NotNull ( source , nameof ( source ) ) ; in AsNoTracking ( ) do ? public class MyContext : MyContextBase { // Constructor public MyContext ( DbContextOptions < MyContext > options ) : base ( options ) { } // Public properties public DbSet < MyList > MyLists { get ; set ; } } public class MyList { public string Id { get ; set ; } public string Email { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public bool Blocked { get ; set ; } } public class MyController : MyControllerBase { private MyContext ContactContext = this.ServiceProvider.GetService < MyContext > ( ) ; public MyController ( IServiceProvider serviceProvider ) : base ( serviceProvider ) { } private bool isContact ( string firstName , string lastName ) { try { var list = this .ContactContext .MyLists .AsNoTracking ( ) // ! ! ! Here it explodes ! ! ! .FirstOrDefault ( entity = > entity.FirstName == firstName & & entity.LastName == lastName ) ; return list ! = null ; } catch ( Exception exception ) { throws Exception ; } return false ; } } using Moq ; using Xunit ; [ Fact ] [ Trait ( `` Category '' , `` Controller '' ) ] public void Test ( ) { string firstName = `` Bob '' ; string lastName = `` Baumeister '' ; // Creating a list with the expectad data var fakeContacts = new MyList [ ] { new MyList ( ) { FirstName = `` Ted '' , LastName = `` Teddy '' } , new MyList ( ) { PartnerId = `` Bob '' , Email = `` Baumeister '' } } ; // Mocking the DbSet < MyList > var dbSet = CreateMockSet ( fakeContacts.AsQueryable ( ) ) ; // Setting the mocked dbSet in ContactContext ContactContext contactContext = new ContactContext ( new DbContextOptions < ContactContext > ( ) ) { MyLists = dbSet.Object } ; // Mocking ServiceProvider serviceProvider .Setup ( s = > s.GetService ( typeof ( ContactContext ) ) ) .Returns ( contactContext ) ; // Creating a controller var controller = new ContactController ( serviceProvider.Object ) ; // Act bool result = controller.isContact ( firstName , lastName ) // Assert Assert.True ( result ) ; } private Mock < DbSet < T > > CreateMockSet < T > ( IQueryable < T > data ) where T : class { var queryableData = data.AsQueryable ( ) ; var mockSet = new Mock < DbSet < T > > ( ) ; mockSet.As < IQueryable < T > > ( ) .Setup ( m = > m.Provider ) .Returns ( queryableData.Provider ) ; mockSet.As < IQueryable < T > > ( ) .Setup ( m = > m.Expression ) .Returns ( queryableData.Expression ) ; mockSet.As < IQueryable < T > > ( ) .Setup ( m = > m.ElementType ) .Returns ( queryableData.ElementType ) ; mockSet.As < IQueryable < T > > ( ) .Setup ( m = > m.GetEnumerator ( ) ) .Returns ( queryableData.GetEnumerator ( ) ) ; return mockSet ; } at System.Linq.EnumerableRewriter.FindMethod ( Type type , String name , ReadOnlyCollection ' 1 args , Type [ ] typeArgs ) at System.Linq.EnumerableRewriter.VisitMethodCall ( MethodCallExpression m ) at System.Linq.Expressions.MethodCallExpression.Accept ( ExpressionVisitor visitor ) at System.Linq.Expressions.ExpressionVisitor.Visit ( Expression node ) at System.Linq.EnumerableQuery ' 1.GetEnumerator ( ) at System.Linq.EnumerableQuery ' 1.System.Collections.Generic.IEnumerable < T > .GetEnumerator ( ) at My.Package.Contact.Controller.MyController.isContact ( String firstName , String lastName ) in C : \Users\source\repos\src\My.Package\My.Package.Contact\Controller\MyController.cs : line 31 mockSet.As < IQueryable < T > > ( ) .Setup ( m = > m.AsNoTracking < T > ( ) ) .Returns ( mockSet.Object ) ; public static IQueryable < TEntity > AsNoTracking < TEntity > ( [ NotNull ] this IQueryable < TEntity > source ) where TEntity : class { Check.NotNull ( source , nameof ( source ) ) ; return source.Provider is EntityQueryProvider ? source.Provider.CreateQuery < TEntity > ( Expression.Call ( instance : null , method : AsNoTrackingMethodInfo.MakeGenericMethod ( typeof ( TEntity ) ) , arguments : source.Expression ) ) : source ; } public static class QueryableExtensions { public static IQueryable < T > AsGatedNoTracking < T > ( this IQueryable < T > source ) where T : class { if ( source.Provider is EntityQueryProvider ) return source.AsNoTracking < T > ( ) ; return source ; } }",Mock or better workaround for AsNoTracking in ASP.NET Core "C_sharp : as the title says , i have an array of hashsets , but i do n't know how apply to them a comparer . Like this : Of Course i need the comparer.. What am i doing wrong ? Thank you //This Works : public HashSet < Animal.AnimalCell > UpdateList = new HashSet < Animal.AnimalCell > ( new CellComparer ( ) ) ; //This Does not work : public HashSet < Animal.AnimalCell > [ ] UpdateListThreaded = new HashSet < Animal.AnimalCell > ( new CellComparer ( ) ) [ 10 ] ; //This Does not Work : public HashSet < Animal.AnimalCell > [ ] UpdateListThreaded = new HashSet < Animal.AnimalCell > [ 10 ] ( new CellComparer ( ) ) ; //This Works : public HashSet < Animal.AnimalCell > [ ] UpdateListThreaded = new HashSet < Animal.AnimalCell > [ 10 ] ;",Array of HashSets with comparer in C # "C_sharp : When I use XNA Framework ( For windows Phone ) my game work perfectly , but when I migrate on Silverlight/XNA Framework I got a problem with animation lagging.The problem is the following : When I set fixed time step to GameTimer ( timer.UpdateInterval = TimeSpan.FromTicks ( 333333 ) ) , the REAL time step does n't FIXED and timer events ( OnUpdate , OnDraw ) fires with different intervals.This code shows my problem more clearly : Silverlight/XNA Framework : ( Animation lagging ) : XNA Framework : ( All works fine ) : TimeSpan curNow ; TimeSpan lastUpdate ; TimeSpan lastDraw ; public GamePage ( ) { timer = new GameTimer ( ) ; timer.UpdateInterval = TimeSpan.FromTicks ( 333333 ) ; timer.Update += OnUpdate ; timer.Draw += OnDraw ; } private void OnUpdate ( object sender , GameTimerEventArgs e ) { curNow = new TimeSpan ( DateTime.Now.Ticks ) ; TimeSpan elapsed=e.ElapsedTime ; //Always constant and has value : 33ms TimeSpan realElapsed = curNow - lastUpdate ; //Real elapsed time always changing and has a value between : 17-39ms ( sometimes more then 39ms ) lastUpdate = curNow ; } private void OnDraw ( object sender , GameTimerEventArgs e ) { curNow = new TimeSpan ( DateTime.Now.Ticks ) ; TimeSpan elapsed=e.ElapsedTime ; //Always changing and has a value between : 17-39ms ( sometimes more then 39ms ) TimeSpan realElapsed = curNow -lastDraw ; //Always changing and has a value between : 17-39ms ( sometimes more then 39ms ) lastDraw= curNow ; } TimeSpan curNow ; TimeSpan lastUpdate ; TimeSpan lastDraw ; public Game ( ) { // Frame rate is 30 fps by default for Windows Phone . TargetElapsedTime = TimeSpan.FromTicks ( 333333 ) ; } protected override void Update ( GameTime gameTime ) { curNow = new TimeSpan ( DateTime.Now.Ticks ) ; TimeSpan elapsed=gameTime.ElapsedGameTime ; //Always constant and has value : 33ms TimeSpan realElapsed = curNow - lastUpdate ; //Real elapsed time has a value between : 34-35ms ( sometimes more then 35ms ) lastUpdate = curNow ; } protected override void Draw ( GameTime gameTime ) { curNow = new TimeSpan ( DateTime.Now.Ticks ) ; TimeSpan elapsed=gameTime.ElapsedGameTime ; //Value between : 33-34ms ( sometimes more then 34ms ) TimeSpan realElapsed = curNow - lastDraw ; //Value between : 34-35ms ( sometimes more then 35ms ) lastDraw = curNow ; }",Silverlight/XNA animation lagging "C_sharp : Well lets say we have this c # code : IL : Now to the question my understanding is that ldarg. # puts the arguments supplied to the method on the stack so we can work with them ? But why does it call ldarg.1 and ldarg.0 when the method only takes one argument ? public override void Write ( XDRDestination destination ) { destination.WriteInt ( intValue ) ; destination.WriteBool ( boolValue ) ; destination.WriteFixedString ( str1 , 100 ) ; destination.WriteVariableString ( str2 , 100 ) ; } .method public hidebysig virtual instance void Write ( class [ XDRFramework ] XDRFramework.XDRDestination destination ) cil managed { // Code size 53 ( 0x35 ) .maxstack 8 IL_0000 : ldarg.1 IL_0001 : ldarg.0 IL_0002 : call instance int32 LearnIL.Test1 : :get_intValue ( ) IL_0007 : callvirt instance void [ XDRFramework ] XDRFramework.XDRDestination : :WriteInt ( int32 ) IL_000c : ldarg.1 IL_000d : ldarg.0 IL_000e : call instance bool LearnIL.Test1 : :get_boolValue ( ) IL_0013 : callvirt instance void [ XDRFramework ] XDRFramework.XDRDestination : :WriteBool ( bool ) IL_0018 : ldarg.1 IL_0019 : ldarg.0 IL_001a : call instance string LearnIL.Test1 : :get_str1 ( ) IL_001f : ldc.i4.s 100 IL_0021 : callvirt instance void [ XDRFramework ] XDRFramework.XDRDestination : :WriteFixedString ( string , uint32 ) IL_0026 : ldarg.1 IL_0027 : ldarg.0 IL_0028 : call instance string LearnIL.Test1 : :get_str2 ( ) IL_002d : ldc.i4.s 100 IL_002f : callvirt instance void [ XDRFramework ] XDRFramework.XDRDestination : :WriteVariableString ( string , uint32 ) IL_0034 : ret } // end of method Test1 : :Write",MSIL Question ( Basic ) "C_sharp : I 'm using MEF and I have two exports having the same contract type but with different contract name Eg : I could retrieve each exports using its respective contract name : But now I wish to retrieve all instances implementing MyPlugin . is there any way I could do it ? I 've tried using the following code : But it did not work . Apparently it is used to retrieve only implementations with no specific contract name.Any opinion ? [ Export ( `` TypeA '' , typeof ( MyPlugin ) ) ] [ Export ( `` TypeB '' , typeof ( MyPlugin ) ) ] ServiceLocator.GetExportedValues < MyPlugin > ( `` TypeA '' ) ; ServiceLocator.GetExportedValues < MyPlugin > ( ) ;",Service Locator : Get all exports "C_sharp : I am trying to write a regexp which would match a comma separated list of words and capture all words . This line should be matched apple , banana , orange , peanut and captures should be apple , banana , orange , peanut . To do that I use following regexp : It successfully matches the string but all of a sudden only apple and peanut are captured . This behaviour is seen in both C # and Perl . Thus I assume I am missing something about how regexp matching works . Any ideas ? : ) ^\s* ( [ a-z_ ] \w* ) ( ? : \s* , \s* ( [ a-z_ ] \w* ) ) *\s* $",Odd regexp behaviour - matches only first and last capture group "C_sharp : Just curious , I 'm not trying to solve any problem.Why only local variables should be assigned ? In the following example : Why a and b gives me just a warning and c gives me an error ? Addionally , why I ca n't just use the default value of Value Type and write the following code ? Does it have anything to do with memory management ? class Program { static int a ; static int b { get ; set ; } static void Main ( string [ ] args ) { int c ; System.Console.WriteLine ( a ) ; System.Console.WriteLine ( b ) ; System.Console.WriteLine ( c ) ; } } bool MyCondition = true ; int c ; if ( MyCondition ) c = 10 ;",About unassigned variables "C_sharp : With this code : I was getting a compiler error , `` Use of unassigned local variable 'dataToAdd ' '' So I had to explicitly assign `` false '' to the bool : In context : Why is it necessary ? Do n't bools have a default value of false ? bool dataToAdd ; if ( null == _priceComplianceDetailList ) return dataToAdd ; bool dataToAdd = false ; if ( null == _priceComplianceDetailList ) return dataToAdd ; private bool PopulateSheetWithDetailData ( ) { bool dataToAdd = false ; if ( null == _priceComplianceDetailList ) return dataToAdd ; List < PriceComplianceDetail > _sortedDetailList = . . . return _sortedDetailList.Count > 0 ; }",What is the reason for `` Use of unassigned local variable '' error ? "C_sharp : When you have a class car that implements IVehicle and you want to wrap it in a decorator that forwards all calls to car and counts them , how would you do it ? In Ruby I could just build a decorator without any methods and use method_missing to forward all calls to the car object.In Java I could build a Proxy object that runs all code through one method and forwards it afterwards.Is there any similiar thing i can do in C # ? update : based on the answeres and what i´ve read about System.Reflection.Emit it should be possible to write a method similiar to this : where type implements all interface of someType , executes functionToBeApplied and then forwards the method call to object while returning its return.Is there some lib that does just that or would i have to write my own ? Type proxyBuilder ( Type someType , delagate functionToBeApplied , Object forward )",What is the shortest way to implement a proxy or decorator class in c # ? "C_sharp : is there any way to 'hack ' or 'coerce ' covariant overrides in to C # ? For example : Unfortunately , C # does n't support this ( which seems a bit ridiculous , but that 's neither here nor there ) .I thought I might have an answer with method hiding : But this does n't add the entry in to the 'vtable ' , it just basically declares a brand new method with the same name , and as such means that accessing Betas through a pointer to an Alpha will call Alpha.DoSomething ( ) .So , any good tricks ? public class Alpha { public virtual Alpha DoSomething ( ) { return AlphaFactory.GetAlphaFromSomewhere ( ) ; } } public class Beta : Alpha { public override Beta DoSomething ( ) { return BetaFactory.GetBetaFromSomewhere ( ) ; } } new public Beta DoSomething ( ) { return BetaFactory.GetBetaFromSomewhere ( ) ; }",Workaround for lack of return type covariance when overriding virtual methods "C_sharp : I 'm trying to update a value in a MS Access DB ( *.mdb ) using OleDB in C # . Nothing fancy , except that I need to choose the row by an binary value , a VARBINARY ( 4 ) . Naively I thought UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE=01020304 ; would work . But is does not.Alternative tries were : Using CAST results in a syntax error exception : missing operator.Using CONVERT results in exception : Undefined function 'CONVERT ' in expression.The number of affected rows , in int result , is always zero . Using UPDATE MYTABLE SET VALUE= 'new ' WHERE VALUE= old ; works , but will sometimes hit more than one row . While trying and failing to find a way to circumvent checking BINVALUEI noticed that you should not use Arabic commas ( ' ) around values in the WHERE clause . UPDATE MYTABLE SET VALUE= 'new ' WHERE VALUE='old ' ; does NOT work while UPDATE MYTABLE SET VALUE= 'new ' WHERE VALUE=old ; works.Using MS Query yields different results concerning the Arabic commas : UPDATE MYTABLE SET VALUE='new ' WHERE BINVALUE='01020304 ' executes , but has no effect.UPDATE MYTABLE SET VALUE='new ' WHERE BINVALUE=01020304 results in the error message `` Syntax error in number in query expression 'BINVALUE=01020304 ' . `` I ca n't reproduce the error message `` Column BINVALUE ca n't be used in the criteria . '' that I mentioned in the comments.Using other columns to identify the desired row does not work , as most values are the same . Strangely enough BINVALUE serves as a the primary key.On top of that , I am not allowed to change the DB schema , as a legacy application needs it exactly that way.Based on gloomy.penguin 's input I assume there is a problem with the type casting/matching in the WHERE clause . This leads to the question how casting/conversion is done in OleDB or Access as the CAST operator appears to be known , but CONVERT is not . My guess would be that CAST has another syntax than in standard SQL for whatever reasons . Any suggestions , how this update query can be made to work ? This is my stripped down example code : UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE='01020304 ' ; UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE='0x01020304 ' ; UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE=0x01020304 ; UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE=CAST ( '01020304 ' as VARBINARY ) ; UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE=CAST ( 01020304 as VARBINARY ) ; UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE=CAST ( '01020304 ' as VARBINARY ( 4 ) ) ; UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE=CAST ( 01020304 as VARBINARY ( 4 ) ) ; UPDATE MYTABLE SET VALUE= 'new ' WHERE BINVALUE=CONVERT ( varbinary ( 4 ) , '01020304 ' ) ; UPDATE MYTABLE SET VALUE= 'new ' WHERE CAST ( BINVALUE as VARCHAR ( MAX ) ) = CAST ( '01020304 ' as VARCHAR ( MAX ) ) ; UPDATE MYTABLE SET VALUE= 'new ' WHERE CAST ( BINVALUE as VARCHAR ( MAX ) ) = CAST ( 01020304 as VARCHAR ( MAX ) ) ; UPDATE MYTABLE SET VALUE= 'new ' WHERE CONVERT ( VARCHAR ( MAX ) , BINVALUE ) = CONVERT ( VARCHAR ( MAX ) , '01020304 ' ) ; static String ToHexString ( Byte [ ] buffer ) { String str ; str = BitConverter.ToString ( buffer ) .Replace ( `` - '' , string.Empty ) ; return ( str ) ; } ... String table = `` MYTABLE '' ; String newvalue = `` new '' ; Byte [ ] binvalue = { 1 , 2 , 3 , 4 } ; String providerStr= @ '' Provider=Microsoft.JET.OLEDB.4.0 ; '' + @ '' data source=C : \myDB.mdb '' ; connection = new OleDbConnection ( providerStr ) ; connection.Open ( ) ; String cmd = @ '' UPDATE `` + table + `` SET VALUE= ' '' + newvalue + `` ' '' + `` WHERE BINVALUE= ' '' + ToHexString ( binvalue ) + `` ' '' + `` ; '' ; OleDbCommand command = new OleDbCommand ( cmd , connection ) ; int result = command.ExecuteNonQuery ( ) ; connection.Close ( ) ;",Using a binary column as a comparison criterion "C_sharp : Here 's the json string that I have.How can I select the # text data for EPS for years 2015 , 2016 , 2017 ? Here 's the query that I have so far : Here 's the jsonExtensions I 'm using : The problem is that EPS will not always be in the same position for the next company ? So , I want the query to search for EPS clientcode & return the values for the years mentioned above , hopefully using the DRY method . Would you be so kind as to help me finish up my query ? NOTE : I 'm actually downloading a XML string , converting it to JSON and then parsing it . { `` ? xml '' : { `` @ version '' : `` 1.0 '' , `` @ encoding '' : `` UTF-8 '' } , `` DataFeed '' : { `` @ FeedName '' : `` issuerDetails '' , `` SecurityDetails '' : { `` Security '' : { `` SecurityID '' : { `` @ idValue '' : `` AAPL-NSDQ '' , `` @ fiscalYearEnd '' : `` 2016-12-31T00:00:00.00 '' } , `` FinancialModels '' : { `` FinancialModel '' : [ { `` @ id '' : `` 780 '' , `` @ name '' : `` Estimates - Energy '' , `` @ clientCode '' : `` A '' , `` Values '' : [ { `` @ name '' : `` EBITDA '' , `` @ clientCode '' : `` EBITDA '' , `` @ currency '' : `` C $ '' , `` Value '' : [ { `` @ year '' : `` 2014 '' , `` # text '' : `` 555.64 '' } , { `` @ year '' : `` 2015 '' , `` # text '' : `` -538.986 '' } , { `` @ year '' : `` 2016 '' , `` # text '' : `` 554.447 '' } , { `` @ year '' : `` 2017 '' , `` # text '' : `` 551.091 '' } , { `` @ year '' : `` 2018 '' , `` # text '' : `` 0 '' } ] } , { `` @ name '' : `` EPS '' , `` @ clientCode '' : `` EPS '' , `` @ currency '' : `` C $ '' , `` Value '' : [ { `` @ year '' : `` 2014 '' , `` # text '' : `` 0 '' } , { `` @ year '' : `` 2015 '' , `` # text '' : `` -1.667 '' } , { `` @ year '' : `` 2016 '' , `` # text '' : `` -1.212 '' } , { `` @ year '' : `` 2017 '' , `` # text '' : `` 0.202 '' } , { `` @ year '' : `` 2018 '' , `` # text '' : `` 0 '' } ] } , { `` @ name '' : `` CFPS '' , `` @ clientCode '' : `` CFPS '' , `` @ currency '' : `` C $ '' , `` Value '' : [ { `` @ year '' : `` 2014 '' , `` # text '' : `` 3.196 '' } , { `` @ year '' : `` 2015 '' , `` # text '' : `` -0.207 '' } , { `` @ year '' : `` 2016 '' , `` # text '' : `` 0.599 '' } , { `` @ year '' : `` 2017 '' , `` # text '' : `` 2.408 '' } , { `` @ year '' : `` 2018 '' , `` # text '' : `` 0 '' } ] } ] } ] } } } } } JObject jsonFeed = JObject.Parse ( jsonText ) ; var query = from security in jsonFeed.SelectTokens ( `` DataFeed.SecurityDetails.Security '' ) .SelectMany ( i = > i.ObjectsOrSelf ( ) ) let finModels = security.SelectTokens ( `` FinancialModels.FinancialModel '' ) .SelectMany ( s = > s.ObjectsOrSelf ( ) ) .FirstOrDefault ( ) where finModels ! = null select new { FinModelClientCode = ( string ) finModels.SelectToken ( `` Values [ 1 ] . @ clientCode '' ) , FinModelYear2015 = ( string ) finModels.SelectToken ( `` Values [ 1 ] .Value [ 1 ] . @ year '' ) , FinModelValue2015 = ( string ) finModels.SelectToken ( `` Values [ 1 ] .Value [ 1 ] . # text '' ) , FinModelYear2016 = ( string ) finModels.SelectToken ( `` Values [ 1 ] .Value [ 2 ] . @ year '' ) , FinModelValue2016 = ( string ) finModels.SelectToken ( `` Values [ 1 ] .Value [ 2 ] . # text '' ) , FinModelYear2017 = ( string ) finModels.SelectToken ( `` Values [ 1 ] .Value [ 3 ] . @ year '' ) , FinModelValue2017 = ( string ) finModels.SelectToken ( `` Values [ 1 ] .Value [ 3 ] . # text '' ) , } ; public static class JsonExtensions { public static IEnumerable < JToken > DescendantsAndSelf ( this JToken node ) { if ( node == null ) return Enumerable.Empty < JToken > ( ) ; var container = node as JContainer ; if ( container ! = null ) return container.DescendantsAndSelf ( ) ; else return new [ ] { node } ; } public static IEnumerable < JObject > ObjectsOrSelf ( this JToken root ) { if ( root is JObject ) yield return ( JObject ) root ; else if ( root is JContainer ) foreach ( var item in ( ( JContainer ) root ) .Children ( ) ) foreach ( var child in item.ObjectsOrSelf ( ) ) yield return child ; else yield break ; } public static IEnumerable < JToken > SingleOrMultiple ( this JToken source ) { IEnumerable < JToken > arr = source as JArray ; return arr ? ? new [ ] { source } ; } } XmlDocument doc = new XmlDocument ( ) ; doc.LoadXml ( xmlString ) ; jsonText = Newtonsoft.Json.JsonConvert.SerializeXmlNode ( doc ) ; JObject jsonFeed = JObject.Parse ( jsonText ) ;",LINQ to JSON - Setup list from dynamic nested array "C_sharp : I am attempting to get some custom objects from the CollectionChanged event of a collection which implements INotifyCollectionChanged.The problem I am facing is that myItems always says `` Enumeration yielded no results '' .Expanding on debug e.NewItems.SyncRoot shows the following : So clearly the data is there . What is the method for retrieving this data ? MyControl_MyCollectionChanged ( object sender , NotifyCollectionChangedEventArgs e ) { if ( e.Action == NotifyCollectionChangedAction.Add ) { lock ( e.NewItems.SyncRoot ) { var myItems = e.NewItems.OfType < MyType > ( ) ; if ( myItems.Any ( ) ) { //do stuff } } } } e.NewItems.SyncRoot | { object [ 1 ] } |- [ 0 ] | { System.Linq.Enumerable.WhereSelectListIterator < MyType , IMyInterface > } | |-base ... | |-Non-public members| |-Results View | Expanding the Results View ... | |- [ 0 ] | MyType",INotifyCollectionChanged 's NewItems - can not use OfType < T > to get data "C_sharp : There is a test that consists of 12 questions . each question must have a value greater than 4 points . all the question must add to 100. also all the questions must have an integer value . so a possible combination may be 5,5,5,5,5,5,5,5,5,5,5,45there is a method that theoretically will give this result : note that I created each loop for values less than 46 because if all questions must have a value greater than 4 it will be impossible for a question to be worth 50 points for example.EditSorry people I think I am not explaining my self clearly . I piked 12 questions as a random guess . This example may have been with a test with 100 questions . I need something like what dlev mentioned in his comment . I also know I can place breaks in the loops to make the method more efficient . if the sum is greater than 100 then why continue looping just brak out of the corresponding loop // this method will return the possible number of testspublic static double PosibleNumberOfTests ( ) { int q1 , q2 , q3 , q4 , q5 , q6 , q7 , q8 , q9 , q10 , q11 , q12 ; // each question value double counter=0 ; // if there is a valid combination then counter will be increased by 1 for ( q12 = 5 ; q12 < 46 ; q12++ ) { for ( q11 = 5 ; q11 < 46 ; q11++ ) { for ( q10 = 5 ; q10 < 46 ; q10++ ) { for ( q9 = 5 ; q9 < 46 ; q9++ ) { for ( q8 = 5 ; q8 < 46 ; q8++ ) { for ( q7 = 5 ; q7 < 46 ; q7++ ) { for ( q6 = 5 ; q6 < 46 ; q6++ ) { for ( q5 = 5 ; q5 < 46 ; q5++ ) { for ( q4 = 5 ; q4 < 46 ; q4++ ) { for ( q3 = 5 ; q3 < 46 ; q3++ ) { for ( q2 = 5 ; q2 < 46 ; q2++ ) { for ( q1 = 5 ; q1 < 46 ; q1++ ) { if ( q1 + q2 + q3 + q4 + q5 + q6 + q7 + q8 + q9 + q10 + q11 + q12 == 100 ) counter++ ; // here is what we need . How many times will this line be executed ! } } } } } } } } } } } } return counter ; }",How to determine how many times will a statement inside a loop will be executed with conditional statements "C_sharp : I have a code snippet : As described in a comment I can not terminate the For Loop directly from the Switch , only if I declare a boolean and at the End of Switch test PS : or maybe I 'm very confused ! [ POST ] I got the message , and the problem is Solved , but i would like to asume that using Switch within a for loop is n't a god idea , because i heard from lot of developer 's i should break from loop in the moment when i get the desired result , so using switch need 's extra boolean or push the Int i value to 50 direclty , but what would happen if we 're using while loop ? int n = 0 ; for ( int i = 0 ; i < 50 ; i++ ) { n = checkStatus ( ) ; switch ( n ) { case 1 : break ; break ; //This is unreachable and so i can not Terminate the For Loop within the SWITCH } } if ( LoopShouldTerminate ) break ;",Break inside switch Can not Terminate FOR Loop "C_sharp : I 'm designing an application to farm one of my games for me . However , The approach I 'm going with is to listen for a sound or spike in sound levels before running a desired macro combination . The audio I 'm looking to monitor is the current PC 's audio output , not a microphone or external device.This subject seem 's to be vary vague on tutorials or information , however from my knowledge I found a post here that explains to use a BuckSoft.DirectSound project ? So based on the information I found , I assume you do something like the following ? From personal prospective I would love to help clarify a solution to the public as this topic is not well documented and avoided . I 'm open to all solutions or suggestions , however , my focus is on vb.net and will consider C # if needed.Another option that I have seen is the CoreAudio API . I have seen this API used on multiple posts for the ability to extract the current sound levels , however I have not seen examples for reading the current Master VU meter and fader data/Levels.Data I 'm looking to gather : As showed bellow , I 'm NOT looking to gather the physical sound level % but rather looking to run actions if the VU levels spike from 0 . This means if I play a video or sound file , the application will hear a sound coming from the current work station and perform a desired action.Bellow will be my rough example of how I plan to use or collect data from my prospective . Using an timer within vb.net I can have an statement consistently looking for an change in `` VUSoundLevels '' ( Not a real statement ) and run a script when an change/input happens . If AnalogSignalMeter1.LeftLevel > 0 Or AnalogSignalMeter1.RightLevel > 0 Then ' Do SomethingEnd If Private Function GetVol ( ) As Integer 'Function to read current volume setting Dim MasterMinimum As Integer = 0 Dim DevEnum As New MMDeviceEnumerator ( ) Dim device As MMDevice = DevEnum.GetDefaultAudioEndpoint ( EDataFlow.eRender , ERole.eMultimedia ) Dim Vol As Integer = 0 With device.AudioEndpointVolume Vol = CInt ( .MasterVolumeLevelScalar * 100 ) If Vol < MasterMinimum Then Vol = MasterMinimum / 100.0F End If End With Return VolEnd Function Private Sub Timer1_Tick ( ) If VUSoundLevels > 0 Then ' Run Code & Exit Loop End IFEnd Sub",Run script based on sound VU level in vb.net "C_sharp : I know that we can < % : % > syntax for html encoding that is introduced in .Net 4 . But I was reading new features of Asp.Net 4.5 , and I got that we have another type i-e < % # : % > that is used for encoding the result of databind expression.I am confuse with this.Please explain both of them . What is the difference between < % : % > and < % # : % > in Asp.Net",Difference between < % : % > and < % # : % > in Asp.Net "C_sharp : I 've completed a OOP course assignment where I design and code a Complex Number class . For extra credit , I can do the following : Add two complex numbers . The function will take one complex number object as a parameter and return a complex number object . When adding two complex numbers , the real part of the calling object is added to the real part of the complex number object passed as a parameter , and the imaginary part of the calling object is added to the imaginary part of the complex number object passed as a parameter.Subtract two complex numbers . Thefunction will take one complexnumber object as a parameter andreturn a complex number object . Whensubtracting two complex numbers , thereal part of the complex numberobject passed as a parameter issubtracted from the real part of thecalling object , and the imaginarypart of the complex number objectpassed as a parameter is subtractedfrom the imaginary part of thecalling object.I have coded this up , and I used the this keyword to denote the current instance of the class , the code for my add method is below , and my subtract method looks similar : My question is : Did I do this correctly and with good style ? ( using the this keyword ) ? public ComplexNumber Add ( ComplexNumber c ) { double realPartAdder = c.GetRealPart ( ) ; double complexPartAdder = c.GetComplexPart ( ) ; double realPartCaller = this.GetRealPart ( ) ; double complexPartCaller = this.GetComplexPart ( ) ; double finalRealPart = realPartCaller + realPartAdder ; double finalComplexPart = complexPartCaller + complexPartAdder ; ComplexNumber summedComplex = new ComplexNumber ( finalRealPart , finalComplexPart ) ; return summedComplex ; }",C # using the `` this '' keyword in this situation ? "C_sharp : I have a panel MessagesPanel that contains messages which are retrieved from a database . I go over the messages using a foreach loop . In the loop , I call a function AddMessageToPanel which dynamically adds a GroupBox to the panel , with the message information and content . The messages are retrieved oldest to newest , top to down ( Like in WhatsApp ) . The panel is set to AutoScroll=true , and I want it to scroll to the very bottom to the newest message.I tried those solutions : autoscroll panel to bottomHow to Programmatically Scroll a PanelHow to scroll a panel manually ? None of them worked for me . The panel just looks the same , with the scroll bar at the top.In particular , I have tried the following codes : and I subscribe to it with the event ControlAdded.And also : With and without MessagesPanel.SuspendLayout ( ) ; Here is my function : I want the MessagesPanel to scroll all the way down . How to do this ? Thanks ! private void MessagePanel_ControlAdded ( object sender , ControlEventArgs e ) { MessagesPanel.ScrollControlIntoView ( e.Control ) ; } MessagesPanel.VerticalScroll.Value = MessagesPanel.VerticalScroll.Maximum private void AddMessageToPanel ( string sender , string datetime , string content ) { GroupBox groupBox = new GroupBox ( ) ; groupBox.Location = new Point ( 0 , 120 * MessagesPanel.Controls.Count ) ; groupBox.RightToLeft = RightToLeft.Yes ; groupBox.Size = new Size ( 500 , 100 ) ; groupBox.Text = string.Format ( `` { 0 } ( { 1 } ) '' , sender , datetime ) ; TextBox textBox = new TextBox ( ) ; textBox.Enabled = false ; textBox.BackColor = Color.White ; textBox.BorderStyle = BorderStyle.None ; textBox.Multiline = true ; textBox.Size = new Size ( 495 , 95 ) ; textBox.Location = new Point ( 0 , 20 ) ; textBox.Text = content ; groupBox.Controls.Add ( textBox ) ; MessagesPanel.Controls.Add ( groupBox ) ; }",How to scroll a panel to the bottom in c # ? "C_sharp : BackgroundI wanted to make a few integer-sized structs ( i.e . 32 and 64 bits ) that are easily convertible to/from primitive unmanaged types of the same size ( i.e . Int32 and UInt32 for 32-bit-sized struct in particular ) .The structs would then expose additional functionality for bit manipulation / indexing that is not available on integer types directly . Basically , as a sort of syntactic sugar , improving readability and ease of use.The important part , however , was performance , in that there should essentially be 0 cost for this extra abstraction ( at the end of the day the CPU should `` see '' the same bits as if it was dealing with primitive ints ) .Sample StructBelow is just the very basic struct I came up with . It does not have all the functionality , but enough to illustrate my questions : The TestI wanted to test the performance of this struct . In particular I wanted to see if it could let me get the individual bytes just as quickly if I were to use regular bitwise arithmetic : ( i > > 8 ) & 0xFF ( to get the 3rd byte for example ) .Below you will see a benchmark I came up with : The Byte1 ( ) , Byte2 ( ) , Byte3 ( ) , and Byte4 ( ) are just the extension methods that do get inlined and simply get the n-th byte by doing bitwise operations and casting : EDIT : Fixed the code to make sure variables are actually used . Also commented out 3 of 4 variables to really test struct casting / member access rather than actually using the variables.The ResultsI ran these in the Release build with optimizations on x64.EDIT : New results after fixing the code : QuestionsThe benchmark results were surprising for me , and that 's why I have a few questions : EDIT : Fewer questions remain after altering the code so that the variables actually get used.Why is the pointer stuff so slow ? Why is the cast taking twice as long as the baseline case ? Are n't implicit/explicit operators inlined ? How come the new System.Runtime.CompilerServices.Unsafe package ( v. 4.5.0 ) is so fast ? I thought it would at least involve a method call ... More generally , how can I make essentially a zero-cost struct that would simply act as a `` window '' onto some memory or a biggish primitive type like UInt64 so that I can more effectively manipulate / read that memory ? What 's the best practice here ? [ StructLayout ( LayoutKind.Explicit , Pack = 1 , Size = 4 ) ] public struct Mask32 { [ FieldOffset ( 3 ) ] public byte Byte1 ; [ FieldOffset ( 2 ) ] public ushort UShort1 ; [ FieldOffset ( 2 ) ] public byte Byte2 ; [ FieldOffset ( 1 ) ] public byte Byte3 ; [ FieldOffset ( 0 ) ] public ushort UShort2 ; [ FieldOffset ( 0 ) ] public byte Byte4 ; [ DebuggerStepThrough , MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static unsafe implicit operator Mask32 ( int i ) = > * ( Mask32* ) & i ; [ DebuggerStepThrough , MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static unsafe implicit operator Mask32 ( uint i ) = > * ( Mask32* ) & i ; } public unsafe class MyBenchmark { const int count = 50000 ; [ Benchmark ( Baseline = true ) ] public static void Direct ( ) { var j = 0 ; for ( int i = 0 ; i < count ; i++ ) { //var b1 = i.Byte1 ( ) ; //var b2 = i.Byte2 ( ) ; var b3 = i.Byte3 ( ) ; //var b4 = i.Byte4 ( ) ; j += b3 ; } } [ Benchmark ] public static void ViaStructPointer ( ) { var j = 0 ; int i = 0 ; var s = ( Mask32* ) & i ; for ( ; i < count ; i++ ) { //var b1 = s- > Byte1 ; //var b2 = s- > Byte2 ; var b3 = s- > Byte3 ; //var b4 = s- > Byte4 ; j += b3 ; } } [ Benchmark ] public static void ViaStructPointer2 ( ) { var j = 0 ; int i = 0 ; for ( ; i < count ; i++ ) { var s = * ( Mask32* ) & i ; //var b1 = s.Byte1 ; //var b2 = s.Byte2 ; var b3 = s.Byte3 ; //var b4 = s.Byte4 ; j += b3 ; } } [ Benchmark ] public static void ViaStructCast ( ) { var j = 0 ; for ( int i = 0 ; i < count ; i++ ) { Mask32 m = i ; //var b1 = m.Byte1 ; //var b2 = m.Byte2 ; var b3 = m.Byte3 ; //var b4 = m.Byte4 ; j += b3 ; } } [ Benchmark ] public static void ViaUnsafeAs ( ) { var j = 0 ; for ( int i = 0 ; i < count ; i++ ) { var m = Unsafe.As < int , Mask32 > ( ref i ) ; //var b1 = m.Byte1 ; //var b2 = m.Byte2 ; var b3 = m.Byte3 ; //var b4 = m.Byte4 ; j += b3 ; } } } [ DebuggerStepThrough , MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static byte Byte1 ( this int it ) = > ( byte ) ( it > > 24 ) ; [ DebuggerStepThrough , MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static byte Byte2 ( this int it ) = > ( byte ) ( ( it > > 16 ) & 0xFF ) ; [ DebuggerStepThrough , MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static byte Byte3 ( this int it ) = > ( byte ) ( ( it > > 8 ) & 0xFF ) ; [ DebuggerStepThrough , MethodImpl ( MethodImplOptions.AggressiveInlining ) ] public static byte Byte4 ( this int it ) = > ( byte ) it ; Intel Core i7-3770K CPU 3.50GHz ( Ivy Bridge ) , 1 CPU , 8 logical cores and 4 physical coresFrequency=3410223 Hz , Resolution=293.2360 ns , Timer=TSC [ Host ] : .NET Framework 4.6.1 ( CLR 4.0.30319.42000 ) , 64bit RyuJIT-v4.6.1086.0 DefaultJob : .NET Framework 4.6.1 ( CLR 4.0.30319.42000 ) , 64bit RyuJIT-v4.6.1086.0 Method | Mean | Error | StdDev | Scaled | ScaledSD | -- -- -- -- -- -- -- -- -- | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- - : | -- -- -- -- - : | Direct | 14.47 us | 0.3314 us | 0.2938 us | 1.00 | 0.00 | ViaStructPointer | 111.32 us | 0.6481 us | 0.6062 us | 7.70 | 0.15 | ViaStructPointer2 | 102.31 us | 0.7632 us | 0.7139 us | 7.07 | 0.14 | ViaStructCast | 29.00 us | 0.3159 us | 0.2800 us | 2.01 | 0.04 | ViaUnsafeAs | 14.32 us | 0.0955 us | 0.0894 us | 0.99 | 0.02 | Method | Mean | Error | StdDev | Scaled | ScaledSD | -- -- -- -- -- -- -- -- -- | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- - : | -- -- -- -- - : | Direct | 57.51 us | 1.1070 us | 1.0355 us | 1.00 | 0.00 | ViaStructPointer | 203.20 us | 3.9830 us | 3.5308 us | 3.53 | 0.08 | ViaStructPointer2 | 198.08 us | 1.8411 us | 1.6321 us | 3.45 | 0.06 | ViaStructCast | 79.68 us | 1.5478 us | 1.7824 us | 1.39 | 0.04 | ViaUnsafeAs | 57.01 us | 0.8266 us | 0.6902 us | 0.99 | 0.02 |","Why is casting a struct via Pointer slow , while Unsafe.As is fast ?" "C_sharp : Why do the following lines of code not create a compiler warning ? As I see it , the compiler should inform you that the second throw exception can not be reached . void Main ( ) { throw new Exception ( ) ; throw new Exception ( ) ; }",Why does throwing 2 exceptions in a row not generate an unreachable code warning ? "C_sharp : I am trying to add integer to Arabic string but no successoutput : سُوْرَةُ الْفَاتِحَة-1Desired output : I want the integer on the right side .Update : Am displaying this result in ListBox in visual studio by using Items.Insert ( ) Method , so if anyone know to tweak ListBox then kindly share I mean if ListBox display Numbers 1 2 3 4 with each row ? // Arabic String Astr = `` سُوْرَةُ الْفَاتِحَة '' ; // String with Integer -1num = `` - '' +1 ; // Adding Stringsr = Astr + num ; r = num + Astr ; سُوْرَةُ الْفَاتِحَة‎-1",Insert integer to Arabic String in Start "C_sharp : I have the following C # code in my ASP.NET MVC application . I try to compare 2 string using the Equals method , with culture = `` vi '' . My code below : Results : CCC = false ; xx = true ; zz = true ; I do n't know why CCC is false . Is there anything wrong ? If I set culture = id , ko , en , etc ... then CCC = true . Who can help me ? string culture = `` vi '' ; System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo ( culture ) ; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture ; var CCC = string.Equals ( `` CategId '' , `` CATEGID '' , StringComparison.CurrentCultureIgnoreCase ) ; var xx = string.Equals ( `` TestGID '' , `` TestGID '' , StringComparison.CurrentCultureIgnoreCase ) ; var zz = string.Equals ( `` id '' , `` ID '' , StringComparison.CurrentCultureIgnoreCase ) ;",String.Equals GID returning false ? "C_sharp : I am trying to convert the following 2 methods into c # without the .net compiler complaining at me . Quite frankly I just do n't understand how the two methods are really working behind the scenes . So an answer and explanation would be great here.The second method is particularly confusing because of the shift operator being used that is different that the first method.Thanks in advance for any help . public static int bytesToInt ( byte b0 , byte b1 , byte b2 , byte b3 ) { return ( ( ( int ) b0 < < 24 ) & 0xFF000000 ) | ( ( ( int ) b1 < < 16 ) & 0x00FF0000 ) | ( ( ( int ) b2 < < 8 ) & 0x0000FF00 ) | ( ( int ) b3 & 0x000000FF ) ; } public static byte [ ] charToBytes ( char c ) { byte [ ] result = new byte [ 2 ] ; result [ 0 ] = ( byte ) ( ( c > > > 8 ) & 0x00FF ) ; result [ 1 ] = ( byte ) ( ( c > > > 0 ) & 0x00FF ) ; return result ; }",Converting java method to C # : converting bytes to integers with bit shift operators "C_sharp : Taking into account a 5x5 grid , it requires all possible combinations of knights moves to be recorded , from every single starting square , via every subsequent square.I envisaged it as being a binary tree like structure , but as each square on the board can have more than 2 potential next moves , I do n't think it would work . I looked into A*/Pathfinding algorithms , but they all require an end node to work with from what I can see , and I do n't know the end node as it is on going every time and would be different.My pseudocode thus far is : Any advice/pointers would be greatly appreciated as I am very lost ! For each square on the board Check if this key has potential moves If Potential moves < Some way of selecting a next move ( this could be the square we just originated from too ! ) > Register this move into a collection we can check against for subsequent moves Recursively call function with the square we just landed on Else ContinueEnd",Recursive tree search "C_sharp : I have a problem with selecting a string collection and have reproduced it with the following small example.Given the following SQL : And the code ( I used LINQPad ) : The first assert passes and this , in my mind , validates my mapping of the categories onto the post.The query in the try block throws an exceptionSo I 've changed it to the 3rd attempt you see in the code , calling .ToList ( ) .First ( ) . This query does not throw any exception but the categories list is returned empty.Am I doing something wrong ? Is there a better mapping technique to use here ? Or are there workarounds to get my query working ? CREATE TABLE [ Post ] ( [ Id ] INT IDENTITY NOT NULL , [ Name ] NVARCHAR ( 20 ) NOT NULL , CONSTRAINT [ PK_Post ] PRIMARY KEY CLUSTERED ( [ Id ] ) ) CREATE TABLE [ Category ] ( [ Id ] INT IDENTITY NOT NULL , [ PostId ] INT NOT NULL , [ Name ] NVARCHAR ( 20 ) NOT NULL , CONSTRAINT [ FK_Category_Post ] FOREIGN KEY ( [ PostId ] ) REFERENCES [ Post ] ( [ Id ] ) ) INSERT INTO [ Post ] ( [ Name ] ) VALUES ( 'Post 1 ' ) INSERT INTO [ Category ] ( [ PostId ] , [ Name ] ) VALUES ( 1 , 'Alpha ' ) void Main ( ) { using ( var sessionFactory = Fluently.Configure ( ) .Database ( MsSqlConfiguration.MsSql2008.Dialect < MsSql2012Dialect > ( ) .ConnectionString ( @ '' Data Source= ( localdb ) \Projects ; Initial Catalog=NhTest ; '' ) ) .Mappings ( x = > { x.FluentMappings.Add ( typeof ( PostMap ) ) ; } ) .BuildSessionFactory ( ) ) using ( var session = sessionFactory.OpenSession ( ) ) { var post = session.Get < Post > ( 1 ) ; Debug.Assert ( post.Categories.First ( ) == `` Alpha '' ) ; try { var second = session.Query < Post > ( ) .Where ( x = > x.Id == 1 ) .Select ( x = > new { x.Categories , x.Name , } ) .Single ( ) ; } catch ( Exception ex ) { Debug.Fail ( ex.ToString ( ) ) ; } var third = session.Query < Post > ( ) .Where ( x = > x.Id == 1 ) .Select ( x = > new { x.Categories , x.Name , } ) .ToList ( ) .First ( ) ; Debug.Assert ( third.Categories.Count ( ) == 1 , `` Category count was `` + third.Categories.Count ( ) ) ; } } // Define other methods and classes hereclass Post { public virtual int Id { get ; protected set ; } public virtual string Name { get ; protected set ; } public virtual IList < string > Categories { get ; protected set ; } } class PostMap : ClassMap < Post > { public PostMap ( ) { Id ( x = > x.Id ) ; Map ( x = > x.Name ) ; HasMany ( x = > x.Categories ) .Table ( `` Category '' ) .Element ( `` Name '' ) .KeyColumn ( `` PostId '' ) ; } } 'System.Linq.EnumerableQuery ` 1 [ System.Collections.Generic.IList ` 1 [ System.String ] ] ' can not be converted to type 'System.Linq.IQueryable ` 1 [ System.Object [ ] ]",NHibernate querying on a string collection using Linq results in either error or empty collection "C_sharp : I tried this one : And I declared the function like this : In edmx file I have this : But Entity Framework throws the exception that the query can not be constructed . This error I receive : The specified method 'System.String GetProvinceCodeByLatLong ( Double , Double ) ' on the type 'Infrastructure.CustomRepositories.AssetDataRepository ' can not be translated into a LINQ to Entities store expression GetProvinceCodeByLatLong ( a.Latitude , a.Longitude ) [ DbFunction ( `` Core.Models '' , `` fn_GetProvinceCodeByLatLong '' ) ] public static string GetProvinceCodeByLatLong ( double latitude , double longitude ) { throw new NotSupportedException ( `` Direct calls are not supported . `` ) ; } < Function Name= '' fn_GetProvinceCodeByLatLong '' ReturnType= '' varchar '' Aggregate= '' false '' BuiltIn= '' false '' NiladicFunction= '' false '' IsComposable= '' true '' ParameterTypeSemantics= '' AllowImplicitConversion '' Schema= '' dbo '' > < Parameter Name= '' latitude '' Type= '' float '' Mode= '' In '' / > < Parameter Name= '' longitude '' Type= '' float '' Mode= '' In '' / > < /Function >",Is it possible to call T-SQL function in Entity Framework and LINQ ? C_sharp : Can I use ApprovalTests with PDF 's ? I tried using the FileLauncher but it seems the identical PDF 's are slightly different at file ( bit ) level . Or did I use it wrongly ? [ TestMethod ] [ UseReporter ( typeof ( FileLauncherReporter ) ) ] public void TestPdf ( ) { var createSomePdf = PdfCreate ( ) ; ApprovalTests.Approvals.Verify ( new FileInfo ( createSomePdf.FileName ) ) ; },Approvaltests and PDF "C_sharp : I 'm using FakeItEasy to fake some Entity Framework calls , to make sure a bunch of weird legacy database tables are getting mapped properly.I need to assert that a Customer with an Invoice matching a specific DeliveryAddress is being added to the database.If I do this : the code works perfectly . I want to streamline the syntax by moving the expectation elsewhere , but when i do this : The test fails . What is happening inside the FakeItEasy code that means the expectation expression works when it 's inline but ca n't be captured in a variable and reused later ? A.CallTo ( ( ) = > db.Customers.Add ( A < Customer > .That.Matches ( c = > c.Invoices.First ( ) .Address == EXPECTED_ADDRESS ) ) ) ) .MustHaveHappened ( ) ; var expected = A < Customer > .That.Matches ( c = > c.Invoices.First ( ) .Address == EXPECTED_ADDRESS ) ) ; A.CallTo ( ( ) = > db.Customers.Add ( expected ) ) .MustHaveHappened ( ) ;",Why ca n't I capture a FakeItEasy expectation in a variable ? "C_sharp : Is there any way that I could specify at runtime the configuration file I would like to use ( other than App.config ) ? For example I would like to read a first argument from a command line that will be a path to the application 's config and I would like my application to refer to it when I use ConfigurationManager.AppSettings ( It 's probably impossible but still it 's worth asking ) .I did find this piece of code : It works , but it overrides the original App.config 's AppSettings section and my application is n't supposed to write anything . System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration ( ConfigurationUserLevel.None ) ; config.AppSettings.File = myRuntimeConfigFilePath ; config.Save ( ConfigurationSaveMode.Modified ) ; ConfigurationManager.RefreshSection ( `` appSettings '' ) ;",.NET own configuration file "C_sharp : I want to add text to a custom tag , to an MP3-file . I tried doing like this , but I ca n't get the tag to change.This is my code for now : I get the album tag to change , but not the albumtype tag . Am I missing something ? TagLib.File f = TagLib.File.Create ( @ '' C : \Users\spunit\Desktop\denna.mp3 '' ) ; TagLib.Id3v2.Tag t = ( TagLib.Id3v2.Tag ) f.GetTag ( TagTypes.Id3v2 ) ; PrivateFrame p = PrivateFrame.Get ( t , `` albumtype '' , true ) ; p.PrivateData = System.Text.Encoding.Unicode.GetBytes ( `` TAG CHANGED '' ) ; f.Tag.Album = `` test '' ; f.Save ( ) ;",Add custom tag in tagLib sharp "C_sharp : Here 's the situation : I am trying to launch an application , but the location of the .exe is n't known to me . Now , if the file extension is registered ( in Windows ) , I can do something like : However , I need to pass some command line arguments as well . I could n't get this to workAny suggestions on a mechanism to solve this ? Edit @ akuMy StackOverflow search skills are weak ; I did not find that post . Though I generally dislike peering into the registry , that 's a great solution . Thanks ! Process.Start ( `` Sample.xls '' ) ; Process p = new Process ( ) ; p.StartInfo.FileName = `` Sample.xls '' ; p.StartInfo.Arguments = `` /r '' ; // open in read-only mode p.Start ( ) ;",Launch a file with command line arguments without knowing location of exe ? "C_sharp : I have previously asked a question on how to Selecting dynamically created Listboxs items in C # which was answered . The problem now is that when the listbox gets the focus when popped up ! I ca n't continue typing unless I either select an item or press Esc , which I have explicitly defined to set focus back to my TextBox.The irony is that I have a condition in my KeyDown event which says if the UP or Down arrow keys are pressed , set the focus on ListBox so that user can choose an item , but do n't transfer the focus so that user can continue typing freely.Just like what we have on Visual Studio , when a user presses a dot , he is not blocked and forced to choose an item form the Intellisense list , but he can continue typing and or at any time use arrow keys UP or Down to select the proper item . I ca n't achieve the same functionality using the code below . How can I get this to work as mentioned ? I need to say that using ActiveControl , and transferFocus , using this.Focus ( ) prior to lst.Focus ( ) , disabling and enabling textbox they all did n't work ! private void txtResults_KeyDown ( object sender , KeyEventArgs e ) { string [ ] words= ( ( TextBox ) sender ) .Text.Split ( ' ' ) ; string s = sampleWord.Text = words [ words.Length - 1 ] ; if ( e.KeyCode == Keys.OemPeriod ) { ShowPopUpList ( s ) ; lst.Focus ( ) ; //This transfers the focus to listbox but then prevents user //from being able to type anymore unless he/she chooses an item ! } else if ( e.KeyCode == Keys.Down || e.KeyCode == Keys.Up ) { lst.Focus ( ) ; //doesnt work : -/ } else { lst.Hide ( ) ; txtResults.Focus ( ) ; } }",Ca n't get focus on dynamically created listbox in C # "C_sharp : UPDATE : I should have mentioned in the original post that I want to learn more about generics here . I am aware that this can be done by modifying the base class or creating an interface that both document classes implement . But for the sake of this exercise I 'm only really interested in solutions that do not require any modification to the document classes or their base class . I thought that the fact that the question involves extension methods would have implied this.I have written two nearly identical generic extension methods and am trying to figure out how I might refactor them into a single method . They differ only in that one operates on List and the other on List , and the properties I 'm interested in are AssetID for AssetDocument and PersonID for PersonDocument . Although AssetDocument and PersonDocument have the same base class the properties are defined in each class so I do n't think that helps . I have triedthinking I might then be able to test the type and act accordingly but this results in the syntax error Type parameter 'T ' inherits conflicting constraintsThese are the methods that I would like to refactor into a single method but perhaps I am simply going overboard and they would best be left as they are . I 'd like to hear what you think . public static string ToCSVList < T > ( this T list ) where T : List < PersonDocument > , List < AssetDocument > public static string ToCSVList < T > ( this T list ) where T : List < AssetDocument > { var sb = new StringBuilder ( list.Count * 36 + list.Count ) ; string delimiter = String.Empty ; foreach ( var document in list ) { sb.Append ( delimiter + document.AssetID.ToString ( ) ) ; delimiter = `` , '' ; } return sb.ToString ( ) ; } public static string ToCSVList < T > ( this T list ) where T : List < PersonDocument > { var sb = new StringBuilder ( list.Count * 36 + list.Count ) ; string delimiter = String.Empty ; foreach ( var document in list ) { sb.Append ( delimiter + document.PersonID.ToString ( ) ) ; delimiter = `` , '' ; } return sb.ToString ( ) ; }",How to refactor these generic methods ? "C_sharp : How to check control types in switch case statement ? Following is error in above statement : 'Textbox ' is a type , which is not valid in the given context Private void CheckControl ( Control ctl ) { switch ( ctl ) { case TextBox : MessageBox.Show ( `` This is My TextBox '' ) ; break ; case Label : MessageBox.Show ( `` This is My Label '' ) ; break ; } }",How to check control Type in Switch Case "C_sharp : I 'm trying to convert this C # method into PHP . What does the out in the second parameter mean ? public static bool Foo ( string name , out string key )",C # out keyword meaning and does it have an equivalent in PHP ? "C_sharp : Why does it shows question marks on the message box instead of text HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( `` http : //teamxor.net/vb/tx48/ '' + page ) ; HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ; StreamReader sr = new StreamReader ( response.GetResponseStream ( ) ) ; string result = sr.ReadToEnd ( ) ; Regex r = new Regex ( `` < div > . * ? < /div > '' ) ; MatchCollection mr = r.Matches ( result ) ; foreach ( Match m in mr ) { MessageBox.Show ( m.Value , `` Test '' , MessageBoxButtons.OK , MessageBoxIcon.Information , MessageBoxDefaultButton.Button1 , MessageBoxOptions.RtlReading ) ; }",Why does it show question marks on the message box instead of text "C_sharp : I have been trying to figure out how to cover my internal function that is used as call back when getting item from a cache . I have a CacheService that accepts key and Func . The Func is called when the item is not in cache.This sample code was based from anothe suggestion here in SO , but the cacheService.Get method always returns null and the WhenCalled was never called.I understand its debatable whethere I should cover this internal method , but for start im trying possible way to cover this without creating a new class just for this internal methods . Appreciated your help.CacheService.csSomeService.csSomeServiceTest.cs public T Get < T > ( string key , Func < T > funcWhenNotExist ) { if ( ! Exists ( key ) ) { var result = funcWhenNotExist ( ) ; Cache.Put ( key , result ) ; } return DoSomethingWithRetry ( ( ) = > ( T ) Cache.Get ( key ) , MAXRETRY ) ; } public SomeDto GetSomeDto ( string dtoAlias ) { string cacheKey = `` whatever '' ; var someDto = cacheService.Get ( cacheKey , ( ) = > GetSomeDtoInternal ( dtoAlias ) ) ; return someDto } internal SomeDto GetSomeDtoInternal ( string dtoAlias { //do more here } // Arrange SomeDto stubResult = new SomeDto ( ) ; cacheService.Stub ( s = > s.Get ( Arg < string > .Is.Anything , Arg < Func < SomeDto > > .Is.Anything ) ) .WhenCalled ( m = > { var func = ( Func < SomeDto > ) m.Arguments [ 1 ] ; stubResult = func ( ) ; } ) .Return ( stubResult ) ; // Act var result = service.GetSomeDto ( `` whateveralias '' ) ;",Unit testing callback function Func < T > in RhinoMocks "C_sharp : string to build up using keyvaluepair is like this : `` name1=v1 & name2=v2 & name3=v3 '' what i am doing : any elegant way to avoid the last removal statement of ' & ' sign ? var sb = new StringBuilder ( ) ; foreach ( var name in nameValues ) { sb.AppendFormat ( `` { 0 } = { 1 } & '' , name.Key , name.Value ) ; } //remove last ' & ' sign , this is what i think is uglysb.ToString ( ) .Remove ( lastIndex ) ;",an elegant way to build the string in c # "C_sharp : I am writing a continuous polling loop to watch for some events to happen and then take some action on UI thread.I am writing following codeThe do while loop does not have any code now , because I want to test that if i run a loop infinitely the UI does not block , however , it is not working as expected and when the code runs this loop ( which will never return ) the UI freezes and becomes unresponsive untill i break the run.What should i do to make it run silently in the background , Note : the parent from where this method is called is a Web browser controlsdocumentcompelte ` event . The web browser control is inside windows forms application . public static void HandlePopup ( this HostedControl control , string className , string caption , System.Action callback ) { var popupTask = Task.Factory.StartNew ( ( ) = > { Thread.Sleep ( 5000 ) ; // just wait for 5 seconds . } , CancellationToken.None , TaskCreationOptions.None , TaskScheduler.Default ) .ContinueWith ( ( prevTask ) = > { AutomationElementCollection collection = null ; do { } while ( true ) ; } , CancellationToken.None , TaskContinuationOptions.None , TaskScheduler.FromCurrentSynchronizationContext ( ) ) .ContinueWith ( ( prevTask ) = > { if ( ! prevTask.IsFaulted ) { if ( control.InvokeRequired ) { control.Invoke ( callback ) ; } else { callback ( ) ; } } } , CancellationToken.None , TaskContinuationOptions.None , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ; try { ////popupTask.Wait ( ) ; } catch ( AggregateException ex ) { ex.Handle ( exnew = > { return true ; } ) ; } }",Task continuation blocking UI thread "C_sharp : I 'm running ASP.NET 5 ( Core ) with IIS 7.5 . I 've already installed httpPlatformHandler and set the physical path of the site ( in IIS ) to the wwwroot folder that I published from visual studio 2015 . All I get is the blank continuous loading page . I am pretty sure I have everything wired up correctly . Also , it loads up fine if I uncomment out the app.Run statement from within the Configure method and comment out the app.UseIISPlatformHandler , app.UseDefaultFiles , app.UseStaticFiles and app.UseMVC.My Code is below . I do n't know what else to do at this point . Any suggestions ? If any other code snippets are needed , let me know.Startup.cs ( Configure method ) web.configNew Edit . I 've updated my folder structure to MVC ( using Controllers , Views , etc ) and I 've changed the Configure method a bit . Now it loads a blank screen and the console is logging a 404 not found . Anymore suggestions ? Adding my full Startup.cs : public void Configure ( IApplicationBuilder app , ILoggerFactory loggerFactory ) { app.UseIISPlatformHandler ( ) ; app.UseDefaultFiles ( ) ; app.UseStaticFiles ( ) ; app.UseMvc ( ) ; //app.Run ( async ( context ) = > // { // var greeting = greeter.GetGreeting ( ) ; // await context.Response.WriteAsync ( greeting ) ; // } ) ; } < system.webServer > < handlers > < add name= '' httpPlatformHandler '' path= '' * '' verb= '' * '' modules= '' httpPlatformHandler '' resourceType= '' Unspecified '' / > < /handlers > < httpPlatform processPath= '' % DNX_PATH % '' arguments= '' % DNX_ARGS % '' stdoutLogEnabled= '' false '' startupTimeLimit= '' 3600 '' forwardWindowsAuthToken= '' true '' / > public IConfiguration Configuration { get ; set ; } public static string ConnectionString { get ; set ; } public Startup ( ) { var builder = new ConfigurationBuilder ( ) .AddJsonFile ( `` appsetting.json '' ) .AddEnvironmentVariables ( ) ; Configuration = builder.Build ( ) ; ConnectionString = Configuration.GetSection ( `` connString '' ) .Value ; } // This method gets called by the runtime . Use this method to add services to the container . // For more information on how to configure your application , visit http : //go.microsoft.com/fwlink/ ? LinkID=398940 public void ConfigureServices ( IServiceCollection services ) { services.AddMvc ( ) ; } // This method gets called by the runtime . Use this method to configure the HTTP request pipeline . public void Configure ( IApplicationBuilder app , ILoggerFactory loggerFactory ) { app.UseIISPlatformHandler ( ) ; //app.UseDefaultFiles ( ) ; app.UseFileServer ( true ) ; app.UseMvc ( routes = > { routes.MapRoute ( name : `` default '' , template : `` { controller=Home } / { action=Index } '' ) ; } ) ; } // Entry point for the application . public static void Main ( string [ ] args ) = > WebApplication.Run < Startup > ( args ) ;",Why does my ASP.NET 5 Application Not Run On IIS 7.5 ? "C_sharp : IIS 7.5 / Windows Server 2008 R2Multiple IIS sites bound to the same IP address , using host names . Inbound traffic to sites working fine . Outbound web requests made by the back-end site code fail . Remote site returns 404 ( NotFound ) . Verified via a network trace that the traffic is making it to the remove server.Same requests work fine if done from a site using a dedicated IP address ( i.e . not shared w/ any other sites ) .Anyone have any ideas on how to make this work or what could be going wrong ? Network trace on hosting server : Successful request from site w/ non-shared IP address : Failed request from site using a shared IP address : Code : No . Time Source Destination Protocol Info 6366 15:54:35.590463 192.168.1.76 173.194.77.121 HTTP GET /key/value/one/two HTTP/1.1 6369 15:54:35.599879 173.194.77.121 192.168.1.76 TCP http > 55407 [ ACK ] Seq=1 Ack=110 Win=344 Len=0 6370 15:54:35.621587 173.194.77.121 192.168.1.76 HTTP HTTP/1.1 200 OK ( application/json ) 6608 15:54:35.815774 192.168.1.76 173.194.77.121 TCP 55407 > http [ ACK ] Seq=110 Ack=357 Win=509 Len=0 No . Time Source Destination Protocol Info 9720 15:54:39.244192 192.168.1.80 173.194.77.121 HTTP GET /key/value/one/two HTTP/1.1 9760 15:54:39.256958 173.194.77.121 192.168.1.80 TCP [ TCP segment of a reassembled PDU ] 9761 15:54:39.256962 173.194.77.121 192.168.1.80 HTTP HTTP/1.1 404 Not Found ( text/html ) 9762 15:54:39.257027 192.168.1.80 173.194.77.121 TCP 55438 > http [ ACK ] Seq=212 Ack=1676 Win=512 Len=0 public static HttpWebRequest CreateWebRequest ( string url , string method = `` GET '' , string referer = null , string contentType = null , int timeout = 100000 , string authentication = null , string bindToIpAddress = null , string host = null ) { var request = ( HttpWebRequest ) WebRequest.Create ( url ) ; if ( ! string.IsNullOrWhiteSpace ( bindToIpAddress ) ) { IPAddress bindIp ; if ( ! IPAddress.TryParse ( bindToIpAddress , out bindIp ) ) { throw new ArgumentException ( `` bindToIpAddress '' ) ; } request.ServicePoint.BindIPEndPointDelegate = ( ( sp , rep , rc ) = > { return new IPEndPoint ( bindIp , 0 ) ; } ) ; } request.Accept = `` */* '' ; request.ContentType = contentType ; request.Referer = referer ; request.Method = method ; request.Timeout = timeout ; if ( ! string.IsNullOrWhiteSpace ( host ) ) { request.Host = host ; } return request ; } string GetData ( ) { try { string result ; var request = CreateWebRequest ( `` http : //jsonplaceholder.typicode.com/posts/1 '' , `` GET '' , `` somedomain.com '' , timeout : ( 10 * 1000 ) , bindToIpAddress : `` 192.168.27.133 '' /*site IP*/ ) ; request.Accept = `` application/json '' ; using ( var response = request.GetResponse ( ) ) { using ( var sr = new StreamReader ( response.GetResponseStream ( ) ) ) { result = sr.ReadToEnd ( ) ; } } return result ; } catch ( Exception ex ) { return null ; } }",outbound web requests fail when made from IIS sites using shared IP address "C_sharp : In C # we have .Net class and the short names , like Double and double . I was suggested sometime back that we shall use the short name always , wanted to know why . I know they both are same , but why one is sometimes preferred over others ? Just readability or is there something more to it ? For example if I am creating a Class having a string and a boolean properties , which of the following should be used always and when the other should be used : OR Class MyClass { ... private String x ; private Boolean y ; ... } Class MyClass { ... private string x ; private bool y ; ... }","Best Practices : What to use , .Net Class or short name ?" "C_sharp : I have a webpage , in which there is a sort that I have to order the list by Chinese strokes.I have created an application containing code like this : but there is an error : At least one object must implement IComparable.What does this mean and how can I fix it ? List < Student > stuList = new List < Student > ( ) { new Student ( `` 上海 '' ) , new Student ( `` 深圳 '' ) , new Student ( `` 广州 '' ) , new Student ( `` 香港 '' ) } ; System.Globalization.CultureInfo strokCi = new System.Globalization.CultureInfo ( `` zh-tw '' ) ; System.Threading.Thread.CurrentThread.CurrentCulture = strokCi ; ; //stuList.sort ( ) ;",c # List < T > Sort : by Chinese strokes "C_sharp : I just came across a bug in NHibernate which happens to already be raised : https : //nhibernate.jira.com/browse/NH-2763I 'm not sure if this applies to anything else other than enums but when using a Lambda from VB , it looks different to the same Lambda from C # .C # : VBThey are the same as far as I 'm aware ? ( My VB is n't great ) If I put a break point on the same line of code , where the above code is passed into . In C # I get : On the same line when VB version is passed in , I get : Is this something I 'm doing wrong ? Is the result 's the same , just displayed different between C # /VB ? Edit : Ok so they are displayed different , but they ca n't be the same because NHibernate can not handle it . The C # version is handled perfectly fine by NHibernate , the VB version resolves in the following exception being thrown : The NHibernate StackTrace : So something must be different between the two ? Edit 2 : For Jonathan . This is the method where the expression is used : Where ( x = > x.Status == EmployeeStatus.Active ) Where ( Function ( x ) x.Status = EmployeeStatus.Active ) at NHibernate.Impl.ExpressionProcessor.FindMemberExpression ( Expression expression ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Impl\ExpressionProcessor.cs : line 168 at NHibernate.Impl.ExpressionProcessor.ProcessSimpleExpression ( Expression left , Expression right , ExpressionType nodeType ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Impl\ExpressionProcessor.cs : line 323 at NHibernate.Impl.ExpressionProcessor.ProcessSimpleExpression ( BinaryExpression be ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Impl\ExpressionProcessor.cs : line 316 at NHibernate.Impl.ExpressionProcessor.ProcessBinaryExpression ( BinaryExpression expression ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Impl\ExpressionProcessor.cs : line 418 at NHibernate.Impl.ExpressionProcessor.ProcessExpression ( Expression expression ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Impl\ExpressionProcessor.cs : line 486 at NHibernate.Impl.ExpressionProcessor.ProcessExpression [ T ] ( Expression ` 1 expression ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Impl\ExpressionProcessor.cs : line 504 at NHibernate.Criterion.QueryOver ` 2.Add ( Expression ` 1 expression ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Criterion\QueryOver.cs : line 635 at NHibernate.Criterion.QueryOver ` 2.NHibernate.IQueryOver < TRoot , TSubType > .Where ( Expression ` 1 expression ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Criterion\QueryOver.cs : line 686 at *removed*.EmployeeRepository.GetByEntityId ( Int64 entityId , Expression ` 1 basicCriteria ) in D : \*removed*\EmployeeRepository.cs : line 76 public IEnumerable < Employee > GetByEntityId ( long entityId , Expression < Func < Employee , bool > > basicCriteria ) { IEnumerable < Employee > result ; using ( var tx = Session.BeginTransaction ( ) ) { var employeeQuery = Session.QueryOver < Employee > ( ) .Where ( x = > x.EntityId == entityId ) ; if ( basicCriteria ! = null ) employeeQuery = employeeQuery.Where ( basicCriteria ) ; result = employeeQuery.List ( ) ; tx.Commit ( ) ; } return result ; }",Why do lambda expressions in VB differ from C # ? "C_sharp : tl ; drWhat is the EzAPI code to use an OLE DB Source with data access mode of `` SQL command from variable '' and assign a variable ? PreambleOnce a month , we need to refresh our public test site with subsets of production data . We have determined that for our needs , an SSIS solution provides the best fit for accomplishing this task.My goal is to systematically build a large number ( 100+ ) of `` replication '' packages . EzAPI is a friendly wrapper to the SSIS object model and it seems like a great way to save mouse-clicks.I would like for my packages to look likeVariable - `` tableName '' ; [ Schema ] . [ TableName ] Variable - `` sourceQuery '' ; SELECT * FROM [ Schema ] . [ TableName ] DataFlow - `` Replicate Schema_TableName '' OLE DB Source - `` Src Schema_TableName '' ; Data Access Mode : SQL command from variable ; Variable name : User : :sourceQueryOLE DB Destination - `` Dest Schema_TableName '' ; Table or view name variable- fast load ; Variable name - User : :tableNameCodeThis is the code for my table to table replication package . Invocation looks like TableToTable s2 = new TableToTable ( @ '' localhost\localsqla '' , `` AdventureWorks '' , `` [ HumanResources ] . [ Department ] '' , @ '' localhost\localsqlb '' ) ; and that builds a package that does what I want except for using a variable in the source . ProblemThe above code supplies the access mode as SQL Query and the query is embedded in the OLE Source . The desire it to use `` SQL Command From Variable '' and that variable being @ [ User : :sourceQuery ] What I 'm stuck on is using a variable in the source . It should be a simple matter of assigning something likeThis results in the correct data access mode selected but the variable is n't populated.You can observe that I perform a similar step in the destination which does accept the variable and works `` right . `` What does n't workListing out the permutations I 've attemptedResults in Data Access Mode set to Table or View and name of table or the view is blank.Results in Data Access Mode set to `` Table or view name variable '' and variable name is sourceQuery . Very close to what I want , except the access mode is not correct . Were this package to run , it 'd blow up as the OpenRowSet would expect a straight table name.Results in Data Access Mode set to `` SQL Command '' and the SQL command text is `` User : :sourceQuery '' That 's the literal value of the variable name so it 's the right thing but since the access mode is wrong , it does n't work.Niether of these are correct access modes as they are for destinations ( I still tried them but they did n't work as expected ) .At this point , I thought I 'd try to work backwards by creating a package that has the OLE DB source defined as I want it and then inspect the source object 's properties.My code has set both SqlCommand and DataSourceVarible with the variable 's qualified name . I 've pulled down changeset 65381 and compiled that ( after fixing some references to the SQL Server 2012 dlls ) in hopes there might have been a fix since the Dec 30 2008 Stable build but to no avail.Have I found a bug in their code or am I just missing something ? using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using Microsoft.SqlServer.SSIS.EzAPI ; using Microsoft.SqlServer.Dts.Runtime ; namespace EzApiDemo { public class TableToTable : EzSrcDestPackage < EzOleDbSource , EzSqlOleDbCM , EzOleDbDestination , EzSqlOleDbCM > { public TableToTable ( Package p ) : base ( p ) { } public static implicit operator TableToTable ( Package p ) { return new TableToTable ( p ) ; } public TableToTable ( string sourceServer , string database , string table , string destinationServer ) : base ( ) { string saniName = TableToTable.SanitizeName ( table ) ; string sourceQuery = string.Format ( `` SELECT D.* FROM { 0 } D '' , table ) ; // Define package variables this.Variables.Add ( `` sourceQuery '' , false , `` User '' , sourceQuery ) ; this.Variables.Add ( `` tableName '' , false , `` User '' , table ) ; // Configure DataFlow properties this.DataFlow.Name = `` Replicate `` + saniName ; this.DataFlow.Description = `` Scripted replication '' ; // Connection manager configuration this.SrcConn.SetConnectionString ( sourceServer , database ) ; this.SrcConn.Name = `` PROD '' ; this.SrcConn.Description = string.Empty ; this.DestConn.SetConnectionString ( destinationServer , database ) ; this.DestConn.Name = `` PREPROD '' ; this.DestConn.Description = string.Empty ; // Configure Dataflow 's Source properties this.Source.Name = `` Src `` + saniName ; this.Source.Description = string.Empty ; this.Source.SqlCommand = sourceQuery ; // Configure Dataflow 's Destination properties this.Dest.Name = `` Dest `` + saniName ; this.Dest.Description = string.Empty ; this.Dest.Table = table ; this.Dest.FastLoadKeepIdentity = true ; this.Dest.FastLoadKeepNulls = true ; this.Dest.DataSourceVariable = this.Variables [ `` tableName '' ] .QualifiedName ; this.Dest.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE ; this.Dest.LinkAllInputsToOutputs ( ) ; } /// < summary > /// Sanitize a name so that it is valid for SSIS objects . /// Strips [ ] /\ : = /// Replaces . with _ /// < /summary > /// < param name= '' name '' > < /param > /// < returns > < /returns > public static string SanitizeName ( string name ) { string saniName = name.Replace ( `` [ `` , String.Empty ) .Replace ( `` ] '' , string.Empty ) .Replace ( `` . `` , `` _ '' ) .Replace ( `` / '' , string.Empty ) .Replace ( `` \\ '' , string.Empty ) .Replace ( `` : '' , string.Empty ) ; return saniName ; } } } this.Source.DataSourceVariable = this.Variables [ `` sourceQuery '' ] .QualifiedName ; this.Source.AccessMode = AccessMode.AM_SQLCOMMAND_VARIABLE ; this.Dest.DataSourceVariable = this.Variables [ `` tableName '' ] .QualifiedName ; this.Dest.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE ; this.Source.AccessMode = AccessMode.AM_OPENROWSET ; this.Source.AccessMode = AccessMode.AM_OPENROWSET_VARIABLE ; this.Source.AccessMode = AccessMode.AM_SQLCOMMAND ; this.Source.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD ; this.Source.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE ; Application app = new Application ( ) ; Package p = app.LoadPackage ( @ '' C : \sandbox\SSISHackAndSlash\SSISHackAndSlash\EzApiPackage.dtsx '' , null ) ; TableToTable to = new TableToTable ( p ) ;",What is the EzAPI equivalent for using an OLE DB Source command from variable ? "C_sharp : For a project I 'm currently working on , I 'm given an array of objects , each of which contain a `` content '' property and a `` level '' property . I need to convert this list into an HTML bulleted list . For example , if I was given the following input ( shown in JSON for simplicity ) : I would need to convert it to the following XHTML : The end product would look like this : HeyI just met youand this is crazybut here 's my numbercall me , maybe ( < - one level deeper - I do n't think I can do this in SO ) Kind of a weird puzzle . Any suggestions as to an algorithm/approach that would be most efficient/easy to implement ? I 'm implementing this in C # , but an example/idea in another language would be more than welcome . [ { content : `` Hey '' , level : `` 1 '' } , { content : `` I just met you '' , level : `` 2 '' } , { content : `` and this is crazy '' , level : `` 2 '' } , { content : `` but here 's my number '' , level : `` 1 '' } , { content : `` call me , maybe '' , level : `` 3 '' } ] < ul > < li > Hey < /li > < li > < ul > < li > I just met you < /li > < li > and this is crazy < /li > < /ul > < /li > < li > but here 's my number < /li > < li > < ul > < li > < ul > < li > call me , maybe < /li > < /ul > < /li > < /ul > < /li > < /ul >",Converting a list into XML "C_sharp : I 'm making a WPF text-editor using Glyphs element.And I have a problem that the text is not drawn correctlyas you can see in the picture , how can I solve this problem ? There are two problems : Kerning between letters.Kerning between letters and diacritics.The first problem I solved by GetKerningPairs function.How do I solve this problem , maybe I 'm wrong ? < Window x : Class= '' MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 200 '' Width= '' 525 '' > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' 100 '' / > < ColumnDefinition Width= '' * '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < Grid.RowDefinitions > < RowDefinition Height= '' AUTO '' / > < RowDefinition Height= '' AUTO '' / > < /Grid.RowDefinitions > < TextBlock Text= '' TextBlock '' VerticalAlignment= '' Center '' Margin= '' 6 '' / > < TextBlock Grid.Row= '' 1 '' Text= '' Glyphs '' VerticalAlignment= '' Center '' Margin= '' 6 '' / > < TextBlock Text= '' בְּרֵאשִׁית '' Grid.Column= '' 1 '' FontSize= '' 50 '' FontFamily= '' Times New Roman '' FontWeight= '' Normal '' Grid.Row= '' 0 '' / > < Glyphs Grid.Row= '' 1 '' Grid.Column= '' 1 '' FontUri = `` C : \WINDOWS\Fonts\TIMES.TTF '' FontRenderingEmSize = `` 50 '' UnicodeString = `` בְּרֵאשִׁית '' BidiLevel= '' 1 '' Fill = `` Black '' / > < TextBlock Text= '' AVAV '' Grid.Column= '' 2 '' FontSize= '' 50 '' FontFamily= '' Times New Roman '' FontWeight= '' Normal '' Grid.Row= '' 0 '' / > < Glyphs Grid.Row= '' 1 '' Grid.Column= '' 2 '' FontUri = `` C : \WINDOWS\Fonts\TIMES.TTF '' FontRenderingEmSize = `` 50 '' UnicodeString = `` AVAV '' BidiLevel= '' 0 '' Fill = `` Black '' / > < /Grid > < /Window >",WPF ` Glyphs ` not rendering the text right like ` TextBlock ` "C_sharp : Just let me start off with a demonstration : This code works as expected . After garbage collection is over , the reference in h is nullified . Now , here 's the twist : I add an empty try/finally block to the test after the GC.Collect ( ) line and lo , the weakly referenced object is not collected ! If the empty try/finally block is added before the GC.Collect ( ) line , the test passes though.What gives ? Can anyone explain how in exactitude does try/finally blocks affect the lifetime of objects ? Note : all testing done in Debug . In Release both tests pass.Note 2 : To reproduce the app must be targeting either the .NET 4 or the .NET 4.5 runtime and it must be run as 32-bit ( either target x86 , or Any CPU with `` Prefer 32-bit '' option checked ) [ TestMethod ] public void Test ( ) { var h = new WeakReference ( new object ( ) ) ; GC.Collect ( ) ; Assert.IsNull ( h.Target ) ; } [ TestMethod ] public void Test ( ) { var h = new WeakReference ( new object ( ) ) ; GC.Collect ( ) ; try { } // I just add an empty finally { } // try/finally block Assert.IsNull ( h.Target ) ; // FAIL ! }",Why does the existence of a try/finally block stop the garbage collector from working ? C_sharp : I 'm trying to rename my indexer property using IndexerName attribute on my abstract classes . But it still show compilation error The type 'XXX ' already contains a definition for 'Item'.Abstract class : Concrete class : Compilation error : The type 'MyConcrete ' already contains a definition for 'Item'.I 've tried to put IndexerName on indexer override and it show error `` Can not set the IndexerName attribute on an indexer marked override '' How to use IndexerName on abstract classes ? Thanks in advance . public abstract class MyAbstract { [ IndexerName ( `` Indexer '' ) ] public abstract string this [ string propertyName ] { get ; } } public class MyConcrete : MyAbstract { string item ; public string Item { get { return item ; } set { item = value ; } } public override string this [ string propertyName ] { get { return propertyName ; } } },IndexerName attribute on abstract classes "C_sharp : I have a Canvas with 2 `` dots '' drawn on it . See this ( simplified ) code : As you can see , I want to rotate the canvas using the given RotateTransform.Next , I want to put a TextBlock near to each Ellipse ( a label ) . However , I do n't want to include this TextBlock into the Canvas because it will then rotate also . I want the text to remain horizontal . Any idea how to solve this in an elegant way ? < Canvas > < Ellipse / > < Ellipse / > < Canvas.RenderTransform > < RotateTransform x : Name= '' rotateEllipse '' / > < /Canvas.RenderTransform > < /Canvas >",Binding to X Y coordinates of element on WPF Canvas "C_sharp : This is the first time I 've really dealt with Expression Trees , and I am a bit lost . I apologise ifthis question just does n't make any sense at all . Consider the following classes : So right now I have a helper method that looks like this : And then it gets invoked like this : But I dislike building three almost exact same expressions , and having to explicitly passthem into the Helper . What I would prefer is to something like this : And then : But I 'm not really sure how to do that ... Its boggling my mind , any shove in theright direction would be wildly appriciated . public class Foo < T > { public T Value { get ; set ; } public bool Update { get ; set ; } } public class Bar { public Foo < bool > SomeBool { get ; set ; } public Foo < string > SomeString { get ; set ; } } public void Helper < T > ( Expression < Func < Bar , Foo < T > > > baseExpression , Expression < Func < Bar , T > > valExpression , Expression < Func < Bar , bool > > updateExpression ) { // Do some stuff with those expressions . } Helper ( b= > b.SomeBool , b= > b.SomeBool.Value , b= > b.SomeBool.Update ) ; Helper ( b= > b.SomeBool ) ; public void Helper < T > ( Expression < Func < Bar , Foo < T > > > baseExpression ) { // Do some stuff var valExpression = ? ? ? ; // append ` .Value ` to baseExpression var updateExpression = ? ? ? ; // append ` .Update ` to baseExpression }",Adding a node/property to an Expression Tree "C_sharp : I was bit this week by a bug that occurred when my code was hosted in an x64 process . I am using a hash value for lookup and I am storing that hash value in a database . The hash value that has been generated in the past was a x86 hash and now that x64 hashes are being generated I am getting errors because the lookup values do n't match anymore . I am highly skeptical of this , but I thought I 'd ask anyway . Is there a way to generate an x86 hash value if my code is running in an x64 process ? For reference , I am running on .NET 4.0 using C # .Edit : Here 's the problem I 've been running into : String.GetHashCode ( ) returns different valuesYou can duplicate the problem by creating a console app with the following code : Run the app with x86 platform , then run it with the x64 platform . I just want to get consistent values across platforms . However , I may just create a pre-compiled list of hashes so I can fail over in the event I need to . I just wanted to know if there were a way to get consistent values from GetHashCode ( ) . I do n't think so , but if it is possible it would be the easiest solution in my case . `` DDD.Events.Application.ApplicationReferenceCreated '' .GetHashCode ( )",Can you generate an x86 hash value when running in x64 mode ? "C_sharp : I 'm testing a method that manipulates a collection . Given a set of parameters it should contain exactly one element that matches a condition . Edit : The collection might have several other elements not matching the condition aswell.I 'm using Single to test that behaviour , which works fine , as it will fail the test by throwing an exception if there is no match at all or more than one match . But there is no actual assert , which somehow violates arrange , act , assert . So I 'm wondering if this is a bad practice and if there 's a better way to do this.Following pseudo code to demonstrate my question : [ TestMethod ] public void TestMethod ( ) { List list = MethodToTest ( param1 , param2 ) ; list.Single ( s = > s.Matches ( condition ) ) ; //No actual Assert }",Is using Single as an Assert a bad practice ? C_sharp : What are the advantages and when is it appropriate to use a static constructor ? and then creating an instance of the class viaas opposed to just having a public constructor and creating objects using I can see the first approach is useful if the Create method returns an instance of an interface that the class implements ... it would force callers create instances of the interface rather than the specific type . public class MyClass { protected MyClass ( ) { } public static MyClass Create ( ) { return new MyClass ( ) ; } } MyClass myClass = MyClass.Create ( ) ; MyClass myClass = new MyClass ( ) ;,Why have a Create method instead of using `` new '' ? "C_sharp : I want to pretty print an XDocument but leaving white space inside xml : space= '' preserve '' elements untouched.This snippet : Results in the following indented output ( which is just want I want ) : However , let 's say that I need to preserve white space inside the < b > element : In this case I get the following output : This is not good , since indentation was added inside the xml : space= '' preserve '' scope . The expected output in this case would be : I 'm surprised that XDocument does n't support this by default.Is it possible to get a pretty printed ( indented ) output from an XDocument and keeping white space inside xml : space= '' preserve '' as-is ? I understand that one option is to write my own XmlWriter implementation that takes care of this , but I would rather use something from the framework ( if available ) . new XDocument ( new XElement ( `` a '' , new XElement ( `` b '' , new XElement ( `` c '' ) ) ) ) .Save ( Console.Out ) ; < a > < b > < c / > < /b > < /a > new XDocument ( new XElement ( `` a '' , new XElement ( `` b '' , new XAttribute ( XNamespace.Xml + `` space '' , `` preserve '' ) , new XElement ( `` c '' ) ) ) ) .Save ( Console.Out ) ; < a > < b xml : space= '' preserve '' > < c / > < /b > < /a > < a > < b xml : space= '' preserve '' > < c / > < /b > < /a >",Save XDocument with indentation and xml : space= '' preserve '' "C_sharp : I 'm getting confused with what happens on the stack and heap in respect to value type properties in classes.My understanding so far : When you create a class with a structure ( value type ) like this : If you create a class instance like so : The stack and heap will look like this : ... where the Bar structure is embeded in the Foo class in the heap . This makes sense to me , but I start to loose it when we consider modifying the Number integer in the BarStruct class , within the Foo Object . For example : As I understand , this should be returning a copy of BarStruct to live on the stack , which means that any changes of a member of BarStruct would not be carried through to the object , which is why the last line above gives an error.Is this right so far ? If so , my question is , how come an assignment such as this : ... is valid and changes the heap value ? Surely this is just changing the value on the stack ? ? Also , ( by and by ) I find it so confusing that you are able to use new on a value type . To me , new is for allocatting on the heap ( as per C++ ) and feels unnatural to be doing this for items on the stack.So just to re-iterate the question , Am I correct in my assumption of what happens when a property containing a structure is called and why can you assign a new structure to a copy and yet it still changes the reference on the heap ? Really hope this all make sense.Yell if you need clarification ! Ta , Andy . class Foo { private Bar _BarStruct ; public Bar BarStruct { get { return _BarStruct ; } set { _BarStruct = value ; } } } private struct Bar { public int Number ; Bar ( ) { Number = 1 ; } Bar ( int i ) { Number = i ; } } Foo fooObj = new Foo ( ) ; Foo fooObj = new Foo ( ) ; fooObj.BarStruct.Number = 1 ; fooObj.BarStruct = new Bar ( 2 ) ;",Returning a value type from a property "C_sharp : I 'm on an ASP.Net 2.0 project , in C # . I have some data that gets stored in session state . For ease of use , it is wrapped in a property , like this : Getting and setting the value works exactly as you 'd expect . If I want to clear the value , I just set it to null , and there are no problems . However , in another developer 's page , he calls the collection 's Clear ( ) method . I thought this would be a bug , but it seems to work , and I do n't understand why . It works like so : Why does this work ? My naive expectation would be that the middle line loads the serialized value from session , deserializes into an object , calls Clear ( ) on that object , and then lets the unnamed object fall out of scope . That would be a bug , because the value stored in Session would remain unchanged . But apparently , it 's smart enough to instead call the property setter and serialize the newly changed collection back into session . This makes me a little nervous , because there are places in our legacy code where property setters have side effects , and I do n't want those getting called if it 's not intended.Does the property setter always get called in a situation like this ? Is something else going on ? Or do I completely misunderstand what 's happening here ? [ Added to explain answer ] It turns out did misunderstand . I knew that objects stored in Session must be serializable , and based on that I made too many assumptions about how the collection behaves internally . I was overthinking.There is only one instance of the stored object ( my IList ) . Each call to the getter returns a reference to that same instance . So the quoted code above works just as it appears , with no special magic required.And to answer the title question : No , setters are not called implicitly . protected IList < Stuff > RelevantSessionData { get { return ( IList < Stuff > ) Session [ `` relevant_key '' ] ; } set { Session [ `` relevant_key '' ] = value ; } } Debug.WriteLine ( RelevantSessionData.Count ) ; //outputs , say , 3RelevantSessionData.Clear ( ) ; Debug.WriteLine ( RelevantSessionData.Count ) ; //outputs 0",Are .Net property setters ever called implicitly ? "C_sharp : I 'm trying to test NLog under LINQPad.I successfully linked it and my code compiles well . However , NLog does n't write log files because it is not configured.I tried to make various config files like : NLog.config and LINQPad.config but it looks like I do not do it correctly.My testing code under LINQPad is : Config code : Where to put the config file ? void Main ( ) { try { int zero = 0 ; int result = 5 / zero ; } catch ( DivideByZeroException ex ) { Logger logger = LogManager.GetCurrentClassLogger ( ) ; logger.ErrorException ( `` Whoops ! `` , ex ) ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < nlog xmlns= '' http : //www.nlog-project.org/schemas/NLog.xsd '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' > < targets > < target name= '' logfile '' xsi : type= '' File '' fileName= '' logfile.log '' / > < /targets > < rules > < logger name= '' * '' minlevel= '' Info '' writeTo= '' logfile '' / > < /rules > < /nlog >",NLog via LINQPad - Where to put config file ? "C_sharp : I am trying to parse date of format : 2013-09-17T05:15:27.947This is my codeBut its giving some format exception every time . Seems I am missing something basic . String MessageRecieptDate = messageReceiptDate.Replace ( `` T '' , `` `` ) .Remove ( messageReceiptDate.Length-4 ) ; DateTime dt = new DateTime ( ) ; IFormatProvider culture = new CultureInfo ( `` en-US '' ) ; dt = DateTime.ParseExact ( MessageRecieptDate , `` dd MMM '' , culture ) ;",unable to parse date string of format like 2013-09-17T05:15:27.947 C_sharp : is there any effective difference between Foo.Something and Bar.Something in this example ? AFAIK they behave exactly the same . If they do why not to use plain Fields like in Foo ? In java we use setters to be able enforce new invariants without breaking code and getters to return safe data but in c # you can always rewrite Foo into this : And old code will not be broken . class Foo { public string Something ; } class Bar { public string Something { get ; set ; } } class Program { static void Main ( string [ ] args ) { var MyFoo = new Foo ( ) ; MyFoo.Something = `` Hello : foo '' ; System.Console.WriteLine ( MyFoo.Something ) ; var MyBar = new Bar ( ) ; MyBar.Something = `` Hello : bar '' ; System.Console.WriteLine ( MyBar.Something ) ; System.Console.ReadLine ( ) ; } } class Foo { private string _Something ; public string Something { get { //logic return _Something ; } set { //check new invariant _Something = value ; } } },C # autoproperty vs normal fields "C_sharp : This is my first question , and I know I should search before asking anything , I am sure that I have done search but I did n't find appropriate information.I am using code-first approach to implement my Context and my Models , So I have a simple Context like : and my model : and I have two connectionstrings like below : and my EF config : I want to write to different Db just by changing ConnectionString like : the first context works fine but the sqlcontext get the below exception : An unhandled exception of type 'System.NullReferenceException ' occurred in EntityFramework.dll Additional information : Object reference not set to an instance of an objectbut if I remove the DbConfigurationType decoration then the second sqlContext works fine the first one give below exception : An unhandled exception of type 'System.Data.SqlClient.SqlException ' occurred in EntityFramework.dll Additional information : Login failed for user 'root'.I know that is because of DbConfigurationType which can define in application start or decorate on Context or defined in config file ... .but how can I have this ( multiple connectionstrings and one context ) ? [ DbConfigurationType ( typeof ( MySql.Data.Entity.MySqlEFConfiguration ) ) ] public partial class MultipleContext : DbContext { public MariaDBContext ( string connection ) : base ( connection ) { //Database.SetInitializer < MultipleDBContext > ( new MariaDbInitializer ( ) ) ; } public virtual DbSet < Test > Tests { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder.Entity < Test > ( ) .ToTable ( `` test '' ) .HasKey ( e = > e.ID ) ; } } public partial class Test { public int ID { get ; set ; } public string Name { get ; set ; } public string Family { get ; set ; } } < connectionStrings > < add name= '' MariaDBContext '' connectionString= '' server=127.0.0.1 ; user id=root ; password=xx ; database=sb1 '' providerName= '' MySql.Data.MySqlClient '' / > < add name= '' SqlDBContext '' connectionString= '' Data Source=localhost ; Integrated Security=SSPI ; Initial Catalog=db1 '' providerName= '' System.Data.SqlClient '' / > < /connectionStrings > < entityFramework > < defaultConnectionFactory type= '' System.Data.Entity.Infrastructure.LocalDbConnectionFactory , EntityFramework '' > < parameters > < parameter value= '' mssqllocaldb '' / > < /parameters > < /defaultConnectionFactory > < providers > < provider invariantName= '' MySql.Data.MySqlClient '' type= '' MySql.Data.MySqlClient.MySqlProviderServices , MySql.Data.Entity.EF6 , Version=6.9.8.0 , Culture=neutral , PublicKeyToken=c5687fc88969c44d '' / > < /providers > < /entityFramework > MultipleDBContext context = new MultipleDBContext ( System.Configuration.ConfigurationManager.ConnectionStrings [ `` MariaDBContext '' ] .ToString ( ) ) ; var xx = context.Tests.Where ( x = > x.ID > 0 ) .ToList ( ) ; context.Tests.Add ( new Test ( ) { Name = `` name '' , Family = `` '' } ) ; context.SaveChanges ( ) ; xx = context.Tests.Where ( x = > x.ID > 0 ) .ToList ( ) ; //Use sql connectionMultipleDBContext sqlContext = new MultipleDBContext ( System.Configuration.ConfigurationManager.ConnectionStrings [ `` SqlDBContext '' ] .ToString ( ) ) ; var sqlTest = sqlContext.Tests.Where ( x = > x.ID > 0 ) .ToList ( ) ; sqlContext.Tests.Add ( new Test ( ) { Name = `` name_ '' + DateTime.Now.Ticks.ToString ( ) , Family = `` family_ '' + DateTime.Now.Ticks.ToString ( ) , } ) ; sqlContext.SaveChanges ( ) ; sqlTest = sqlContext.Tests.Where ( x = > x.ID > 0 ) .ToList ( ) ;","One DbContext and multiple database , EF code first" "C_sharp : I am having some serious issues with WPF and using DrawingContext , or specifically VisualDrawingContext coming from overriding OnRender on an element or if using DrawingVisual.RenderOpen ( ) . The problem is this allocates a lot . For example , it seems to be allocating a byte [ ] buffer each time a drawing context is used.Examples , of how drawing context is used.or This causes a lot of allocations , causing some unwanted garbage collections . So yes I need this , and please stay on topic : ) .What are the options for drawing in WPF with zero or low number of managed heap allocations ? Reusing objects is fine , but I have yet to find a way to do this ... or does n't then have issues with DependencyProperty and allocations around/inside it.I do know about WritableBitmapEx but was hoping for a solution that does not involve rasterising to predefined bitmap , but instead proper `` vector '' graphics that can still be zoomed for example.NOTE : CPU usage is a concern but much less than the massive garbage pressure caused by this.UPDATE : I am looking for a solution for .NET Framework 4.5+ , if there is anything in later versions e.g . 4.7 that might help answer this then that is fine . But it is for the desktop .NET Framework.UPDATE 2 : A brief description of the two main scenarios . All examples have been profiled with CLRProfiler , and it shows clearly that lots of allocations occur due to this and that this is a problem for our use case . Note that this is example code intended to convey the principles not the exact code.A : This scenario is shown below . Basically , an image is shown and some overlay graphics are drawn via a custom DrawingVisualControl , which then uses using ( var drawingContext = m_drawingVisual.RenderOpen ( ) ) to get a drawing context and then draws via that . Lots of ellipse , rectangles and text is drawn . This example also shows some scaling stuff , this is just for zooming etc.The ` DrawingVisualControl is defined as : B : The second scenario involves drawing a moving `` grid '' of data e.g . 20 rows of 100 columns , with elements consisting of a border and text with different colors to display some status . The grid moves depending on external input , and for now is only updated 5-10 times per second . 30 fps would be better . This , thus , updates 2000 items in an ObservableCollection tied to a ListBox ( with VirtualizingPanel.IsVirtualizing= '' True '' ) and the ItemsPanel being a Canvas . We ca n't even show this during our normal use case , since it allocates so much that the GC pauses become way too long and frequent.There is a lot of data binding here , and the box'ing of value types do incur a lot of allocations , but that is not the main problem here . It is the allocations done by WPF . using ( var drawingContext = m_drawingVisual.RenderOpen ( ) ) { // Many different drawingContext.Draw calls // E.g . DrawEllipse , DrawRectangle etc . } override void OnRender ( DrawingContext drawingContext ) { // Many different drawingContext.Draw calls // E.g . DrawEllipse , DrawRectangle etc . } < Viewbox x : Name= '' ImageViewbox '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Center '' > < Grid x : Name= '' ImageGrid '' SnapsToDevicePixels= '' True '' ClipToBounds= '' True '' > < Grid.LayoutTransform > < ScaleTransform x : Name= '' ImageTransform '' CenterX= '' 0 '' CenterY= '' 0 '' ScaleX= '' { Binding ElementName=ImageScaleSlider , Path=Value } '' ScaleY= '' { Binding ElementName=ImageScaleSlider , Path=Value } '' / > < /Grid.LayoutTransform > < Image x : Name= '' ImageSource '' RenderOptions.BitmapScalingMode= '' NearestNeighbor '' SnapsToDevicePixels= '' True '' MouseMove= '' ImageSource_MouseMove '' / > < v : DrawingVisualControl x : Name= '' DrawingVisualControl '' Visual= '' { Binding DrawingVisual } '' SnapsToDevicePixels= '' True '' RenderOptions.BitmapScalingMode= '' NearestNeighbor '' IsHitTestVisible= '' False '' / > < /Grid > < /Viewbox > public class DrawingVisualControl : FrameworkElement { public DrawingVisual Visual { get { return GetValue ( DrawingVisualProperty ) as DrawingVisual ; } set { SetValue ( DrawingVisualProperty , value ) ; } } private void UpdateDrawingVisual ( DrawingVisual visual ) { var oldVisual = Visual ; if ( oldVisual ! = null ) { RemoveVisualChild ( oldVisual ) ; RemoveLogicalChild ( oldVisual ) ; } AddVisualChild ( visual ) ; AddLogicalChild ( visual ) ; } public static readonly DependencyProperty DrawingVisualProperty = DependencyProperty.Register ( `` Visual '' , typeof ( DrawingVisual ) , typeof ( DrawingVisualControl ) , new FrameworkPropertyMetadata ( OnDrawingVisualChanged ) ) ; private static void OnDrawingVisualChanged ( DependencyObject d , DependencyPropertyChangedEventArgs e ) { var dcv = d as DrawingVisualControl ; if ( dcv == null ) { return ; } var visual = e.NewValue as DrawingVisual ; if ( visual == null ) { return ; } dcv.UpdateDrawingVisual ( visual ) ; } protected override int VisualChildrenCount { get { return ( Visual ! = null ) ? 1 : 0 ; } } protected override Visual GetVisualChild ( int index ) { return this.Visual ; } } < ListBox x : Name= '' Items '' Background= '' Black '' VirtualizingPanel.IsVirtualizing= '' True '' SnapsToDevicePixels= '' True '' > < ListBox.ItemTemplate > < DataTemplate DataType= '' { x : Type vm : ElementViewModel } '' > < Border Width= '' { Binding Width_mm } '' Height= '' { Binding Height_mm } '' Background= '' { Binding BackgroundColor } '' BorderBrush= '' { Binding BorderColor } '' BorderThickness= '' 3 '' > < TextBlock Foreground= '' { Binding DrawColor } '' Padding= '' 0 '' Margin= '' 0 '' Text= '' { Binding TextResult } '' FontSize= '' { Binding FontSize_mm } '' TextAlignment= '' Center '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Center '' / > < /Border > < /DataTemplate > < /ListBox.ItemTemplate > < ListBox.ItemContainerStyle > < Style TargetType= '' { x : Type ListBoxItem } '' > < Setter Property= '' Canvas.Left '' Value= '' { Binding X_mm } '' / > < Setter Property= '' Canvas.Top '' Value= '' { Binding Y_mm } '' / > < /Style > < /ListBox.ItemContainerStyle > < ListBox.ItemsPanel > < ItemsPanelTemplate > < Canvas IsItemsHost= '' True '' Width= '' { Binding CanvasWidth_mm } '' Height= '' { Binding CanvasHeight_mm } '' / > < /ItemsPanelTemplate > < /ListBox.ItemsPanel > < /ListBox >",Low Allocation Drawing in WPF C_sharp : I 'm encountering a very strange issue while debugging a unit test . If I debug the unit test ( ctrl+r ctrl+t ) I am getting an uncaught exception . If I just run the unit test ( ctrl+r t ) I do not get this exception.The uncaught exception is a NHibernate.ByteCode.ProxyFactoryFactoryNotConfiguredException.Stack trace : I used .Net Reflector to look at the assembly that defines this method ( NHibernate.Validator ... it 's open source ) and here is the method that `` throws '' the exception : How can this exception not be caught by that Try Catch block ? at NHibernate.Bytecode.AbstractBytecodeProvider.get_ProxyFactoryFactory ( ) in d : \CSharp\NH\NH\nhibernate\src\NHibernate\Bytecode\AbstractBytecodeProvider.cs : line 32at NHibernate.Validator.Util.NHibernateHelper.IsProxyFactoryConfigurated ( ) public static bool IsProxyFactoryConfigurated ( ) { try { IProxyFactoryFactory proxyFactoryFactory = Environment.BytecodeProvider.ProxyFactoryFactory ; return true ; } catch ( ProxyFactoryFactoryNotConfiguredException ) { return false ; } },C # Uncaught exception in unit test "C_sharp : I 'm writing a .NET Core console application . I wanted to limit console input to a certain number of maximum characters for each input . I have some code that does this by building a string with Console.ReadKey ( ) instead of Console.ReadLine ( ) Everything worked perfectly testing it on Windows . Then , when I deployed to a Raspberry Pi 3 running Raspbian , I quickly encountered all sorts of problems . I remembered that Linux handles line endings differently from Windows , and it seems backspaces are handled differently as well . I changed the way I handled those , going off the ConsoleKey instead of the character , and the newline problem went away , but backspaces only sometimes register . Also , sometimes characters get outputted to the console outside of my input box , even though I set the ReadKey to not output to the console on its own . Am I missing something about how Linux handles console input ? //I replaced my calls to Console.ReadLine ( ) with this . The limit is the//max number of characters that can be entered in the console.public static string ReadChars ( int limit ) { string str = string.Empty ; //all the input so far int left = Console.CursorLeft ; //store cursor position for re-outputting int top = Console.CursorTop ; while ( true ) //keep checking for key events { if ( Console.KeyAvailable ) { //true to intercept input and not output to console //normally . This sometimes fails and outputs anyway . ConsoleKeyInfo c = Console.ReadKey ( true ) ; if ( c.Key == ConsoleKey.Enter ) //stop input on Enter key break ; if ( c.Key == ConsoleKey.Backspace ) //remove last char on Backspace { if ( str ! = `` '' ) { tr = str.Substring ( 0 , str.Length - 1 ) ; } } else if ( c.Key ! = ConsoleKey.Tab & & str.Length < limit ) { //do n't allow tabs or exceeding the max size str += c.KeyChar ; } else { //ignore tabs and when the limit is exceeded continue ; } Console.SetCursorPosition ( left , top ) ; string padding = `` '' ; //padding clears unused chars in field for ( int i = 0 ; i < limit - str.Length ; i++ ) { padding += `` `` ; } //output this way instead Console.Write ( str + padding ) ; } } return str ; }",Why is .NET Core handling ReadKey differently on Raspbian ? "C_sharp : This is a question about Extension Method visibility in .Net ( specifically C # ) , and why intellisense may work , but the compiler fail on the same piece of code.Picture this ... I have .Net 3.5 class library consisting of a bunch of objects and a single Extension Methods class . Here is one of the methods : To use the extension methods within the class library itself , each class that requires one of the methods needs to specify : Since that is a different namespace than the rest of the library . All of that works fine.Now , a .Net 2.0 web site properly references this library , and a class file wishes to use the library . So it declares that it is : That SEEMS to work just fine , and when typing a string , Intellisense does see the extension method dangling off a string instance : http : //www.flipscript.com/test/ToTitleCase.jpgI love it when a plan comes together ! However , that 's the end of the joy.When attempting to Build the web site , the build fails with the following message : http : //www.flipscript.com/test/titlecaseerror.jpgWhen attempting to directly copy the ExtensionMethods class into the web project , the build again fails . This time , because the word `` this '' was not expected.Oddly enough , the extension method does work as a normal static method : http : //www.flipscript.com/test/titlecaseok.jpg ... and the Build works just fine ( so the problem is NOT actually with the `` this '' keyword ) . In fact , the build works whether the ExtensionMethods class is in the class library or the web site.In other words , this does solve the problem , and the build will succeed ... .but the solution sucks.Question : Is there some sort of secret trick to get Extension Methods to work correctly in this scenario ? http : //www.flipscript.com/test/ToTitleCase.jpgI 've tried the `` namespace System.Runtime.CompilerServices '' trick , but that did n't seem to help.What would cause Intellisense to see an extension method correctly , and the compiler to fail ? Note : The contrived example variable should have been called 'name ' instead of 'FirstName ' , but you get the idea . namespace MyApp.Extensions { public static class ExtensionMethods { public static string ToTitleCase ( this string Origcase ) { string TitleCase = Origcase ; ... implementation ... return TitleCase ; } } using MyApp.Extensions ; using MyApp.Extensions",.Net Extension Method ( this string Foo ) Only Partially Visible "C_sharp : Possible Duplicate : incorrect stacktrace by rethrow It is generally accepted that in .NET throw ; does not reset the stack trace but throw ex ; does.However , in this simple program , I get different line numbers : The output is : System.InvalidCastException : Unable to cast object of type 'System.Int32 ' to type 'System.String ' . at ConsoleApplication2.Program.Main ( String [ ] args ) in C : \long-path\Program.cs : line 13 System.InvalidCastException : Unable to cast object of type 'System.Int32 ' to type 'System.String ' . at ConsoleApplication2.Program.Main ( String [ ] args ) in C : \long-path\Program.cs : line 18Note : The first stack trace contains line 13 , the second contains line 18 . Additionally , neither line 13 nor line 18 are the lines where the cast is actually happening.My question now is : In what circumstances does throw ; change the stack trace and in which circumstance does n't it change the stack trace ? Please note , that this has already been observed , but not answered in general.UPDATE : I ran the code above in Debug mode and it yields this : System.InvalidCastException : Unable to cast object of type 'System.Int32 ' to type 'System.String ' . at ConsoleApplication2.Program.Throw ( ) in C : \long-path\Program.cs : line 33 at ConsoleApplication2.Program.Wrapper ( ) in C : \long-path\Program.cs : line 28 at ConsoleApplication2.Program.Main ( String [ ] args ) in C : \long-path\Program.cs : line 13 System.InvalidCastException : Unable to cast object of type 'System.Int32 ' to type 'System.String ' . at ConsoleApplication2.Program.Throw ( ) in C : \long-path\Program.cs : line 33 at ConsoleApplication2.Program.Wrapper ( ) in C : \long-path\Program.cs : line 28 at ConsoleApplication2.Program.Main ( String [ ] args ) in C : \long-path\Program.cs : line 18Please note : The last line number still changes void Main ( ) { try { try { Wrapper ( ) ; // line 13 } catch ( Exception e ) { Console.WriteLine ( e.ToString ( ) ) ; throw ; // line 18 } } catch ( Exception e ) { Console.WriteLine ( e.ToString ( ) ) ; } } public void Wrapper ( ) { Throw ( ) ; // line 28 } public void Throw ( ) { var x = ( string ) ( object ) 1 ; // line 33 }","throw ; is said to not reset stack trace , but it does in certain circumstances" "C_sharp : I just stumbled over a very interesting problem . Giving the following code : I would expect that the second method will be called because the runtime type of the variable is B . Any ideas why the code calls the first method instead ? Thanks , TibiSome clarifications : Polymorphism means several forms which has nothing to do where you declare the method . Method overloading is a form of polymorphism , ad-hoc polymorphism . The way polymorphism is normally implemented by using late binding . dynamic is the workaround for this problem.The fact is that this is not working in C # ( or Java ) it is a design decission which I would like to understand why was made , and none of the answers is answering this question./Tibi using System ; class Program { class A { } class B : A { } private static void MyMethod ( A a ) /* first method */ { Console.WriteLine ( `` A '' ) ; ; } private static void MyMethod ( B b ) /* second method */ { Console.WriteLine ( `` B '' ) ; } static void Main ( string [ ] args ) { var a = new A ( ) ; // Call first method MyMethod ( a ) ; A b = new B ( ) ; // Should call the second method MyMethod ( b ) ; Console.ReadLine ( ) ; } }",Polymorphic methods not working on C # 4 "C_sharp : I have this two entities : Now I need to list each Class grouping by Course and ordered by ( descending ) Course.StartDate then by Class.StartTime . I can get to group by Course and order by Course.StartDate : But ca n't manage to also order each Class by it 's StartTime . I tried this : And even this : But the Classes are never ordered by it 's StartTime . *Edit for better clarification : This is for a WebService and I must return a List < IGrouping < Course , Class > > and I really want an elegant way of doing this ( i.e . using just Linq ) , without manually creating the list . Unless it 's not possible of course.Any help is apreciated ( I 'm using EF code-first 4.3 btw ) . public class Course { public int Id { get ; set ; } public string Name { get ; set ; } public DateTime StartDate { get ; set ; } public DateTime EndDate { get ; set ; } public virtual ICollection < Class > Classes { get ; set ; } } public class Class { public int Id { get ; set ; } public string Name { get ; set ; } public DateTime StartTime { get ; set ; } public DateTime EndTime { get ; set ; } ] public Course Course { get ; set ; } } var myList = context.Classes .GroupBy ( c = > c.Course ) .OrderByDescending ( g = > g.Key.StartDate ) .ToList ( ) var myList = context.Classes .OrderBy ( c = > c.StartTime ) .GroupBy ( c = > c.Course ) .OrderByDescending ( g = > g.Key.StartDate ) .ToList ( ) var myList = context.Classes .GroupBy ( c = > c.Course ) .OrderByDescending ( g = > g.Key.StartDate ) .ThenBy ( g = > g.Select ( c = > c.StartTime ) ) .ToList ( )",Grouping and multiple orderings using Linq to Entities "C_sharp : The following call in C # returns false : However , the following line is perfectly valid : Why is it so ? Is it because nullable types are backed using Nullable < T > and the fact the first generic argument implements an interface does not imply that the Nullable class also implement that interface ? ( eg : List < Foo > does not implement interfaces that Foo implement ) EDIT : I think the line above compile because when boxing an nullable type , only the underlying type is boxed as explained here : https : //msdn.microsoft.com/en-us/library/ms228597.aspx typeof ( IComparable ) .IsAssignableFrom ( typeof ( DateTime ? ) ) IComparable comparable = ( DateTime ? ) DateTime.Now ;",Why IsAssignableFrom return false when comparing a nullable against an interface ? "C_sharp : I am trying to make a callback interface between C # and Java using JNA.C # < -- CLI -- > Visual C++ 2010 < -- JNA -- > JavaBetween Java and C++ I am using unmanaged structures to get callback functionality . In C++ I am trying to wrap structure , that has callback pointers , into managed object.Between Java and C++ everything works until I 'm trying to use gcroot for managed object generation in unmanaged code.UPDATE it even fails without gcroot . Just with `` Logger^ logger = gcnew Logger ( logStruct ) ; '' My current solution is as follows : JavaLoggerStruct.javaITestLib.javaMain.javaC++JNATestC.hJNATestC.cppI wrote these on the fly . I hope these validate as well.What am I doing wrong ? For example if I use ... ... everything works just fine.Is there another way to pass managed object to C # ? Log for this error LOGUPDATEIt seems that anykind of my own Class usage will head me to failure.UPDATEAnykind of my own Managed object or function use heads me to failure.UPDATEStaticCSharpClass : :staticMethod ( ) ; fails as well . Looks like all operations related to Managed objects fail.UPDATEIf I invoke the same method from .NET , everything works fine.just to make this problem more findableInternal Error ( 0xe0434352 ) package jnatest ; import com.sun.jna.Callback ; import com.sun.jna.Structure ; import java.util.logging.Logger ; public class LoggerStruct extends Structure { private Logger logger ; public interface GetLevelCallback extends Callback { int callback ( ) ; } public GetLevelCallback getLevel ; public LoggerStruct ( Logger log ) { super ( ) ; this.log = log ; getLevel = new GetLevelCallback ( ) { public int callback ( ) { return logger.getLevel ( ) .intValue ( ) ; } } setFieldOrder ( new String [ ] { `` getLevel '' } ) ; } } package jnatest ; import com.sun.jna.Library ; import com.sun.jna.Native ; public interface ITestLib extends Library { ITestLib INSTANCE = ( ITestLib ) Native.loadLibrary ( `` JNATestC '' , ITestLib.class ) ; int callbackTest ( LoggerStruct logStruct ) ; } package jnatest ; import com.sun.jna.NativeLibrary ; import java.util.logging.Logger ; import java.util.logging.FileHandler ; public class MainClass { public static void main ( String [ ] args ) throws Exception { NativeLibrary.addSearchPath ( `` JNATestC '' , `` C : \\JNATest '' ) ; Logger log = Logger.getLogger ( `` Test '' ) ; FileHandler fileTxt = new FileHandler ( `` Logging.txt '' ) ; log.addHandler ( fileTxt ) ; LoggerStruct logStruct = new LoggerStruct ( log ) ; ITestLib.INSTANCE.callbackTest ( logStruct ) ; } } # pragma onceextern `` C '' { struct LoggerStruct { int ( *getLevel ) ( ) ; } __declspec ( dllexport ) void callbackTest ( LoggerStruct * logStruct ) ; } namespace JnaWrapperTypes { public ref class Logger { // `` public ref '' because I have to use it in C # as well private : LoggerStruct * logStruct ; public : Logger ( LoggerStruct * logStruct ) ; ~Logger ( ) { } int getLevel ( ) ; } ; } # include `` stdafx.h '' # include < vcclr.h > # include `` JNATestC.h '' namespace JnaWrapperTypes { Logger : :Logger ( LoggerStruct * logStruct ) { this- > logStruct = logStruct ; } Logger : :getLevel ( ) { return logStruct- > getLevel ( ) ; } } using namespace JnaWrapperTypes ; using namespace StaticCSharpNamespace ; // Just an example . Not existing C # lib.extern `` C '' { __declspec ( dllexport ) void callbackTest ( LoggerStruct * logStruct ) { int level = logStruct- > getLevel ( ) ; gcroot < Logger^ > logger = gcnew Logger ( logStruct ) ; // IF I ADD `` gcroot '' FOR `` Logger '' THEN WHOLE INVOKE FAILS level = logger- > getLevel ( ) ; StaticCSharpClass : :staticMethod ( logger ) ; // I want to pass Managed object to C # later gcroot < System : :String^ > str = gcnew System : :String ( `` '' ) ; // This does n't generate error } } gcroot < System : :String^ > str = gcnew System : :String ( `` '' ) ;",How to create managed object in unmanaged C++ while wrapping it for JNA between Java and C # ? "C_sharp : I am implementing a web api that will fetch data using entity framework 6 . I am using Sql Server 2014 and visual studio 2015.While debugging the the code in the CustomerDao class I am seeing an exception in the customerOrderContext object though I can see the records in the customer object . However after the using block executes I cant see any records . ( ( System.Data.SqlClient.SqlConnection ) customerOrderContext.Database.Connection ) .ServerVersionCustomerDaoThe connection string in the config file is as followsThe context class is followsCustomProvider.cs using ( var customerOrderContext = new Entities ( ) ) { return ( from customer in customerOrderContext.Customers select new CustomerOrder.BusinessObjects.Customers { Id = customer.Id , FirstName = customer.FirstName , LastName = customer.LastName , Address = customer.Address , City = customer.City , Email = customer.Email , Gender = customer.Gender , State = customer.State , Zip = customer.Zip } ) .ToList ( ) ; } < add name= '' Entities '' connectionString= '' metadata=res : //*/EF.CustomerOrderContext.csdl|res : //*/EF.CustomerOrderContext.ssdl|res : //*/EF.CustomerOrderContext.msl ; provider=System.Data.SqlClient ; provider connection string= & quot ; data source=Tom-PC\MSSQLSERVER2014 ; initial catalog=Ransang ; integrated security=True ; MultipleActiveResultSets=True ; App=EntityFramework & quot ; '' providerName= '' System.Data.EntityClient '' / > public partial class Entities : DbContext { public Entities ( ) : base ( `` name=Entities '' ) { } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { } public virtual DbSet < Customer > Customers { get ; set ; } public virtual DbSet < OrderDetail > OrderDetails { get ; set ; } public virtual DbSet < Order > Orders { get ; set ; } public virtual DbSet < Product > Products { get ; set ; } } public IEnumerable < BusinessObjects.Customers > GetAllCustomers ( ) { IList < BusinessObjects.Customers > customerCollection = new List < BusinessObjects.Customers > ( ) ; dataAccess.CustomerDao.GetAllCustomers ( ) ; return customerCollection ; }",Entity Framework 6 error serverversion : ( System.Data.SqlClient.SqlConnection ) customerOrderContext.Database.Connection ) .ServerVersion "C_sharp : I am creating images with a byte [ ] array in C # , and then converting them to a Bitmap in order to save them to disk.Here 's a few extracts from my code : This works well , until the width / height are n't a power of 2 ( i.e . 512x512 works , but 511x511 does n't ) , and then I get the following error : For reference , here are my using statements : Why does n't it work with pixel data sets that do n't have size that 's power of 2 ? How can I make it work with such sizes ? // Create an array of RGB pixelsbyte [ ] pixels = new byte [ width * height * 3 ] ; // Do some processing here ... .// Import the pixel data into a new bitmaBitmap image = new Bitmap ( width , height , width * 3 , PixelFormat.Format24bppRgb , GCHandle.Alloc ( pixels , GCHandleType.Pinned ) .AddrOfPinnedObject ( ) ) ; // Save the imageimage.Save ( `` testimage.png '' , ImageFormat.Png ) ; Unhandled Exception : System.ArgumentException : Parameter is not valid . at System.Drawing.Bitmap..ctor ( Int32 width , Int32 height , Int32 stride , PixelFormat format , IntPtr scan0 ) ( ... ... . ) using System ; using System.Collections.Generic ; using System.Drawing ; using System.Drawing.Imaging ; using System.Runtime.InteropServices ; using System.Diagnostics ;",C # Bitmap : `` Parameter is invalid '' on sizes that are n't a power of 2 "C_sharp : I 'm developping an application and I have a problem with a deadlock.My code looks like that : Then I 'm sending an .xml-file to this process : So actually I can send a part of my .xml-file to my process but at some point I 'll get a deadlock.I guess I do n't knoy how to use BeginOutputReadLine ( ) correctly . Process p = new Process ( ) ; // That using an other application XmlSerializer xs = new XmlSerializer ( data.GetType ( ) ) ; using ( var ms = new MemoryStream ( ) ) { var sw = new StreamWriter ( ms ) ; XmlWriter xmlwriter = XmlWriter.Create ( sw , xmlWriterSettings ) ; xmlwriter.WriteProcessingInstruction ( `` PipeConfiguratorStyleSheet '' , processing ) ; xs.Serialize ( xmlwriter , data ) ; xmlwriter.Flush ( ) ; ms.Position = 0 ; var sr = new StreamReader ( ms ) ; while ( ! sr.EndOfStream ) { String line = sr.ReadLine ( ) ; p.StandardInput.WriteLine ( line ) ; Console.WriteLine ( line ) ; p.BeginOutputReadLine ( ) ; p.CancelOutputRead ( ) ; } }",Deadlock while writing to Process.StandardInput "C_sharp : I have a program ( C # ) with a list of tests to do.Also , I have two thread . one to add task into the list , and one to read and remove from it the performed tasks.I 'm using the 'lock ' function each time one of the threads want to access to the list.Another thing I want to do is , if the list is empty , the thread who need to read from the list will sleep . and wake up when the first thread add a task to the list.Here is the code I wrote : Apparently I did it wrong , and it 's not performed as expected ( The readTread does't read from the list ) .Does anyone know what is my problem , and how to make it right ? Many thanks , ... List < String > myList = new List ( ) ; Thread writeThread , readThread ; writeThread = new Thread ( write ) ; writeThread.Start ( ) ; readThraed = new Thread ( read ) ; readThread.Start ( ) ; ... private void write ( ) { while ( ... ) { ... lock ( myList ) { myList.Add ( ... ) ; } ... if ( ! readThread.IsAlive ) { readThraed = new Thread ( read ) ; readThread.Start ( ) ; } ... } ... } private void read ( ) { bool noMoreTasks = false ; while ( ! noMoreTasks ) { lock ( MyList ) //syncronize with the ADD func . { if ( dataFromClientList.Count > 0 ) { String task = myList.First ( ) ; myList.Remove ( task ) ; } else { noMoreTasks = true ; } } ... } readThread.Abort ( ) ; }",lock shared data using c # "C_sharp : In an app that I 'm writing I have two potentially large sets of data I need to map against each other . One is a List returned from a web service and one is a DataTable . I need to take the ANSI ( or ISO ) number for each item in the list and find the row of the DataTable containing that ANSI number and then do stuff with it.Since DataTable.Select is pretty slow and I would have to do that for each item in the List , I experimented with faster alternatives . Keep in mind that there is no database for the DataTable object . So I ca n't leverage any SQL capabilities or anything like that.I thought the fastest way might be to create a dictionary with a KeyValuePair ( A : Ansi number or I : Iso number ) and use that as a key . The value would be the rest of the row . Creating that dictionary would obviously take a little processing time , but then I could leverage the extremely fast search times of the dictionary to find each row I need and then add the rows back to the table afterwards . So within the foreach loop going for the list I would only have a complexity of O ( 1 ) with the dictionary instead of O ( n ) or whatever DataTable.Select has.To my surprise it turned out the dictionary was incredibly slow . I could n't figure out why until I found out that using a string ( just ANSI number ) instead of a KeyValuePair increased the performance dramatically . I 'm talking hundreds of times faster . How on Earth is that possible ? Here is how I test : I generate a List that simulates the output from the web service . I create a dictionary based on that list with a key ( either string or KeyValuePair ) and the DataRow as value . I go through a foreach loop for that list and search each item in that list in my dictionary and then assign a value to the DataRow that is returned . That 's it.If I use KeyValuePair as a key to access the dictionary it takes seconds for 1,000 items , if I modify the dictionary to take only a string as a key it takes milliseconds for 10,000 items . FYI : I designed the test so that there would always be hits , so all keys are always found.Here is the block of code for which I 'm measuring the time : So how on Earth is it possible that the execution time suddenly becomes hundreds of times longer if I use a Dictionary ( KeyValuePair , DataRow ) instead of Dictionary ( String , DataRow ) ? foreach ( ProductList.Products item in pList.Output.Products ) { //KeyValuePair < string , string > kv = new KeyValuePair < string , string > ( `` A '' , item.Ansi ) ; DataRow row = dict [ item.Ansi ] ; for ( int i = 0 ; i < 10 ; i++ ) { row [ `` Material '' ] = item.Material + `` a '' ; //Do stuff just for debugging } hits++ ; }",Abysmal performance with Dictionary that has a KeyValuePair as key ( C # .NET ) "C_sharp : I try to send this two requests but I only get as a response the errors listed in the title . My two webrequests to the google servers are like this : I get the following output from the Debugger : HttpClient http = new HttpClient ( ) ; HttpResponseMessage response = await http.GetAsync ( `` https : //accounts.google.com/o/oauth2/token ? code= '' +localSettings.Values [ `` AccessKey '' ] + '' & client_id=XX-XXXXXXXXXX.apps.googleusercontent.com & client_secret=XXXXX-XXXX & redirect_uri=http : //localhost/oauth2callback & grant_type=authorization_code '' ) ; //response.EnsureSuccessStatusCode ( ) ; Debug.WriteLine ( response.ToString ( ) ) ; HttpResponseMessage response1 = await http.GetAsync ( `` https : //content.googleapis.com/youtube/v3/subscriptions ? part=id & maxResults=10 & mine=true & key= '' +localSettings.Values [ `` AccessKey '' ] ) ; Debug.WriteLine ( response1.ToString ( ) ) ; StatusCode : 405 , ReasonPhrase : `` , Version : 2.0 , Content : System.Net.Http.StreamContent , Headers : { server : GSE alt-svc : quic= '' :443 '' ; p= '' 1 '' ; ma=604800 cache-control : max-age=0 , private accept-ranges : none date : Tue , 29 Sep 2015 16:05:03 GMT x-frame-options : SAMEORIGIN vary : Accept-Encoding x-content-type-options : nosniff alternate-protocol : 443 : quic , p=1 x-xss-protection : 1 ; mode=block content-type : application/json expires : Tue , 29 Sep 2015 16:05:03 GMT } StatusCode : 400 , ReasonPhrase : `` , Version : 2.0 , Content : System.Net.Http.StreamContent , Headers : { server : GSE alt-svc : quic= '' :443 '' ; p= '' 1 '' ; ma=604800 cache-control : max-age=0 , private accept-ranges : none date : Tue , 29 Sep 2015 16:05:04 GMT x-frame-options : SAMEORIGIN vary : X-Origin vary : Origin vary : Accept-Encoding x-content-type-options : nosniff alternate-protocol : 443 : quic , p=1 x-xss-protection : 1 ; mode=block content-type : application/json ; charset=UTF-8 expires : Tue , 29 Sep 2015 16:05:04 GMT }",Http Request Status Code 405 ReasonPhrase : `` Youtube APi "C_sharp : I wanted to write this LINQ statement : originalResults is of type Dictionary < int , ItemBO > .I get that item is of type KeyValuePair < int , ItemBO > , but would have thought that the cast from a list of that type to a Dictionary of that type would have been ... er ... `` Natural '' .Instead , to get the compiler to shut up , I needed to write this : Which , although not entirely counter-intuitive , suggests that a lot of unnecessary work unpackaging and repackaging the Dictionary is going on under the covers . Is there a better solution ? Is there a concept I 'm missing out on ? Dictionary < int , ItemBO > result = ( Dictionary < int , ItemBO > ) ( from item in originalResults where item.Value.SomeCriteria == true select item ) ; Dictionary < int , ItemBO > result = ( from item in originalResults where item.Value.SomeCriteria == true select item.Value ) .ToDictionary ( GetItemKey ) ;",Coercing a LINQ result list of KeyValuePair into a Dictionary - Missing the Concept "C_sharp : I 've read about new keyword in method signature and have seen the example below on this post , but I still do n't get why to write new keyword in method signature . If we 'll omit it , it still will do the same things . It will compile . There is gon na be a warning , but it will compile.So , writing new in method signature is just for readability ? public class A { public virtual void One ( ) { /* ... */ } public void Two ( ) { /* ... */ } } public class B : A { public override void One ( ) { /* ... */ } public new void Two ( ) { /* ... */ } } B b = new B ( ) ; A a = b as A ; a.One ( ) ; // Calls implementation in Ba.Two ( ) ; // Calls implementation in Ab.One ( ) ; // Calls implementation in Bb.Two ( ) ; // Calls implementation in B",Is using new keyword in method signature generally just for readability ? "C_sharp : I have a WinForms , C # solution that uses ClickOnce deployment that is causing some trouble with resource files . In short , files marked as Content in class library project do not get copied to the output bin/ folders after I deploy with ClickOnce.Here is the basic structure of the solution ( it contains a lot more projects then the ones I list below ) The Main Gui project is the StartUp project for this program and is a simple MDI container that launches the other GUI applications within it . When I build in either Debug/Release mode on my development machine , everything works as expected . The GUI programs are compiled , the Datafile.wav and Mods.xml files are copied to the bin/ folder and the Elements.xml and AminoAcids.xml files are copied to the bin/Resources/ folder . The program functions as expected with no hiccups.Here is where the problem begins , I use the Click-Once publishing feature in VS2010 to release the program internally to my co-workers on our server . They are able to install the program just fine and even start it up . But as soon as they click on a button that uses one of the resource files ( Elements.xml or AminoAcids.xml ) it throws an exception that the file can not be found . This does n't happen for the other two content files ( Datafile.wav and Mods.xml ) in other words , those are correctly copied to the final directory.So I go to Main Gui Project - > Properties - > Publish - > Application Files.. and I see that the Datafile.wav and Mods.xml are included in this list . However , the other two content files ( Elements.xml and AminoAcids.xml ) are not . I believe this is the problem , because when I publish the program to our server , it does n't know to copy the resources over . How would I inform ClickOnce that they need to include these files ? The ClassLibrary.dll shows up in this list , but none of the .xml files.I then tried to go to ClassLibrary - > Properties - > Publish but there is no tab for Publish because it is a Class Library . So I am unable to specify that I want those two resource files to be copied to the final bin/Resources file on any client computer . Does any have any idea how to overcome this ? I would like to keep the resource files ( .xml ) as Build Action : Content and not Embedded Resources since the users of the program might change/update/expand the contents of the files . Solution | -- Gui 1 Project | | -- References | | | -- ClassLibrary | -- Gui 2 Project | | -- References | | | -- ClassLibrary | -- Main Gui Project ( StartUp Project ) | | -- References | | | -- Gui 1 Project | | | -- Gui 2 Project | | | -- ClassLibrary | | -- Datafile.wav ( Build Action : Content , Copy-if-newer ) | | -- Mods.xml ( Build Action : Content , Copy-if-newer ) | | -- VariousSourceFiles.cs | -- ClassLibrary | | -- Resources | | | -- Elements.xml ( Build Action : Content , Copy-if-newer ) | | | -- AminoAcids.xml ( Build Action : Content , Copy-if-newer ) | | -- VariousSourceFiles.cs",Content Defined in Class Library does n't transfer during ClickOnce Deployment "C_sharp : I 've got a few questions about how to provide both synchronous and asynchronous implementation of the same functionality in a library . I am gon na ask them first and then provide the example code below ( which is actually quite a bit , but in fact it 's quite simple ) .Is there an approach to avoid violating the DRY principle ? Consider the implementations of JsonStreamReader.Read , JsonStreamWriter.Write , JsonStreamWriter.Flush , ProtocolMessenger.Send , ProtocolMessenger.Receive and their asynchronous versions.Is there an approach to avoid violating the DRY principle when unit testing both synchronous and asynchronous versions of the same method ? I am using NUnit , although I guess all frameworks should be the same in this regard.How should be implemented a method returning Task or Task < Something > considering the Take 1 and Take 2 variants of ComplexClass.Send and ComplexClass.Receive ? Which one is correct and why ? Is it correct to always include .ConfigureAwait ( false ) after await in a library considering it is not known where the library will be used ( Console application , Windows Forms , WPF , ASP.NET ) ? And here follows the code I am referring to in the first questions.IWriter and JsonStreamWriter : IReader and JsonStreamReader : IMessenger and ProtocolMessenger : ComplexClass : public interface IWriter { void Write ( object obj ) ; Task WriteAsync ( object obj ) ; void Flush ( ) ; Task FlushAsync ( ) ; } public class JsonStreamWriter : IWriter { private readonly Stream _stream ; public JsonStreamWriter ( Stream stream ) { _stream = stream ; } public void Write ( object obj ) { string json = JsonConvert.SerializeObject ( obj ) ; byte [ ] bytes = Encoding.UTF8.GetBytes ( json ) ; _stream.Write ( bytes , 0 , bytes.Length ) ; } public async Task WriteAsync ( object obj ) { string json = JsonConvert.SerializeObject ( obj ) ; byte [ ] bytes = Encoding.UTF8.GetBytes ( json ) ; await _stream.WriteAsync ( bytes , 0 , bytes.Length ) .ConfigureAwait ( false ) ; } public void Flush ( ) { _stream.Flush ( ) ; } public async Task FlushAsync ( ) { await _stream.FlushAsync ( ) .ConfigureAwait ( false ) ; } } public interface IReader { object Read ( Type objectType ) ; Task < object > ReadAsync ( Type objectType ) ; } public class JsonStreamReader : IReader { private readonly Stream _stream ; public JsonStreamReader ( Stream stream ) { _stream = stream ; } public object Read ( Type objectType ) { byte [ ] bytes = new byte [ 1024 ] ; int bytesRead = _stream.Read ( bytes , 0 , bytes.Length ) ; string json = Encoding.UTF8.GetString ( bytes , 0 , bytesRead ) ; object obj = JsonConvert.DeserializeObject ( json , objectType ) ; return obj ; } public async Task < object > ReadAsync ( Type objectType ) { byte [ ] bytes = new byte [ 1024 ] ; int bytesRead = await _stream.ReadAsync ( bytes , 0 , bytes.Length ) .ConfigureAwait ( false ) ; string json = Encoding.UTF8.GetString ( bytes , 0 , bytesRead ) ; object obj = JsonConvert.DeserializeObject ( json , objectType ) ; return obj ; } } public interface IMessenger { void Send ( object message ) ; Task SendAsync ( object message ) ; object Receive ( ) ; Task < object > ReceiveAsync ( ) ; } public interface IMessageDescriptor { string GetMessageName ( Type messageType ) ; Type GetMessageType ( string messageName ) ; } public class Header { public string MessageName { get ; set ; } } public class ProtocolMessenger : IMessenger { private readonly IMessageDescriptor _messageDescriptor ; private readonly IWriter _writer ; private readonly IReader _reader ; public ProtocolMessenger ( IMessageDescriptor messageDescriptor , IWriter writer , IReader reader ) { _messageDescriptor = messageDescriptor ; _writer = writer ; _reader = reader ; } public void Send ( object message ) { Header header = new Header ( ) ; header.MessageName = _messageDescriptor.GetMessageName ( message.GetType ( ) ) ; _writer.Write ( header ) ; _writer.Write ( message ) ; _writer.Flush ( ) ; } public async Task SendAsync ( object message ) { Header header = new Header ( ) ; header.MessageName = _messageDescriptor.GetMessageName ( message.GetType ( ) ) ; await _writer.WriteAsync ( header ) .ConfigureAwait ( false ) ; await _writer.WriteAsync ( message ) .ConfigureAwait ( false ) ; await _writer.FlushAsync ( ) .ConfigureAwait ( false ) ; } public object Receive ( ) { Header header = ( Header ) _reader.Read ( typeof ( Header ) ) ; Type messageType = _messageDescriptor.GetMessageType ( header.MessageName ) ; object message = _reader.Read ( messageType ) ; return message ; } public async Task < object > ReceiveAsync ( ) { Header header = ( Header ) await _reader.ReadAsync ( typeof ( Header ) ) .ConfigureAwait ( false ) ; Type messageType = _messageDescriptor.GetMessageType ( header.MessageName ) ; object message = await _reader.ReadAsync ( messageType ) .ConfigureAwait ( false ) ; return message ; } } public interface ISomeOtherInterface { void DoSomething ( ) ; } public class ComplexClass : IMessenger , ISomeOtherInterface { private readonly IMessenger _messenger ; private readonly ISomeOtherInterface _someOtherInterface ; public ComplexClass ( IMessenger messenger , ISomeOtherInterface someOtherInterface ) { _messenger = messenger ; _someOtherInterface = someOtherInterface ; } public void DoSomething ( ) { _someOtherInterface.DoSomething ( ) ; } public void Send ( object message ) { _messenger.Send ( message ) ; } // Take 1 public Task SendAsync ( object message ) { return _messenger.SendAsync ( message ) ; } // Take 2 public async Task SendAsync ( object message ) { await _messenger.SendAsync ( message ) .ConfigureAwait ( false ) ; } public object Receive ( ) { return _messenger.Receive ( ) ; } // Take 1 public Task < object > ReceiveAsync ( ) { return _messenger.ReceiveAsync ( ) ; } // Take 2 public async Task < object > ReceiveAsync ( ) { return await _messenger.ReceiveAsync ( ) .ConfigureAwait ( false ) ; } }",Using async await when implementing a library with both synchronous and asynchronous API for the same functionality "C_sharp : I have the following method : When mContext is a System.Data.Linq.DataContext everything works great . However , when mContext is an in-memory mock during my uniting testing , the comparison between e.Password and hash always returns false.If I rewrite this comparison as e.Password.SequenceEqual ( hash ) , then my unit tests will pass , but I get an exception when I 'm talking to LinqToSql . ( System.NotSupportedException : The query operator 'SequenceEqual ' is not supported . ) Is there a way that I can write this query that will satisfy my unit tests with an in-memory mock , as well as the production component with LinqToSql ? User IDataContext.AuthenticateUser ( string userName , string password ) { byte [ ] hash = PasswordHasher.HashPassword ( userName , password ) ; var query = from e in mContext.GetTable < User > ( ) where e.Email == userName & & e.Password == hash select e ; return query.FirstOrDefault ( ) ; }",Comparing byte [ ] in LINQ-to-SQL and in a unit test that uses mocking "C_sharp : I 'm having a problem to create a generic View to represent NotFound pages.The view is created and it 's fine . I need to know how i can direct the user to the NotFound view in my Controllers and how to render a specific `` Return to Index '' in each controller.Here is some code : // NotFound View// Controller piece of codeI 'm not sure how to redirect to a whole different page . Can anyone give me any pointers ? Thanks public class NotFoundModel { private string _contentName ; private string _notFoundTitle ; private string _apologiesMessage ; public string ContentName { get ; private set ; } public string NotFoundTitle { get ; private set ; } public string ApologiesMessage { get ; private set ; } public NotFoundModel ( string contentName , string notFoundTitle , string apologiesMessage ) { this._contentName = contentName ; this._notFoundTitle = notFoundTitle ; this._apologiesMessage = apologiesMessage ; } } < % @ Page Title= '' '' Language= '' C # '' MasterPageFile= '' ~/Views/Shared/Site.Master '' Inherits= '' System.Web.Mvc.ViewPage < Geographika.Models.NotFoundModel > '' % > < asp : Content ID= '' Content1 '' ContentPlaceHolderID= '' TitleContent '' runat= '' server '' > < % = Html.Encode ( Model.ContentName ) % > < /asp : Content > < asp : Content ID= '' Content2 '' ContentPlaceHolderID= '' MainContent '' runat= '' server '' > < h2 > < % = Html.Encode ( Model.NotFoundTitle ) % > < /h2 > < p > < % = Html.Encode ( Model.ApologiesMessage ) % > < /p > < ! -- How can i render here a specific `` BackToIndexView '' , but that it 's not bound to my NotFoundModel ? -- > < /asp : Content > // // GET : /Term/Details/2 public ActionResult Details ( int id ) { Term term = termRepository.SingleOrDefault ( t = > t.TermId == id ) ; if ( term == null ) return View ( `` NotFound '' ) ; // how can i return the specific view that its not bound to Term Model ? // the idea here would be something like : // return View ( `` NotFound '' , new NotFoundModel ( `` a '' , '' b '' , '' c '' ) ) ; else return View ( `` Details '' , term ) ; }",Creating a generic NotFound View in ASP.MVC "C_sharp : I am using the settings plugin and I have it working to store some booleans . Now I wanted to add managing a DateTime object . I added the following to Settings.cs : Originally I used the following in my code : When I added some logging I had this : It prints out:1/1/0001 12:00:00 AM1/1/0001 12:30:00 AM1/1/0001 12:00:00 AMWhy does this behavior occur ? private const string TimeRemainingKey = `` time_remaining '' ; private static readonly DateTime TimeRemainingDefault = DateTime.Now ; public static DateTime TimeRemaining { get { return AppSettings.GetValueOrDefault ( TimeRemainingKey , TimeRemainingDefault ) ; } set { AppSettings.AddOrUpdateValue ( TimeRemainingKey , value ) ; } } Settings.TimeRemaining = new DateTime ( ) .AddMinutes ( 30 ) ; DateTime dt = new DateTime ( ) ; Debug.WriteLine ( dt.ToString ( ) ) ; dt = dt.AddMinutes ( 30 ) ; Debug.WriteLine ( dt.ToString ( ) ) ; Settings.TimeRemaining = dt ; Debug.WriteLine ( Settings.TimeRemaining.ToString ( ) ) ;",Settings plugin not working properly with DateTime property "C_sharp : I am coming from the Entity Framework over to NHibernate . When looking at how to create my domain entities I noticed that in some of the examples they do n't include the column of the foreign key relationship . Since the Session class contains a Load ( ) method it is possible to just use objects without the trip to the database instead of primary keys . Is this a normal practice when constructing entity models in NHibernate.Example EntityCreating Entity -- OR -- - public class BlogPost : Entity { public virtual string Name { get ; set ; } //Should this be here public virtual int AuthorID { get ; set ; } public virtual Author Author { get ; set ; } } BlogPost post = new BlogPost { Name = `` My first post '' , Author = session.Load < Author > ( 1 ) //Avoids hitting the database } ; session.Save ( post ) ; BlogPost post = new BlogPost { Name = `` My first post '' , AuthorID = 1 //Use the id of the object } ; session.Save ( post ) ;",Should I have the foreign key column in my entity models ? "C_sharp : I 'm using WinForms . My program opens .Tiff image documents into a picturebox . The problem I 'm having is printing high quality tiff images from the picturebox . I 've tried and tested printing many times . When the document prints the words are not crisp/clear its a little blurry . I tested my printer also to check if there was a problem with my printer . I printed a regular text document using Microsoft word and it printed out clearly , so its an issue with my code.Can someone provide me with the code to print in high quality .tiff images in my picturebox ? Would I need to increase my DPI programmatically to increase the quality of the image ? This is my code . After analyzing my code further , I think I figured out why my pictures are turning out blurry . When I open a Tiff document , I have in my form a back , and forward button for the multiple tiff pages . In the RefreshImage method , I think that ’ s where my images are turning blurry . Here is my code : private void DVPrintDocument_PrintPage ( object sender , System.Drawing.Printing.PrintPageEventArgs e ) { e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic ; e.Graphics.DrawImage ( pictureBox1.Image , 25 , 25 , 800 , 1050 ) ; } private void Print_button_Click ( object sender , EventArgs e ) { PrintPreviewDialog.Document = PrintDocument ; PrintPreviewDialog.ShowDialog ( ) ; } private int intCurrPage = 0 ; // defining the current page ( its some sort of a counter ) bool opened = false ; // if an image was opened // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -Next and Back Button -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - private void btn_Back_Click ( object sender , EventArgs e ) { if ( opened ) // the button works if the file is opened . you could go with button.enabled { if ( intCurrPage == 0 ) // it stops here if you reached the bottom , the first page of the tiff { intCurrPage = 0 ; } else { intCurrPage -- ; // if its not the first page , then go to the previous page RefreshImage ( ) ; // refresh the image on the selected page } } } private void btn_Next_Click ( object sender , EventArgs e ) { if ( opened ) // the button works if the file is opened . you could go with button.enabled { if ( intCurrPage == Convert.ToInt32 ( lblNumPages.Text ) ) // if you have reached the last page it ends here // the `` -1 '' should be there for normalizing the number of pages { intCurrPage = Convert.ToInt32 ( lblNumPages.Text ) ; } else { intCurrPage++ ; RefreshImage ( ) ; } } } private void Form1_Load ( object sender , EventArgs e ) { var bm = new Bitmap ( pictureBox1.Image ) ; bm.SetResolution ( 600 , 600 ) ; Image image1 = new Bitmap ( bm ) ; pictureBox1.Image = image1 ; pictureBox1.Refresh ( ) ; } public void RefreshImage ( ) { Image myImg ; // setting the selected tiff Image myBmp ; // a new occurance of Image for viewing myImg = System.Drawing.Image.FromFile ( @ lblFile.Text ) ; // setting the image from a file int intPages = myImg.GetFrameCount ( System.Drawing.Imaging.FrameDimension.Page ) ; // getting the number of pages of this tiff intPages -- ; // the first page is 0 so we must correct the number of pages to -1 lblNumPages.Text = Convert.ToString ( intPages ) ; // showing the number of pages lblCurrPage.Text = Convert.ToString ( intCurrPage ) ; // showing the number of page on which we 're on myImg.SelectActiveFrame ( System.Drawing.Imaging.FrameDimension.Page , intCurrPage ) ; // going to the selected page myBmp = new Bitmap ( myImg , pictureBox1.Width , pictureBox1.Height ) ; // setting the new page as an image // Description on Bitmap ( SOURCE , X , Y ) pictureBox1.Image = myBmp ; // showing the page in the pictureBox1 }",Print high quality Tiff documents from picturebox C # "C_sharp : Why does Int32 use int in its source code ? Does n't Int32 equal int in C # ? So what is the original source code for int ? I 'm confused..there is the same issue between Boolean and bool too . [ Serializable ] [ System.Runtime.InteropServices.StructLayout ( LayoutKind.Sequential ) ] [ System.Runtime.InteropServices.ComVisible ( true ) ] # if GENERICS_WORK public struct Int32 : IComparable , IFormattable , IConvertible , IComparable < Int32 > , IEquatable < Int32 > /// , IArithmetic < Int32 > # else public struct Int32 : IComparable , IFormattable , IConvertible # endif { internal int m_value ; // Here ? ? ? ? public const int MaxValue = 0x7fffffff ; public const int MinValue = unchecked ( ( int ) 0x80000000 ) ; ... }",Why does ` Int32 ` use ` int ` in its source code ? "C_sharp : I have a custom form object structure I use successfully with mongodb.I 've been investigating the possibility of replacing Mongo with DocumentDb.My Class structure consists of a base control that different types of control inherit from . e.g . Textbox control , Dropdown ControlIn mongo I use the discriminator field to store the actual type , in the c # DocumentDb driver I cant see find the same feature.below is a sample of how mongo stores my class structure.In documentdb the structure looks like As you can see the mongo version has a `` _t '' property stating the actual type , this is then used when I read the data to create the correct type . In the documentdb version it is simply a fieldtype { `` _t '' : `` TextboxControl '' , `` LabelText '' : `` Location of incident '' , `` IsRequired '' : true , `` _id '' : `` cbe059d9-b6a9-4de2-b63b-14d44b022e37 '' } { `` LabelText '' : `` Location of incident '' , `` IsRequired '' : true , `` id '' : `` cbe059d9-b6a9-4de2-b63b-14d44b022e37 '' }",Can I use polymorphism/inheritance in C # DocumentDb driver "C_sharp : I am developing three web applications that are part of a larger system . These are single page applications with an API , and as such I have wildcard route for non API actions that points to my main controller.For two of these applications this works fine but for the third the redirect does n't work and I just get a 404 returned when trying to access a front end route . The setup as far as I can tell is identical and I am completely stumped as to why it is not working.I am using screenshots rather than code snippets so I can show the setup side by side ( working on the left , not working on the right ) .As you can see the key sections of code are identical in both applications and yet one works and one does n't . What have I missed ? Where else should I look ? And any guidance on how I can debug this would be greatly appreciated . .csprojStartup.csThis is the key bit of code which as you can see is identical in both places : Program.csWeb.config app.UseMvc ( routes = > { routes.EnableDependencyInjection ( ) ; routes.MapRoute ( `` default '' , `` { controller=Home } / { action=Index } / { id ? } '' ) ; } ) ; app.MapWhen ( x = > ! x.Request.Path.Value.StartsWith ( `` /api '' , StringComparison.OrdinalIgnoreCase ) , builder = > { builder.UseMvc ( routes = > { routes.MapRoute ( `` spa-fallback '' , `` { *url } '' , new { controller = `` Home '' , action = `` Index '' } ) ; } ) ; } ) ;",ASP.NET Core MVC Wildcard route not working with identical setup to another that is working "C_sharp : I have been learning about the basics of C # but have n't come across a good explanation of what this is : I do n't know what the < string > is doing or if it 's the List that is doing the magic . I have also seen objects been thrown within the < > tags.Can someone explain this to me with examples , please ? var l = new List < string > ( ) ;",What is the `` < > '' syntax within C # "C_sharp : How would one create a fluent interface instead of a more tradition approach ? Here is a traditional approach : Interface : Usage : I 'd like to be able to say : Lastly , is this situation a good fit for fluent interfaces ? Or would a more traditional approach make more sense ? interface IXmlDocumentFactory < T > { XmlDocument CreateXml ( ) //serializes just the data XmlDocument CreateXml ( XmlSchema schema ) //serializes data and includes schema } interface IXmlSchemaFactory < T > { XmlSchema CreateXmlSchema ( ) //generates schema dynamically from type } var xmlDocFactory = new XmlDocumentFactory < Foo > ( foo ) ; var xmlDocument = xmlDocFactory.CreateXml ( ) ; //or ... var xmlDocFactory = new XmlDocumentFactory < Foo > ( foo ) ; var xmlSchemaFactory = new XmlSchemaFactory < Foo > ( ) ; var xmlDocument = xmlDocFactory.CreateXml ( xmlSchemaFactory.CreateXmlSchema ( ) ) ; var xmlDocument = new XmlDocumentFactory < Foo > ( foo ) .CreateXml ( ) .IncludeSchema ( ) ; //or ... var xmlDocument = new XmlDocumentFacotry < Foo > ( foo ) .CreateXml ( ) ;","Trying to understand how to create fluent interfaces , and when to use them" "C_sharp : I 'm a newby to Stack Overflow so please go easy on me ! I 'm reading C # in Depth but I 've come across a scenario that I do n't believe is covered . A quick search of the web did n't throw up any results either.Say I define the following overloaded methods : If I call AreEqual ( ) without specifying a type argument : Is the generic or non-generic version of the method invoked ? Is the generic method invoked with the type argument being inferred , or is the non-generic method invoked with the method arguments being implicitly cast to System.Object ? I hope my question is clear . Thanks in advance for any advice . void AreEqual < T > ( T expected , T actual ) void AreEqual ( object expected , object actual ) AreEqual ( `` Hello '' , `` Hello '' )",Type inference for type arguments of generic methods "C_sharp : Whilst 'investigating ' finalisation ( read : trying stupid things ) I stumbled across some unexpected behaviour ( to me at least ) . I would have expected the Finalise method to not be called , whereas it gets called twice Could anyone explain whether this behaviour is intentional and if so why ? This above code was compiled in x86 debug mode and running on the CLR v4.Many thanks class Program { static void Main ( string [ ] args ) { // The MyClass type has a Finalize method defined for it // Creating a MyClass places a reference to obj on the finalization table . var myClass = new MyClass ( ) ; // Append another 2 references for myClass onto the finalization table . System.GC.ReRegisterForFinalize ( myClass ) ; System.GC.ReRegisterForFinalize ( myClass ) ; // There are now 3 references to myClass on the finalization table . System.GC.SuppressFinalize ( myClass ) ; System.GC.SuppressFinalize ( myClass ) ; System.GC.SuppressFinalize ( myClass ) ; // Remove the reference to the object . myClass = null ; // Force the GC to collect the object . System.GC.Collect ( 2 , System.GCCollectionMode.Forced ) ; // The first call to obj 's Finalize method will be discarded but // two calls to Finalize are still performed . System.Console.ReadLine ( ) ; } } class MyClass { ~MyClass ( ) { System.Console.WriteLine ( `` Finalise ( ) called '' ) ; } }",Can anyone explain this finalisation behaviour "C_sharp : We can cast Span < T > and ReadOnlySpan < T > to another using MemoryMarshal.Cast method overloads . Like : But is there any way to cast Memory < T > to another ? for example cast Memory < byte > to Memory < ushort > . Span < byte > span = stackalloc byte [ 4 ] ; var singleIntSpan = MemoryMarshal.Cast < byte , int > ( span ) ;",How can I cast Memory < T > to another "C_sharp : first time I write on the SO , because he could not find solution myself.At the interview , I was given the task to write a method that checks the characters in the string to a unique . Requirements : not using LINQ . Desirable : do not use additional data types ( Dictionary , HashSet ... etc . Arrays and lists Allowed ) Example : My implementation : But it does not meet the requirements of data types , and is not the best performance ... I also tried the approach with a dictionary : But he is no better than the previous . I will welcome any idea how to solve this task better ? p.s `` Hello '' - return false ; `` Helo '' - return true static HashSet < char > charSet = new HashSet < char > ( ) ; static bool IsUniqueChar ( string str ) { foreach ( char c in str ) { charSet.Add ( c ) ; } return charSet.Count ( ) == str.Length ; } static Dictionary < char , bool > charSetDictionary = new Dictionary < char , bool > ( ) ; static bool IsUniqueChar ( string str ) { try { foreach ( char c in str ) { charSetDictionary.Add ( c , true ) ; } } catch { return false ; } static void Main ( string [ ] args ) { Stopwatch sw = Stopwatch.StartNew ( ) ; IsUniqueChar ( `` Hello '' ) ; sw.Stop ( ) ; Console.WriteLine ( `` Elapsed= { 0 } '' , sw.Elapsed ) ; //~005044 }",Check string on duplicate char "C_sharp : I saw Jon Skeet give a talk a year or so ago where he showed a snippet of C # 5 that would take a list of Tasks and return them in the order they completed.It made use of async/await and WhenAny and was quite beautiful but I ca n't for the life of me remember how it worked . Now I have need for it.I 'm hoping to figure out how to create a method with a signature similar to this..And could be used as follows : I 've come up with the following but it does n't feel as simple as I rememberDo anyone remember know the snippet I 'm referring to or how this can be improved upon ? Task < IEnumerable < T > > InOrderOfCompletion < T > ( IEnumerable < T > tasks ) where T : Task public async Task < int > DelayedInt ( int i ) { await Task.Delay ( i*100 ) ; return i ; } [ Test ] public async void Test ( ) { Task < int > [ ] tasks = new [ ] { 5 , 7 , 1 , 3 , 2 , 6 , 4 } .Select ( DelayedInt ) .ToArray ( ) ; IEnumerable < Task < int > > ordered = await InOrderOfCompletion ( tasks ) ; Assert.That ( ordered.Select ( t = > t.Result ) .ToArray ( ) , Is.EqualTo ( new [ ] { 1,2,3,4,5,6,7 } ) ) ; } async Task < IEnumerable < T > > InOrderOfCompletion < T > ( IEnumerable < T > tasks ) where T : Task { HashSet < Task > taskSet = new HashSet < Task > ( tasks ) ; List < T > results = new List < T > ( ) ; while ( taskSet.Count > 0 ) { T complete = ( T ) await Task.WhenAny ( taskSet ) ; taskSet.Remove ( complete ) ; results.Add ( complete ) ; } return results ; }",Sort Tasks into order of completition "C_sharp : I have a plugin system where I use MarshalByRefObject to create isolated domains per plugin , so users can reload their new versions , as they see fit without having to turn off the main application.Now I have the need to allow a plugin to view which plugins are currently running and perhaps start/stop a specific plugin.I know how to issue commands from the wrapper , in the below code for example : So then I could , for example : Of course the above is just a resumed sample ... Then on my wrapper I have methods like : Which basically is a wrapper to issue the Start/Stop of a specific plugin from the list and a list to keep track of running plugins : Plugin is just a simple class that holds Domain , RemoteLoader information , etc.What I do n't understand is , how to achieve the below , from inside a plugin . Be able to : View the list of running pluginsExecute the Start or Stop for a specific pluginOr if this is even possible with MarshalByRefObject given the plugins are isolated or I would have to open a different communication route to achieve this ? For the bounty I am looking for a working verifiable example of the above described ... using System ; using System.Linq ; using System.Reflection ; using System.Security.Permissions ; namespace Wrapper { public class RemoteLoader : MarshalByRefObject { private Assembly _pluginAassembly ; private object _instance ; private string _name ; public RemoteLoader ( string assemblyName ) { _name = assemblyName ; if ( _pluginAassembly == null ) { _pluginAassembly = AppDomain.CurrentDomain.Load ( assemblyName ) ; } // Required to identify the types when obfuscated Type [ ] types ; try { types = _pluginAassembly.GetTypes ( ) ; } catch ( ReflectionTypeLoadException e ) { types = e.Types.Where ( t = > t ! = null ) .ToArray ( ) ; } var type = types.FirstOrDefault ( type = > type.GetInterface ( `` IPlugin '' ) ! = null ) ; if ( type ! = null & & _instance == null ) { _instance = Activator.CreateInstance ( type , null , null ) ; } } public void Start ( ) { if ( _instance == null ) { return ; } ( ( IPlugin ) _instance ) .OnStart ( ) ; } public void Stop ( ) { if ( _instance == null ) { return ; } ( ( IPlugin ) _instance ) .OnStop ( close ) ; } } } var domain = AppDomain.CreateDomain ( Name , null , AppSetup ) ; var assemblyPath = Assembly.GetExecutingAssembly ( ) .Location ; var loader = ( RemoteLoader ) Domain.CreateInstanceFromAndUnwrap ( assemblyPath , typeof ( RemoteLoader ) .FullName ) ; loader.Start ( ) ; bool Start ( string name ) ; bool Stop ( string name ) ; List < Plugin > Plugins",How can I communicate between plugins ? C_sharp : I have for example 5 List all of the same type . Can I simply do List < T > newset = List1.Concat ( List2 ) .Concat ( List3 ) .Concat ( List4 ) ... ..,List < T > Concatenation for ' X ' amount of lists "C_sharp : Toying with making a compiler for my own language , I 'm trying to generate some MSIL code using the Reflection.Emit framework . It works fine when using int when I declare local variables . However , when I want to declare a local variable of a type I have not yet compiled I get into trouble since the DeclareLocal ( ) takes a Type as argument . That is my uncompiled class , say A , still needs to be defined using So how will I ever be able to compile the following program assemblyBuilder = Thread.GetDomain ( ) .DefineDynamicAssembly ( assemName , AssemblyBuilderAccess.RunAndSave ) ; module = assemblyBuilder.DefineDynamicModule ( Filename ) ; module.DefineType ( name , TypeAttributes.Public | TypeAttributes.Class ) class A { void M ( ) { B b = new B ( ) ; } } class B void M ( ) { A a = new A ( ) ; } }",ILGenerator.DeclareLocal ( ) takes a type of a class not yet compiled "C_sharp : I was searching right here on StackOverflow and found the answer to Mute Volume in C # . I do n't understand what 's going on with the answer . I 've never gotten deep into Marshaling or P/Invoke . I 've used them before but never understood what I was doing.So here 's what I 'm confused about : When declaring these , does it matter what they are named , or are they just treated like any integer regardless of what they 're called ? Where do the values 0x80000 and 0x319 come from ? private const int APPCOMMAND_VOLUME_MUTE = 0x80000 ; private const int WM_APPCOMMAND = 0x319 ;",What are `` APPCOMMAND '' variables used with P/Invoke ? "C_sharp : I 've got a really weird problem related to .NET 4.5.Today a User told me that he is n't able to enter floating numbers into a Textbox ( like `` 2.75 '' ) .The textbox just does n't accept `` . `` , which is the correct 'seperator ' for floating numbers in my Culture ( `` de-CH '' ) .This issue occurred after I compiled the software with .NET 4.5 ( formerly it was 4.0 ) .I can reproduce this error . All other textboxes in the application are working fine.The textbox is a regular WPF Control . No fancy user defined control or anything like that.Again : the textbox just does n't accept ' . ' as a character . It seems that it completely ignores it . Every other character ( even special ones like `` @ '' ) are fine.Recompiling the application on .NET 4.0 solves the problem.The xaml for the textbox is : Definition of ProcessHours : Hours_TextChanged is : UpdateHoursValidity ( ) just fades a Text Message below the actual textbox . It is not connected with the `` broken '' textbox in any way : So nothing fancy here either.What I tried so far : - removing the textbox , recompiling , adding the textbox again , recompiling - > same situationSetting the Language property of the textbox specifically in xaml ( Language=de-CH ) Setting the culture according to these tips : how to set default culture info for entire c # application Setting the culture according to this blogpost : http : //www.west-wind.com/weblog/posts/2009/Jun/14/WPF-Bindings-and-CurrentCulture-FormattingThere is NO Message on the debugconsole when I try to enter a `` . `` .Any ideas on this one ? Thanks in advance ! < TextBox x : Name= '' _Hours '' Grid.Row= '' 9 '' Grid.Column= '' 1 '' VerticalAlignment= '' Center '' TextAlignment= '' Center '' FontWeight= '' Bold '' FontSize= '' 16 '' Text= '' { Binding ProcessHours , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' TextChanged= '' Hours_TextChanged '' / > partial class ProjectTask { ... public double TotalProcessHours { get { return ProjectBookings.Sum ( b = > b.ProcessHours ) ; } } ... } private void Hours_TextChanged ( object sender , TextChangedEventArgs e ) { UpdateHoursValidity ( ) ; } private void UpdateHoursValidity ( ) { string key = IsInvalidHoursWarning ? `` ShowWarningStoryboard '' : `` HideWarningStoryboard '' ; var storyboard = FindResource ( key ) as Storyboard ; if ( storyboard ! = null ) storyboard.Begin ( ) ; }",Weird TextBox issues with .NET 4.5 - no ' . ' allowed "C_sharp : I have a Console Application project written in C # which I 've added Application Insights to with the following NuGet packages.I 've configured my InstrumentationKey in the config file and I 'm firing up a TelemetryClient on startup using the with the following code : Everything is working well except AI is not capturing any requests that get sent to Mongo , I can see requests going off to SQL server in the 'Application map ' but no sign of any other external requests . Is there any way that I can see telemetry of requests made to Mongo ? EDIT - Thanks to Peter Bons I ended up with pretty much the following which works like a charm and allows me to distinguish between success and failure : Microsoft.ApplicationInsightsMicrosoft.ApplicationInsights.Agent.InterceptMicrosoft.ApplicationInsights.DependencyCollectorMicrosoft.ApplicationInsights.NLogTargetMicrosoft.ApplicationInsights.PerfCounterCollectorMicrosoft.ApplicationInsights.WebMicrosoft.ApplicationInsights.WindowsServerMicrosoft.ApplicationInsights.WindowsServer.TelemetryChannel var telemetryClient = new TelemetryClient ( ) ; telemetryClient.Context.User.Id = Environment.UserName ; telemetryClient.Context.Session.Id = Guid.NewGuid ( ) .ToString ( ) ; telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString ( ) ; var telemetryClient = new TelemetryClient ( ) ; var connectionString = connectionStringSettings.ConnectionString ; var mongoUrl = new MongoUrl ( connectionString ) ; var mongoClientSettings = MongoClientSettings.FromUrl ( mongoUrl ) ; mongoClientSettings.ClusterConfigurator = clusterConfigurator = > { clusterConfigurator.Subscribe < CommandSucceededEvent > ( e = > { telemetryClient.TrackDependency ( `` MongoDB '' , e.CommandName , DateTime.Now.Subtract ( e.Duration ) , e.Duration , true ) ; } ) ; clusterConfigurator.Subscribe < CommandFailedEvent > ( e = > { telemetryClient.TrackDependency ( `` MongoDB '' , $ '' { e.CommandName } - { e.ToString ( ) } '' , DateTime.Now.Subtract ( e.Duration ) , e.Duration , false ) ; } ) ; } ; var mongoClient = new MongoClient ( mongoClientSettings ) ;",How to track MongoDB requests from a console application "C_sharp : I have a fairly complex piece of logic that generates a IQueryable for me that I use to return data from my database using Fluent.NHibernate.However , I need to be able to store the results of this query back into the database ( just the primary keys really but that is kind of a side issue ) How can I generate an insert statement based on the IQueryable I already have to get SQL like the example below generated : INSERT INTO MySavedResults ( Id , FirstName , LastName ) SELECT Id , FirstName , LastName FROM MemberWHERE FirstName = 'John ' and LastName ='Snow ' and ... -- more conditions","Using Fluent.NHibernate , how can I do an Insert based on a Select statement" "C_sharp : I have implemented a basic data binding in code behind , this is the code : And this is the converter 's code , Even though I do n't receive compiler 's error message , but the binding code is not working . Why ? Binding bindingSlider = new Binding ( ) ; bindingSlider.Source = mediaElement.Position ; bindingSlider.Mode = BindingMode.TwoWay ; bindingSlider.Converter = ( IValueConverter ) Application.Current.Resources [ `` DoubleTimeSpan '' ] ; slider.SetBinding ( Slider.ValueProperty , bindingSlider ) ; class DoubleTimeSpan : IValueConverter { public object Convert ( object value , Type targetType , object parameter , string language ) { return ( ( TimeSpan ) value ) .TotalSeconds ; } public object ConvertBack ( object value , Type targetType , object parameter , string language ) { return TimeSpan.FromSeconds ( ( double ) value ) ; } }",C # binding not working "C_sharp : I have a WCF service hosted in IIS that is retrieving data from multiple sources ( all SQL Server ) . With each data source , I have to impersonate a different Active Directory user to connect to the database . I am using Entity Framework v6.1.1 for two of the data sources . Integrated Security is set to True in the connection strings , too.I use the example below to set the impersonated user , where the impersonated user is a System.Security.Principal.WindowsImpersonationContext that I set from configuration : The problem is that the previous code throws a SqlException saying that the account running the web service can not log on to the database . It appears that when I hit the await I lose the impersonation context.What are some suggestions to solve this problem ? internal async Task < List < string > > GetItemsByLookupItemsAsync ( List < string > lookupItems ) { var result = new List < string > ( ) ; using ( var db = new EntityFrameworkDb ( ) ) { var query = from item in db.Table where lookupItems.Contains ( item.LookupColumn ) select item.StringColumn ; var queryResult = new List < string > ( ) ; using ( GetImpersonatedUser ( ) ) { queryResult.AddRange ( await query.ToListAsync ( ) ) ; } result.AddRange ( queryResult.OrderBy ( e = > e ) ) ; } return result ; }",Async/Await with Entity Framework 6.1.1 and impersonation "C_sharp : I 'm having a heck of an issue with the following : I have a generic class , with a constraint , that derives from a non-generic interface : This code is not correct through , because it thinks IDrilldown is a constraint , when its NOT . What I want is for the class DrilldownBase to inherit from IDrilldown . What am I missing ? Thanks . public abstract class DrilldownBase < W > where W : class , IDrilldown","Constraint syntax with generics , also deriving from a class" "C_sharp : I have implemented IErrorHandler to handle authorization exceptions thrown within the constructor of my restful WCF service . When a general exception is caught my custom type is returned as expected , but the ContentType header is incorrect.However when the error handler tries to return a 401 Unauthorized http status code the message body is overridden to the default type but the ContentType header is as it should be . Obviously something is wrong here , but I 'm not sure what.How do I implement IErrorHandler such that it returns my custom type in json with the correct headers ? BaseDataResponseContract Object : This is the object I want to return . All of the other objects in my application inherit from this object . When an exception is thrown all we really care about is the http status code and the error message.IErrorHandler Implementation ( logging is not shown for brevity ) : IServiceBehavior Implementation : Web.Config : Finally , I am seeing similar behavior when using WebFaultException . My thought is that this is the result of some deeply buried .Net shenanigans . I am choosing to implement IErrorHandler so that I can catch any other exceptions that may not be handled . Reference : https : //msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler ( v=vs.100 ) .aspxhttp : //www.brainthud.com/cards/5218/25441/which-four-behavior-interfaces-exist-for-interacting-with-a-service-or-client-description-what-methods-do-they-implement-andOther Examples : IErrorHandler does n't seem to be handling my errors in WCF .. any ideas ? How to make custom WCF error handler return JSON response with non-OK http code ? How do you set the Content-Type header for an HttpClient request ? HTTP/1.1 500 Internal Server ErrorContent-Type : application/xml ; ... { `` ErrorMessage '' : '' Error ! '' } HTTP/1.1 401 UnauthorizedContent-Type : application/json ; ... { `` Message '' : '' Authentication failed . `` , '' StackTrace '' : null , '' ExceptionType '' : '' System.InvalidOperationException '' } [ Serializable ] [ DataContract ( Name = `` BaseDataResponseContract '' ) ] public class BaseDataResponseContract { [ DataMember ] public string ErrorMessage { get ; set ; } } // end namespace WebServices.BehaviorsAndInspectors { public class ErrorHandler : IErrorHandler { public bool HandleError ( Exception error ) { return true ; } // end public void ProvideFault ( Exception ex , MessageVersion version , ref Message fault ) { // Create a new instance of the object I would like to return with a default message var baseDataResponseContract = new BaseDataResponseContract { ErrorMessage = `` Error ! '' } ; // Get the outgoing response portion of the current context var response = WebOperationContext.Current.OutgoingResponse ; // Set the http status code response.StatusCode = HttpStatusCode.InternalServerError ; // If the exception is a specific type change the default settings if ( ex.GetType ( ) == typeof ( UserNotFoundException ) ) { baseDataResponseContract.ErrorMessage = `` Invalid Username ! `` ; response.StatusCode = HttpStatusCode.Unauthorized ; } // Create the fault message that is returned ( note the ref parameter ) fault = Message.CreateMessage ( version , `` '' , baseDataResponseContract , new DataContractJsonSerializer ( typeof ( BaseDataResponseContract ) ) ) ; // Tell WCF to use JSON encoding rather than default XML var webBodyFormatMessageProperty = new WebBodyFormatMessageProperty ( WebContentFormat.Json ) ; fault.Properties.Add ( WebBodyFormatMessageProperty.Name , webBodyFormatMessageProperty ) ; // Add ContentType header that specifies we are using json var httpResponseMessageProperty = new HttpResponseMessageProperty ( ) ; httpResponseMessageProperty.Headers [ HttpResponseHeader.ContentType ] = `` application/json '' ; fault.Properties.Add ( HttpResponseMessageProperty.Name , httpResponseMessageProperty ) ; } // end } // end class } // end namespace namespace WebServices.BehaviorsAndInspectors { public class ErrorHandlerExtensionBehavior : BehaviorExtensionElement , IServiceBehavior { public override Type BehaviorType { get { return GetType ( ) ; } } protected override object CreateBehavior ( ) { return this ; } private IErrorHandler GetInstance ( ) { return new ErrorHandler ( ) ; } void IServiceBehavior.AddBindingParameters ( ServiceDescription serviceDescription , ServiceHostBase serviceHostBase , Collection < ServiceEndpoint > endpoints , BindingParameterCollection bindingParameters ) { } // end void IServiceBehavior.ApplyDispatchBehavior ( ServiceDescription serviceDescription , ServiceHostBase serviceHostBase ) { var errorHandlerInstance = GetInstance ( ) ; foreach ( ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers ) { dispatcher.ErrorHandlers.Add ( errorHandlerInstance ) ; } } void IServiceBehavior.Validate ( ServiceDescription serviceDescription , ServiceHostBase serviceHostBase ) { } // end } // end class } // end namespace < system.serviceModel > < services > < service name= '' WebServices.MyService '' > < endpoint binding= '' webHttpBinding '' contract= '' WebServices.IMyService '' / > < /service > < /services > < extensions > < behaviorExtensions > < ! -- This extension if for the WCF Error Handling -- > < add name= '' ErrorHandlerBehavior '' type= '' WebServices.BehaviorsAndInspectors.ErrorHandlerExtensionBehavior , WebServices , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null '' / > < /behaviorExtensions > < /extensions > < behaviors > < serviceBehaviors > < behavior > < serviceMetadata httpGetEnabled= '' true '' / > < serviceDebug includeExceptionDetailInFaults= '' true '' / > < ErrorHandlerBehavior / > < /behavior > < /serviceBehaviors > < /behaviors > ... . < /system.serviceModel >",IErrorHandler returning wrong message body when HTTP status code is 401 Unauthorized "C_sharp : I came across this c # code in a project today and I could n't help but question its efficiency : Being from a Java background , the spList.GetItems ( query ) definitely made me think that its a performance hit . I would 've done something like the following to improve it : However , the code is in C # ... So my question is : would the code I suggested above improve performance , or have I missed something fundamental about C # 's foreach loop ? Thanks . SPList spList = spWeb.GetListCustom ( `` tasks '' ) ; foreach ( SPListITem item in spList.GetItems ( query ) ) { // ... do something with the SPListCollection it returned } SPList spList = spWeb.GetListCustom ( `` tasks '' ) ; SPListIteCollection taskListCollection = taskList.GetItems ( query ) ; foreach ( SPListITem item in taskListCollection ) { // ... do something with the SPListCollection it returned }",Efficiency of putting a query in the C # foreach condition "C_sharp : This code wo n't compile : But if I delete last string arguments everything is fine : Question is - why these optional string arguments break compiler 's choice of method call ? Added : Clarified question : I dont get why compiler ca n't choose right overload in the first case but could do it in second one ? Edited : [ CallerMemberName ] attribute is not a cause of a problem here so I 've deleted it from question . using System ; using System.Runtime.CompilerServices ; static class Extensions { public static void Foo ( this A a , Exception e = null , string memberName = `` '' ) { } public static void Foo < T > ( this A a , T t , Exception e = null , string memberName = `` '' ) where T : class , IB { } } interface IB { } class A { } class Program { public static void Main ( ) { var a = new A ( ) ; var e = new Exception ( ) ; a.Foo ( e ) ; // < - Compile error `` ambiguous call '' } } public static void Foo ( this A a , Exception e = null ) { } public static void Foo < T > ( this A a , T t , Exception e = null ) where T : class , IB { }",Ambiguous extension method call "C_sharp : Do you see any pitfalls or issues when spawning off two separate tasks for an Oracle db query and Active Directory query and then waiting for both.Below is a very basic stripped down example . Essentially we have an employee object that gets created from pieces of info from AD and from an Oracle DB . ( called sequentially ) At this point Employee object has been created and pieced together from both queries and can be used . This has worked without issue , but if each of these calls were its own task would you see any issues from a scaling view point ? ( excluding any other obvious code issues ) I did some test with the stopwatch class and the Task version comes back faster every time ( avg : 100-120ms vs 200-250ms ) and has no problem , but was n't sure how this scaled on a multicore system . I 've not done a lot with TPL , but was curious on this approach . var partialEmployeeA=ActiveDirectoryLookup ( employeeID ) ; var partialEmployeeB=OracleDBLookup ( employeeID ) ; var finalEmployee=Merge ( partialEmployeeA , partialEmployeeB ) ; Employee partialEmployeeA ; Employee partialEmployeeB ; var t1 = Task.Run ( ( ) = > { partialEmployeeA=ActiveDirectoryLookup ( employeeID ) ; } ) ; var t2 = Task.Run ( ( ) = > { partialEmployeeB=OracleDBLookup ( employeeID ) ; } ) ; , Task.WaitAll ( t1 , t2 ) ; var finalEmployee=Merge ( partialEmployeeA , partialEmployeeB ) ;",background thread using Task.Run "C_sharp : I 'm using WatiN for some automated tests and what I found was that creating an IE instance for every test was not scalable . The creation and shutdown time of each IE instance was eating me alive : However , the using statement did prove useful in that I can always ensure that my IE instance would have its dispose ( ) method called which would close the IE window.Anyway , I created a singleton which maintained a single IE instance which all my tests use across all my test classes : And the test now : This works well and my tests run much faster now that I 'm not opening and closing IE every test . However , I have this one problem in that when the tests complete my IE instance will still remain open . I ca n't figure out an elegant way to ensure that BrowserPool.Browser has dispose ( ) or close ( ) called on it before the application ends . I even tried using a finalizer in the BrowserPool class but that did n't seem to work because the _browser variable had already been reclaimed when my finalizer is called.How can I ensure that dispose ( ) is called on my IE instance after the test run ? [ TestMethod ] public void Verify_Some_Useful_Thing ( ) { using ( var browser = new IE ( ) ) { browser.GoTo ( `` /someurl '' ) ; // etc.. // some assert ( ) statements } } public class BrowserPool { private static readonly Lazy < BrowserPool > _instance = new Lazy < BrowserPool > ( ( ) = > new BrowserPool ( ) ) ; private IE _browser ; private string _ieHwnd ; private int _threadId ; public IE Browser { get { var currentThreadId = GetCurrentThreadId ( ) ; if ( currentThreadId ! = _threadId ) { _browser = IE.AttachTo < IE > ( Find.By ( `` hwnd '' , _ieHwnd ) ) ; _threadId = currentThreadId ; } return _browser ; } set { _browser = value ; _ieHwnd = _browser.hWnd.ToString ( ) ; _threadId = GetCurrentThreadId ( ) ; } } /// < summary > /// private to prevent direct instantiation . /// < /summary > private BrowserPool ( ) { Browser = new IE ( ) ; } /// < summary > /// Get the current executing thread 's id . /// < /summary > /// < returns > Thread Id. < /returns > private int GetCurrentThreadId ( ) { return Thread.CurrentThread.GetHashCode ( ) ; } /// < summary > /// Accessor for instance /// < /summary > public static BrowserPool Instance { get { return _instance ; } } } [ TestMethod ] public void Verify_Some_Useful_Thing ( ) { var browser = BrowserPool.Instance.Browser ; browser.GoTo ( `` /someurl '' ) ; // some assertions }",How can I ensure that I dispose of an object in my singleton before the application closes ? "C_sharp : Is it possible to have a generic constraint which is an unbounded generic type ? For example : Edit : Just to explain the context , I want to constrain the usage of the method to an IDictionary , but for the method itself it does not matter exactly what TKey and TValue are . public T DoSomething < T > ( T dictionary ) where T : IDictionary < , > { ... }",C # unbounded generic type as constrain "C_sharp : Check the code bellow : I do n't understand how it would be useful in my code , could n't I just do a method like : Would n't it be easier and clearer to implement ? class Money { public Money ( decimal amount ) { Amount = amount ; } public decimal Amount { get ; set ; } public static implicit operator decimal ( Money money ) { return money.Amount ; } public static explicit operator int ( Money money ) { return ( int ) money.Amount ; } } public static int returnIntValueFrom ( Money money ) { return ( int ) money.Amount ; }",Why should I use implicit/explicit operator ? C_sharp : How are 4 bytes chars are represented in C # ? Like one char or a set of 2 chars ? var someCharacter = ' x ' ; //put 4 bytes UTF-16 character,How are 4 bytes characters represented in C # "C_sharp : I have written a c # console app which I 've deployed to an Azure Webjob . The app runs fine locally but on Azure I get the error : I think I 've tracked it down to accessing a certificate file . I have added it to a Resources.resx in the project 's properties and I 'm accessing the cert with the following ( also the line it 's failing on ) Is this the correct way , or is there a better way . I 've tried using a relative path in AppSettings but failed with this as well.As a side note , I have put the plain text password in AppSettings for now but will handle this better when my concept is proven . Is there a discussion on how to store passwords like this , and whether the certificate should be created without a password ? [ 09/16/2015 10:40:35 > 998fb8 : SYS ERR ] Job failed due to exit code -1073740940 X509Certificate2 _certificate = new X509Certificate2 ( echoService.Properties.Resources.public_privatekey , ConfigurationManager.AppSettings [ `` certPsw '' ] ) ;",Azure Webjob failing Exit Code -1073740940 C_sharp : We have a class structure as listed belowThere are two lists – 1 ) List of Costpage and Items present in the database 2 ) User selected costpagesQUESTIONWe need to compare these two lists and get a resultant list that has costpages for which the count of distinct items in the actual set and selected set are same.What is the best performing LINQ for this ( in Chain-Method approach ) ? EXPECTED RESULTExpected Result based on the following scenario is a list with only 1 costpage – “ C2 ” ( for which items match ) CODE public class ItemDTO { public int ItemID { get ; set ; } } public class CostPageDTO { public string CostPageNumber { get ; set ; } public List < ItemDTO > Items { get ; set ; } } static void Main ( string [ ] args ) { List < CostPageDTO > selectedCostPageAndItems = GetSelectedCostPageAndItems ( ) ; List < CostPageDTO > actualItems = GetActualItems ( ) ; //LINQ code to get the matching count costPages } private static List < CostPageDTO > GetSelectedCostPageAndItems ( ) { ItemDTO i1 = new ItemDTO ( ) ; i1.ItemID = 1 ; ItemDTO i2 = new ItemDTO ( ) ; i2.ItemID = 2 ; ItemDTO i3 = new ItemDTO ( ) ; i3.ItemID = 3 ; CostPageDTO c1 = new CostPageDTO ( ) ; c1.CostPageNumber = `` C1 '' ; c1.Items = new List < ItemDTO > ( ) ; c1.Items.Add ( i1 ) ; CostPageDTO c2 = new CostPageDTO ( ) ; c2.CostPageNumber = `` C2 '' ; c2.Items = new List < ItemDTO > ( ) ; c2.Items.Add ( i2 ) ; c2.Items.Add ( i3 ) ; //CostPageDTO c2Duplicate = new CostPageDTO ( ) ; //c2Duplicate.CostPageNumber = `` C2 '' ; //c2Duplicate.Items = new List < ItemDTO > ( ) ; //c2Duplicate.Items.Add ( i2 ) ; //c2Duplicate.Items.Add ( i3 ) ; List < CostPageDTO > selectedCostPageAndItems = new List < CostPageDTO > ( ) ; selectedCostPageAndItems.Add ( c1 ) ; selectedCostPageAndItems.Add ( c2 ) ; //selectedCostPageAndItems.Add ( c2Duplicate ) ; return selectedCostPageAndItems ; } private static List < CostPageDTO > GetActualItems ( ) { ItemDTO i1 = new ItemDTO ( ) ; i1.ItemID = 1 ; ItemDTO i2 = new ItemDTO ( ) ; i2.ItemID = 2 ; ItemDTO i3 = new ItemDTO ( ) ; i3.ItemID = 3 ; ItemDTO i3Duplicate = new ItemDTO ( ) ; i3Duplicate.ItemID = 3 ; CostPageDTO c1 = new CostPageDTO ( ) ; c1.CostPageNumber = `` C1 '' ; c1.Items = new List < ItemDTO > ( ) ; c1.Items.Add ( i1 ) ; c1.Items.Add ( i2 ) ; c1.Items.Add ( i3 ) ; CostPageDTO c2 = new CostPageDTO ( ) ; c2.CostPageNumber = `` C2 '' ; c2.Items = new List < ItemDTO > ( ) ; c2.Items.Add ( i2 ) ; c2.Items.Add ( i3 ) ; c2.Items.Add ( i3Duplicate ) ; List < CostPageDTO > actualItems = new List < CostPageDTO > ( ) ; actualItems.Add ( c1 ) ; actualItems.Add ( c2 ) ; return actualItems ; },LINQ for comparing two lists with complex entities "C_sharp : On this page , I see the following code : But I do n't understand why it is the way it is.Why attributes & FileAttributes.Hidden ) ? What does the singular check on attributes actually do ? Does it check if it 's not null ? I have a feeling I know , but it seems weird . Random and weird . if ( ( attributes & FileAttributes.Hidden ) == FileAttributes.Hidden )",How does if ( ( attributes & FileAttributes.Hidden ) == FileAttributes.Hidden ) { } work ? "C_sharp : I am at a loss to understand why this Test would fail with Message `` Assert.AreEqual failed . Expected : < 2 > . Actual : < 1 > . `` but the following would pass : [ TestMethod ] public void Test ( ) { char [ ] a1 = `` abc '' .ToCharArray ( ) ; char [ ] a2 = { ' a ' , ' b ' , ' c ' , ' ' , ' ' } ; Assert.AreEqual ( 2 , a2.Except ( a1 ) .Count ( ) ) ; } [ TestMethod ] public void Test ( ) { char [ ] a1 = `` abc '' .ToCharArray ( ) ; char [ ] a2 = { ' a ' , ' b ' , ' c ' , ' ' , 'd ' , ' ' } ; Assert.AreEqual ( 2 , a2.Except ( a1 ) .Count ( ) ) ; }",C # Linq Char arrays Except ( ) - Weird behavior "C_sharp : I have a class , instances of which need to be disposed . I also have several classes that produce these instances , either singly or lists of them.Should I return IList < MyClass > from my methods or should I create a class that is MyClassCollection which is also disposable and return this instead ? EDIT : My main reason for asking is that I have ended up doing this quite a lot : and it seems that I would be better doing : IList < MyObject > list = GetList ( ) ; foreach ( MyObject obj in list ) { //do something obj.Dispose ( ) ; } using ( IList < MyObject > list = GetList ( ) ) { foreach ( MyObject obj in list ) { //do something } }",Should I have methods which return lists of Disposable instances ? "C_sharp : I have a custom WebControl which implements a .Value getter/setter returning a Nullable < decimal > It 's a client-side filtered textbox ( a subclass of TextBox with included javascript and some server side logic for setting/getting the value ) Here is the getter & the setter from that control : The problem that I 'm seeing is that the output from this statement : I am seeing Amount being set to `` 0 '' when uxAmount.Value returns 10000.This worked as I expected ( excuse the change in casing ) : I have also seen this behaviour ( recently ) when calling a UDF function defined on a Linq2Sql data context along with the null coalescing operator , that is I knew my UDF call returned the expected value but I was getting the RHS value instead.Further confusing me , if I evaluate uxAmount.Value in the watch , I get 10000 of type Nullable < decimal > .Here are some expressions I 've tried : Then I added this expression following the above 4Now It seems like the last call is always 0 , but the value of uxAmount.Value ( which is parsed out of .Text as per above getter/setter using a TryParse is stable . I 'm stopped at a breakpoint and there 's no other threads that could manipulate this value.Note the use of the M suffix to force the constant to decimal as it was integer and I suspected a type conversion issue.Any ideas ? The value of both the LHS and RHS appear to be stable and known. -- edit -- some screengrabs from VS2010 public decimal ? Value { get { decimal amount = 0 ; if ( ! decimal.TryParse ( this.Text , NumberStyles.Currency , null , out amount ) ) { return null ; } else { return amount ; } } set { if ( ! value.HasValue ) { this.Text = `` '' ; } else { this.Text = string.Format ( `` $ { 0 : # , # # 0.00 } '' , value ) ; } } } decimal Amount = uxAmount.Value ? ? 0M ; decimal ? _Amount = uxAmount.Value ; decimal amount = _Amount ? ? 0 ; decimal ? _Amount = uxAmount.Value ; //10000decimal amount = _Amount ? ? 0 ; //10000decimal amount2 = _Amount ? ? 0M ; //10000decimal Amount = uxAmount.Value ? ? 0M ; //0 decimal amount3 = ( uxTaxAmount.Value ) ? ? 0M ; decimal Amount = uxAmount.Value ? ? 0M ; //10000decimal amount3 = ( uxAmount.Value ) ? ? 0M ; //0",Understanding the null coalescing operator ( ? ? ) C_sharp : I have new problem . My code : C # code : I 'm generating this code via System.Reflection and System.Reflection.Emit classes . Does anybody known why this can not works ? Please help.One small question - should I generate constructor ? .method public static void Main ( ) cil managed { .entrypoint // Code size 3 ( 0x3 ) .maxstack 1 IL_0000 : ldnull IL_0001 : stloc.0 IL_0002 : ret } // end of method Program : :Main il.Emit ( OpCodes.Ldnull ) ; il.Emit ( OpCodes.Stloc_0 ) ; il.Emit ( OpCodes.Ret ) ;,`` AccessViolationException was unhandled '' error in C # Managed Code "C_sharp : I need to extract values from a JSON string so I can compare them . I only need to verify that they are in order ( ascending/descending ) . I was going to check the first and second 'choices ' and compare . I do n't anything more advanced.EDIT/UPDATE : How could I use wildcards ( * ) in this type of query to skip having each segment ? string one = ( string ) o [ this.Context [ *WILDCARD* ] [ `` cid1 '' ] ] .ToString ( ) ; /* this works , but has too many [ ] string one = ( string ) o [ this.Context [ `` partner '' ] ] [ this.Context [ `` campaign '' ] ] [ this.Context [ `` segment1 '' ] ] [ this.Context [ `` segment2 '' ] ] [ this.Context [ `` qid2 '' ] ] [ `` community '' ] [ this.Context [ `` cid1 '' ] ] .ToString ( ) ; */ { `` partner '' : { `` campaign '' : { `` round1 '' : { `` round2 '' : { `` def123 '' : { `` community '' : { `` choicec '' : 28 } , `` user '' : { `` choice '' : `` choicec '' , `` writeDateUTC '' : `` 2015-06-15T17:21:59Z '' } } } , `` abc321 '' : { `` community '' : { `` choicec '' : 33 } , `` user '' : { `` choice '' : `` choicec '' , `` writeDateUTC '' : `` 2015-06-15T17:21:59Z '' } } } } } }","C # -- Get , then compare values from JSON string" "C_sharp : I have the following code in my application which creates an instance of an Akka.NET actor in my cluster as such : Note that I deliberately omit the name property as I intend to create N actors of type ActorA and do n't want to manage the names . Running the above I end up with an actor which has an ID that looks like this : The problem I run into is trying to determine the Actor path from a different node . So for example I have tried doing the following : Where via leveraging of the cluster MEMBER-UP event I try to send an Identify request to the new member but the problem I run into is the ClusterEvent.MemberUp object provided does not contain information regarding the actors within the node but only appears to contain a node reference that looks like this : akka.tcp : //mycluster @ localhost:666Which makes perfect sense because its the node that has come online , not an actor.If I change my code to use a named actor : I can then successfully query the service how I need . This is what you would expect when you have a named actor but there appears to be no way to actually externally determine instances of running actors on a node.So , when using N instances of unnamed actors what are the correct steps to identify references to the actors you are interested in , specifically when the actors have been generated without a name ? EDIT : I 've decided to restate the question because I did n't adequately describe it initially . The correct expression of this question is : `` Is there a way to get all instantiated actors currently available on a given node from a external actor when all you have is the node path ? `` To me it just seems like this should be something built into the base framework UNLESS there is some sort of design consideration that I do n't fully understand.I also note that I think it 's likely the correct approach to my particular problem might just be that I am trying to do a Pub/Sub and this https : //getakka.net/articles/clustering/distributed-publish-subscribe.html is more appropriate . _actorSystem = ActorSystem.Create ( `` mycluster '' ) ; _actoraActor = this._actorSystem.ActorOf < ActorA > ( ) ; akka : //mycluster/user/ $ a # 1293118665 public class ActorB : ReceiveActor { private readonly Cluster Cluster = Akka.Cluster.Cluster.Get ( Context.System ) ; public ActorB ( ) { this.Receive < ActorIdentity > ( this.IdentifyMessageReceived ) ; this.ReceiveAsync < ClusterEvent.MemberUp > ( this.MemberUpReceived ) ; } protected override void PreStart ( ) { this.Cluster.Subscribe ( this.Self , ClusterEvent.InitialStateAsEvents , new [ ] { typeof ( ClusterEvent.IMemberEvent ) , typeof ( ClusterEvent.UnreachableMember ) } ) ; } protected override void PostStop ( ) { this.Cluster.Unsubscribe ( this.Self ) ; } private async Task < bool > MemberUpReceived ( ClusterEvent.MemberUp obj ) { if ( obj.Member.HasRole ( `` actora '' ) ) { // ! The problem is here . //ALL YOU ARE PROVIDED IS THE NODE ADDRESS : //Obviously this makes sense because it 's the node that has come alive //and not the instances themselves . string address = obj.Member.Address.ToString ( ) ; //akka.tcp : //mycluster @ localhost:666 Context.ActorSelection ( address ) .Tell ( new Identify ( 1 ) ) ; } return true ; } private bool IdentifyMessageReceived ( ActorIdentity obj ) { return true ; } } _actorSystem = ActorSystem.Create ( `` mycluster '' ) ; _actoraActor = this._actorSystem.ActorOf < ActorA > ( `` actora '' ) ;",Is there a way to get all instantiated actors currently available on a given node in Akka.NET "C_sharp : Can I define a background worker in a method ? Question : If Download ( ) function takes a long time to download the file , can GC kick in and collect worker object before the RunWorkerCompleted ( ) is executed ? private void DownLoadFile ( string fileLocation ) { BackgroundWorker worker = new BackgroundWorker ( ) ; worker.DoWork += new DoWorkEventHandler ( ( obj , args ) = > { // Will be executed by back ground thread asynchronously . args.Result = Download ( fileLocation ) ; } ) ; worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler ( ( obj , args ) = > { // will be executed in the main thread . Result r = args.Result as Result ; ReportResult ( r ) ; } ) ; worker.RunWorkerAsync ( fileLocation ) ; }",Background worker and garbage collection ? "C_sharp : I have ASP.NET MVC 5.0 project using ASP.NET Identity . When user log in i use this function to track user by system.In user profile i have ability to change UserName , after that i need automatically to relogin user to stay user tracking . I logout user and use this function to login , but where i can get IsPersistent property of current session ? I can store IsPersistent in User table on database after each login , but I think this is not the best solution . SignInManager.SignIn ( user , IsPersistent , false )",How to get is session IsPersistent on ASP.NET MVC ? "C_sharp : I 'm building an expression tree dependency analyzer for a cross data source IQueryProvider.That is , I have an IQueryable with some elements that can be executed locally in memory against some arbitrary provider ( say Entity Framework ) . Some other elements in the IQueryable go against an entity that I need to make a remote WCF call . The WCF operation takes a serialized expression tree , will deserialize it , execute the LINQ query against its own local data store ( lets also say Entity Framework ) , then send me back the results ( though this mechanism could just as easily be a WCF Data Services DataServiceQuery ... but I 'm not using it because it 's level of functional support is limited ... at best ) . Once I get the results back from the WCF service , I will perform the result of the LINQ query in memory against the locally executed LINQ query.So , what 's so hard about that ? Well , I need to determine the dependencies of the expression tree , so that my local underlying Query Provider wo n't explode trying to execute my LINQ query which has components that can only be executed on the remote WCF service ... and vice versa.Let 's take the simple scenario : Query < T > is a simple queryable wrapper with my own provider which has the chance to parse the tree an figure out what to do before swapping out roots with a different query provider . So , in the above case I need to : Execute the query against MyEntityA using a local object context and apply only the myEntityX.SomeProperty == `` Hello '' criteria . That is , run the following locally : // assume the functionality for replacing new Query < MyEntityA > with new// ObjectContext < MyEntityA > ( ) is already there ... var resultX = ( from entityX in new Query < MyEntityX > ( ) where entityX.SomeProperty == `` Hello '' ) .ToList ( ) .AsQueryable ( ) ; Send over the following serialized and have it execute on my remote WCF service , then get the results back.// Send the preceeding expression over the over the wire// and get the results back ( just take my word this already works ) var resultY = ( from entityY in new Query < MyEntityY > ( ) where entityY.SomeOtherProperty == `` Hello 2 '' ) .ToList ( ) .AsQueryable ( ) ; Execute the following in memory : var finalResult = ( from entityX in resultX from entityY in resultY where entityX.SomeProperty == `` Hello '' & & entityY.SomeOtherProperty == `` Hello 2 '' & & entityX.Id == entityY.XId ) .ToList ( ) ; Note that the solution must incorporate a way of accumulating criteria that is specified off of projections too ... likeThis should result in the same two individual queries above being actually issued before the rest is evaluated in memory . On an unrelated note , I think I will probably used PLINQ and or DRYAD for running the in memory operations with improved performance.So , I have some ideas ( like doing some passes over the tree with a visitor and accumulating candidates for a given entity type ) , but I 'm looking for some other peoples ' suggestions about how to accumulate the parts my expression tree that can be executed against a given context ... that is , knowing that one where criteria applies to one underlying new Query < T > and another criteria applies to a different one ... so that I can figure out what I can do against data store 1 , what I can do against data store 2 and what I need to do in memory , and execute the different parts of the tree accordingly . It 's sort of like a Funcletizer , but a bit more complex ... Thanks for any assistance . var result = ( from entityX in new Query < MyEntityX > ( ) from entityY in new Query < MyEntityY > ( ) where entityX.SomeProperty == `` Hello '' & & entityY.SomeOtherProperty == `` Hello 2 '' & & entityX.Id == entityY.XId ) .ToList ( ) ; var result = ( from i in ( from entityX in new Query < MyEntityX > ( ) from entityY in new Query < MyEntityY > ( ) select new { PropX = entityX , PropY = entityY } ) where i.PropX.SomeProperty == `` Hello '' & & i.PropY.SomeOtherProperty == `` Hello 2 '' & & i.PropX.Id == i.PropY.XId select i ) .ToList ( ) ;",Expression Tree Dependency Analyzer "C_sharp : Basically , I want to be able to do something like this : So , some `` steps '' are named and some are not.The thing I do not like is that the StepClause has knowledge of its derived class NamedStepClause.I tried a couple of things to make this sit better with me.I tried to move things out to interfaces but then the problem just moved from the concrete to the interfaces - INamedStepClause still need to derive from IStepClause and IStepClause needs to return INamedStepClause to be able to call Step ( ) .I could also make Step ( ) part of a completely separate type . Then we do not have this problem and we 'd have : Which is ok but I 'd like to make the step-naming optional if possible.I found this other post on SO here which looks interesting and promising.What are your opinions ? I 'd think the original solution is completely unacceptable or is it ? By the way , those action methods will take predicates and functors and I do n't think I want to take an additional parameter for naming the step there.The point of it all is , for me , is to only define these action methods in one place and one place only . So the solutions from the referenced link using generics and extension methods seem to be the best approaches so far . public class StepClause { public NamedStepClause Action1 ( ) { } public NamedStepClause Action2 ( ) { } } public class NamedStepClause : StepClause { public StepClause Step ( string name ) { } } var workflow = new Workflow ( ) .Configure ( ) .Action1 ( ) .Step ( `` abc '' ) .Action2 ( ) .Action2 ( ) .Step ( `` def '' ) .Action1 ( ) ; var workflow = new Workflow ( ) .Configure ( ) .Step ( ) .Action1 ( ) .Step ( `` abc '' ) .Action2 ( ) .Step ( ) .Action2 ( ) .Step ( `` def '' ) .Action1 ( ) ;",Fluent interface design and code smell "C_sharp : We have two same letter ' ی ' and ' ي ' which the first came as main letter after windows seven.Back to old XP we had the second one as main.Now the inputs I get is determined as different if one client is on windows XP and the other on windows seven.I have also tried to use Persian culture with no success.Am I missing anything ? EDIT : Had to change the words for better understanding.. now they look similar . Outputs : foreach ( CompareOptions i in Enum.GetValues ( new CompareOptions ( ) .GetType ( ) ) .OfType < CompareOptions > ( ) ) Console.WriteLine ( string.Compare ( `` محسنين '' , `` محسنین '' , new CultureInfo ( `` fa-ir '' ) , i ) + `` \t : `` + i ) ; -1 : None-1 : IgnoreCase-1 : IgnoreNonSpace-1 : IgnoreSymbols-1 : IgnoreKanaType-1 : IgnoreWidth1 : OrdinalIgnoreCase-1 : StringSort130 : Ordinal",Why comparing two equal persian word does not return 0 ? C_sharp : I hope this has n't been asked before.I have a nullable boolean called boolIsAllowed and a if condition like so : My question is this good code or would I be better separating it into a nested if statement ? Will the second condition get checked if boolIsAllowed.HasValue is equal to false and then throw an exception ? I hope this question is n't too stupid.Thanks in advance . if ( boolIsAllowed.HasValue & & boolIsAllowed.Value ) { //do something },Nested if statements or not "C_sharp : I 've a WCF service that at the moment 11 clients ping in to every 3 minutes . They have all been running fine for a couple weeks . Last night , they all of a sudden stopped being able to ping in due to timing out . So I looked at my server web.config . Specifically : which should have no problems working.I changed both values to 500 , saved the file , and everything started working again . So it must have been some issue with how many connections where being made.My question is : is there a way to view on the server app how many concurrent calls there are currently ? Like some sort of monitoring system ? This would help me to find why 50 possible calls was not enough for 11 clients . Question 2 : Does editing a service 's web.config , then saving it , reset all the connections ? Or was it just that I made the concurrent calls larger ? < serviceThrottling maxConcurrentCalls = '' 50 '' maxConcurrentSessions= '' 200 '' / >",Is there a way to tell how many `` Concurrent Calls '' are being made to a WCF service ? "C_sharp : Why tooltip , displayed manually with ToolTip.Show , is not shown , when window , containing control , is inactive ? I went for ToolTip.Show because I must have tooltip onscreen for unlimited time , which is not possible with normal ToolTip . I also love the idea of having tooltip text as a part of control itself . But unfortunately , when showing tooltip this way for inactive window ( despite ShowAlways = true ) , it simply does n't work.The OnMouseHower event is rised , but _toolTip.Show does nothing.. unless window is activated , then everything works.BountyAdding bounty for a solution to display tooltip for an inactive form ( preferably with solution when tooltip text is a property of control , not IContainer ) . public class MyControl : Button { private _tip ; public string ToolTip { get { return _tip ; } set { _tip = value ; } } private ToolTip _toolTip = new ToolTip ( ) ; public MyControl ( ) { _toolTip.UseAnimation = false ; _toolTip.UseFading = false ; _toolTip.ShowAlways = true ; } protected override void OnMouseHover ( EventArgs e ) { _toolTip.Show ( _tip , this , 0 , Height ) ; base.OnMouseHover ( e ) ; } protected override void OnMouseLeave ( EventArgs e ) { _toolTip.Hide ( this ) ; base.OnMouseLeave ( e ) ; } }",ToolTip.Show for an inactive window does n't works "C_sharp : I 've begun making a 2D sprite based Windows game using XNA . I 'm not very experienced with it yet but I 'm learning . Let me start off with saying that I 'm using XNA game studio 3.1 , I have n't updated to 4.0 ( yet ) .What I 'm trying to accomplish is to be able to draw all my sprites to a fixed size buffer which is then , at the end of the rendering pass , scaled to the size of the actual backbuffer and then drawn to that . I 'm not sure how multiple resolutions are usually supported , but it seemed like an adequate solution to me.I tried to achieve this by using a RenderTarget2D object to draw all my stuff to , then get the Texture2D from that and draw that to the backbuffer.My code looks like this : The problem I encounter is that the colours are all wrong . Below is a picture that shows two screenshots : the first is a screenshot of how it 's supposed to look ( I wrote my own scaling algorithm before which simply scaled each sprite by itself ) and to the right it 's how it looks when using the RenderTarget2D.Does anyone know what I 'm doing wrong ? private RenderTarget2D RenderTarget ; private DepthStencilBuffer DepthStencilBufferRenderTarget ; private DepthStencilBuffer DepthStencilBufferOriginal ; private SpriteBatch SpriteBatch ; protected override void Initialize ( ) { base.Initialize ( ) ; RenderTarget = new RenderTarget2D ( GraphicsDevice , 1920 , 1080 , 1 , SurfaceFormat.Single ) ; DepthStencilBufferRenderTarget = new DepthStencilBuffer ( GraphicsDevice , 1920 , 1080 , GraphicsDevice.DepthStencilBuffer.Format ) ; DepthStencilBufferOriginal = GraphicsDevice.DepthStencilBuffer ; SpriteBatch = new SpriteBatch ( GraphicsDevice ) ; } protected override void Draw ( GameTime gameTime ) { GraphicsDevice.DepthStencilBuffer = DepthStencilBufferRenderTarget ; GraphicsDevice.SetRenderTarget ( 0 , RenderTarget ) ; GraphicsDevice.Clear ( Color.Black ) ; SpriteBatch.Begin ( ) ; //drawing all stuff here SpriteBatch.End ( ) ; GraphicsDevice.DepthStencilBuffer = DepthStencilBufferOriginal ; GraphicsDevice.SetRenderTarget ( 0 , null ) ; GraphicsDevice.Clear ( Color.Black ) ; Texture2D output = RenderTarget.GetTexture ( ) ; SpriteBatch.Begin ( ) ; Rectangle backbuffer = new Rectangle ( 0 , 0 , m_Options.DisplayWidth , m_Options.DisplayHeight ) ; SpriteBatch.Draw ( output , backbuffer , Color.White ) ; SpriteBatch.End ( ) ; base.Draw ( gameTime ) ; }",Colours are wrong when using RenderTarget2D in XNA "C_sharp : I have [ RequestSizeLimit ] on my API controller , and it kinda works as expected : requests bigger than specified limit are rejected.The problem is , an exception is thrown : So HTTP 500 is returned , but I would expect 413 or 400 . And I do n't expect an exception , since this is a perfectly normal situation.Could not find any documentation on this . What is the right way to return 413 for requests that are too big ? [ HttpPut ] [ RequestSizeLimit ( 120_000_000 ) ] public async Task < IActionResult > Put ( IFormCollection form ) { ... } Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException : Request body too large . at Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException.Throw ( RequestRejectionReason reason ) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1MessageBody.ForContentLength.OnReadStarting ( ) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.TryInit ( ) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.ReadAsync ( Memory ` 1 buffer , CancellationToken cancellationToken ) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal ( Memory ` 1 buffer , CancellationToken cancellationToken )",RequestSizeLimitAttribute : HTTP 500 instead of 413 in ASP.NET Core 2.1.401 "C_sharp : When using WPF databinding , I obviously ca n't do something along the lines of MyCollection = new CollectionType < Whatever > ( WhateverQuery ( ) ) ; since the bindings have a reference to the old collection . My workaround so far has been MyCollection.Clear ( ) ; followed by a foreach doing MyCollection.Add ( item ) ; - which is pretty bad for both performance and aesthetics.ICollectionView , although pretty neat , does n't solve the problem either since it 's SourceCollection property is read-only ; bummer , since that would have been a nice and easy solution.How are other people handling this problem ? It should be mentioned that I 'm doing MVVM and thus ca n't rummage through individual controls bindings . I suppose I could make a wrapper around ObservableCollection sporting a ReplaceSourceCollection ( ) method , but before going that route I 'd like to know if there 's some other best practice.EDIT : For WinForms , I would bind controls against a BindingSource , allowing me to simply update it 's DataSource property and call the ResetBindings ( ) method - presto , underlying collection efficiently changed . I would have expected WPF databinding to support a similar scenario out of the box ? Example ( pseudo-ish ) code : WPF control ( ListBox , DataGrid , whatever you fancy ) is bound to the Users property . I realize that collections should be read-only to avoid the problems demonstrated by ReloadUsersBad ( ) , but then the bad code for this example obviously would n't compile : ) public class UserEditorViewModel { public ObservableCollection < UserViewModel > Users { get ; set ; } public IEnumerable < UserViewModel > LoadUsersFromWhateverSource ( ) { /* ... */ } public void ReloadUsersBad ( ) { // bad : the collection is updated , but the WPF control is bound to the old reference . Users = new ObservableCollection < User > ( LoadUsersFromWhateverSource ( ) ) ; } public void ReloadUsersWorksButIsInefficient ( ) { // works : collection object is kept , and items are replaced ; inefficient , though . Users.Clear ( ) ; foreach ( var user in LoadUsersFromWhateverSource ( ) ) Users.Add ( user ) ; } // ... whatever other stuff . }",WPF : Replacing databound collection contents without Clear/Add "C_sharp : I 've been working on a Website for users to upload videos to a shared YouTube account for later access . After much work I 've been able to get an Active Token , and viable Refresh Token.However , the code to initialize the YouTubeService object looks like this : I 've already got a token , and I want to use mine . I 'm using ASP.NET version 3.5 , and so I ca n't do an async call anyways.Is there any way I can create a YouTubeService object without the async call , and using my own token ? Is there a way I can build a credential object without the Authorization Broker ? Alternatively , the application used YouTube API V2 for quite some time , and had a form that took a token , and did a post action against a YouTube URI that was generated alongside the token in API V2 . Is there a way I can implement that with V3 ? Is there a way to use Javascript to upload videos , and possibly an example that I could use in my code ? UserCredential credential ; using ( var stream = new FileStream ( `` client_secrets.json '' , FileMode.Open , FileAccess.Read ) ) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync ( GoogleClientSecrets.Load ( stream ) .Secrets , // This OAuth 2.0 access scope allows an application to upload files to the // authenticated user 's YouTube channel , but does n't allow other types of access . new [ ] { YouTubeService.Scope.YoutubeUpload } , `` user '' , CancellationToken.None ) ; } var youtubeService = new YouTubeService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = Assembly.GetExecutingAssembly ( ) .GetName ( ) .Name , } ) ;",Creating a YouTube Service via ASP.NET using a pre-existing Access Token "C_sharp : When learning more about the standard event model in .NET , I found that before introducing generics in C # , the method that will handle an event is represented by this delegate type : But after generics were introduced in C # 2 , I think this delegate type was rewritten using genericity : I have two questions here : First , why was n't the TEventArgs type parameter made contravariant ? If I 'm not mistaken it is recommended to make the type parameters that appear as formal parameters in a delegate 's signature contravariant and the type parameter that will be the return type in the delegate signature covariant.In Joseph Albahari 's book , C # in a Nutshell , I quote : If you ’ re defining a generic delegate type , it ’ s good practice to : Mark a type parameter used only on the return value as covariant ( out ) . Mark any type parameters used only on parameters as contravariant ( in ) . Doing so allows conversions to work naturally by respecting inheritance relationships between types.Second question : Why was there no generic constraint to enforce that the TEventArgs derive from System.EventArgs ? As follows : Thanks in advance . Edited to clarify the second question : It seems like the generic constraint on TEventArgs ( where TEventArgs : EventArgs ) was there before and it was removed by Microsoft , so seemingly the design team realized that it didn ’ t make much practical sense.I edited my answer to include some of the screenshots from .NET reference source //// Summary : // Represents the method that will handle an event that has no event data.//// Parameters : // sender : // The source of the event.//// e : // An object that contains no event data.public delegate void EventHandler ( object sender , EventArgs e ) ; //// Summary : // Represents the method that will handle an event when the event provides data.//// Parameters : // sender : // The source of the event.//// e : // An object that contains the event data.//// Type parameters : // TEventArgs : // The type of the event data generated by the event.public delegate void EventHandler < TEventArgs > ( object sender , TEventArgs e ) ; public delegate void EventHandler < TEventArgs > ( object source , TEventArgs e ) where TEventArgs : EventArgs ;",Why was n't TEventArgs made contravariant in the standard event pattern in the .NET ecosystem ? "C_sharp : When I get deserialized XML result into xsd-generated tree of objects and want to use some deep object inside that tree a.b.c.d.e.f , it will give me exception if any node on that query path is missing.I want to avoid checking for null for each level like this : First solution is to implement Get extension method that allows this : Second solution is to implement Get ( string ) extension method and use reflection to get result looking like this : Third solution , could be to implement ExpandoObject and use dynamic type to get result looking like this : But last 2 solutions do not give benefits of strong typing and IntelliSense.I think the best could be fourth solution that can be implemented with Expression Trees : orI already implemented 1st and 2nd solutions.Here is how 1st solution looks like : How to implement 4th solution if possible ? Also it would be interesting to see how to implement 3rd solution if possible . if ( a.b.c.d.e.f ! = null ) Console.Write ( `` ok '' ) ; if ( a ! = null ) if ( a.b ! = null ) if ( a.b.c ! = null ) if ( a.b.c.d ! = null ) if ( a.b.c.d.e ! = null ) if ( a.b.c.d.e.f ! = null ) Console.Write ( `` ok '' ) ; if ( a.Get ( o= > o.b ) .Get ( o= > o.c ) .Get ( o= > o.d ) .Get ( o= > o.e ) .Get ( o= > o.f ) ! = null ) Console.Write ( `` ok '' ) ; if ( a.Get ( `` b.c.d.e.f '' ) ! = null ) Console.Write ( `` ok '' ) ; dynamic da = new SafeExpando ( a ) ; if ( da.b.c.d.e.f ! = null ) Console.Write ( `` ok '' ) ; if ( Get ( a.b.c.d.e.f ) ! = null ) Console.Write ( `` ok '' ) ; if ( a.Get ( a= > a.b.c.d.e.f ) ! = null ) Console.Write ( `` ok '' ) ; [ DebuggerStepThrough ] public static To Get < From , To > ( this From @ this , Func < From , To > get ) { var ret = default ( To ) ; if ( @ this ! = null & & ! @ this.Equals ( default ( From ) ) ) ret = get ( @ this ) ; if ( ret == null & & typeof ( To ) .IsArray ) ret = ( To ) Activator.CreateInstance ( typeof ( To ) , 0 ) ; return ret ; }",How to use Expression Tree to safely access path of nullable objects ? "C_sharp : Since Java 5 , the volatile keyword has release/acquire semantics to make side-effects visible to other threads ( including assignments to non-volatile variables ! ) . Take these two variables , for example : Note that i is a regular , non-volatile variable . Imagine thread 1 executing the following statements : At some later point in time , thread 2 executes the following statements : According to the Java memory model , the write of v in thread 1 followed by the read of v in thread 2 ensures that thread 2 sees the write to i executed in thread 1 , so the value 42 is printed.My question is : does volatile have the same release/acquire semantics in C # ? int i ; volatile int v ; i = 42 ; v = 0 ; int some_local_variable = v ; print ( i ) ;",volatile with release/acquire semantics "C_sharp : The C # compiler allows operations between different enum types in another enum type declaration , like this : but forbids them inside method code , i.e . the operation : Is flagged with this error : Operator '| ' can not be applied to operands of type 'VerticalAnchors ' and 'HorizontalAnchors'.There 's a workaround , of course : I am curious about this compiler behaviour . Why are operations between different enum types allowed in another enum declaration but not elsewhere ? public enum VerticalAnchors { Top=1 , Mid=2 , Bot=4 } public enum HorizontalAnchors { Lef=8 , Mid=16 , Rig=32 } public enum VisualAnchors { TopLef = VerticalAnchors.Top | HorizontalAnchors.Lef , TopMid = VerticalAnchors.Top | HorizontalAnchors.Mid , TopRig = VerticalAnchors.Top | HorizontalAnchors.Rig , MidLef = VerticalAnchors.Mid | HorizontalAnchors.Lef , MidMid = VerticalAnchors.Mid | HorizontalAnchors.Mid , MidRig = VerticalAnchors.Mid | HorizontalAnchors.Rig , BotLef = VerticalAnchors.Bot | HorizontalAnchors.Lef , BotMid = VerticalAnchors.Bot | HorizontalAnchors.Mid , BotRig = VerticalAnchors.Bot | HorizontalAnchors.Rig } VerticalAnchors.Top | HorizontalAnchors.Lef ; ( int ) VerticalAnchors.Top | ( int ) HorizontalAnchors.Lef",Why are operations between different enum types allowed in another enum declaration but not elsewhere ? "C_sharp : I have developed many .NET / SQL Server applications but I 'm suffering from SQL query timeouts that I ca n't get to the bottom of . I have lots of experience in this area of finding the offending queries and re-indexing / re-writing them . My web app is hosted on AWS using RDS for SQL Server and EC2 for the Web App . We have 100-200 unique users per day and the database is around 15GB with a couple of tables > 1GB.I see exceptions throughout the day with the message : The queries that suffer from timeouts are as random as the time the timeouts occur . It does n't seem to coincide with anything obvious ( backups run overnight etc ) .I have tried taking each query from the C # app and running it directly in SQL ( with the same SET options like Arith Abort ) and they all run just fine . Some are slower queries by nature but the slowest one runs in about 2 seconds and has ~400k logical reads . However , I also see queries timeout that run in 15ms and have < 10 logical reads.The most odd thing I 've seen is I 've taken a query from the web app and coded it up into a console app which has been running for 24 hours , calling the query once per second . It has not had a single exception / timeout even though I 've seen the main system have timeouts for the same query during the time it 's been running.I have recently upgraded the RDS server to an M5 Large and all indexes are rebuilt overnight every day . I have run DBCC FREEPROCCACHE at some point to ensure there are no stale query plans causing the problem.I feel it 's parameter sniffing or my last thought is hardware / network glitches but that really clutching at straws ! The stack trace I get looks like it 's mid-query and not during the connection phase.Any help with some techniques to get to the bottom of this would be much appreciated as it 's unsettling and I fear it 's suddenly going to get a lot worse.ThanksEDIT 1I have tried to create the same problem locally by running the test app ( as above ) once every 10ms and running a slow blocking transaction in SSMS at the same time.Query From AppQuery in SSMSWhen this errors I see what I 'd usually expect to see in SQL Profiler where the app query takes exactly 30000ms and I get an exception in the app . However , the useful output from this is the stack trace is different from the one I see in production ( above ) .I 'm reading this stack trace as the query never started to execute since it 's still trying to read meta-data for the query . However , this contrasts with the stack trace from production that ( to my eyes ) appears to be in the middle of reading data from columns but has a timeout mid execution.I 've also been reading about .NET 4.6.2 which is the version we 're using . I 'll upgrade everything to 4.7.2 this evening to rule that out . ( Connection to remote SQL server breaks when upgrading web server to .net framework 4.6.1 ) 'Execution Timeout Expired . The timeout period elapsed prior to completion of the operation or the server is not responding . ' at System.Data.SqlClient.SqlInternalConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning ( TdsParserStateObject stateObj , Boolean callerHasConnectionLock , Boolean asyncClose ) at System.Data.SqlClient.TdsParserStateObject.ReadSniError ( TdsParserStateObject stateObj , UInt32 error ) at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync ( ) at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket ( ) at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer ( ) at System.Data.SqlClient.TdsParserStateObject.TryReadByteArray ( Byte [ ] buff , Int32 offset , Int32 len , Int32 & totalRead ) at System.Data.SqlClient.TdsParserStateObject.TryReadString ( Int32 length , String & value ) at System.Data.SqlClient.TdsParser.TryReadSqlStringValue ( SqlBuffer value , Byte type , Int32 length , Encoding encoding , Boolean isPlp , TdsParserStateObject stateObj ) at System.Data.SqlClient.TdsParser.TryReadSqlValue ( SqlBuffer value , SqlMetaDataPriv md , Int32 length , TdsParserStateObject stateObj , SqlCommandColumnEncryptionSetting columnEncryptionOverride , String columnName ) at System.Data.SqlClient.SqlDataReader.TryReadColumnInternal ( Int32 i , Boolean readHeaderOnly ) at System.Data.SqlClient.SqlDataReader.TryReadColumn ( Int32 i , Boolean setTimeout , Boolean allowPartiallyReadColumn ) at System.Data.SqlClient.SqlDataReader.GetValueInternal ( Int32 i ) at System.Data.SqlClient.SqlDataReader.GetValue ( Int32 i ) SELECT TOP 10 *FROM MyTableWHERE LastModifiedBy = 'Stu ' BEGIN TRANUPDATE TOP ( 10000 ) MyTable SET LastModifiedBy = 'Me ' where LastModifiedBy = 'Me'WAITFOR DELAY '00:00:35'COMMIT at System.Data.SqlClient.SqlConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at System.Data.SqlClient.SqlInternalConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning ( TdsParserStateObject stateObj , Boolean callerHasConnectionLock , Boolean asyncClose ) at System.Data.SqlClient.TdsParser.TryRun ( RunBehavior runBehavior , SqlCommand cmdHandler , SqlDataReader dataStream , BulkCopySimpleResultSet bulkCopyHandler , TdsParserStateObject stateObj , Boolean & dataReady ) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData ( ) at System.Data.SqlClient.SqlDataReader.get_MetaData ( ) at System.Data.SqlClient.SqlCommand.FinishExecuteReader ( SqlDataReader ds , RunBehavior runBehavior , String resetOptionsString , Boolean isInternal , Boolean forDescribeParameterEncryption , Boolean shouldCacheForAlwaysEncrypted ) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds ( CommandBehavior cmdBehavior , RunBehavior runBehavior , Boolean returnStream , Boolean async , Int32 timeout , Task & task , Boolean asyncWrite , Boolean inRetry , SqlDataReader ds , Boolean describeParameterEncryptionRequest ) at System.Data.SqlClient.SqlCommand.RunExecuteReader ( CommandBehavior cmdBehavior , RunBehavior runBehavior , Boolean returnStream , String method , TaskCompletionSource ` 1 completion , Int32 timeout , Task & task , Boolean & usedCache , Boolean asyncWrite , Boolean inRetry ) at System.Data.SqlClient.SqlCommand.RunExecuteReader ( CommandBehavior cmdBehavior , RunBehavior runBehavior , Boolean returnStream , String method ) at System.Data.SqlClient.SqlCommand.ExecuteReader ( CommandBehavior behavior , String method ) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader ( CommandBehavior behavior ) at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader ( CommandBehavior behavior )",Need help diagnosing SQL Server strange query timeouts from C # "C_sharp : From the code on one page I want to be able to generate an instance of another page and parse the html from certain controls on that page.this is what i have tried so farThe problem is APIListPage.pdfPage is always null . var APIListPage = ( APIList ) BuildManager.CreateInstanceFromVirtualPath ( `` ~/APIHelp/APIList.aspx '' , typeof ( APIList ) ) ; ParseHtml ( APIListPage.pdfPage ) ;",Create instance of an ASPX page programmatically and parse html "C_sharp : We are developing a project in ASP.NET/C # which is a not a very large project but a sizeable one . Currently we have developed few pages . I am talking from point of view of a single page right now.The approach is followed for every pages that has been developed so far.In the code behind of my page we use Linq To SQL queries directly . The insert operation is done , queries to fill dropdownlists and other database related operations are used in code behind itself.We use functions though.The same goes for other pages as well.My question is should I include them in class files and then create objects and call appropriate methods to do my stuff ? If yes , should we create a single class or create one class per page . Is this called creating Data Access Layer.Can anyone help me suggest a proper way to do this ? Is this approach a good programming practice.This is a simple function that we are using in our code behindCan anyone point a simple example referring to this query ? I hope my question makes sense.Any suggestions are welcome . public void AccountTypeFill ( ) { //Get the types of Account ie Entity and individual var acc = from type in dt.mem_types select type.CustCategory ; if ( acc ! = null ) { NewCustomerddlAccountType.DataSource = acc.Distinct ( ) .ToList ( ) ; NewCustomerddlAccountType.DataBind ( ) ; } }",Should I use Linq To SQL directly in code behind or use some other approach ? "C_sharp : I had an interesting interview question today . Consider you have the following console application : When the Console.ReadLine ( ) line is reached execution is suspended and the program waits for input from the keyboard . How many threads are there at this point and what state are they in , e.g . Running , Suspended , etc . ? I suppose what the interviewer was after was awareness/understanding of the threads that make up a .NET console app and how they work together to interact with the IO subsystem of the underlying OS . static void Main ( string [ ] args ) { Console.WriteLine ( `` Hello world '' ) ; Console.ReadLine ( ) ; }",What happens when a .NET console app blocks on Console.ReadLine ( ) ? "C_sharp : I have a UWP project want to reads StorageFolder VideosLibrary and show a list of mp4 files at Views with thumbnail.With MVVM ligth toolkit I have setup this 4 flies with xaml.The Xaml is using UWP community toolkit wrap panel.1 ) ViewModelLocator.cs2 ) VideoListItem.cs3 ) VideoListModel.cs4 ) Video.xamlI wanted to do something like below in my VideoListModel for constructor.how can I accomplish this initialization in an asynchronous way ? To get the thumbnail I have created the method of GetVideoItem ( ) , But I ca n't find a way to call the GetVideoItem asynchronously in a constructor.Does anyone know how to solve this task ? namespace UWP.ViewModels { /// < summary > /// This class contains static reference to all the view models in the /// application and provides an entry point for the bindings./// < /summary > class ViewModelLocator { /// < summary > /// Initializes a new instance of the ViewModelLocator class . /// < /summary > public ViewModelLocator ( ) { ServiceLocator.SetLocatorProvider ( ( ) = > SimpleIoc.Default ) ; if ( ViewModelBase.IsInDesignModeStatic ) { // Create design time view services and models } else { // Create run Time view services and models } //Register services used here SimpleIoc.Default.Register < VideoListModel > ( ) ; } public VideoListModel VideoListModel { get { return ServiceLocator.Current.GetInstance < VideoListModel > ( ) ; } } } namespace UWP.Models { class VideoListItem : ViewModelBase { public string VideoName { get ; set ; } public string Author { get ; set ; } public Uri Vid_url { get ; set ; } public BitmapImage Image { get ; set ; } public VideoListItem ( string videoname , string author , Uri url , BitmapImage img ) { this.VideoName = videoname ; this.Author = author ; this.Vid_url = url ; this.Image = img ; } } } namespace UWP.ViewModels { class VideoListModel : ViewModelBase { public ObservableCollection < VideoListItem > VideoItems { get ; set ; } private VideoListItem videoItems ; public VideoListModel ( ) { } public async static Task < List < VideoListItem > > GetVideoItem ( ) { List < VideoListItem > videoItems = new List < VideoListItem > ( ) ; StorageFolder videos_folder = await KnownFolders.VideosLibrary.CreateFolderAsync ( `` Videos '' ) ; var queryOptions = new QueryOptions ( CommonFileQuery.DefaultQuery , new [ ] { `` .mp4 '' } ) ; var videos = await videos_folder.CreateFileQueryWithOptions ( queryOptions ) .GetFilesAsync ( ) ; foreach ( var video in videos ) { //Debug.WriteLine ( video.Name ) ; //videoItems.Add ( new VideoListItem ( ) ) ; var bitmap = new BitmapImage ( ) ; var thumbnail = await video.GetThumbnailAsync ( ThumbnailMode.SingleItem ) ; await bitmap.SetSourceAsync ( thumbnail ) ; videoItems.Add ( new VideoListItem ( video.DisplayName , `` '' , new Uri ( video.Path ) , bitmap ) ) ; } //foreach ( var video in videoItems ) // { // Debug.WriteLine ( `` Name : { 0 } , Author : { 1 } , Uri : { 2 } , Bitmap : { 3 } '' , video.VideoName , video.Author , video.Vid_url , video.Image.UriSource ) ; // } return videoItems ; } } } < Page xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' using : UWP.Views '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : Controls= '' using : Microsoft.Toolkit.Uwp.UI.Controls '' x : Class= '' UWP.Views.Video '' mc : Ignorable= '' d '' NavigationCacheMode= '' Enabled '' DataContext= '' { Binding Source= { StaticResource ViewModelLocator } , Path=VideoListModel } '' > < ! -- NavigationCacheMode Enable for the page state save -- > < Page.Resources > < DataTemplate x : Key= '' VideoTemplate '' > < Grid Width= '' { Binding Width } '' Height= '' { Binding Height } '' Margin= '' 2 '' > < Image HorizontalAlignment= '' Center '' Stretch= '' UniformToFill '' Source= '' { Binding Image } '' / > < TextBlock Text= '' { Binding VideoName } '' / > < StackPanel Orientation= '' Horizontal '' > < TextBlock Text= '' Author '' / > < TextBlock Text= '' { Binding Author } '' / > < /StackPanel > < /Grid > < /DataTemplate > < /Page.Resources > < Grid Background= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' > < ListView Name= '' VideosListWrapPanal '' ItemTemplate= '' { StaticResource VideoTemplate } '' > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < Controls : WrapPanel / > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel > < /ListView > < /Grid > < /Page > public async MainViewModel ( ) { VideoItems = new ObservableCollection < MainMenuItem > ( await GetVideoItem ( ) ) ; }",How to make my constructor async in UWP MVVM model ? ( MVVM Lighttoolkit ) C_sharp : Is there any way to have a yield created iterator continue to the next item when an exception occurs inside one of the iterator blocks ? This is currently not working : Boolean result ; while ( true ) { try { result = enumerator.MoveNext ( ) ; //Taken from a yield created enumerable if ( ! result ) break ; } catch ( Exception ex ) { Console.WriteLine ( `` CATCHED ... '' ) ; continue ; } },Is there any way to make a yield created Iterator Continue to the next item upon an Exception ? "C_sharp : So , I really enjoy using extension methods.. maybe a bit too much . So , I 'm going to ask about my latest enjoyment to ensure that I 'm not going too far . Scenario is that we have a Guid ? variable that gets passed in . If the variable is null or Guid.Empty , then we want to use a different Guid . So , I wrote an extension method to make it read like English : This automatically implies that a `` null this '' will not throw an exception . For instance , this will work : This is not possible without using extension methods , and in my opinion can be quite misleading . However , it 's just so concise and clean ! So , what do you think ? Is this an acceptable thing to do or could it be too confusing to other programmers ? Also , I 'm sure there will be other scenarios where I do things like this and checking this for null , but this is the best example I have right now . Note : I 'm not really asking about this Guid ? business in particular . I 'm asking more about the overall pattern implemented ( having an extension method where the this can be null ) internal static Guid OrIfEmpty ( this Guid ? guid , Guid other ) { if ( ! guid.HasValue || guid.Value == Guid.Empty ) { return other ; } return guid.Value ; } ( ( Guid ? ) null ) .OrIfEmpty ( other ) ;",Is `` null this '' an acceptable use of extension methods ? "C_sharp : Can we restrict Type property of a class to be a specific type ? Eg : assume that sampleControl is UI class ( may be Control , Form , .. ) its Value of EntityType Property should only accept the value of typeof ( Entity ) , but not the the typeof ( NonEntity ) how can we restrict the user to give the specific type at Deign time ( bcause - Sample is a control or form we can set its property at design time ) , is this posible in C # .netHow can we achive this using C # 3.0 ? In my above class I need the Type property that to this must be one of the IEntity . public interface IEntity { } public class Entity : IEntity { } public class NonEntity { } class SampleControl { public Type EntityType { get ; set ; } }",Type Restriction "C_sharp : I have a legacy VB.Net class library that includes some extension methods , one of which is roughly this : To use these extensions in VB I just have to import Extensions.OrmExtensions . I have another project , which is in C # that depends on the VB one with the extensions and I ca n't get them to work . OrmExtensions is n't available and simply using the namespace VBProject.Extensions does n't make the extensions available.There are multiple projects that depend on the VB project and ideally the extensions should be available to all of them.I 've done a fair bit of googling but have n't been able to turn up anything about actually using VB extension methods in C # . I assume the issue is that they 're required to be in a Module , but I have n't been able to confirm that.I 'd rather not duplicate the extension methods everywhere they 're required ( especially in our unit test project , which is in C # ) . Namespace Extensions Public Module OrmExtensions < Extension ( ) > Public Function ToDomainObjectCollection ( ByRef objects As OrmCollection ( Of OrmObject ) ) As DomainObjectCollection Return objects.AsQueryable ( ) .ToDomainObjectCollection ( ) End Function < Extension ( ) > Public Function ToDomainObjectCollection ( ByRef objects As IQueryable ( Of OrmObject ) ) As DomainObjectCollection Dim doc As New DomainObjectCollection ( ) For Each o In objects doc.Add ( o.ToDomainObject ( ) ) Next Return doc End Function End ModuleEnd Namespace",How can I use VB.Net extension methods in a C # project "C_sharp : I have a generic dictionary that pass to a method which only accepts IQueryable as a parameterIs it possible to cast the queryable back to the original dictionary ? And I do n't mean creating a new dictionary with .ToDictionary ( ... ) I know in this simple example this does not make much sense . But in the big picture I have an interface which requires me to return an IQueryable as a dataSource . On implementation returns a dictionary . On a different place in my code I have classes that process the dataSources . The processor knows that the dataSource will be an Dictionary but I do n't want to have the overhead for creating another Dictionary if I already have one . private static void Main ( ) { var dict = new Dictionary < int , int > ( ) ; dict.Add ( 1,1 ) ; SomeMethod ( dict.AsQueryable ( ) ) ; } public static void SomeMethod ( IQueryable dataSource ) { // dataSource as Dictionary < int , int > -- > null var dict = dataSource. ? ? ? }",Get original dictionary from dict.AsQueryable ( ) "C_sharp : I have many methods that require some logging with the same pattern . Some methods need to return some value , some do n't . I have created a method with Action parameter to avoid copypasting all of the logic . It looks like this : Now I have some calls that like thatBut I need some function that return values . What are the best ways to do it ? I have found two now:1 ) Create a copy of Execute method with FuncThis method works but has some copy paste as well.2 ) Trick the parameter into being an Action : This does not require copy paste but does not look so nice.Is there a way to join Action and Func somehow to avoid any of these methods or may be there is another way to achieve the same result ? private void Execute ( Action action ) { Logger.Start ( ) ; try { action ( ) ; } catch ( Exception exception ) { Logger.WriteException ( ) ; throw ; } finally { Logger.Finish ( ) ; } } public void DoSomething ( string parameter ) { Execute ( ( ) = > GetProvider ( parameter ) .DoSomething ( ) ) ; } private T Execute < T > ( Func < T > action ) { Logger.Start ( ) ; try { return action ( ) ; } catch ( Exception exception ) { Logger.WriteException ( ) ; throw ; } finally { Logger.Finish ( ) ; } } public Result DoSomething ( string parameter ) { Result result = null ; Execute ( ( ) = > result = GetProvider ( parameter ) .DoSomething ( ) ) ; return result ; }",Combining Action and Func in one parameter "C_sharp : I created a BlinkingLabelclass , derives from Forms.Label , which has a Forms.Timer which allows me to enable and disable the blinking effect.I have created 4 labels of BlinkingLabel type , my problem is that if all 4 labels where to blink in different times , the blinking effect is not synced.How can I adjust my design in a way that even if the labels where blinking in different times , the blinking will be synced ? ******* Edited******I added the following code , but still I ca n't get label 1 and 2 to blink same time . What am trying to do to is to test the following : make label1 blink then I click button to make label 2 to blink and they are not synced . Any idea what am doing wrong ? public partial class UserControl1 : UserControl { Timer blinkTimer ; Color blinkingColor = Color.Red ; int interval = 300 ; bool flag1 = false ; bool flag2 = false ; public UserControl1 ( ) { InitializeComponent ( ) ; // Blinking abel default values this.blinkTimer = new Timer ( ) ; this.blinkTimer.Interval = interval ; ; this.blinkTimer.Tick += new System.EventHandler ( timer_Tick ) ; flag1 = true ; this.blinkTimer.Start ( ) ; } private void blinkLabels ( Label label ) { if ( label.ForeColor == Color.White ) label.ForeColor = blinkingColor ; else label.ForeColor = Color.White ; } void timer_Tick ( object sender , System.EventArgs e ) { if ( flag1 == true ) blinkLabels ( label1 ) ; if ( flag2 == true ) blinkLabels ( label2 ) ; } private void button1_Click ( object sender , EventArgs e ) { flag2 = true ; this.blinkTimer.Start ( ) ; }",Sync Blinking Labels in C # "C_sharp : I just stumbled upon an undocumented behavior of the GetFiles methods in System.IO.Directory.Whenever the searchPattern parameter passed to the method contains a reserved Windows device name , such as `` nul . * '' or `` aux.bmp '' , the method returns an array containing the name of a nonexisting file , like C : \Users\ft1\nul or D : \aux , etc.I wonder if those device names have a special meaning it that context , like `` . '' or `` .. '' , or if this is just a sort of bug . Anyway , that still seems pretty weird.For example , this code snippet in C # : printsAny clues ? string [ ] fileNames = Directory.GetFiles ( @ '' C : \D : \..\..\ ... \ '' , `` con.txt '' ) ; foreach ( string fileName in fileNames ) Console.WriteLine ( fileName ) ; C : \D : \..\..\ ... \con",Directory.GetFiles finds nonexisting files "C_sharp : In the MVC view I use the values like this : Here , the title1 works fine . But the title2 ActionLink failed with a compiler error : CS1973 : 'System.Web.Mvc.HtmlHelper ' has no applicable method named 'StandardHeader ' but appears to have an extension method by that name . Extension methods can not be dynamically dispatched . Consider casting the dynamic arguments or calling the extension method without the extension method syntax.string.Format ( ) has quite a few overloads , but the return type is always string . Why does the variable declaration using var fail here ? @ { ViewBag.Username = `` Charlie Brown '' ; string title1 = string.Format ( `` Welcome { 0 } '' , ViewBag.Username ) ; var title2 = string.Format ( `` Welcome { 0 } '' , ViewBag.Username ) ; } @ Html.ActionLink ( title1 , `` Index '' ) @ Html.ActionLink ( title2 , `` Index '' )","Why does n't this string.Format ( ) return string , but dynamic ?" C_sharp : I have the code like thisThe code never gets executed and staticField has default value 0 . Also the code causes MVVMlight 's SimpleIoc to throw an exception with code like this : Above code causes MVVMLight to throw an exception sayingThis very bizarre . I 'm using Win8 RTM x64 + VS2012 Express for Windows 8 . public class SomeClass { private static int staticField = 10 ; } SimpleIoc.Default.Register < SomeClass > ( ) ; Can not build instance : Multiple constructors found but none marked with PreferredConstructor .,"In WinRT , static field not initialized at all" "C_sharp : I have a fun issue where during application shutdown , try / catch blocks are being seemingly ignored in the stack.I do n't have a working test project ( yet due to deadline , otherwise I 'd totally try to repro this ) , but consider the following code snippet.During runtime this pattern works famously . We get legacy support for code that relies on exceptions for program control ( bad ) and we get to move forward and slowly remove exceptions used for program control.However , when shutting down our UI , we see an exception thrown from `` Run '' even though `` doThrow '' is false for ALL current uses of `` RunAndPossiblyThrow '' . I 've even gone so far as to verify this by modifying code to look like `` RunAndIgnoreThrow '' and I 'll still get a crash post UI shutdown.Mr . Eric Lippert , I read your blog daily , I 'd sure love to hear it 's some known bug and I 'm not going crazy.EDITThis is multi-threaded , and I 've verified all objects are not modified while being accessedEDITExplicitly show exception is oursEDITforgot to mention , this is on closing , and unfortunately visual studio can not catch the crash directly . It 's likely crashing on a thread other than the UI thread , and once the main closes , this closes . I 've only been able to debug this by repeatedly running & closing the application , with task manager open , `` Create Dump File '' and looking at the resulting 400+mb mess in Windbg . Win7 64 for reference . Make sure this makes sense to you.EDITThe following code on shutdown still shows the same exception.The only thing that seems to get rid of the exception is to go straight to Naturally the exception 's gone , but my fears of going crazy are still present.EDITit just got worse ... this still crashes ... EDITI have a distinct feeling this is going to get me nowhere . On top of the wierd behavior , I can also note that during execution of the UI in the above case , the try catch is being executed faithfully . My UI does n't crash & it 's full of empty strings . However once I start closing the UI , the crash shows itself and the try catch no longer holds back the exception.EDIT & finalApparently the dump file was listing in it the most recent first-chance exception . I verified this by creating a new project that threw inside a try catch & slept for 10 seconds . During the wait I got the .dmp file & sure enough , my completely caught exception was showing up.I 'll mark some points for the useful answers , however unfortunately there 's still no rhyme or reason why my code is crashing ... class IndexNotFoundException : Exception { } public static string RunAndPossiblyThrow ( int index , bool doThrow ) { try { return Run ( index ) ; } catch ( IndexNotFoundException e ) { if ( doThrow ) throw ; } return `` '' ; } public static string Run ( int index ) { if ( _store.Contains ( index ) ) return _store [ index ] ; throw new IndexNotFoundException ( ) ; } public static string RunAndIgnoreThrow ( int index ) { try { return Run ( index ) ; } catch ( IndexNotFoundException e ) { } return `` '' ; } class IndexNotFoundException : Exception { } public static string RunAndPossiblyThrow ( int index , bool doThrow ) { try { return Run ( index ) ; } catch { } return `` '' ; } public static string Run ( int index ) { if ( _store.Contains ( index ) ) return _store [ index ] ; throw new IndexNotFoundException ( ) ; } class IndexNotFoundException : Exception { } public static string RunAndPossiblyThrow ( int index , bool doThrow ) { try { return Run ( index ) ; } catch { } return `` '' ; } public static string Run ( int index ) { if ( _store.Contains ( index ) ) return _store [ index ] ; return `` '' ; } class IndexNotFoundException : Exception { } public static string RunAndPossiblyThrow ( int index , bool doThrow ) { try { throw new IndexNotFoundException ( ) ; } catch { } return `` '' ; }",When is a try catch not a try catch ? "C_sharp : Right now I 'm doing : This works for distinguishing USA from Europe and Asia , but it ignores South America.Is there a better way ? bool UseMetricByDefault ( ) { return TimeZone.CurrentTimeZone.GetUtcOffset ( DateTime.Now ) .TotalHours > = 0 ; }",Is there a way to tell if the user would prefer metric or imperial without asking in C # ? "C_sharp : There 's a lot of exposition here - but it 's needed.Not sure how many people are aware of this , but , the Razor code editor in Visual Studio causes your website to be 'test-fired ' up to just before the Application_Start event - and this is causing some annoying issues in my current project , which uses WebActivator to do a lot of the site initialisation.Update - On closer inspection it 's not just Razor - it looks like it 's Visual Studio-wide - hence the change of titleI need to be able to detect when website code is being run by Visual Studio and not by a web server.To demonstrate - do the following ( exactly as written to ensure it reproduces ) : Create a new MVC 4 site , I used the Internet Application template so there were some pages there on creation.Add the WebActivator package from nugetAdd a class to the App_Start folder called RazorPageBugTestPaste this code ( changing the relevant namespace ) : Notice that this code is not something that would usually work on a web server anyway - given that it 's writing to drive C : ( indeed this might not work on your machine if you do n't run VS as administrator ) .Now build the project.This next bit works best if you already have Explorer open on C : Once that 's completed , find a Razor view and open itWait for all the C # /VB bits to be highlightedTake a look at drive C - oh look , there 's a file called 'trace.txt ' and the date is within the last few seconds ! So that demonstrates the problem here - the Razor code editor is firing up an AppDomain and , effectively , shelling the website in order to get intellisense ( including things like stuff in the App_Helpers folder etc ) . Now it does n't actually trigger the Application_Start method - but when you have WebActivator in the project as well , any of its pre-application-start methods are triggered.In my case this is causing huge issues - high CPU usage and memory usage in devenv.exe ( equivalent to the website having just been started ) because I initialise DI containers and god-knows what else at this point , but one in particular is proving really annoying.My website has a component that listens on the network for status and cache-invalidation messages from other machines in the web farm . In QA and Live environments this listener never fails to open the port and listen - on my dev machine , however , it frequently fails - saying the port 's already in use . When I look for the process that 's holding it open - it 's always devenv.exe.You guessed it - I start this listener in a WebActivator-initialised boot-strapping call.So the question is - does anyone know of a way to detect that the code is n't being run by a 'proper ' web host so I can stop it being run ? I 'm particularly hopeful for this as it 'll also mean that my Visual Studio and Razor editing experience will become a damn-site faster as a result ! As a bonus , any fix could legitimately be sent to David Ebbo - author of WebActivator - so he can stick it earlier in his stack to prevent the problem completely ! UpdateI have just added an issue to the WebActivator page on GitHub to see if David Ebbo can push either my fix , or a better one , down into the WebActivator component . using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using MvcApplication6.App_Start ; using System.IO ; [ assembly : WebActivator.PreApplicationStartMethod ( typeof ( RazorPageBugTest ) , `` Start '' , Order = 0 ) ] namespace MvcApplication6.App_Start { public static class RazorPageBugTest { public static void Start ( ) { using ( var writer = File.Open ( @ '' c : \trace.txt '' , FileMode.Create ) ) { using ( var tw = new StreamWriter ( writer ) ) { tw.AutoFlush = true ; tw.WriteLine ( `` Written at { 0 } '' , DateTime.Now ) ; } } } } }",Detect when Visual Studio is test-firing the website for intellisense "C_sharp : When doing P/Invoke , it is important to make the data layout match.We can control the layout of struct by using some attribute.For example : gives a size of 4 . While we can tell compiler to make it a 1 byte bool to match C++ type of bool : gives a size of 1.These make sense . But when I test fixed bool array , I was confused.gives a size of 4 bytes . andstill gives a size of 4 bytes . butgives a size of 8.It looks like in fixed bool array , the size of bool element is still 1 byte , but the alignment is 4 bytes . This does n't match C++ bool array , which is 1 byte size and alignment.Can someone explain me on this ? Update : I finally find out , the reason is , bool type in a struct , then that struct will NEVER be blittable ! So do n't expect a struct which has bool type inside to be same layout as in C.Regards , Xiang . struct MyStruct { public bool f ; } struct MyStruct { [ MarshalAs ( UnmanagedType.I1 ) ] public bool f ; } unsafe struct MyStruct { public fixed bool fs [ 1 ] ; } unsafe struct MyStruct { public fixed bool fs [ 4 ] ; } unsafe struct MyStruct { public fixed bool fs [ 5 ] ; }",What 's the size and alignment of C # fixed bool array in struct ? "C_sharp : The definition of Nullable < T > is : The constraint where T : struct implies that T can only be a value type . So I very well understand that I can not write : Because string is a reference type , not a value type . But I do n't really understand why ca n't I write Why is it not allowed ? After all , Nullable < int > is a value-type , and therefore , it can be type argument to Nullablle < T > .When I compiled it on ideone , it gives this error ( ideone ) : error CS0453 : The type 'int ? ' must be a non-nullable value type in order to use it as type parameter 'T ' in the generic type or method 'System.Nullable ' Compilation failed : 1 error ( s ) , 0 warnings [ SerializableAttribute ] public struct Nullable < T > where T : struct , new ( ) Nullable < string > a ; //error . makes sense to me Nullable < Nullable < int > > b ; //error . but why ?",Why ca n't I write Nullable < Nullable < int > > ? "C_sharp : Here 's a simplified version of my example : When the command is disposed , is the connection closed ? Or would I need to have that first using statement be for the connection , and then create the command in the closure ? using ( DbCommand cmd = new SqlCommand ( `` myProcedure '' , ( SqlConnection ) DataAccessHelper.CreateDatabase ( ) .CreateConnection ( ) ) { CommandType = CommandType.StoredProcedure } ) { cmd.Connection.Open ( ) ; using ( IDataReader dr = cmd.ExecuteReader ( ) ) doWork ( dr ) ; }",.Net : Does my connection get closed via Dispose in this example ? "C_sharp : I 'm setting up the format layout for the video as follows : This is how I am setting up the Codec Context : I 'm using the following code to setup the `` movflags '' > `` faststart '' option for the header of the video : The file is opened and the header is written as follows : After this , I write each video frame as follows : After that , I write the trailer : The file finishes writing and everything closes and frees up correctly . However , the MP4 file is unplayable ( even VLC cant play it ) . AtomicParsley.exe wo n't show any information about the file either.The DLLs used for the AutoGen library are : AVOutputFormat* outputFormat = ffmpeg.av_guess_format ( null , `` output.mp4 '' , null ) ; AVCodec* videoCodec = ffmpeg.avcodec_find_encoder ( outputFormat- > video_codec ) ; AVFormatContext* formatContext = ffmpeg.avformat_alloc_context ( ) ; formatContext- > oformat = outputFormat ; formatContext- > video_codec_id = videoCodec- > id ; ffmpeg.avformat_new_stream ( formatContext , videoCodec ) ; AVCodecContext* codecContext = ffmpeg.avcodec_alloc_context3 ( videoCodec ) ; codecContext- > bit_rate = 400000 ; codecContext- > width = 1280 ; codecContext- > height = 720 ; codecContext- > gop_size = 12 ; codecContext- > max_b_frames = 1 ; codecContext- > pix_fmt = videoCodec- > pix_fmts [ 0 ] ; codecContext- > codec_id = videoCodec- > id ; codecContext- > codec_type = videoCodec- > type ; codecContext- > time_base = new AVRational { num = 1 , den = 30 } ; AVDictionary* options = null ; int result = ffmpeg.av_dict_set ( & options , `` movflags '' , `` faststart '' , 0 ) ; int writeHeaderResult = ffmpeg.avformat_write_header ( formatContext , & options ) ; if ( ( formatContext- > oformat- > flags & ffmpeg.AVFMT_NOFILE ) == 0 ) { int ioOptionResult = ffmpeg.avio_open ( & formatContext- > pb , `` output.mp4 '' , ffmpeg.AVIO_FLAG_WRITE ) ; } int writeHeaderResult = ffmpeg.avformat_write_header ( formatContext , & options ) ; outputFrame- > pts = frameIndex ; packet.flags |= ffmpeg.AV_PKT_FLAG_KEY ; packet.pts = frameIndex ; packet.dts = frameIndex ; int encodedFrame = 0 ; int encodeVideoResult = ffmpeg.avcodec_encode_video2 ( codecContext , & packet , outputFrame , & encodedFrame ) ; if ( encodedFrame ! = 0 ) { packet.pts = ffmpeg.av_rescale_q ( packet.pts , codecContext- > time_base , m_videoStream- > time_base ) ; packet.dts = ffmpeg.av_rescale_q ( packet.dts , codecContext- > time_base , m_videoStream- > time_base ) ; packet.stream_index = m_videoStream- > index ; if ( codecContext- > coded_frame- > key_frame > 0 ) { packet.flags |= ffmpeg.AV_PKT_FLAG_KEY ; } int writeFrameResult = ffmpeg.av_interleaved_write_frame ( formatContext , & packet ) ; } int writeTrailerResult = ffmpeg.av_write_trailer ( formatContext ) ; avcodec-56.dllavdevice-56.dllavfilter-5.dllavformat-56.dllavutil-54.dllpostproc-53.dllswresample-1.dllswscale-3.dll",FFmpeg `` movflags '' > `` faststart '' causes invalid MP4 file to be written "C_sharp : I have a project with the .csproj defined using the .NET Core format . The project contains user control files consisting of a .xaml file and an associated .cs file . Previously I got a compilation error on those user controls until I added the following content to the .csproj file : At that point the solution began to compile within Visual Studio . However , when I attempt to build from the command line using dotnet build , the build fails with the error I had previously seen in Visual Studio : The name 'InitializeComponent ' does not exist in the current context.Any ideas why the solution builds in VS2017 but not using dotnet build , or how I go about fixing this ? EDIT : .csproj content without PackageReferences < ItemGroup > < Page Include= '' **\*.xaml '' > < SubType > Designer < /SubType > < Generator > MSBuild : UpdateDesignTimeXaml < /Generator > < /Page > < Compile Update= '' **\*.xaml.cs '' SubType= '' Code '' DependentUpon= '' % ( Filename ) '' / > < /ItemGroup > < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < LanguageTargets > $ ( MSBuildToolsPath ) \Microsoft.CSharp.targets < /LanguageTargets > < TargetFramework > net45 < /TargetFramework > < IsPackable > true < /IsPackable > < /PropertyGroup > < ItemGroup > < Page Include= '' **\*.xaml '' > < SubType > Designer < /SubType > < Generator > MSBuild : UpdateDesignTimeXaml < /Generator > < /Page > < Compile Update= '' **\*.xaml.cs '' SubType= '' Code '' DependentUpon= '' % ( Filename ) '' / > < /ItemGroup > < ItemGroup > < Reference Include= '' PresentationCore '' / > < Reference Include= '' PresentationFramework '' / > < Reference Include= '' System '' / > < Reference Include= '' System.ComponentModel.DataAnnotations '' / > < Reference Include= '' System.Core '' / > < Reference Include= '' System.Xaml '' / > < Reference Include= '' WindowsBase '' / > < /ItemGroup > < /Project >",Dotnet build fails for projects containing UserControl ( InitializeComponent does not exist in the current context ) "C_sharp : Note : Let me appologize for the length of this question , i had to put a lot of information into it . I hope that does n't cause too many people to simply skim it and make assumptions . Please read in its entirety . Thanks.I have a stream of data coming in over a socket . This data is line oriented . I am using the APM ( Async Programming Method ) of .NET ( BeginRead , etc.. ) . This precludes using stream based I/O because Async I/O is buffer based . It is possible to repackage the data and send it to a stream , such as a Memory stream , but there are issues there as well.The problem is that my input stream ( which i have no control over ) does n't give me any information on how long the stream is . It simply is a stream of newline lines looking like this : So , using APM , and since i do n't know how long any given data set will be , it is likely that blocks of data will cross buffer boundaries requiring multiple reads , but those multiple reads will also span multiple blocks of data.Example : My first thought was to use a StringBuilder and simply append the buffer lines to the SB . This works to some extent , but i found it difficult to extract blocks of data . I tried using a StringReader to read newlined data but there was no way to know whether you were getting a complete line or not , as StringReader returns a partial line at the end of the last block added , followed by returning null aftewards . There is n't a way to know if what was returned was a full newlined line of data.Example : What 's worse , is that if I just keep appending to the data , the buffers get bigger and bigger , and since this could run for weeks or months at a time that 's not a good solution . My next thought was to remove blocks of data from the SB as I read them . This required writing my own ReadLine function , but then I 'm stuck locking the data during reads and writes . Also , the larger blocks of data ( which can consist of hundreds of reads and megabytes of data ) require scanning the entire buffer looking for newlines . It 's not efficient and pretty ugly.I 'm looking for something that has the simplicity of a StreamReader/Writer with the convenience of async I/O . My next thought was to use a MemoryStream , and write the blocks of data to a memory stream then attach a StreamReader to the stream and use ReadLine , but again I have issues with knowing if a the last read in the buffer is a complete line or not , plus it 's even harder to remove the `` stale '' data from the stream . I also thought about using a thread with synchronous reads . This has the advantage that using a StreamReader , it will always return a full line from a ReadLine ( ) , except in broken connection situations . However this has issues with canceling the connection , and certain kinds of network problems can result in hung blocking sockets for an extended period of time . I 'm using async IO because i do n't want to tie up a thread for the life of the program blocking on data receive.The connection is long lasting . And data will continue to flow over time . During the intial connection , there is a large flow of data , and once that flow is done the socket remains open waiting for real-time updates . I do n't know precisely when the initial flow has `` finished '' , since the only way to know is that no more data is sent right away . This means i ca n't wait for the initial data load to finish before processing , I 'm pretty much stuck processing `` in real time '' as it comes in.So , can anyone suggest a good method to handle this situation in a way that is n't overly complicated ? I really want this to be as simple and elegant as possible , but I keep coming up with more and more complicated solutions due to all the edge cases . I guess what I want is some kind of FIFO in which i can easily keep appending more data while at the same time poping data out of it that matches certain criteria ( ie , newline terminated strings ) . COMMAND\n ... Unpredictable number of lines of data ... \nEND COMMAND\n ... .repeat ... . Byte buffer [ 1024 ] = `` ... ... ... ... ... ..blah\nThis is another l '' [ another read ] `` ine\n ... ... ... ... ... ... ... ... ... ..More Lines ... '' // Note : no newline at the endStringBuilder sb = new StringBuilder ( `` This is a line\nThis is incomp.. '' ) ; StringReader sr = new StringReader ( sb ) ; string s = sr.ReadLine ( ) ; // returns `` This is a line '' s = sr.ReadLine ( ) ; // returns `` This is incomp.. ''",What is a good method to handle line based network I/O streams ? "C_sharp : I have the following string : and want to split it by commas that are outside parentheses to this : [ A ] == [ B ] * 10 - FUNCTION ( [ C ] , STRING_EXPRESSION , FUNCTION ( [ D ] , [ C ] , [ E ] ) ) FUNCTION ( [ C ] , [ X ] ) 100I was not able to do this alone or using any of the similar answers here.For example , , \s* ( ? ! \ [ ^ ( ) \ ] *\ ) ) regular expression works well , but only if not nested parentheses are used , which is my case.Could anyone tell me how to split the values ( using or not regular expression ) ? [ A ] == [ B ] * 10 - FUNCTION ( [ C ] , STRING_EXPRESSION , FUNCTION ( [ D ] , [ C ] , [ E ] ) ) , FUNCTION ( [ C ] , [ X ] ) , 100",Splitting values by commas that are outside parentheses ? "C_sharp : When you have different instances of the same class such as 'FootballTeam ' for example and you want to let another instance of this FootballTeam class know that something occured , whats the best way to go about this ? Events wo n't really work I guess ... EG : FootballTeam A = new FootballTeam ( ) ; FootballTeam B = new FootballTeam ( ) ; // now A needs to let B know about it 's manager change// manager is a property inside this class ...",c # class instance communication "C_sharp : From what I have read POCO classes should be persistence ignorant and should not contain references to repositories.Q1 . Given the above , how would I populate the QuestionBlocks collection ? I have read that POCO 's should contain behavior so you do n't end of with an anemic model , so I 'm kind of confused as how one is supposed to do that without persistence . If that 's the case then what kind of behavior would you put in a POCO ? Ex : public class Survey { public int SurveyId { get ; set ; } public string Title { get ; set ; } public int BrandId { get ; set ; } public DateTime Created { get ; set ; } public List < SurveyQuestionBlock > QuestionBlocks { get ; set ; } [ ResultColumn ] public string Name { get ; set ; } /// < summary > /// Constructor /// < /summary > public Survey ( ) { Created = DateTime.Now ; QuestionBlocks = new List < SurveyQuestionBlock > ( ) ; } }","POCO 's , behavior and Peristance Igorance" "C_sharp : I have the following 2 classes : I then have an EF query that brings back 'all active ' Rules , and I need it to .Include Exclusions for each Rule ( if there are any ) BUT only Exclusions that have been assigned the specified InstanceId . So the filtering is being done against the Exclusions property , rather than filtering out Rules.I also have a few conditions as I build up my EF query that I need to take into consideration.Here is my query at the moment : I tried applying a .Where within the .Include ( ) in an attempt to only include the relevant Exclusions ( based on instanceId ) but found out you ca n't do that . I hunted around and found some examples where people had used an anonymous type , but I could n't get this working when building up the query piece by piece as I 'm doing here.So , I do n't know how I can accomplish this as I really do n't want to be returning 'every ' Exclusion for each Rule , when I do n't need every Exclusion returned . public class Rule { public int Id { get ; set ; } public string RuleValue { get ; set ; } public bool IsActive { get ; set ; } public SharedRuleType RuleType { get ; set ; } public List < Exclusion > Exclusions { get ; set ; } } public class Exclusion { public int Id { get ; set ; } public int InstanceId { get ; set ; } public int SiteId { get ; set ; } [ ForeignKey ( `` RuleId '' ) ] public int RuleId { get ; set ; } public Rule Rule { get ; set ; } } public async Task < List < Rule > > GetRules ( int instanceId , SharedRuleType ruleType , string searchTerm ) { using ( var context = new MyDbContext ( ) ) { var query = context.Set < Rule > ( ) .Include ( r = > r.Exclusions ) // *** Currently returns ALL exclusions but I only want ones where InstanceId == instanceId ( param ) *** .Where ( r = > r.IsActive ) ; if ( ! string.IsNullOrEmpty ( searchTerm ) ) { query = query.Where ( r = > r.RuleValue.Contains ( searchTerm ) ) ; } if ( ruleType ! = SharedRuleType.None ) { query = query.Where ( r = > r.RuleType == ruleType ) ; } return await query.ToListAsync ( ) ; } }",How to apply WHERE condition to EF .Include ( ) when building up EF query "C_sharp : I have the need to create a REST webservice.For that I followed this tutorial : http : //www.odata.org/blog/how-to-use-web-api-odata-to-build-an-odata-v4-service-without-entity-framework/Everything worked fine , I also added BasicAuth to it , it works like a glove.Now , my question ... This webservice will work with possible versions of it , so we decided to implement a sort of versions systems . Also , we want the client applications to choose the database that they want to perform their actions.For that , we thought that it would be nice to have URIs with this style : http : //localhost/Connection/northwind/API/1/DataRowThis is the code that I have . I used to have only the entity DataRow defined . Now I have also defined the entity API and Connection.How do I implement a URI/endpoint like what I want ? This is the code that I have , so far.File : WebApiConfig.csControllers\DataRows.csControllers\Connections.csModels\DataRow.cs using Integration.Models ; using Microsoft.OData.Edm ; using System.Web.Http ; using System.Web.OData.Batch ; using System.Web.OData.Builder ; using System.Web.OData.Extensions ; using Integration.Controllers ; namespace Integration { public static class WebApiConfig { public static void Register ( HttpConfiguration config ) { config.MapODataServiceRoute ( `` odata '' , null , GetEdmModel ( ) , new DefaultODataBatchHandler ( GlobalConfiguration.DefaultServer ) ) ; config.EnsureInitialized ( ) ; } private static IEdmModel GetEdmModel ( ) { //GlobalConfiguration.Configuration.Filters.Add ( new BasicAuthenticationFilter ( ) ) ; // basicAutenthentication ODataConventionModelBuilder builder = new ODataConventionModelBuilder ( ) ; builder.Namespace = `` Integration '' ; builder.ContainerName = `` DefaultContainer '' ; builder.EntitySet < DataRow > ( `` DataRow '' ) ; builder.EntitySet < Connection > ( `` Connection '' ) ; builder.EntitySet < API > ( `` API '' ) ; var edmModel = builder.GetEdmModel ( ) ; return edmModel ; } } } using Integration.DataSource ; using System.Linq ; using System.Web.Http ; using System.Web.OData ; using System.Net ; namespace Integration.Controllers { [ EnableQuery ] public class DataRowController : ODataController { [ BasicAuthenticationFilter ] public IHttpActionResult Get ( ) { return Content ( HttpStatusCode.NoContent , '' NoContent '' ) ; } [ BasicAuthenticationFilter ] public IHttpActionResult Post ( Models.DataRow row ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } //do stuff to save data // .. return Content ( HttpStatusCode.Created , `` OK '' ) ; } } } using Integration.DataSource ; using System.Linq ; using System.Web.Http ; using System.Web.OData ; using System.Net ; namespace Integration.Controllers { [ EnableQuery ] public class ConnectionController : ODataController { [ BasicAuthenticationFilter ] public IHttpActionResult Get ( ) { return Ok ( IntegrationDataSources.Instance.Connection.AsQueryable ( ) ) ; } [ BasicAuthenticationFilter ] public IHttpActionResult Post ( Models.Connection connection ) { return Content ( HttpStatusCode.NotImplemented , `` NotImplemented '' ) ; } } } using System ; using System.Collections.Generic ; using System.ComponentModel.DataAnnotations ; using System.Linq ; using System.Web ; namespace Integration.Models { public class DataRow { [ Key ] public int ID { get ; set ; } [ Required ] public int Type { get ; set ; } [ Required ] public string DataType { get ; set ; } [ Required ] public string Data { get ; set ; } [ Required ] public int APIVersion { get ; set ; } [ Required ] public string IntegrationProvider { get ; set ; } } public class Connection { [ Key ] public string ConnectionName { get ; set ; } public API Api { get ; set ; } } public class API { [ Key ] public int Version { get ; set ; } public DataRow row { get ; set ; } } }",REST webservice WebAPI - create endpoint based on multiple entities "C_sharp : I have a string like the following : You can look at it as this tree : As you can see , it 's a string serialization / representation of a class Testing.UserI want to be able to do a split and get the following elements in the resulting array : I ca n't split by | because that would result in : How can I get my expected result ? I 'm not very good with regular expressions , but I am aware it is a very possible solution for this case . [ Testing.User ] |Info : ( [ Testing.Info ] |Name : ( [ System.String ] |Matt ) |Age : ( [ System.Int32 ] |21 ) ) |Description : ( [ System.String ] |This is some description ) - [ Testing.User ] - Info - [ Testing.Info ] - Name - [ System.String ] - Matt - Age - [ System.Int32 ] - 21- Description - [ System.String ] - This is some description [ 0 ] = [ Testing.User ] [ 1 ] = Info : ( [ Testing.Info ] |Name : ( [ System.String ] |Matt ) |Age : ( [ System.Int32 ] |21 ) ) [ 2 ] = Description : ( [ System.String ] |This is some description ) [ 0 ] = [ Testing.User ] [ 1 ] = Info : ( [ Testing.Info ] [ 2 ] = Name : ( [ System.String ] [ 3 ] = Matt ) [ 4 ] = Age : ( [ System.Int32 ] [ 5 ] = 21 ) ) [ 6 ] = Description : ( [ System.String ] [ 7 ] = This is some description )",Complex string splitting C_sharp : Basically suppose you have some collection : Is this acceptable ? Or is this bug-prone or bad practice ? I will pretty much always be using the IEnumerator < T > but I still want the non-generic version to be stable and properly implemented . public class FurCollection : IEnumerable < FurStrand > { public IEnumerator < FurStrand > GetEnumerator ( ) { foreach ( var strand in this.Strands ) { yield return strand ; } } IEnumerator IEnumerable.GetEnumerator ( ) { return this.GetEnumerator ( ) ; } },Is it ok to return IEnumerator < T > .GetEnumerator ( ) in IEnumerator.GetEnumerator ( ) ? "C_sharp : I 'm thinking about creating some classes along a `` single-use '' design pattern , defined by the following features : Instances are used for performing some task.An instance will execute the task only once . Trying to call the execute method twice will raise an exception.Properties can be modified before the execute method is called . Calling them afterward will also raise an exception.A minimalist implementation might look like : Questions : Is there a name for this ? Pattern or anti-pattern ? public class Worker { private bool _executed = false ; private object _someProperty ; public object SomeProperty { get { return _someProperty ; } set { ThrowIfExecuted ( ) ; _someProperty = value ; } } public void Execute ( ) { ThrowIfExecuted ( ) ; _executed = true ; // do work . . . } private void CheckNotExcecuted ( ) { if ( _executed ) throw new InvalidOperationException ( ) ; } }",Single-use object : yea or nay ? "C_sharp : I have the following code which is throwing a CryptographicException about 5 % of the time and I ca n't figure out why a ) it does n't fail consistently and b ) why it 's failing at all : The stack looks like : The rest of the time ( 95 % ) , this code works as expected and I 'm able to communicate with a federated service using this dynamically generated certificate . Any ideas ? // Initialize the new secure keysvar keyGenerator = KeyGenerator.Create ( ) ; var keyPair = keyGenerator.GenerateKeyPair ( ) ; this._privateKey = keyPair.ToEncryptedPrivateKeyString ( privateKeySecret ) ; this._publicKey = keyPair.ToPublicKeyString ( ) ; // Initialize the certificate generationvar certificateGenerator = new X509V3CertificateGenerator ( ) ; var serialNo = BigInteger.ProbablePrime ( 128 , new Random ( ) ) ; certificateGenerator.SetSerialNumber ( serialNo ) ; certificateGenerator.SetSubjectDN ( GetLicenseeDN ( ) ) ; certificateGenerator.SetIssuerDN ( GetLicencerDN ( ) ) ; certificateGenerator.SetNotAfter ( DateTime.Now.AddYears ( 100 ) ) ; certificateGenerator.SetNotBefore ( DateTime.Now.Subtract ( new TimeSpan ( 7 , 0 , 0 , 0 ) ) ) ; certificateGenerator.SetSignatureAlgorithm ( `` SHA512withRSA '' ) ; certificateGenerator.SetPublicKey ( keyPair.PublicKey ) ; var result = certificateGenerator.Generate ( keyPair.PrivateKey ) ; this._clientCertificate = new X509Certificate2 ( DotNetUtilities.ToX509Certificate ( result ) ) ; this._clientCertificate.PrivateKey = DotNetUtilities.ToRSA ( ( RsaPrivateCrtKeyParameters ) keyPair.PrivateKey ) ; System.Security.Cryptography.CryptographicException : Bad Data.Result StackTrace : at System.Security.Cryptography.CryptographicException.ThrowCryptographicException ( Int32 hr ) at System.Security.Cryptography.Utils._ImportKey ( SafeProvHandle hCSP , Int32 keyNumber , CspProviderFlags flags , Object cspObject , SafeKeyHandle & hKey ) at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters ( RSAParameters parameters ) at Org.BouncyCastle.Security.DotNetUtilities.ToRSA ( RsaPrivateCrtKeyParameters privKey ) in C : \BouncyCastle\crypto\src\security\DotNetUtilities.cs : line 173 at EBSConnect.EBSClientBase.InitializeSecurity ( String privateKeySecret ) in c : \Projects\EBSConnect\Source\EBSConnect\EBSClientBase.cs : line 78",Why am I getting a Bad Data exception only 5 % of the time ? "C_sharp : So I 've refactored completely to constructor injection , and now I have a bootstrapper class that looks similar to this : I stared at it for a second before realizing that Unity is really not doing anything special here for me . Leaving out the ctor sigs , the above could be written as : The constructor injection refactoring is great and really opens up the testability of the code . However , I 'm doubting the usefulness of Unity here . I realize I may be using the framework in a limited manner ( ie not injecting the container anywhere , configuring in code rather than XML , not taking advantage of lifetime management options ) , but I am failing to see how it is actually helping in this example . I 've read more than one comment with the sentiment that DI is better off simply used as a pattern , without a container . Is this a good example of that situation ? What other benefits does this solution provide that I am missing out on ? var container = new UnityContainer ( ) ; container.RegisterType < Type1 , Impl1 > ( ) ; container.RegisterType < Type2 , Impl2 > ( ) ; container.RegisterType < Type3 , Impl3 > ( ) ; container.RegisterType < Type4 , Impl4 > ( ) ; var type4Impl = container.Resolve ( ( typeof ) Type4 ) as Type4 ; type4Impl.Run ( ) ; Type1 type1Impl = Impl1 ( ) ; Type2 type2Impl = Impl2 ( ) ; Type3 type3Impl = Impl3 ( type1Impl , type2Impl ) ; Type4 type4Impl = Impl4 ( type1Impl , type3Impl ) ; type4Impl.Run ( ) ;",What is an IOC container actually doing for me here ? "C_sharp : I am currently trying to print the contents of a content container ( it only contains datagrids with information ) and an image using PrintFixedDocument . It prints flawlessly on my machine ( windows 10 ) with full image quality and on another pc which is windows 8 , the quality is the same.However when this is done on a Windows 7 pc the image quality becomes very poor and the final result is very blurred . This is a problem as the computer can not be updated from windows 7 for various reasons , so im wondering if anyone else has experienced this and if so is there a workaround ? Also could be an issue with my GetFixedDocument method , though I can not work out why this would work on both win 10 and 8 but not 7.NOTE THIS IS RUNNING FROM AN INSTALLED VERSION OF THE APPLICATION ON EACH PCALSO BEEN TRIED ON MULTIPLE PRINTERS ON ALL 3 OPERATING SYSTEMSAny help would be appreciatedXaml : C # : public partial class CouponViewerView { public CouponViewerView ( ) { InitializeComponent ( ) ; } C # Print helper code : < StackPanel Margin= '' -105,146,66,0 '' Height= '' 900 '' VerticalAlignment= '' Top '' x : Name= '' PrintImageContextMenu '' > < Image Canvas.ZIndex= '' 0 '' Source= '' { Binding Coupon.OverlayImagePath } '' Margin= '' 0 , -21 , -76,108 '' Stretch= '' Fill '' / > < ContentControl Content= '' { Binding } '' ContentTemplateSelector= '' { StaticResource DataViewerDataTemplateSelector } '' / > < /StackPanel > public void Print ( ) { //Executes On Thread Application.Current.Dispatcher.Invoke ( System.Windows.Threading.DispatcherPriority.Normal , ( EventHandler ) delegate { UpdateLayout ( ) ; var fixedDoc = PrintHelper.GetFixedDocument ( StackPanelToPrint , new PrintDialog ( ) ) ; PrintHelper.ShowPrintPreview ( fixedDoc ) ; } , null , null ) ; } private void PrintCurrentForm ( object sender , RoutedEventArgs e ) { Print ( ) ; } public static void ShowPrintPreview ( FixedDocument fixedDoc ) { var wnd = new Window ( ) ; var viewer = new DocumentViewer ( ) ; viewer.Document = fixedDoc ; wnd.Content = viewer ; wnd.ShowDialog ( ) ; } public static FixedDocument GetFixedDocument ( FrameworkElement toPrint , PrintDialog printDialog ) { var capabilities = printDialog.PrintQueue.GetPrintCapabilities ( printDialog.PrintTicket ) ; var pageSize = new Size ( printDialog.PrintableAreaWidth , printDialog.PrintableAreaHeight ) ; var visibleSize = new Size ( capabilities.PageImageableArea.ExtentWidth , capabilities.PageImageableArea.ExtentHeight ) ; var fixedDoc = new FixedDocument ( ) ; //If the toPrint visual is not displayed on screen we neeed to measure and arrange it toPrint.Measure ( new Size ( double.PositiveInfinity , double.PositiveInfinity ) ) ; toPrint.Arrange ( new Rect ( new Point ( 0 , 0 ) , toPrint.DesiredSize ) ) ; // var size = toPrint.DesiredSize ; //Will assume for simplicity the control fits horizontally on the page double yOffset = 0 ; while ( yOffset < size.Height ) { var vb = new VisualBrush ( toPrint ) { Stretch = Stretch.None , AlignmentX = AlignmentX.Left , AlignmentY = AlignmentY.Top , ViewboxUnits = BrushMappingMode.Absolute , TileMode = TileMode.None , Viewbox = new Rect ( 0 , yOffset , visibleSize.Width , visibleSize.Height ) } ; var pageContent = new PageContent ( ) ; var page = new FixedPage ( ) ; ( ( IAddChild ) pageContent ) .AddChild ( page ) ; fixedDoc.Pages.Add ( pageContent ) ; page.Width = pageSize.Width ; page.Height = pageSize.Height ; var canvas = new Canvas ( ) ; FixedPage.SetLeft ( canvas , capabilities.PageImageableArea.OriginWidth ) ; FixedPage.SetTop ( canvas , capabilities.PageImageableArea.OriginHeight ) ; canvas.Width = visibleSize.Width ; canvas.Height = visibleSize.Height ; canvas.Background = vb ; page.Children.Add ( canvas ) ; yOffset += visibleSize.Height ; } return fixedDoc ; }",PrintFixedDocument wpf print quality- Windows 10/8 vs Windows 7 C_sharp : I 'm wondering why in C # the following is fine : ButIs n't ? Why is there a bias against the + ? int y = x++-+-++x ; int y = x+++-+++x ;,Why is x++-+-++x legal but x+++-+++x is n't ? C_sharp : First code : Second code : What is the difference between the blocks ? if ( i==0 ) { // do instructions here } if ( 0==i ) { // do instructions here },Is there a difference between i==0 and 0==i ? "C_sharp : In a UWP-Windows 10 C # /XAML app using Template10 , I 'm currently trying to have my pages/views inherit from a base class that inherits from Windows.UI.Xaml.Controls.Page.This has been working correctly , however when I try to make the base class generic , and include a type argument in the child class and the XAML in the following way , it does not work : The error I receive is : The error shows up every time I add the line x : TypeArguments= '' l : Model '' to the XAML . Multiple rebuilds , cleans , etc. , in visual studio have not solved the problem.Is there something I am doing wrong in the implementation of the generic in XAML ? namespace App.Views { public abstract class InfoListViewBase < M > : Page where M : InfoListViewModelBase { public InfoListViewBase ( ) { } } public sealed partial class ModelPage : InfoListViewBase < Model > { public Model ( ) { InitializeComponent ( ) ; NavigationCacheMode = NavigationCacheMode.Disabled ; } } } < local : InfoListViewBase x : Class= '' App.Views.ModelPage '' x : TypeArguments= '' l : Model '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : Behaviors= '' using : Template10.Behaviors '' xmlns : Core= '' using : Microsoft.Xaml.Interactions.Core '' xmlns : Interactivity= '' using : Microsoft.Xaml.Interactivity '' xmlns : controls= '' using : Template10.Controls '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : local= '' using : App.Views '' xmlns : l= '' using : Library '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' > < /local : InfoListViewBase > The name `` InfoListViewBase ` 1 '' does not exist in the namespace `` using : App.Views '' .",Generic base class for Pages/Views in UWP Windows 10 App "C_sharp : System.Xml.Serialization.XmlCodeExporter generates code ( in code CodeDom form ) from an XSD schema . But it does it with some quirks . For example an optional element : I would expect this to generate a corresponding code member of type Nullable < decimal > , but it actually creates a member of type decimal , and then a separate SomethingSpecified field which should be toggled separately to indicate a null value . This is probably because the library is from before the introduction of nullable types , but it leads to really inconvenient code . Is it possible to adjust this code generation , or is there an alternative tool which generate better code in this case ? Edit : I know I can modify the schema and add nillable='true ' , but I do n't want to change the schema to work around limitations of the code generation . < xs : element name= '' Something '' type= '' xs : decimal '' minOccurs= '' 0 '' maxOccurs= '' 1 '' / >",XmlCodeExporter and nullable types "C_sharp : Since IEnumerable has a covariant parameter in C # 4.0 I am confused how it is behaving in the following code.So basically the DoTestOne method does n't compile while DoTestTwo does . In addition to why it does n't work , if anyone knows how I can achieve the effect of DoTestOne ( assigning an IEnumberable < H > where H : IFoo to an IEnumberable < IFoo > ) I would appreciate the help . public class Test { IEnumerable < IFoo > foos ; public void DoTestOne < H > ( IEnumerable < H > bars ) where H : IFoo { foos = bars ; } public void DoTestTwo ( IEnumerable < IBar > bars ) { foos = bars ; } } public interface IFoo { } public interface IBar : IFoo { }",Assigning IEnumerable ( Covariance ) "C_sharp : I was having a look at the IL generated for a very simple method because I want to do a small bit of reflection emitting myself and I came across something that is mentioned in the comments in this question ( but was not the question ) : Using Br_S OpCode to point to next instruction using Reflection.Emit.Label and nobody answered it and I am wondering about it . so ... If I have a method like this : and then I run ILDASM on it I see the IL is this : The part that I find curious is : The first line is doing an Unconditional Transfer to the second line . What is the reason for this operation , does n't it do nothing ? EDITIt seems my question was phrased badly as there is some confusion over what I wanted to know . The last sentence should maybe be something like this : What is the reason that the compiler has output this unconditional transfer statement when it seems to be serving no purpose ? UPDATEThe suggestion that it was for a breakpoint made me think to try and compile this in Release mode and sure enough the part that I am interested in vanished and the IL became just this ( which is why I jumped the gun and thought that the breakpoint answer was the reason ) : The question of `` why is it there '' still plays on my mind though - if it is not the way the compiler always works and it is not for some useful debugging reason ( like having somewhere to place a breakpoint ) why have it at all ? I guess the answer is probably : `` just the way it has been made , no solid reason , and it does n't really matter because the JIT will sort it all out nicely in the end . `` I wish I 'd not asked this now , this is going to ruin my acceptance percentage ! ! : - ) public string Test ( ) { return `` hello '' ; } .method public hidebysig instance string Test ( ) cil managed { // Code size 11 ( 0xb ) .maxstack 1 .locals init ( [ 0 ] string CS $ 1 $ 0000 ) IL_0000 : nop IL_0001 : ldstr `` hello '' IL_0006 : stloc.0 IL_0007 : br.s IL_0009 IL_0009 : ldloc.0 IL_000a : ret } IL_0007 : br.s IL_0009 IL_0009 : ldloc.0 .method public hidebysig instance string Test ( ) cil managed { // Code size 6 ( 0x6 ) .maxstack 8 IL_0000 : ldstr `` hello '' IL_0005 : ret }",Why does the compiler create an instruction that seems to do nothing when returning a string from a method ? "C_sharp : I have a question about how bindings work in WPF.If i have a viewmodel with a property like this : Then if I bind it to a xaml with something like this : It works ... Nothing new here.However , if I remove the getters and setters from the test string and end up with something like this : The very same binding does n't work . I have no idea why this occurs because to me , it 's equivalent a public attribute to a public attribute with custom get and set.Can someone shed some light on this subject for me ? : ) TYVM in advance ! ! PS : Sorry about my syntax highlight . I just ca n't figure how to work with the code block . private string testString ; public string TestString { get { return testString ; } set { testString = value ; } } < TextBlock Text= '' { Binding Path=TestString , Mode=TwoWay } '' Foreground= '' Red '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' FontFamily= '' Calibri '' FontSize= '' 24 '' FontWeight= '' Bold '' > < /TextBlock > public string TestString ;",Binding question in WPF - Diference between Properties and Fields "C_sharp : Recently I 've experimented with an implementation of the visitor pattern , where I 've tried to enforce Accept & Visit methods with generic interfaces : -whose purpose is to 1 ) mark certain type `` Foo '' as visitable by such a visitor , which in turn is a `` visitor of such type Foo '' and 2 ) enforce Accept method of the correct signature on the implementing visitable type , like so : So far so good , the visitor interface : -should 1 ) mark the visitor as `` able to visit '' the TVisitable 2 ) what the result type ( TResult ) for this TVisitable should be 3 ) enforce Visit method of a correct signature per each TVisitable the visitor implementation is `` able to visit '' , like so : Quite pleasantly & beautifully , this lets me write : Very good.Now the sad times begin , when I add another visitable type , like : which is visitable by let 's say just the CountVisitor : which suddenly breaks the type inference in the Accept method ! ( this destroys the whole design ) giving me : `` The type arguments for method 'Foo.Accept < TResult > ( IVisitor < TResult , Foo > ) ' can not be inferred from the usage . `` Could anyone please elaborate on why is that ? There is only one version of IVisitor < T , Foo > interface which the CountVisitor implements - or , if the IVisitor < T , Bar > ca n't be eliminated for some reason , both of them have the same T - int , = no other type would work there anyway . Does the type inference give up as soon as there are more than just one suitable candidate ? ( Fun fact : ReSharper thinks the int in theFoo.Accept < int > ( ... ) is redundant : P , even though it would n't compile without it ) public interface IVisitable < out TVisitable > where TVisitable : IVisitable < TVisitable > { TResult Accept < TResult > ( IVisitor < TResult , TVisitable > visitor ) ; } public class Foo : IVisitable < Foo > { public TResult Accept < TResult > ( IVisitor < TResult , Foo > visitor ) = > visitor.Visit ( this ) ; } public interface IVisitor < out TResult , in TVisitable > where TVisitable : IVisitable < TVisitable > { TResult Visit ( TVisitable visitable ) ; } public class CountVisitor : IVisitor < int , Foo > { public int Visit ( Foo visitable ) = > 42 ; } public class NameVisitor : IVisitor < string , Foo > { public string Visit ( Foo visitable ) = > `` Chewie '' ; } var theFoo = new Foo ( ) ; int count = theFoo.Accept ( new CountVisitor ( ) ) ; string name = theFoo.Accept ( new NameVisitor ( ) ) ; public class Bar : IVisitable < Bar > { public TResult Accept < TResult > ( IVisitor < TResult , Bar > visitor ) = > visitor.Visit ( this ) ; } public class CountVisitor : IVisitor < int , Foo > , IVisitor < int , Bar > { public int Visit ( Foo visitable ) = > 42 ; public int Visit ( Bar visitable ) = > 7 ; } var theFoo = new Foo ( ) ; int count = theFoo.Accept ( new CountVisitor ( ) ) ;",C # generic method type argument not inferred from usage "C_sharp : I want to make something like thisand I can do that by hard coding rectangles into a grid with this code : However that is just for one line , and if I need different dimensions it can get pretty messy . Is there an easier way of achieving this while still being able to add events to each rectangle ? < Rectangle Grid.Column= '' 0 '' Grid.Row= '' 0 '' Fill= '' Black '' / > < Rectangle Grid.Column= '' 1 '' Grid.Row= '' 0 '' Fill= '' Black '' / > < Rectangle Grid.Column= '' 2 '' Grid.Row= '' 0 '' Fill= '' Black '' / > < Rectangle Grid.Column= '' 3 '' Grid.Row= '' 0 '' Fill= '' Black '' / > < Rectangle Grid.Column= '' 4 '' Grid.Row= '' 0 '' Fill= '' Black '' / >",Creating a grid filled with rectangles "C_sharp : I am trying to download a .gz file of a few hundred MBs , and turn it into a very long string in C # . My test URL : https : //commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2017-47/segments/1510934803848.60/wat/CC-MAIN-20171117170336-20171117190336-00002.warc.wat.gzmemstream has a length of 283063949 . The program lingers for about 15 seconds on the line where it is initialized , and my network is floored during it , which makes sense.outmemstream has a length of only 548.Written to the command line is the first lines of the zipped document . They are not garbled . I 'm not sure how to get the rest . using ( var memstream = new MemoryStream ( new WebClient ( ) .DownloadData ( url ) ) ) using ( GZipStream gs = new GZipStream ( memstream , CompressionMode.Decompress ) ) using ( var outmemstream = new MemoryStream ( ) ) { gs.CopyTo ( outmemstream ) ; string t = Encoding.UTF8.GetString ( outmemstream.ToArray ( ) ) ; Console.WriteLine ( t ) ; }",GZipStream from MemoryStream only returns a few hundred bytes "C_sharp : I have been working in C # for about 8 months so forgive me if this is dumb ... I have an enum that I will need the string value several times in a class . So I want to use Enum.GetName ( ) to set it to a string variable which is no problem . I just do it like so ... And it works just fine.But I tried to protect it a little better because this particular Enum is more important that all the others and it would not be good if I accidentally changed the string value somehow so I tried to make it const like this.To my eyes this seems fine as it should all be known at compile time.But Visual Studio 2013 Throws an error saying the `` Can not resolve symbol GetName '' . I know it works when it is not marked `` const '' .So this leads me with two questions about this ? Why does it loose reference to the GetName enum ? ( After a bit of research I suspect it is something to do with GetName being a method and not a property of the Enum class but the error message just does not make sense to me ) And Finally is there a way to read the Name of MyEnum.Name to a const string other than what I am doing ? private string MyEnumString = Enum.GetName ( typeof ( MyEnum ) , MyEnum.Name ) ; private const string MyEnumString = Enum.GetName ( typeof ( MyEnum ) , MyEnum.Name ) ;",Enum.GetName ( ) As Constant property "C_sharp : For code such as this : This code is generated ( release mode , no debugger attached , 64bit ) : Now I can see the point of most instructions there , but what 's up with the AND instructions ? ecx will never be more than 0x1F in this code anyway , but I excuse it for not noticing that ( and also for not noticing that the result is a constant ) , it 's not an ahead-of-time compiler that can afford to spend much time on analysis after all . But more importantly , SHL with a 32bit operand masks cl by 0x1F already . So it seems to me that these ANDs are entirely useless . Why are they generated ? Do they have some purpose I 'm missing ? int res = 0 ; for ( int i = 0 ; i < 32 ; i++ ) { res += 1 < < i ; } xor edx , edx mov r8d,1 _loop : lea ecx , [ r8-1 ] and ecx,1Fh ; why ? mov eax,1 shl eax , cl add edx , eax mov ecx , r8d and ecx,1Fh ; why ? mov eax,1 shl eax , cl add edx , eax lea ecx , [ r8+1 ] and ecx,1Fh ; why ? mov eax,1 shl eax , cl add edx , eax lea ecx , [ r8+2 ] and ecx,1Fh ; why ? mov eax,1 shl eax , cl add edx , eax add r8d,4 cmp r8d,21h jl _loop",Why are AND instructions generated ? "C_sharp : I have been searching of a while now , and have still not been able to find an answer to my question , instead I find answers to Making a Generic Method with multiple Generic Type parameters.So , this is my problem . I have an interface IMyInterface < T1 , T2 > and I want to create it as a Type . Currently I can create the type for IMyInterface < T > like this : Any assistance would be greatly appreciated.Thanks : ) Type type = typeof ( IMyInterface < > ) .MakeGenericType ( genericTypeForMyInterface )",How do I create a Type with multiple generic type parameters "C_sharp : I did the following query : I would expect the above to generate something like : but it generates : Why does the above linq query generate a subquery and where does the C1 come from ? var list = from book in books where book.price > 50 select book ; list = list.Take ( 50 ) ; SELECT top 50 id , title , price , authorFROM BooksWHERE price > 50 SELECT [ Limit1 ] . [ C1 ] as [ C1 ] [ Limit1 ] . [ id ] as [ Id ] , [ Limit1 ] . [ title ] as [ title ] , [ Limit1 ] . [ price ] as [ price ] , [ Limit1 ] . [ author ] FROM ( SELECT TOP ( 50 ) [ Extent1 ] . [ id ] as as [ Id ] , [ Extent1 ] . [ title ] as [ title ] , [ Extent1 ] . [ price ] as [ price ] , [ Extent1 ] . [ author ] as [ author ] FROM Books as [ Extent1 ] WHERE [ Extent1 ] . [ price ] > 50 ) AS [ Limit1 ]",Why did the following linq to sql query generate a subquery ? "C_sharp : Is it possible to test WCF throttling behaviour through Wcftest client ? If Yes then How ? I have a code below for ServiceHostMy service has a method such as : ServiceThrottlingBehavior stb = _servicehost.Description.Behaviors.Find < ServiceThrottlingBehavior > ( ) ; if ( stb == null ) { stb = new ServiceThrottlingBehavior ( ) ; stb.MaxConcurrentCalls = 1 ; stb.MaxConcurrentInstances = 1 ; stb.MaxConcurrentSessions = 1 ; _servicehost.Description.Behaviors.Add ( stb ) ; } public string ThrottlingCheck ( ) { Thread.Sleep ( new TimeSpan ( 0 , 0 , 0 , 5 , 0 ) ) ; //5 seconds return `` Invoke Complete '' ; }",Is it possible to test WCF throttling behaviour through Wcftest client ? "C_sharp : I have seen a lot of questions about whether to declare variables inside or outside a for loop scope . This is discussed at length , for example here , here , and here . The answer is that there is absolutely no performance difference ( same IL ) , but for clarity , declaring variables in the tightest scope is preferred.I was curious about a slightly different situation : versusI expected both methods to compile to the same IL in Release mode . However , this is not the case . I 'll spare you the full IL and just point out the difference . The first method has one local : while the second has just two locals , one for each for loop counter : So there is a difference between these two which is not optimized away , which is surprising to me.Why am I seeing this , and is there actually a performance difference between the two methods ? int i ; for ( i = 0 ; i < 10 ; i++ ) { Console.WriteLine ( i ) ; } for ( i = 0 ; i < 10 ; i++ ) { Console.WriteLine ( i ) ; } for ( int i = 0 ; i < 10 ; i++ ) { Console.WriteLine ( i ) ; } for ( int i = 0 ; i < 10 ; i++ ) { Console.WriteLine ( i ) ; } .locals init ( [ 0 ] int32 i ) .locals init ( [ 0 ] int32 i , [ 1 ] int32 i )",Reuse of for loop iteration variable "C_sharp : I have modified startup.Auth.cs so that I could add scopes . Here is what I have : This allows me to authenticate the user . I have tried adding the scopes wl.signin , wl.emails and wl.contacts_emails . However , they cause the Microsoft login page to report the following error : AADSTS70011 : The provided value for the input parameter 'scope ' is not valid . The scope wl.signin , wl.emails , wl.contacts_emails is not valid . The scope combination of openid and email seems to work . However , the scope openid is overkill for what I am trying to do . That is , I think it is too much to ask from the user . The scope email all by it self does n't work.This is particularly weird because the template that Visual Studio sets up assumes that the external authentication provider will supply an email address.How do I get only the user 's email ? For context , I am using the following documents : https : //developer.microsoft.com/en-us/graph/docs/concepts/permissions_reference # openid-permissions which gives the impression that I want email and profile included in the scope . However , it goes on to state that they are included by default.I am trying to implement external Authentication in my MVC project using the document : https : //docs.microsoft.com/en-us/aspnet/core/security/authentication/social/microsoft-logins . MicrosoftAccountAuthenticationOptions mo = new MicrosoftAccountAuthenticationOptions ( ) { ClientId = `` My Client ID '' , ClientSecret = `` My Client Secret '' , } ; app.UseMicrosoftAccountAuthentication ( mo ) ;",How do I get the user 's email when using Microsoft Account Authentication in an MVC project ? "C_sharp : I 've written a program ( in C # ) that reads and manipulates MSIL programs that have been generated from C # programs . I had mistakenly assumed that the syntax rules for MSIL string constants are the same as for C # , but then I ran into the following situation : This C # statementgets compiled into ( among other MSIL statements ) thisI was n't expecting the backslash that is used to escape the question mark . Now I can obviously take this backslash into account as part of my processing , but mostly out of curiosity I 'd like to know if there is a list somewhere of which characters get escaped when the C # compiler converts C # constant strings to MSIL constant strings.Thanks . string s = `` Do you wish to send anyway ? `` ; IL_0128 : ldstr `` Do you wish to send anyway\ ? ''",Where can I find a list of escaped characters in MSIL string constants ? "C_sharp : I think I 've found a MUCH faster way to copy bitmaps in c # . ( If it 's valid , I 'm sure I was n't the first but I have n't seen it anywhere yet . ) The simplest way I can think to ask this is to assert what I based my idea on and if no one shoots holes in it , assume the idea is sound:1 ) LockBits simply copies a block of pixel data out of a bitmap to fixed memory to be edited and copied back in using UnlockBits2 ) Using LockBits does not affect the copied memory block so it should have no effect on the image copied from.3 ) Since you never enter unsafe code , there should be no risk of corrupting memory.Possible holes I see:1 ) If the PixelFormats of the two bitmaps are different , this method may not always copy correctly . However , since LockBits requires specifying a pixelformat , it seems this is handled . ( If so , hooray for that overhead the other 99.9 % of the time we 're not switching pixelformats ! /EndSarcasm ) 2 ) If the stride of the two bitmaps does n't match , there could be a problem ( because stride is the outer for loop 's incrementor in the copy operation . ) This problem would limit copying to bitmaps with equal stride.Edit : I think assertion # 2 must be wrong ... I just found an error when trying to later access the bitmap passed through CopyMe . Workaround below , but I 'm not sure if it leaves a block of fixed memory lying around . ( memory leak alert ! ) void FastCopyRegion ( Bitmap CopyMe , ref Bitmap IntoMe , Rectangle CopyArea ) { // ` IntoMe ` need not be declared ` ref ` but it brings // attention to the fact it will be modified Debug.Assert ( CopyMe.PixelFormat == IntoMe.PixelFormat , `` PixelFormat mismatch , we could have a problem '' ) ; Debug.Assert ( CopyMe.Width == IntoMe.Width , //This check does not verify `` Stride mismatch , we could have a problem '' ) ; // sign of ` stride ` match BitmapData copyData = CopyMe.LockBits ( CopyArea , ImageLockMode.ReadWrite , CopyMe.PixelFormat ) ; IntoMe.UnlockBits ( copyData ) ; } void FastCopyRegion ( Bitmap CopyMe , ref Bitmap IntoMe , Rectangle CopyArea ) { // ` IntoMe ` need not be declared ` ref ` but it brings attention to the fact it will be modified Debug.Assert ( CopyMe.PixelFormat == IntoMe.PixelFormat , `` PixelFormat mismatch , we could have a problem '' ) ; Debug.Assert ( CopyMe.Width == IntoMe.Width , `` Width mismatch , we could have a problem '' ) ; BitmapData copyD = IntoMe.LockBits ( CopyArea , ImageLockMode.ReadWrite , CopyMe.PixelFormat ) ; BitmapData copyData = CopyMe.LockBits ( CopyArea , ImageLockMode.ReadWrite , CopyMe.PixelFormat ) ; CopyMe.UnlockBits ( copyData ) ; IntoMe.UnlockBits ( copyData ) ; }",Is it safe ( pun intended ) to copy bitmap regions using lockbits this way ? "C_sharp : I am using a C # .NET 2.0 winform in 2010 , I have added the ability for a user to log in and post comments . I copied the .NET developer guide in how to post comments but I am getting random but frequent exceptions when trying to post comments . At first I thought it might be because there is some issue with using a google e-mail instead of the youtube log in name , to get around this when a user succesfully logs in I request the profile , get the user name and create a new youtube settings class and give the appropriate credentials with the users profile name . This however has n't resolved the issue , the comments still work sporadically . Here is the code that basically handles logging in.The above code is in a seperate form , the form that hosts the youtube video basically looks to see if this process has been completed and grabs the username , password used to log in and sets the new settings : This then used to add a comment : When it fails I get the following : { `` Execution of request failed : https : //gdata.youtube.com/feeds/api/videos/t-8K8Hj8bxE/comments '' } With the following info : { `` The remote server returned an error : ( 403 ) Forbidden . `` } Status code : System.Net.HttpStatusCode.ForbiddenStatus description : ForbiddenA few things come to mind , I do not have a proper log out that sends anything to youtube implimented at the minute ( is this needed ? ) , so it may be that I 've logged in multiple times and that is somehow flagging on youtubes side ? It could also be that I am essentially creating new settings and request objects that were n't used to get the video/comments and maybe the video taken from the normal settings file ( with no log in ) is giving problems or something like that ? To be honest , I have n't got a clue what is wrong and any help would be greatly appriecated . youtubeService.setUserCredentials ( userBox.Text , passwordBox.Text ) ; try { String strAuth = youtubeService.QueryClientLoginToken ( ) ; } catch ( Exception ex ) { } m_LoggedInSettings = new YouTubeRequestSettings ( myappname , mydevkey , username , password ) ; m_LoggedInRequest = new YouTubeRequest ( m_LoggedInSettings ) ; Comment userComment = new Comment ( ) ; userComment.Content = commentText ; m_LoggedInRequest.AddComment ( youtubevideo , userComment ) ;",Adding comments with the Youtube API randomly failing in .NET "C_sharp : I have a base class for data access classes . This class implements IDisposable . This base class contains the IDbConnection and instantiates it in the constructor.Classes that inherit from this class actually access the database : Classes that use FooDAL use the using pattern to ensure that Dispose gets called on the FooDAL with code like this : My question is , does this also ensure that the IDbCommand is disposed of properly even though it 's not wrapped in a using pattern or try-finally ? What happens if an exception occurs during the execution of the command ? Also , would it be better to instantiate the connection in CreateFoo instead of in the constructor of the base class for performance reasons ? Any help is appreciated . public class DALBase : IDisposable { protected IDbConnection cn ; public DALBase ( ) { cn = new MySqlConnection ( connString ) ; } public void Dispose ( ) { if ( cn ! = null ) { if ( cn.State ! = ConnectionState.Closed ) { try { cn.Close ( ) ; } catch { } } cn.Dispose ( ) ; } } } public class FooDAL : DALBase { public int CreateFoo ( ) { // Notice that the cmd here is not wrapped in a using or try-finally . IDbCommand cmd = CreateCommand ( `` create foo with sql '' , cn ) ; Open ( ) ; int ident = int.Parse ( cmd.ExecuteScalar ( ) .ToString ( ) ) ; Close ( ) ; cmd.Dispose ( ) ; return ident ; } } using ( FooDAL dal = new FooDAL ( ) ) { return dal.CreateFoo ( ) ; }",Does IDbCommand get disposed from within a class that implements IDisposable ? "C_sharp : I want to import a FORTRAN DLL into visual C # . While I have done that with functions , the problem arises when I want to import a subroutine with multiple outputs . Here is a simple example : FORTRAN DLL : C # Console App : Here are the answers that I get : x=0 , y=0 , MySub ( a , b , x , y ) =17I 'm a bit new in Visual C # programming , but I think above results mean that the two statements i.e . ' a+b ' and ' 2*a+3*b ' have been calculated but not assigned to x and y , and the latter ( 2*a+3*b ) has been assigned to the function MySub itself ! I have used OutAttributes in C # , also Intent [ In ] , Intent [ Out ] in FORTRAN , but none have changed the results . I would appreciate any help or advice . Subroutine MySub ( a , b , x , y ) ! DEC $ ATTRIBUTES DLLEXPORT , STDCALL , ALIAS : 'MySub ' : : MySubImplicit NoneInteger , INTENT ( IN ) : : a , bInteger , INTENT ( OUT ) : : x , y y=a+b x=2*a+3*bEnd Subroutine MySub using System ; using System.Runtime.InteropServices ; namespace AlReTest { class Program { [ DllImport ( @ '' D : \ ... \AltRetTest.dll '' , CallingConvention=CallingConvention.StdCall ) ] public static extern int MySub ( int a , int b , [ Out ] int x , [ Out ] int y ) ; static void Main ( string [ ] args ) { int a = 4 ; int b = 3 ; int x = 0 ; int y = 0 ; MySub ( a , b , x , y ) ; Console.WriteLine ( x ) ; Console.WriteLine ( y ) ; Console.WriteLine ( MySub ( a , b , x , y ) ) ; } } }",Calling a FORTRAN subroutine from C # "C_sharp : I am trying to convert an object to a generic type . Here is an example method : This gives this error : Can not implicitly convert type 'object ' to 'T ' . An explicit conversion exists ( are you missing a cast ? ) I have tried several variations to get my result cast as the generic type , but it is not working out each time.Is there a way to make this cast ? NOTE : In my real example I am getting an `` object '' back from a stored procedure . The method could call one of several stored procedures , so the result could be a string or a int ( or long ) depending on which sproc is called . void Main ( ) { object something = 4 ; Console.WriteLine ( SomeMethod < int > ( something ) ) ; Console.WriteLine ( SomeMethod < string > ( something ) ) ; } public T SomeMethod < T > ( object someRandomThing ) { T result = Convert.ChangeType ( someRandomThing , typeof ( T ) ) ; return result ; }",Generic Type Conversions "C_sharp : I 'm using this : To get user timezone . This works fine . I want to convert this : To .net timezone ? In .net Timezone that timezone does not exists . I tried to get proper timezone with : Any idea how to convert google timezone to .net timezone ? Is that possible ? Thank you guys in advance ! string url = string.Format ( `` https : //maps.googleapis.com/maps/api/timezone/json ? location= { 0 } , { 1 } & timestamp=1374868635 & sensor=false '' , lat , lon ) ; using ( HttpClient cl = new HttpClient ( ) ) { string json = await cl.GetStringAsync ( url ) .ConfigureAwait ( false ) ; TimeZoneModel timezone = new JavaScriptSerializer ( ) .Deserialize < TimeZoneModel > ( json ) ; } `` timeZoneName '' : `` Central European Summer Time '' TimeZoneInfo tzf = TimeZoneInfo.FindSystemTimeZoneById ( `` Central European Summer Time '' ) ;",Converting google time zone to .net timezone "C_sharp : I 'm trying to create a class that accepts a constructor similar to that of a dictionary , list , or array where you can create the object with a literal collection of objects , though I have been unable to find how to create such a constructor , if it 's even possible . MyClass obj = new MyClass ( ) { { value1 , value2 } , { value3 , value4 } }","How do you create an array-like C # constructor that will allow `` new MyClass ( ) { obj1 , obj2 , obj3 } ; ''" "C_sharp : I have class BookDTO which represents object which will be used in exchanging data between client and service where service is wcf service have following attributesIs this proper ( standard ) way of decorating object which will be send over the wire ? I 've seen examples with Is [ KnownType ( typeof ( Book ) ) ] redudant here ? I 've forget to mention that I 'm introduced with DataMember attributes , so please disregard that . [ Serializable ] [ DataContract ] [ KnownType ( typeof ( Book ) ) ] public class BookDTO { ... } [ DataContract ( NameSpace= '' somenamespace.DTO.Book '' ) ]",Proper way of decorating dto class in wcf communication "C_sharp : I have got this enumAnd there is UI with 3 checkboxes so depending which of them are checked I have to generate possible cases to do some job.But I am not sure that this code is a correct ... Are there other ways to do it ? enum NetopScriptGeneratingCases { AddLogMessages , AddLogErrors , AddLogJournal , AllLog = AddLogMessages | AddLogErrors | AddLogJournal , DoNothing } NetopScriptGeneratingCases netopScriptGeneratingCases = NetopScriptGeneratingCases.DoNothing ; if ( checkBoxAddAuditLog.Checked ) { netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogJournal ; } else if ( checkBoxAddErrorLog.Checked ) { netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogErrors ; } else if ( checkBoxAddLogMessages.Checked ) { netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogMessages ; } else if ( checkBoxAddAuditLog.Checked || checkBoxAddErrorLog.Checked ) { netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogJournal | NetopScriptGeneratingCases.AddLogErrors ; } else if ( checkBoxAddAuditLog.Checked || checkBoxAddLogMessages.Checked ) { netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogJournal | NetopScriptGeneratingCases.AddLogMessages ; } else if ( checkBoxAddErrorLog.Checked || checkBoxAddLogMessages.Checked ) { netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogErrors | NetopScriptGeneratingCases.AddLogMessages ; } else if ( checkBoxAddErrorLog.Checked || checkBoxAddLogMessages.Checked || checkBoxAddAuditLog.Checked ) { netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogErrors | NetopScriptGeneratingCases.AddLogMessages | NetopScriptGeneratingCases.AddLogJournal ; } var modifiedFiles = NetopScriptGenerator.GenerateNetopScript ( netopScriptGeneratingCases , netopFiles ) ;",How to optimize enum assignment in C # "C_sharp : I am currently performing an ajax call to my controller with the following code : This is the controller : It gets to the controller and the AddNewProduct function runs successfully . The problem is that i want it to return the image name that is created within the controller . This works as well but with that it also return my complete html page.I alert something on success and when an error occurs but somehow it always ends up in the error with the following alert : it shows the value I need but why does it return my complete HTML as well ? $ .ajax ( { type : `` POST '' , url : `` @ Url.Action ( `` uploadImage '' , `` Item '' ) '' , data : ' { `` imageData '' : `` ' + image + ' '' } ' , contentType : `` application/json ; charset=utf-8 '' , dataType : `` json '' , success : function ( success ) { alert ( 'Success ' + success.responseText ) ; } , error : function ( response ) { alert ( response.responseText ) ; } } ) ; [ HttpPost ] public ActionResult uploadImage ( string imageData ) { string imageName = Guid.NewGuid ( ) .ToString ( ) ; try { ProductManager pm = new ProductManager ( ) ; pm.AddNewProduct ( imageName ) ; } catch ( Exception e ) { writeToLog ( e ) ; } return Json ( new { success = imageName } , JsonRequestBehavior.AllowGet ) ; }",ajax call returns values and my html page "C_sharp : Microsoft says fields and properties must differ by more than just case . So , if they truly represent the same idea how should they be different ? Here 's Microsoft 's example of what not to do : They give no guidance on how this should look . What do most developers do ? using System ; namespace NamingLibrary { public class Foo // IdentifiersShouldDifferByMoreThanCase { protected string bar ; public string Bar { get { return bar ; } } } }",How to best name fields and properties "C_sharp : When dealing with custom exceptions , I usually inherit from Exception and then add some fields/properties to my exception class to store some additional info : In the above example , the ErrorCode value is stored in the exception , meaning that I have to add it to and retireve if from the SerializationInfo object in the protected constructor and the overridden GetObjectData method.The Exception class has a Data property , which according to MSDN : Gets a collection of key/value pairs that provide additional user-defined information about the exception.If I store the error code inside the Data , it will get serialised for me by the Exception class ( according to Reflector ) , meaning that my exception class now looks like : This means that whilst there is a bit more work to do in dealing with the get/set of the error code ( like dealing with casting errors and situations where the error code might not be in the dictionary ) , I do n't have to worry about serialising/deserialising it.Is this just two different ways of achieving the same thing , or does one way have any clear advantage ( s ) over the other ( apart from those I 've already mentioned ) ? public class MyException : Exception { public int ErrorCode { get ; set ; } public MyException ( ) { } } public class MyException : Exception { public int ErrorCode { get { return ( int ) Data [ `` ErrorCode '' ] ; } set { Data [ `` ErrorCode '' ] = value ; } } public MyException ( ) { } }",How should I store data inside custom exceptions ? "C_sharp : I 'm trying to pull a large-ish dataset ( 1.4 million records ) from a SQL Server and dump to a file in a WinForms application . I 've attempted to do it with paging , so that I 'm not holding too much in memory at once , but the process continues to grow it 's memory footprint as it runs . About 25 % through , it was taking up 600,000K . Am I doing the paging wrong ? Can I get some suggestions on how to keep the memory usage from growing so much ? var query = ( from organizations in ctxObj.Organizations where organizations.org_type_cd == 1 orderby organizations.org_ID select organizations ) ; int recordCount = query.Count ( ) ; int skipTo = 0 ; int take = 1000 ; if ( recordCount > 0 ) { while ( skipTo < recordCount ) { if ( skipTo + take > recordCount ) take = recordCount - skipTo ; foreach ( Organization o in query.Skip ( skipTo ) .Take ( take ) ) { writeRecord ( o ) ; } skipTo += take ; } }",How do I reduce the memory footprint with large datasets in EF5 ? "C_sharp : Is there a way to control the type conversion in C # ? So for example , if I have two types with essentially the same details , but one is used for the internal working of my application and the other is a DTO used for communicating with non-.Net applications : Right now , I need to create a new instance of PlayerDTO from my Player instance every time and I 'm looking for a better , cleaner way of doing this.One idea I had was to add an AsPlayerDTO ( ) method to the player class , but would be nice if I can control the type conversion process so I can do this instead : Anyone know if this is possible and how I might be able to do it ? Thanks , public sealed class Player { public Player ( string name , long score ) { Name = name ; Score = score ; ID = Guid.NewGuid ( ) ; } public string Name { get ; private set ; } public Guid ID { get ; private set ; } public long Score { get ; private set ; } } public sealed class PlayerDTO { public PlayerDTO ( string name , long score , string id ) { Name = name ; Score = score ; ID = id ; } public string Name { get ; private set ; } // the client is not .Net and does n't have Guid public string ID { get ; private set ; } public long Score { get ; private set ; } } var playerDto = player as PlayerDTO ;",How to control Type conversion in C # C_sharp : Interface definitionBut in my code the BaseType of my interface is null . I can not make any sense of this ! public interface IPayeePayrollRunInitialPayElementData : IPayeePayrollRunPayElementData,Why is my interface 's BaseType null ? "C_sharp : I read the following blog post regarding the new xaml editing features available in VS2013 : http : //blogs.msdn.com/b/visualstudio/archive/2013/08/09/xaml-editor-improvements-in-visual-studio-2013.aspxData binding Intellisense is something I 've been wanting for ages , so I gave it a try - but unfortunately it 's returning an error in the error list ( though it still builds fine ) .This is what I 've added to my UserControl declaration / tag : This is the error in the list : Error 95 Access is denied : System.Collections.ObjectModel.ObservableCollection ' 1 [ _.di1.TemplateEditorCustomVM+TemplateCriteriaVM ] '.I 'm not entirely sure what it 's attempting to do , both classes are declared as public ( main view model and a nested class ) .Anyone got any ideas ? If not it 's not the end of the world , as Resource Key Intellisense appears to work which is still a huge bonus.EditOK - I moved the nested classes out into the public namespace , and VS has given me a more detailed error : Error 64 Attempt by method ' _.di1.Templates.TemplateEditorCustomVM..ctor ( ) ' to access method 'System.ComponentModel.BindingList ' 1 < System.__Canon > ..ctor ( ) ' failed.I 'm a little confused I must say : Firstly , why would intellisense need to instantiate the VM class , all it should care about is what properties are available and what type they are - all of which can be retrieved with reflection . Secondly I do n't understand why its erroring when it runs fine when the application is started.I may have to do the old trick of having visual studio debug itself running the designer to see what it 's attempting to do ... further editRight , I changed the BindingList properties to straight forward List properties ( as the BindingList is from the WinForms side of things so I thought this might be worth changing to see what it does ) . But I got a similar error : Error 64 Attempt by method ' _.di3.Templates.TemplateEditorCustomVM..ctor ( ) ' to access method 'System.Collections.Generic.List ' 1 < System.__Canon > ..ctor ( ) ' failed.I did a quick google on System.__Canon and its just a optimization detail : https : //stackoverflow.com/a/16856205/182568Though still no closer to sussing out whats going on , ah well I 'll keep digging further.edit - now have a repoRight , I began commenting out huge chunks of the VM to try to get to the bottom of this out of curiosity - and I now have a VM class which appears to reproduce the issue : Gives : Error 14 Attempt by method ' _.di14.Templates.SanityTestVM..ctor ( ) ' to access method 'System.Collections.Generic.List ' 1 < System.__Canon > ..ctor ( ) ' failed.It appears the issue is having a List which has a nested class for its type - if its a normal class ( non nested ) , everything is fine.I think I 'm going to need to submit a connect case for this - before I do is anyone able to confirm this , I have 4 versions of VS on a Windows 8.1 machine and I just want to rule the development environment out . d : DataContext= '' { d : DesignInstance Type=lTemplates : TemplateEditorCustomVM } '' public class Nested { public class TestCheck { public int One { get ; set ; } public int Two { get ; set ; } } } public class SanityTestVM { public List < Nested.TestCheck > Test { get ; set ; } }",xaml d : DataContext giving `` Access is denied '' error C_sharp : Inspired from a -5 question again ! Is empty case of switch in C # combined with the next non-empty one ? I read [ this comment ] of @ Quartermeister and been astonished ! So why this compilesbut this does n't . neither thisupdate : The -5 question became -3 . switch ( 1 ) { case 2 : } int i ; switch ( i=1 ) { case 2 : // Control can not fall through from one case label ( 'case 2 : ' ) to another } switch ( 2 ) { case 2 : // Control can not fall through from one case label ( 'case 2 : ' ) to another },What 's compiler thinking about the switch-statement ? "C_sharp : I 'm trying to improve the performance of a complex database read operation . I 've found some code that , in limited testing , performs much faster than previous attempts using a variety of techniques , including a hand-tuned stored procedure . It 's using Dapper , but Dapper is n't the primary source of concern.This is somewhat simplified , but I hope it highlights my primary issue : Is this code a good idea ? I know that it 's possible to make it safer by reusing the same connection , but creating many connections makes it faster by an order of magnitude in my testing . I 've also tested/counted the number of concurrent connections from the database itself , and I 'm seeing hundreds of statements running at the same time.Some related questions : Should I use more async ( ex : CreateConnection ( ) , GetAllOrders ) , orless ? What kind of testing can/should I do before I put this kind ofcode in production ? Are there alternative strategies that can producesimilar performance but require fewer connections ? public IEnumerable < Order > GetOpenOrders ( Guid vendorId ) { var tasks = GetAllOrders ( vendorId ) .Where ( order = > ! order.IsCancelled ) .Select ( async order = > await GetLineItems ( order ) ) .Select ( async order = > { var result = ( await order ) ; return result.GetBalance ( ) > 0M ? result : null ; } ) .Select ( async order = > await PopulateName ( await order ) ) .Select ( async order = > await PopulateAddress ( await order ) ) .ToList ( ) ; Task.WaitAll ( tasks.ToArray < Task > ( ) ) ; return tasks.Select ( t = > t.Result ) ; } private IDbConnection CreateConnection ( ) { return new SqlConnection ( `` ... '' ) ; } private IEnumerable < Order > GetAllOrders ( Guid vendorId ) { using ( var db = CreateConnection ( ) ) { return db.Query < Order > ( `` ... '' ) ; } } private async Task < Order > GetLineItems ( Order order ) { using ( var db = CreateConnection ( ) ) { var lineItems = await db.QueryAsync < LineItem > ( `` ... '' ) ; order.LineItems = await Task.WhenAll ( lineItems.Select ( async li = > await GetPayments ( li ) ) ) ; return order ; } } private async Task < LineItem > GetPayments ( LineItem lineItem ) { using ( var db = CreateConnection ( ) ) { lineItem.Payments = await db.QueryAsync < Payment > ( `` ... '' ) ; return lineItem ; } } private async Task < Order > PopulateName ( Order order ) { using ( var db = CreateConnection ( ) ) { order.Name = ( await db.QueryAsync < string > ( `` ... '' ) ) .FirstOrDefault ( ) ; return order ; } } private async Task < Order > PopulateAddress ( Order order ) { using ( var db = CreateConnection ( ) ) { order.Address = ( await db.QueryAsync < string > ( `` ... '' ) ) .FirstOrDefault ( ) ; return order ; } }",Can I create many DBConnections asynchronously ? "C_sharp : TryValidateObject does not seem to work on with the Compare model validation attribute when unit testing.I get ModelState.IsValid = true , when I know it is false ( when unit testing ) .I 've got this example model : Using this helper method to validate models when unit testing : And I run this unit test : public class CompareTestModel { public string Password { get ; set ; } [ System.Web.Mvc.Compare ( `` Password '' , ErrorMessage = `` The passwords do not match '' ) ] public string PasswordCompare { get ; set ; } } using System.Collections.Generic ; using System.ComponentModel.DataAnnotations ; using System.Web.Mvc ; public static class ModelHelper { public static void ValidateModel ( this Controller controller , object viewModel ) { controller.ModelState.Clear ( ) ; var validationContext = new ValidationContext ( viewModel , null , null ) ; var validationResults = new List < ValidationResult > ( ) ; Validator.TryValidateObject ( viewModel , validationContext , validationResults , true ) ; foreach ( var result in validationResults ) { foreach ( var name in result.MemberNames ) { controller.ModelState.AddModelError ( name , result.ErrorMessage ) ; } } } } [ Test ] public void CompareAttributeTest ( ) { // arrange var model = new CompareTestModel ( ) ; model.Password = `` password '' ; model.PasswordCompare = `` different password '' ; AccountController controller = new AccountController ( ) ; // act controller.ValidateModel ( model ) ; // assert Assert.IsFalse ( controller.ModelState.IsValid ) ; }",Unit testing Mvc.Compare Attribute incorrectly returns model isValid = true "C_sharp : I 'm using the CSharpCodeProvider class to compile a C # script which I use as a DSL in my application . When there are warnings but no errors , the Errors property of the resulting CompilerResults instance contains no items . But when I introduce an error , the warnings suddenly get listed in the Errors property as well.So how to I get hold of the warnings when there are no errors ? By the way , I do n't want to set TreatWarningsAsErrors to true . string script = @ '' using System ; using System ; // generate a warning namespace MyNamespace { public class MyClass { public void MyMethod ( ) { // uncomment the next statement to generate an error //intx = 0 ; } } } '' ; CSharpCodeProvider provider = new CSharpCodeProvider ( new Dictionary < string , string > ( ) { { `` CompilerVersion '' , `` v4.0 '' } } ) ; CompilerParameters compilerParameters = new CompilerParameters ( ) ; compilerParameters.GenerateExecutable = false ; compilerParameters.GenerateInMemory = true ; CompilerResults results = provider.CompileAssemblyFromSource ( compilerParameters , script ) ; foreach ( CompilerError error in results.Errors ) { Console.Write ( error.IsWarning ? `` Warning : `` : `` Error : `` ) ; Console.WriteLine ( error.ErrorText ) ; }",CSharpCodeProvider does n't return compiler warnings when there are no errors "C_sharp : When my program tries to access the dll in the network drive , I got this error message.Following the link , I got this info I need to have this configuration.How do I put this configuration info to what ? I use Visual Studio 2010 , but I do n't use Visual Studio IDE , but just have one simple batch file to build the C # code.ADDEDI found this site using App.config , and I think it may not be possible to use method with command line build . Unhandled Exception : System.IO.FileLoadException : Could not load file or assembly 'file : ///Z : \smcho\works\tasks\2011\ni\ng_fpgabackend\myclass.dll ' or one of its dependencies . Operation is not supported . ( Exception from HRESULT : 0x80131515 ) -- - > System.NotSupportedException : An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework . This release of the .NET Framework does not enable CAS policy by default , so this load maybe dangerous . If this load is not intended to sandbox the assembly , please enable the loadFromRemoteSources switch.See http : //go.microsoft.com/fwlink/ ? LinkId=155569 for more information . < configuration > < runtime > < loadFromRemoteSources enabled= '' true '' / > < /runtime > < /configuration >",How do I setup configuration when I use command line to build C # /.NET ? "C_sharp : I 've got an ASP.NET Core MVC app , hosted on Azure websites , where I 've implemented Session and Identity . My problem is , after 30 minutes , I get logged out . It does n't matter if I 've been active in the last 30 minutes or not.Doing some searching , I found that the issue is the SecurityStamp stuff , found here . I 've tried implementing this by doing the following : Here 's my UserManager impelmentation with the security stamp stuff : Here 's my ConfigureServices method on Startup.cs : And lastly , here 's my Configure method on Startup.cs : What 's wrong with my implementation here ? UPDATE : What a second ... I noticed my UserManager is not inheriting from any interfaces for the security stamp stuff , is that what 's needed ? public class UserManager : UserManager < Login > { public UserManager ( IUserStore < Login > store , IOptions < IdentityOptions > optionsAccessor , IPasswordHasher < Login > passwordHasher , IEnumerable < IUserValidator < Login > > userValidators , IEnumerable < IPasswordValidator < Login > > passwordValidators , ILookupNormalizer keyNormalizer , IdentityErrorDescriber errors , IServiceProvider services , ILogger < UserManager < Login > > logger ) : base ( store , optionsAccessor , passwordHasher , userValidators , passwordValidators , keyNormalizer , errors , services , logger ) { // noop } public override bool SupportsUserSecurityStamp = > true ; public override async Task < string > GetSecurityStampAsync ( Login login ) { return await Task.FromResult ( `` MyToken '' ) ; } public override async Task < IdentityResult > UpdateSecurityStampAsync ( Login login ) { return await Task.FromResult ( IdentityResult.Success ) ; } } public void ConfigureServices ( IServiceCollection services ) { // Add framework services . services.AddApplicationInsightsTelemetry ( Configuration ) ; services.AddSingleton ( _ = > Configuration ) ; services.AddSingleton < IUserStore < Login > , UserStore > ( ) ; services.AddSingleton < IRoleStore < Role > , RoleStore > ( ) ; services.AddIdentity < Login , Role > ( o = > { o.Password.RequireDigit = false ; o.Password.RequireLowercase = false ; o.Password.RequireUppercase = false ; o.Password.RequiredLength = 6 ; o.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays ( 365 ) ; o.Cookies.ApplicationCookie.SlidingExpiration = true ; o.Cookies.ApplicationCookie.AutomaticAuthenticate = true ; } ) .AddUserStore < UserStore > ( ) .AddUserManager < UserManager > ( ) .AddRoleStore < RoleStore > ( ) .AddRoleManager < RoleManager > ( ) .AddDefaultTokenProviders ( ) ; services.AddScoped < SignInManager < Login > , SignInManager < Login > > ( ) ; services.AddScoped < UserManager < Login > , UserManager < Login > > ( ) ; services.Configure < AuthorizationOptions > ( options = > { options.AddPolicy ( `` Admin '' , policy = > policy.Requirements.Add ( new AdminRoleRequirement ( new RoleRepo ( Configuration ) ) ) ) ; options.AddPolicy ( `` SuperUser '' , policy = > policy.Requirements.Add ( new SuperUserRoleRequirement ( new RoleRepo ( Configuration ) ) ) ) ; options.AddPolicy ( `` DataIntegrity '' , policy = > policy.Requirements.Add ( new DataIntegrityRoleRequirement ( new RoleRepo ( Configuration ) ) ) ) ; } ) ; services.Configure < FormOptions > ( x = > x.ValueCountLimit = 4096 ) ; services.AddScoped < IPasswordHasher < Login > , PasswordHasher > ( ) ; services.AddDistributedMemoryCache ( ) ; services.AddSession ( ) ; services.AddMvc ( ) ; // repos InjectRepos ( services ) ; // services InjectServices ( services ) ; } public void Configure ( IApplicationBuilder app , IHostingEnvironment env , ILoggerFactory loggerFactory ) { loggerFactory.AddConsole ( Configuration.GetSection ( `` Logging '' ) ) ; loggerFactory.AddDebug ( ) ; app.UseApplicationInsightsRequestTelemetry ( ) ; if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; app.UseDatabaseErrorPage ( ) ; app.UseBrowserLink ( ) ; } else { app.UseExceptionHandler ( `` /home/error '' ) ; } app.UseStatusCodePages ( ) ; app.UseStaticFiles ( ) ; app.UseSession ( ) ; app.UseIdentity ( ) ; app.UseMiddleware ( typeof ( ErrorHandlingMiddleware ) ) ; app.UseMiddleware ( typeof ( RequestLogMiddleware ) ) ; app.UseMvc ( routes = > { routes.MapRoute ( name : `` default '' , template : `` { controller=Home } / { action=Index } / { id ? } '' ) ; } ) ; }",ASP.NET Core website timing out after 30 minutes "C_sharp : I built a simple Razor Pages website in order to show some views on a couple of database tables.In the index.cshtml.cs I just have : In the Registrations/index.cshtml.cs I have : Testing the website from Visual Studio is fine , and running from the project directory with dotnet run is also fine.So I deployed the website with : dotnet publish -o ../Published/ -c releasethen run it with dotnet MyWebsite.dll from the publish directory.When I connect to http : //localhost:5000 , I get a general error.Looking at the console this is the exception thrown : I ca n't understand what 's wrong with deployed version . public class IndexModel : PageModel { public IActionResult OnGet ( ) { return RedirectToPage ( `` ./Registrations/Index '' ) ; } } public class IndexModel : PageModel { int pageSize = 30 ; private readonly RegistrationAdmin.PostgresDbContext _context ; public IndexModel ( RegistrationAdmin.PostgresDbContext context ) { _context = context ; } public PaginatedList < Registration > Registration { get ; set ; } public async Task OnGetAsync ( int pageIndex = 1 ) { IQueryable < Registration > registrations = _context.Registrations .Include ( r = > r.ContactPerson ) .Include ( r = > r.Badge ) .OrderByDescending ( r = > r.RegistrationId ) ; this.Registration = await PaginatedList < Registration > . CreateAsync ( registrations.AsNoTracking ( ) , pageIndex , pageSize ) ; } } Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware [ 1 ] An unhandled exception has occurred while executing the request.System.InvalidOperationException : No page named './Registrations/Index ' matches the supplied values . at Microsoft.AspNetCore.Mvc.Infrastructure.RedirectToPageResultExecutor.ExecuteAsync ( ActionContext context , RedirectToPageResult result ) at Microsoft.AspNetCore.Mvc.RedirectToPageResult.ExecuteResultAsync ( ActionContext context ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync ( IActionResult result ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync [ TFilter , TFilterAsync ] ( ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow ( ResultExecutedContext context ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext [ TFilter , TFilterAsync ] ( State & next , Scope & scope , Object & state , Boolean & isCompleted ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters ( ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter ( ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow ( ResourceExecutedContext context ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next ( State & next , Scope & scope , Object & state , Boolean & isCompleted ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync ( ) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync ( ) at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke ( HttpContext httpContext ) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke ( HttpContext context ) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke ( HttpContext context )",Can not deploy Razor Pages website "C_sharp : I am trying to update a textbox using the code behind in an ASP application like this : The textbox shows one variable the first time but it does n't get updated after that , what am I doing wrong ? I searched and people are suggestin calling Textbox.Update or Textbox.Refresh but I think these are old as they do n't exist anymore . Thanks protected void click_handler ( object sender , EventArgs e ) { Thread worker = new Thread ( new ThreadStart ( thread_function ) ) ; worker.Start ( ) ; } protected void thread_function ( ) { int i = 0 ; while ( true ) { Textbox.Text = i.ToString ( ) ; i++ ; } }",How update textbox in a loop running on another thread in C # "C_sharp : I have a ListView with some ListViewItems ( only text ) .The following image is an example : The problem is that when I select one of these items the text is truncated , like in the following image : Why ? How can I solve this problem ? listView1 = new ListView { View = System.Windows.Forms.View.Details , HeaderStyle = ColumnHeaderStyle.None } ; listView1.Columns.Add ( String.Empty , -2 , HorizontalAlignment.Left ) ;",ListViewItem text truncated after selection - Compact Framework "C_sharp : When I run the code below the output is `` DelegateDisplayIt '' , typically repeated 1-4 times . I 've run this code probably 100 times , and not once has the output ever been `` ParameterizedDisplayIt '' . So it seems the manner in which the thread is created and subsequently started affects how the parameter is passed . When creating a new thread with an anonymous delegate the parameter is a reference back to the original variable , but when created with a ParameterizedThreadStart delegate the parameter is an entirely new object ? Does my assumption seem correct ? If so , this seems an odd side affect of the thread constructor , no ? static void Main ( ) { for ( int i = 0 ; i < 10 ; i++ ) { bool flag = false ; new Thread ( delegate ( ) { DelegateDisplayIt ( flag ) ; } ) .Start ( ) ; var parameterizedThread = new Thread ( ParameterizedDisplayIt ) ; parameterizedThread.Start ( flag ) ; flag = true ; } Console.ReadKey ( ) ; } private static void DelegateDisplayIt ( object flag ) { if ( ( bool ) flag ) Console.WriteLine ( `` DelegateDisplayIt '' ) ; } private static void ParameterizedDisplayIt ( object flag ) { if ( ( bool ) flag ) Console.WriteLine ( `` ParameterizedDisplayIt '' ) ; }",Differing behavior when starting a thread : ParameterizedThreadStart vs . Anonymous Delegate . Why does it matter ? "C_sharp : I have the following testThe problem is that the call to DealDamage from the Attack method is n't being registered , because inside the method , this is realAttacker not wrappedAttacker attacker hence the method call is n't being intercepted.How can I test this assertion ? Can this be done with FakeItEasy ? Does a different mocking framework allow me to test this ? [ Test ] public void Attack_TargetWith3Damage_CausesAttackerToDeal3DamageToTarget ( ) { var realAttacker = CreateCreature ( damage : 3 ) ; var wrappedAttacker = A.Fake < ICreature > ( x = > x.Wrapping ( realAttacker ) ) ; var target = A.Fake < ICreature > ( ) ; wrappedAttacker.Attack ( target ) ; A.CallTo ( ( ) = > wrappedAttacker.DealDamage ( target , 3 ) ) .MustHaveHappened ( ) ; }",Asserting a call to a public method on the same mock instance "C_sharp : The querytranslates toIs there a LINQ syntax that would translate to the following ? var q = from elem in collection where someCondition ( elem ) select elem ; var q = collection.Where ( elem = > someCondition ( elem ) ) ; var q = collection.Where ( ( elem , index ) = > someCondition ( elem , index ) ) ;","Is there a LINQ syntax for the ( T , int ) overloads of Where and Select ?" "C_sharp : Apologies for the amount of code , but it is easier to explain it this way.I have a custom attribute CustomUserData implemented as follows : and an extension method for enums as : I then have a helper class that serializes/deserializes an enum that has custom data associated with it as follows : however this is specific to ParameterDisplayModeEnum and I have a bunch of enums that I need to treat this way for serialization/deserialization so I would prefer to have a generic such as : However this will not work as GetCustomUserData ( ) can not be invoked . Any suggestions ? I can not change the use of the custom attribute or the use of the enums . I am looking for a generic way to do the serialization/deserialization without having to write a concrete list helper class each time.All suggestions appreciated . public class CustomUserData : Attribute { public CustomUserData ( object aUserData ) { UserData = aUserData ; } public object UserData { get ; set ; } } public static class EnumExtensions { public static TAttribute GetAttribute < TAttribute > ( this Enum aValue ) where TAttribute : Attribute { Type type = aValue.GetType ( ) ; string name = Enum.GetName ( type , aValue ) ; return type.GetField ( name ) .GetCustomAttributes ( false ) .OfType < TAttribute > ( ) .SingleOrDefault ( ) ; } public static object GetCustomUserData ( this Enum aValue ) { CustomUserData userValue = GetAttribute < CustomUserData > ( aValue ) ; return userValue ! = null ? userValue.UserData : null ; } } public static class ParameterDisplayModeEnumListHelper { public static List < ParameterDisplayModeEnum > FromDatabase ( string aDisplayModeString ) { //Default behaviour List < ParameterDisplayModeEnum > result = new List < ParameterDisplayModeEnum > ( ) ; //Split the string list into a list of strings List < string > listOfDisplayModes = new List < string > ( aDisplayModeString.Split ( ' , ' ) ) ; //Iterate the enum looking for matches in the list foreach ( ParameterDisplayModeEnum displayModeEnum in Enum.GetValues ( typeof ( ParameterDisplayModeEnum ) ) ) { if ( listOfDisplayModes.FindIndex ( item = > item == ( string ) displayModeEnum.GetCustomUserData ( ) ) > = 0 ) { result.Add ( displayModeEnum ) ; } } return result ; } public static string ToDatabase ( List < ParameterDisplayModeEnum > aDisplayModeList ) { string result = string.Empty ; foreach ( ParameterDisplayModeEnum listItem in aDisplayModeList ) { if ( result ! = string.Empty ) result += `` , '' ; result += listItem.GetCustomUserData ( ) ; } return result ; } } public static class EnumListHelper < TEnum > { public static List < TEnum > FromDatabase ( string aDisplayModeString ) { //Default behaviour List < TEnum > result = new List < TEnum > ( ) ; //Split the string list into a list of strings List < string > listOfDisplayModes = new List < string > ( aDisplayModeString.Split ( ' , ' ) ) ; //Iterate the enum looking for matches in the list foreach ( TEnum displayModeEnum in Enum.GetValues ( typeof ( TEnum ) ) ) { if ( listOfDisplayModes.FindIndex ( item = > item == ( string ) displayModeEnum.GetCustomUserData ( ) ) > = 0 ) { result.Add ( displayModeEnum ) ; } } return result ; } public static string ToDatabase ( List < TEnum > aDisplayModeList ) { string result = string.Empty ; foreach ( TEnum listItem in aDisplayModeList ) { if ( result ! = string.Empty ) result += `` , '' ; result += listItem.GetCustomUserData ( ) ; } return result ; } }","Generics , enums and custom attributes - is it possible ?" "C_sharp : BackgroundThe following server side code is used to spin up a long-running task that will post updates to the web front end via SignalR . I 've placed a button on the front end that I then want to stop the task at the user 's request.IssueWhen front end trigger 's the Stop method , the tokenSource is null . I suspect , this is because it 's not reaching the same instance of the ChartHub that spawned the Task.Code using System ; ... using System.Security.Principal ; namespace dvvWeb.Hubs { public class ChartHub : Hub { CancellationTokenSource tokenSource ; CancellationToken ct ; public void Start ( string serverName , string dbName , string numberOfPoints , string pollingFrequency ) { ConfigModel config = new ConfigModel ( ) ; tokenSource = new CancellationTokenSource ( ) ; ct = tokenSource.Token ; config.Servername = HttpUtility.UrlDecode ( serverName ) ; config.DbName = HttpUtility.UrlDecode ( dbName ) ; config.Preferences.NumberOfPoints = int.Parse ( numberOfPoints ) ; config.Preferences.PollingFrequency = int.Parse ( pollingFrequency ) ; dvvGraphingModel graphingModel = new dvvGraphingModel ( ) ; dvvGraphingHelper graphingHelper = new dvvGraphingHelper ( graphingModel , config.Servername , config.DbName ) ; graphingModel = graphingHelper.Tick ( config.Preferences ) ; var identity = WindowsIdentity.GetCurrent ( ) ; Task.Run ( ( ) = > workItemAsync ( ct , graphingModel , graphingHelper , config , identity ) ) ; } public void Stop ( ) { tokenSource.Cancel ( ) ; } private async Task < CancellationToken > workItemAsync ( CancellationToken ct , dvvGraphingModel graphingModel , dvvGraphingHelper graphingHelper , ConfigModel configModel , WindowsIdentity identity ) { await addDataAsync ( ct , graphingModel , graphingHelper , configModel , identity ) ; return ct ; } private async Task < CancellationToken > addDataAsync ( CancellationToken ct , dvvGraphingModel graphingModel , dvvGraphingHelper graphingHelper , ConfigModel configModel , WindowsIdentity identity ) { try { while ( ! ct.IsCancellationRequested ) { identity.Impersonate ( ) ; Clients.Caller.addPointToChart ( JsonConvert.SerializeObject ( graphingModel ) ) ; System.Threading.Thread.Sleep ( configModel.Preferences.PollingFrequency * 1000 ) ; graphingModel = graphingHelper.Tick ( configModel.Preferences ) ; } } catch ( TaskCanceledException tce ) { Trace.TraceError ( `` Caught TaskCanceledException - signaled cancellation `` + tce.Message ) ; } return ct ; } } }",Cancelling a Task started by ASP.NET "C_sharp : What is wrong with capital ' I ' in some cultures ? I found that in some cultures in ca n't be found in special conditions - if you are looking for [ a-z ] with flag RegexOptions.IgnoreCase . Here is sample code : Output is ( notice missing capital I in every line ) : Interesting is that if flag `` IgnoreCase '' is not used then it works well , and finds `` I '' . var allCultures = CultureInfo.GetCultures ( CultureTypes.AllCultures ) ; var allLetters = `` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '' ; var allLettersCount = allLetters.Length ; foreach ( var culture in allCultures ) { Thread.CurrentThread.CurrentCulture = culture ; Thread.CurrentThread.CurrentUICulture = culture ; var matched = string.Empty ; foreach ( var m in Regex.Matches ( allLetters , `` [ A-Za-z0-9 ] '' , RegexOptions.IgnoreCase ) ) matched += m ; var count = matched.Length ; if ( count ! = allLettersCount ) Console.WriteLine ( `` Culture ' { 0 } ' - { 1 } missing ; Matched : { 2 } '' , culture.Name , ( allLettersCount - count ) .ToString ( ) , matched ) ; } Culture 'az ' - 1 missing ; Matched : ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789Culture 'az-Cyrl ' - 1 missing ; Matched : ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789Culture 'az-Cyrl-AZ ' - 1 missing ; Matched : ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789Culture 'az-Latn ' - 1 missing ; Matched : ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789Culture 'az-Latn-AZ ' - 1 missing ; Matched : ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789Culture 'tr ' - 1 missing ; Matched : ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789Culture 'tr-TR ' - 1 missing ; Matched : ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",Regex and Capital I in some cultures "C_sharp : Is it possible to only print the columns in a row in a DataGridView that have values and exclude the non empty ones ? I 'm trying to print the ones and only the ones that have actual values stored in it , but right now it is printing all of them . Here is a screenshot of the actual print document ( saved as a pdf ) : http : //imgur.com/HiF9heqI would like to eliminate the rest of the columns that are empty.Here is the code I have in place to print and the code that fills the data table : and the menu strip item that fills the DataGridView : I think that if only the non-empty values were printed it would format the printed document correctly ( see screenshot ) . Any help would be greatly appreciated.Thanks ! Update - I got it so where the empty cells are not shown ( http : //imgur.com/R0ueyft ) but I guess my other question is how to not have the column headers shown as well if the cells are empty . I updated my code to reflect the changes I made . private void Printdoc_PrintPage ( object sender , System.Drawing.Printing.PrintPageEventArgs e ) { try { qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells ; // set the left margin of the document to be printed int leftMargin = e.MarginBounds.Left ; // set the top margin of the document to be printed int topMargin = e.MarginBounds.Top ; // variable to determine if more pages are to be printed bool printMore = false ; // temp width int tmpWidth = 0 ; // for the first page to print , set the cell width and header height if ( firstPage ) { foreach ( DataGridViewColumn gridCol in qbcDataGridView.Columns ) { tmpWidth = ( int ) ( Math.Floor ( ( double ) gridCol.Width / totalWidth * totalWidth * ( ( double ) e.MarginBounds.Width / totalWidth ) ) ) ; headerHeight = ( int ) ( e.Graphics.MeasureString ( gridCol.HeaderText , gridCol.InheritedStyle.Font , tmpWidth ) .Height ) + 2 ; // save the width and height of the headers arrayLeftColumns.Add ( leftMargin ) ; arrayColWidths.Add ( tmpWidth ) ; leftMargin += tmpWidth ; } } // loop until all of the grid rows get printed while ( row < = qbcDataGridView.Rows.Count - 1 ) { DataGridViewRow gridRow = qbcDataGridView.Rows [ row ] ; // set the cell height cellHeight = gridRow.Height + 5 ; int count = 0 ; // check to see if the current page settings allow more rows to print if ( topMargin + cellHeight > = e.MarginBounds.Height + e.MarginBounds.Top ) { newPage = true ; firstPage = false ; printMore = true ; break ; } else { if ( newPage ) { // draw the header e.Graphics.DrawString ( `` QBC Directory '' , new Font ( qbcDataGridView.Font , FontStyle.Bold ) , Brushes.Black , e.MarginBounds.Left , e.MarginBounds.Top - e.Graphics.MeasureString ( `` QBC Directory '' , new Font ( qbcDataGridView.Font , FontStyle.Bold ) , e.MarginBounds.Width ) .Height - 13 ) ; // set the data ( now ) and the current time String date = DateTime.Now.ToLongDateString ( ) + `` `` + DateTime.Now.ToShortTimeString ( ) ; // draw the date on the print document e.Graphics.DrawString ( date , new Font ( qbcDataGridView.Font , FontStyle.Bold ) , Brushes.Black , e.MarginBounds.Left + ( e.MarginBounds.Width - e.Graphics.MeasureString ( date , new Font ( qbcDataGridView.Font , FontStyle.Bold ) , e.MarginBounds.Width ) .Width ) , e.MarginBounds.Top - e.Graphics.MeasureString ( `` QBC Directory '' , new Font ( new Font ( qbcDataGridView.Font , FontStyle.Bold ) , FontStyle.Bold ) , e.MarginBounds.Width ) .Height - 13 ) ; // draw the column headers topMargin = e.MarginBounds.Top ; foreach ( DataGridViewColumn gridCol in qbcDataGridView.Columns ) { if ( ! string.IsNullOrEmpty ( gridCol.HeaderText ) ) { // header color e.Graphics.FillRectangle ( new SolidBrush ( Color.LightGray ) , new Rectangle ( ( int ) arrayLeftColumns [ count ] , topMargin , ( int ) arrayColWidths [ count ] , headerHeight ) ) ; // header text box e.Graphics.DrawRectangle ( Pens.Black , new Rectangle ( ( int ) arrayLeftColumns [ count ] , topMargin , ( int ) arrayColWidths [ count ] , headerHeight ) ) ; // header string e.Graphics.DrawString ( gridCol.HeaderText , gridCol.InheritedStyle.Font , new SolidBrush ( gridCol.InheritedStyle.ForeColor ) , new RectangleF ( ( int ) arrayLeftColumns [ count ] , topMargin , ( int ) arrayColWidths [ count ] , headerHeight ) , string_format ) ; } else { break ; } count++ ; } newPage = false ; topMargin += headerHeight ; } count = 0 ; // draw the column 's contents foreach ( DataGridViewCell gridCell in gridRow.Cells ) { if ( gridCell.Value ! = null ) { if ( ! string.IsNullOrEmpty ( gridCell.Value.ToString ( ) ) ) { e.Graphics.DrawString ( gridCell.Value.ToString ( ) , gridCell.InheritedStyle.Font , new SolidBrush ( gridCell.InheritedStyle.ForeColor ) , new RectangleF ( ( int ) arrayLeftColumns [ count ] , topMargin , ( int ) arrayColWidths [ count ] , cellHeight ) , string_format ) ; } else { break ; } } else { break ; } // draw the borders for the cells e.Graphics.DrawRectangle ( Pens.Black , new Rectangle ( ( int ) arrayLeftColumns [ count ] , topMargin , ( int ) arrayColWidths [ count ] , cellHeight ) ) ; count++ ; } } row++ ; topMargin += cellHeight ; // if more lines exist , print another page if ( printMore ) { e.HasMorePages = true ; } else { e.HasMorePages = false ; } } } catch ( Exception ex ) { MessageBox.Show ( ex.Message , `` Error '' , MessageBoxButtons.OK , MessageBoxIcon.Error ) ; } } private void MenuViewMembers_Click ( object sender , EventArgs e ) { qbcDataGridView.Font = new Font ( qbcDataGridView.Font.FontFamily , 10 ) ; qbcDataGridView.Location = new Point ( 30 , 100 ) ; qbcDataGridView.Size = new Size ( 1500 , 500 ) ; dbConn.Open ( ) ; DataTable dt = new DataTable ( ) ; DbAdapter = new OleDbDataAdapter ( `` select ID , household_head , birthday , phone , email , address , status , spouse , spouse_birthday , spouse_email , anniversary , spouse_status , '' + `` child1 , child1_birthday , child1_email , child2 , child2_birthday , child3_birthday , child4 , child4_birthday , child4_email , child5 , child5_birthday , child5_email , '' + `` child6 , child6_birthday , child6_email , child7 , child7_birthday , child7_email from members '' , dbConn ) ; DbAdapter.Fill ( dt ) ; qbcDataGridView.DataSource = dt ; qbcDataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells ; qbcDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells ; qbcDataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True ; dbConn.Close ( ) ; Controls.Add ( qbcDataGridView ) ; }",Printing only columns in rows that have values from a datagridview "C_sharp : Is there a way to batch a collection of items from the blocking collection.E.G.I have a messaging bus publisher calling blockingCollection.Add ( ) And a consuming thread which is created like this : However , I only want the Console to write after the blocking collection has 10 items on it , whereas GetConsumingEnumerable ( ) always fires after each item is added . I could write my own queue for this but I 'd like to use the blocking collection if possible ? Task.Factory.StartNew ( ( ) = > { foreach ( string value in blockingCollection.GetConsumingEnumerable ( ) ) { Console.WriteLine ( value ) ; } } ) ;",BlockingCollection < T > batching using TPL DataFlow "C_sharp : I 've got an architecture like the following : Data ( Class Library that handles our Entity Framework stuff ) Components ( Middle tier class library that references Data library ) WebOffice ( Web Application that references Components library , but NOT Data library ) Now , I have the following snippet of code ( this lives inside our Components.Payment.cs ; and tblPayment is contained in our Data library . ) : After I added this ; the WebOffice project is giving the following error : errorCS0012 : The type 'Data.Model.tblPayment ' is defined in an assembly that is not referenced . You must add a reference to assembly 'Data , Version=3.5.0.0 , Culture=neutral , PublicKeyToken=749b8697f3214861'.Now , this does n't quite make sense to me , because the WebOffice project is n't calling the Retrieve ( tblPayment tblPayment ) method at all . ( That 's only being used inside the Components library ) Any clue why it would be asking for the Data reference ? Do I need to reference every library that a referenced library references ? ( try saying that 5 times fast ... ) public static Payment Retrieve ( int id ) { var t = repository.Retrieve ( id ) ; //the above line returns a tblPayment object if ( t ! = null ) return new Payment ( t ) ; return null ; } public static Payment Retrieve ( tblPayment tblPayment ) { return new Payment ( tblPayment ) ; }","Why do I need to reference this assembly , even though its not being used" C_sharp : If I 'm using something like this : What precisely is the |= accomplishing ? xr.Settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings ;,What is happening when you use the |= operator in C # ? "C_sharp : I 'm receiving data from a web service . The data are in the following format : I need to parse the input.Can you advise me what format is this and what is the easiest way to parse them ? ... I can parse by splitting the string by ' ; ' and to search the individual elements for the wanted key and the following value . ( possible , but bad solution ) Probably the data are serialized in a standard format and can be deserialized in a dictionary . a:5 : { s:7 : '' request '' ; s:14 : '' 94.190.179.118 '' ; s:6 : '' status '' ; i:206 ; s:12 : '' currencyCode '' ; s:3 : '' BGL '' ; }",Deserializing PHP Data from Web service "C_sharp : I currently have the following Commandto detach a database , but it throws an exception when I execute it . Saying that the database is in use . How can I drop the connection when or before I detach it ? Update : I am currently using SMO but it 's still not working : SqlCommand command = new SqlCommand ( @ '' sys.sp_detach_db 'DBname ' '' , conn ) ; bool DetachBackup ( string backupDBName ) { string connectionString = ConfigurationManager.ConnectionStrings [ `` ConnectionString '' ] .ConnectionString ; var builder = new SqlConnectionStringBuilder ( connectionString ) ; string serverName = builder.DataSource ; string dbName = builder.InitialCatalog ; try { Server smoServer = new Server ( serverName ) ; smoServer.DetachDatabase ( backupDBName + DateTime.Now.ToString ( `` yyyyMMdd '' ) , false ) ; return true ; } catch ( Exception ex ) { MessageBox.Show ( ex.ToString ( ) ) ; return false ; } }",C # How to drop connection when detaching database "C_sharp : I 've created a very simple function that does the following : This is the code that generates the MSIL . Why does this throw the `` Operation could destabilize the runtime '' exception ? I ca n't spot anything wrong with it ; it matches the assembly seen in Reflector/Reflexil perfectly . public static object [ ] ToArray ( int ID ) { return new object [ 4 ] ; } // create method Type arrayType = typeof ( object [ ] ) ; Type intType = typeof ( int ) ; DynamicMethod dm = new DynamicMethod ( methodName , arrayType , new Type [ ] { intType } ) ; ILGenerator il = dm.GetILGenerator ( ) ; // create the array -- object [ ] il.Emit ( OpCodes.Ldc_I4 , 4 ) ; il.Emit ( OpCodes.Newarr , typeof ( object ) ) ; il.Emit ( OpCodes.Stloc_0 ) ; // return the array il.Emit ( OpCodes.Ldloc_0 ) ; il.Emit ( OpCodes.Ret ) ; return dm ; object result = dm.Invoke ( null , new object [ ] { 1 } ) ;",Simple generated MSIL throws `` Operation could destabilize the runtime '' "C_sharp : In MonoDevelop ( linux version ) , ctrl+backspace clears all the linebreaks till the last word/char block , and delete that.For example : ( where _ is my cursor focus is on , and . are line breaks , pressing ctrl+backspace will return me this : instead of : How do I get rid of it ? qwe asd ... _ qwe _ qwe asd.._",How do I get rid of the annoying ctrl+backspace behaviour in MonoDevelop ? "C_sharp : Given the two classes : I have set up the following test : I can create Foo objects directly with and without seed values without any problem . But once I try to create a Bar object that has a Foo property , I get an ObjectCreationException : The decorated ISpecimenBuilder could not create a specimen based on the request : Foo . This can happen if the request represents an interface or abstract class ; if this is the case , register an ISpecimenBuilder that can create specimens based on the request . If this happens in a strongly typed Build expression , try supplying a factory using one of the IFactoryComposer methods.I 'd expect TestFooFactory to get passed a null seed value during the creation of Bar , just as when I created Foo without a seed value . Am I doing something wrong , or could this be a bug ? In my real-world scenario , I want to customize how AutoFixture would use seeded values for certain objects when I pass seeded values in , but I still want AutoFixture to default to normal behavior if no seed is provided . class Foo { ... } class Bar { public Foo FooBar { get ; set ; } } void Test ( ) { var fixture = new Fixture ( ) ; fixture.Customize < Foo > ( x = > x.FromSeed ( TestFooFactory ) ) ; var fooWithoutSeed = fixture.Create < Foo > ( ) ; var fooWithSeed = fixture.Create < Foo > ( new Foo ( ) ) ; var bar = fixture.Create < Bar > ( ) ; //error occurs here } Foo TestFooFactory ( Foo seed ) { //do something with seed ... return new Foo ( ) ; }",Customizing AutoFixure using FromSeed Causes Exception C_sharp : I 'm developing a client/server data driven application using caliburn.micro for frontend and Asp.net WebApi 2 for backend.The application contains a class called `` Person '' . A `` Person '' object is serialized ( JSON ) and moved back and forth from client to server using simple REST protocal . The solution works fine without any problem.Problem : I have set a parent class `` PropertyChangedBase '' for `` Person '' in order to implement NotifyOfPropertyChanged ( ) .But this time the properties of class `` Person '' has NULL values at receiving end.I guess there is a problem with serialization / deserialization.This is only happens when implementing PropertyChangedBase.Can anyone help me to overcome this issue ? public class Person { public int Id { get ; set ; } public string FirstName { get ; set ; } ... } public class Person : PropertyChangedBase { public int Id { get ; set ; } private string _firstName ; public string FirstName { get { return _firstName ; } set { _firstName = value ; NotifyOfPropertyChange ( ( ) = > FirstName ) ; } } ... },caliburn.micro serialization issue when implementing PropertyChangedBase "C_sharp : EDIT : I 've found an answer ( with help from Tejs ) ; see below.I 'm developing a Metro app using HTML/Javascript , along with some C # -based helper libraries . Generally speaking I 'm having a lot of success calling C # methods from Javascript , but I ca n't seem to get passing arrays ( in my specific case , arrays of strings ) to work . Passing individual strings works without issue.My code is something like this : Then , in C # : The problem is that the method `` Foo '' gets an array with the correct length ( so in the above example , 3 ) , but all of the elements are empty . I also tried this : That did n't work either - again , the array was the correct size , but all the elements were null.I 've tried passing string literals , string variables , using `` new Array ( ... ) '' in javascript , changing the signature of `` Foo '' to `` params string [ ] '' and `` params object [ ] '' , all to no avail.Since passing individual strings works fine , I can probably work around this with some hackery ... but it really seems like this should work . It seems really odd to me that the array is passed in as the right size ( i.e . whatever 's doing the marshaling knows SOMETHING about the javascript array structure ) and yet the contents are n't getting populated . // in javascript projectvar string1 = ... ; var string2 = ... ; var string3 = ... ; var result = MyLibrary.MyNamespace.MyClass.foo ( [ string1 , string2 , string3 ] ) ; // in C # projectpublic sealed class MyClass { public static string Foo ( string [ ] strings ) { // do stuff ... } } public static string Foo ( object [ ] strings ) { ...",Pass array from javascript to C # in Metro app "C_sharp : My CQRS application has some complex domain objects . When they are created , all properties of the entity are directly specified by the user , so the CreateFooCommand has about 15 properties.FooCreatedEvent thus also has 15 properties , because I need all entity properties on the read-side.As the command parameters must be dispatched to the domain object and FooCreatedCommand should not be passed to the domain , there is a manual mapping from CreateFooCommand to the domain.As the domain should create the domain event , That is another mapping from the domain Foo properties to FooCreatedEvent.On the read side , I use a DTO to represent the structure of Foo as it is stored within my read-model . So the event handler updating read-side introduces another mapping from event parameters to DTO.To implement a simple business case , we haveTwo redundant classesThree mappings of basically the same propertiesI thought about getting rid of command/event arguments and push the DTO object around , but that would imply that the domain can receive or create a DTO and assign it to the event.Sequence : Any ideas about making CQRS less implementation pain ? REST Controller -- Command+DTO -- > Command Handler -- DTO -- > Domain -- ( Event+DTO ) -- > Event Handler",CQRS : Class Redundancy and passing DTO to Domain "C_sharp : I have an asp.net-core web api project with a configuration containing the following definition : This configuration is used to initialize the following class : This class is initialized from configuration using the following code in the ConfigureServices method in Startup.cs : My service constructor looks like this : In the constructor I notice that Value2 is null , even though it does appear in the configuration as an empty list - which is the value I would expect the property to be initialized with . I expected that the property would be initialized with null only when the field is missing from the configuration . Is there any way with which I could initialize the field as an empty list ? `` MyClass '' : { `` Value1 '' : 1 , `` Value2 '' : [ ] } public class MyClass { public int Value1 { get ; set ; } public int [ ] Value2 { get ; set ; } } public void ConfigureServices ( IServiceCollection services ) { services.AddOptions ( ) ; services.Configure < MyClass > ( Configuration.GetSection ( `` MyClass '' ) ) ; services.AddSingleton < AService > ( ) ; services.AddMvc ( ) ; } public FeedbackRetrievalService ( IOptions < MyClass > myclass ) { _myclass = myclass ; }",Why does a property get initialized to a null instead of an empty list from configuration ? "C_sharp : Here is the code . I still get incorrect resultsThe result is Cumartesi , Temmuz 25 , 2009Instead it should be Saturday , July 25 , 2009How can i fix this error ? C # .net v4.5.2 string srRegisterDate = `` 25.07.2009 00:00:00 '' CultureInfo culture = new CultureInfo ( `` en-US '' ) ; srRegisterDate = String.Format ( `` { 0 : dddd , MMMM d , yyyy } '' , Convert.ToDateTime ( srRegisterDate ) , culture ) ;","When parsing datetime into month day with English culture , it is still parsed in Turkish language" "C_sharp : Currently I have a working live stream using webapi . By receiving a flv stream directly from ffmpeg and sending it straight to the client using PushStreamContent . This works perfectly fine if the webpage is already open when the stream starts . The issue is when I open another page or refresh this page you can no longer view the stream ( the stream is still being sent to the client fine ) . I think it is due to something missing from the start of the stream but I am not sure what to do . Any pointers would be greatly appreciated.Code for client reading streamCode for receiving stream and then sending to client public class VideosController : ApiController { public HttpResponseMessage Get ( ) { var response = Request.CreateResponse ( ) ; response.Content = new PushStreamContent ( WriteToStream , new MediaTypeHeaderValue ( `` video/x-flv '' ) ) ; return response ; } private async Task WriteToStream ( Stream arg1 , HttpContent arg2 , TransportContext arg3 ) { //I think metadata needs to be written here but not sure how Startup.AddSubscriber ( arg1 ) ; await Task.Yield ( ) ; } } while ( true ) { bytes = new byte [ 8024000 ] ; int bytesRec = handler.Receive ( bytes ) ; foreach ( var subscriber in Startup.Subscribers.ToList ( ) ) { var theSubscriber = subscriber ; try { await theSubscriber.WriteAsync ( bytes , 0 , bytesRec ) ; } catch { Startup.Subscribers.Remove ( theSubscriber ) ; } } }",Live FLV streaming in C # WebApi C_sharp : With C # 6 I have the following model : And I have the following ( example code ) : If Result is null I get an error so I need to use : Is there a shorter way to do this in C # 6 ? public class Model { public Int32 ? Result { get ; set ; } } Model model = new Model ( ) ; Int32 result = model.Result.Value ; Int32 result = model.Result.HasValue ? model.Result.Value : 0 ;,Get value or null of nullable variable "C_sharp : A simple C # codeandResharper says that result in Console.WriteLine ( result ) is always true . Why ? bool result ; if ( bool.TryParse ( `` false '' , out result ) & & result ) { Console.WriteLine ( result ) ; } bool result ; if ( bool.TryParse ( `` tRue '' , out result ) & & result ) { Console.WriteLine ( result ) ; }",Expression is always true in C # "C_sharp : I have a ViewModel that represents multiple options and implements IDataErrorInfo . This ViewModel is only valid if at least one of these options is selected . It is bound to a ContentControl . A DataTemplate is used to visualize the ViewModel as a GroupBox containing an ItemsControl . Another DataTemplate visualizes each option as a CheckBox.What do I have to do , to make the ContentControl work together with IDataErrorInfo and check the validity when a check box is checked or unchecked ? Some code : Binding : Data templates : Style : < ContentControl Content= '' { Binding GeneralInvoiceTypes , ValidatesOnDataErrors=True } '' Margin= '' 0,0,5,0 '' / > < DataTemplate DataType= '' { x : Type ViewModels : MultipleOptionsViewModel } '' > < GroupBox Header= '' { Binding Title } '' > < ItemsControl ItemsSource= '' { Binding Options } '' / > < /GroupBox > < /DataTemplate > < DataTemplate DataType= '' { x : Type ViewModels : OptionViewModel } '' > < CheckBox IsChecked= '' { Binding IsChecked } '' Content= '' { Binding Name } '' Margin= '' 6,3,3,0 '' / > < /DataTemplate > < Style TargetType= '' { x : Type ContentControl } '' > < Style.Triggers > < Trigger Property= '' Validation.HasError '' Value= '' true '' > < Setter Property= '' ToolTip '' Value= '' { Binding RelativeSource= { x : Static RelativeSource.Self } , Path= ( Validation.Errors ) [ 0 ] .ErrorContent } '' / > < /Trigger > < /Style.Triggers > < Setter Property= '' Validation.ErrorTemplate '' > < Setter.Value > < ControlTemplate > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' 90* '' / > < ColumnDefinition Width= '' 20 '' / > < /Grid.ColumnDefinitions > < Border BorderBrush= '' Red '' BorderThickness= '' 1 '' CornerRadius= '' 2.75 '' Grid.Column= '' 0 '' > < AdornedElementPlaceholder Grid.Column= '' 0 '' / > < /Border > < TextBlock Foreground= '' Red '' Grid.Column= '' 1 '' Margin= '' 0 '' FontSize= '' 12 '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Left '' x : Name= '' txtError '' > * < /TextBlock > < /Grid > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style >",GroupBox in ContentControl - support for IDataErrorInfo implemented by the content bound to the ContentControl "C_sharp : Given a list of filter parameters in the form of : Where : How do I write an expression which would result in the following SQL where clause ( note the OR operators in bold : WHERE ( age = 22 AND name = `` phil '' ) OR ( age = 19 AND name = `` dave '' ) OR ( age = 31 AND name = `` nick '' ) My current implementation results in each of the statements seperated by the AND operator : The code above results in the following SQL : WHERE ( age = 22 AND name = `` phil '' ) AND ( age = 19 AND name = `` dave '' ) AND ( age = 31 AND name = `` nick '' ) What do I need to change in the expression to cause the generated SQL to use 'OR ' instead of 'AND ' in the indicated locations ? I would prefer to avoid using third party libraries where possible.EDIT : As suggested by @ KingKing , a union does return the required results : I would still like to know if it is possible to generate the statement using the 'Or ' operator as described . public class filterParm { public int age { get ; set ; } public string name { get ; set ; } } var parms = new List < filterParm > { new filterParm { age = 22 , `` phil '' } , new filterParm { age = 19 , `` dave '' } , new filterParm { age = 31 , `` nick '' } } ; private _dbSet < user > Users { get ; set ; } public List < user > CustomFilter ( List < filterParm > parms ) { IQueryable < TEntity > query = _dbSet ; if ( parms.Count > 0 ) { foreach ( var parm in parms ) { query = query.Where ( u = > u.Age == parm.Age & & u.Name == parm.Name ) ; } } return query.ToList ( ) ; } private _dbSet < user > Users { get ; set ; } public List < user > CustomFilter ( List < filterParm > parms ) { IQueryable < TEntity > query = _dbSet ; if ( parms.Count > 0 ) { query = query.Where ( u = > u.Age == parms [ 0 ] .Age & & u.Name == parms [ 0 ] .Name ) ; for ( int i = 1 ; i < parms.Count ; i++ ) { var parm = parms [ i ] ; query = query.Union ( DbSet.Where ( u = > u.Age == parm.Age & & u.Name == parm.Name ) ) ; } } return query.ToList ( ) ; }",Multiple 'Or ' statements in EF expression C_sharp : I 'm trying to use PowerShell from C # to create a new file on desktop . In the terminal you would do : So I 'm trying to do this in C # to mimic the previous statements : This runs without any exceptions but the file is n't created on the desktop . Can anyone point out what I 'm doing wrong with the AddScript ? EDITIt looks like the problem comes from using cd and then the create in sequence.I was able to get it working by doingIf anyone knows how to do a cd command followed by another please let me know . cd desktop $ null > > newfile.txt using ( PowerShell PowerShellInstance = PowerShell.Create ( ) ) { PowerShellInstance.AddScript ( `` cd desktop ; $ null > > newfile.txt '' ) ; PowerShellInstance.Invoke ( ) ; } PowerShellInstance.AddScript ( `` $ null > > C : \\users\\me\\Desktop\\newfile.txt '' ) ;,C # PowerShell create blank text file on desktop "C_sharp : I am working on an application and trying to follow Robert C. Martin 's SOLID principles . I am using the Command Pattern and I was wondering about the implementation . In all of his examples in Clean Code and Agile Principles , Patterns and Practices in C # his command objects never return anything . His Command interface is ; All of the examples are `` AddEmployee '' , `` DelEmployee '' , `` EditEmployee '' , etc . Would I have a command that would be `` GetAllEmployees '' or is there some other special `` Interactor '' I would create for that specific purpose ? One way I am thinking of handling that specific case is to have two interfaces a non generic like the one above and a generic one like this ; What I am asking is would this be an acceptable implementation of this pattern or is there another way we would access data from the application ? public interface Command { void Execute ( ) ; } public interface Command < T > { T Execute ( ) ; }",Command Pattern use for Returning Data "C_sharp : I have GridView and a button as follows . Then i am binding the gridview with data from my database . GridView has two hiddenfield for Id and ClassIndex.when i selecting a checkbox and click button , i want to get the corresponding Id and FileName.and Button Likethe code behind button isbut i am getting an error like Input string was not in a correct format.What is the error and how to solve it ? < asp : GridView ID= '' GridView1 '' runat= '' server '' AutoGenerateColumns= '' False '' > < Columns > < asp : TemplateField > < ItemTemplate > < asp : CheckBox ID= '' check '' runat= '' server '' / > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField > < ItemTemplate > < asp : HiddenField ID= '' hdfId '' runat = '' server '' Value= ' < % # Eval ( `` Id '' ) % > ' / > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField > < ItemTemplate > < asp : HiddenField ID= '' hdfClssIndex '' runat = '' server '' Value= ' < % # Eval ( `` ClassIndex '' ) % > ' / > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField > < ItemTemplate > < asp : Label ID= '' lblFileName '' runat = '' server '' Text= ' < % # Eval ( `` FileName '' ) % > ' / > < /ItemTemplate > < /asp : TemplateField > < /Columns > < /asp : GridView > < asp : Button ID= '' Button1 '' runat= '' server '' onclick= '' Button1_Click '' Text= '' Send Request '' / > protected void Button1_Click ( object sender , EventArgs e ) { foreach ( GridViewRow row in GridView1.Rows ) { var check = row.FindControl ( `` check '' ) as CheckBox ; if ( check.Checked ) { int Id = Convert.ToInt32 ( row.Cells [ 1 ] .Text ) ; //some logic follws here } } }",How to get the Id from Gridview of Chechbox.checked ? "C_sharp : Update : This occurs when the Code Analysis option `` Suppress results from generated code ( managed only ) '' is turned off , and Rule Set is set to `` Microsoft Basic Design Guideline Rules '' .On 2013-04-26 , Microsoft confirmed this is a bug , but will not fix it in either this or the next version of Visual Studio.Link to MS Connect itemWe frequently initialize event handlers with an empty delegate to avoid the need for checking nulls . E.g . : However , since starting to compile some of our code in Visual Studio 2012 ( RTM ) , I 'm noticing a lot of events in derived classes are now triggering CA1601 : Do not hide base class methods warnings in Visual Studio 2012 's Code Analysis.Here 's a sample that will trigger the warning : Note : In VS2012 the warning is triggered when compiled in either .NET 4.5 or .NET 4.0 . The same sample does not trigger the warning in VS2010.Performance reasons aside , are there any legitimate reasons we should n't be initializing events with empty delegates ? The default assumption is that it 's probably just a quirk in the analysis in Visual Studio 2012 . Here 's the code analysis result for those that do n't have access to VS2012 yet : CA1061 Do not hide base class methods Change or remove 'Class2.Class2 ( ) ' because it hides a more specific base class method : 'Class1.Class1 ( ) ' . TestLibrary1 Class1.cs 14Addendum : I found that the option to `` Suppress results from generated code '' in the code analysis is turned off.Also , I found that this seems to occur when the event handler in the base type is both : a delegate other than EventHandler or EventHandler -and-events in both the base class and the derived class are initialized using an anonymous method or empty delegate ( either inline or in the constructor ) .Of possible relevance : We 're running Visual Studio 2012 RTM , which was installed in-place over the release candidate . public EventHandler SomeEvent = delegate { } ; using System ; using System.ComponentModel ; [ assembly : CLSCompliant ( true ) ] namespace TestLibrary1 { public abstract class Class1 { public event PropertyChangedEventHandler PropertyChanged = delegate { } ; } public class Class2 : Class1 { // this will cause a CA1061 warning public event EventHandler SelectionCancelled = delegate { } ; } public class Class3 : Class1 { // this will not cause a CA1061 warning public event EventHandler SelectionCancelled ; } }",Why would an empty delegate event handler cause a CA1061 warning ? "C_sharp : I have an instance of the type object , from which I know that it is a pointer ( can easily be verified with myobject.GetType ( ) .IsPointer ) . Is it possible to obtain the pointer 's value via reflection ? code so far : Addendum №1 : As the object in question is value type -not a reference type- , I can not use GCHandle : :FromIntPtr ( IntPtr ) followed by GCHandle : :Target to obtain the object 's value ... object obj = ... . ; // type and value unknown at compile timeType t = obj.GetType ( ) ; if ( t.IsPointer ) { void* ptr = Pointer.Unbox ( obj ) ; // I can obtain its ( the object 's ) bytes with : byte [ ] buffer = new byte [ Marshal.SizeOf ( t ) ] ; Marshal.Copy ( ( IntPtr ) ptr , buffer , 0 , buffer.Length ) ; // but how can I get the value represented by the byte array 'buffer ' ? // or how can I get the value of *ptr ? // the following line obviously does n't work : object val = ( object ) *ptr ; // error CS0242 ( obviously ) }",Get pointer value via reflection "C_sharp : I was under the impression that lambda expression contexts in C # contain references to the variables of the parent function scope that are used in them . Consider : outputsHowever , if this was true , the following would be illegal , because the lambda context would reference a local variable that went out of scope : However , this compiles , runs and outputsWhich means that either something weird is going on , or the context keeps values of the local variables , not references to them . But if this was true , it would have to update them on every lambda invokation , and I do n't see how that would work when the original variables go out of scope . Also , it seems that this could incur an overhead when dealing with large value types.I know that , for example , in C++ , this is UB ( confirmed in answer to this question ) .The question is , is this well-defined behaviour in C # ? ( I think C # does have some UB , or at least some IB , right ? ) If it is well-defined , how and why does this actually work ? ( implementation logic would be interesting ) public class Test { private static System.Action < int > del ; public static void test ( ) { int i = 100500 ; del = a = > System.Console.WriteLine ( `` param = { 0 } , i = { 1 } '' , a , i ) ; del ( 1 ) ; i = 10 ; del ( 1 ) ; } public static void Main ( ) { test ( ) ; } } param = 1 , i = 100500param = 1 , i = 10 public class Test { private static System.Action < int > del ; public static void test ( ) { int i = 100500 ; del = a = > System.Console.WriteLine ( `` param = { 0 } , i = { 1 } '' , a , i ) ; } public static void Main ( ) { test ( ) ; del ( 1 ) ; } } param = 1 , i = 100500",Why does a lambda expression preserve enclosing scope variable values after method terminates ? "C_sharp : I would like to know how to open URL on button click in Gear VR App . Samsung Internet App in Oculus Store can be used in this scenario . Just like in 2D Non-VR Android Application , URL is automatically opened in Chrome or Firefox based on default browser . But in Gear VR app when I callthe app freezes . If this is not possible at all , then is there a way to show intractable Web-View in 3D space ? Any kind of help will be appreciated . Application.OpenURL ( `` http : //www.google.co.uk '' ) ;",How to open URL in Virtual Reality ( GearVR ) App "C_sharp : I 'm making my first attempt at experimenting with Comet . I developed a very simple chat web app - basically a hello world of comet via c # . The problem i 'm having is IIS will sometimes crash and by crash i mean it simply stops responding to HTTP requests . It then takes for ever to restart the app pool and sometimes the whole IIS service . I 'm almost positive the culprit is the ManualResetEvent object I 'm using to block comet requests threads until a signal to release ( update ) those threads is received . I tried writing an HTTP handler to get around this and set the reusable property to false ( to put new requests threads on another instance of the ManualResetEvent object ) but that did n't work . I 'm also trying implementing the IRegisteredObject so I can release those theads when the app is shutting down but that does n't seem to work either . It still crashes and there does n't seem to be any pattern in when it crashes ( that i 've noticed ) . I 'm almost sure it 's a combination of static instances and the use of ManualResetEvent that 's causing it . I just do n't know for sure how or how to fix it for that matter.Comet.cs ( My simple comet lib ) My chat class and web serviceThe test aspx fileAnd the aspx code behindIf anyone has a good theory on the cause and/or fix for the seemingly arbitrary crashes it would be much appreciated if you'ld post : ) using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading ; using System.Net.Mail ; using System.Web.Hosting ; namespace Comet { public class CometCore : IRegisteredObject { # region Globals private static CometCore m_instance = null ; private List < CometRequest > m_requests = new List < CometRequest > ( ) ; private int m_timeout = 120000 ; //Default - 20 minutes ; # endregion # region Constructor ( s ) public CometCore ( ) { HostingEnvironment.RegisterObject ( this ) ; } # endregion # region Properties /// < summary > /// Singleton instance of the class /// < /summary > public static CometCore Instance { get { if ( m_instance == null ) m_instance = new CometCore ( ) ; return m_instance ; } } /// < summary > /// In milliseconds or -1 for no timeout . /// < /summary > public int Timeout { get { return m_timeout ; } set { m_timeout = value ; } } # endregion # region Public Methods /// < summary > /// Pauses the thread until an update command with the same id is sent . /// < /summary > /// < param name= '' id '' > < /param > public void WaitForUpdates ( string id ) { //Add this request ( and thread ) to the list and then make it wait . CometRequest request ; m_requests.Add ( request = new CometRequest ( id ) ) ; if ( m_timeout > -1 ) request.MRE.WaitOne ( m_timeout ) ; else request.MRE.WaitOne ( ) ; } /// < summary > /// Un-pauses the threads with this id . /// < /summary > /// < param name= '' id '' > < /param > public void SendUpdate ( string id ) { for ( int i = 0 ; i < m_requests.Count ; i++ ) { if ( m_requests [ i ] .ID.Equals ( id ) ) { m_requests [ i ] .MRE.Set ( ) ; m_requests.RemoveAt ( i ) ; i -- ; } } } # endregion public void Stop ( bool immediate ) { //release all threads for ( int i = 0 ; i < m_requests.Count ; i++ ) { m_requests [ i ] .MRE.Set ( ) ; m_requests.RemoveAt ( i ) ; i -- ; } } } public class CometRequest { public string ID = null ; public ManualResetEvent MRE = new ManualResetEvent ( false ) ; public CometRequest ( string pID ) { ID = pID ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.Services ; using Comet ; namespace CometTest { /// < summary > /// Summary description for Chat /// < /summary > [ WebService ( Namespace = `` http : //tempuri.org/ '' ) ] [ WebServiceBinding ( ConformsTo = WsiProfiles.BasicProfile1_1 ) ] [ System.ComponentModel.ToolboxItem ( false ) ] // To allow this Web Service to be called from script , using ASP.NET AJAX , uncomment the following line . [ System.Web.Script.Services.ScriptService ] public class Chat : System.Web.Services.WebService { [ WebMethod ] public string ReceiveChat ( ) { return ChatData.Instance.GetLines ( ) ; } [ WebMethod ] public string ReceiveChat_Comet ( ) { CometCore.Instance.WaitForUpdates ( `` chat '' ) ; return ChatData.Instance.GetLines ( ) ; } [ WebMethod ] public void Send ( string line ) { ChatData.Instance.Add ( line ) ; CometCore.Instance.SendUpdate ( `` chat '' ) ; } } public class ChatData { private static ChatData m_instance = null ; private List < string > m_chatLines = new List < string > ( ) ; private const int m_maxLines = 5 ; public static ChatData Instance { get { if ( m_instance == null ) m_instance = new ChatData ( ) ; return m_instance ; } } public string GetLines ( ) { string ret = string.Empty ; for ( int i = 0 ; i < m_chatLines.Count ; i++ ) { ret += m_chatLines [ i ] + `` < br > '' ; } return ret ; } public void Add ( string line ) { m_chatLines.Insert ( 0 , line ) ; if ( m_chatLines.Count > m_maxLines ) { m_chatLines.RemoveAt ( m_chatLines.Count - 1 ) ; } } } } < % @ Page Language= '' C # '' AutoEventWireup= '' true '' CodeBehind= '' Default.aspx.cs '' Inherits= '' CometTest.Default '' % > < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head runat= '' server '' > < title > < /title > < /head > < body > < form id= '' form1 '' runat= '' server '' > < asp : ScriptManager ID= '' ScriptManager1 '' runat= '' server '' > < Services > < asp : ServiceReference Path= '' ~/Chat.asmx '' / > < /Services > < /asp : ScriptManager > < div id= '' lyrChatLines '' style= '' height : 200px ; width : 300px ; border : 1px solid # cccccc ; overflow : scroll '' > < /div > < asp : Panel runat= '' server '' DefaultButton= '' cmdSend '' > < asp : UpdatePanel runat= '' server '' > < ContentTemplate > < asp : TextBox style= '' width : 220px '' runat= '' server '' ID= '' txtChat '' > < /asp : TextBox > < asp : Button runat= '' server '' ID= '' cmdSend '' Text= '' Send '' OnClick= '' cmdSend_Click '' / > < /ContentTemplate > < /asp : UpdatePanel > < /asp : Panel > < script type= '' text/javascript '' > function CometReceive ( ) { CometTest.Chat.ReceiveChat_Comet ( receive , commError , commError ) ; } function ReceiveNow ( ) { CometTest.Chat.ReceiveChat ( receive , commError , commError ) ; } function receive ( str ) { document.getElementById ( `` lyrChatLines '' ) .innerHTML = str ; setTimeout ( `` CometReceive ( ) '' , 0 ) ; } function commError ( ) { document.getElementById ( `` lyrChatLines '' ) .innerHTML = `` Communication Error ... '' ; setTimeout ( `` CometReceive ( ) '' , 5000 ) ; } setTimeout ( `` ReceiveNow ( ) '' , 0 ) ; < /script > < /form > < /body > < /html > using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.UI ; using System.Web.UI.WebControls ; namespace CometTest { public partial class Default : System.Web.UI.Page { protected void Page_Load ( object sender , EventArgs e ) { } protected void cmdSend_Click ( object sender , EventArgs e ) { Chat service = new Chat ( ) ; service.Send ( Request.UserHostAddress + `` > `` + txtChat.Text ) ; txtChat.Text = string.Empty ; txtChat.Focus ( ) ; } } }",c # comet server freezing IIS "C_sharp : I would like to use net wisdom to clarify some moments regarding multi-threading in .net . There are a lot of stuff in the internet about it however I was not able to find a good answer to my question . Let say we want to maintain a state of something in our class with safety for concurrent threads . Easy case is when state is int : 'volatile ' should be enough in this case . Whatever thread needs to get current state it can use 'State ' property which will never be cached . Whatever thread wants to update state it can do it safely using 'UpdateState'.However , what to do if state is a structure ? Is a complete 'lock ' the only way ? Side question : can a variable still be cached inside the lock ? And eventually the main question : will this code be sufficient for managing a collection of state objects in multi-threading environment ? Or there might be some hidden problems.Thanks for your answers . class Class1 { volatile int state = 0 ; public int State { get { return state ; } } public Action < int > StateUpdated ; public void UpdateState ( int newState ) { state = newState ; if ( StateUpdated ! = null ) StateUpdated ( newState ) ; } } struct StateData { //some fields } class Class1 { StateData state ; public StateData State { get { return state ; } } public Action < StateData > StateUpdated ; public void UpdateState ( StateData newState ) { state = newState ; if ( StateUpdated ! = null ) StateUpdated ( newState ) ; } } public struct StateData { //some fields } public delegate void StateChangedHandler ( StateData oldState , StateData newState ) ; class Class1 { ConcurrentDictionary < string , StateData > stateCollection = new ConcurrentDictionary < string , StateData > ( ) ; public StateData ? GetState ( string key ) { StateData o ; if ( stateCollection.TryGetValue ( key , out o ) ) return o ; else return null ; } public StateChangedHandler StateUpdated ; void UpdateState ( string key , StateData o ) { StateData ? prev = null ; stateCollection.AddOrUpdate ( key , o , ( id , old ) = > { prev = old ; return o ; } ) ; if ( prev ! = null & & StateUpdated ! = null ) StateUpdated ( prev.Value , o ) ; } }",Volatile for structs and collections of structs "C_sharp : So I am using Nancy with Nowin . The beauty of using Nowin is I do n't have to mess around with various Windows commands to set up a simple web server . According to the Nowin readme I can configure SSL using the following line However , when using Nancy I do n't seem to have access to this Server builder class . Everything seems to happen magically behind the scenes.Any ideas how I can pass the certificate through to Nowin ? builder.SetCertificate ( new X509Certificate2 ( `` certificate.pfx '' , `` password '' ) ) ;",How can I pass a SSL certificate to Nowin when using Nancy "C_sharp : I want to filter a string array : from the command line , e.g : `` -command1 x y -command2 a b -command3 c d '' Taking all the words with a '- ' at the beginning , then converting those to upper case.This will return the args list with words starting with '- ' lower case - that is the lambda is not being applied . Why is this ? Is a copy of the list being made for the lambda capture , and that is modified , not the origina list itself ? string [ ] args var commands = args.Where ( x = > x.StartsWith ( `` - '' ) ) .ToList < String > ( ) ; commands.ForEach ( x = > { x.ToUpper ( ) } ) ; commands.ToString ( ) ;",Modify elements in list with ForEach lambda "C_sharp : I have an Office addin which uses the following backstage XML to add custom UI elements into Microsoft Word backstage : This is the exact base-case scenario described here to modify the Save As dialog.On my machine , it does not show anything under Save As . I do however see that the following function gets called when the backstage is shown : What are some of the reasons why the UI will not show , and also , how can I debug what is going on here ? I tried turning on Show add-in user interface errors in the Advanced tab of Word Options , under the General section , but it does n't display any errors to me , as far as I can tell.Not sure if it helps , but our ribbon inherits IRibbonExtensibility.We 've also found this logic sometimes works on some machines but not on others . I am clueless as to why ... one thing I can tell you that is definitely different is that the types for this addin are registered with regasm instead of the addin being installed using a path|vstolocal registry key under Outlook 's registry . In other words , we are using regasm to install the addin.Edit : I have tried the suggested answer but it is still not working given that approach . My team and I are pretty convinced at this point that this is a major VSTO bug and we have cooked up a project to showcase it . This project showcases backstage bugs with Windows 10 Pro 64-bit version 1607 ( OS build 14393.351 ) and 32-bit Word 2016 16.0.7426.1009 ( Office 2016 32-bit version 1610 , build 7466.2023 ) : https : //github.com/Murdoctor/WordAddin1If you run this sample on the same or similar environment , you can see that if you click the Home tab at the top of Word , you will see the button that is defined in https : //github.com/Murdoctor/WordAddin1/blob/master/WordAddIn1/Ribbon1.xml , but , if you open up the backstage you do n't see the sample tab that should be inserted after the info tab , TabInfo ( this screenshot was taken with a release build run in debug mode directly from Visual Studio , and I can see the addin is registered up and everything as well ) : The only thing that you will see is this ( this is also proof the addin is running and registered to its local VSTO file ) : Edit : This also affects Office 64-bit . I just installed Word 2016 16.0.7426.1009 ( Office 2016 64-bit version 1610 , build 7466.2023 ) thinking that changing to x64 might help , but I still experience the same issue on my machine.Edit : This also affects today 's release of Windows 10 Pro x64 version 1607 , build 14393.447 . Also , I have tried disabling all other addins , still the same thing . < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < customUI xmlns= '' http : //schemas.microsoft.com/office/2009/07/customui '' onLoad= '' Ribbon_Load '' > < backstage onShow= '' Backstage_OnShow '' > < tab idMso= '' TabSave '' > < firstColumn > < taskFormGroup idMso= '' SaveGroup '' > < category idMso= '' Save '' > < task id= '' myCustomTask '' label= '' My Custom Task '' insertAfterMso= '' ButtonTaskDynamicServiceProvider '' > < group id= '' myGroupInTabSave '' label= '' Custom functionality '' helperText= '' This group contains custom functionality . `` > < primaryItem > < button id= '' myButton '' label= '' My Button '' onAction= '' CallMe '' / > < /primaryItem > < /group > < /task > < /category > < /taskFormGroup > < /firstColumn > < /tab > < /backstage > < /customUI > public void Backstage_OnShow ( object contextObject ) { // It hits this method . }",Why is this custom backstage UI for Word not displaying its user interface ? "C_sharp : I am using ServiceStack.Text library for reading from CSV files in C # . I would like to know how to deserialize CSV to objects where CSV contains white space separated header ? I am using this code to deserialize CSV to empClass object : If I have a csv file like thisand my class is like It populates EmpId but it does n't populate Employee Name and Employee Address as it contains the white-space in the header.Will be grateful if anyone can help . List < empClass > objList = File.ReadAllText ( filePath ) .FromCsv < List < empClass > > ( ) ; EmpId , Employee Name , Employee Address 12 , JohnSmith,123 ABC Street public class empClass { public string EmpId ; public string Employee_Name ; public string Employee_Address ; }",How to import CSV file with white-space in header with ServiceStack.Text "C_sharp : I have tried getting an HTTP-trigger in an Azure Functions 3.0/3.1 app to return the string-representation of enums without any luck . I have tried both Core 3.0 and Core 3.1.Given this class : I expect this HTTP-trigger : to return { `` test '' : `` TestValue '' } . Instead it returns { `` test '' : 0 } .In .Net Core 2 , I could decorate the enum using [ JsonConverter ( typeof ( StringEnumConverter ) ) ] from the namespace Newtonsoft.Json to make this happen . This does not work now.I know .Net Core 3 switched to the converter in the System.Text.Json-namespace , so I tried decorating the same enum with [ JsonConverter ( typeof ( JsonStringEnumConverter ) ) ] from the namespace System.Text.Json.Serialization . This did not work either.All of the other similar issues either says that the above should work , or , like this , says to solve it by configuring JsonOptions in the .AddControllers ( ) or .AddMvc ( ) -chain , but for a function app that wo n't work . The function runtime is responsible for setting up the controllers , so we do n't have direct access to further configuration AFAIK.The issue should be reproducible with a barebones Azure Functions project using the core tools : Then change the http trigger to return an object with an enum inside.My versions : Additional informationI have tried multiple workarounds , so here is some of my observations.OkObjectResult is handled by ObjectResultExecutor . I tried to copy the implementation into my solution and adding it to the DI container so I could debug : At line 101 in the linked source , the formatter is chosen . Interestingly , when I break at this point , the formatter chosen is NewtonsoftJsonOutputFormatter ! I would think the first JsonConverter-attribute should work with this , but it doesn't.I figured it would be worth a shot to modify the list of available output formatters . The ActionResultExecutor uses DefaultOutputFormatterSelector to make its selection , which in turn injects IOptions < MvcOptions > to get output formatters.To force the DefaultOutputFormatterSelector to choose differently I tried this : Note that the regular IConfigureOptions < T > could n't be used as the options.Outputformatters-collection was missing all other formatters than Microsoft.AspNetCore.Mvc.WebApiCompatShim.HttpResponseMessageOutputFormatter , which is strange in itself ( why is a brand new 3.0 app using a compatibility shim ? ) .I tried to remove the type NewtonsoftJsonOutputFormatter from the collection using : To do that I had to reference the nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson to access the type , but the type when I referenced it was different from the one used by the runtime . type.Assembly.CodeBase for the type used by the runtime was located in % USERPROFILE % /AppData/Local/AzureFunctionsTools/ but the one from nuget was located in Project root/bin/Debug . I have never encountered this before . Usually , the package will be a transient dependency so I can reference it without explicitly depending on the package myself , so I 'm not really sure what 's going on here . Is this normal , or is there something wrong in my environment ? When I removed it in another manner it did n't matter and it got selected anyway , so it seems like the MvcOptions injected in DefaultOutputFormatterSelector is not the same MvcOptions we can configure in the startup.At this point , I ran out of leads and turned to you guys . I hope there is someone who can point me in the right direction . public enum TestEnum { TestValue } public class TestClass { public TestEnum Test { get ; set ; } } [ FunctionName ( `` MyHttpTrigger '' ) ] public static IActionResult Run ( [ HttpTrigger ( AuthorizationLevel.Function , `` get '' , `` post '' , Route = null ) ] HttpRequest req , ILogger log ) { return new OkObjectResult ( new TestClass { Test = TestEnum.TestValue } ) ; } func init MyFunctionProjcd MyFunctionProjfunc new -- name MyHttpTrigger -- template `` HttpTrigger '' > func -- version3.0.1975 > dotnet -- version3.1.100 builder.Services.AddSingleton < IActionResultExecutor < ObjectResult > , TestExecutor > ( ) ; class MvcOptionsConfiguration : IPostConfigureOptions < MvcOptions > { ... } public class Startup : FunctionsStartup { public override void Configure ( IFunctionsHostBuilder builder ) { builder.Services.ConfigureOptions < MvcOptionsConfiguration > ( ) ; } } options.OutputFormatters.RemoveType < NewtonsoftJsonOutputFormatter > ( ) ;",Serializing Enum as string using attribute in Azure Functions 3.0 "C_sharp : F # supports a type constraint for `` unmanaged '' . This is not the same as a value type constraint like `` struct '' constraints . MSDN notes that the behavior of the unmanaged constraint is : The provided type must be an unmanaged type . Unmanaged types are either certain primitive types ( sbyte , byte , char , nativeint , unativeint , float32 , float , int16 , uint16 , int32 , uint32 , int64 , uint64 , or decimal ) , enumeration types , nativeptr < _ > , or a non-generic structure whose fields are all unmanaged types.This is a very handy constraint type when doing platform invocation , and more than once I wish C # had a way of doing this . C # does not have this constraint . C # does not support all constraints that can be specified in CIL . An example of this is an enumeration . In C # , you can not do this : However , the C # compiler does honor the `` enum '' constraint if it comes across it in another library . Jon Skeet is able to use this to create his Unconstrained Melody project.So , my question is , is F # 's `` unmanaged '' constraint something that can be represented in CIL , like an enum constraint and just not exposed in C # , or is it enforced purely by the F # compiler like some of the other constraints F # supports ( like Explicit Member Constraint ) ? public void Foo < T > ( T bar ) where T : enum",Behavior of F # `` unmanaged '' type constraint "C_sharp : Say I have one interface and two classes , and one of the classes implement this interface : In class AAA2 , property F1 is 'inherited ' ( I 'm not sure ) from interface IAAA , then I use reflection to check whether a property is virtual : The output is : Any reason for this ? interface IAAA { int F1 { get ; set ; } } class AAA1 { public int F1 { get ; set ; } public int F2 { get ; set ; } } class AAA2 : IAAA { public int F1 { get ; set ; } public int F2 { get ; set ; } } Console.WriteLine ( `` AAA1 which does not implement IAAA '' ) ; foreach ( var prop in typeof ( AAA1 ) .GetProperties ( ) ) { var virtualOrNot = prop.GetGetMethod ( ) .IsVirtual ? `` '' : `` not '' ; Console.WriteLine ( $ @ '' { prop.Name } is { virtualOrNot } virtual '' ) ; } Console.WriteLine ( `` AAA2 which implements IAAA '' ) ; foreach ( var prop in typeof ( AAA2 ) .GetProperties ( ) ) { var virtualOrNot = prop.GetGetMethod ( ) .IsVirtual ? `` '' : `` not '' ; Console.WriteLine ( $ '' { prop.Name } is { virtualOrNot } virtual '' ) ; } AAA1 which does not implement IAAAF1 is not virtualF2 is not virtualAAA2 which implements IAAAF1 is virtualF2 is not virtual",Why does a property inherited from an interface become virtual ? C_sharp : I 'm new to roslyn so I 'm looking for some pointers or sample code to start doing what I want.I have a lot of code that is similar to this ( it was generated by a tool ) What I want to do is detect and then rewrite the syntax to something that is more efficient and developer friendlyEssentially I am wanting to optimize out all switches that are on boolean values . switch ( boolVariable ) { case false : { str = `` blahblah '' ; break ; } case true : { str = `` somethingelse '' ; break ; } default : { str = `` ughthiswouldnevergethit '' ; break ; } } if ( boolVariable ) { str = `` somethingelse '' ; } else { str = `` blahblah '' ; },Use Rosyln to rewrite switch blocks to if/else "C_sharp : I have a simple class : And I want to hold an array of MyClass objects like this : Is it possible , without creating a `` collection '' object , to be able to access one of those objects in the array of objects by the string indexer ( is that the right terminology ) ? For example , if myClasses [ 2 ] has the value `` andegre '' in the MyClassName property , how/can I access it like this : Instead of doing something like : TIA public class MyClass { public string MyClassName { get ; private set ; } public string MyClassValue { get ; private set ; } } MyClass [ ] myClasses = new MyClass [ 5 ] ; MyClass andegre = myClasses [ `` andegre '' ] ; MyClass andegre = myClasses [ GetIndexOfOfMyClassName ( `` andegre '' ) ] ;",Use string indexer on custom class "C_sharp : When using NInject if I set up a binding for IEnumerable , it will work if I directly request an IEnumerable , but not if another bound object requires an IEnumerable . Is this by design ? class Program { static void Main ( string [ ] args ) { var k = new StandardKernel ( ) ; k.Bind < IEnumerable < int > > ( ) .ToMethod ( GetInts ) ; k.Bind < IFoo > ( ) .To < Foo > ( ) ; //Has an IEnumberable < int > constructor arg var works = k.Get < IEnumerable < int > > ( ) ; //returns the array of ints var tst = k.Get < IFoo > ( ) ; //Empty integer array is passed in by ninject ? ? ? tst.Get ( ) ; //returns an empty integer array ? ? ? ? return ; } public static int [ ] GetInts ( IContext ctx ) { return new int [ ] { 1,2,3,4,5 } ; } } public interface IFoo { IEnumerable < int > Get ( ) ; } public class Foo : IFoo { private int [ ] _vals ; public Foo ( IEnumerable < int > vals ) { _vals = vals.ToArray ( ) ; } public IEnumerable < int > Get ( ) { return _vals ; } }","Using NInject , resolving IEnumerable < T > fails when injecting a a ctor arg , but not when doing Get < IEnumerable < T > > ( )" "C_sharp : I understand that enumerators and the yield keyword can be used to help with async/staggered operations , as you can call MoveNext ( ) to run the next block of code.However , I do n't really understand what that Enumerator object is . Where does the memory in use of the scope of the Enumerator go ? If you do n't MoveNext ( ) an Enumerator all the way , does it get GC 'd eventually ? Basically , I 'm trying to keep my GC hits down , as I am potentially using a LOT of Enumerators and GC can be an issue inside Unity , especially due to the older version of Mono it uses.I have tried to profile this but ca n't wrap my head around them still . I do n't understand the scoping/referencing that happens with Enumerators . I also do n't understand if Enumerators are created as Objects when you create one from a function that yields.The following example shows my confusion better : // Example enumeratorIEnumerator < bool > ExampleFunction ( ) { SomeClass heavyObject = new SomeClass ( ) ; while ( heavyObject.Process ( ) ) { yield return true ; } if ( ! heavyObject.Success ) { yield return false ; } // In this example , we 'll never get here - what happens to the incomplete Enumerator // When does heavyObject get GC 'd ? heavyObject.DoSomeMoreStuff ( ) ; } // example call - Where does this enumerator come from ? // Is something creating it with the new keyword in the background ? IEnumerator < bool > enumerator = ExampleFunction ( ) ; while ( enumerator.MoveNext ( ) ) { if ( ! enumerator.Current ) { break ; } } // if enumerator is never used after this , does it get destroyed when the scope ends , or is it GC 'd at a later date ?",How does GC work with IEnumerator and yield ? "C_sharp : Just created an acc on SO to ask this : ) Assuming this simplified example : building a web application to manage projects ... The application has the following requirements/rules.1 ) Users should be able to create projects inserting the project name.2 ) Project names can not be empty.3 ) Two projects ca n't have the same name . I 'm using a 4-layered architecture ( User Interface , Application , Domain , Infrastructure ) .On my Application Layer i have the following ProjectService.cs class : On my Domain Layer , i have the Project.cs class and the IProjectRepository.cs interface : On my Infrastructure layer , i have the implementation of IProjectRepository which does the actual querying ( the code is irrelevant ) .I do n't like two things about this design:1 ) I 've read that the repository interfaces should be a part of the domain but the implementations should not . That makes no sense to me since i think the domain should n't call the repository methods ( persistence ignorance ) , that should be a responsability of the services in the application layer . ( Something tells me i 'm terribly wrong . ) 2 ) The process of creating a new project involves two validations ( not null and not duplicate ) . In my design above , those two validations are scattered in two different places making it harder ( imho ) to see whats going on.So , my question is , from a DDD perspective , is this modelled correctly or would you do it in a different way ? public class ProjectService { private IProjectRepository ProjectRepo { get ; set ; } public ProjectService ( IProjectRepository projectRepo ) { ProjectRepo = projectRepo ; } public void CreateNewProject ( string name ) { IList < Project > projects = ProjectRepo.GetProjectsByName ( name ) ; if ( projects.Count > 0 ) throw new Exception ( `` Project name already exists . `` ) ; Project project = new Project ( name ) ; ProjectRepo.InsertProject ( project ) ; } } public class Project { public int ProjectID { get ; private set ; } public string Name { get ; private set ; } public Project ( string name ) { ValidateName ( name ) ; Name = name ; } private void ValidateName ( string name ) { if ( name == null || name.Equals ( string.Empty ) ) { throw new Exception ( `` Project name can not be empty or null . `` ) ; } } } public interface IProjectRepository { void InsertProject ( Project project ) ; IList < Project > GetProjectsByName ( string projectName ) ; }","In a DDD approach , is this example modelled correctly ?" "C_sharp : This bothers me a lot and I find I write stupid bugs when combined with Intellisense ( VS 2008 Pro ) : Did you catch it ? I certainly did n't until IsAction never changed , causing bugs.Intellisense somehow converted `` isA < tab > '' to `` IsAction '' for me which means the property Foo.IsAction is always false regardless of the constructor input . Just brilliant.I have to say that I particularly hate the `` implicit this '' ( I do n't know if that has a formal name ) and I would like to turn it off so it never assumes it . Is there a way to do this ? This also applies in calling static methods of the same class.Alternatively , what naming conventions avoid this little problem ? The property must remain `` IsAction '' so it has to be a convention on the constructor parameter name . Oddly enough , if I name it with the exact matching spelling then this.IsAction = IsAction ; works out correctly.The problem is n't case-sensitive languages but the implicitness of this . Now that I think about it , this also more of a VS 2008 Pro question than a C # . I can live with code already written without the this but I do n't want to write new code without it which means telling InNoldorin 's answer got me thinking.Now that I think about it , this also more of a VS 2008 question than a C # . I can live with code already written without the this ( though I do change it if I 'm in there mucking around ) but I do n't want to write new code without it which means telling Intellisense to stop doing it . Can I tell Intellisense to knock it off ? class Foo { public Foo ( bool isAction ) { this.IsAction = IsAction ; } public bool IsAction { get ; private set ; } }",How do I disable the implicit `` this '' in C # ? "C_sharp : We are using Json.net for serialization . and we want to allow pretty much any kind of user defined class/message to be serializable.One thing that Json.net can not support out of the box is if you store an int , float or a decimal in an object field.e.g.if I store an int , float or decimal in the Something field , it will be deserialized into either a long or a double ( as json.net can not do anything more than guess the type of the primitive in the json ( `` foo '' :123 < - int or long ? ) Im completely aware that I can use a correct type on the property and set various hints.But I want to solve this for any random class/message.My current approach is a custom JsonConverter that deals with the above types and then serializes them into a surrogate type , which holds the value as a string and a discriminator for what type this is.And then on ReadJson I turn that back into the correct type.There is a lot of overheat for doing this.especially for the typename of the surrogate type . `` foo.bar.baz.PrimitiveSurrogate , mylib '' Can I customize how this typename is stored ? e.g . if I want to apply aliases to some specific types ? Are there other approaches ? I could serialize the whole thing into a special string instead , which would be smaller , but then again , that feels iffy.So what are my options here if I want to keep primitives with their correct type when stored in an untyped structure ? [ Edit ] Normal Json : vs.Our current surrogate version : I could replace V and T with just ` `` V '' : '' 123L '' and parse the suffix , as we only store int , float and decimal in that type , so we can easily have a hardcoded descriminator.But , that still doesnt get rid of the $ type for the surrogate itself , I would like to atleast shorten that to something like ` `` $ type '' : '' Surrogate '' or something in that direction . [ Edit again ] I 've got it down to : But I 'd really want to get rid of the long typename and replace with an alias somehow . [ Edit again again ] I 've got it down to this now : That good enough imo.We do n't need to interop with any other json system , its just our framework in both ends so the made up format works even if it is not pretty . public class SomeMessage { public object Something { get ; set ; } } { `` foo '' :123 } { `` foo '' : { `` $ type '' : '' Akka.Serialization.PrimitiveSurrogate , Akka '' , `` V '' : '' 123 '' , `` T '' :1 } } { `` $ type '' : '' Akka.Util.PrimitiveSurrogate , Akka '' , '' V '' : '' F123.456 '' } { `` $ '' : '' M123.456 '' }","Surrogate int , float and decimal using Json.NET" "C_sharp : This is confusing , as I 'm getting seemingly contradictive errors.I 'm using generics , constraining T to Something , then constraining U to AnOperation < Something > . I expected that an object AnOperation < Something > is from now on considered of type U . But , I 'm getting errors : Can not implicitly convert type 'ConsoleApp1.AnOperation < T > ' to ' U'That 's weird . Well , i tried explicitly casting it to U , then I got this error : Can not convert type 'ConsoleApp1.AnOperation < T > ' to ' U ' which also stated Cast is redundantWhat 's happening here ? Edit : I 'm trying to understand what is the problem in the language level , not looking for a workaround on an actual problem . namespace ConsoleApp1 { class Program { static void Main ( string [ ] args ) { } } class MyClass < T , U > where T : Something where U : AnOperation < Something > { public U GetAnOperationOfSomething ( ) { AnOperation < T > anOperation = new AnOperation < T > ( ) ; return anOperation ; // Can not implicitly convert type 'ConsoleApp1.AnOperation < T > ' to ' U ' // return ( U ) anOperation ; // Can not convert type 'ConsoleApp1.AnOperation < T > ' to ' U ' also Cast is redundant } } public class Something { } public class AnOperation < T > where T : Something { } }",Trying to utilize combination of generic parameters "C_sharp : I am using ASP.NET.Core to embed a web server into a large legacy desktop application . My middleware components need to reference pre-existing application objects.With difficulty I have got this working using the native DI container , but the resulting code is extraordinarily obtuse and opaque.What I would really like to do , is to explicitely inject the dependencies , which are specific pre-existing object instances , through constructor parameters . The auto-magic of the DI container is n't giving me any benefits , just a lot of pain ! Is it possible to use ASP.NET.Core without the DI Container ? Here 's some simplified code to illustrate my current solution : Startup and application code : Can this sample code be refactored to eliminate the DI container ? class Dependency { public string Text { get ; } public Dependency ( string text ) = > Text = text ; } class MyMiddleware { private readonly RequestDelegate _next ; private readonly Dependency _dep1 ; private readonly Dependency _dep2 ; public MyMiddleware ( RequestDelegate next , Dependency dep1 , Dependency dep2 ) { _next = next ; _dep1 = dep1 ; _dep2 = dep2 ; } public Task InvokeAsync ( HttpContext context ) { return context.Response.WriteAsync ( _dep1.Text + _dep2.Text ) ; } } class Startup { private readonly Dependency _dep1 ; private readonly Dependency _dep2 ; public Startup ( Dependency dep1 , Dependency dep2 ) { _dep1 = dep1 ; _dep2 = dep2 ; } public void Configure ( IApplicationBuilder appBuilder ) { appBuilder.UseMiddleware < MyMiddleware > ( _dep1 , _dep2 ) ; } } public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; var dep1 = new Dependency ( `` Hello `` ) ; var dep2 = new Dependency ( `` World '' ) ; int port = 5000 ; StartWebServer ( port , dep1 , dep2 ) ; Process.Start ( $ '' http : //localhost : { port } '' ) ; } void StartWebServer ( int port , Dependency dep1 , Dependency dep2 ) { IWebHostBuilder builder = new WebHostBuilder ( ) ; builder.UseUrls ( $ '' http : //0.0.0.0 : { port } / '' ) ; builder.UseKestrel ( ) ; builder.ConfigureServices ( servicesCollection = > servicesCollection.AddSingleton ( new Startup ( dep1 , dep2 ) ) ) ; builder.UseStartup < Startup > ( ) ; IWebHost webHost = builder.Build ( ) ; var task = webHost.StartAsync ( ) ; } }",Can ASP.NET.Core be used without the DI Container "C_sharp : The following code allows me to store a value for each type T : I can store as many values as there are types and the compiler does n't know before-head what types I 'm going to use.How and where are those static field values stored ? Update : Obviously it 's stored in memory , but I want to know about this memory . Is it heap ? Is it some special CLR memory ? How is it called ? What else is stored that way ? Update 2 : JITter generates a single implementation MyDict < __Canon > for all reference type arguments of MyDict < T > . Yet , the values are stored separately . I guess that there is still some per-type-argument structure for each type argument , and while thw vtable is linked to the JITted MyDict < __Canon > , the fields are separate . Am I right ? public static class MyDict < T > { public static T Value ; }",Where does .Net store the values of the static fields of generic types ? "C_sharp : Consider the following code : Let 's assume that this MyReadAsync method is directly called from an event handler of a WPF application , as follows : Here are my questions : Using ConfigureAwait ( false ) allows that the portion of the code that starts with the line this.count += read ; can be executed on any threadpool thread , correct ? For two separate calls of MyReadAsync , there is no guarantee that the portion of the code that starts with this.count += read ; will be executed on the same thread , correct ? If 1 & 2 are correct , then it seems to me that the code this.count += read ; should be protected with appropriate thread synchronization primitives , correct ? using System.IO ; using System.Threading.Tasks ; public class MyClass { private int count ; public async Task < int > MyReadAsync ( Stream stream , byte [ ] buffer ) { var read = await stream.ReadAsync ( buffer , 0 , buffer.Length ) .ConfigureAwait ( false ) ; this.count += read ; return read ; } } private async void OnWhatever ( object sender , EventArgs args ) { await myObject.MyReadAsync ( this.stream , this.buffer ) ; }",Thread synchronization with Task.ConfigureAwait ( false ) "C_sharp : For some reason Microsoft decided to not support simple concat in EF5.e.g.This will throw if foo.id or foo.bar are numbers.The workaround I 've found is apparently this pretty peice of code : Which works fine , but is just horrid to look at.So , is there some decent way to accomplish this with cleaner code ? I 'm NOT interested in doing this client side , so no .AsEnumerable ( ) answers please . Select ( foo = > new { someProp = `` hello '' + foo.id + `` / '' + foo.bar } Select ( foo = > new { someProp = `` hello '' + SqlFunctions.StringConvert ( ( double ? ) foo.id ) .Trim ( ) + `` / '' + SqlFunctions.StringConvert ( ( double ? ) foo.bar ) .Trim ( ) }",Best way to concat strings and numbers in SQL server using Entity Framework 5 ? "C_sharp : First of all , sorry for my bad English ... I hope you 'll understand what I want to say.I have a problem with a little code where I need to get the value of class ' properties . ( That 's not my full project , but the concept of what I want to do . And with this simple code , I 'm blocked . ) There is the code : ( This sample works correctly . ) But I want to replace Group.sub with a dynamic accessing ( like the foreach with GetField ( Var ) where it works ) . I tried a lot of combinations , but I have n't found any solutions.oror So I think you understand . I would like to give the instance of object Group.sub dynamically . Because , on my full project , I have a lot of subclasses . Any ideas ? using System ; using System.Reflection ; class Example { public static void Main ( ) { test Group = new test ( ) ; BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static ; Group.sub.a = `` allo '' ; Group.sub.b = `` lol '' ; foreach ( PropertyInfo property in Group.GetType ( ) .GetField ( `` sub '' ) .FieldType.GetProperties ( bindingFlags ) ) { string strName = property.Name ; Console.WriteLine ( strName + `` = `` + property.GetValue ( Group.sub , null ) .ToString ( ) ) ; Console.WriteLine ( `` -- -- -- -- -- -- -- - '' ) ; } } } public class test { public test2 sub = new test2 ( ) ; } public class test2 { public string a { get ; set ; } public string b { get ; set ; } } property.GetValue ( property.DeclaringType , null ) property.GetValue ( Group.GetType ( ) .GetField ( `` sub '' ) , null ) property.GetValue ( Group.GetType ( ) .GetField ( `` sub '' ) .FieldType , null )",C # GetValue of PropertyInfo with SubClasses "C_sharp : The LOD description I 've seen ( for example , Wikipedia , C2 Wiki ) talk about not calling methods . To quote Wikipedia : The Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects : - O itself - M 's parameters - any objects created/instantiated within M - O 's direct component objects - a global variable , accessible by O , in the scope of M But what about accessing properties , variables or enums ? For example , given this : Are any/all of these LOD violations ? ( Ignore the direct variable access for now , if you can.. ) I would n't do the first two ( whether 'official ' violations or not ) , not quite so sure about the enum though . class FirstClass { public SecondClass GetRelatedClass ( ) { return new SecondClass ( ) ; } public enum InnerEnum { Violated , NotViolated } } class SecondClass { public int Property { get ; set ; } public string _variable = `` Danny Demeter '' ; } void Violate ( FirstClass first ) { SecondClass second = first.GetRelatedClass ( ) ; var x = second.Property ; var y = second._variable ; var z = FirstClass.InnerEnum.Violated ; }",Does the Law of Demeter only apply to methods ? "C_sharp : How can I achieve a join and a where in C # MVC using something like Linq or EF Join ? This is the equivalent SQL I am trying to achieve.This method should return a list of the promotions for the user . First , I get a list of all of the promotions , then I get the composite list of claimed promotions for the user . This is what I have so far.I realize there are a lot of problems here . I 'm trying to learn Linq and Entity Framework , but I do n't know how to add the where clause to an IList or if there is an easier way to accomplish this . It seems to me like there would be a way to filter the promotion list where it contains the Promotion.objectId in the promosClaimed list , but I do n't know the syntax . select * from promotion PJOIN PromotionsClaimed PCon PC.PromotionId = P.objectidwhere PC.userId = @ USERID public IList < Promotion > GetRewardsForUser ( string userId ) { //a list of all available promotions IList < Promotion > promos = _promotionLogic.Retrieve ( ) ; //contains a list of Promotion.objectIds for that user IList < PromotionsClaimed > promosClaimed = _promotionsClaimedLogic.RetrieveByCriteria ( t = > t.userId == userId ) ; //should return a list of the Promotion name and code for the rewards claimed by user , but a complete list of Promotion entities would be fine var selectedPromos = from promo in promos join promoClaimed in promosClaimed on promo.objectId equals promoClaimed.PromotionId select new { PromoName = promo.Name , PromoCode = promo.Code } ; return selectedPromos ; }",How to use Join and Where to return an IList ? "C_sharp : I am trying to create a Task pipeline/ordered scheduler in combination with using TaskFactory.FromAsync.I want to be able to fire off web service requests ( using FromAsync to use I/O completion ports ) but maintain their order and only have a single one executing at any one time.At the moment I do not use FromAsync so I can do TaskFactory.StartNew ( ( ) = > api.DoSyncWebServiceCall ( ) ) and rely on the OrderedTaskScheduler used by the TaskFactory to ensure that only one request is outstanding.I assumed that this behaviour would stay when using the FromAsync method but it does not : All of these beginGetStuff methods get called within the FromAsync call ( so although they are dispatched in order but there are n api calls occurring at the same time ) .There is an overload of FromAsync that takes a TaskScheduler : but the docs say : The TaskScheduler that is used to schedule the task that executes the end method.And as you can see , it takes the already constructed IAsyncResult , not a Func < IAsyncResult > .Does this call for a custom FromAsync method or am I missing something ? Can anyone suggest where to start on this implementation ? Cheers , EDIT : I want to abstract this behaviour away from the caller so , as per the behaviour of TaskFactory ( with a specialized TaskScheduler ) , I need the Task to be returned immediately - this Task will not only encapsulate the FromAsync Task but also the queueing of that task whilst it awaits its turn to execute.One possible solution : However , this utilizes a thread whilst the FromAsync call is occurring . Ideally I 'd not have to do that . TaskFactory < Stuff > taskFactory = new TaskFactory < Stuff > ( new OrderedTaskScheduler ( ) ) ; var t1 = taskFactory.FromAsync ( ( a , s ) = > api.beginGetStuff ( a , s ) , a = > api.endGetStuff ( a ) ) ; var t2 = taskFactory.FromAsync ( ( a , s ) = > api.beginGetStuff ( a , s ) , a = > api.endGetStuff ( a ) ) ; var t3 = taskFactory.FromAsync ( ( a , s ) = > api.beginGetStuff ( a , s ) , a = > api.endGetStuff ( a ) ) ; public Task FromAsync ( IAsyncResult asyncResult , Action < IAsyncResult > endMethod , TaskCreationOptions creationOptions , TaskScheduler scheduler ) class TaskExecutionQueue { private readonly OrderedTaskScheduler _orderedTaskScheduler ; private readonly TaskFactory _taskFactory ; public TaskExecutionQueue ( OrderedTaskScheduler orderedTaskScheduler ) { _orderedTaskScheduler = orderedTaskScheduler ; _taskFactory = new TaskFactory ( orderedTaskScheduler ) ; } public Task < TResult > QueueTask < TResult > ( Func < Task < TResult > > taskGenerator ) { return _taskFactory.StartNew ( taskGenerator ) .Unwrap ( ) ; } }",TPL FromAsync with TaskScheduler and TaskFactory "C_sharp : I wrote a C # class that is populating a `` List of List of doubles '' with some data ( does n't matter what the data is , for now it can just be some garbage : ) ) , for testing purposes : Here is the code : I compared the speed of execution of this code with the following : ( replacing the List of double by a Tuple ) Turns out that using the Tuple seems to be considerably faster . I ran this piece of code for different List sizes ( from 200,000 elements - > 5 millions elements in the list ) and here are the results I get : I can not really get my head around this one . How come I get such a significant difference ? Using a Tuple that stores object of the same type ( doubles here ) does n't make much sense . I 'd rather use a List/array to do that : what am I doing wrong ? Is there a way I can make case # 1 run as fast/faster than case # 2 ? Thanks ! class test { public test ( ) { _myListOfList = new List < List < double > > ( 1000000 ) ; } public void Run ( ) { for ( int i = 0 ; i < _myListOfList.Capacity ; i++ ) { _myListOfList.Add ( new List < double > ( 3 ) { i , 10*i , 100*i } ) ; //Populate the list with data } } private List < List < double > > _myListOfList ; } class test { public test ( ) { _myListOfTuple = new List < Tuple < double , double , double > > ( 1000000 ) ; } public void Run ( ) { for ( int i = 0 ; i < _myListOfTuple.Capacity ; i++ ) { _myListOfTuple.Add ( new Tuple < double , double , double > ( i , 10 * i , 100 * i ) ) ; //Populate the list with data } } private List < Tuple < double , double , double > > _myListOfTuple ; }",Why is using a Tuple faster than a List in this example ? C_sharp : Consider the following pseudo code that implements the MVP pattern : And here 's an alternative implementation of MVP pattern : Which one is more correct implementation of MVP pattern ? Why ? interface Presenter { void onSendClicked ( ) ; } interface View { String getInput ( ) ; void showProgress ( ) ; void hideProgress ( ) ; } class PresenterImpl implements Presenter { // ... ignore other implementations void onSendClicked ( ) { String input = view.getInput ( ) ; view.showProgress ( ) ; repository.store ( input ) ; view.hideProgress ( ) ; } } class ViewImpl implements View { // ... ignore other implementations void onButtonClicked ( ) { presenter.onSendClicked ( ) ; } String getInput ( ) { return textBox.getInput ( ) ; } void showProgress ( ) { progressBar.show ( ) ; } void hideProgress ( ) { progressBar.hide ( ) ; } } interface Presenter { void saveInput ( String input ) ; } interface View { void showProgress ( ) ; void hideProgress ( ) ; } class PresenterImpl implements Presenter { // ... ignore other implementations void saveInput ( String input ) { view.showProgress ( ) ; repository.store ( input ) ; view.hideProgress ( ) ; } } class ViewImpl implements View { // ... ignore other implementations void onButtonClicked ( ) { String input = textBox.getInput ( ) ; presenter.saveInput ( intput ) ; } void showProgress ( ) { progressBar.show ( ) ; } void hideProgress ( ) { progressBar.hide ( ) ; } },MVP design pattern best practice "C_sharp : I 'm using the basic template that VS 2019 provides with the weather forecasting data when creating a ASP.NET WebAPI project and added some very basic authentication with user login and support for JWT Token which all works fine.I 'm trying to create a blazor client project to consume the API and display the data on the page . AFAIK Blazor does n't support localstorage so I 'm using Blazored LocalStorage package to give me this ability . My problem stems from fact using JS via OnInitializedAsync ( ) is not possible in server-side blazor ( https : //github.com/aspnet/AspNetCore/issues/13396 ) as a result I 'm not sure how one is suppose to consume these web api calls . As this will produce a null reference exceptionOne suggestion was to use OnAfterRenderAsync ( ) method to call them as JS would be ready by then . Which semi-works but obviously the UI does n't match because it needs to be refreshed - however to manually refresh it seems I have to call StateHasChanged ( ) ; which in turn calls OnAfterRender method again and as a result I had to put a check but this ultimately feels incredibly hacky.What is the correct way to consume an API with authnetication and display the data correctly on the client side ? Side question HttpClient does n't seem to be injectable in server-side and it 's recommended to use HttpClientFactory - is it a good idea to create a client on every request or make a singleton and re-use thoughout the client project ? protected override async Task OnInitializedAsync ( ) { var client = HttpFactory.CreateClient ( ) ; var token = await LocalStorage.GetItemAsync < string > ( `` authToken '' ) ; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ( `` Bearer '' , token ) ; var response = await client.GetAsync ( `` url/WeatherForecast '' ) ; var str = await response.Content.ReadAsStringAsync ( ) ; Items = JsonConvert.DeserializeObject < IEnumerable < WeatherForecast > > ( str ) ; } private bool hasRendered ; protected override async Task OnAfterRenderAsync ( bool _ ) { if ( ! hasRendered ) return ; var client = HttpFactory.CreateClient ( ) ; var token = await LocalStorage.GetItemAsync < string > ( `` authToken '' ) ; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ( `` Bearer '' , token ) ; var response = await client.GetAsync ( `` https : //url/WeatherForecast '' ) ; var str = await response.Content.ReadAsStringAsync ( ) ; Items = JsonConvert.DeserializeObject < IEnumerable < WeatherForecast > > ( str ) ; StateHasChanged ( ) ; hasRendered = true ; }",Consuming WebAPI in blazor with authentication "C_sharp : I am uploading to Google Cloud Storage using a service account . I need to be able to display the progress of the upload in the WPF UI . Now , Whenever I try to update the ProgressBar.Value , it 's not working , but when I just have the bytesSent written in Console , I can see the progress . public async Task < bool > UploadToGoogleCloudStorage ( string bucketName , string token , string filePath , string contentType ) { var newObject = new Google.Apis.Storage.v1.Data.Object ( ) { Bucket = bucketName , Name = System.IO.Path.GetFileNameWithoutExtension ( filePath ) } ; var service = new Google.Apis.Storage.v1.StorageService ( ) ; try { using ( var fileStream = new FileStream ( filePath , FileMode.Open ) ) { var uploadRequest = new ObjectsResource.InsertMediaUpload ( service , newObject , bucketName , fileStream , contentType ) ; uploadRequest.OauthToken = token ; ProgressBar.Maximum = fileStream.Length ; uploadRequest.ProgressChanged += UploadProgress ; uploadRequest.ChunkSize = ( 256 * 1024 ) ; await uploadRequest.UploadAsync ( ) .ConfigureAwait ( false ) ; service.Dispose ( ) ; } } catch ( Exception ex ) { Console.WriteLine ( ex.Message ) ; throw ex ; } return true ; } private void UploadProgress ( IUploadProgress progress ) { switch ( progress.Status ) { case UploadStatus.Starting : ProgressBar.Minimum = 0 ; ProgressBar.Value = 0 ; break ; case UploadStatus.Completed : System.Windows.MessageBox.Show ( `` Upload completed ! `` ) ; break ; case UploadStatus.Uploading : //Console.WriteLine ( progress.BytesSent ) ; - > This is working if I do n't call the method below . UpdateProgressBar ( progress.BytesSent ) ; break ; case UploadStatus.Failed : Console.WriteLine ( `` Upload failed `` + Environment.NewLine + progress.Exception.Message + Environment.NewLine + progress.Exception.StackTrace + Environment.NewLine + progress.Exception.Source + Environment.NewLine + progress.Exception.InnerException + Environment.NewLine + `` HR-Result '' + progress.Exception.HResult ) ; break ; } } private void UpdateProgressBar ( long value ) { Dispatcher.Invoke ( ( ) = > { this.ProgressBar.Value = value ; } ) ; }",Asynchronous Google File Upload with Progress Bar WPF "C_sharp : I have been looking over several examples of backgroundworkers and I ran across code that looks similar to thisI have not been using the `` using '' statment in my code like this . I ran across something similar while using the Code Rush trial , which made me come back to this code and question if i should be doing this or not . Please help me understand if/why this would be best practice . Thanks . public class MyClass { public MyClass ( ) { using ( BackgroundWorker _Worker = new BackgroundWorker { WorkerReportsProgress = true } ) { _Worker.DoWork += ( s , args ) = > { ... } ; } _Worker.RunWorkerAsync ( ) ; } }",using statement for background worker "C_sharp : I 'm in my first couple of days using Linq in C # , and I 'm curious to know if there is a more concise way of writing the following.I know that if I were to want to check the existence of a value in the field of a single table , I could just use the following : But I 'm curious to know if there is a way to do the lambda technique , but where it would satisfy the first technique 's conditions across those two tables.Sorry for any mistakes or clarity , I 'll edit as necessary . Thanks in advance . MyEntities db = new MyEntities ( ConnString ) ; var q = from a in db.TableA join b in db.TableB on a.SomeFieldID equals b.SomeFieldID where ( a.UserID == CurrentUser & & b.MyField == Convert.ToInt32 ( MyDropDownList.SelectedValue ) ) select new { a , b } ; if ( q.Any ( ) ) { //snip } if ( db.TableA.Where ( u = > u.UserID == CurrentUser ) .Any ( ) ) { //snip }",Any Way to Use a Join in a Lambda Where ( ) on a Table < > ? "C_sharp : I 'm looking for a library/module/package with which I could create and sign X.509 certificates , with the ability to conditionally add custom v3 extensions – which can be fairly complicated ; for example , this bletchful OpenSSL.cnf snippet used by Kerberos PKINIT , just to represent foo @ EXAMPLE.ORG : Out of everything I have found for languages I know ( that being Perl , Python , Ruby , PHP , Bash , and some C # ) , using openssl from command line with automatically generated .cnf files ... which is an ugly process . Is there a better way to do it ? ( Ruby 's 'openssl ' looked very nice at first , but then I got to PKINIT ... ) [ v3_extensions ] subjectAltName = email : foo @ example.org , otherName : pkinitSan ; SEQUENCE : krb_princ_name_1 [ krb_princ_name_1 ] realm = EXP:0 , GeneralString : EXAMPLE.ORG principal_name = EXP:1 , SEQUENCE : krb_princ_seq_1 [ krb_princ_seq_1 ] name_type = EXP:0 , INTEGER:1 name_string = EXP:0 , SEQUENCE : krb_principal_1 [ krb_principal_1 ] princ0 = GeneralString : foo",X.509 libraries "C_sharp : So I have a Blog object which has a list of tag objects ( List < Tag > ) .I 'm trying to create a method that takes a list of tags and returns a list of blogs that contain all the tags in the passed in list.I was able to make a method that will return a list of blogs if it matches one tag , but not a list of tags.to do that I have thisBut I ca n't figure out how to do something like thisIs there any way to do this ? Thank you ! I 'm using LINQ to Entities entities.Blogs.Where ( b = > b.Tags.Any ( t = > t.Name == tagName ) ) entities.Blogs.Where ( b = > b.Tags.Any ( t = > t.Name == tags [ 0 ] AND t.Name == tags [ 1 ] AND t.Name == tags [ 2 ] etc ... ... . ) )",How to do WHERE IN in linq "C_sharp : So I 've been working on a pet project for the Windows Store , and have hit a bit of a stumbling block : keyboard events refuse to fire . I 've tried forcing focus onto the main page , tried forcing focus onto the Grid , but nothing seems to help . Anyone run into issues like this ? My google-fu has failed me.Relevant code : XAML : C # : < Page x : Class= '' PlatformTD.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' using : PlatformTD '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' > < Grid Background= '' { StaticResource ApplicationPageBackgroundThemeBrush } '' Name= '' LayoutRoot '' > < Canvas HorizontalAlignment= '' Stretch '' VerticalAlignment= '' Stretch '' Name= '' MainCanvas '' x : FieldModifier= '' public '' SizeChanged= '' MainCanvas_SizeChanged '' Loaded= '' MainCanvas_Loaded '' / > < /Grid > < /Page > public MainPage ( ) { this.InitializeComponent ( ) ; MainCanvas.KeyDown += MainPage_KeyDown ; MainCanvas.KeyUp += MainPage_KeyUp ; KeyDown += MainPage_KeyDown ; KeyUp += MainPage_KeyUp ; LayoutRoot.KeyDown += MainPage_KeyDown ; LayoutRoot.KeyUp += MainPage_KeyUp ; } private void MainPage_KeyUp ( object sender , KeyRoutedEventArgs e ) { // breakpoint here to catch when event fires // does stuff } private void MainPage_KeyDown ( object sender , KeyRoutedEventArgs e ) { // breakpoint here to catch when event fires // does stuff }",Keyboard events not firing in RT app "C_sharp : MSDN states of the property TypeId that : As implemented , this identifier is merely the Type of the attribute . However , it is intended that the unique identifier be used to identify two attributes of the same type.Is the intended use however , to distinguish between individual attribute instances ( e.g . those associated with different instances of the class to which they are applied ) or between attributes which have the same type but due to their property values are semantically different ? For example , say I had the following : Should I implement TypeId as Or public sealed class AmpVolume : System.Attribute { public int MaxVolume { get ; set ; } public AmpVolume ( int maxvolume ) { MaxVolume = maxvolume ; } } [ AmpVolume ( 11 ) ] public class SpinalTapGuitarAmp { } [ AmpVolume ( 11 ) ] public class SpinalTapBassAmp { } [ AmpVolume ( 10 ) ] public class RegularAmp { } get { return ( object ) this ; //TypeId identifies every individual instance of the attribute } get { return ( object ) MaxVolume ; //If we compare two AmpVolume attributes , they should be the same if the volume is the same , right ? }",Should the TypeIds of two attributes which are semantically identical be different or the same ? "C_sharp : I asked this question and got this interesting ( and a little disconcerting ) answer.Daniel states in his answer ( unless I 'm reading it incorrectly ) that the ECMA-335 CLI specification could allow a compiler to generate code that throws a NullReferenceException from the following DoCallback method.He says that , in order to guarantee a NullReferenceException is not thrown , the volatile keyword should be used on _Callback or a lock should be used around the line local = Callback ; .Can anyone corroborate that ? And , if it 's true , is there a difference in behavior between Mono and .NET compilers regarding this issue ? EditHere is a link to the standard.UpdateI think this is the pertinent part of the spec ( 12.6.4 ) : Conforming implementations of the CLI are free to execute programs using any technology that guarantees , within a single thread of execution , that side-effects and exceptions generated by a thread are visible in the order specified by the CIL . For this purpose only volatile operations ( including volatile reads ) constitute visible side-effects . ( Note that while only volatile operations constitute visible side-effects , volatile operations also affect the visibility of non-volatile references . ) Volatile operations are specified in §12.6.7 . There are no ordering guarantees relative to exceptions injected into a thread by another thread ( such exceptions are sometimes called `` asynchronous exceptions '' ( e.g. , System.Threading.ThreadAbortException ) . [ Rationale : An optimizing compiler is free to reorder side-effects and synchronous exceptions to the extent that this reordering does not change any observable program behavior . end rationale ] [ Note : An implementation of the CLI is permitted to use an optimizing compiler , for example , to convert CIL to native machine code provided the compiler maintains ( within each single thread of execution ) the same order of side-effects and synchronous exceptions.So ... I 'm curious as to whether or not this statement allows a compiler to optimize the Callback property ( which accesses a simple field ) and the local variable to produce the following , which has the same behavior in a single thread of execution : The 12.6.7 section on the volatile keyword seems to offer a solution for programmers wishing to avoid the optimization : A volatile read has `` acquire semantics '' meaning that the read is guaranteed to occur prior to any references to memory that occur after the read instruction in the CIL instruction sequence . A volatile write has `` release semantics '' meaning that the write is guaranteed to happen after any memory references prior to the write instruction in the CIL instruction sequence . A conforming implementation of the CLI shall guarantee this semantics of volatile operations . This ensures that all threads will observe volatile writes performed by any other thread in the order they were performed . But a conforming implementation is not required to provide a single total ordering of volatile writes as seen from all threads of execution . An optimizing compiler that converts CIL to native code shall not remove any volatile operation , nor shall it coalesce multiple volatile operations into a single operation . class MyClass { private Action _Callback ; public Action Callback { get { return _Callback ; } set { _Callback = value ; } } public void DoCallback ( ) { Action local ; local = Callback ; if ( local == null ) local = new Action ( ( ) = > { } ) ; local ( ) ; } } if ( _Callback ! = null ) _Callback ( ) ; else new Action ( ( ) = > { } ) ( ) ;",Is there a race condition in this common pattern used to prevent NullReferenceException ? "C_sharp : I have a MVC Controller which provides a simple ViewAs you can see from above what I need to implement is a method that gets the html generated by Index ( ) , zip it and return it as a file that can be downloaded.I know how to zip , but I do n't know how to get the html . public class MyController : Controller { [ HttpGet ] public ActionResult Index ( ) { return View ( ) ; } [ HttpGet ] public ActionResult ZipIndex ( ) { // Get the file returned bu Index ( ) and zip it return File ( /* zip stream */ ) ; } }",Get the generated html file inside an action "C_sharp : I have a data structure which consists of pairs of values , the first of which is an integer and the second of which is an alphanumeric string ( which may begin with digits ) : A table of these would comprise up to 100,000 rows . I 'd like to provide a lookup function in which the user can look up either the number ( as if it were a string ) , or pieces of the string . Ideally the lookup will be `` live '' as the user types ; after each keystroke ( or maybe after a brief delay ~250-500 ms ) a new search will be done to find the most likely candidates . So , for example searching on1 will return 15 APPLES , 16 APPLE COMPUTER , 17 ORANGE , and291 156TH ELEMENT15 will narrow the search to 15 APPLES , 291 156TH ELEMENTAP will return 15 APPLES and 16 APPLE COMPUTER ( ideally , but not required ) ELEM will return 291 156TH ELEMENT.I was thinking about using two Dictionary < string , string > s since ultimately the ints are being compared as strings -- one will index by the integer part and the other by the string part . But really searching by substring should n't use a hash function , and it seems wasteful to use twice the memory that I feel like I should need.Ultimately the question is , is there any well-performing way to text search two large lists simultaneously for substrings ? Failing that , how about a SortedDictionary ? Might increase performance but still would n't solve the hash problem.Thought about creating a regex on the fly , but I would think that would perform terribly.I 'm new to C # ( having come from the Java world ) so I have n't looked into LINQ yet ; is that the answer ? EDIT 18:21 EST : None of the strings in the `` Name '' field will be longer than 12-15 characters , if that affects your potential solution . + -- -- -- -- + -- -- -- -- -- -- -- -- -+| Number | Name |+ -- -- -- -- + -- -- -- -- -- -- -- -- -+| 15 | APPLES || 16 | APPLE COMPUTER || 17 | ORANGE || 21 | TWENTY-1 || 291 | 156TH ELEMENT |+ -- -- -- -- + -- -- -- -- -- -- -- -- -+",Which C # data structure allows searching a pair of strings most efficiently for substrings ? "C_sharp : I have the following F # functionIn my C # class I want to call the Fetch F # function mocking out the logger function.So I have the following C # function as the mocker.I 'm trying to call the F # function from a C # class with the following.The problem with FuncConvert.ToFSharpFunc is that takes only one type argument.When I change the Fetch F # logger function to the following it works fine when I use ToFSharpFunc ( Print ) where the C # Print function also takes in one string.Anyone got ideas ? let Fetch logger id = logger `` string1 '' `` string2 '' // search a database with the id and return a result void Print ( string x , string y ) { // do nothing } var _logger = FuncConvert.ToFSharpFunc < string , string > ( Print ) ; var _result = Fetch ( logger , 3 ) ; let Fetch logger id = logger `` string1 '' // search a database with the id and return a result",Call F # function from C # passing function as a parameter "C_sharp : I am aware that the classic way to create a dynamic object is to inherit from DynamicObject . However if I already have a class and I wish to add dynamic properties to subclasses of that then I am stuck.Say I have a class ReactiveObject And I wish to add dynamic properties to it using DynamicObject . So I do thisI thought the easy way to do this might be to create an instance of DynamicObject and proxy the call to that.except that is not going to work because the returned meta object does n't know anything about the methods on MyReactiveObject . Is there any easy way to do this without fully reimplementing DynamicObject . public class MyReactiveObject : ReactiveObject , IDynamicMetaObjectProvider { public DynamicMetaObject GetMetaObject ( Expression parameter ) { ... } } public class MyDynamicObject : DynamicObject { } public class MyReactiveObject : ReactiveObject , IDynamicMetaObjectProvider { MyDynamicObject DynamicObject = new MyDynamicObject ( ) ; public DynamicMetaObject GetMetaObject ( Expression parameter ) { return this.DynamicObject.GetMetaObject ( parameter ) ; } }",How to create a dynamic object via composition rather than inheritence "C_sharp : I am using DDD with CQRS and Event Sourcing.I need to use an Event Store ( specifically this event store ) within my custom implementation of IEventStore to persist and retrieve domain events but I am having difficulties with the approach to take that deals with serialization/deserialization.This is the interface I am implementing : Outside my implementation of IEventStore I can have mappers from every IDomainEvent into some serializable/deserializable EventDto or json string . That 's not a problem.But these are my restrictions : my domain events are immutable objects that implement IDomainEvent ( i.e : no setters ) my domain events are not always easily serializable/deserializable in a generic way . Often they have abstract or interface properties , so the concrete mappers between my domain events and some serializable object such as string json or event DTO are decided outside my IEventStore implementation.My IEventStore implementation needs to be generic in a way that if I add new domain event types , I should not need to touch anything within the IEventStore implementationMy IEventStore implementation can receive injected some specific implementations of IMapper < TSource , TDestination > , so that I could use a them to serialize/deserialize between specific types ( not interfaces ) .This below is my attempt : The problems is mainly , as you can imagine , in the IDomainEventFactory implementation . I need a class that implements the following interface : This class needs to know which specific IDomainEvent does it need to deserialize the resolvedEvent to at runtime . In other words , if the event being retrieved is a json representation of MyThingCreatedEvent maybe I can use a service such as IMapper < ResolvedEvent , MyThingCreatedEvent > . But if the event being retrieved is a json representation of MyThingUpdatedEvent then I would need a service such as IMapper < ResolvedEvent , MyThingUpdatedEvent > . Some approaches came to my mind.OPTION 1 : I thought I could have the IDomainEventFactory implementation use the autofac IComponentContext so that at runtime I could somehow manage to do some _componentContext.Resolve ( theNeededType ) . But I do n't know how to retrieve the IMapper that I need . Maybe this is something possible but I doubt it . OPTION 2 : Maybe I could have some mapping service such as IBetterMapper such asso that my factory can delegate the concern of knowing how to deserialize anything into TDestination . But I would have the same problem : I do n't know how to create a type at runtime from a string , for example , to do something like _myBetterMapper.Map < WhichTypeHere > and there is the additional problem of implementing that Map method , which I guess would require some registration table and based on the type choose one or another specific mapper.I am really stuck with this . Hopefully I get some help from you guys ! : ) UPDATE : I have implemented my own solution and uploaded the project here in my personal repo : https : //gitlab.com/iberodev/DiDrDe.EventStore.Infra.EventStoreThe solution I went with is to keep the event store wrapper agnostic but to provide custom serializer/deserializer at DI registration for those events that are a bit `` special '' . EventStore allows adding custom metadata headers , so I am using some custom headers to specify concrete implementation types on each data stream so that I know where to deserialize when retrieving the persisted events . public interface IEventStore { Task < IEnumerable < IDomainEvent > > GetEventsAsync ( Identity aggregateIdentity , Type aggregateType ) ; Task PersistAsync ( IAggregateRoot aggregateRoot , IEnumerable < IDomainEvent > domainEvents ) ; } public interface IMapper < in TSource , out TDestination > { TDestination Map ( TSource source ) ; // I have implementations of this if needed } public class MyEventStore : IEventStore { private readonly IStreamNameFactory _streamNameFactory ; private readonly IEventStoreConnection _eventStoreConnection ; //this is the Greg Young 's EventStore product that I want to use as database private readonly IDomainEventFactory _domainEventFactory ; private readonly IEventDataFactory _eventDataFactory ; public EventStore ( IStreamNameFactory streamNameFactory , IEventStoreConnection eventStoreConnection , IDomainEventFactory domainEventFactory , IEventDataFactory eventDataFactory ) { _streamNameFactory = streamNameFactory ; _eventStoreConnection = eventStoreConnection ; _domainEventFactory = domainEventFactory ; _eventDataFactory = eventDataFactory ; } public async Task < IEnumerable < IDomainEvent > > GetEventsAsync ( Identity aggregateIdentity , Type aggregateType ) { var aggregateIdentityValue = aggregateIdentity.Value ; var streamName = _streamNameFactory.Create ( aggregateIdentityValue , aggregateType ) ; var streamEventSlice = await _eventStoreConnection.ReadStreamEventsForwardAsync ( streamName , 0 , Int32.MaxValue , false ) ; var domainEvents = streamEventSlice .Events .Select ( x = > _domainEventFactory.Create ( x ) ) ; return domainEvents ; } [ SuppressMessage ( `` ReSharper '' , `` PossibleMultipleEnumeration '' ) ] public async Task PersistAsync ( IAggregateRoot aggregateRoot , IEnumerable < IDomainEvent > domainEvents ) { var numberOfEvents = domainEvents.Count ( ) ; var aggregateRootVersion = aggregateRoot.Version ; var originalVersion = aggregateRootVersion - numberOfEvents ; var expectedVersion = originalVersion - 1 ; var aggregateIdentityValue = aggregateRoot.AggregateIdentity.Value ; var aggregateRootType = aggregateRoot.GetType ( ) ; var streamName = _streamNameFactory.Create ( aggregateIdentityValue , aggregateRootType ) ; var assemblyQualifiedName = aggregateRootType.AssemblyQualifiedName ; var eventsToStore = domainEvents.Select ( x = > _eventDataFactory.Create ( x , assemblyQualifiedName ) ) ; await _eventStoreConnection.AppendToStreamAsync ( streamName , expectedVersion , eventsToStore ) ; } } public interface IDomainEventFactory { IDomainEvent Create ( ResolvedEvent resolvedEvent ) ; } public interface IBetterMapping { TDestination Map < TDestination > ( object source ) where TDestination : class ; }",Serialize and Deserialize domain events to persist and retrieve from Event Store in generic implementation "C_sharp : Background InfoI 'm using the Database-First approach . I created a TextTemplate ( .tt ) file that generates interfaces from the EDMX file , also , I modified the original TextTemplate file included/produced by the EDMX file ( project item ) to have the generated classes implement those interfaces . [ Person ] ( Partial Public Class ) As you can see in the code sample above , I also added a constructor that takes the interface to initialize the Person class ... [ IPerson ] ( Interface ) The CrewMember Class and ICrewMember Inteface contain : boolean properties ( IsCaptain and IsAssigned ) Int PersonID as a property , Int CrewMemberID as a property , and Person Person as Person of course . ( I have tried IPerson Person as well ) .My Intention ; The IssueI intended to use ICollection < ICrewMember > for the Navigation . Then use DTO/Model/ModelView Objects/Classes that Implement those interfaces.When I generated ICollection < InterfaceTEntity > types in the navigation property , I was n't seeing any issues.. with EntityFramework.. until I attempted to update two Entities using the same context : context.CrewMembers and context.People in the same function.The issue I am having/seeing seemed to be with EntityFramework 's Change-Tracking Feature . However , it is actually rooted with asynchronous operations within EntityFramework itself.If I debug and step through the above method , there is no exception , and the database/tables updates properly.. If I run it without catching a debug point before the statement declaring queryPerson.. it will throw an exception ( a misleading exception regarding Person.CrewMembers having to be ICollection < T > ) ..This certainly seems to be a timing issueAttempted Workaround/ Points of InterestI attempted to remove the virtual attribute on the ICollection < > properties ; did n't affect the issue.I attempted to remove Lazy Loading ; did n't affect the issue.I attempted to commit the changes between the queries ; did not affect the issue.I attempted to perform to use FirstAsync < > on query ; but I 'm not sure if I 'm even using it properly.. I 'm still fiddling with this approach . *EDIT/UPDATE - ( misleading ) Exception , Stack Trace , and Target Site*EDIT/UPDATE - QuestionThough to ask this question may be improperly scoping the issue I 'm having ... When using Generic Type interfaces with the ICollection in Navigation Properties of the generated classes , How can/do I handle potentially unsafe threading instances ( in my UpdateCrewmMemberModel method ) that occur within/from EntityFramework ? namespace TestSolution.Domain.Entities { using System ; using System.Collections.Generic ; using TestSolution.Domain.Entities ; public partial class Person : IPerson { public Person ( ) { //this.CrewMembers = new HastSet < CrewMember > ( ) ; this.CrewMembers = new HashSet < ICrewMember > ( ) ; } public Person ( IPerson iPerson ) { this.PersonID = iPerson.PersonID ; this.First = iPerson.First ; this.Last = iPerson.Last ; //this.CrewMembers = new HastSet < CrewMember > ( ) ; this.CrewMembers = new HashSet < ICrewMember > ( ) ; } public int PersonID { get ; set ; } public string First { get ; set ; } public string Last { get ; set ; } //public virtual ICollection < CrewMember > CrewMembers { get ; set ; } public virtual ICollection < ICrewMember > CrewMembers { get ; set ; } } } namespace TestSolution.Domain.Entities { using System ; using System.Collections.Generic ; public interface IPerson { int PersonID { get ; set ; } string First { get ; set ; } string Last { get ; set ; } //ICollection < CrewMember > CrewMembers { get ; set ; } ICollection < ICrewMember > CrewMembers { get ; set ; } } } public void UpdateCrewMemberModel ( CrewMemberModel CrewMember ) { var query = ( from crewMember in UnitOfWork.DataContext.CrewMembers where crewMember.CrewMemberID == CrewMember.CrewMemberID select crewMember ) .First < CrewMember > ( ) ; query.IsAssigned = CrewMember.IsAssigned ; query.IsCaptain = CrewMember.IsCaptain ; // Exception is thrown here var queryPerson = ( from person in UnitOfWork.DataContext.People where person.PersonID == query.PersonID select person ) .First < Person > ( ) ; queryPerson.First = CrewMember.Person.First ; queryPerson.Last = CrewMember.Person.Last ; //Note that UnitOfWork uses a Factory Repository Pattern ; //Commit just calls on UnitOfWork.DataContext.SaveAll ( ) Method UnitOfWork.Commit ( ) ; } System.Data.Entity.Core.EntityException { `` The navigation property 'CrewMembers ' on entity of type 'System.Data.Entity.DynamicProxies.Person_1A1EF42B1FC8D2DD0084F803201DE1DE4CF6E704C5AE129D954BD5BEAB55826C ' must implement ICollection < T > in order for Entity Framework to be able to track changes in collections . `` } Source : EntityFrameworkat System.Data.Entity.Core.Objects.DataClasses.EntityCollection ` 1.CheckIfNavigationPropertyContainsEntity ( IEntityWrapper wrapper ) at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Add ( IEntityWrapper wrappedTarget , Boolean applyConstraints , Boolean addRelationshipAsUnchanged , Boolean relationshipAlreadyExists , Boolean allowModifyingOtherEndOfRelationship , Boolean forceForeignKeyChanges ) at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Add ( IEntityWrapper wrappedEntity , Boolean applyConstraints ) at System.Data.Entity.Core.Objects.DataClasses.EntityReference ` 1.set_ReferenceValue ( IEntityWrapper value ) at System.Data.Entity.Core.Objects.DataClasses.EntityReference.SetEntityKey ( EntityKey value , Boolean forceFixup ) at System.Data.Entity.Core.Objects.EntityEntry.FixupEntityReferenceToPrincipal ( EntityReference relatedEnd , EntityKey foreignKey , Boolean setIsLoaded , Boolean replaceExistingRef ) at System.Data.Entity.Core.Objects.EntityEntry.FixupReferencesByForeignKeys ( Boolean replaceAddedRefs , EntitySetBase restrictTo ) at System.Data.Entity.Core.Objects.ObjectStateManager.FixupReferencesByForeignKeys ( EntityEntry newEntry , Boolean replaceAddedRefs ) at System.Data.Entity.Core.Objects.ObjectStateManager.AddEntry ( IEntityWrapper wrappedObject , EntityKey passedKey , EntitySet entitySet , String argumentName , Boolean isAdded ) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly [ TEntity ] ( Func ` 2 constructEntityDelegate , EntityKey entityKey , EntitySet entitySet ) at lambda_method ( Closure , Shaper ) at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator ` 1.ReadNextElement ( Shaper shaper ) at System.Data.Entity.Core.Common.Internal.Materialization.Shaper ` 1.SimpleEnumerator.MoveNext ( ) at System.Data.Entity.Internal.LazyEnumerator ` 1.MoveNext ( ) at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) at TestSolution.Infrastructure.Service.CrewMemberService.UpdateCrewMemberModel ( CrewMemberModel CrewMember ) in c : \Users\brett.caswell\Documents\Visual Studio 2012\Projects\TestSolution\TestSolution.Infrastructure.Service\Services\CrewMemberServices.cs : line 67TargetSite : { Boolean CheckIfNavigationPropertyContainsEntity ( System.Data.Entity.Core.Objects.Internal.IEntityWrapper ) }",EntityCollection - ICollection < InterfaceTEntity > - Runtime Issue/Quirk "C_sharp : I am trying to use LINQ to return the an element which occurs maximum number of times AND the number of times it occurs.For example : I have an array of strings : In this array , the query would return cherry as the maximum occurred element , and 3 as the number of times it occurred . I would also be willing to split them into two queries if that is necessary ( i.e. , first query to get the cherry , and second to return the count of 3 . string [ ] words = { `` cherry '' , `` apple '' , `` blueberry '' , `` cherry '' , `` cherry '' , `` blueberry '' } ; // ... Some LINQ statement here// ...",Simple LINQ question in C # "C_sharp : For the last few months I 've been developing a side project for my company , but the higher-ups have now decided it would be a good fit in an existing product.I 've been developing the side project using Microsoft 's Code Contracts for static type checking ( partly because I had n't used them before and was eager to learn ) .My problem is that if I check in my code to the code base with Contracts in place , will every other developer need the Code Contracts tools installed to be able to continue developing ? I know for a fact that none of them have it installed , and I 'm the junior here so I doubt I could convince them all to take it up.I 'm using .Net 4.5 , so the Code Contract libraries are included , but I 'm wondering if Visual Studio will complain that they 're not building with CONTRACTS_FULL specified in the build options every time they go to build , or , if I leave CONTRACTS_FULL in the build options , what will happen when another developer tries to build ? Additionally I 'm wondering how the end-product will act when a Contract fails , but the code has not been built with the Code Contracts Rewriter.I created a new solution with just one project . Created a simple function that fired a code contract violation , with code contracts uninstalled and CONTRACTS_FULL not specified . Built and ran it and received the following error : I think the error message needs rewriting , as CONTRACTS_FULL is most definitely not specified.Thanks to Matías Fidemraizer , we 've worked out that this happens when using Contract.Requires < TException > ( ) and not on Contract.Requires ( ) .Ideally , I 'd like to modify this behaviour so that the Contract fires the provided exception as if it were a normal guard statement instead of complaining about the rewriter.Here 's a fiddle demonstrating the problem : https : //dotnetfiddle.net/cxrAPe Run-time exception ( line 8 ) : An assembly ( probably `` hdxticim '' ) must be rewritten using the code contracts binary rewriter ( CCRewrite ) because it is calling Contract.Requires < TException > and the CONTRACTS_FULL symbol is defined . Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild . CCRewrite can be downloaded from http : //go.microsoft.com/fwlink/ ? LinkID=169180 . After the rewriter is installed , it can be enabled in Visual Studio from the project 's Properties page on the Code Contracts pane . Ensure that `` Perform Runtime Contract Checking '' is enabled , which will define CONTRACTS_FULL",Can I leave contracts in code that I 'm merging with a codebase used by non-code contracts developers ? "C_sharp : It is about this ( Inject the dependency ) versus this ( Create the dependency ) The latter sample so they say is bad because ... it violates DI ... of course nothing is injected ... but what if DI would not exist , what is so bad that the CustomerService is created manually from the Billing class ? I see no practical advantage concerning exchangeability of the Service interface.I ask for a practical example with source code may it be a unit test or showing a practical solution why it is so much more loose coupling . Anyone keen enough to show his DI muscles and why it has a practical right to exist and be applied ? UPDATESo people have not to read all up I will write here my short experience : DI as a pattern has a practical usage . To follow DI by not injecting all services manually ( a poor mans DI tool so they say ... ) use a DI framework like LightCore/Unity but be sure you use the right tool for the appropriate job . This is what I did not ; - ) Developing a mvvm/wpf application I have other requirements the LightCore/Unity tool could not support they even were a barrier . My solutions was to use MEFEDMVVM with which I am happy . Now my services are automatically injected at runtime not at startup time . : - ) private readonly ICustomerService _customerService ; public Billing ( ICustomerService customerService ) { _customerService = customerService ; } private readonly ICustomerService _customerService ; public Billing ( ) { _customerService = new CustomerService ( ) ; }",I know how to use dependency injection but I recognize no practical advantage for it "C_sharp : I am creating a file downloader in .NET which downloads an array of files from a server using Asynchronous tasks . However , even though I create the Task [ ] and returned string [ ] with the same length.Here is my method : and the exception : which points to this line : I know it will be something daft that I missed , but I 'm rattling my brain trying to figure it out . Thanks for the help in advance ! public static string [ ] DownloadList ( string [ ] urlArray , string [ ] toPathArray , string login = `` '' , string pass = `` '' , bool getExt = false ) { Console.WriteLine ( `` DownloadList ( { 0 } , { 1 } , { 2 } , { 3 } , { 4 } ) '' , urlArray , toPathArray , login , pass , getExt ) ; try { returnedArray = new string [ urlArray.Length ] ; Task [ ] taskArray = new Task [ urlArray.Length ] ; for ( int i = 0 ; i < urlArray.Length ; i++ ) { Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` i = { 0 } '' , i ) ; Task task = new Task ( ( ) = > { returnedArray [ i ] = Download ( urlArray [ i ] , toPathArray [ i ] , login , pass , getExt , true ) ; } ) ; task.Start ( ) ; taskArray [ i ] = task ; } Task.WaitAll ( taskArray ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Done ! Press Enter to close . `` ) ; Console.ReadLine ( ) ; return returnedArray ; } catch ( Exception e ) { Console.WriteLine ( ) ; Console.WriteLine ( e.Message ) ; Console.ReadLine ( ) ; return null ; } }",C # - Index was outside the bounds of the array using same list sizes in for loop "C_sharp : In my app I am allowing users to save photos from camera and photo library to isolated storage . I then get the name of each file and read the photo and add to my list . Once the list is built , I bind it to the list box.I can get about 5 displayed without a problem . After I scroll I get the exception : This is my XAML : This is the code : Very new to WP7 development and confused as to why my code partially works . System.Windows.Markup.XamlParseException occurred Message= [ Line : 0 Position : 0 ] -- - Inner Exception -- -KeyNotFoundException < ListBox x : Name= '' userPhotosListBox '' > < ListBox.ItemTemplate > < DataTemplate > < StackPanel x : Name= '' DataTemplateStackPanel '' Orientation= '' Horizontal '' > < ContentControl Content= '' { Binding Image } '' Width= '' 400 '' / > < Image Name= '' { Binding FileName } '' Source= '' /Images/appbar.delete.rest.png '' Width= '' 48 '' Height= '' 48 '' MouseLeftButtonUp= '' Image_MouseLeftButtonUp '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Center '' MaxWidth= '' 48 '' MaxHeight= '' 48 '' / > < /StackPanel > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > using ( var store = IsolatedStorageFile.GetUserStoreForApplication ( ) ) { var userFiles = store.GetFileNames ( ) ; foreach ( var userFile in userFiles ) { if ( userFile.Contains ( PhotoInIsolatedStoragePrefix ) ) { var currentBitmap = ReadBitmapImageFromIso ( userFile ) ; var userPhotoImage = new Image { Source = currentBitmap } ; var userImg = new Img ( userPhotoImage , userFile ) ; userPhotosListBox.Items.Add ( userImg ) ; } } } public class Img { public Img ( Image img , string fileName ) { this.Image = img ; this.FileName = fileName ; } public Image Image { get ; set ; } public string FileName { get ; set ; } }",XamlParseException when binding to listbox C_sharp : I 'm trying to use Windows Runtime Component ( C # ) in my Windows 10 Universal App ( JavaScript ) .I found how to do that in Windows 8.x store apps : https : //msdn.microsoft.com/en-us/library/hh779077.aspxbut this solution is not working with Windows 10 Universal App . It is throwing exception that class is not registered in the JavaScript.WRC code : In JS : namespace SampleComponent { public sealed class Example { public static string GetAnswer ( ) { return `` The answer is 42 . `` ; } public int SampleProperty { get ; set ; } } } document.getElementById ( 'output ' ) .innerHTML = SampleComponent.Example.getAnswer ( ) ;,Calling C # component from JavaScript in Windows 10 Universal App C_sharp : Can I set a breakpoint like below ( the asterisk symbolises the breakpoint dot ) ? Environment is C # and Visual Studio 2015 . ( I just told a colleague that I was possible but seem to stand corrected ) var x = ifThis ? * This ( ) : That ( ) ;,Can I set a breakpoint in an inline if in Visual Studio and C # ? "C_sharp : Trying to implement a very simple TPH setup for a system I 'm making , 1 base , 2 inherited classes.However the inherited classes all belong to the same entity set , so within my ObjectContext using loop , I can only access the base abstract class . I 'm not quite sure how I get the elements which are concrete classes ? ( I 've also converted it to using POCO ) .Then within my application using the Entities : There 's a CelestialBodies entity set on sec , but no Planets/Satellites as I 'd expect.Not quite sure what needs to be done to access them.Thanks using ( SolEntities sec = new SolEntities ( ) ) { Planets = sec.CelestialBodies ; }",EF TPH Inheritance Query "C_sharp : I am using an AutoSuggestBox control to display some results , as such : SearchResults ( ItemsSource binding ) is defined as such : And ShowModel is a basic model with bindable properties.The problem I 'm having is when I 'm clicking on one of the results , it is filling the textbox with the path of the model , as seen below : Before selecting an entry : After selecting an entry : What I want is to define some sort of template for the textbox to bind to one of the model 's properties so the model path is not displayed . Is this even possible ? < AutoSuggestBox Width= '' 192 '' PlaceholderText= '' Search '' HorizontalAlignment= '' Right '' ItemsSource= '' { Binding SearchResults } '' > < i : Interaction.Behaviors > ... < /i : Interaction.Behaviors > < AutoSuggestBox.ItemTemplate > < DataTemplate > < TextBlock > < Run Text= '' { Binding Name } '' / > < Run Text= '' ( `` / > < Run Text= '' { Binding Origin_Country [ 0 ] } '' / > < Run Text= '' ) '' / > < /TextBlock > < /DataTemplate > < /AutoSuggestBox.ItemTemplate > private ObservableCollection < ShowModel > _searchResults = default ( ObservableCollection < ShowModel > ) ; public ObservableCollection < ShowModel > SearchResults { get { return _searchResults ; } set { Set ( ref _searchResults , value ) ; } }",AutoSuggestBox query selected textbox "C_sharp : The main requirement for my current project is to receive , parse and store millions of radio messages per day . This means many messages per second are processed . At the moment the method of storing the parsed messages uses simple a SqlCommand and ExecuteNonQuery for each individual message . Seeing as each the project consists of multiple TcpClients reading in on separate threads there will be many concurrent instances of the below block being executed : I understand an alternative may be to cache the parsed messages and at scheduled times perform a bulk insert.Using the Entity Framework is an option , but probably overkill for the simple requirements.The program requires a persistent connection 24 hours per day and therefore never closes the db connection.So my question is , how reasonable is my current approach ? Should I close and open connections for each message ? Or continue using a global db connection shared and passed by reference ? query.Append ( string.Format ( `` INSERT INTO { 0 } ( { 1 } ) VALUES ( { 2 } ) '' , this._TABLE_ , col , val ) ) ; sqlCmd = new SqlCommand ( query.ToString ( ) , sql ) ; sqlCmd.ExecuteNonQuery ( ) ;",Best practice for storing constant stream of data "C_sharp : In C # , I can define an extension method for a generic array of type T like this : but for the life of me I ca n't figure out how to do the same in F # ! I tried type ' a array with , type array < ' a > with and type ' a [ ] with and the compiler was n't happy with any of them.Can anyone tell me what 's the right to do this in F # ? Sure , I can do this by overshadowing the Array module and add a function for that easily enough , but I really want to know how to do it as an extension method ! public static T GetOrDefault < T > ( this T [ ] arr , int n ) { if ( arr.Length > n ) { return arr [ n ] ; } return default ( T ) ; }",How to define a type extension for T [ ] in F # ? "C_sharp : I have raw pixel data coming from a camera in RGB8 format which I need to convert to a Bitmap . However , the Bitmap PixelFormat only seems to support RGB 16 , 24 , 32 , and 48 formats . I attempted to use PixelFormat.Format8bppIndexed , but the image appears discolored and inverted.Is there any other way to convert this data type correctly ? public static Bitmap CopyDataToBitmap ( byte [ ] data ) { var bmp = new Bitmap ( 640 , 480 , PixelFormat.Format8bppIndexed ) ; var bmpData = bmp.LockBits ( new Rectangle ( 0 , 0 , bmp.Width , bmp.Height ) , ImageLockMode.WriteOnly , bmp.PixelFormat ) ; Marshal.Copy ( data , 0 , bmpData.Scan0 , data.Length ) ; bmp.UnlockBits ( bmpData ) ; return bmp ; }",Convert RGB8 byte [ ] to Bitmap "C_sharp : Members , What I am trying to do is to right or left shift the digits of an Int32 ( not the bits ! ! ) .So if shift the constant : by 3I should get So no digits get lost , because we talk about a circular shift.After a bit of testing I 've come up with this method , which works : The way I am looking for should be an arithmetic solution , not a string conversion and then the rotation.I also assume that : The Int32 value has no 0-digits in it , to prevent any loss of digits.The Int32 is a non-negative numberA positive Rotation integer should shift to the right , and negative one to the left.My algorithm already does all of that , and I like to know if there are way to tweak it a bit , if there is a better arithmetic solution to the problem ? 123456789 789123456 static uint [ ] Pow10 = new uint [ ] { 1 , 10 , 100 , 1000 , 10000 , 100000 , 1000000 , 10000000 , 100000000 , uint.MaxValue } ; static uint RotateShift10 ( uint value , int shift ) { int r = ( int ) Math.Floor ( Math.Log10 ( value ) + 1 ) ; while ( r < shift ) shift = shift - r ; if ( shift < 0 ) shift = 9 + shift ; uint x = value / Pow10 [ shift ] ; uint i = 0 ; while ( true ) { if ( x < Pow10 [ i ] ) return x + ( value % Pow10 [ shift ] ) * Pow10 [ i ] ; i += 1 ; } }",Circular shift Int32 digits using C # "C_sharp : I 'm using projection of query results to a custom type , which is n't a part of entity data model : I want AvailableVersions to be sorted in descending order . Hence , I 've tried to add sorting for AvailableVersions in projection : With sorting , execution of the query throws an System.Data.EntityCommandCompilationException with System.InvalidCastException as inner exception : Unable to cast object of type 'System.Data.Entity.Core.Query.InternalTrees.SortOp ' to type 'System.Data.Entity.Core.Query.InternalTrees.ProjectOp'Without .OrderByDescending ( v = > v.Id ) everything works fine.Is this yet another feature , that is n't supported in Entity Framework , or I 've missed something ? P.S . I know , that I can sort items later at client side , but I 'm wondering about sorting at the server side . public sealed class AlgoVersionCacheItem : NotificationObject { public int OrderId { get ; set ; } public string OrderTitle { get ; set ; } public int ? CurrentVersion { get ; set ; } public int CachedVersion { get ; set ; } public IEnumerable < int > AvailableVersions { get ; set ; } } return someQueryable .Select ( version = > new AlgoVersionCacheItem { OrderId = version.OrderId , OrderTitle = version.Order.Title , CurrentVersion = version.Order.CurrentAlgoVersionId , CachedVersion = version.Id , AvailableVersions = version .Order .AlgoVersions .Where ( v = > ( allowUncommittedVersions || v.Statuses.Any ( s = > s.AlgoVersionStatusListItemId == ModelConstants.AlgoVersionCommitted_StatusId ) ) & & v.Id ! = version.Id ) .OrderByDescending ( v = > v.Id ) // this line will cause exception .Select ( v = > v.Id ) } ) .Where ( item = > item.AvailableVersions.Any ( ) ) .OrderByDescending ( item = > item.OrderId ) .ToArray ( ) ;",Sorting nested collection in projection : Unable to cast object of type 'SortOp ' to type 'ProjectOp ' "C_sharp : There is a large JSON file ( about a thousand lines ) . The task is to update existing JProperties , or add new JProperties in a specific location in the structure . The location of the new texts are based on the JToken.Path property . For example , this is the start of the JSON : Now the JSON must be updated using a given list of JToken paths and the corresponding values . The first possibility is , the JProperty corresponding to the path might already exist , in which case the value needs to be updated . I am already successfully implementing this with JToken.Replace ( ) . The second possibility is , the JProperty does not exist yet and needs to be added . For example , I need to add `` DanaerysTargaryen.Dragons.Dragon1.Color '' with the value `` Black '' .I know I can use the JSON.Net Add ( ) method , but to use this only the final child token of the path can be missing from the JSON . For example , I can useBut what about if I need to add `` JonSnow.Weapon.Type '' with the value `` Longsword '' ? Because `` Weapon '' does not exist yet as a JProperty , and it needs to be added along with `` Type '' : `` Longsword '' . With each path , it is unknown how much of the path already exists in the JSON . How can this be parameterised ? What should AddToJson ( ) look like ? Iterating through the entire path and checking each possible JProperty to see if it exists , and then adding the rest underneath , seems very cumbersome . Is there a better way to do this ? Any Json.NET tricks I am unaware of ? I am not even sure how the iteration could be parameterised . `` JonSnow '' : { `` Direwolf '' : { `` Name '' : `` Ghost '' , `` Color '' : `` White '' , } } '' DanaerysTargaryen '' : { `` Dragons '' : { `` Dragon1 '' : { `` Name '' : `` Drogon '' , } } `` Hair '' : { `` Color '' : `` White '' } } JObject ObjToUpdate= JObject.Parse ( jsonText ) ; JObject Dragon = ObjToUpdate [ `` DanaerysTargaryen '' ] [ `` Dragons '' ] [ `` Dragon1 '' ] as JObject ; Dragon.Add ( `` Color '' , `` Black '' ) ) ; // from outside source : Dictionary < string , string > PathBasedDict // key : Jtoken.Path ( example : `` JonSnow.Weapon.Type '' ) // value : new text to be added ( example : `` Longsword '' ) foreach ( KeyValuePair entry in PathBasedDict ) { string path = entry.Key ; string newText = entry.Value ; if ( ObjToUpdate.SelectToken ( path ) ! = null ) { ObjToUpdate.SelectToken ( path ) .Replace ( newText ) ; } else AddToJson ( path , newText ) ; }",How to add a new JProperty to a JSON based on path ? "C_sharp : I am attempting to create a some code that can serialize and deserialize a library of Classes into an AutoCAD drawing . This question has little to do with AutoCAD other than it being the reason why I can not debug it by normal means . I started this project from this article and successfully got his code to run . However the way his code is structured , It would require me to have all of my classes inherit from his baseobject . As this clearly is a code smell , I knew I needed to create an interface instead . Below is the code that I ended up with . This first section is the code responsible for doing the serialization into an AutoCAD drawing.The second section is an example of a class that implements my custom serialization interfaceHere is a dummy class I am attempting to test with : and here is the interface : When I attempt to run the code inside AutoCAD , All I get is this error . Which leads me to believe there is a simple bug in my initialization of my classes . Non of my breakpoints get hit.How should I debug this ? and where have I screwed up my initialization ? [ EDIT ] -Here is what is in the `` Details '' : public class Commands { public class MyUtil { const int kMaxChunkSize = 127 ; public ResultBuffer StreamToResBuf ( MemoryStream ms , string appName ) { ResultBuffer resBuf = new ResultBuffer ( new TypedValue ( ( int ) DxfCode.ExtendedDataRegAppName , appName ) ) ; for ( int i = 0 ; i < ms.Length ; i += kMaxChunkSize ) { int length = ( int ) Math.Min ( ms.Length - i , kMaxChunkSize ) ; byte [ ] datachunk = new byte [ length ] ; ms.Read ( datachunk , 0 , length ) ; resBuf.Add ( new TypedValue ( ( int ) DxfCode.ExtendedDataBinaryChunk , datachunk ) ) ; } return resBuf ; } public MemoryStream ResBufToStream ( ResultBuffer resBuf ) { MemoryStream ms = new MemoryStream ( ) ; TypedValue [ ] values = resBuf.AsArray ( ) ; // Start from 1 to skip application name for ( int i = 1 ; i < values.Length ; i++ ) { byte [ ] datachunk = ( byte [ ] ) values [ i ] .Value ; ms.Write ( datachunk , 0 , datachunk.Length ) ; } ms.Position = 0 ; return ms ; } public void NewFromEntity ( IClearspanSerializable objectToSave , Entity ent ) { using ( ResultBuffer resBuf = ent.GetXDataForApplication ( `` Member '' ) ) { BinaryFormatter bf = new BinaryFormatter ( ) ; bf.Binder = new MyBinder ( ) ; MemoryStream ms = this.ResBufToStream ( resBuf ) ; objectToSave.SetObjectData ( bf.Deserialize ( ms ) ) ; } } public void SaveToEntity ( IClearspanSerializable objectToSave , Entity ent ) { // Make sure application name is registered // If we were to save the ResultBuffer to an Xrecord.Data , // then we would not need to have a registered application name Transaction tr = ent.Database.TransactionManager.TopTransaction ; RegAppTable regTable = ( RegAppTable ) tr.GetObject ( ent.Database.RegAppTableId , OpenMode.ForWrite ) ; if ( ! regTable.Has ( `` Member '' ) ) { RegAppTableRecord app = new RegAppTableRecord ( ) ; app.Name = `` Member '' ; regTable.Add ( app ) ; tr.AddNewlyCreatedDBObject ( app , true ) ; } BinaryFormatter bf = new BinaryFormatter ( ) ; MemoryStream ms = new MemoryStream ( ) ; bf.Serialize ( ms , objectToSave ) ; ms.Position = 0 ; ent.XData = this.StreamToResBuf ( ms , `` Member '' ) ; ; } } public sealed class MyBinder : SerializationBinder { public override Type BindToType ( string assemblyName , string typeName ) { return Type.GetType ( string.Format ( `` { 0 } , { 1 } '' , typeName , assemblyName ) ) ; } } [ CommandMethod ( `` SaveClassToEntityXData '' , CommandFlags.Modal ) ] public void SaveClassToEntityXData ( IClearspanSerializable objectToSerialize ) { Database db = Application.DocumentManager.MdiActiveDocument.Database ; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor ; PromptEntityResult per = ed.GetEntity ( `` Select entity to save class to : \n '' ) ; if ( per.Status ! = PromptStatus.OK ) return ; MyUtil util = new MyUtil ( ) ; // Save it to the document using ( Transaction tr = db.TransactionManager.StartTransaction ( ) ) { Entity ent = ( Entity ) tr.GetObject ( per.ObjectId , OpenMode.ForWrite ) ; util.SaveToEntity ( objectToSerialize , ent ) ; tr.Commit ( ) ; } // Write some info about the results //ed.WriteMessage ( `` Content of MyClass we serialized : \n { 0 } \n '' , mc.ToString ( ) ) ; } [ CommandMethod ( `` GetClassFromEntityXData '' , CommandFlags.Modal ) ] public void GetClassFromEntityXData ( IClearspanSerializable objectToRestore ) { Database db = Application.DocumentManager.MdiActiveDocument.Database ; Editor ed = Application.DocumentManager.MdiActiveDocument.Editor ; MyUtil util = new MyUtil ( ) ; PromptEntityResult per = ed.GetEntity ( `` Select entity to get class from : \n '' ) ; if ( per.Status ! = PromptStatus.OK ) return ; // Get back the class using ( Transaction tr = db.TransactionManager.StartTransaction ( ) ) { Entity ent = ( Entity ) tr.GetObject ( per.ObjectId , OpenMode.ForRead ) ; util.NewFromEntity ( objectToRestore , ent ) ; tr.Commit ( ) ; } } } [ Serializable ] public class MattMember : IClearspanSerializable { public string Name ; List < int > MattsInts ; public MattMember ( string passedName , List < int > passedInts ) { Name = passedName ; MattsInts = passedInts ; } [ SecurityPermission ( SecurityAction.LinkDemand , Flags = SecurityPermissionFlag.SerializationFormatter ) ] public void GetObjectData ( SerializationInfo info , StreamingContext context ) { info.AddValue ( `` Name '' , Name ) ; info.AddValue ( `` MattsInts '' , MattsInts ) ; } [ SecurityPermission ( SecurityAction.LinkDemand , Flags = SecurityPermissionFlag.SerializationFormatter ) ] public void SetObjectData ( SerializationInfo info , StreamingContext context ) { if ( info == null ) { throw new System.ArgumentNullException ( `` info '' ) ; } Name = ( string ) info.GetValue ( `` Name '' , typeof ( string ) ) ; MattsInts = ( List < int > ) info.GetValue ( `` MattsInts '' , typeof ( List < int > ) ) ; } void IClearspanSerializable.SetObjectData ( object objectInDisguise ) { if ( objectInDisguise == null ) { throw new System.ArgumentNullException ( `` info '' ) ; } MattMember objectToCopy = ( MattMember ) objectInDisguise ; Name = objectToCopy.Name ; MattsInts = objectToCopy.MattsInts ; } } public interface IClearspanSerializable { void GetObjectData ( SerializationInfo info , StreamingContext context ) ; void SetObjectData ( object objectInDisguise ) ; } ******************************************************************************Application does not support just-in-time ( JIT ) debugging . See the end of this message for details . ************** Exception Text **************System.ArgumentException : Can not bind to the target method because its signature or security transparency is not compatible with that of the delegate type . at System.Delegate.CreateDelegate ( Type type , Object firstArgument , MethodInfo method , Boolean throwOnBindFailure ) at System.Delegate.CreateDelegate ( Type type , Object firstArgument , MethodInfo method ) at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorker ( MethodInfo mi , Object commandObject , Boolean bLispFunction ) at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorkerWithExceptionFilter ( MethodInfo mi , Object commandObject , Boolean bLispFunction ) at Autodesk.AutoCAD.Runtime.PerDocumentCommandClass.Invoke ( MethodInfo mi , Boolean bLispFunction ) at Autodesk.AutoCAD.Runtime.CommandClass.CommandThunk.Invoke ( ) ************** Loaded Assemblies **************mscorlib Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18444 built by : FX451RTMGDR CodeBase : file : ///C : /Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Acdbmgd Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AcdbMgd.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- adui20 Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/adui20.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AdUiPalettes Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AdUiPalettes.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- WindowsBase Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/WindowsBase/v4.0_4.0.0.0__31bf3856ad364e35/WindowsBase.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationFramework Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/PresentationFramework/v4.0_4.0.0.0__31bf3856ad364e35/PresentationFramework.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationCore Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_32/PresentationCore/v4.0_4.0.0.0__31bf3856ad364e35/PresentationCore.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System.Xaml Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xaml/v4.0_4.0.0.0__b77a5c561934e089/System.Xaml.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System.Configuration Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System.Xml Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AdApplicationFrame Assembly Version : 0.0.0.0 Win32 Version : 5.2.8.100 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AdApplicationFrame.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AdWindows Assembly Version : 5.2.10.200 Win32 Version : 5.2.10.200 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AdWindows.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationFramework.Classic Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/PresentationFramework.classic/v4.0_4.0.0.0__31bf3856ad364e35/PresentationFramework.classic.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System.Drawing Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- accoremgd Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/accoremgd.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System.Core Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Acmgd Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/Acmgd.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcWindows Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AcWindows.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcWindows.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcWindows.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcCui Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AcCui.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationFramework-SystemXml Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/PresentationFramework-SystemXml/v4.0_4.0.0.0__b77a5c561934e089/PresentationFramework-SystemXml.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationFramework.Aero Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/PresentationFramework.Aero/v4.0_4.0.0.0__31bf3856ad364e35/PresentationFramework.Aero.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- WindowsFormsIntegration Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/WindowsFormsIntegration/v4.0_4.0.0.0__31bf3856ad364e35/WindowsFormsIntegration.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System.Windows.Forms Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationUI Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/PresentationUI/v4.0_4.0.0.0__31bf3856ad364e35/PresentationUI.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- System.Xml.Linq Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml.Linq/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.Linq.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationFramework-SystemXmlLinq Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/PresentationFramework-SystemXmlLinq/v4.0_4.0.0.0__b77a5c561934e089/PresentationFramework-SystemXmlLinq.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- FeaturedAppsPlugin Assembly Version : 20.0.0.0 Win32 Version : 20.0.46.0.0 CodeBase : file : ///C : /ProgramData/Autodesk/ApplicationPlugins/Autodesk % 20FeaturedApps.bundle/Contents/Windows/2015/Win32/FeaturedAppsPlugin.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- UIAutomationTypes Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 built by : FX451RTMGREL CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/UIAutomationTypes/v4.0_4.0.0.0__31bf3856ad364e35/UIAutomationTypes.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- PresentationFramework-SystemCore Assembly Version : 4.0.0.0 Win32 Version : 4.0.30319.18408 CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_MSIL/PresentationFramework-SystemCore/v4.0_4.0.0.0__b77a5c561934e089/PresentationFramework-SystemCore.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Anonymously Hosted DynamicMethods Assembly Assembly Version : 0.0.0.0 Win32 Version : 4.0.30319.18444 built by : FX451RTMGDR CodeBase : file : ///C : /Windows/Microsoft.Net/assembly/GAC_32/mscorlib/v4.0_4.0.0.0__b77a5c561934e089/mscorlib.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcLayer Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AcLayer.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcLayer.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcLayer.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcAeNet.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcAeNet.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcCloudRender.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcCloudRender.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcCustomize.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcCustomize.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcDxWizard.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcDxWizard.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcExportLayoutUI.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcExportLayoutUI.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcInterfere.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcInterfere.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcLayerTools.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcLayerTools.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcMrUi.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcMrUi.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcMultiLineUi.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcMultiLineUi.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcRecoverAll.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcRecoverAll.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcScaleList.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcScaleList.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcUnderlay.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcUnderlay.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcViewTransitionsUi.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcViewTransitionsUi.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AdskConnectionPointMgd.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AdskConnectionPointMgd.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcCalcUi.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcCalcUi.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcLivePreviewContext Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AcWindows.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcDialogToolTips Assembly Version : 20.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/AcDialogToolTips.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- AcDialogToolTips.resources Assembly Version : 0.0.0.0 Win32 Version : 20.0.51.0.0 CodeBase : file : ///C : /Program % 20Files/Autodesk/AutoCAD % 202015/en-US/AcDialogToolTips.resources.DLL -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Write To Block Assembly Version : 1.0.5276.26438 Win32 Version : 1.0.0.0 CodeBase : file : ///C : /Users/Administrator/Documents/Clearspan/AutoCAD % 20Projects/Write % 20To % 20Block/Write % 20To % 20Block/bin/Debug/Write % 20To % 20Block.dll -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ************** JIT Debugging **************Application does not support Windows Forms just-in-time ( JIT ) debugging . Contact the application author for moreinformation .",Serialization Code Causes Unhandled Exception "C_sharp : I have a custom control that is show only with a given set of config values.I want to capture the trace.axd data and output it to this control . web.configI want to be able to load the trace.axd file in a usercontrol . Then have that usercontrol be loaded whenever needed . writeToDiagnosticsTrace= '' true '' ... < listeners > name= '' WebPageTraceListener '' type= '' System.Web.WebPageTraceListener , System.Web , Version=2.0.3600.0 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a '' < /listeners >",Redirecting the Trace.axd output "C_sharp : I 'm doing like this : is this good , am I going to have more performance with this ? entities.AsParallel ( ) .ForAll ( o = > repository.Insert ( o ) ) ;",is it ok to use plinq ForAll for a bulk insert into database ? "C_sharp : I am working with screen sharing project.I am capturing desktop screen using below function.it works fine . But whenever secure desktop prompting for elevation.it returns black/empty image.But when i turn off secured desktop from local security policy.It works fine.Is there any way to capture secure desktop without disabling Local Security Policy.Edit : Exe Installed in Secured locationExe is digitally signed static Bitmap CaptureDesktop ( ) { SIZE size ; Bitmap printscreen = null ; size.cx = Win32Stuff.GetSystemMetrics ( Win32Stuff.SM_CXSCREEN ) ; size.cy = Win32Stuff.GetSystemMetrics ( Win32Stuff.SM_CYSCREEN ) ; int width = size.cx ; int height = size.cy ; IntPtr hWnd = Win32Stuff.GetDesktopWindow ( ) ; IntPtr hDC = Win32Stuff.GetDC ( hWnd ) ; if ( hDC ! = IntPtr.Zero ) { IntPtr hMemDC = GDIStuff.CreateCompatibleDC ( hDC ) ; if ( hMemDC ! = IntPtr.Zero ) { IntPtr m_HBitmap = GDIStuff.CreateCompatibleBitmap ( hDC , width , height ) ; if ( m_HBitmap ! = IntPtr.Zero ) { IntPtr hOld = ( IntPtr ) GDIStuff.SelectObject ( hMemDC , m_HBitmap ) ; GDIStuff.BitBlt ( hMemDC , 0 , 0 , width , height , hDC , 0 , 0 , GDIStuff.SRCCOPY ) ; GDIStuff.SelectObject ( hMemDC , hOld ) ; GDIStuff.DeleteDC ( hMemDC ) ; printscreen = System.Drawing.Image.FromHbitmap ( m_HBitmap ) ; GDIStuff.DeleteObject ( m_HBitmap ) ; } } } Win32Stuff.ReleaseDC ( hWnd , hDC ) ; return printscreen ; }",Screenshot secure desktop "C_sharp : Are there any decent articles online that explain in detail how the conventions work in EF 4.1 ? There was an article linked from Scott Gu 's blog , but it was dated 2010 , I think it was then in CTP 4 . Not sure if the conventions have beem modified since then . But I do n't understand how it works . For example how does it know to use the table SkillType if I have this code ( what does it look for ? ) : This is just 1 of my confusions , then there is foreign keys , primary keys , etc . I need to familiarise myself with these conventions so any goof articles that I can read please let me know . I did Google and could n't get anything solid and concrete . public DbSet < SkillType > SkillTypes { get ; set ; }",Understanding Entity Framework 4.1 Conventions "C_sharp : I have a MVC model similar to thisI receive the error Templates can be used only with field access , property access , single-dimension array index , or single-parameter custom indexer expressions.when trying to create a label for the number field , with the model lambda expression stored in a variable.For example , in my view I have : I noticed using the debugger that the lambda expression is model = > Convert ( model.Number ) , instead of model = > model.Number , but this only happens to value types from what I can tell , as I have tested with integers ( nullable and non-nullable ) and DateTime objects . It seems that the NodeType for the lambda expression is Convert , for strings is Member access . I know the cause of the error itself , but I do n't know what causes the compiler to evaluate model= > model.Number to model = > Convert ( model.Number ) .Thanks ! public class Model { public string Name { get ; set ; } public int Number { get ; set ; } } @ Html.LabelFor ( model = > model.Name ) // Works fine @ Html.LabelFor ( model = > model.Number ) // Works fine @ { Expression < Func < Offer , object > > nameExpression = model = > model.Name ; Expression < Func < Offer , object > > numberExpression = model = > model.Number ; } @ Html.LabelFor ( nameExpression ) // Works fine @ Html.LabelFor ( numberExpression ) // Error !",MVC4 Templates can be used only with field access "C_sharp : I am trying to use Microsoft Identity library to do a role base authorization and I am failing.I can authenticate the userI see the role that user is belonging to matches the Role I have on the controllerWhen I go to that controller I get 403 Forbidden errorI do n't know how to debug it further.Startup : My Controller with a role : Repo url services.AddIdentity < User , UserRole > ( opt = > opt.User.RequireUniqueEmail = true ) .AddRoles < UserRole > ( ) .AddEntityFrameworkStores < EntityDbContext > ( ) .AddDefaultTokenProviders ( ) ; var jwtSetting = _configuration .GetSection ( `` JwtSettings '' ) .Get < JwtSettings > ( ) ; services.AddAuthentication ( options = > { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme ; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme ; } ) .AddJwtBearer ( config = > { config.RequireHttpsMetadata = false ; config.SaveToken = true ; config.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = jwtSetting.Issuer , ValidAudience = jwtSetting.Audience , IssuerSigningKey = new SymmetricSecurityKey ( Encoding.UTF8.GetBytes ( jwtSetting.Key ) ) } ; } ) ; [ Authorize ( Roles = `` Internal '' ) ] [ ApiController ] [ Route ( `` Api/ [ controller ] '' ) ] public class UserController : BasicCrudController < User > { // Stuff here ... }",".NET Core 3.1 role based authorization fails , getting 403 exception" "C_sharp : I 'm trying to figure how I should use the Ford Fulkerson algorithm in this situation The situation is kinda sudoku-like . We have a matrix a which contains integer values . The last column of each row and last row of each column , contains the sum of the entire row / column.Example : This thing is , that the values within the matrix are not always correct . The values for the sum are not always correct , for example : There is a matrix b which contains the max difference a cell can have to meet the given sum . For exampleFor example for the value of a [ 0 ] [ 0 ] , which is 1 , the max differences is the value at b [ 0 ] [ 0 ] , which is 1 , so the value at a [ 0 ] [ 0 ] can be changed to 0 or 2 maximum ( and all the numbers in between , but for this example we only have 2 options ) .My question is : Given a matrix a ( with invalid values for a given sum ) and a matrix b with the max differences which can be used to meet the required sum , how can I determine wether it 's even possible with the given maximum differences and how do I get a valid result of such a matrix ( if thus exists ) .My current approach ( which not works ) : Make a bipartite graph of the rows and columns , so you have a source , a sink and a node for each row and column . Then connect each row to each column.Then connect the source to each row.Then connect each column to the sink.Set capacities for the edges from the source to each row-node to the Math.Abs ( current sum of numbers in a - given sum of numbers in a ( for that row ) ) .Same for the edges from each column-node to the sink ( but for the column sums this time ) .Set the capacities between nodes for the rows to the columns to the given max differences in b for each cell accordingly.Use Ford Fulkerson to determine the max flow.I do n't know how I should use my results of the algorithm to determine the correct values for matrix a to meet the given sum for each row and column . int [ ] [ ] a = { { 1 , 3 , 5 , 9 } , { 4 , 2 , 1 , 7 } , { 5 , 5 , 6 , * } } // * Is not determined since the sums // * do not count as summable values . int [ ] [ ] a = { { 1 , 3 , 3 , 9 } , { 2 , 3 , 1 , 7 } , { 5 , 5 , 6 , * } } // * Is not determined since the sums do // * not count as summable values . int [ ] [ ] b = { { 1 , 0 , 3 } , { 2 , 1 , 2 } }",Max flow in bipartite graph using Ford Fulkerson to determine values to suffice to sum "C_sharp : Consider the following : :2 things : :Why can I unbox to StringComparison ? I guess this is because it 's underlying type is Int32 but I still find it odd.Why does nullableEnum have a value of null ? As I understand the only valid unboxing is from a boxed value type is to it 's type or to a nullable type . If int can unbox to Enum , then why does n't the same hold true for the nullable values ? Similarly , if Instead of 5 I boxed StringComparison.OrdinalIgnoreCase , it would be that nullableInt would be null , but nullableEnum would not be . Object box = 5 ; int @ int = ( int ) box ; // int = 5int ? nullableInt = box as int ? ; // nullableInt = 5 ; StringComparison @ enum = ( StringComparison ) box ; // enum = OrdinalIgnoreCaseStringComparison ? nullableEnum = box as StringComparison ? ; // nullableEnum = null .",Why does unboxing enums yield odd results ? "C_sharp : Imagine this case where I have an object that I need to check a property.However , the object can currently have a null value.How can I check these two conditions in a single `` if '' condition ? Currently , I have to do something like this : I would like something like this : I want to evaluate the second condition only if the first was true.Maybe I 'm missing something , and that 's why I need your help ; - ) if ( myObject ! = null ) { if ( myObject.Id ! = pId ) { myObject.Id = pId ; myObject.Order = pOrder ; } } if ( myObject ! = null & & myObject.Id ! = pId )",Chained IF structure "C_sharp : I am trying out the Managed Extensibility Framework for the first time in Visual Studio 2010 beta 2 using the System.ComponentModel.Composition from .net-4.0.I have been unable to get the CompositionContainer to find my implementation assemblies using the two alternative routines below.First attempt ( this worked in an older codeplex release of MEF ) : Second attempt ( this worked in beta 1 , I think ) : Is there a new way to do this in beta 2 ? EDIT : It turned out to be nothing to do with the composition . I had a static property representing my imported implementation : which should have been : I marked Daniel 's answer as accepted because the sage advice of debugging in a more thorough fashion solved the problem . var composition = new CompositionBatch ( ) ; composition.AddPart ( this ) ; var container = new CompositionContainer ( new DirectoryCatalog ( AppDomain.CurrentDomain.BaseDirectory ) ) ; container.Compose ( composition ) ; var aggregateCatalog = new AggregateCatalog ( new AssemblyCatalog ( Assembly.GetExecutingAssembly ( ) ) , new DirectoryCatalog ( AppDomain.CurrentDomain.BaseDirectory ) ) ; var compositionContainer = new CompositionContainer ( aggregateCatalog ) ; compositionContainer.ComposeParts ( this ) ; [ Import ] public static ILog Log { get ; set ; } [ Import ] public ILog Log { get ; set ; }",Instruct MEF to use any available assemblies "C_sharp : I have seen example code that looks like this , which seems perfectly reasonable : But I have also seen several examples that look like this : Why would I ever want to do this ? I ca n't imagine any scenario where I would want to build a system that knows its user names in advance . [ Authorize ( Roles = `` Admin , User '' ) ] public class SomeController : Controller [ Authorize ( Users = `` Charles , Linus '' ) ] public class SomeController : Controller",Why would I hard-code user permissions in my controller attributes ? "C_sharp : I have these two pieces of code , wich one is more readable ? foreachlinq decimal technicalPremium = 0 ; foreach ( Risk risk in risks ) { technicalPremium = technicalPremium + risk.TechnicalPremium ; } return technicalPremium ; return risks.Sum ( risk = > risk.TechnicalPremium ) ;",What is more readable ? "C_sharp : I have the following types : And I have a code-first DBContext : This works great if I query for a car or moto directly ... But if I want a list of all vehicles , whether car or moto , I would like to do this : When I try the above code , I get an exception : System.InvalidOperationException : The entity type Vehicle is not part of the model for the current context.That makes perfect sense ... I did n't add Vehicle to the context . I added car and moto . At this point , I 'm not sure what to do . I tried adding Vehicle to my context , but that combined the tables for car and moto into one Vehicle table . I definitely want a separate table for cars and motos ( and possibly a table for the vehicle base properties as well ) . What 's the best way to do this ? public abstract class Vehicle { public int Id { get ; set ; } public double TopSpeed { get ; set ; } } public class Car : Vehicle { public int Doors { get ; set ; } } public class Motorcycle : Vehicle { public string Color { get ; set ; } } public MyDbContext : DbContext { public DbSet < Car > Cars { get ; set ; } public DbSet < Motorcycle > Motorcycles { get ; set ; } } var dbContext = new MyDbContext ( ) ; var cars = dbContext.Set < Car > ( ) .Where ( x= > x.TopSpeed > 10 ) ; // < -- THIS WORKS var dbContext = new MyDbContext ( ) ; var vehicles = dbContext.Set < Vehicle > ( ) .Where ( x= > x.TopSpeed > 10 ) ; // < -- THIS DOES NOT WORK",Querying by base type in EF4 Code-First C_sharp : Why does this work : But this does n't : Compiler says error CS0029 : Can not implicitly convert type 'string ' to 'bool ' if ( `` xx '' .StartsWith ( `` x '' ) ) { } if ( `` xx '' + `` xx '' .StartsWith ( `` x '' ) ) { },Why does this not compile in C # ? "C_sharp : I 'm trying to create a very simple model binder for ObjectId types in my models but ca n't seem to make it work so far.Here 's the model binder : This is the ModelBinderProvider I 've coded : Here 's the class I 'm trying to bind the body parameter to : This is the action method : For this code to work , I mean for the model binder to run , I inherited the controller from Controller and removed the [ FromBody ] attribute from the Player parameter.When I run this , I can step into BindModelAsync method of the model binder , however I ca n't seem to get the Id parameter value from the post data . I can see the bindingContext.FieldName is correct ; it is set to Id but result.FirstValue is null.I 've been away from Asp.Net MVC for a while , and it seems lots of things have been changed and became more confusing : - ) EDITBased on comments I think I should provide more context.If I put [ FromBody ] before the Player action parameter , player is set to null . If I remove [ FromBody ] , player is set to a default value , not to the values I post . The post body is shown below , it 's just a simple JSON : public class ObjectIdModelBinder : IModelBinder { public Task BindModelAsync ( ModelBindingContext bindingContext ) { var result = bindingContext.ValueProvider.GetValue ( bindingContext.FieldName ) ; return Task.FromResult ( new ObjectId ( result.FirstValue ) ) ; } } public class ObjectIdModelBinderProvider : IModelBinderProvider { public IModelBinder GetBinder ( ModelBinderProviderContext context ) { if ( context == null ) throw new ArgumentNullException ( nameof ( context ) ) ; if ( context.Metadata.ModelType == typeof ( ObjectId ) ) { return new BinderTypeModelBinder ( typeof ( ObjectIdModelBinder ) ) ; } return null ; } } public class Player { [ BsonId ] [ ModelBinder ( BinderType = typeof ( ObjectIdModelBinder ) ) ] public ObjectId Id { get ; set ; } public Guid PlatformId { get ; set ; } public string Name { get ; set ; } public int Score { get ; set ; } public int Level { get ; set ; } } [ HttpPost ( `` join '' ) ] public async Task < SomeThing > Join ( Player player ) { return await _someService.DoSomethingOnthePlayer ( player ) ; } { `` Id '' : `` 507f1f77bcf86cd799439011 '' `` PlatformId '' : `` 9c8aae0f-6aad-45df-a5cf-4ca8f729b70f '' }",Creating a ModelBinder for MongoDB ObjectId on Asp.Net Core "C_sharp : i have an actionresult that overrides Execute ( as you do ) and the actionresult basically receives a model , serializes it , and writes it out to the reponse via response.write ( model as text ) .ive done some looking around and i cant see an easy way to test the response is correct . i think the best way is to test instantiate the custom actionresult & model , call the execute method , and then somehome inspect the controllercontexts ' response . Only problem is , how do i get the reponses output as a string ? i read somewhere that you cant get the responses outputstream as text ? if so , how do i verify that my content is being written to the response stream ? i can test my serialiser to reduce the risk , but id like to get some coverage over the ExecuteResult override ... public class CustomResult : ActionResult { private readonly object _contentModel ; private readonly ContentType _defaultContentType ; public CustomResult ( object contentModel , ContentType defaultContentType ) { _contentModel = contentModel ; _defaultContentType = defaultContentType ; } public override void ExecuteResult ( ControllerContext context ) { context.HttpContext.Response.Write ( serialized model ) ; } }",testing a custom actionresult in mvc 2 "C_sharp : Is it me , or something nasty going on here about NotifyIcon . Whatever I give to timeout parameter of NotifyIcon.ShowBalloonTip method it is shown for only certain amount of time . Which is around 9 secs on win7 and win 8.1 and around 4 secs on windows server 2008 r2 . These are the operating systems I tried so far . I tried both overloads of NotifyIcon.ShowBalloonTip but I get same results.and thisOn msdn it says : Minimum and maximum timeout values are enforced by the operating system and are typically 10 and 30 seconds , respectively , however this can vary depending on the operating system.Okay , but do n't we have any word on this ? If it is a preset value , why there is this timeout parameter ? I 'm hoping I 'm missing something stupid . ( I 'm working with .net 4.5 ) //this is only shown for 9 secondsnotifyIcon1.ShowBalloonTip ( 15000 ) ; //this is only shown for 9 seconds too : ) notifyIcon1.ShowBalloonTip ( 15000 , `` 1 sec '' , `` shown for one sec '' , ToolTipIcon.Info ) ;",Annoying NotifyIcon.ShowBalloonTip behaviour "C_sharp : Say , if I create a dictionary like this : So when I do : Am I guaranteed to have these values retrieved as such : `` z1 '' , `` abc9 '' , `` abc8 '' , `` ABC1 '' ? And what if I first do this , will it be : `` z1 '' , `` abc8 '' , `` ABC1 '' ? Dictionary < string , MyClass > dic = new Dictionary < string , MyClass > ( ) ; dic.add ( `` z1 '' , val1 ) ; dic.add ( `` abc9 '' , val2 ) ; dic.add ( `` abc8 '' , val3 ) ; dic.add ( `` ABC1 '' , val4 ) ; foreach ( KeyValuePair < string , MyClass > kvp in dic ) { } dic.Remove ( `` abc9 '' ) ;",Are elements in a .NET 's Dictionary sequential ? "C_sharp : In my VB.NET application , the event AppDomain.CurrentDomain.AssemblyResolve has a handler subscribed to it . The ResolveEventHandler which is subscribed to this event was added upstream from my code ( for all I know , System.AppDomain has its own Private Method subscribed to the Event ) ... is it possible to Remove all handlers from this event , so that I can add my own handler and ensure it 's the only one ? Essentially I 'm trying to do this : But I do n't know what ClassX or MethodX are in this example because I have n't added a handler to this event yet , and this handler was added by upstream code . I 'm using the method described here to check if any handler is subscribed event : https : //stackoverflow.com/a/2953318/734914Edit : I was able to figure out which method is subscribed to the event , using the Immediate Window while debugging.Now I 'm trying to Remove it , like this , because it 's not a Public method : But that gives a compiler error saying : `` AddressOf parameter must be the name of a method '' . So I 'm not sure how to specify a non-Public method here RemoveHandler AppDomain.CurrentDomain.AssemblyResolve , AddressOf ClassX.MethodX ? DirectCast ( gettype ( System.AppDomain ) .GetField ( `` AssemblyResolve '' , BindingFlags.Instance or BindingFlags.NonPublic ) .GetValue ( AppDomain.CurrentDomain ) , ResolveEventHandler ) { System.ResolveEventHandler } _methodBase : Nothing _methodPtr : 157334028 _methodPtrAux : 1827519884 _target : { System.ResolveEventHandler } **Method : { System.Reflection.Assembly ResolveAssembly** ( System.Object , System.ResolveEventArgs ) } Target : Nothing RemoveHandler AppDomain.CurrentDomain.AssemblyResolve , AddressOf GetType ( Reflection.Assembly ) .GetMethod ( `` ResolveAssembly '' )",Is it possible to Remove a VB.NET EventHandler that your class did n't Add ? "C_sharp : I am working on a download manager and trying to get cookie required contents using HttpWebRequest . I want to integrate my application to Chrome and so I can get the necessary cookie headers and values from the browser.But first I need to know if cookie is required to get a content to download and which cookies are they . I ca n't find any helpful resource about this topic . This is what I imagine : How can I do these steps ? HttpWebRequest req = ( WebRequest.Create ( url ) ) as HttpWebRequest ; //At first , get if cookies are necessary ? //If it is , get the required cookie headers //Then add the cookies to the requestCookieContainer cc = new CookieContainer ( ) ; Cookie c1 = new Cookie ( `` header1 '' , `` value1 '' ) ; Cookie c2 = new Cookie ( `` header2 '' , `` value2 '' ) ; CookieCollection ccollection = new CookieCollection ( ) ; ccollection.Add ( c1 ) ; ccollection.Add ( c2 ) ; cc.Add ( uri , ccollection ) ; req.CookieContainer = cc ; //Get response and other stuff ... ...",How do I know which cookie ( s ) are must to make a correct HttpWebRequest ? "C_sharp : I am trying to implement HMAC authentication using the code given here : http : //bitoftech.net/2014/12/15/secure-asp-net-web-api-using-api-key-authentication-hmac-authentication/.I integrated this code inside my ASP.NET web forms application . I created a folder named `` HMACAPI '' and added the controllers and filters inside it . I also installed all the required Nuget packages . This is how I am implementing my service methods : This is my route configuration for the API : But when I use client.PostAsJsonAsync ( ) , it 's showing Method Not Allowed error . I tried various SO questions but none of their answers are helping.What I tried : Removed WebDAV module.Added [ HttpPost ] attribute to post method.I am using `` http : //localhost:56697/api/forms/ '' URL to access the API . But I also tried `` http : //localhost:56697/api/forms '' and `` http : //localhost:56697/api/forms/test '' .UPDATEAs suggested by Obsidian Phoenix I was able to run it without [ HMACAuthentication ] attribute . But I want to implement this with HMAC authentication . So , what can be the reasons for this ? [ HMACAuthentication ] [ RoutePrefix ( `` api/forms '' ) ] public class FormsController : ApiController { [ Route ( `` '' ) ] public IHttpActionResult Get ( ) { ClaimsPrincipal principal = Request.GetRequestContext ( ) .Principal as ClaimsPrincipal ; var Name = ClaimsPrincipal.Current.Identity.Name ; return Ok ( `` test '' ) ; } [ Route ( `` '' ) ] public IHttpActionResult Post ( string order ) { return Ok ( order ) ; } } GlobalConfiguration.Configure ( APIWebFormsProject.API.WebApiConfig.Register ) ;",Getting `` Method Not Allowed '' error when using ASP.NET Web API inside ASP.NET Web Forms "C_sharp : I tried to find a solution for this minor problem for quite a while but could n't find an answer.I want to set the sender 's name of my e-mails that I send using log4net SmtpAppender , but I ca n't figure out how.This is my log4net appender config : It works , but when I receive the e-mail , the name of the sender is whatever is in front of the @ in the `` from '' parameter , in this case `` sender '' ( as it 's sender @ sending.com ) .What I want is a custom name , let 's say Notifier , but still keep sending from sender @ sending.comI tried different parameters ( just random guesses , since I could n't find any good ideas while searching the net ) ... like from_name or sender_name ... nothing works ... It 's my first question on SO , hope I met all criteria and someone can help me : ) Cheers < appender name= '' SmtpAppender '' type= '' log4net.Appender.SmtpAppender '' > < to value= '' sender @ sending.com '' / > < from value= '' receiver @ receiving.rom '' / > < subject value= '' test logging message '' / > < smtpHost value= '' ... `` / > < authentication value= '' Basic '' / > < port value= '' 587 '' / > < bufferSize value= '' 1 '' / > < username value= '' ... `` / > < password value= '' ... `` / > < EnableSsl value= '' true '' / > < lossy value= '' true '' / > < evaluator type= '' log4net.Core.LevelEvaluator '' > < threshold value= '' FATAL '' / > < /evaluator > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % newline % date [ % thread ] % -5level % logger [ % property { NDC } ] - % message % newline % newline % newline '' / > < /layout > < /appender >",How to set log4net SmtpAppender sender name in .config file "C_sharp : Can you help me to understand , from below code snippet ? and it would be great if someone explain me to achive this in C # 1.1 . ( Snippet From MS ) - words.Aggregate ( ( workingSentence , next ) = > + next + `` `` + workingSentence ) ; string sentence = `` the quick brown fox jumps over the lazy dog '' ; // Split the string into individual words . string [ ] words = sentence.Split ( ' ' ) ; // Prepend each word to the beginning of the // new sentence to reverse the word order . string reversed = words.Aggregate ( ( workingSentence , next ) = > next + `` `` + workingSentence ) ; Console.WriteLine ( reversed ) ; // This code produces the following output : // // dog lazy the over jumps fox brown quick the",Need more details on Enumerable.Aggregate function "C_sharp : My application is intended to work almost entirely through a Windows 7 taskbar item with the use of thumbnails and jump lists . I know I can easily create a Form and simply hide it , but this seems like overkill . Plus , I 'd like to toy around with NativeWindow as much as possible , because I 've never used it before.Essentially , I have a class called RootWindow that derives from NativeWindow that will handle hotkeys and hopefully everything else . I do n't need a visible window at all , but simply something to process window messages and provide a taskbar item that I can attach thumbnails and jump lists to.Is there some kind of special CreateParams option I need to pass to CreateHandle ? Or am I out of luck ? EDIT : Well , it was easier than I thought it would be , although it 's not exactly what I want . Once I passed the NativeWindow 's handle to the ShowWindow API , the taskbar item appeared . However , it also shows a window in the upper left corner of the screen . Is there some way to get rid of that window while still showing the taskbar item ? public class RootWindow : NativeWindow { public const int SW_SHOWNOACTIVATE = 4 ; [ DllImport ( `` User32.dll '' ) ] private static extern int ShowWindow ( IntPtr hWnd , short cmdShow ) ; public RootWindow ( ) { CreateHandle ( new CreateParams ( ) ) ; ShowWindow ( this.Handle , SW_SHOWNOACTIVATE ) ; } }",Show a taskbar item with a NativeWindow "C_sharp : I have a C # Extension method that can be used with tasks to make sure any exceptions thrown are at the very minimum observed , so as to not crash the hosting process . In .NET4.5 , the behavior has changed slightly so this wo n't happen , however the unobserved exception event is still triggered . My challenge here is writing a test to prove the extension method works . I am using NUnit Test Framework and ReSharper is the test runner.I have tried : The test always fails on the Assert.IsTrue . When I run this test manually , in something like LINQPad , I get the expected behavior of wasUnobservedException coming back as true.I am guessing the test framework is catching the exception and observing it such that the TaskScheduler.UnobservedTaskException is never being triggered.I have tried modifying the code as follows : The attempt I made in this code was to cause the task to get GC 'd before the exception was thrown , so that the finalizer would see an uncaught , unobserved exception . However this resulted in the same failure described above.Is there , in fact , some sort of exception handler hooked up by the Test Framework ? If so , is there a way around it ? Or am I just completely messing something up and there is a better/easier/cleaner way of doing this ? var wasUnobservedException = false ; TaskScheduler.UnobservedTaskException += ( s , args ) = > wasUnobservedException = true ; var res = TaskEx.Run ( ( ) = > { throw new NaiveTimeoutException ( ) ; return new DateTime ? ( ) ; } ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Assert.IsTrue ( wasUnobservedException ) ; var wasUnobservedException = false ; TaskScheduler.UnobservedTaskException += ( s , args ) = > wasUnobservedException = true ; var res = TaskEx.Run ( async ( ) = > { await TaskEx.Delay ( 5000 ) .WithTimeout ( 1000 ) .Wait ( ) ; return new DateTime ? ( ) ; } ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Assert.IsTrue ( wasUnobservedException ) ;",Test for UnObserved Exceptions "C_sharp : I am calling a thickbox when a link is clicked : And , when a server button is clicked I call this javascript function to show a jGrowl notification : Both works as expected except when the jGrowl is shown first than the thickbox . This will cause the thickbox not to work and the page will be shown as a normal web ( as if the thickbox had been gone ) .Does anyone know what is happening ? UPDATE : This is the a test page without Master Page : This is the codebehind : I have just tested it without the UpdatePanel and it worked perfectly . So , it is definitely a problem with the UpdatePanel or the way that it is interacting with the jGrowl called from the codebehind.I would massively appreciate your help guys.UPDATE : I have even created a demo project where this problem can be easily identified . Would n't mind to send it to anyone willing to help me out with this . Thanks in advance guys ! UPDATE : I have also tried the solution given by @ Rick , changing the way the jGrowl script is executed from codebehind : However , the problem persist since the outcome is exactly the same . Any other ideas ? I 'd massively appreciate your help.UPDATE : I have also tried this in IE8 and Chrome , facing the same problem . So , this is nothing to do with the browser . Just in case . < a href= '' createContact.aspx ? placeValuesBeforeTB_=savedValues & TB_iframe=true & height=400 & width=550 & modal=true '' title= '' Add a new Contact '' class= '' thickbox '' > Add a new Contact < /a > ScriptManager.RegisterClientScriptBlock ( this , typeof ( Page ) , Guid.NewGuid ( ) .ToString ( ) , `` $ ( function ( ) { $ .jGrowl ( 'No Contact found : `` + searchContactText.Text + `` ' ) ; } ) ; '' , true ) ; < % @ Page Language= '' C # '' AutoEventWireup= '' true '' CodeBehind= '' WebForm2.aspx.cs '' Inherits= '' RoutingPortal.Presentation.WebForm2 '' % > < ! DOCTYPE html PUBLIC `` -//W3C//DTD XHTML 1.0 Transitional//EN '' `` http : //www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd '' > < html xmlns= '' http : //www.w3.org/1999/xhtml '' > < head runat= '' server '' > < title > < /title > < script src= '' ../Scripts/jquery-1.6.2.js '' type= '' text/javascript '' > < /script > < script src= '' ../Scripts/jquery-ui-1.8.16.custom.min.js '' type= '' text/javascript '' > < /script > < script src= '' ../Scripts/thickbox.js '' type= '' text/javascript '' > < /script > < script src= '' ../Scripts/jquery.jgrowl.js '' type= '' text/javascript '' > < /script > < link href= '' ../Scripts/css/jquery.jgrowl.css '' rel= '' stylesheet '' type= '' text/css '' / > < link rel= '' stylesheet '' href= '' ~/CSS/thickbox.css '' type= '' text/css '' media= '' screen '' / > < /head > < body > < form id= '' form1 '' runat= '' server '' > < asp : ScriptManager ID= '' ScriptManager1 '' runat= '' server '' > < /asp : ScriptManager > < asp : UpdatePanel ID= '' UpdatePanel1 '' runat= '' server '' > < ContentTemplate > < div > < a href= '' createContact.aspx ? placeValuesBeforeTB_=savedValues & TB_iframe=true & height=400 & width=550 & modal=true '' title= '' Add a new Contact '' class= '' thickbox '' > Add a new Contact < /a > < asp : Button ID= '' Button1 '' runat= '' server '' Text= '' Button '' OnClick= '' Button1_Click '' / > < /div > < /ContentTemplate > < /asp : UpdatePanel > < /form > < /body > < /html > namespace RoutingPortal.Presentation { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load ( object sender , EventArgs e ) { } protected void Button1_Click ( object sender , EventArgs e ) { ScriptManager.RegisterClientScriptBlock ( this.Page , typeof ( Page ) , Guid.NewGuid ( ) .ToString ( ) , `` $ ( function ( ) { $ .jGrowl ( 'My Message ' ) ; } ) ; '' , true ) ; } } } ScriptManager.RegisterStartupScript ( this.Page , typeof ( Page ) , Guid.NewGuid ( ) .ToString ( ) , `` $ .jGrowl ( 'My Message ' ) ; '' , true ) ;","When jGrowl is called , the thickbox stops working properly ( using UpdatePanel )" "C_sharp : I have a Response.Redirect in my Employee page . It redirects to Salary page . It was working fine until I added exception handling as below.This caused a new exception saying `` Thread was being aborted ” . I came to know that this can be avoided by setting endResponse as false for the redirect . Explanation of new exception : It always throws the exception but handled by the framework . Since I added a try..catch it was caught there ( and I am throwing a new exception ) Note : CompleteRequest does bypass further HTTP filters and modules , but it does n't bypass further events in the current page lifecycleNote : Response.Redirect throw this exception to end processing of the current page . ASP .Net itself handles this exception and calls ResetAbort to continue processing . QUESTIONWhether “ setting endResponse as false ” can increase performance since the exception is not thrown ? Whether “ setting endResponse as false ” can decrease performance since the page lifecycle events are not terminated ? PITFALLIf you set endResponse as false , remaining code in the eventhandler will be executed . So we need to make a if check for the remaining code ( Check : if redirection criteria was not met ) .ReferenceWhy Response.Redirect causes System.Threading.ThreadAbortException ? ASP.NET exception `` Thread was being aborted '' causes method to exit Response.Redirect ( `` Salary.aspx '' ) ; try { Response.Redirect ( `` Salary.aspx '' ) ; } catch ( Exception ex ) { //MyLog ( ) ; throw new Exception ( ) ; } //Remaining code in event handler Response.Redirect ( url , false ) ; Context.ApplicationInstance.CompleteRequest ( ) ;",Can `` EndResponse '' increase performance of ASP.Net page "C_sharp : I 'm reading up more about async here : http : //msdn.microsoft.com/en-us/library/hh873173 ( v=vs.110 ) .aspxGoing through this example : I wonder , if I 'm already performing await on Task.WhenAny why do I need to await again inside of the try block ? If I already did this : Task < bool > recommendation = await Task.WhenAny ( recommendations ) ; Why do this : if ( await recommendation ) BuyStock ( symbol ) ; Task < bool > [ ] recommendations = … ; while ( recommendations.Count > 0 ) { Task < bool > recommendation = await Task.WhenAny ( recommendations ) ; try { if ( await recommendation ) BuyStock ( symbol ) ; break ; } catch ( WebException exc ) { recommendations.Remove ( recommendation ) ; } }",Capturing Exceptions on async operations C_sharp : This is a cursory question I ca n't quite answer.The main programHow do I implement the Util.Print method to get this output to the console : class Program { static void Main ( string [ ] args ) { Console.WriteLine ( `` Begin '' ) ; var myClass = new MyClass ( ) ; Util.Print ( myClass.Id ) ; Util.Print ( myClass.Server ) ; Util.Print ( myClass.Ping ) ; Console.WriteLine ( `` End '' ) ; } } BeginIdServerPingEnd,Print property name ( not what you would think ) "C_sharp : I am look for a reproducible example that can demonstrate how volatile keyword works . I 'm looking for something that works `` wrong '' without variable ( s ) marked as volatile and works `` correctly '' with it.I mean some example that will demonstrate that order of write/read operations during the execution is different from expected when variable is not marked as volatile and is not different when variable is not marked as volatile.I thought that I got an example but then with help from others I realized that it just was a piece of wrong multithreading code . Why volatile and MemoryBarrier do not prevent operations reordering ? I 've also found a link that demonstrates an effect of volatile on the optimizer but it is different from what I 'm looking for . It demonstrates that requests to variable marked as volatile will not be optimized out.How to illustrate usage of volatile keyword in C # Here is where I got so far . This code does not show any signs of read/write operation reordering . I 'm looking for one that will show.Edit : As I understand an optimization that causes reordering can come from JITer or from hardware itself . I can rephrase my question . Does JITer or x86 CPUs reorder read/write operations AND is there a way to demonstrate it in C # if they do ? using System ; using System.Threading ; using System.Threading.Tasks ; using System.Runtime.CompilerServices ; namespace FlipFlop { class Program { //Declaring these variables static byte a ; static byte b ; //Track a number of iteration that it took to detect operation reordering . static long iterations = 0 ; static object locker = new object ( ) ; //Indicates that operation reordering is not found yet . static volatile bool continueTrying = true ; //Indicates that Check method should continue . static volatile bool continueChecking = true ; static void Main ( string [ ] args ) { //Restarting test until able to catch reordering . while ( continueTrying ) { iterations++ ; a = 0 ; b = 0 ; var checker = new Task ( Check ) ; var writter = new Task ( Write ) ; lock ( locker ) { continueChecking = true ; checker.Start ( ) ; } writter.Start ( ) ; checker.Wait ( ) ; writter.Wait ( ) ; } Console.ReadKey ( ) ; } static void Write ( ) { //Writing is locked until Main will start Check ( ) method . lock ( locker ) { WriteInOneDirection ( ) ; WriteInOtherDirection ( ) ; //Stops spinning in the Check method . continueChecking = false ; } } [ MethodImpl ( MethodImplOptions.NoInlining ) ] static void WriteInOneDirection ( ) { a = 1 ; b = 10 ; } [ MethodImpl ( MethodImplOptions.NoInlining ) ] static void WriteInOtherDirection ( ) { b = 20 ; a = 2 ; } static void Check ( ) { //Spins until finds operation reordering or stopped by Write method . while ( continueChecking ) { int tempA = a ; int tempB = b ; if ( tempB == 10 & & tempA == 2 ) { continueTrying = false ; Console.WriteLine ( `` Caught when a = { 0 } and b = { 1 } '' , tempA , tempB ) ; Console.WriteLine ( `` In `` + iterations + `` iterations . `` ) ; break ; } } } } }",A reproducible example of volatile usage "C_sharp : Can I have all the options like OnlyOnRanToCompletion , OnlyOnCanceled , NotOnFaulted , etc . using async/await ? I ca n't find examples on how to achieve the same results as using Tasks , for instance : I 'm not sure if simple conditional or exception handling can manage all the continuation behaviors available in explicit Tasks . Task.Factory.StartNew ( foo ) .ContinueWith ( bar , TaskContinuationOptions.NotOnRanToCompletion ) ;",How to set TaskContinuationOptions using async/await ? "C_sharp : I 'm calling a delegate ( dynamically configurable service ) using : At this point I want to catch all exceptions that occurred in the called service method , however , I do not want to catch any exception that occurred due to the DynamicInvoke call . E.g . : service delegate throws DomainException - > catch the exceptionDynamicInvoke ( ) throws MemberAccessException because the delegate is a private method - > do not catch the exception , let it bubble upI hope it is clear what I 'm asking . How to decide whether a catched exception originates from the DynamicInvoke call itself or from the underlying delegate.Oh yeah , and : I can not use the exception type to decide ! It is completely possible that the service itself throws a MemberAccessException as well , because it could do some delegate stuff itself ... public void CallService ( Delegate service , IContext ctx ) { var serviceArgs = CreateServiceArguments ( service , ctx ) ; service.DynamicInvoke ( serviceArgs ) ; }",Delegate.DynamicInvoke - catch exception "C_sharp : I 'm trying to write an app that communicates with an OAuth URL . Communication with the OAuth URL behaves appropriately , and the user is correctly prompted to log in . However , due to restrictions in the redirect URL for the app , I am unable to redirect to an ms-app domain ( which I believe is how you open a UWP app on Windows 10 - please correct me if this assumption is incorrect ! ) .Other than hosting my own website and having a redirect created , does anyone know how to do this ? The code I 'm currently using for the client is the sample code : The issue manifests itself like this : try { var webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync ( WebAuthenticationOptions.None , url ) ; switch ( webAuthenticationResult.ResponseStatus ) { case WebAuthenticationStatus.Success : // Successful authentication . result = webAuthenticationResult.ResponseData.ToString ( ) ; break ; case WebAuthenticationStatus.ErrorHttp : // HTTP error . result = webAuthenticationResult.ResponseErrorDetail.ToString ( ) ; break ; default : // Other error . result = webAuthenticationResult.ResponseData.ToString ( ) ; break ; } } catch ( Exception ex ) { // Authentication failed . Handle parameter , SSL/TLS , and Network Unavailable errors here . result = ex.Message ; }",Redirect to UWP app from OAuth without ms-app "C_sharp : Had a coworker ask me this , and in my brain befuddled state I did n't have an answer : Why is it that you can do : But not : If there 's an implicit cast/operation for string conversion when you are concatenating , why not the same when assigning it as a string ? ( Without doing some operator overloading , of course ) string ham = `` ham `` + 4 ; string ham = 4 ;","Strings and ints , implicit and explicit" "C_sharp : BackgroundThe background for this is that I had a recent conversation in the comments with another clearly knowledgeable user about how LINQ is compiled . I first `` summarized '' and said LINQ was compiled to a for loop . While this is n't correct , my understanding from other stacks such as this one is that the LINQ query is compiled to a lambda with a loop inside of it . This is then called when the variable is enumerated for the first time ( after which the results are stored ) . The other user said that LINQ takes additional optimizations such as hashing . I could n't find any supporting documentation either for or against this.I know this seems like a really obscure point but I have always felt that if I do n't understand how something works completely , its going to be difficult to understand why I 'm not using it correctly.The QuestionSo , lets take the following very simple example : What is this statement actually compiled to in CLR ? What optimizations does LINQ take over me just writing a function that manually parses the results ? Is this just semantics or is there more to it than that ? ClarificationClearly I 'm asking this question because I do n't understand what the inside of the LINQ `` black box '' looks like . Even though I understand that LINQ is complicated ( and powerful ) , I 'm mostly looking for a basic understanding of either the CLR or a functional equivalent to a LINQ statement . There are great sites out there for helping understand how to create a LINQ statement but very few of these seem to give any guidance on how those are actually compiled or run.Side Note - I will absolutely read through the John Skeet series on linq to objects.Side Note 2 - I should n't have tagged this as LINQ to SQL . I understand how ORM 's and micro-ORM 's work . That is really besides the point of the question . var productNames = from p in products where p.Id > 100 and p.Id < 5000 select p.ProductName ;",What is LINQ Actually Compiled To ? "C_sharp : I want to change the date picker by upper-casing the first letter of the month . Currently I 'm using the set culture info in the thread and specify the format there , but for my culture the month is always all lowercase : Displays : And I would like to have : How can I change that ? CultureInfo ci = new CultureInfo ( `` es-MX '' ) ; ci.DateTimeFormat.ShortDatePattern = `` ddd dd/MMM/yyyy '' ; Thread.CurrentThread.CurrentCulture = ci ; Dom 19/ago/2012 Dom 19/Ago/2012",Change date picker text : capitalize month "C_sharp : I have a class : I have a List of Myobject objects : How to sort this list with condition : sort Name first & sort Age later . With this list , the result after sorting : public class MyObject { public string Name ; public int Age ; } Name AgeABC 12BBC 14ABC 11 Name AgeABC 11ABC 12BBC 14",How to sort a List in C # "C_sharp : I am experiencing a very weird problem with our test code in a commercial product under Windows 7 64 bit with VS 2012 .net 4.5 compiled as 64 bit.The following test code , when executed in a separate project behaves as expected ( using a NUnit test runner ) : The test returns as the comparison with < float.Epsilon is always true for x , y and z being 0.0f.Now here is the weird part . When I run this code in the context of our commercial product then this test fails . I know how stupid this sounds but I am getting the exception thrown . I 've debugged the issue and when I evaluate the condition it is always true but the compiled executable still does not go into the true branch of the condition and throws the exception.In the commercial product this test case only fails when my test case performs additional set-up code ( designed for integration tests ) where a very large system is initialized ( C # , CLI and a very large C++ part ) . I can not dig further in this set up call as it practically bootstraps everything.I am not aware of anything in C # that would have influence of an evaluation.Bonus weirdness : When I compare with less-or-equal with float.Epsilon : then the test succeeds . I have tried comparing with only less-than and float.Epsilon*10 but this did not work : I 've been unsuccessfully googling that issue and even though posts of Eric Lippert et al . tend to go towards float.Epsilon I do not fully understand what effect is applied on my code.Is it some C # setting , does the massive native-to-managed and vice versa influences the system . Something in the CLI ? Edit : Some more things to discover : I 've used GetComponentParts from this MSDN page http : //msdn.microsoft.com/en-us/library/system.single.epsilon % 28v=vs.110 % 29.aspx to visualize my mantiassa end exponents and here are the results : Test code : Without the entire boostrap chain I get ( test passes ) With full bootstrapping chain I get ( test fails ) Things to notice : The float.Epsilon has lost its last bit in its mantissa.I ca n't see how the /fp compiler flag in C++ influences the float.Epsilon representation.Edit and final verdictWhile it is possible to use a separate thread to obtain float.Epsilon it will behave different than expected on the thread with reduced FPU word.On the reduced FPU word thread this is the output of the `` thread-foreign '' float.EpsilonNote that the last mantissa bit is 1 as expected but this float value will still be interpreted as 0 . This of course makes sense as we are using a precision of a float that is bigger then the FPU word set but it may be a pitfall for somebody.I 've decided to move to a machine fps that is calculated once as described here : https : //stackoverflow.com/a/9393079/2416394 ( ported to float , of course ) [ Test ] public void Test ( ) { float x = 0.0f ; float y = 0.0f ; float z = 0.0f ; if ( ( x * x + y * y + z * z ) < ( float.Epsilon ) ) { return ; } throw new Exception ( `` This is totally bad '' ) ; } if ( ( x * x + y * y + z * z ) < = ( float.Epsilon ) ) // this works ! if ( ( x * x + y * y + z * z ) < ( float.Epsilon*10 ) ) // this does n't ! float x = 0.0f ; float y = 0.0f ; float z = 0.0f ; var res = ( x*x + y*y + z*z ) ; Console.WriteLine ( GetComponentParts ( res ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( GetComponentParts ( float.Epsilon ) ) ; 0 : Sign : 0 ( + ) Exponent : 0xFFFFFF82 ( -126 ) Mantissa : 0x00000000000001.401298E-45 : Sign : 0 ( + ) Exponent : 0xFFFFFF82 ( -126 ) Mantissa : 0x0000000000001 0 : Sign : 0 ( + ) Exponent : 0xFFFFFF82 ( -126 ) Mantissa : 0x00000000000000 : Sign : 0 ( + ) Exponent : 0xFFFFFF82 ( -126 ) Mantissa : 0x0000000000000 0 : Sign : 0 ( + ) Exponent : 0xFFFFFF82 ( -126 ) Mantissa : 0x0000000000001",Can something in C # change float comparison behaviour at runtime ? [ x64 ] "C_sharp : I 'm confused ! Today is November 3rdshazbot comes out to -1294967296Huh ? ? ? DateTime DateTime = new DateTime ( 2010,11,3 ) ; long shazbot = 1000000000 * DateTime.Day ;",1000000000 * 3 = -1294967296 ? "C_sharp : I am opening VS2010 solutions using C # and VS2010 automation . I open the solutions like this : The problem I am having is that when I create the instance of the VisualStudio.DTE.10.0 object , it starts the devenv.exe process from winlogon.exe which sees completely different environment than my application . Some of the environment variables are important for resolving some paths set in projects.Is there any how I can influence the environment variables of the devenv.exe process ? Is there any way how I could inject environment/properties using the VS2010 automation interfaces ? Type type = Type.GetTypeFromProgID ( `` VisualStudio.DTE.10.0 '' , true ) ; Object comObject = Activator.CreateInstance ( type ) ; ... sol.Open ( solution_full_path ) ;",Visual Studio 2010 automation and environment variables "C_sharp : I am having an issue deserializing time values into LocalTime- granted , I am pretty new to NodaTime . I want to import a web service result which lists a time in `` HH : mm '' format . I get an exception unless I use a time in `` hh : mm : ss.fff '' format . Is there a way to specify a different pattern and get `` HH : mm '' to work ? Please see this codeException being thrown : using System ; using System.Collections.Generic ; using Newtonsoft.Json ; using NodaTime ; using NodaTime.Serialization.JsonNet ; using NodaTime.Text ; // Required for LocalTimePatternnamespace TestNodaTime { class MyObject { [ JsonProperty ( `` var1 '' ) ] public int MyProperty { get ; set ; } [ JsonProperty ( `` time '' ) ] public LocalTime MyTime { get ; set ; } } class Program { static void Main ( string [ ] args ) { string serializedObject1 = `` [ { \ '' var1\ '' : \ '' 42\ '' , \ '' time\ '' : \ '' 01:02:03.004\ '' } ] '' ; string serializedObject2 = `` [ { \ '' var1\ '' : \ '' 42\ '' , \ '' time\ '' : \ '' 01:02\ '' } ] '' ; JsonSerializerSettings jss = new JsonSerializerSettings ( ) ; jss.ConfigureForNodaTime ( DateTimeZoneProviders.Bcl ) ; // This works - the pattern is `` hh : mm : ss.fff '' MyObject mo1 = JsonConvert.DeserializeObject < List < MyObject > > ( serializedObject1 , jss ) [ 0 ] ; // This causes an exception - the pattern is `` HH : mm '' MyObject mo2 = JsonConvert.DeserializeObject < List < MyObject > > ( serializedObject2 , jss ) [ 0 ] ; /* * An unhandled exception of type 'NodaTime.Text.UnparsableValueException ' occurred in Newtonsoft.Json.dll * Additional information : The value string does not match a quoted string in the pattern . * Value being parsed : '01:02^ ' . ( ^ indicates error position . ) */ } } } NodaTime.Text.UnparsableValueException was unhandled HResult=-2146233033 Message=The value string does not match a quoted string in the pattern . Value being parsed : '01:02^ ' . ( ^ indicates error position . ) Source=NodaTime StackTrace : at NodaTime.Text.ParseResult ` 1.GetValueOrThrow ( ) at NodaTime.Text.ParseResult ` 1.get_Value ( ) at NodaTime.Serialization.JsonNet.NodaPatternConverter ` 1.ReadJsonImpl ( JsonReader reader , JsonSerializer serializer ) at NodaTime.Serialization.JsonNet.NodaConverterBase ` 1.ReadJson ( JsonReader reader , Type objectType , Object existingValue , JsonSerializer serializer ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable ( JsonConverter converter , JsonReader reader , Type objectType , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue ( JsonProperty property , JsonConverter propertyConverter , JsonContainerContract containerContract , JsonProperty containerProperty , JsonReader reader , Object target ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject ( Object newObject , JsonReader reader , JsonObjectContract contract , JsonProperty member , String id ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList ( IList list , JsonReader reader , JsonArrayContract contract , JsonProperty containerProperty , String id ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , Object existingValue , String id ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal ( JsonReader reader , Type objectType , JsonContract contract , JsonProperty member , JsonContainerContract containerContract , JsonProperty containerMember , Object existingValue ) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize ( JsonReader reader , Type objectType , Boolean checkAdditionalContent ) at Newtonsoft.Json.JsonSerializer.DeserializeInternal ( JsonReader reader , Type objectType ) at Newtonsoft.Json.JsonSerializer.Deserialize ( JsonReader reader , Type objectType ) at Newtonsoft.Json.JsonConvert.DeserializeObject ( String value , Type type , JsonSerializerSettings settings ) at Newtonsoft.Json.JsonConvert.DeserializeObject [ T ] ( String value , JsonSerializerSettings settings ) at TestNodaTime.Program.Main ( String [ ] args ) at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) InnerException :",Deserializing LocalTime from JSON using JSON.NET and NodaTime results in NodaTime.Text.UnparsableValueException C_sharp : I know what this code is doing but I 'm not sure on the syntax . It does n't seem to conform to a `` standard '' format . Is it mostly LINQ ? The first part makes sense but it 's the part in the brackets I do n't understand . How can we use s without declaring it ? And how are we putting logic into a method call ? return db.Subjects.SingleOrDefault ( s = > s.ID == ID ) ;,How does this LINQ Expression work ? "C_sharp : This is an example , I 'm just curious as to how it would be achieved.I want to enable only subclasses of Animal to be able to set the number of legs that they have , but I still want them to be able to set their own colour . Therefore , I want to restrict classes further down the hierarchy from then altering this Legs property.For example , I want to eliminate this kind of subclass : How would this be achieved ? I 'm aware that I could stop overriding in a subclass by sealing the implementation of a function in the parent class . I tried this with the Legs property but I could n't get it to work.Thanks public abstract class Animal { public string Colour { get ; protected set ; } public int Legs { get ; protected set ; } public abstract string Speak ( ) ; } public class Dog : Animal { public Dog ( ) { Legs = 4 ; } public override string Speak ( ) { return `` Woof '' ; } } public sealed class Springer : Dog { public Springer ( ) { Colour = `` Liver and White '' ; } } public sealed class Chihuahua : Dog { public Chihuahua ( ) { Colour = `` White '' ; } public override string Speak ( ) { return `` *annoying* YAP ! `` ; } } public sealed class Dalmatian : Dog { public Dalmatian ( ) { Legs = 20 ; Colour = `` Black and White '' ; } }",How do I limit overriding in a hierarchy ? "C_sharp : I want to make a route that catches all `` php '' files ... I 've tried : But I get the following exception : It must catch : I want to write a single rule that can catch N levels ... How can I do that ? routes.MapRoute ( `` php '' , `` { *x } .php '' , new { controller = ... } ) ; A path segment that contains more than one section , such as a literal sectionor a parameter , can not contain a catch-all parameter.Parameter : routeUrl /p1/p2/p3.php/p1/p2.php/p1.php",How can I write a route to catch *.php ? "C_sharp : I am using MEF to create `` plugins '' for my WPF application . Some of these plugins I want to embed directly into the EXE file as the EXE needs to be standalone . I am using Costura by Fody to embed the resource along with all my other references . As the exe file needs to be standalone I am unable to create a directory for these plugins and use the DirectoyCatalogIs there anyway I can either load the assembly from the embedded resource , or simply specify the assembly name such as : I have tried looping through the Manifest resources but these appear to be zipped by Fody : Any help/suggestions appreciated . catalog.Catalogs.Add ( new AssemblyCatalog ( `` My.Assembly.Name ) ) ; var resourceNames = GetType ( ) .Assembly.GetManifestResourceNames ( ) ; foreach ( var resourceName in resourceNames )",MEF - Get assembly from embedded DLL "C_sharp : Various answers suggest it is a bad idea to sleep inside a thread , for example : Avoid sleep . Why exactly ? One reason often given is that it is difficult to gracefully exit the thread ( by signalling it to terminate ) if it is sleeping.Let 's say I wanted to periodically check for new files in a network folder , maybe once every 10s . This seems perfect for a thread with the priority set to low ( or lowest ) because I do n't want the potentially time-consuming file I/O to impact my main thread.What are the alternatives ? Code is given in Delphi but would apply equally to any multi-threaded application : A minor modification might be : but this still involves a Sleep ... procedure TNetFilesThrd.Execute ( ) ; begin try while ( not Terminated ) do begin // Check for new files // ... // Rest a little before spinning around again if ( not Terminated ) then Sleep ( TenSeconds ) ; end ; finally // Terminated ( or exception ) so free all resources ... end ; end ; // Rest a little before spinning around againnSleepCounter : = 0 ; while ( not Terminated ) and ( nSleepCounter < 500 ) do begin Sleep ( TwentyMilliseconds ) ; Inc ( nSleepCounter ) ; end ;",Alternative to sleep inside a thread "C_sharp : What is the actual difference , advantages and disadvantages , of creating a new event handler , vs assigning it directly to the event ? vs _gMonitor.CollectionChanged += new NotifyCollectionChangedEventHandler ( OnCollectionChanged ) ; _gMonitor.CollectionChanged += OnCollectionChanged ;",Attaching Eventhandler with New Handler vs Directly assigning it "C_sharp : How do I use the Task.Factory.FromAsync factory for an end method that returns multiple values via `` out '' parameters ? The begin method has this signature : End method is : Can I some how use : public virtual System.IAsyncResult BeginGetCaseStatus ( int CaseOID , int ClientOID , System.AsyncCallback @ __Callback , object @ __UserData ) public virtual void EndGetCaseStatus ( System.IAsyncResult @ __AsyncResult , out DTGenericCode [ ] BasicStatus , out DTGenericCode [ ] ARStatus ) public Task < ? > GetCaseStatusAsync ( int CaseOID , int ClientOID ) { return Task.Factory.FromAsync ( BeginGetCaseStatus ( CaseOID , ClientOID , null , null ) , EndGetCaseStatus ( ? , ? ) ) ; }",Task.Factory.FromAsync with `` out '' parameters in End Method "C_sharp : C # 's ref locals are implemented using a CLR feature called managed pointers , that come with their own set of restrictions , but luckily being immutable is not one of them . I.e . in ILAsm if you have a local variable of managed pointer type , it 's entirely possible to change this pointer , making it `` reference '' another location . ( C++/CLI also exposes this feature as interior pointers . ) Reading the C # documentation on ref locals it appears to me that C # 's ref locals are , even though based on the managed pointers of CLR , not relocatable ; if they are initialized to point to some variable , they can not be made to point to something else . I 've tried usingand similar constructs , to no avail.I 've even tried to write a small struct wrapping a managed pointer in IL , it works as far as C # is concerned , but the CLR does n't seem to like having a managed pointer in a struct , even if in my usage it does n't ever go to the heap.Does one really have to resort to using IL or tricks with recursion to overcome this ? ( I 'm implementing a data structure that needs to keep track of which of its pointers were followed , a perfect use of managed pointers . ) ref object reference = ref some_var ; ref reference = ref other_var ;",Is it possible to reassign a ref local ? "C_sharp : I 'm using LINQ To Sql ( not Entity Framework ) , the System.Data.Linq.DataContext library , hitting a SQL Server 2005 database and using .Net Framework 4.The table dbo.Dogs has a column `` Active '' of type CHAR ( 1 ) NULL . If I was writing straight SQL the query would be : The LINQ query is this : The SQL that gets generated from the above LINQ query converts the Active field to UNICODE . This means I can not use the index on the dbo.Dogs.Active column , slowing the query significantly : Is there anything I can do to stop Linq to Sql from inserting that UNICODE ( ) call ( and thus losing the benefit of my index on dogs.Active ) ? I tried wrapping the parameters using the EntityFunctions.AsNonUnicode ( ) method , but that did no good ( it inserted a CONVERT ( ) to NVARCHAR instead of UNICODE ( ) in the generated sql ) , eg : SELECT * FROM dbo.Dogs where Active = ' A ' ; from d in myDataContext.Dogs where d.Active == ' A ' select d ; SELECT [ t0 ] .Name , [ t0 ] .ActiveFROM [ dbo ] . [ Dog ] AS [ t0 ] WHERE UNICODE ( [ t0 ] . [ Active ] ) = @ p1 ... where d.Active.ToString ( ) == EntityFunctions.AsNonUnicode ( ' A'.ToString ( ) ) ;",LINQ to SQL will not generate sargable query "C_sharp : This code consumes near zero CPU ( i5 family ) In my code performance difference compared to SemaphoreSlim is 3x times or more for the case when spinning is really justified ( 5 Mops ) . However , I am concerned about using it for long-term wait . The standard advice is to implement two-phase wait operation . I could check NextSpinWillYield property and introduce a counter+reset to increase the default spinning iterations without yielding , and than back off to a semaphore.But what are downsides of using just SpinWait.SpinOnce for long-term waiting ? I have looked through its implementation and it properly yields when needed . It uses Thread.SpinWait which on modern CPUs uses PAUSE instruction and is quite efficient according to Intel.One issue that I have found while monitoring Task Manager is that number of threads if gradually increasing due to the default ThreadPool algorithm ( it adds a thread every second when all tasks are busy ) . This could be solved by using ThreadPool.SetMaxThreads , and then the number of threads is fixed and CPU usage is still near zero.If the number of long-waiting tasks is bounded , what are other pitfalls of using SpinWait.SpinOnce for long-term waiting . Does it depend on CPU family , OS , .NET version ? ( Just to clarify : I will still implement two-phase waiting , I am just curios why not using SpinOnce all the time ? ) public void SpinWait ( ) { for ( int i = 0 ; i < 10000 ; i++ ) { Task.Factory.StartNew ( ( ) = > { var sw = new SpinWait ( ) ; while ( true ) { sw.SpinOnce ( ) ; } } ) ; } }",C # SpinWait for long-term waiting C_sharp : For example let 's declare : And now we can do the following : So we 're really not hiding the List from usage but only hide it behind interface . How to hide the list in such example without copying _strings in the new collection to restrict modification of the list ? private readonly List < string > _strings = new List < string > ( ) ; public IEnumerable < string > Strings { get { return _strings ; } } ( ( List < string > ) obj.Strings ) .Add ( `` Hacked '' ) ;,How to avoid public access to private fields ? "C_sharp : here is my validation code : this code runs fine when used in a desktop app ( .net 4.6 ) the code fails when used in a .net core asp 2.1 controller with the following exception raised by schemas.Compile ( ) ; : XmlSchemaException : Type 'http : //some.domain.org : tAccountingItemTypes ' is not declared.It seems that related schema files are not loaded in the asp core app . How can I force loading of related schemas ? the schemas are : base.xsdenums.xsd string xsdPath = `` base.xsd '' ; XDocument doc = XDocument.Load ( xmlPath ) ; XmlSchemaSet schemas = new XmlSchemaSet ( ) ; schemas.Add ( `` http : //some.domain.org '' , xsdPath ) ; schemas.Compile ( ) ; bool isValid = true ; doc.Validate ( schemas , ( o , e ) = > { res.AddMessage ( MessageSeverities.Error , $ '' { e.Severity } : { e.Message } '' ) ; isValid = false ; } ) ; if ( isValid ) { res.AddMessage ( MessageSeverities.Notice , $ '' { formFile.FileName } is valid ! `` ) ; } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < xs : schema targetNamespace= '' http : //some.domain.org '' xmlns= '' http : //some.domain.org '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' elementFormDefault= '' qualified '' > < xs : include id= '' enums '' schemaLocation= '' enums.xsd '' / > < xs : complexType name= '' tAccountingLines '' > < xs : sequence > < xs : element name= '' AccountingLine '' type = '' tAccountingLine '' > < /xs : element > < /xs : sequence > < /xs : complexType > < xs : complexType name= '' tAccountingLine '' > < xs : sequence > < xs : element name= '' AccountingType '' type= '' tAccountingItemTypes '' > < /xs : element > < /xs : element > < /xs : sequence > < /xs : complexType > < /xs : schema > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < xs : schema targetNamespace= '' http : //some.domain.org '' xmlns= '' http : //some.domain.org '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' elementFormDefault= '' qualified '' > < xs : simpleType name= '' tAccountingItemTypes '' > < xs : restriction base= '' xs : string '' > < xs : enumeration value= '' V1 '' / > < xs : enumeration value= '' V2 '' / > < xs : enumeration value= '' V3 '' / > < /xs : restriction > < /xs : simpleType > < /xs : schema >",different behavior for Full Framework and .NET Core for xml schema compilation "C_sharp : I need a regular expression that Contain at least two of the five following character classes : Lower case characters Upper case characters NumbersPunctuation “ Special ” characters ( e.g . @ # $ % ^ & * ( ) _+|~-=\ { } [ ] : '' ; ' < > / ` etc . ) This is I have done so farbut Char.IsSymbol is returning false on @ % & $ . ? etc..and through regexbut I need a single regular expression with `` OR '' condition . int upperCount = 0 ; int lowerCount = 0 ; int digitCount = 0 ; int symbolCount = 0 ; for ( int i = 0 ; i < password.Length ; i++ ) { if ( Char.IsUpper ( password [ i ] ) ) upperCount++ ; else if ( Char.IsLetter ( password [ i ] ) ) lowerCount++ ; else if ( Char.IsDigit ( password [ i ] ) ) digitCount++ ; else if ( Char.IsSymbol ( password [ i ] ) ) symbolCount++ ; Regex Expression = new Regex ( `` ( { ( ? =.* [ a-z ] ) ( ? =.* [ A-Z ] ) . { 8 , } } | { ( ? =.* [ A-Z ] ) ( ? ! .*\\s ) . { 8 , } } ) '' ) ; bool test= Expression.IsMatch ( txtBoxPass.Text ) ;",regular expression for strong password "C_sharp : I 've written an extension method on IQueryable which returns the same type of IQueryable , just filtered a bit.Let 's say it 's something like that : calling the above method is as simple as someLinqResult.Foo ( 2 ) I need other method that will return instance of other generic class , but with other base class ( not the same as source T above ) .So , here 's the code , let 's assume this method is supposed to return a list of given type ( other than the input type which IQueryable has ! ) but the same length [ the actual problem is about transforming NHibernate query results , but it does n't matter ) : now , given that the strLinqResult is IQueryable < string > , I need to call it strLinqResult.Bar < int , string > ( ) ; .The point is I have to pass both types , even though the first one is already known as I 'm calling the method on already defined IQuerable . Since it was enough to call Foo ( 2 ) and not Foo < string > ( 2 ) I thought the compiler is able to `` pass/guess '' the type automatically . So why do I need to call the second method Bar < int , string > ( ) ; and not just Bar < int > ( ) ? the actual code : ApplyListRequestParams is kind of Foo method from the example code - it just applies pagination & ordering params available in ListRequest object.Items is a public List < T > Items in a class ListResponse < T > . TranslateTo is a method from ServiceStack . The above method called on IQueryable < T > returned by NHibernate ( T is Domain Model ) takes the request parameters ( ordering , pagination ) , applies them , and then transforms the results list from DomainModel to DTO Object of type TResponse . The list is then wrapped in a generic response class ( generic , so it is reusable for many DTO types ) public static IEnumerable < T > Foo < T > ( this IEnumerable < T > source , int ? howmany = null ) { if ( howmany.HasValue ) return source.Take ( howmany.Value ) ; return source ; } public static List < TTarget > Bar < TTarget , TSource > ( this IEnumerable < TSource > source ) { return new List < TTarget > ( source.Count ( ) ) ; } public static ListResponse < TResponse > BuildListResponse < T , TResponse > ( this IQueryable < T > iq , ListRequest request ) where TResponse : new ( ) { var result = iq.ApplyListRequestParams ( request ) .ToList ( ) .ConvertAll ( x = > x.TranslateTo < TResponse > ( ) ) ; var tcount = iq.Count ( ) ; return new ListResponse < TResponse > { Items = result , _TotalCount = tcount , _PageNumber = request._PageNumber ? ? 1 , } ; }",generic extension method on IQueryable < T > "C_sharp : I have a lot of serialized objects saved as XML , but I would like to add 2 variables to these objects.Here is my object : This object has been serialized quite a bit , and I want keep the ability to read these `` older '' files into my application.But I need to add a few more variables to make the object better , such as : Can anyone suggest the best method to add these new variables ? I actually changed MyObject and added the dictionary and I believe it is no longer being read in properly.Thanks in advance ! Edit : I 'm also not able to catch an exception anywhere to see where it fails when reading in the object , I 'm doing this to do so : Edit 2 : I believe this actually may be due to me using an Enum as part of the dictionary , I added [ Serializable ] above the enum and it still does n't work - thoughts ? public class MyObject { public Int32 MyVariables = 0 ; } public class MyObject { public Int32 MyVariables = 0 ; public Dictionary < string , MyEnum > MyDict = new Dictionary < string , MyEnum > ( ) ; } System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ( ) ; object obj = formatter.Deserialize ( File.Open ( Path , FileMode.Open ) ) ;",How to change a serialized object ? "C_sharp : I have the following two entities ( among many , but these give me the problem ) andWhen allowing EF to create my database it complained that I needed to turn off cascade delete because of multiple paths , which I have done as follows.The problem is , when the database is created I get two foreign keys , one is called StartAreaId , as I would expect , and the other is StartArea_StartAreaId . Only StartAreaId is being used . Why and how do I get rid of the StartArea_StartAreaId . If I remove the HasForeignKey in the context and remove the StartAreaId from the entity I get multiple StartArea_StartAreaId columns , as in StartArea_StartAreaId and StartArea_StartAreaId1 . What do I need to do to stop this from happening ? I just want StartAreaId as my foreign key . public class StartPoint { public int StartPointId { get ; set ; } public string Description { get ; set ; } public int StartPointNumber { get ; set ; } public int StartAreaId { get ; set ; } public StartArea StartArea { get ; set ; } } public class StartArea { public int StartAreaId { get ; set ; } public string Description { get ; set ; } public ICollection < StartPoint > StartPoints { get ; set ; } } modelBuilder.Entity < StartPoint > ( ) .HasRequired ( x = > x.StartArea ) .WithMany ( ) .HasForeignKey ( x = > x.StartAreaId ) .WillCascadeOnDelete ( false ) ;",EF 4.1 Code First Foreign Key adds Extra column "C_sharp : Just to clarify , I have this working using dynamic and MakeGenericType . But I cant help but think there is a better way to do this . What I am trying to do is create a `` plug-in '' loader , using Unity . I will just explain it as I post the code so you can get a sense for what I am doing.First I 'll just post the plug-in itself : Couple things to note here . First is the RegisterActionAttribute : Then the interfaces : All fairly straight forward . The goal here is just to attach some meta-data to the class when it is loaded . The loading happens via unity using a wrapper that simply loads the assemblies in the bin directory using a file search pattern and adds it to a singleton class with a collection of StrategyActions . I do n't need paste all the unity code here as I know it works and registers and resolves the assemblies . So now to the meat of the question . I have a function on the singleton that executes actions . These are applied with Unity.Interception HandlerAttributes and passed a string like so ( I can post the code for this but I did n't think it was relevant ) : The handler calls the following execute function on the singleton class to `` execute '' functions that are registered ( added to the collection ) . This execute is wrapped in an enumerator call which returns a collection of results , which sorts to manage dependencies and what not ( see below ) . These values are referenced by the caller using the Value property of ISTrategyResult { T } to do various things defined by other business rules.Now mind you , this works , and I get the return type that is specified by the plugins RegisterAction attribute . As you can see I am capturing the Type of the plugin and the return type . I am using the `` generic '' variable to resolve the type with unity through the use of MakeGenericType , which works fine . I am also creating a generic representing the return type based on the type from the collection . What I do n't like here is having to use dynamic to return this value to a function . I ca n't figure out a way to return this as a IStrategyResult { T } because obviously the caller to `` dynamic Execute ( ... '' can not , at run-time , imply return type of the function . I mulled around with making the call to Execute with a MakeGenericMethod call as I actually have the expected type the StrategyAction . It would be cool if I could some how figure out away to return a strongly typed result of IStrategyResult { T } while determining the type of T during the call . I do understand why I can not do this with my current implementation I am just trying to find a way to wrap all this functionality without using dynamic . And was hoping somebody could provide some advice that might be useful . If that means wrapping this with other calls to non-generic classes or something like that , that would be fine as well if that is the only solution . [ RegisterAction ( `` MyPlugin '' , typeof ( bool ) , typeof ( MyPlugin ) ) ] public class MyPlugin : IStrategy < bool > { public IStrategyResult < bool > Execute ( ISerializable info = null ) { bool result ; try { // do stuff result = true ; } catch ( Exception ) { result = false ; } return new StrategyResult < bool > { Value = result } ; } } [ AttributeUsage ( AttributeTargets.Class ) ] public sealed class RegisterActionAttribute : Attribute { public StrategyAction StrategyAction { get ; } public RegisterActionAttribute ( string actionName , Type targetType , Type returnType , params string [ ] depdencies ) { StrategyAction = new StrategyAction { Name = actionName , StrategyType = targetType , ResponseType = returnType , Dependencies = depdencies } ; } } public interface IStrategy < T > { IStrategyResult < T > Execute ( ISerializable info = null ) ; } public interface IStrategyResult < T > { bool IsValid { get ; set ; } T Value { get ; set ; } } [ ExecuteAction ( `` MyPlugin '' ) ] public dynamic Execute ( string action , params object [ ] parameters ) { var strategyAction = _registeredActions.FirstOrDefault ( a = > a.Name == action ) ; if ( strategyAction == null ) return null ; var type = typeof ( IStrategy < > ) ; var generic = type.MakeGenericType ( strategyAction.StrategyType ) ; var returnType = typeof ( IStrategyResult < > ) ; var genericReturn = returnType.MakeGenericType ( strategyAction.ResponseType ) ; var instance = UnityManager.Container.Resolve ( generic , strategyAction.Name ) ; var method = instance.GetType ( ) .GetMethod ( `` Execute '' ) ; return method.Invoke ( instance , parameters ) ; } public List < dynamic > ExecuteQueuedActions ( ) { var results = new List < dynamic > ( ) ; var actions = _queuedActions.AsQueryable ( ) ; var sortedActions = TopologicalSort.Sort ( actions , action = > action.Dependencies , action = > action.Name ) ; foreach ( var strategyAction in sortedActions ) { _queuedActions.Remove ( strategyAction ) ; results.Add ( Execute ( strategyAction.Name ) ) ; } return results ; }",Returning an instance of a generic type to a function resolved at runtime "C_sharp : I have a list of many words . What I need is to find all words ending on `` ing '' , `` ed '' , '' ied '' and with a single vowel and doubled consonant before : Should match words : begged , slamming , zagging . Not match helping ( `` lp '' -not double consonant ) It 's working on RegexPal.com , but it is not working in C # ( not matches any words , returns 0 words in list ) My code : Works when I do n't use \1 . But returns words with single consonant . \w* [ ^aoyie ] [ aoyie ] ( [ ^aoyie ] ) \1 ( ed|ing|ied ) List < Book_to_Word > allWords = ( from f in db2.Book_to_Words.AsEnumerable ( ) select f ) .ToList ( ) ; List < Book_to_Word > wordsNOTExist = ( from f in allWords where Regex.IsMatch ( f.WordStr , @ '' ^ ( \w* [ ^aoyie ] + [ aoyie ] ( [ ^aoyie ] ) ( ed|ing|ied ) ) $ '' ) select f ) .ToList ( ) ;",Regex.Match double consonants in c # "C_sharp : We can add Message header to WCF message by adding MessageHeader attribute like thisFirst question is , how secure is this , and is this working for all type of WCF bindings ? and the second question , is it possible to add encrypted header to all messages and extract in server part dynamical like this ? [ MessageContract ] public class HelloResponseMessage { [ MessageHeader ( ProtectionLevel=EncryptAndSign ) ] public string SSN { get { return extra ; } set { this.extra = value ; } } } MessageHeader header = MessageHeader.CreateHeader ( `` SessionKey '' , `` ns '' , _key ) ; OperationContext.Current.OutgoingMessageHeaders.Add ( header ) ;",Dynamically add encrypted WCF message header "C_sharp : Is there any type-safe , compile-time checked possibilty of referring to values that implement multiple interfaces ? GivenI 'm able to write code for objects implementing A or B , but not both . So I 've to come up with ugly wrappers : Is there a trick to write this code more intuitively without losing type-safety ( runtime-casts etc . ) ? E.g.Edit : This is not about having a list in particular - I just wanted to give a `` complete '' example with the issue of storing such values . My problem is just how to type a combination of both interfaces ( like A & B or A and B ) .Another more useful example : List < IDrawable & IMovable > ... interface A { void DoA ( ) ; } interface B { void DoB ( ) ; } class ABCollection { private class ABWrapper : A , B { private readonly A a ; private readonly B b ; public static ABWrapper Create < T > ( T x ) where T : A , B { return new ABWrapper { a = x , b = x } ; } public void DoA ( ) { a.DoA ( ) ; } public void DoB ( ) { b.DoB ( ) ; } } private List < ABWrapper > data = new List < ABWrapper > ( ) ; public void Add < T > ( T val ) where T : A , B { data.Add ( ABWrapper.Create ( val ) ) ; } } private List < A and B > ...",Typing polymorphic values with multiple interfaces in C # C_sharp : How can you do something like the following in C # ? I guess a better question is why ca n't you do that when you can do this : Type _nullableEnumType = typeof ( Enum ? ) ; Type _nullableDecimalType = typeof ( decimal ? ) ;,How to get Type of Nullable < Enum > ? "C_sharp : By another question about the maximum number of files in a folder , I noticed that is returning a System.In32 , but the Maximum value of a Int32 iswhile on NTFS ( an many other filesystems ) the maximum number of files can go far beyond that.on NTFS it is Which leads me to the interesting question : Is it possible to get the number of files in a folder on NTFS with the .NET framework , when the number of files exceeds the Int32.MaxValue , in an elegant and performing manner ? note : this is not a matter of why . and I know , those are a lot of files ; ) DirectoryInfo.GetFiles ( ) .Length 2.147.483.647 ( Int32.MaxValue ) 4.294.967.295 single files in one folder ( probably an Uint32 )",What if DirectoryInfo.GetFiles ( ) .Length exceeds Int32.MaxValue ? "C_sharp : Just ran across the problem described below . If `` Console.TreatControlCAsInput = true ; '' , you have to press [ enter ] twice on ReadLine ( ) .I 've written some demo code below . I am correct in surmising that this code demonstrate a bug in the .NET 4 framework ? Console.Write ( `` Test 1 : Console.TreatControlCAsInput = false\nType \ '' hello\ '' : `` ) ; { string readline = Console.ReadLine ( ) ; // type `` hello '' [ enter ] . Console.WriteLine ( `` You typed : { 0 } '' , readline ) ; // Prints `` hello '' . } Console.Write ( `` Test 2 : Console.TreatControlCAsInput = true\nType \ '' hello\ '' : `` ) ; Console.TreatControlCAsInput = true ; { string readline = Console.ReadLine ( ) ; // type `` hello '' [ enter ] . Console.WriteLine ( `` You typed : { 0 } '' , readline ) ; // Should print `` hello '' - but instead , you have to press [ enter ] // *twice* to complete the ReadLine ( ) command , and it adds a `` \r '' // rather than a `` \n '' to the output ( so it overwrites the original line ) } // This bug is a fatal error , because it makes all ReadLine ( ) commands unusable . Console.Write ( `` [ any key to exit ] '' ) ; Console.ReadKey ( ) ;",TreatControlCAsInput issue . Is this a bug ? "C_sharp : I have a C # requirement for individually processing a 'great many ' ( perhaps > 100,000 ) records . Running this process sequentially is proving to be very slow with each record taking a good second or so to complete ( with a timeout error set at 5 seconds ) .I would like to try running these tasks asynchronously by using a set number of worker 'threads ' ( I use the term 'thread ' here cautiously as I am not sure if I should be looking at a thread , or a task or something else ) .I have looked at the ThreadPool , but I ca n't imagine it could queue the volume of requests required . My ideal pseudo code would look something like this ... I will also need a mechanism that the processing method can report back to the parent/calling class.Can anyone point me in the right direction with perhaps some example code ? public void ProcessRecords ( ) { SetMaxNumberOfThreads ( 20 ) ; MyRecord rec ; while ( ( rec = GetNextRecord ( ) ) ! = null ) { var task = WaitForNextAvailableThreadFromPool ( ProcessRecord ( rec ) ) ; task.Start ( ) } }",How to use Threads for Processing Many Tasks "C_sharp : The struct System.DateTime and its cousin System.DateTimeOffset have their structure layout kinds set to `` Auto '' . This can be seen with : or : or it can be seen from the IL which declares : Normally a struct ( that is a .NET value type which is not an enum ) written with C # will have layout `` Sequential '' ( unless a StructLayoutAttribute has been applied to specify another layout ) .I searched through some common BCL assemblies , and DateTime and DateTimeOffset were the only publicly visible structs I found with this layout.Does anyone know why DateTime has this unusual struct layout ? typeof ( DateTime ) .IsAutoLayout /* true */ typeof ( DateTime ) .StructLayoutAttribute.Value /* Auto */ .class public auto ansi serializable sealed beforefieldinit System.DateTime ¯¯¯¯",Why does the System.DateTime struct have layout kind Auto ? C_sharp : Is there a way I can call a custom scalar DB function as part of my LINQ to Entities query ? The only thing I can find on the web about this is this page : https : //docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/how-to-call-custom-database-functionsHowever the instructions given here seem to assume you are using a DB-first approach and talk about modifying the .edmx file . What about if you 're using a code-first approach ? I want to be able to write something like this : var result = await ( from itm in _itemDataContext.Items where itm.QryGroup1 == `` Y '' & & _itemDataContext.Dbo_MyCustomScalarIntFn ( itm.QryGroup2 ) > 0 ) .ToArrayAsync ( ) ;,Calling a custom scalar DB function inside a LINQ to Entities query ? "C_sharp : I have an android mobile app , and i want to send webrequest to server to post some data , but before posting the data i send an http get request to get some data , and then sending post request , first i receive get successfully but when i send the post request it throws bellow exception on this line of my code requestStream.Write ( bytes , 0 , bytes.Length ) ; the exception is : System.ObjectDisposedException : Can not access a disposed object . Object name : 'System.Net.Sockets.NetworkStream'.and here is my get and post request codeGET : with this code i get receive my result without any problem , and here is my POST : i have searched and tried ways but i did not get the solution , and plus when i comment the first function , and only run the second function it will work fine but when i run the first and then the second it throws the exception , does anything belong to dispose the stream and web response from first code ? i think using statement is already disposes them.any help appreciated . public void GetTokenInfo ( ) { try { var uri = new Uri ( string.Format ( _host + `` webserver/SesTokInfo '' , string.Empty ) ) ; var webRequest = WebRequest.Create ( uri ) ; using ( var response = webRequest.GetResponse ( ) as HttpWebResponse ) { using ( var requestStream = response.GetResponseStream ( ) ) { using ( var reader = new StreamReader ( requestStream ) ) { var content = reader.ReadToEnd ( ) ; XmlDocument xDocument = new XmlDocument ( ) ; xDocument.LoadXml ( content ) ; XmlElement root = xDocument.DocumentElement ; if ( IsResponseReturned ( root ) ) { GlobalConfig.SessionId = root.GetElementsByTagName ( `` SesInfo '' ) [ 0 ] .InnerText ; GlobalConfig.Token = root.GetElementsByTagName ( `` TokInfo '' ) [ 0 ] .InnerText ; } } } } } catch ( Exception exception ) { Debug.WriteLine ( exception ) ; } } public WebResponse PostData ( string body , string url ) { WebResponse webResponse = null ; try { var uri = new Uri ( string.Format ( _host + url , string.Empty ) ) ; var webRequest = ( HttpWebRequest ) WebRequest.Create ( uri ) ; webRequest.Headers.Add ( `` Cookie '' , GlobalConfig.SessionId ) ; webRequest.Headers.Add ( `` _RequestVerificationToken '' , GlobalConfig.Token ) ; webRequest.Method = `` POST '' ; webRequest.ContentType = `` application/xml '' ; byte [ ] bytes = Encoding.UTF8.GetBytes ( body ) ; webRequest.ContentLength = bytes.Length ; Stream requestStream = webRequest.GetRequestStream ( ) ; requestStream.Write ( bytes , 0 , bytes.Length ) ; webResponse = webRequest.GetResponse ( ) ; } catch ( Exception exception ) { Console.WriteLine ( exception ) ; } return webResponse ; }","Xamarin Android httpwebrequest , Can not access a disposed object" "C_sharp : I noticed that start up times would vary depending on here I placed a piece of initialization code . I thought this was really weird , so I wrote up a small benchmark , which confirmed my suspicions . It seems that code that 's executed before the main method is invoked is slower than normal.Why does Benchmark ( ) ; run at different speeds depending on if called before and after the regular code path ? Here 's the benchmark code : The results show that Benchmark ( ) runs almost twice slower for both the static constructor and constructor for the static Program program property : Doubling the number of iterations in the benchmark loop causes all times to double , suggesting that the performance penalty incurred is not constant , but a factor . Why would this be the case ? It would make sense if initialization would be just as fast if it were done where it belongs . Testing was done in .NET 4 , release mode , optimizations on . class Program { static Stopwatch stopwatch = new Stopwatch ( ) ; static Program program = new Program ( ) ; static void Main ( ) { Console.WriteLine ( `` main method : '' ) ; Benchmark ( ) ; Console.WriteLine ( ) ; new Program ( ) ; } static Program ( ) { Console.WriteLine ( `` static constructor : '' ) ; Benchmark ( ) ; Console.WriteLine ( ) ; } public Program ( ) { Console.WriteLine ( `` public constructor : '' ) ; Benchmark ( ) ; Console.WriteLine ( ) ; } static void Benchmark ( ) { for ( int t = 0 ; t < 5 ; t++ ) { stopwatch.Reset ( ) ; stopwatch.Start ( ) ; for ( int i = 0 ; i < 1000000 ; i++ ) IsPrime ( 2 * i + 1 ) ; stopwatch.Stop ( ) ; Console.WriteLine ( stopwatch.ElapsedMilliseconds + `` ms '' ) ; } } static Boolean IsPrime ( int x ) { if ( ( x & 1 ) == 0 ) return x == 2 ; if ( x < 2 ) return false ; for ( int i = 3 , s = ( int ) Math.Sqrt ( x ) ; i < = s ; i += 2 ) if ( x % i == 0 ) return false ; return true ; } } // static Program program = new Program ( ) public constructor:894 ms895 ms887 ms884 ms883 msstatic constructor:880 ms872 ms876 ms876 ms872 msmain method:426 ms428 ms426 ms426 ms426 ms// new Program ( ) in Main ( ) public constructor:426 ms427 ms426 ms426 ms426 ms // static Program program = new Program ( ) public constructor:2039 ms2024 ms2020 ms2019 ms2013 msstatic constructor:2019 ms2028 ms2019 ms2021 ms2020 msmain method:1120 ms1120 ms1119 ms1120 ms1120 ms// new Program ( ) in Main ( ) public constructor:1120 ms1128 ms1124 ms1120 ms1122 ms",Code in static constructor runs slower "C_sharp : Say we have a method that looks like this : If I test that by doing this : The test will fail saying that it Expected : < System.ArgumentNullException > But was : nullI can fix that by changing the test to Is this just how you would usually do it ? Or is there a better way to write the test ? Or maybe a better way to write the method itself ? Tried to do the same with the built-in Select method , and it failed even without a ToArray or anything like that , so apparently there is something you can do about it ... I just do n't know what : p public IEnumerable < Dog > GrowAll ( this IEnumerable < Puppy > puppies ) { if ( subjects == null ) throw new ArgumentNullException ( `` subjects '' ) ; foreach ( var puppy in puppies ) yield return puppy.Grow ( ) ; } Puppy [ ] puppies = null ; Assert.Throws < ArgumentNullException > ( ( ) = > puppies.GrowAll ( ) ) ; Puppy [ ] puppies = null ; Assert.Throws < ArgumentNullException > ( ( ) = > puppies.GrowAll ( ) .ToArray ( ) ) ;","C # , NUnit : How to deal with testing of exceptions and deferred execution" "C_sharp : I am making a console application and I have a `` Menu '' where the user can enter information to create a new Person object . The following is inside a method . like so . I want the user to be able to exit the method at anytime if they decide they do n't want to be making a new person . So I 'd like to make a new method called `` CheckExit '' and if they type `` EXIT '' it will leave the `` CreatePerson '' method . So I want the `` CheckExit '' to return a return . Otherwise I have to add an `` if '' statement after every input and that gets clutter-y . Is this possible ? Does return have a return type ? What would be the proper way to do this ? Write ( `` Please enter the first name : `` , false ) ; string fName = Console.ReadLine ( ) .ToUpper ( ) ; Write ( `` Please enter the middle initial : `` , false ) ; string mInitial = Console.ReadLine ( ) .ToUpper ( ) ; Write ( `` Please enter the last name : `` , false ) ; string lName = Console.ReadLine ( ) .ToUpper ( ) ;",What is the return type of `` return '' C # "C_sharp : Is there a better way to manage a bunch of generic functions ? These all have a implementation that look almost the same . Changing them however is a monks job atm.The interface that 's implemented looks like this : Pretty but you can emagine how the implementation looks . And what if I want to change something to the signature of these methods . IProxy < T > AddInterceptor < T1 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , TResult > , T1 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , TResult > , T1 , T2 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , TResult > , T1 , T2 , T3 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , TResult > , T1 , T2 , T3 , T4 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , TResult > , T1 , T2 , T3 , T4 , T5 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , TResult > func ) ; IProxy < T > AddInterceptor < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , TResult > ( Expression < Action < T > > functionOrProperty , Func < Func < T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , TResult > , T1 , T2 , T3 , T4 , T5 , T6 , T7 , T8 , T9 , T10 , T11 , T12 , T13 , T14 , T15 , TResult > func ) ;",Maintaining a bunch of generic functions "C_sharp : ScopeI have developed a Wrapper for the Http Web Request class to execute Gets and Posts in an easier way . This library is being used without any problem for over two years already , but today , we faced a weird problem.There 's one website ( it will take a while to load ) , that apparently , keeps streaming characters to the HTML frontend , so our library `` Get '' request gets stuck into a loop.Different Timeout PropertiesLooking at the Http Web Request reference we find that there are two different timeout properties . We are using both of them , but none of them seem to abort properly.Read Write Timeout - Gets or sets a time-out in milliseconds when writing to or reading from a stream.Timeout - Gets or sets the time-out value in milliseconds for the GetResponse and GetRequestStream methods.One Timeout to Rule them allIs there any way to set an `` Operation Timeout '' that will force the stream/connection disposing after some pre-configured time ? Some Code SampleThis Code seem to work fine , but how do i read the response as string , since it is being constantly transmited ( as the browser shows ) ? QuestionWhat 's the proper way to handle websites like this ? ( By handle I mean to be able to identify and skip situations where the server simply wo n't stop transmitting ? ) public class Program { public static void Main ( ) { string url = `` http : //anus.io '' ; Console.WriteLine ( `` Initializing Request State Object '' ) ; RequestState myRequestState = new RequestState ( ) ; // Creating Http Request myRequestState.request = ( HttpWebRequest ) WebRequest.Create ( url ) ; myRequestState.request.Method = `` GET '' ; myRequestState.request.ReadWriteTimeout = 4000 ; myRequestState.request.Timeout = 4000 ; Console.WriteLine ( `` Begining Async Request '' ) ; IAsyncResult ar = myRequestState.request.BeginGetResponse ( new AsyncCallback ( ResponseCallback ) , myRequestState ) ; Console.WriteLine ( `` Waiting for Results '' ) ; ar.AsyncWaitHandle.WaitOne ( ) ; myRequestState.response = ( HttpWebResponse ) myRequestState.request.EndGetResponse ( ar ) ; Console.WriteLine ( `` Response status code = { 0 } '' , myRequestState.response.StatusCode ) ; } public static void ResponseCallback ( IAsyncResult asyncResult ) { Console.WriteLine ( `` Completed '' ) ; } }",.NET HTTP Request Timeout not `` Aborting '' on continuous streaming site "C_sharp : Usually answers to questions like this can be found either here or , if not here , on MSDN , but I have looked and looked and not found the answer . Experimentation seems to show that code like : does no harm . Or at least that firing the event does n't toss an exception ( that I can tell ) by trying to invoke a null event listener . However , there seems to be nowhere on the Web that will validate my hope that such code is n't doing at least something that I might not want done . For example , causing the Click event to think it has listeners when it might not , and wasting those ever-precious super-ultra-mini-microseconds in `` now let 's perform null-checks and invoke all listeners that are not null '' code.It seems that documentation should say what the behavior of the += and -= operators is if the listener on the RHS is null . But like I say , I ca n't find that documentation anywhere . I 'm sure someone here can provide it , though ... . ( Obviously , my code does n't have a hard-coded null ; my question is more about whether code like this is wasteful or completely harmless : or if I should [ i.e. , need to for any reason ] add null-checks around each such += operation . ) SomeControl.Click += null ; public static void AddHandlers ( [ NotNull ] this Button button , [ CanBeNull ] EventHandler click = null , [ CanBeNull ] EventHandler load = null ) { button.Click += click ; button.Load += load ; }",Is adding ( or removing ) a null event listener a no-op ? "C_sharp : I have this controllerBoth the GET and POST request returns a statuscode of 500 . This is the expected behavior.But when I add app.UseExceptionHandler ( `` /api/debug/error '' ) ; In the Startup.cs file , the POST request does no longer return a statuscode of 500 , instead it returns 404 . The GET request is still working as it should by returning a statuscode of 500.DebugControllerAny idé why adding app.UseExceptionHandler ( `` /api/debug/error '' ) ; would make the POST request behave this way ? A repo to reproduce this behavior can be found Here . [ Route ( `` api/ [ controller ] '' ) ] public class ValuesController : Controller { // GET api/values [ HttpGet ] public IEnumerable < string > Get ( ) { Console.WriteLine ( `` GET Index '' ) ; throw new Exception ( ) ; } // POST api/values [ HttpPost ] public void Post ( ) { Console.WriteLine ( `` POST Index '' ) ; throw new Exception ( ) ; } } [ Route ( `` api/ [ controller ] '' ) ] public class DebugController : Controller { [ HttpGet ( `` error '' ) ] public IActionResult Index ( ) { return StatusCode ( 500 , '' Hello , World ! From debug controller '' ) ; } }",ASP.NET Core returns 404 instead of 500 when using ExceptionHandler PipeLine "C_sharp : I got Invalid token `` = '' in class , struct or interface member declaration.This is C # 6 feature . How to convert it to C # 5 ? public List < string > MembershipIds { get ; set ; } = new List < string > ( ) ;",Convert C # 6.0 default propertyvalues to C # 5.0 "C_sharp : Why is IList defined like this ? Could n't it just beSo , to test I created these interfaces , just to be sure if that works ! While its perfectly fine , Resharper complains about `` Redundant interfaces '' .Any ideas why Microsoft went on with this implementation ? public interface IList < T > : ICollection < T > , IEnumerable < T > , IEnumerablepublic interface ICollection < T > : IEnumerable < T > , IEnumerablepublic interface IEnumerable < T > : IEnumerable public interface IList < T > : ICollection < T > public interface IOne { string One ( ) ; } public interface ITwo : IOne { string Two ( ) ; } public interface IThree : ITwo , IOne { string Three ( ) ; }",Why does IList < T > implement IEnumerable < T > and ICollection < T > while ICollection < T > itself implements IEnumerable < T > "C_sharp : First of all , I know that lock { } is synthetic sugar for Monitor class . ( oh , syntactic sugar ) I was playing with simple multithreading problems and discovered that can not totally understand how lockng some arbitrary WORD of memory secures whole other memory from being cached is registers/CPU cache etc . It 's easier to use code samples to explain what I 'm saying about : In the end ms_Sum will contain 100000000 which is , of course , expected.Now we age going to execute same cycle but on 2 different threads and with upper limit halved.Because of no synchronization we get incorrect result - on my 4-core machine it is random number nearly 52 388 219 which is slightly larger than half from 100 000 000 . If we enclose ms_Sum += 1 ; in lock { } , we , of cause , would get absolutely correct result 100 000 000 . But what 's interesting for me ( truly saying I was expecting alike behavior ) that adding lock before of after ms_Sum += 1 ; line makes answer almost correct : For this case I usually get ms_Sum = 99 999 920 , which is very close.Question : why exactly lock ( ms_Lock ) { ms_Counter += 1 ; } makes program completely correct but lock ( ms_Lock ) { } ; ms_Counter += 1 ; only almost correct ; how locking arbitrary ms_Lock variable makes whole memory stable ? Thanks a lot ! P.S . Gone to read books about multithreading.SIMILAR QUESTION ( S ) How does the lock statement ensure intra processor synchronization ? Thread synchronization . Why exactly this lock is n't enough to synchronize threads for ( int i = 0 ; i < 100 * 1000 * 1000 ; ++i ) { ms_Sum += 1 ; } for ( int i = 0 ; i < 50 * 1000 * 1000 ; ++i ) { ms_Sum += 1 ; } for ( int i = 0 ; i < 50 * 1000 * 1000 ; ++i ) { lock ( ms_Lock ) { } ; // Note curly brackets ms_Sum += 1 ; }",Threads synchronization . How exactly lock makes access to memory 'correct ' ? "C_sharp : I have a IQueryable list with COLOURS class typeI want to get random 2 rows , I am using this code block to do this : I want 2 rows but sometimes its getting 3 rows or 5 rows : Take ( 2 ) is not working - what 's the problem ? I have noticed something when I check Entire MEthod : IQueryable < COLOURS > renkler = dbcontext.colours.Select ( s= > new COLOURS { ... . renkler.OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( 2 ) ; var result = NewProducts ( ) .OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( 2 ) ; int result_count = result.Count ( ) ; //This value is 2 : D //but ToList ( ) result 5 : D public IQueryable < COLOURS > NewProducts ( ) { DateTime simdi = DateTime.Now ; DateTime simdi_30 = DateTime.Now.AddDays ( -30 ) ; var collection_products = DefaultColours ( ) .Where ( w = > ( ( w.add_date.Value > = simdi_30 & & w.add_date.Value < = simdi ) || w.is_new == true ) ) .OrderByDescending ( o = > o.add_date ) .Take ( 200 ) .Select ( s = > new COLOURS { colour_code = s.colour_code , model_code = s.products.model_code , sell_price = ( decimal ) s.sell_price , market_price = ( decimal ) s.market_price , is_new = ( bool ) s.is_new , product_id = ( int ) s.product_id , colour_name = s.name , product_name = s.products.name , description = s.products.description , img_path = s.product_images.FirstOrDefault ( f = > f.is_main == true ) .img_path , category_id = ( int ) s.category_relations.FirstOrDefault ( ) .category_id , display_order = ( short ) s.display_order , section_id = ( int ) s.products.section_id , stock_amount = s.pr_sizes.Where ( w = > w.is_active == true & & w.quantity > = 0 ) .Count ( ) > 0 ? ( int ) s.pr_sizes.Where ( w = > w.is_active == true & & w.quantity > = 0 ) .Sum ( s2 = > s2.quantity ) : 0 , section_name = s.products.pr_sections.name , } ) ; return collection_products ; } public IQueryable < COLOURS > RandomNewProducts ( int n ) { var result = NewProducts ( ) .OrderBy ( o = > Guid.NewGuid ( ) ) .Take ( n ) ; int result_count = result.Count ( ) ; //2 //When I run this method it 's getting 5 rows return result ; }",Lambda expressions order by and take issue "C_sharp : Let 's say I have an enum : Like it was said in the How should I convert a string to an enum in C # ? question , I parse enum from string , using Enum.Parse method : Unfortunately , it does n't work as expected with integer numbers , represented as strings.I do not expect Parse.Enum ( ) to convert int from string , but actually it does.A simple test : Only two checks of four can be passed.Enumer.ParseEnum ( `` 2 '' ) returns MyEnum.OptionTwo instead of null.Moreover , Enumer.ParseEnum ( `` 12345 '' ) returns 12345 , regardless it 's out of the scope.What is the best way to parse : Only string values of `` MyEnum.OptionOne '' , `` MyEnum.OptionTwo '' , `` MyEnum.OptionThree '' into their enum counterparts.Strings `` MyEnum.OptionOne '' , `` MyEnum.OptionTwo '' , `` MyEnum.OptionThree '' AND the values of 0 , 2 and 4 into MyEnum.OptionOne , MyEnum.OptionTwo , MyEnum.OptionThree respectively ? The link to the similar question How should I convert a string to an enum in C # ? does n't help with the test provided - it still converts strings as integers , even when they are out of the enum scope . public enum MyEnum { OptionOne = 0 , OptionTwo = 2 , OptionThree = 4 } public class Enumer { public static MyEnum ? ParseEnum ( string input ) { try { return ( MyEnum ) Enum.Parse ( typeof ( MyEnum ) , input ) ; } catch ( ArgumentException ) { return null ; } } } [ TestClass ] public class Tester { [ TestMethod ] public void TestEnum ( ) { Assert.AreEqual ( MyEnum.OptionTwo , Enumer.ParseEnum ( `` OptionTwo '' ) ) ; Assert.IsNull ( Enumer.ParseEnum ( `` WrongString '' ) ) ; Assert.IsNull ( Enumer.ParseEnum ( `` 2 '' ) ) ; // returns 2 instead of null Assert.IsNull ( Enumer.ParseEnum ( `` 12345 '' ) ) ; // returns 12345 instead of null } }",What is the best way to strictly parse string to enum ? "C_sharp : I need the weekdays abbreviation in different cultures . I have it in spanish already ( hardcoded ) . Are there something already in .NET that has it already ? //string [ ] days = { `` lunes '' , `` martes '' , `` miércoles '' , `` jeuves '' , `` viernes '' , `` sábado '' , `` domingo '' } ; string [ ] days = { `` L '' , `` M '' , `` X '' , `` J '' , `` V '' , `` S '' , `` D '' } ;",Is there anything in .NET that gets the abbreviation of all weekdays specific to culture ? "C_sharp : I need to create a Serializer to support all of the following tasks : Removing null propertiesRemoving Empty ListsI noticed the Syntax of the ODataMediaTypeFormatter has been changed.And I 'm having trouble adding my Serialzation provider to the pipe.Here what I 've tried : On WebApiConfig.cs : Plus I 've Created the following Odatameditatypeformatter : Currently I checked all the base methods and none of them seems to hit the breakpoint while creating a Get/Post request to my OData controllers.Any one managed to do it on the new version of Microsoft.Aspnet.OData 7.0.1 ? var odataFormatters = ODataMediaTypeFormatters.Create ( ) ; odataFormatters.Add ( new MyDataMediaTypeFormatter ( ) ) ; config.Formatters.InsertRange ( 0 , odataFormatters ) ; public class MyODataMediaTypeFormatter : ODataMediaTypeFormatter { static IEnumerable < ODataPayloadKind > payloadKinds = new List < ODataPayloadKind > { ODataPayloadKind.Asynchronous , ODataPayloadKind.Batch , ODataPayloadKind.BinaryValue , ODataPayloadKind.Collection , ODataPayloadKind.EntityReferenceLink , ODataPayloadKind.EntityReferenceLinks , ODataPayloadKind.Error , ODataPayloadKind.Delta , ODataPayloadKind.IndividualProperty , ODataPayloadKind.MetadataDocument , ODataPayloadKind.Parameter , ODataPayloadKind.Resource , ODataPayloadKind.ServiceDocument , ODataPayloadKind.Unsupported , ODataPayloadKind.Value } ; public MyODataMediaTypeFormatter ( ) : base ( payloadKinds ) { } }",OData WebApi V4 .net - Custom Serialization "C_sharp : I 've built a web application . When I built it I ticked 'Organizational Accounts'It works well - I log in with my Office 365 account and User.Identity.Name contains the email addressThis application is a replacement front end for an older ASP Classic app . The App has an existing security table that I need to use.I want to use the email address to look up a record in this table to get The internal database key for the user ( so I can use it in database calls ) The security level ( authorisation ) for the userI want to look this up as soon as I am authenticated and save these two values to Session to refer to laterI have an existing method that does all of this lookup and caching . I actually got it working by calling it from the _LoginPartial.cshtml view but clearly it is incorrect to be triggering this kind of thing from a viewHere 's the code to look up and cache user info . For now this is in AccountController.cs but it does n't have to beI think the reference to User.Identity.Name triggers the login process so I could either just try and call this at startup ( I do n't know the correct way to do this ) , or I think the proper thing to do is to call this using the OnAuthentication method , and to link it up I should pass the name of my function to the OnAuthenticated property . Here 's two links to the method and property : https : //msdn.microsoft.com/en-us/library/system.web.mvc.controller.onauthentication ( v=vs.118 ) .aspxhttps : //msdn.microsoft.com/en-us/library/microsoft.owin.security.microsoftaccount.microsoftaccountauthenticationprovider.onauthenticated ( v=vs.113 ) .aspxBut I have to say that OO programming is not my thing and I ca n't work out from these pages how to use them or which class to put them into.This page implies it needs to go into Startup.Auth.cs but my Startup.Auth.cs looks nothing like that one . Here is most of my Startup.Auth.cs which was mostly autogenerated when I ticked 'organisational ' at the start . ( On a side note , app.UseKentorOwinCookieSaver ( ) ; is my next challenge because apparently organisational login does n't work with Session can you believe it ! ! ! ) Can anyone help me add required code to call GetAdditionalUserInfo ( ) ? after login ? Or alternatively confirm that I can just call this at startup , and suggest the correct way to do it . private Boolean GetAdditionalUserInfo ( ) { // if authentication info is saved , do n't go find it if ( Session [ `` UID '' ] ! = null ) return true ; // get the db employee id from the database and save it to the session var r = ( from e in db.Employees where e.Email == User.Identity.Name select new { e.Emp_ID , e.Group_ID } ) .SingleOrDefault ( ) ; if ( ( r == null ) || ( r.Group_ID == ( int ) Role.Inactive ) ) { // could n't find record or inactive return false ; } // Update last login datetime Employee ell = db.Employees.Find ( r.Emp_ID ) ; ell.LastLogin = DateTime.Now ; db.SaveChangesAsync ( ) ; // Save user details to the session Session [ `` UID '' ] = r.Emp_ID ; // TBD : Investigate `` CLAIMS '' - this should probably be a claim Session [ `` Role '' ] = r.Group_ID ; return true ; } public partial class Startup { private static string clientId = ConfigurationManager.AppSettings [ `` ida : ClientId '' ] ; private static string aadInstance = ConfigurationManager.AppSettings [ `` ida : AADInstance '' ] ; private static string tenantId = ConfigurationManager.AppSettings [ `` ida : TenantId '' ] ; private static string postLogoutRedirectUri = ConfigurationManager.AppSettings [ `` ida : PostLogoutRedirectUri '' ] ; //private static string authority = aadInstance + tenantId ; // to make this multi tenant , use common endpoint , not the tenant specific endpointprivate static string authority = aadInstance + `` common '' ; public void ConfigureAuth ( IAppBuilder app ) { app.SetDefaultSignInAsAuthenticationType ( CookieAuthenticationDefaults.AuthenticationType ) ; // https : //stackoverflow.com/questions/20737578/asp-net-sessionid-owin-cookies-do-not-send-to-browser app.UseKentorOwinCookieSaver ( ) ; app.UseCookieAuthentication ( new CookieAuthenticationOptions ( ) ) ; app.UseOpenIdConnectAuthentication ( new OpenIdConnectAuthenticationOptions { ClientId = clientId , Authority = authority , PostLogoutRedirectUri = postLogoutRedirectUri , TokenValidationParameters = new TokenValidationParameters { // If you do n't add this , you get IDX10205 // from here http : //charliedigital.com/2015/03/14/adding-support-for-azure-ad-login-o365-to-mvc-apps/ ValidateIssuer = false } , Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = ctx = > { bool isAjaxRequest = ( ctx.Request.Headers ! = null & & ctx.Request.Headers [ `` X-Requested-With '' ] == `` XMLHttpRequest '' ) ; if ( isAjaxRequest ) { ctx.Response.Headers.Remove ( `` Set-Cookie '' ) ; ctx.State = NotificationResultState.HandledResponse ; } return System.Threading.Tasks.Task.FromResult ( 0 ) ; } } } ) ; } }",Capturing login event so I can cache other user information "C_sharp : Consider M , T , W , TH , F , S , SU are days of week.I have regex which is working well except for one scenario when there is no sequence of weekdays , i.e . there is no M , T , W , TH , F , S , SU at the expected location inside the string.For example , q10MT is valid but q10HT is invalid.Below is my expression : In case of q10MT , the output is q10MT which is correct , but in case of q10HT the output is q10 which is incorrect , my regex should return no value or empty string when there is no match.What changes do I need to make in order to achieve this ? string expression = `` q ( \\d* ) ( M ) ? ( T ( ? ! H ) ) ? ( W ) ? ( TH ) ? ( F ) ? ( S ( ? ! U ) ) ? ( SU ) ? `` ;",Match exactly one occurrence with regex "C_sharp : I tried VS2015 with my exisiting solution and I get some valid new errors ( like unreachable code that the compiler did n't catch before ) , but I also get an error for example on this line : I get the following error : Error CS1503 Argument 3 : can not convert from 'ref bool [ mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ' to 'ref bool [ mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 ] ' I can not see why it would throw that error , obviously the types do match . Is this a bug in the new compiler or has the behaviour of the ref keyword changed ? The function in this case is a C++ function which is imported to C # using a c # class derived from the c++ class . It 's signature is this : It might be good to mention that I opted to use the VS2013 c++ compiler for the c++ sources in the solution for now , so the c++ side should be the same as before . My guess is that something in the interop between c # and c++ changed . bool bWasAlreadyLocked = false ; oEnv.LockDoc ( oWarnings , oEventDoc , ref bWasAlreadyLocked ) ; void CBkgDocEnvX : :LockDoc ( CFIWarningList ^oWarnings , CBaseDoc ^oBaseDoc , // Outputbool % rbWasAlreadyLocked )",C # 6/C++ ref keyword error "C_sharp : I am using the LAME command line mp3 encoder in a project . I want to be able to see what version someone is using . if I just execute LAME.exe with no paramaters i get , for example : if i try redirecting the output to a text file using > to a text file the text file is empty . Where is this text accessable from when running it using System.Process in c # ? C : \LAME > LAME.exeLAME 32-bits version 3.98.2 ( http : //www.mp3dev.org/ ) usage : blah blahblah blahC : \LAME >",How do I capture command-line text that is not sent to stdout ? "C_sharp : I 'm digging in on how to structure projects and so I stumbled upon Onion Architecture . As far as I understand it , it 's more of a domain-centered-focus architecture instead of a database-driven type.I 'm looking for some github projects to study and learn more about the architecture , so I found this one https : //github.com/chetanvihite/OnionArchitecture.SampleI 'm having a hard time understanding : How he uses it is by constructor injection.Do you always expose a service such as IUserService to an app that consumes it ? But I noticed , IUserRepository has the same methods as IUserService ? If you say Infrastructure concerns , does it mean or does it involve a database ? Or not necessarily ? If not , what are examples of infrastructure concerns ? Do you have any recommendation on free projects/github projects that I can download to learn or study further about onion architecture ? I understand better on examplesP.S.As I 'm learning onion architecture , it always , if not always , at least it mention about DDD . So I guess , I 'll be learning DDD also : ) namespace Domain.Interfaces { public interface IUserRepository { IEnumerable < User > GetUsers ( ) ; } } namespace Services.Interfaces { public interface IUserService { IEnumerable < User > GetUsers ( ) ; } } namespace Services { public class UserService : IUserService { private readonly IUserRepository _repository ; public UserService ( IUserRepository repository ) { _repository = repository ; } public IEnumerable < User > GetUsers ( ) { return _repository.GetUsers ( ) ; } } } private readonly IUserService _service ; public HomeController ( IUserService service ) { _service = service ; }",Why expose service instead of repository in Onion Architecture ? "C_sharp : When I open a PDF file with Word automation , it show a dialog that ask me to confirm the convertion ( With a `` do not show again '' checkbox ) . Word will now convert your PDF to an editable Word document . This may take a while . The resulting Word document will be optimized to allow you to edit the text , so it might not look exactly like the original PDF , especially if the file contained lots of graphics.How to hide this dialog ? PS : ConfirmConversions : true add an other dialog . var application = new Microsoft.Office.Interop.Word.Application ( ) ; application.Visible = false ; try { application.ShowStartupDialog = false ; } catch { } try { application.DisplayAlerts = WdAlertLevel.wdAlertsNone ; } catch { } var doc = application.Documents.Open ( inputFilePath , ConfirmConversions : false , ReadOnly : true , AddToRecentFiles : false , Revert : true , NoEncodingDialog : true ) ;",How to hide pdf importer popup in word automation "C_sharp : In my C # /WinRT app ( Windows Store app ) I have a TextBox . I can set it 's TextWrapping property to Wrap or NoWrap and it works . But if I try to use the value of `` WrapWholeWords '' I get a design time error with the property value highlighted . When I mouse over the error I get the error message `` the parameter is incorrect '' with the error code E_RUNTIME_SETVALUE . Can anyone tell me why this is happening and how to fix it if I can ? The TextBox is hosted on a grid control if that matters . Note , the WrapWholeWords value is offered by Intellisense from the XAML editor and from the Property Editor pane in the IDE . < TextBox x : Name= '' txtNotes '' Grid.Column= '' 2 '' TextWrapping= '' WrapWholeWords '' Text= '' TextBlock '' Margin= '' 30 '' FontSize= '' 20 '' / >",Getting a parameter is incorrect error with TextWrapping property set to WrapWholeWords ? "C_sharp : I am using version 2 of ProtoBuf-net , and currently I 'm geting the error `` Unable to determine member : A '' Is it possible to create a run-time model for Protobuf-net when we use ClassOfType < T > ? If so , can anyone spot what I 'm missing in the below code ? btw : this request is modelled off of Deserialize unknown type with protobuf-net I could get a version of this going just fine ... but they are using an abstract base class , not a generic class of T.THIS IS A WORKING EXAMPLE ( stuff that was n't working is removed ) .RequestThis is minor , but it 'd be nice if could also be implemented like this btw : I 'm starting to dig into the protobuf-net implementation , and I 'm starting to notice some interesting methods like this . Something to come back to later I guess : Discussion : when I saw the way you could deserialize to an abstract base type in the link above , I thought , yes , that 's closer to what was thinking . Could we deserialize to the open generic Container < > first , and then cast more specifically if we need to in different assemblies . Maybe I 'm getting mixed up a little here.You could think of it in terms of Tupple < TBase , TPayload > . Or a variation like Tupple < TBase , Lazy < TPayload > > maybe . It 's not that different to List < T > . There are some TreeTypeThings < T > that I have too , but I do n't need to serialize/deserialize them ( yet ) .I had a non-generic sequence working , so it is n't a show stopper . My first implementation could be more efficient . I think I can do better on that with existing protobuf-net features though.I like the cleaner generic way of working with these ideas . Although I can get to the same destination manually , Generics make other things possible . re : clarificationeverything can be defined ahead of time by the caller . ( btw : You 've got me thinking about the run-time only scenario now , but no , I do n't need that ) . using System ; using System.IO ; using NUnit.Framework ; using ProtoBuf ; using ProtoBuf.Meta ; namespace ProtoBufTestA2 { [ TestFixture ] public class Tester { [ Test ] public void TestMsgBaseCreateModel ( ) { var BM_SD = new Container < SomeDerived > ( ) ; using ( var o = BM_SD ) { o.prop1 = 42 ; o.payload = new SomeDerived ( ) ; using ( var d = o.payload ) { d.SomeBaseProp = -42 ; d.SomeDerivedProp = 62 ; } } var BM_SB = new Container < SomeBase > ( ) ; using ( var o = BM_SB ) { o.prop1 = 42 ; o.payload = new SomeBase ( ) ; using ( var d = o.payload ) { d.SomeBaseProp = 84 ; } } var model = TypeModel.Create ( ) ; model.Add ( typeof ( Container < SomeDerived > ) , true ) ; // BM_SD model.Add ( typeof ( Container < SomeBase > ) , true ) ; // BM_SB model.Add ( typeof ( SomeBase ) , true ) ; // SB model.Add ( typeof ( SomeDerived ) , true ) ; // SD model [ typeof ( SomeBase ) ] .AddSubType ( 50 , typeof ( SomeDerived ) ) ; // SD var ms = new MemoryStream ( ) ; model.SerializeWithLengthPrefix ( ms , BM_SD , BM_SD.GetType ( ) , ProtoBuf.PrefixStyle.Base128 , 0 ) ; model.SerializeWithLengthPrefix ( ms , BM_SB , BM_SB.GetType ( ) , ProtoBuf.PrefixStyle.Base128 , 0 ) ; ms.Position = 0 ; var o1 = ( Container < SomeDerived > ) model.DeserializeWithLengthPrefix ( ms , null , typeof ( Container < SomeDerived > ) , PrefixStyle.Base128 , 0 ) ; var o2 = ( Container < SomeBase > ) model.DeserializeWithLengthPrefix ( ms , null , typeof ( Container < SomeBase > ) , PrefixStyle.Base128 , 0 ) ; } } [ ProtoContract ] public class Container < T > : IDisposable { [ ProtoMember ( 1 ) ] public int prop1 { get ; set ; } [ ProtoMember ( 2 ) ] public T payload { get ; set ; } public void Dispose ( ) { } } [ ProtoContract ] public class AnotherDerived : SomeDerived , IDisposable { [ ProtoMember ( 1 ) ] public int AnotherDerivedProp { get ; set ; } public override void Dispose ( ) { } } [ ProtoContract ] public class SomeDerived : SomeBase , IDisposable { [ ProtoMember ( 1 ) ] public int SomeDerivedProp { get ; set ; } public override void Dispose ( ) { } } [ ProtoContract ] public class SomeBase : IDisposable { [ ProtoMember ( 1 ) ] public int SomeBaseProp { get ; set ; } public virtual void Dispose ( ) { } } [ ProtoContract ] public class NotInvolved : IDisposable { [ ProtoMember ( 1 ) ] public int NotInvolvedProp { get ; set ; } public void Dispose ( ) { } } [ ProtoContract ] public class AlsoNotInvolved : IDisposable { [ ProtoMember ( 1 ) ] public int AlsoNotInvolvedProp { get ; set ; } public void Dispose ( ) { } } } ( Container < SomeDerived > ) model.DeserializeWithLengthPrefix ( ... ) model.DeserializeWithLengthPrefix < Container < SomeDerived > > ( ... ) : public MetaType Add ( int fieldNumber , string memberName , Type itemType , Type defaultType ) ;",Is of < T > allowed in a run-time ProtoBuf-net model ? "C_sharp : I want to create unit testable code that mocks out the calls to the .Net System.IO classes , so I can really unit test instead of depending on the filesystem.I am using the SystemWrapper classes to wrap around the BCL classes.I am trying to get a simple example working to see whether a file exists.The problem I am having is that injecting the dependency in the class does n't work because instantiating the dependency ( through StructureMap ) requires knowing what constructor parameter to pass , which wo n't be available at that time , also there is no default constructor . sample code : What I do n't like is that the dependency is not injected , ObjectFactory should not be here ( but I see no other way of creating this ) .The ExplicitArguments makes it messy and the argument-name is a magic-string.For me to get this to work StructureMap config class needs to know explict which constructor I want to use ( I just started with StructureMap so this might not be the right way to set it up ) : Does anyone found a better solution to create testable code against the System.IO classes ? I know part of the problem is in the design of the System.IO classes . // do n't want to create dependency here like so//IFileInfoWrap fileInfoWrap = new FileInfoWrap ( filename ) ; // using service locator ( anti-pattern ? ! ) since it ca n't be // injected in this classvar fileInfoWrap = ObjectFactory.GetInstance < IFileInfoWrap > ( new ExplicitArguments ( new Dictionary < string , object > { { `` fileName '' , filename } } ) ) ; Console.WriteLine ( `` File exists ? { 0 } '' , fileInfoWrap.Exists ) ; ObjectFactory.Initialize ( x = > { x.Scan ( scan = > { scan.AssembliesFromPath ( `` . `` ) ; scan.RegisterConcreteTypesAgainstTheFirstInterface ( ) ; scan.WithDefaultConventions ( ) ; } ) ; // use the correct constructor ( string instead of FileInfo ) x.SelectConstructor ( ( ) = > new FileInfoWrap ( null as string ) ) ; // setting the value of the constructor x.For < IFileInfoWrap > ( ) .Use < FileInfoWrap > ( ) .Ctor < string > ( `` fileName '' ) .Is ( @ '' . `` ) ; } ) ;",How to create testable code using .Net IO classes ? "C_sharp : I 'm trying to put login and register form into same view . I did everything suggested in other questions but my problem still not fixed.Here is my parent view authentication.cshtml : In my partials I use forms like this : One of the actions is like this : And here are the models I 'm using : In the action registerVM 's Email property has value , but others are null . ModelState.IsValid is false.What am I doing wrong ? @ model Eriene.Mvc.Models.AccountVM < div class= '' row '' > < div class= '' col-md-6 '' > @ Html.Partial ( `` _Login '' , Model.Login ? ? new Eriene.Mvc.Models.LoginVM ( ) ) < /div > < div class= '' col-md-6 '' > @ Html.Partial ( `` _Register '' , Model.Register ? ? new Eriene.Mvc.Models.RegisterVM ( ) ) < /div > < /div > @ using ( Html.BeginForm ( `` Register '' , `` Account '' , FormMethod.Post , new { @ id = `` login-form '' , @ role = `` form '' , @ class = `` login-form cf-style-1 '' } ) ) [ HttpPost ] [ AllowAnonymous ] public ActionResult Register ( RegisterVM registerVM ) { if ( ModelState.IsValid ) { User user = new Data.User ( ) ; user.Email = registerVM.Email ; user.ActivationCode = Guid.NewGuid ( ) .ToString ( ) ; user.FirstName = registerVM.FirstName ; user.LastName = registerVM.LastName ; user.Password = PasswordHelper.CreateHash ( registerVM.Password ) ; return RedirectToAction ( `` Index '' , `` Home '' ) ; } return View ( `` Authentication '' , new AccountVM ( ) { Register = registerVM } ) ; } public class AccountVM { public LoginVM Login { get ; set ; } public RegisterVM Register { get ; set ; } } public class RegisterVM { [ Required ] public string Email { get ; set ; } [ Required ] public string FirstName { get ; internal set ; } [ Required ] public string LastName { get ; internal set ; } [ Required ] public string Password { get ; internal set ; } [ Compare ] public string PasswordRetype { get ; internal set ; } } public class LoginVM { [ Required ] public string Email { get ; set ; } [ Required ] public string Password { get ; set ; } public bool RememberMe { get ; set ; } }",MVC Nested View Model with Validation "C_sharp : I have a rather strange problem.I am exporting an interface from a C # library to COM.I have enabled the 'register with COM ' project setting , so it calls tlbexp.exe to make the type libs.We use camel case on our method names and I noticed that the exported type library changes these any method that happens to coincide with a class name to Pascal case ... e.gThe exported IFoo in the type lib defines IFoo- > RandomClass ( ) instead of IFoo- > randomClass ( ) Any ideas on what causes this and how to stop it ? interface IFoo { void randomClass ( ) } class RandomClass { }",tlbexp.exe changes method names ' case "C_sharp : one of my controller could not load `` Index '' .for example : does n't work.but http : //localhost:51638/Reserve/Index works.and this problem is just for one of my controller and other is correct.and my RouteConfig is : after delete the controller and add Controller again it was n't fix.and encounter to this error page : HTTP Error 403.14 - ForbiddenThe Web server is configured to not list the contents of this directory.and this is my Controller Code http : //localhost:51638/Reserve/ public static void RegisterRoutes ( RouteCollection routes ) { routes.IgnoreRoute ( `` { resource } .axd/ { *pathInfo } '' ) ; // BotDetect requests must not be routed routes.IgnoreRoute ( `` { *botdetect } '' , new { botdetect = @ '' ( . * ) BotDetectCaptcha\.ashx '' } ) ; routes.MapRoute ( name : `` Default '' , url : `` { controller } / { action } / { id } '' , defaults : new { controller = `` UserHome '' , action = `` Index '' , id = UrlParameter.Optional } ) ; } public class ReserveController : Controller { // // GET : /Reserve/ public ActionResult Index ( ) { return View ( ) ; } }",Asp.net MVC Routing Issue 403.14 "C_sharp : I found myself frequently need to use Enumerable.Zip ( ) , but having it to ensure the two IEnumerables to have the same length ( or both to be infinite ) . E.g. , if one enumerable reaches the end but the other does n't , I want it to throw . According to the doc , Zip ( ) will just stop enumerating as soon as one of them comes to the end . I ended up always need something like below . What 's the most `` built-in '' /elegant way to address this ? void Foo ( IEnumerable < int > a , IEnumerable < int > b ) { // caching them . they are not huge or infinite in my scenario var a = a.ToList ( ) ; var b = b.ToList ( ) ; if ( a.Count ( ) ! = b.Count ( ) ) { throw ... ; } Enumerable.Zip ( a , b , ... ) ; }",Enumerable.Zip to enforce same lengths "C_sharp : Let 's say I have a method foo which returns a ValueTuple where one of it 's members is disposable , for example ( IDisposable , int ) .What is the best way to make sure the returned disposable object is correctly disposed on the calling side ? I tried the following : But this wo n't compile : ' ( IDisposable disposable , int number ) ' : type used in a using statement must be implicitly convertible to 'System.IDisposable'Do I really need to wrap my code in a try-finally block and dispose my object explicitly in the finally block , or is there a nicer way to do it ? Actually I 'd like to see the new ValueTuples implement the IDisposable interface and call Dispose ( ) on all their disposable members . Could this be a worthwhile feature request for Microsoft ? using ( var ( disposable , number ) = foo ( ) ) { // do some stuff using disposable and number }",C # ValueTuple with disposable members "C_sharp : Maybe I 'm just not getting it , but I have a service that is deployed to an IIS 6 machine . That machine has a LAN address and a Public internet address.How on earth am I supposed to be able publish this service with both accessible ? Address 1 : http : //serverName/ServiceName/Service.svcAddress 2 : http : //www.companyName.com/ServiceName/Service.svcAt first I thought : No big deal , 2 endpoints . So I haveThe client code then looks like : No dice . Ca n't add the service reference . No protocol binding matches the given address 'Address 1 ' . Protocol bindings are configured at the Site level in IIS or WAS configuration . Then I thought : Maybe the host tag and its dns tag will help . Nope , that 's for authentication.Then I thought : I 'll use net.tcp for the local endpoint . Oops ... IIS 6 does n't support net.tcp.Then I thought : I know , the ProxyClient constructor takes a remoteAddress string as its second parameter . Now it 'll look like : Apparently not . When trying to instantiate the ProxyClient ... Could not find endpoint element with name 'MyEndpointName ' and contract MyService.IService ' in the ServiceModel client configuration section.Which leads me to the app.config whose generated client section looks like this : Which sure does n't look right to me.My next thought is not a healthy one . Please help . < endpoint address= '' Address 1 '' binding= '' wsHttpBinding '' bindingConfiguration= '' DefaultBindingConfiguration '' name= '' RemoteEndpoint '' / > < endpoint address= '' Address 2 '' binding= '' wsHttpBinding '' bindingConfiguration= '' DefaultBindingConfiguration '' name= '' LocalEndpoint '' / > public void createServiceProxy ( ) { if ( Util.IsOperatingLocally ( ) ) this.proxy = new ProxyClient ( `` LocalEndpoint '' ) ; else this.proxy = new ProxyClient ( `` RemoteEndpoint '' ) ; } < endpoint address= '' '' binding= '' wsHttpBinding '' bindingConfiguration= '' DefaultBindingConfiguration '' name= '' MyEndpointName '' / > public void createServiceProxy ( ) { if ( Util.IsOperatingLocally ( ) ) this.proxy = new ProxyClient ( `` MyEndpointName '' , `` Address 1 '' ) ; else this.proxy = new ProxyClient ( `` MyEndpointName '' , `` Address 2 '' ) ; } < client > < endpoint address= '' http : //localhost:3471/Service.svc '' binding= '' customBinding '' bindingConfiguration= '' MyEndpointName '' contract= '' MyService.IService '' name= '' MyEndpointName '' > < identity > < userPrincipalName value= '' DevMachine\UserNa , e '' / > < /identity > < /endpoint > < /client >",WCF endpoints are driving me insane "C_sharp : My team just received the code written by a contractor , and the contractor had a preference for using type inference with var . Our team prefers explicit typing by using the actual type ( as in below ) : Whereas the contractor deliveredVisual Studio 2008 knows what the inferred type is , as I can see by hovering the var keywordMy question is , is there a way to do a global find and replace var to the inferred type ? Type someName = new Type ( ) ; IList < TypeTwo > someOther = someClass.getStuff ( ) ; var someOther = someClass.getStuff ( ) ;",VS2008 - Replace var with inferred type "C_sharp : BackgroundI accept this is n't something that can occur during normal code execution but I discovered it while debugging and thought it interesting to share . I think this is caused by the JIT compiler , but would welcome any further thoughts.I have replicated this issue targeting the 4.5 and 4.5.1 framework using VS2013 : SetupTo see this exception Common Language Runtime Exceptions must be enabled : DEBUG > Exceptions ... I have distilled the cause of the issue to the following example : To ReplicatePlace a breakpoint on if ( myEnum == MyEnum.Bad ) and run the code . When the break point is hit , Set Next Statement ( Ctrl+Shift+F10 ) to be the opening brace of the if statement and run until : Next , comment out the first lamda statement and comment in the second - so the MyClass instance is n't used . Rerun the process ( hitting the break , forcing into the if statement and running ) . You 'll see the code works correctly : Finally , comment in the first lamda statement and comment out the second - so the MyClass instance is used . Then refactor the contents of the if statement into a new method : Rerun the test and everything works correctly : Conclusion ? My assumption is the JIT compiler has optimized out the lamda to always be null , and some further optimized code is running prior to the instance being initialized . As I previously mentioned this could never happen in production code , but I would be interested to know what was happening . using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication6 { public class Program { static void Main ( ) { var myEnum = MyEnum.Good ; var list = new List < MyData > { new MyData { Id = 1 , Code = `` 1 '' } , new MyData { Id = 2 , Code = `` 2 '' } , new MyData { Id = 3 , Code = `` 3 '' } } ; // Evaluates to false if ( myEnum == MyEnum.Bad ) // BREAK POINT { /* * A first chance exception of type 'System.NullReferenceException ' occurred in ConsoleApplication6.exe Additional information : Object reference not set to an instance of an object . */ var x = new MyClass ( ) ; MyData result ; //// With this line the 'System.NullReferenceException ' gets thrown in the line above : result = list.FirstOrDefault ( r = > r.Code == x.Code ) ; //// But with this line , with ' x ' not referenced , the code above runs ok : //result = list.FirstOrDefault ( r = > r.Code == `` x.Code '' ) ; } } } public enum MyEnum { Good , Bad } public class MyClass { public string Code { get ; set ; } } public class MyData { public int Id { get ; set ; } public string Code { get ; set ; } } } using System.Collections.Generic ; using System.Linq ; namespace ConsoleApplication6 { public class Program { static void Main ( ) { var myEnum = MyEnum.Good ; var list = new List < MyData > { new MyData { Id = 1 , Code = `` 1 '' } , new MyData { Id = 2 , Code = `` 2 '' } , new MyData { Id = 3 , Code = `` 3 '' } } ; // Evaluates to false if ( myEnum == MyEnum.Bad ) // BREAK POINT { MyMethod ( list ) ; } } private static void MyMethod ( List < MyData > list ) { // When the code is in this method , it works fine var x = new MyClass ( ) ; MyData result ; result = list.FirstOrDefault ( r = > r.Code == x.Code ) ; } } public enum MyEnum { Good , Bad } public class MyClass { public string Code { get ; set ; } } public class MyData { public int Id { get ; set ; } public string Code { get ; set ; } } }",CLR System.NullReferenceException when forcing 'Set Next Statement ' into 'if ' block "C_sharp : In response to another question I have tried to do the following . I do n't think I interpreted that question correctly , but I do wonder if the below is possible somehow ( my attempts have failed ) and if not why not : I thought this might be made to work using a generic interface with a covariant type parameter : but I was wrong about that , that does not work either . EDITAs SLaks has pointed out 'Interfaces are covariant ; classes are not . ' ( thanks SLaks ) . So now my question is why ? What was the thinking behind the design ( one for Eric Lippert I think ) is it not possible , undesirable or is it on a 'maybe one day ' list ? public class MyBaseClass { } public class MyClass : MyBaseClass { } public class B < T > { } public class A < T > : B < T > { } static void Main ( string [ ] args ) { // Does not compile B < MyBaseClass > myVar = new A < MyClass > ( ) ; } interface IB < out T > { } public class B < T > : IB < T > { }",.NET 4.0 Covariance "C_sharp : Given the following code : The first two lines are very obvious , just two different objects.I assume the third line to do the following : The part ( a = b ) assigns b to a and returns b , so now a equals b.Then , a.x is assigned to b.That means , a.x equals to b , and also b equals to a . Which implies that a.x equals to a.However , the code prints False.What 's going on ? using System ; class MyClass { public MyClass x ; } public static class Program { public static void Main ( ) { var a = new MyClass ( ) ; var b = new MyClass ( ) ; a.x = ( a = b ) ; Console.WriteLine ( a.x == a ) ; } }",Unexpected non-equality after assignment "C_sharp : Does any one know the difference , if any , of the following statements ? as well asThanksEDITSorry some confusion : I know the difference between AddObject and Attach , what I meant was is there any difference in the way you use AddObject i.e . _context.AddObject ( user ) ; _context.Users.AddObject ( user ) ; _context.Attach ( user ) ; _context.Users.Attach ( user ) ; _context.AddObject ( user ) ; _context.Users.AddObject ( user ) ;",What is the difference between these two statements ( Entity Framework ) "C_sharp : I have a simple form with 2 progressbars and 1 backgroundworker on it . I have 2 loops ( one within the other ) and I 'd like to report back the progress of each loop once incremented . Here 's the code I have : When the program runs , progressbar1 gets updated just fine , but progressbar2 never moves . If I run it through the debugger , I can see the value of progressbar2 being changed , there 's just no change graphically . Any ideas ? private void buttonStart_Click ( object sender , EventArgs e ) { workerCustomers.RunWorkerAsync ( ) ; } private void workerCustomers_ProgressChanged ( object sender , ProgressChangedEventArgs e ) { progressBar1.Value = e.ProgressPercentage ; progressBar2.Value = ( int ) e.UserState ; } private void workerCustomers_DoWork ( object sender , DoWorkEventArgs e ) { for ( int customer = 0 ; customer < 50 ; customer++ ) { int customerPercentage = ++customer * 100 / 50 ; workerCustomers.ReportProgress ( customerPercentage , 0 ) ; for ( int location = 0 ; location < 500 ; location++ ) { int locationPercentage = ++location * 100 / 500 ; workerCustomers.ReportProgress ( customerPercentage , locationPercentage ) ; } workerCustomers.ReportProgress ( customerPercentage , 0 ) ; } }",Only 1 of 2 progress bars gets updated in BackgroundWorker "C_sharp : I am fairly familiar with concepts of service locator and dependency injection , but there is one thing that gets me confused all the time , i.e. , to implement dependency injection for an application we must use some sort of service locator at the start . Please consider the following code , lets say we have some simple DAL class : And then in the Business Logig Layer we have some simple class that uses IUserProvider that is injected using constructor injection : Now we may have couple of classes like that and use constructor injection everywhere , but in the main class where the application starts , all these types have to be resolved anyway , hence we must use a service locator to resolve all these types , for example , here I will create a singleton service locator class to resolve all the dependencies at the start of a console application like this : So it seems like some kind of service locator is always used at the start of the application , hence using service locator is inevitable and it 's not correct to always call it an anti-patern right ( unless it 's used not in the root of the application ) ? public class UserProviderSimple : IUserProvider { public void CreateUser ( User user ) { //some code to user here } } public class UserServiceSimple : IUserService { public IUserProvider UserProvider { get ; set ; } public UserServiceSimple ( IUserProvider userProvider ) { UserProvider = userProvider ; } public void CreateUser ( User user ) { UserProvider.CreateUser ( user ) ; } } public class ServiceLocator { private readonly UnityContainer _container ; private static ServiceLocator _instance ; public static ServiceLocator Instance ( ) { if ( _instance == null ) { _instance = new ServiceLocator ( ) ; return _instance ; } return _instance ; } private ServiceLocator ( ) { _container = new UnityContainer ( ) ; _container.RegisterType < IUserProvider , UserProviderSimple > ( ) ; _container.RegisterType < IUserService , UserServiceSimple > ( ) ; } public T Resolve < T > ( ) { return _container.Resolve < T > ( ) ; } } class Program { private static IUserService _userService ; private static void ConfigureDependencies ( ) { _userService = ServiceLocator.Instance ( ) .Resolve < IUserService ( ) ; } static void Main ( string [ ] args ) { ConfigureDependencies ( ) ; } }",Is it possible to implement dependency injection without using service locator at the start of an application ? "C_sharp : Hej I am playing around with an app for windows phone 8 , using MVVM.I have a problem with acquiring the center of a pinch zoom and understanding the bounds completely on the viewportcontroller . And finally re-configuring the viewportcontroller to still scroll the entire picture . My xaml code is : As far as I understand the Bounds is the area I want to be able to scroll , and height and width is the windows size of the control is this correct ? Answer Yes it is correct.On to the second part : ) Getting the center of the pinch zoom motion.In the if case if ( ! isZooming ) , I try to calculate the center . I have also tried with the different centers that can be found inside the event e. without any success . What am I doing wrong with calculating the center ? Finally after I have zoomed I can not pan around the entire picture anymore . I therefore need to change some variable but have not been able to pin point it , while debugging or searching the web . Any Idea for this ? Answer The image should be resized , and the bounds of the viewport should be set to the new size of the resized image.EditFinal problem is finding the center , and the problem is when this situation occurs : since the e.PinchManipulation.Current gives relative to lightblue square , and I want it relative to the large square , i.e . the bounds . How to do this ? < Grid > < StackPanel > < ViewportControl Bounds= '' 0,0,1271,1381.5 '' Height= '' 480 '' Width= '' 800 '' CacheMode= '' BitmapCache '' RenderTransformOrigin= '' { Binding KontaktPunkter } '' Canvas.ZIndex= '' 1 '' > < ViewportControl.RenderTransform > < CompositeTransform x : Name= '' myTransform '' ScaleX= '' 1 '' ScaleY= '' 1 '' TranslateX= '' 0 '' TranslateY= '' 0 '' / > < /ViewportControl.RenderTransform > < View : Picture/ > < /ViewportControl > < /StackPanel > < View : PopUpUC DataContext= '' { Binding PopUp } '' / > < /Grid > public void ZoomDelta ( ManipulationDeltaEventArgs e ) { FrameworkElement Element = ( FrameworkElement ) e.OriginalSource ; ViewportControl Picture ; Grid PictureGrid ; double MainWidth = Application.Current.RootVisual.RenderSize.Height ; double MainHeight = Application.Current.RootVisual.RenderSize.Width ; if ( Element is ViewportControl ) { Picture = Element as ViewportControl ; } else { Picture = FindParentOfType < ViewportControl > ( Element ) ; } if ( Element is Grid ) { PictueGrid = Element as Grid ; } else { PictureGrid = FindParentOfType < Grid > ( Element ) ; } Grid ScreenGrid = FindParentOfType < Grid > ( PictureGrid ) ; if ( e.PinchManipulation ! = null ) { var newScale = e.PinchManipulation.DeltaScale * Map.previousScale ; if ( ! IsZooming ) { Point FingerOne = e.PinchManipulation.Current.PrimaryContact ; Point FingerTwo = e.PinchManipulation.Current.SecondaryContact ; Point center = new Point ( ( FingerOne.X + FingerTwo.X ) / 2 , ( FingerOne.Y + FingerTwo.Y ) / 2 ) ; KontaktPunkter = new Point ( center.X / Picture.Bounds.Width , center.Y / Picture.Bounds.Height ) ; IsZooming = true ; } var newscale = Map.imageScale * newScale ; var transform = ( CompositeTransform ) Picture.RenderTransform ; if ( newscale > 1 ) { Map.imageScale *= newScale ; transform.ScaleX = Map.imageScale ; transform.ScaleY = Map.imageScale ; } else { transform.ScaleX = transform.ScaleY = 1 ; } } e.Handled = true ; }",ViewportControl Pinch zoom center "C_sharp : I 'm using PostSharp Express in VS2013 to create validation aspects which I can apply to my properties . I followed this PostSharp guide on location interception . They all work well but I am getting hundreds of warnings stating : Conflicting aspects on `` MyNamespace.get_MyProperty '' : transformations `` .MyValidation1Attribute : Intercepted by advice OnGetValue , OnSetValue '' and `` MyNamespace.Validation2Attribute : Intercepted by advice OnGetValue , OnSetValue '' are not commutative , but they are not strongly ordered . Their order of execution is undeterministic.Which I think is a result of my placing multiple validation aspects on the same properties . First I tried to comma-separate the attributes , which I understand is supposed to order them : [ Validation1 , Validation2 ] but the warnings still remained.Since my aspects are commutative ( it does n't matter which order they are executed ) , the PostSharp docs advise to mark them as such using AspectTypeDependency as follows : However , it appears that the PostSharp.Aspects.Dependencies namespace is not included under the Express license . Is there any possible solution to resolving these warnings using only the Express license ? Or does this mean I ca n't ever use more than one aspect without buying pro or ultimate ? I would be willing to try to implement my own dependency controller if I could remove these warnings this way . [ AspectTypeDependency ( AspectDependencyAction.Commute , typeof ( ILocationValidationAspect ) ) ]",PostSharp Conflicting Aspects warning "C_sharp : I am trying to setup unit tests for my Linq To SQL code . My code uses the System.Data.Linq.Table class ( generated by the designer ) .Because this class is sealed and the constructor is internal it is completely impervious to unit testing frameworks like Rhino Mocks . ( Unless you want to alter you code to use the repository pattern , which I would rather not . ) Typemock can ( some how ) mock this class . ( See here for an example . ) However , Typemock is also $ 800 a license . I do n't see my employer springing for that anytime soon.So here is the question . Are there any other mocking frameworks out there that do n't rely on Interfaces to create the mocks ? Edit : Example of code that I need to test : I have shorted this up to make it easier to read . The idea is that I have some code ( like IsUserInOrganization that calls another method ( like GetUsersByOrganization ) that does a Linq query . I would like to unit test the IsUserInOrganization method . Do do that I would need to mock _ctx.Users which is a Table class ( that is sealed and has an internal constructor ) . public class UserDAL : IUserDAL { private IDataClassesDataContext _ctx ; public UserDAL ( ) { string env = ConfigurationManager.AppSettings [ `` Environment '' ] ; string connectionString = ConfigurationManager .ConnectionStrings [ env ] .ConnectionString ; _ctx = new DataClassesDataContext ( connectionString ) ; } public UserDAL ( IDataClassesDataContext context ) { _ctx = context ; } public List < User > GetUsersByOrganization ( int organizationId ) { IOrderedQueryable < User > vUsers = ( from myUsers in _ctx.Users where myUsers.Organization == organizationId orderby myUsers.LastName select myUsers ) ; return vUsers.ToList ( ) ; } public bool IsUserInOrganization ( User user , int orgainzationID ) { // Do some Dal Related logic here . return GetUsersByOrganization ( orgainzationID ) .Contains ( user ) ; } }",Is Typemock the only framework that can mock a Linq To SQL Table class ? "C_sharp : In wpf , i have to click on an image with Panel.ZIndex= '' 1 '' , but this image is `` under '' another image with a Panel.ZIndex= '' 2 '' . The event MouseDown fail . How to do that ? Thanks in advance , M . < Grid > < Image Name= '' Image_1 '' Panel.ZIndex= '' 1 '' / > < Image Name= '' Image_2 '' Panel.ZIndex= '' 2 '' / > < /Grid >",How to click an object with Panel.ZIndex low than another in wpf ? "C_sharp : I 'm writing some Enum functionality , and have the following : I call it like this : I now want to add constraints to T to an Enum , such as ( which I got from Stackoverflow article ) : where T : struct , IConvertible but I am having problems as T needs to be able to take nullable enums . Error message says : The type 'Enums.Animals ? ' must be a non-nullable value type in order to use it as parameter 'T ' in the generic type or methodIs there a way to do this , or do I need to just rely on the runtime checking which I have inside the method ? Thanks all ! public static T ConvertStringToEnumValue < T > ( string valueToConvert , bool isCaseSensitive ) { if ( typeof ( T ) .BaseType.FullName ! = `` System.Enum '' & & typeof ( T ) .BaseType.FullName ! = `` System.ValueType '' ) { throw new ArgumentException ( `` Type must be of Enum and not `` + typeof ( T ) .BaseType.FullName ) ; } if ( String.IsNullOrWhiteSpace ( valueToConvert ) ) return ( T ) typeof ( T ) .TypeInitializer.Invoke ( null ) ; valueToConvert = valueToConvert.Replace ( `` `` , `` '' ) ; if ( typeof ( T ) .BaseType.FullName == `` System.ValueType '' ) { return ( T ) Enum.Parse ( Nullable.GetUnderlyingType ( typeof ( T ) ) , valueToConvert , ! isCaseSensitive ) ; } return ( T ) Enum.Parse ( typeof ( T ) , valueToConvert , ! isCaseSensitive ) ; } EnumHelper.ConvertStringToEnumValue < Enums.Animals ? > ( `` Cat '' ) ;",Adding Constraints for Nullable Enum "C_sharp : I am using AutoFixture in this instance to materialize objects containing a Mongo ObjectId , like soBut I am doing this for every test . Is it possible to register this globall somehow for all tests ? Fixture fixture = new Fixture ( ) ; fixture.Register ( ObjectId.GenerateNewId ) ;",AutoFixture Register type globally "C_sharp : The following code fails to compile ( using VS2010 ) and I do n't see why . The compiler should be able to infer that List < TestClass > is 'compatible ' ( sorry for lack of a better word ) with IEnumerable < ITest > , but somehow it does n't . What am I missing here ? The compiler gives two errors : The best overloaded method match for 'ConsoleApplication1.Program.Test ( System.Collections.Generic.IEnumerable < ConsoleApplication2.ITest > ) ' has some invalid argumentsArgument 1 : can not convert from 'System.Collections.Generic.List < ConsoleApplication2.TestClass > ' to 'System.Collections.Generic.IEnumerable < ConsoleApplication2.ITest > ' interface ITest { void Test ( ) ; } class TestClass : ITest { public void Test ( ) { } } class Program { static void Test ( IEnumerable < ITest > tests ) { foreach ( var t in tests ) { Console.WriteLine ( t ) ; } } static void Main ( string [ ] args ) { var lst = new List < TestClass > ( ) ; Test ( lst ) ; // fails , why ? Test ( lst.Select ( t= > t as ITest ) ) ; //success Test ( lst.ToArray ( ) ) ; // success } }",C # compiler fails to recognize a class is implementing an interface "C_sharp : I have for the first time made something I want to share on NuGet , but I am not sure how this `` release preparation '' is done.At the moment my following steps are : Manually change the assembly version of my main assembly ( MyAssembly ) in AssemblyInfo.cs from 1.0.0.0 to 1.1.0.0Build the main assembly release version in Visual StudioPack the release for my main assembly ( nuget pack -prop configuration=release == MyAssembly.1.1.0.0.nupkg ) Publish this package to NuGet ( nuget push MyAssembly.1.1.0.0.nupkg ) Update the NuGet packages for assemblies referring MyAssembly ( e.g . MyAssembly.Web.Mvc gets its MyAssembly updated from v1.0.0.0 - > v1.1.0.0 using the NuGet Package Manager ) defined in packages.configChange the version AssemblyInfo.cs of MyAssembly.Web.Mvc to 1.1.0.0 , build release , NuGet pack and publishRepeat step 6 for all my references assembliesThis is some steps that are a PITA , and I will some day make an error and break the release.This got me think , am I missing a crucial point , am I doing all this wrong ? UPDATEBased on the knowledge @ ialekseev provided , I have now created this : Build.ps1BuildFunctions.ps1Run like .\Build -version 1.2.0.0 -pack $ true Param ( [ Parameter ( Mandatory= $ true ) ] [ string ] $ version , [ string ] $ configuration = `` Release '' , [ boolean ] $ tests = $ false , [ boolean ] $ publish = $ false , [ boolean ] $ pack = $ false , [ string ] $ outputFolder = `` build\packages '' ) # Include build functions . `` ./BuildFunctions.ps1 '' # The solution we are building $ solution = `` NerveFramework.sln '' $ assemblies = `` NerveFramework '' , `` NerveFramework.Web '' , `` NerveFramework.Web.Mvc '' , `` NerveFramework.Web.WebApi '' # Start by changing the assembly versionWrite-Host `` Changing the assembly versions to ' $ version ' ... '' $ assemblyInfos = Get-ChildItem $ assemblies -Filter `` AssemblyInfo.cs '' -Recurse | Resolve-Path -Relativeforeach ( $ assemblyInfo in $ assemblyInfos ) { ChangeAssemblyVersion $ assemblyInfo $ version } # Build the entire solutionWrite-Host `` Cleaning and building $ solution ( Configuration : $ configuration ) '' BuildSolution $ solution $ configuration # Change dependency version on all depending assembliesWrite-Host `` Changing the NerveFramework ( s ) NuGet Spec version dependencies to ' $ version ' ... '' $ nuspecs = Get-ChildItem $ assemblies -Filter `` NerveFramework*.nuspec '' -Recurse | Resolve-Path -Relativeforeach ( $ nuspec in $ nuspecs ) { ChangeNugetSpecDependencyVersion $ nuspec `` NerveFramework '' $ version } # Pack the assemblies and move to output folderif ( $ pack ) { Write-Host `` Packaging projects ... '' $ projects = Get-ChildItem $ assemblies -Filter `` NerveFramework*.csproj '' -Recurse | Resolve-Path -Relative foreach ( $ project in $ projects ) { PackProject $ project $ configuration $ outputFolder } } # Publish the assembliesif ( $ publish ) { Write-Host `` Publishing packages ... '' $ packages = Get-ChildItem $ outputFolder -Filter `` * $ version.nupkg '' -Recurse | Resolve-Path -Relative foreach ( $ package in $ packages ) { PublishPackage $ package } } Function BuildSolution ( ) { Param ( [ Parameter ( Mandatory= $ true ) ] [ string ] $ solution , [ Parameter ( Mandatory= $ true ) ] [ string ] $ configuration ) # Set the path to the .NET folder in order to use `` msbuild.exe '' $ env : PATH = `` C : \Windows\Microsoft.NET\Framework64\v4.0.30319 '' Invoke-Expression `` msbuild.exe $ solution /nologo /v : m /p : Configuration= $ configuration /t : Clean '' Invoke-Expression `` msbuild.exe $ solution /nologo /v : m /p : Configuration= $ configuration /clp : ErrorsOnly '' } Function ChangeAssemblyVersion ( ) { Param ( [ Parameter ( Mandatory= $ true ) ] [ string ] $ filePath , [ Parameter ( Mandatory= $ true ) ] [ string ] $ publishVersion ) Write-Host `` -- Updating ' $ filePath ' to version ' $ publishVersion ' '' $ assemblyVersionPattern = 'AssemblyVersion\ ( `` [ 0-9 ] + ( \ . ( [ 0-9 ] +|\* ) ) { 1,3 } '' \ ) ' $ assemblyVersion = 'AssemblyVersion ( `` ' + $ publishVersion + ' '' ) ' ; $ assemblyFileVersionPattern = 'AssemblyFileVersion\ ( `` [ 0-9 ] + ( \ . ( [ 0-9 ] +|\* ) ) { 1,3 } '' \ ) ' $ assemblyFileVersion = 'AssemblyFileVersion ( `` ' + $ publishVersion + ' '' ) ' ; ( Get-Content $ filePath -Encoding utf8 ) | ForEach-Object { % { $ _ -Replace $ assemblyVersionPattern , $ assemblyVersion } | % { $ _ -Replace $ assemblyFileVersionPattern , $ assemblyFileVersion } } | Set-Content $ filePath } Function ChangeNugetSpecDependencyVersion ( ) { Param ( [ Parameter ( Mandatory= $ true ) ] [ string ] $ filePath , [ Parameter ( Mandatory= $ true ) ] [ string ] $ packageId , [ Parameter ( Mandatory= $ true ) ] [ string ] $ publishVersion ) [ xml ] $ toFile = ( Get-Content $ filePath ) $ nodes = $ toFile.SelectNodes ( `` //package/metadata/dependencies/dependency [ starts-with ( @ id , $ packageId ) ] '' ) if ( $ nodes ) { foreach ( $ node in $ nodes ) { $ nodeId = $ node.id Write-Host `` -- Updating ' $ nodeId ' in ' $ filePath ' to version ' $ publishVersion ' '' $ node.version = `` [ `` + $ publishVersion + '' ] '' $ toFile.Save ( $ filePath ) } } } Function PackProject ( ) { Param ( [ Parameter ( Mandatory= $ true ) ] [ string ] $ project , [ Parameter ( Mandatory= $ true ) ] [ string ] $ configuration , [ Parameter ( Mandatory= $ true ) ] [ string ] $ outputFolder ) if ( ! ( Test-Path -Path $ outputFolder ) ) { New-Item $ outputFolder -Type Directory } Write-Host `` -- Packaging ' $ project ' '' Invoke-Expression `` .nuget\NuGet.exe pack $ project -OutputDirectory ' $ outputFolder ' -Prop Configuration= $ configuration '' } Function PublishPackage ( ) { Param ( [ Parameter ( Mandatory= $ true ) ] [ string ] $ package ) Write-Host `` -- Publishing ' $ package ' '' Invoke-Expression `` .nuget\NuGet.exe push $ package '' }",NuGet release management "C_sharp : I have two generic types above , which one inherits from another but is still generic . The strange thing I ca n't figure out is that typeof ( SubGenericType < > ) .IsSubclassOf ( typeof ( BaseGenericType < > ) ) returns false . And typeof ( SubGenericType < > ) .IsSubclassOf ( typeof ( BaseGenericType < List < > > ) ) still returns false . I 've tried GetGenericTypeDefinition ( ) and MakeGenericType ( ) and GetGenericArguments ( ) to check the inheritance , still not working . But typeof ( SubGenericType < int > ) .IsSubclassOf ( typeof ( BaseGenericType < List < int > > ) ) returns true . What I want is to get all classes by reflection then grab the specific class which inherits from a generic type passed in.e.g . ( 1 ) List < int > -- > ( 2 ) get generic type definition == > List < T > -- > ( 3 ) make generic == > BaseGenericType < List < T > > -- > ( 4 ) find subclass == > SubGenericType < T > ( 5 ) make generic == > SubGenericType < int > In step ( 4 ) I find nothing although I actually have that SubGenericType < T > . Why is that ? public class BaseGenericType < T > { } public class SubGenericType < T > : BaseGenericType < List < T > > { }",Generic type inheritance "C_sharp : When doing an upcast or downcast , what does really happen behind the scenes ? I had the idea that when doing something as : the cast in the last line would have as only purpose tell the compiler we are safe we are not doing anything wrong . So , I had the idea that actually no casting code would be embedded in the code itself . It seems I was wrong : Why does the CLR need something like castclass string ? There are two possible implementations for a downcast : You require a castclass something . When you get to the line of code that does an castclass , the CLR tries to make the cast . But then , what would happen had I ommited the castclass string line and tried to run the code ? You do n't require a castclass . As all reference types have a similar internal structure , if you try to use a string on an Form instance , it will throw an exception of wrong usage ( because it detects a Form is not a string or any of its subtypes ) .Also , is the following statamente from C # 4.0 in a Nutshell correct ? Does it really create a new reference ? I thought it 'd be the same reference , only stored in a different type of variable.Thanks string myString = `` abc '' ; object myObject = myString ; string myStringBack = ( string ) myObject ; .maxstack 1.locals init ( [ 0 ] string myString , [ 1 ] object myObject , [ 2 ] string myStringBack ) L_0000 : nop L_0001 : ldstr `` abc '' L_0006 : stloc.0 L_0007 : ldloc.0 L_0008 : stloc.1 L_0009 : ldloc.1 L_000a : castclass stringL_000f : stloc.2 L_0010 : ret Upcasting and downcasting between compatible reference types performs referenceconversions : a new reference is created that points to the same object .",How do actually castings work at the CLR level ? "C_sharp : I need to write something I call Aggregation Container , which stores Aggregations , which are essentially Actions that take a collection of objects and output a single object as a result . Examples of Aggregations would be : Arithmetic Mean , Median of a set of numbers , Harmonic Mean etc . Here 's a sample code.Here 's my problem with the code . I have assumed that the objects were just double and hence made a conversion . What if they 're not double ? How can I make sure that I 'm allowed to sum two objects ? Is there some kind of interface for that in standard .Net assemblies ? I need something like ISummable ... Or do I need to implement it myself ( then I will have to wrap all primitive types like double , int , etcetera to support it ) .Any advice regarding the design of such functionality will be helpful . var arithmeticMean = new Aggregation { Descriptor = new AggregationDescriptor { Name = `` Arithmetic Mean '' } , Action = ( IEnumerable arg ) = > { double count = 0 ; double sum = 0 ; foreach ( var item in arg ) { sum += ( double ) item ; count++ ; } return sum / count ; } } ;",Aggregation and how to check if we can sum objects "C_sharp : I have been given the below .NET question in an interview . I don ’ t know why I got low marks . Unfortunately I did not get a feedback.Question : The file hockey.csv contains the results from the Hockey Premier League . The columns ‘ For ’ and ‘ Against ’ contain the total number of goals scored for and against each team in that season ( so Alabama scored 79 goals against opponents , and had 36 goals scored against them ) .Write a program to print the name of the team with the smallest difference in ‘ for ’ and ‘ against ’ goals.the structure of the hockey.csv looks like this ( it is a valid csv file , but I just copied the values here to get an idea ) Team - For - AgainstAlabama 79 36Washinton 67 30Indiana 87 45Newcastle 74 52Florida 53 37New York 46 47Sunderland 29 51Lova 41 64Nevada 33 63Boston 30 64Nevada 33 63Boston 30 64Solution : Output : Smallest difference in for ' andagainst ' goals > TEAM : Boston , GOALS DIF : -34Can someone please review my code and see anything obviously wrong here ? They were only interested in the structure/design of the code and whether the program produces the correct result ( i.e lowest difference ) . Much appreciated . class Program { static void Main ( string [ ] args ) { string path = @ '' C : \Users\ < valid csv path > '' ; var resultEvaluator = new ResultEvaluator ( string.Format ( @ '' { 0 } \ { 1 } '' , path , `` hockey.csv '' ) ) ; var team = resultEvaluator.GetTeamSmallestDifferenceForAgainst ( ) ; Console.WriteLine ( string.Format ( `` Smallest difference in ‘ For ’ and ‘ Against ’ goals > TEAM : { 0 } , GOALS DIF : { 1 } '' , team.Name , team.Difference ) ) ; Console.ReadLine ( ) ; } } public interface IResultEvaluator { Team GetTeamSmallestDifferenceForAgainst ( ) ; } public class ResultEvaluator : IResultEvaluator { private static DataTable leagueDataTable ; private readonly string filePath ; private readonly ICsvExtractor csvExtractor ; public ResultEvaluator ( string filePath ) { this.filePath = filePath ; csvExtractor = new CsvExtractor ( ) ; } private DataTable LeagueDataTable { get { if ( leagueDataTable == null ) { leagueDataTable = csvExtractor.GetDataTable ( filePath ) ; } return leagueDataTable ; } } public Team GetTeamSmallestDifferenceForAgainst ( ) { var teams = GetTeams ( ) ; var lowestTeam = teams.OrderBy ( p = > p.Difference ) .First ( ) ; return lowestTeam ; } private IEnumerable < Team > GetTeams ( ) { IList < Team > list = new List < Team > ( ) ; foreach ( DataRow row in LeagueDataTable.Rows ) { var name = row [ `` Team '' ] .ToString ( ) ; var @ for = int.Parse ( row [ `` For '' ] .ToString ( ) ) ; var against = int.Parse ( row [ `` Against '' ] .ToString ( ) ) ; var team = new Team ( name , against , @ for ) ; list.Add ( team ) ; } return list ; } } public interface ICsvExtractor { DataTable GetDataTable ( string csvFilePath ) ; } public class CsvExtractor : ICsvExtractor { public DataTable GetDataTable ( string csvFilePath ) { var lines = File.ReadAllLines ( csvFilePath ) ; string [ ] fields ; fields = lines [ 0 ] .Split ( new [ ] { ' , ' } ) ; int columns = fields.GetLength ( 0 ) ; var dt = new DataTable ( ) ; //always assume 1st row is the column name . for ( int i = 0 ; i < columns ; i++ ) { dt.Columns.Add ( fields [ i ] .ToLower ( ) , typeof ( string ) ) ; } DataRow row ; for ( int i = 1 ; i < lines.GetLength ( 0 ) ; i++ ) { fields = lines [ i ] .Split ( new char [ ] { ' , ' } ) ; row = dt.NewRow ( ) ; for ( int f = 0 ; f < columns ; f++ ) row [ f ] = fields [ f ] ; dt.Rows.Add ( row ) ; } return dt ; } } public class Team { public Team ( string name , int against , int @ for ) { Name = name ; Against = against ; For = @ for ; } public string Name { get ; private set ; } public int Against { get ; private set ; } public int For { get ; private set ; } public int Difference { get { return ( For - Against ) ; } } }",".NET interview , code structure and the design" "C_sharp : I have a string likeand a List < int > with indexeswith following restrictionsthere are duplicates within the listthe list is not sortedthere may be indexes > Text.lengthwhat 's the best way to remove characters from the text which are in the index list ? expected output : Is there a more efficent way thanUpdate : Here are the Benchmarks of the current answers ( string with 100.000 characters and List < int > with length 10.000 : string Text = `` 012345678901234567890123456789 '' ; List < int > Indexes = new List < int > ( ) { 2 , 4 , 7 , 9 , 15 , 18 , 23 , 10 , 1 , 2 , 15 , 40 } ; 035681234679012456789 foreach ( int index in Indexes .OrderByDescending ( x = > x ) .Distinct ( ) .Where ( x = > x < Text.Length ) ) { Text = Text.Remove ( index , 1 ) ; } Gallant : 3.322 ticksTim Schmelter : 8.602.576 ticksSergei Zinovyev : 9.002 ticksrbaghbanli : 7.137 ticksJirí Tesil Tesarík : 72.580 ticks",Remove chars from string "C_sharp : I 'm attempting to get an insert query to run from my C # web application . When I run the query from SQL Server Management Studio , the insert query takes around five minutes to complete . When run from the application , it times out after thirty minutes ( yes minutes , not seconds ) .I 've grabbed the actual SQL statement from the VS debugger and run it from Mgmt Studio and it works fine.All this is running from my development environment , not a production environment . There is no other SQL Server activity while the query is in progress . I 'm using SQL Server 2008 R2 for development . MS VS 2010 Express , Asp.Net 4.0 . SQL Server Mgmt Studio 10.There is a similar question to this that was never answered : SQL server timeout 2000 from C # .NETHere 's the SET options from : dbcc useroptionsOnly textsize and arithabort are different.Any ideas why there is such a difference in query execution time and what I may be able to do to narrow that difference ? I 'm not sure how useful including the query will be , especially since it would be too much to include the schema . Anyway , here it is : Option MgtStudio Application -- -- -- -- -- -- -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- textsize 2147483647 -1language us_english us_englishdateformat mdy mdydatefirst 7 7lock_timeout -1 -1quoted_identifier SET SETarithabort SET NOT SETansi_null_dflt_on SET SETansi_warnings SET SETansi_padding SET SETansi_nulls SET SETconcat_null_yields_null SET SETisolation level read committed read committed INSERT INTO GeocacherPoints ( CacherID , RegionID , Board , Control , Points ) SELECT z.CacherID , z.RegionID , z.Board , 21 , z.PointsFROM ( SELECT CacherID , gp.RegionID , Board=gp.Board + 10 , ( CASE WHEN ( SELECT COUNT ( * ) FROM Geocache g JOIN GeocacheRegions r ON ( r.CacheID = g.ID ) WHERE r.RegionID = gp.RegionID AND g.FinderPoints > = 5 ) < 20 THEN NULL ELSE ( SELECT SUM ( y.FinderPoints ) / 20 FROM ( SELECT x.FinderPoints , ROW_NUMBER ( ) OVER ( ORDER BY x.FinderPoints DESC , x.ID ) AS Row FROM ( SELECT g.FinderPoints , g.ID FROM Geocache g JOIN Log l ON ( l.CacheID = g.ID ) JOIN Geocacher c ON ( c.ID = l.CacherID ) JOIN GeocacheRegions r ON ( r.CacheID = g.ID ) WHERE YEAR ( l.LogDate ) = @ Year AND g.FinderPoints > = 5 AND c.ID = gp.CacherID AND r.RegionID = gp.RegionID ) x ) y WHERE y.Row < = 20 ) END ) Points FROM GeocacherPoints gp JOIN Region r ON r.RegionID = gp.RegionID WHERE gp.Control = 21 AND r.RegionType IN ( 'All ' , 'State ' ) AND gp.Board = @ Board - 10 ) zWHERE z.Points IS NOT NULL AND z.Points > = 1","Insert query times out in C # web app , runs fine from SQL Server Management Studio" "C_sharp : I have created an Object array like this . But to assign value to object , I have to instantiate each object at every positions of the array ? Why do I need this ? This is My methodAnd Object Class StageObject [ ] StageSplitDate = new StageObject [ Stages.Rows.Count ] ; for ( int i = 0 ; i < Stages.Rows.Count ; i++ ) { StageSplitDate [ i ] = new StageObject ( ) ; StageSplitDate [ i ] .StageId = `` String Value '' ; StageSplitDate [ i ] .FromTime = StartTime ; StartTime =StartTime.AddMinutes ( Convert.ToDouble ( 10 ) ) ; StageSplitDate [ i ] .ToTime = StartTime ; } return StageSplitDate ; public class StageObject { public string StageId { get ; set ; } public DateTime FromTime { get ; set ; } public DateTime ToTime { get ; set ; } }",Why do I need to Instantiate an Object Array Twice ? "C_sharp : I try to get a list of all methods of a type . Type provides the GetMethods method to do this . But unfortunately it seems to be incorrectly implemented . It works properly as long as there is no overridden generic method on the reflected type . In this special case a MethodAccessException is thrown.Does anyone have a workaround for this WP7 bug ? I 'm fine if all methods except the generic ones are returned.Here is a sample of a class that will throw an exception . Note : the none generic return value is intended to prove that the return value is not involved in the problem . Furthermore , the base method can be changed to abstract and the problem still remains . public abstract class BaseClassWithGenericMethod { public virtual System.Collections.IList CreateList < T > ( ) { return new List < T > ( ) ; } } public class DerivedClassWithGenericMethod : BaseClassWithGenericMethod { public override System.Collections.IList CreateList < T > ( ) { return new List < T > ( ) ; } }",WP7 : Type.GetMethods throws MethodAccessException . Is there a workaround for this bug ? "C_sharp : CodeExpected outputActual outputQuestionWhy does replacing not work when the order of `` foo '' and `` foobar '' in regex pattern is changed ? How to fix this ? using System ; using System.Text.RegularExpressions ; namespace RegexNoMatch { class Program { static void Main ( ) { string input = `` a foobar & b '' ; string regex1 = `` ( foobar|foo ) & ? `` ; string regex2 = `` ( foo|foobar ) & ? `` ; string replace = `` $ 1 '' ; Console.WriteLine ( Regex.Replace ( input , regex1 , replace ) ) ; Console.WriteLine ( Regex.Replace ( input , regex2 , replace ) ) ; Console.ReadKey ( ) ; } } } a foobar ba foobar b a foobar ba foobar & b",Why does the order of alternatives matter in regex ? "C_sharp : When disassembling .NET functions , I notice that they all start with a similair pattern.What does this initial code do ? This code appear before the actual code for what the function is supposed to do.Is it some sort of parameter count verification ? func1func2func3 [ Edit ] So is this a correct description of it ? or ? private static void Foo ( int i ) { Console.WriteLine ( `` hello '' ) ; } 00000000 push ebp 00000001 mov ebp , esp 00000003 push eax 00000004 mov dword ptr [ ebp-4 ] , ecx 00000007 cmp dword ptr ds : [ 005C14A4h ] ,0 0000000e je 00000015 00000010 call 65E0367F //the console writleline code follows here and is not part of the question static private void Bar ( ) { for ( int i = 0 ; i < 1000 ; i++ ) { Foo ( i ) ; } } 00000000 push ebp 00000001 mov ebp , esp 00000003 push eax 00000004 cmp dword ptr ds : [ 006914A4h ] ,0 0000000b je 00000012 0000000d call 65CC36CF // the for loop code follows here private static void Foo ( ) { Console.WriteLine ( `` hello '' ) ; } 00000000 push ebp 00000001 mov ebp , esp 00000003 cmp dword ptr ds : [ 005614A4h ] ,0 0000000a je 00000011 0000000c call 65E3367F //fix stackframe00000000 push ebp 00000001 mov ebp , esp //store eax so it can be used locally00000003 push eax //ensure static ctor have been called00000004 cmp dword ptr ds : [ 006914A4h ] ,0 //it has been called , ignore it0000000b je 00000012//it has n't been called , call it now 0000000d call 65CC36CF",.NET functions disassembled C_sharp : I have a very generic extension method to show any type of list within a console : Not when I have a string I can use this Method But in case of string it does n't make sense in my application . How can I exclude string from this method ? I 've read something about public static void ShowList < T > ( this IEnumerable < T > Values ) { foreach ( T item in Values ) { Console.WriteLine ( item ) ; } } string text = `` test '' ; text.ShowList ( ) ; ShowList < T > ( this IEnumerable < T > Values ) : Where ! = string //does n't work,Restrict generic extension method from extending strings "C_sharp : I am currently trying to localize my windowsphone Time App for a few countries . I am using Noda Time as it was extremely easy for a newbie . The problem I am facing that all the Timezone Id 's are in standard English and I am searching for a way to get those Id 's converted to Local Language strings.One way would be too make Localized strings for each ID in every language . But it seems to be Highly inefficient as there are 500 timezones . Please suggest a way for me to get directly the TimeZone ID 's converted into Local Language in a less time consuming way.My code : var now = Instant.FromDateTimeUtc ( DateTime.UtcNow ) ; var tzdb = DateTimeZoneProviders.Tzdb ; var list = from id in tzdb.Ids where id.Contains ( `` / '' ) & & ! id.StartsWith ( `` etc '' , StringComparison.OrdinalIgnoreCase ) let tz = tzdb [ id ] let offset = tz.GetUtcOffset ( now ) orderby offset , id select new { DisplayValue = string.Format ( `` ( UTC { 0 } ) { 1 } { 2 } `` , offset.ToString ( `` +HH : mm '' , null ) , now.WithOffset ( offset ) .TimeOfDay.ToString ( `` hh : mm tt '' , null ) , id ) } ;",How to convert the standard Noda Timezone Id 's from English to Localized Language ? "C_sharp : For POST requests using HttpWebRequest , when I write to a request stream , at what point does the data get sent ? Is it when I close the request stream or when I call GetResponse ? Is the GetResponse call required ? The .net documentation does not seem to be very clear about what is really happeningHere 's the code I 'm curious about : Thanks ! HttpWebRequest request = HttpWebRequest.Create ( url ) as HttpWebRequest ; request.Method = `` POST '' ; request.ContentLength = jsonData.Length ; request.ContentType = `` application/json '' ; Stream requestStream = request.GetRequestStream ( ) ; requestStream.Write ( jsonData , 0 , jsonData.Length ) ; requestStream.Close ( ) ; var response = request.GetResponse ( ) as HttpWebResponse ;",Is HttpWebRequest.GetResponse required to complete a POST ? "C_sharp : Here 's what we 're trying to do : We want an unobtrusive way of taking everything a client prints on their computer ( all of our clients are running POS systems and use Windows XP exclusively ) and sending it to us , and we 've decided the best way to do that is to create a c # app that sends us their spool files , which we can already parse easily . However , this requires setting `` Keep All Printed Documents '' to true . We want to do this in our app rather than manually , for the following reason : some ( hundreds ) of our clients are , for lack of a better word , dumb . We do n't want to force them to mess around in control panel ... our tech support people are busy enough as it is.Here 's where I 've run into a problem : This should , as far as I can tell from several hours of WMI research , set the KeepPrintedJobs property of each printer to true ... but its not working . As soon as the foreach loop ends , KeepPrintedJobs is set back to false . We 'd prefer to use WMI and not mess around in the registry , but I ca n't spend forever trying to make this work . Any ideas on what 's missing ? string searchQuery = `` SELECT * FROM Win32_Printer '' ; ManagementObjectSearcher searchPrinters = new ManagementObjectSearcher ( searchQuery ) ; ManagementObjectCollection printerCollection = searchPrinters.Get ( ) ; foreach ( ManagementObject printer in printerCollection ) { PropertyDataCollection printerProperties = printer.Properties ; foreach ( PropertyData property in printerProperties ) { if ( property.Name == `` KeepPrintedJobs '' ) { printerProperties [ property.Name ] .Value = true ; } } }",Setting printer 's `` KeepPrintedDocuments '' property in .NET "C_sharp : I am having trouble deserialising datetimes with Json.Net 6.0.3 ( I can replicate the issue on 6.0.6 ) . The code is run in .Net 4.5 on Windows 8.1 , and the culture is en-GB.This demonstrates the problem : the output : The date times are different depending on how the JObject is accessed - one is MM/DD/YYYY DD/MM/YYYY . Why is this ? I do n't need them to be in a specific format : the problem is that the format changes . I have a lot of legacy code that parses the datetime string sourced from Json.Net . The code will also run on different computers around the world , maybe with different cultures.Is there a way to make Json.Net always return datetimes in the same format ? using Newtonsoft.Json ; using Newtonsoft.Json.Linq ; var d1 = new DateTimeOffset ( 2014 , 12 , 15 , 18 , 0 , 0 , TimeSpan.FromHours ( 1 ) ) ; var obj = new { time = d1 } ; var json = JsonConvert.SerializeObject ( obj , Formatting.Indented ) ; Console.WriteLine ( json ) ; var jo = JObject.Parse ( json ) ; Console.WriteLine ( jo.Value < string > ( `` time '' ) + `` // jo.Value < string > ( \ '' time\ '' ) '' ) ; Console.WriteLine ( jo [ `` time '' ] + `` // jo [ \ '' time\ '' ] '' ) ; { `` time '' : `` 2014-12-15T18:00:00+01:00 '' } 12/15/2014 17:00:00 // jo.Value < string > ( `` time '' ) 15/12/2014 17:00:00 // jo [ `` time '' ]",Json.Net deserialising DateTimes inconsistently "C_sharp : I have the following entities : And I 'm trying to create an new application user and student , so I 'm doing this : Result is success , the two entities are inserted in database , but Student.UserId is nullHow can I insert both entities and their relationship ? I tried setting student.UserId = user.Id , but then I get an exception with this message : `` Unable to determine a valid ordering for dependent operations '' public class ApplicationUser : IdentityUser { ... public int ? StudentId { get ; set ; } public virtual Student Student { get ; set ; } } public class Student { public int Id { get ; set ; } public string UserId { get ; set ; } public virtual ApplicationUser User { get ; set ; } } var user = new ApplicationUser ( ) { Name = `` test '' , UserName = `` test '' , Student = new Student ( ) } ; var result = await userManager.CreateAsync ( user , `` test12345 ! `` ) ;",Insert dependent entity with ApplicationUser "C_sharp : The code is compiling without any error . I do not understand why the first line of the catch block is not giving any compilation error -catch ( DataException ) DataException parameter of the catch block is a class , and it should have a variable next to it such as - catch ( DataException d ) Can someone explain the above behavior ? static void Main ( string [ ] args ) { try { Console.WriteLine ( `` No Error '' ) ; } catch ( DataException ) /*why no compilation error in this line ? */ { Console.WriteLine ( `` Error ... . '' ) ; } Console.ReadKey ( ) ; }",C # catch ( DataException ) - no variable defined "C_sharp : I 'm new to Windows service development , and need to build one in C # that will listen on port 8080 for data coming in , then parse it . I 've found information about System.Net.WebSockets , System.Net.Sockets , and third-party libraries , such as SuperSocket . There 's this example , but not sure what goes in the OnStart ( ) and what goes in OnStop ( ) methods of my Windows service class . Another example is here , but that 's also not covering Windows service specifically . For basic Windows service development , there 's this MSDN article.I 'm thinking this goes in OnStart ( ) : What would I put into the OnStop ( ) ? The data stream coming in does n't require any authentication . Would I still need to do a handshake ? Your help is appreciated . Socket serverSocket = new Socket ( AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.IP ) ; serverSocket.Bind ( new IPEndPoint ( IPAddress.Any , 8080 ) ) ; serverSocket.Listen ( 128 ) ; serverSocket.BeginAccept ( null , 0 , OnAccept , null ) ;",WebSocket windows service listening on port 8080 "C_sharp : I created a little code which searches for a Regex string and replaces that with something else , it then creates a new output file with the changes made.The code seems to work well with smaller files , but for 100 MB or larger files I am giving the System.OutOfMemoryException ' error . Here 's my code : Visual studio highlights the string text = File.ReadAllText ( textBox1.Text ) ; section.I thought that maybe using File.ReadAllLines would work better , but I was not able to make it work with regex.Can anybody help me on this ? I am newbie to C # and probably my code is not the best one . string foldername = Path.Combine ( Environment.GetFolderPath ( Environment.SpecialFolder.Desktop ) , String.Format ( `` FIXED_ { 0 } .tmx '' , Path.GetFileNameWithoutExtension ( textBox1.Text ) ) ) ; string text = File.ReadAllText ( textBox1.Text ) ; text = Regex.Replace ( text , @ '' < seg\b [ ^ > ] * > '' , `` < seg > '' , RegexOptions.Multiline ) ; text = Regex.Replace ( text , @ '' < seg > < /tuv > '' , `` < seg > < /seg > < /tuv > '' , RegexOptions.Multiline ) ; File.WriteAllText ( foldername , text ) ;",Search and replace regex in large files without getting OutOfMemoryException "C_sharp : I have a little service that uploads an image , and I use it like this : What I 'd like to do is to display a progress dialog , but only if the upload operation takes more than , say , 2 seconds . After the upload is done , I want to close the progress dialog.I made a crude solution using Task/ContinueWith , but I was hoping for a more `` elegant '' way.How can I achieve this using async/await ? ImageInfo result = await service.UploadAsync ( imagePath ) ;",Displaying progress dialog only if a task did not finish in specified time "C_sharp : I have a queue that processes objects in a while loop . They are added asynchronously somewhere.. like this : And they are processed like this : Now , the thing is that I 'd like to modify this to support a TTL-like ( time to live ) flag , so the file path would be added o more than n times.How could I do this , while keeping the bool process ( String path ) function signature ? I do n't want to modify that . I thought about holding a map , or a list that counts how many times the process function returned false for a path and drop the path from the list at the n-th return of false . I wonder how can this be done more dynamically , and preferably I 'd like the TTL to automatically decrement itself at each new addition to the process . I hope I am not talking trash . Maybe using something like this myqueue.pushback ( String value ) ; while ( true ) { String path = queue.pop ( ) ; if ( process ( path ) ) { Console.WriteLine ( `` Good ! `` ) ; } else { queue.pushback ( path ) ; } } class JobData { public string path ; public short ttl ; public static implicit operator String ( JobData jobData ) { jobData.ttl -- ; return jobData.path ; } }",Design pattern for dynamic C # object "C_sharp : Let 's say I have an interface , like this : And some extension methods , like this : Then in any class CoreService : ServiceBase , ILoggable or such I implement that public void Log ( Func < string > message , Logger.Type type ) to whatever I like ( public modifier being kind of meh ... ) and use all the extension methods to do actual logging.So far so good ... or not so good ? Is there something wrong with this approach ? If not , then why the inconvenience : public interface ILoggable { void Log ( Func < string > message , Logger.Type type ) ; } public static class Logger { public static void Log ( this ILoggable loggable , Func < string > message ) { loggable.Log ( message , Type.Information ) ; } public static void Log ( this ILoggable loggable , string prefix , byte [ ] data , int len ) { /* snip */ } public static void Log ( this ILoggable loggable , Exception ex ) { /* snip */ } // And so on ... } catch ( Exception ex ) { this.Log ( ex ) ; // this works Log ( ex ) ; // this goes not",Using extension methods inside extended class itself "C_sharp : I have a class responsible for downloading files in a download manager . This class is responsible for downloading the file and writing it to the given path.The size of the files to download varies normally from 1 to 5 MB but could also be much larger . I 'm using an instance of the WebClient class to get the file from the internet.Every download causes a very large memory increase compared with the file size of the downloaded item . If I download a file with a size of ~3 MB the memory usage is increasing about 8 MB.As you can see the download is producing much LOH which is not cleared after the download . Even forcing the GC or the setting GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce ; is not helping to prevent this memory leak.Comparing Snapshot 1 and 2 you can see that the amount of memory is produced by byte arrays which might be the download result.Doing several downloads shows how terrible this memory leak is.In my opinion this is caused by the WebClient instance in any way . However I ca n't really determine what exactly is causing this issue.It does n't even matters if I force the GC . This screen here shows it without forced gc : What is causing this overheat and how can I fix it ? This is a major bug and imagining 100 or more downloads the process would run out of memory . EditAs suggested I commented out the section responsible for setting the tags and converting the M4A to an MP3 . However the converter is just a call of FFMPEG so it should n't be a memory leak : The DownloadCompleted ( ) method looks now like this : The result after downloading 7 items : It seems like this was not the memory leak.As an addition I 'm submitting the DownloadManager class too as it is handling the whole download operation . Maybe this could be the source of the problem . public class DownloadItem { # region Events public delegate void DownloadItemDownloadCompletedEventHandler ( object sender , DownloadCompletedEventArgs args ) ; public event DownloadItemDownloadCompletedEventHandler DownloadItemDownloadCompleted ; protected virtual void OnDownloadItemDownloadCompleted ( DownloadCompletedEventArgs e ) { DownloadItemDownloadCompleted ? .Invoke ( this , e ) ; } public delegate void DownloadItemDownloadProgressChangedEventHandler ( object sender , DownloadProgressChangedEventArgs args ) ; public event DownloadItemDownloadProgressChangedEventHandler DownloadItemDownloadProgressChanged ; protected virtual void OnDownloadItemDownloadProgressChanged ( DownloadProgressChangedEventArgs e ) { DownloadItemDownloadProgressChanged ? .Invoke ( this , e ) ; } # endregion # region Fields private static readonly Logger Logger = LogManager.GetCurrentClassLogger ( ) ; private WebClient _client ; # endregion # region Properties public PlaylistItem Item { get ; } public string SavePath { get ; } public bool Overwrite { get ; } # endregion public DownloadItem ( PlaylistItem item , string savePath , bool overwrite = false ) { Item = item ; SavePath = savePath ; Overwrite = overwrite ; } public void StartDownload ( ) { if ( File.Exists ( SavePath ) & & ! Overwrite ) { OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( true ) ) ; return ; } OnDownloadItemDownloadProgressChanged ( new DownloadProgressChangedEventArgs ( 1 ) ) ; Item.RetreiveDownloadUrl ( ) ; if ( string.IsNullOrEmpty ( Item.DownloadUrl ) ) { OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( true , new InvalidOperationException ( `` Could not retreive download url '' ) ) ) ; return ; } // GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce ; using ( _client = new WebClient ( ) ) { _client.Headers.Add ( `` user-agent '' , `` Mozilla/4.0 ( compatible ; MSIE 6.0 ; Windows NT 5.2 ; .NET CLR 1.0.3705 ; ) '' ) ; try { _client.DownloadDataCompleted += ( sender , args ) = > { Task.Run ( ( ) = > { DownloadCompleted ( args ) ; } ) ; } ; _client.DownloadProgressChanged += ( sender , args ) = > OnDownloadItemDownloadProgressChanged ( new DownloadProgressChangedEventArgs ( args.ProgressPercentage ) ) ; _client.DownloadDataAsync ( new Uri ( Item.DownloadUrl ) ) ; } catch ( Exception ex ) { Logger.Warn ( ex , `` Error downloading track { 0 } '' , Item.VideoId ) ; OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( true , ex ) ) ; } } } private void DownloadCompleted ( DownloadDataCompletedEventArgs args ) { // _client = null ; // GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce ; // GC.Collect ( 2 , GCCollectionMode.Forced ) ; if ( args.Cancelled ) { OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( true , args.Error ) ) ; return ; } try { File.WriteAllBytes ( SavePath , args.Result ) ; using ( var file = TagLib.File.Create ( SavePath ) ) { file.Save ( ) ; } try { MusicFormatConverter.M4AToMp3 ( SavePath ) ; } catch ( Exception ) { // ignored } OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( false ) ) ; } catch ( Exception ex ) { OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( true , ex ) ) ; Logger.Error ( ex , `` Error writing track file for track { 0 } '' , Item.VideoId ) ; } } public void StopDownload ( ) { _client ? .CancelAsync ( ) ; } public override int GetHashCode ( ) { return Item.GetHashCode ( ) ; } public override bool Equals ( object obj ) { var item = obj as DownloadItem ; return Item.Equals ( item ? .Item ) ; } } class MusicFormatConverter { public static void M4AToMp3 ( string filePath , bool deleteOriginal = true ) { if ( string.IsNullOrEmpty ( filePath ) || ! filePath.EndsWith ( `` .m4a '' ) ) throw new ArgumentException ( nameof ( filePath ) ) ; var toolPath = Path.Combine ( `` tools '' , `` ffmpeg.exe '' ) ; var convertedFilePath = filePath.Replace ( `` .m4a '' , `` .mp3 '' ) ; File.Delete ( convertedFilePath ) ; var process = new Process { StartInfo = { FileName = toolPath , # if ! DEBUG WindowStyle = ProcessWindowStyle.Hidden , # endif Arguments = $ '' -i \ '' { filePath } \ '' -acodec libmp3lame -ab 128k \ '' { convertedFilePath } \ '' '' } } ; process.Start ( ) ; process.WaitForExit ( ) ; if ( ! File.Exists ( convertedFilePath ) ) throw new InvalidOperationException ( `` File was not converted successfully ! `` ) ; if ( deleteOriginal ) File.Delete ( filePath ) ; } } private void DownloadCompleted ( DownloadDataCompletedEventArgs args ) { // _client = null ; // GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce ; // GC.Collect ( 2 , GCCollectionMode.Forced ) ; if ( args.Cancelled ) { OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( true , args.Error ) ) ; return ; } try { File.WriteAllBytes ( SavePath , args.Result ) ; /* using ( var file = TagLib.File.Create ( SavePath ) ) { file.Save ( ) ; } try { MusicFormatConverter.M4AToMp3 ( SavePath ) ; } catch ( Exception ) { // ignore } */ OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( false ) ) ; } catch ( Exception ex ) { OnDownloadItemDownloadCompleted ( new DownloadCompletedEventArgs ( true , ex ) ) ; Logger.Error ( ex , `` Error writing track file for track { 0 } '' , Item.VideoId ) ; } } public class DownloadManager { # region Fields private static readonly Logger Logger = LogManager.GetCurrentClassLogger ( ) ; private readonly Queue < DownloadItem > _queue ; private readonly List < DownloadItem > _activeDownloads ; private bool _active ; private Thread _thread ; # endregion # region Construction public DownloadManager ( ) { _queue = new Queue < DownloadItem > ( ) ; _activeDownloads = new List < DownloadItem > ( ) ; } # endregion # region Methods public void AddToQueue ( DownloadItem item ) { _queue.Enqueue ( item ) ; StartManager ( ) ; } public void Abort ( ) { _thread ? .Abort ( ) ; _queue.Clear ( ) ; _activeDownloads.Clear ( ) ; } private void StartManager ( ) { if ( _active ) return ; _active = true ; _thread = new Thread ( ( ) = > { try { while ( _queue.Count > 0 & & _queue.Peek ( ) ! = null ) { DownloadItem ( ) ; while ( _activeDownloads.Count > = Properties.Settings.Default.ParallelDownloads ) { Thread.Sleep ( 10 ) ; } } _active = false ; } catch ( ThreadInterruptedException ) { // ignored } } ) ; _thread.Start ( ) ; } private void DownloadItem ( ) { if ( _activeDownloads.Count > = Properties.Settings.Default.ParallelDownloads ) return ; DownloadItem item ; try { item = _queue.Dequeue ( ) ; } catch { return ; } if ( item ! = null ) { item.DownloadItemDownloadCompleted += ( sender , args ) = > { if ( args.Error ! = null ) Logger.Error ( args.Error , `` Error downloading track { 0 } '' , ( ( DownloadItem ) sender ) .Item.VideoId ) ; _activeDownloads.Remove ( ( DownloadItem ) sender ) ; } ; _activeDownloads.Add ( item ) ; Task.Run ( ( ) = > item.StartDownload ( ) ) ; } } # endregion",C # WebClient - Large increase of LOH after downloading files "C_sharp : I 've got a query that returns something of the following format : and I 'd like to convert that to a dictionary of < string , string [ ] > like so : I 've tried with this : but so far I am not having any luck . I think what this is doing is actually trying to add individual items like `` tesla '' : [ `` model s '' ] and `` tesla '' : [ `` roadster '' ] and that 's why it 's failing ... any easy way to accomplish what I am trying to do in LINQ ? { `` tesla '' , `` model s '' } { `` tesla '' , `` roadster '' } { `` honda '' , `` civic '' } { `` honda '' , `` accord '' } { `` tesla '' : [ `` model s '' , `` roadster '' ] , `` honda '' : [ `` civic '' , `` accord '' ] } var result = query.Select ( q = > new { q.Manufacturer , q.Car } ) .Distinct ( ) .ToDictionary ( q = > q.Manufacturer.ToString ( ) , q = > q.Car.ToArray ( ) ) ;","Converting a LINQ query into a Dictionary < string , string [ ] >" "C_sharp : Consider the following method signature : This method performs the following : accesses the database to generate a list of Poll objects . returns true if it was success and errorMessage will be an empty stringreturns false if it was not successful and errorMessage will contain an exception message . Is this good style ? Update : Lets say i do use the following method signature : and in that method , it does n't catch any exceptions ( so i depend the caller to catch exceptions ) . How do i dispose and close all the objects that is in the scope of that method ? As soon as an exception is thrown , the code that closes and disposes objects in the method is no longer reachable . public static bool TryGetPolls ( out List < Poll > polls , out string errorMessage ) public static List < Poll > GetPolls ( )",Is this good C # style ? "C_sharp : I have a class with an overloaded method : I want to pass a lambda expression to the Action version : Unfortunately , Visual Studio rightly can not tell the difference between the Action < Foo > and Action < Bar > versions , due to the type inference surrounding the `` foo '' variable -- and so it raises a compiler error : The call is ambiguous between the following methods or properties : 'MyClass.DoThis ( System.Action < Foo > ) ' and 'MyClass.DoThis ( System.Action < Bar > ) 'What 's the best way to get around this ? MyClass.DoThis ( Action < Foo > action ) ; MyClass.DoThis ( Action < Bar > action ) ; MyClass.DoThis ( foo = > foo.DoSomething ( ) ) ;",Ambiguous Call with a Lambda in C # .NET "C_sharp : My question is pretty simple , but unfortunately I could not find any answer yet.Using MEF , I can specify some internal exports and imports in a class library assembly like that : My CompositionContainer is located in the main EXE assembly , but somehow it manages to instantiate the SomeExport object inside the class library assembly so I can use it . Normally , my internal class library types should not be accessible from the EXE assembly , but somehow I get my instances created.How does it work ? [ Export ] internal class SomeExport { } [ ModuleExport ( typeof ( SomeModule ) ) ] internal class SomeModule : IModule { [ ImportingConstructor ] internal SomeModule ( SomeExport instance ) { } }",How does MEF manage to instantiate an exported part which is an internal class of an external assembly ? "C_sharp : I am trying to iterate over a DataTable and get the values from a particular column . So far I just have the Skeleton of the for loop . This does not work as I expected . I get an compiler error when trying to do row [ 0 ] , with the message : `` Can not apply indexing with [ ] to an expression of type Object '' . But row should not be an object , it is a DataRow . To fix this I changed the foreach loop to the following : Why is this necessary ? Why ca n't C # infer the type of row as it would if I was trying to iterate over a string [ ] for example ? foreach ( var row in currentTable.Rows ) { var valueAtCurrentRow = row [ 0 ] ; } foreach ( DataRow row in currentTable.Rows ) { var valueAtCurrentRow = row [ 0 ] ; }",Why ca n't C # infer the type of a DataTable Row "C_sharp : I am facing the exception The ObjectContext instance has been disposed and can no longer be used for operations that require a connection even after using the Include method.Here the function that retrieve the entities : Here the usage of the function : I understand that the using is closing the connection . I thought the ToList ( ) will instantiated the list of objects and the related objects in the include before closing . Can someone point me out what I do wrong ? Sorry , my question was not clear . I do understand that including the line that throw exception inside the bracket of the using is working , but I do not figure out why does the include does not works ? Thank you ! public List < Entity.CapacityGrid > SelectByFormula ( string strFormula , int iVersionId ) { // declaration List < Entity.CapacityGrid > oList ; // retrieve ingredients oList = ( from Grid in _Dc.CapacityGrid.Include ( `` EquipmentSection '' ) join Header in _Dc.CapacityHeader on Grid.HeaderId equals Header.HeaderId where Header.Formula == strFormula & & Header.VersionId == iVersionId select Grid ) .ToList ( ) ; // return return oList ; // retrieve ingredient quantity by equipement using ( Model.CapacityGrid oModel = new Model.CapacityGrid ( Configuration.RemoteDatabase ) ) oQuantity = oModel.SelectByFormula ( strFormulaName , iVersionId ) ; // code to throw the exception var o = ( oQuantity [ 0 ] .EquipmentSection.TypeId ) ;",EntityFramework 4.5 - Still get ObjectDisposedException even after using Include C_sharp : I am reading an Excel document using ADO.Net into a Dataset . Dataset Contains set of employee records which contains login and logout time as a Datatable . I need to fetch the employees 's first login and last logout time as final record from the set of records based on employee id and date . Here is my example data : I need the final record with calculated duration as Is it the best way to use Linq for querying this dataset ? Which way is the best Emp Id Name Login Logout 12345 RAMACHANDRAN 7/30/2013 8:40 7/30/2013 10:40 12345 RAMACHANDRAN 7/30/2013 12:30 7/30/2013 14:20 12345 RAMACHANDRAN 8/01/2013 18:10 8/01/2013 20:20 12345 RAMACHANDRAN 8/01/2013 20:40 8/01/2013 22:00 12346 RAVI 8/03/2013 12:30 8/03/2013 14:20 12346 RAVI 8/03/2013 18:10 8/03/2013 20:20 Emp Id Name Login Logout Duration 12345 RAMACHANDRAN 7/30/2013 8:40 7/30/2013 14:20 5:40 12345 RAMACHANDRAN 8/01/2013 18:10 8/01/2013 22:00 3:50 12346 RAVI 8/03/2013 12:30 8/03/2013 20:20 7:50,Calculate duration between first login and last logout from a set of records in datatable C_sharp : C # has a ref keyword . Using ref you can pass an int to a method by reference . What goes on the stack frame when you call a method that accepts an int by reference ? public void SampleMethod ( ref int i ) { },How does the ref keyword work ( in terms of memory ) "C_sharp : I 'm seeing an await that never seems to return . Here 's the sample code : What happens is OnStart gets called , it sets status to `` Running ... '' , then calls StartProcessing . Five seconds lapse , however I never see the status get set to `` Done ! `` If I call OnStop , then the task is cancelled and I see the `` Done ! '' status.I 'm guessing I 'm creating a task as well as the task created by async/await but it 's hanging or deadlocking ? Here 's the WPF XAML code : public partial class MainWindow : Window , INotifyPropertyChanged { private string _status ; private CancellationTokenSource _cancellationTokenSource ; public MainWindow ( ) { InitializeComponent ( ) ; _status = `` Ready '' ; DataContext = this ; } public string Status { get { return _status ; } set { _status = value ; OnPropertyChanged ( nameof ( Status ) ) ; } } private void OnStart ( object sender , RoutedEventArgs e ) { Status = `` Running ... '' ; _cancellationTokenSource = new CancellationTokenSource ( ) ; StartProcessing ( ) ; } private void OnStop ( object sender , RoutedEventArgs e ) { _cancellationTokenSource.Cancel ( ) ; } private async void StartProcessing ( ) { try { await new Task ( ( ) = > { Thread.Sleep ( 5000 ) ; } , _cancellationTokenSource.Token ) ; } catch ( TaskCanceledException e ) { Debug.WriteLine ( $ '' Expected : { e.Message } '' ) ; } Status = `` Done ! `` ; } public event PropertyChangedEventHandler PropertyChanged ; protected virtual void OnPropertyChanged ( string propertyName ) { PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } < Window x : Class= '' CancellationSample.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' Title= '' Cancellation Test '' Height= '' 350 '' Width= '' 525 '' > < DockPanel LastChildFill= '' True '' > < StackPanel DockPanel.Dock= '' Top '' > < Button Width= '' 70 '' Margin= '' 5 '' Click= '' OnStart '' > Start < /Button > < Button Width= '' 70 '' Margin= '' 5 '' Click= '' OnStop '' > Stop < /Button > < /StackPanel > < StatusBar DockPanel.Dock= '' Bottom '' > < StatusBarItem > < TextBlock Text= '' { Binding Status } '' / > < /StatusBarItem > < /StatusBar > < Grid > < /Grid > < /DockPanel > < /Window >",Why does await never return ? "C_sharp : Are enum types stored as ints in C # ? Will the enum below be represented as 0 , 1 , 2 ? If not , what 's the lightest way to define an enum ? public enum ColumnType { INT , STRING , OBJECT }",Are enum types stored as ints in C # ? "C_sharp : Consider the following network security setup : I have seen the above network setup at many client premises . The IT infrastructure team does n't allow web server in DMZ to establish direct connection to SQL Server hosted in internal network over port 1433 . Irony is I 've seen web.config lying around on web server with plain text DB passwords which they 're OK with.Usually I 've seen and worked on solutions where a WCF is hosted on the `` App '' server ( as it can be used on HTTP ports ) as shown in the diagram . WCF becomes the only way for web frontend to interact with DB . One `` benefit '' of using WCF is that it returns strongly typed objects which are easy to consume from the ASP.NET MVC frontend.Questions : WCF is used because it allows data transfer on 80 or 443 and returns strongly typed objects . Is it a good choice ? Should ASP.NET Web API be used instead ? If so , how to achieve strong typing with complex objects graphs ? Are JSON.net and inbuilt serializers sufficient for the job ? Is there a better solution ? Please note that we can not use ASP.NET Core at present.Since this is a recurring problem , I 'd really like to hear from community if there is better solution than using WCF . Users Internet | ====Firewall==== Port 80 , 443 only | Web Server DMZ - ASP.NET MVC + Web API | ====Firewall==== Port 80 , 443 only | `` App '' Server WCF or ASP.NET Web API ? ? | Database Internal network",How to design tiers of ASP.NET MVC web application if it is to be hosted in DMZ with no direct access to database ( tcp port 1433 blocked by firewall ) ? "C_sharp : I have an outlook add-in developed with VSTO 2010 that I want to write some event logging . While debugging I can get this to work by simply doing the following : The problem is the release version the add-in does n't have admin rights to read the log . I found some articles that talked about creating the EventLog source during installation , but I 'm using ClickOnce and it does n't seem there is a way to do that . Also , someone talked about creating a separate DLL and then call InstallUtil on that DLL to create the source . This does n't work for me either since this still requires admin rights . Is it possible to have the add-in run using Outlook 's security level ? I see Outlook 's messages in the event log so it must have enough rights to do so . if ( ! EventLog.SourceExists ( ADDIN_FRIENDLY_NAME ) ) { EventLog.CreateEventSource ( ADDIN_FRIENDLY_NAME , null ) ; } EventLog.WriteEntry ( ADDIN_FRIENDLY_NAME , message , EventLogEntryType.Warning ) ;",Can an Outlook addin write to the system event log ? "C_sharp : Given a class like this : Is it possible using reflection to get the optional parameter 's default values ? public abstract class SomeClass { private string _name ; private int _someInt ; private int _anotherInt ; public SomeClass ( string name , int someInt = 10 , int anotherInt = 20 ) { _name = name ; _someInt = someInt ; _anotherInt = anotherInt ; } }",Is it possible to get the optional parameter values from a constructor using reflection ? "C_sharp : I need a mock a method present in a base class when an Action method in the Controller class invoke it.Here is my Controller class below , the action method Index ( ) calls the base method GetNameNodeStatus ( ) . Now how can I mock the GetNameNodeStatus ( ) present in the base class when the action method Index calls it using the Nsubstitute mocking frameworks.Here is my base class ClustermonitoringAnd here is my Test class using Cluster.Manager.Helper ; using Cluster.Manager.Messages ; using System ; using System.Collections.Generic ; using System.Globalization ; using System.IO ; using System.Linq ; using System.Net ; using System.Web ; using System.Web.Mvc ; namespace Cluster.Manager { public class HomeController : Controller { // GET : Home public ActionResult Index ( ) { ClusterMonitoring monitoring = new ClusterMonitoring ( ) ; string getStatus = monitoring.GetNameNodeStatus ( `` '' , new Credential ( ) ) ; return View ( ) ; } } } namespace Cluster.Manager.Helper { public class ClusterMonitoring { public virtual string GetNameNodeStatus ( string hostName , Credential credential ) { return `` Method Not Implemented '' ; } } } namespace NSubstituteControllerSupport { [ TestFixture ] public class UnitTest1 { [ Test ] public void ValidateNameNodeStatus ( ) { var validation = Substitute.ForPartsOf < ClusterMonitoring > ( ) ; validation.When ( actionMethod = > actionMethod.GetNameNodeStatus ( Arg.Any < string > ( ) , Arg.Any < Credential > ( ) ) ) .DoNotCallBase ( ) ; validation.GetNameNodeStatus ( `` ipaddress '' , new Credential ( ) ) .Returns ( `` active '' ) ; var controllers = Substitute.For < HomeController > ( ) ; controllers.Index ( ) ; } } }",How do I mock a base method from the Controller class using the NSubstitue framework C_sharp : I have a List in the controllerAnd then in the View I am trying to doAnd it is giving me the error : 'System.Collections.Generic.List ' does not contain a definition for 'First ' If I do @ ViewBag.linkList [ 0 ] It works fine.I already put @ using System.Linq in the view . Am I missing something ? Does Linq works inside the view ? List < string > myList = new List < string > ( ) ; myList.Add ( aString ) ; ViewBag.linkList = myList ; @ ViewBag.linkList.First ( ),Linq does n't work in MVC View "C_sharp : Say I have the following class : Then elsewhere , I callThe //Some more code wo n't be called until _someTask.SetResult ( .. ) is called . The calling-context is waiting around in memory somewhere.However , let 's say SetResult ( .. ) is never called , and someClassInstance stops being referenced and is garbage collected . Does this create a memory leak ? Or does .Net auto-magically know the calling-context needs to be disposed ? class SomeClass { private TaskCompletionSource < string > _someTask ; public Task < string > WaitForThing ( ) { _someTask = new TaskCompletionSource < string > ( ) ; return _someTask.Task ; } //Other code which calls _someTask.SetResult ( .. ) ; } //Some code..await someClassInstance.WaitForThing ( ) ; //Some more code",What happens to Tasks that are never completed ? Are they properly disposed ? "C_sharp : I have come across a class which is non-static , but all the methods and variables are static . Eg : All the variables are static across all instances , so there is no point having separate instances of the class.Is there any reason to create a class such as this ? public class Class1 { private static string String1 = `` one '' ; private static string String2 = `` two '' ; public static void PrintStrings ( string str1 , string str2 ) { ...",Why have all static methods/variables in a non-static class ? "C_sharp : i have some trouble configuring the `` Type Members Layout '' of Resharper 7.1.3 . I started using the template for using with regions and tried to customized it for my needs.P L E A S E : No discussion about `` not using regions , etc . ... '' My first problem is , that he is currently creating one region per field declaration in code , but of course i want to have ONE region with `` Static Fields and Constants '' and ONE region with `` Fields and Constants '' .The second problem is that he does not create a single region for my `` Constructors '' . It seems that he just accepts the first two `` Patterns '' in the configuration but ignores the others. ? ! See here the multiple Regions Problem : My Type Members Layout looks like this : Would be cool , if someone could give me the hint ; ) cheers , Chris < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < ! -- I . OverallI.1 Each pattern can have < Match > ... . < /Match > element . For the given type declaration , the pattern with the match , evaluated to 'true ' with the largest weight , will be used I.2 Each pattern consists of the sequence of < Entry > ... < /Entry > elements . Type member declarations are distributed between entriesI.3 If pattern has RemoveAllRegions= '' true '' attribute , then all regions will be cleared prior to reordering . Otherwise , only auto-generated regions will be clearedI.4 The contents of each entry is sorted by given keys ( First key is primary , next key is secondary , etc ) . Then the declarations are grouped and en-regioned by given propertyII . Available match operandsEach operand may have Weight= '' ... '' attribute . This weight will be added to the match weight if the operand is evaluated to 'true'.The default weight is 1II.1 Boolean functions : II.1.1 < And > ... . < /And > II.1.2 < Or > ... . < /Or > II.1.3 < Not > ... . < /Not > II.2 OperandsII.2.1 < Kind Is= '' ... '' / > . Kinds are : class , struct , interface , enum , delegate , type , constructor , destructor , property , indexer , method , operator , field , constant , event , memberII.2.2 < Name Is= '' ... '' [ IgnoreCase= '' true/false '' ] / > . The 'Is ' attribute contains regular expressionII.2.3 < HasAttribute CLRName= '' ... '' [ Inherit= '' true/false '' ] / > . The 'CLRName ' attribute contains regular expressionII.2.4 < Access Is= '' ... '' / > . The 'Is ' values are : public , protected , internal , protected internal , privateII.2.5 < Static/ > II.2.6 < Abstract/ > II.2.7 < Virtual/ > II.2.8 < Override/ > II.2.9 < Sealed/ > II.2.10 < Readonly/ > II.2.11 < ImplementsInterface CLRName= '' ... '' / > . The 'CLRName ' attribute contains regular expressionII.2.12 < HandlesEvent / > -- > < Patterns xmlns= '' urn : shemas-jetbrains-com : member-reordering-patterns '' > < ! -- Do not reorder COM interfaces and structs marked by StructLayout attribute -- > < Pattern > < Match > < Or Weight= '' 100 '' > < And > < Kind Is= '' interface '' / > < Or > < HasAttribute CLRName= '' System.Runtime.InteropServices.InterfaceTypeAttribute '' / > < HasAttribute CLRName= '' System.Runtime.InteropServices.ComImport '' / > < /Or > < /And > < HasAttribute CLRName= '' System.Runtime.InteropServices.StructLayoutAttribute '' / > < /Or > < /Match > < /Pattern > < ! -- Special formatting of NUnit test fixture -- > < Pattern RemoveAllRegions= '' true '' > < Match > < And Weight= '' 100 '' > < Kind Is= '' class '' / > < HasAttribute CLRName= '' NUnit.Framework.TestFixtureAttribute '' Inherit= '' true '' / > < /And > < /Match > < ! -- Setup/Teardow -- > < Entry > < Match > < And > < Kind Is= '' method '' / > < Or > < HasAttribute CLRName= '' NUnit.Framework.SetUpAttribute '' Inherit= '' true '' / > < HasAttribute CLRName= '' NUnit.Framework.TearDownAttribute '' Inherit= '' true '' / > < HasAttribute CLRName= '' NUnit.Framework.FixtureSetUpAttribute '' Inherit= '' true '' / > < HasAttribute CLRName= '' NUnit.Framework.FixtureTearDownAttribute '' Inherit= '' true '' / > < /Or > < /And > < /Match > < Group Region= '' Setup/Teardown '' / > < /Entry > < ! -- All other members -- > < Entry/ > < ! -- Test methods -- > < Entry > < Match > < And Weight= '' 100 '' > < Kind Is= '' method '' / > < HasAttribute CLRName= '' NUnit.Framework.TestAttribute '' Inherit= '' false '' / > < /And > < /Match > < Sort > < Name/ > < /Sort > < /Entry > < /Pattern > < Pattern RemoveAllRegions= '' true '' > < ! -- static fields and constants -- > < Entry > < Match > < Or > < And > < Kind Is= '' constant '' / > < Static/ > < /And > < And > < Kind Is= '' field '' / > < Static/ > < /And > < /Or > < /Match > < Sort > < Readonly/ > < Name/ > < /Sort > < Group > < Name Region= '' Static Fields and Constants '' / > < /Group > < /Entry > < ! -- fields and constants -- > < Entry > < Match > < Or > < And > < Kind Is= '' constant '' / > < Not > < Static/ > < /Not > < /And > < And > < Kind Is= '' field '' / > < Not > < Static/ > < /Not > < /And > < /Or > < /Match > < Sort > < Readonly/ > < Name/ > < /Sort > < Group > < Name Region= '' Fields and Constants '' / > < /Group > < /Entry > < /Pattern > < ! -- Default pattern -- > < Pattern RemoveAllRegions= '' false '' > < ! -- public delegate -- > < Entry > < Match > < And Weight= '' 100 '' > < Access Is= '' public '' / > < Kind Is= '' delegate '' / > < /And > < /Match > < Sort > < Name/ > < /Sort > < Group Region= '' Delegates '' / > < /Entry > < ! -- public enum -- > < Entry > < Match > < And Weight= '' 100 '' > < Access Is= '' public '' / > < Kind Is= '' enum '' / > < /And > < /Match > < Sort > < Name/ > < /Sort > < Group > < Name Region= '' $ { Name } enum '' / > < /Group > < /Entry > < ! -- Constructors . Place static one first -- > < Entry > < Match > < Kind Is= '' constructor '' / > < /Match > < Sort > < Static/ > < /Sort > < Group > < Name Region= '' Constructor / Destructor '' / > < /Group > < /Entry > < ! -- properties , indexers -- > < Entry > < Match > < Or > < Kind Is= '' property '' / > < Kind Is= '' indexer '' / > < /Or > < /Match > < Group Region= '' Properties '' / > < /Entry > < ! -- interface implementations -- > < Entry > < Match > < And Weight= '' 100 '' > < Kind Is= '' member '' / > < ImplementsInterface/ > < /And > < /Match > < Sort > < ImplementsInterface Immediate= '' true '' / > < /Sort > < Group > < ImplementsInterface Immediate= '' true '' Region= '' $ { ImplementsInterface } Members '' / > < /Group > < /Entry > < ! -- all other members -- > < Entry/ > < ! -- nested types -- > < Entry > < Match > < Kind Is= '' type '' / > < /Match > < Sort > < Name/ > < /Sort > < Group > < Name Region= '' Nested type : $ { Name } '' / > < /Group > < /Entry > < /Pattern > < /Patterns >",Avoid Resharper to add a region per Declaration "C_sharp : I need to loop over a List < dynamic > objects.The list 's objects all have values , but for some reason , I am not able to access any of the dynamic object fields . Below is a screenshot of my debug window : There you can see the object contains fields ( such Alias , Id , Name , etc ) .I tried both casting it to a IDictionary < string , object > and ExpandoObject , to no avail . I did not face such a thing before : failing to access existing fields in a dynamic object when they exist.What is wrong here ? The code is throwing a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException with a message stating { `` 'object ' does not contain a definition for 'Name ' '' } .The list was created adding anonymously-typed objects , like this : where fields is an ICollection < Field > , a strongly-typed collection . return new List < dynamic > ( fields.Select ( field = > new { Id = field.Id , Alias = field.Alias , Name = field.Name , Type = field.Type , Value = field.Value , SortOrder = field.SortOrder } ) ) ;",List < dynamic > elements have fields but I can not access them . Why ? "C_sharp : I am making an article reading app ( similar to the Bing News app ) and I 'm using a FlipView to go between the articles . The FlipView has its ItemsSource databound to an ObservableCollection < T > that holds the content of the article.I only want to keep 3 articles in the ObservableCollection < T > for memory and performance reasons , so I subscribe to the flipView_SelectionChanged event and remove the item at Length - 1 for going back ( to the right ) and item at 0 for going forward ( to the left ) The problem that I 'm having is that when I remove the item at 0 after flipping using the touch gesture , the animation plays a second time.How do I prevent the transition animation from playing a second time ? Here is an example . Create a new Blank Store App , and add the following : and this in the .xaml public sealed partial class MainPage : Page { public ObservableCollection < int > Items { get ; set ; } private Random _random = new Random ( 123 ) ; public MainPage ( ) { this.InitializeComponent ( ) ; Items = new ObservableCollection < int > ( ) ; Items.Add ( 1 ) ; Items.Add ( 1 ) ; Items.Add ( 1 ) ; flipview.ItemsSource = Items ; } private void flipview_SelectionChanged ( object sender , SelectionChangedEventArgs e ) { if ( this.flipview.SelectedIndex == 0 ) { Items.Insert ( 0 , 1 ) ; Items.RemoveAt ( Items.Count - 1 ) ; } else if ( this.flipview.SelectedIndex == this.flipview.Items.Count - 1 ) { Items.Add ( 1 ) ; Items.RemoveAt ( 0 ) ; } } } < Page.Resources > < DataTemplate x : Key= '' DataTemplate '' > < Grid > < Grid.Background > < LinearGradientBrush EndPoint= '' 1,0.5 '' StartPoint= '' 0,0.5 '' > < GradientStop Color= '' Black '' / > < GradientStop Color= '' White '' Offset= '' 1 '' / > < /LinearGradientBrush > < /Grid.Background > < /Grid > < /DataTemplate > < /Page.Resources > < Grid Background= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' > < FlipView x : Name= '' flipview '' SelectionChanged= '' flipview_SelectionChanged '' ItemsSource= '' { Binding } '' ItemTemplate= '' { StaticResource DataTemplate } '' / > < /Grid >",Databound Flipview remove ViewModel.ItemAt ( 0 ) causes flip transition C_sharp : Why it is not possible to use IList in interface definition and then implement this property using List ? Am I missing something here or just C # compiler does n't allow this ? compiler says Error 82 'Category ' does not implement interface member 'ICategory.Products ' . 'Category.Products ' can not implement 'ICategory.Products ' because it does not have the matching return type of 'System.Collections.Generic.IList ' public interface ICategory { IList < Product > Products { get ; } } public class Category : ICategory { public List < Product > Products { get { new List < Product > ( ) ; } } },Why it is not possible to use IList < T > in interface definition and List < T > in inplementation ? "C_sharp : I have a very small website running on Azure in the shared hosting configuration . I have a bunch of networking code on it that involves opening sockets , all of which works successfully.I have written some code that sends a ping and I get a PingException being thrown , with the inner exception being a Win32Exception with the descriptionI am making a guess that it 's because I 'm trying to send an ICMP request , but any guidance would be appreciated , and particularly a work around . There are no more endpoints available from the endpoint mapper",`` There are no more endpoints available from the Endpoint Mapper '' exception when pinging "C_sharp : I was playing with attributes and reflection when I found a strange case . The following code gave me an exception at runtime when I try to get constructor arguments of custom attributes.The problem seems to be the parameters passed to the Test attribute constructor . If one of them is null , ConstructorArguments throw an exception . The exception is ArgumentException with name as exception message . Here is the stack trace from ConstructorArguments call : If I set a non null value to each parameters there is no exception . It seems to only happen with enum array . If I add another parameter such as string and set them to null , there is no problem.A solution could be to always pass a value such as an empty array but here I would like to keep the ability to pass null value because it has a special meaning in my case . using System ; using System.Reflection ; class Program { [ Test ( new [ ] { Test.Foo } , null ) ] static void Main ( string [ ] args ) { var type = typeof ( Program ) ; var method = type.GetMethod ( `` Main '' , BindingFlags.Static | BindingFlags.NonPublic ) ; var attribute = method.GetCustomAttributesData ( ) [ 0 ] .ConstructorArguments ; Console.ReadKey ( ) ; } } public enum Test { Foo , Bar } [ AttributeUsage ( AttributeTargets.Method , AllowMultiple = true ) ] public class TestAttribute : Attribute { public TestAttribute ( Test [ ] valuesOne , Test [ ] valuesTwo ) { } } System.RuntimeTypeHandle.GetTypeByNameUsingCARules ( String name , RuntimeModule scope ) System.Reflection.CustomAttributeTypedArgument.ResolveType ( RuntimeModule scope , String typeName ) System.Reflection.CustomAttributeTypedArgument..ctor ( RuntimeModule scope , CustomAttributeEncodedArgument encodedArg ) System.Reflection.CustomAttributeData.get_ConstructorArguments ( )",Exception when getting attribute constructor arguments with multiple enum arrays "C_sharp : I have a dictionary with a Person and a Count value : It has the following values : I want to alternate each person and decrement the value by 1 each time it goes through the loop . I 'm running into a real mind block on this oneWhat is the best way to get Sally and decrement by 1 and then go to Beth and decrement by 1 and then go to Mary and decrement by 1 and then go back to Sally ... So on and so forth.Just add further clarification I want to loop through this and use the owner.Key value and pass that to another method . So I need to be able to loop through this dictionary 1 at a time.Update : There are a few issues with my question . One issue was the decrementing the dictionary while in a loop . But my main question was how to iterate through each item [ Sally - > Beth - > Mary - > Sally ) until each persons value goes to 0 - That part is still the question at large . Dictionary < string , int > PersonDictionary = new Dictionary < string , int > ( ) ; Sally , 6Beth , 5Mary , 5",Loop through Dictionary "C_sharp : I expose the following class in assembly A : I expose this derived class in a separate assembly ( B ) : Using the code as shown above , the compiler complains on this line : The type 'T ' can not be used as type parameter 'T ' in the generic type or method A.ReferenceService ( ) . There is no boxing conversion or type parameter conversion from 'T ' to 'System.ServiceProcess.ServiceBase'.Naturally , I tried replicating the constraints in assembly B : But the compiler now warns on the line above ... Constraints for override and explicit interface implementation methods are inherited from the base method , so they can not be specified directly.This answer indicates that my solution should have worked . I want to avoid using reflection to expose this method publicly . It should be so simple ! Thanks in advance to anyone who can spot what mistake I am making . public abstract class ServiceDependencyHost { protected virtual T ReferenceService < T > ( ) where T : ServiceBase { // Virtual implementation here ... } } public sealed class ProcessServiceOperation : ServiceDependencyHost { public override T ReferenceService < T > ( ) { // Override implementation here ... return base.ReferenceService < T > ( ) ; } } return base.ReferenceService < T > ( ) ; public override T ReferenceService < T > ( ) where T : ServiceBase",Compilation error when overriding a generic type method C_sharp : It seems like the execution context is not kept until Dispose is called on elements resolved in the controller scope . This is probably due to the fact that asp.net core has to jump between native and managed code and resets the execution context at each jump . Seems like the correct context is not restored any more before the scope is disposed.The following demonstrates the issue - simply put this in the default asp.net core sample project and register TestRepo as a transient dependency . When calling GET api/values/ we set the value for the current task to 5 in a static AsyncLocal at the start of the call . That value flows as expected through awaits without any problem . But when the controller and its dependencies are disposed after the call the AsyncLocal context is already reset.Is this intentional ? And if yes is there any workaround around this problem ? [ Route ( `` api/ [ controller ] '' ) ] public class ValuesController : Controller { private readonly TestRepo _testRepo ; public ValuesController ( TestRepo testRepo ) = > _testRepo = testRepo ; [ HttpGet ( ) ] public async Task < IActionResult > Get ( ) { _testRepo.SetValue ( 5 ) ; await Task.Delay ( 100 ) ; var val = _testRepo.GetValue ( ) ; // val here has correctly 5. return Ok ( ) ; } } public class TestRepo : IDisposable { private static readonly AsyncLocal < int ? > _asyncLocal = new AsyncLocal < int ? > ( ) ; public int ? GetValue ( ) = > _asyncLocal.Value ; public void SetValue ( int x ) = > _asyncLocal.Value = x ; public void Foo ( ) = > SetValue ( 5 ) ; public void Dispose ( ) { if ( GetValue ( ) == null ) { throw new InvalidOperationException ( ) ; //GetValue ( ) should be 5 here : ( } } },AsyncLocal with ASP.NET Core Controller/ServiceProviderScope "C_sharp : Recently I played around with the new for json auto feature of the Azure SQL database.When I select a lot of records for example with this query : and then do a select with the C # SqlDataReader : I get a lot of chunks of data.Why do we have this limitation ? Why do n't we get everything in one big chunk ? When I read a nvarchar ( max ) column , I will get everything in one chunk.Thanks for an explanation Select Wiki.WikiId , Wiki.WikiText , Wiki.Title , Wiki.CreatedOn , Tags.TagId , Tags.TagText , Tags.CreatedOnFrom WikiLeft Join ( WikiTagInner Join Tag as Tags on WikiTag.TagId = Tags.TagId ) on Wiki.WikiId = WikiTag.WikiIdFor Json Auto var connectionString = `` '' ; // connection stringvar sql = `` '' ; // query from abovevar chunks = new List < string > ( ) ; using ( var connection = new SqlConnection ( connectionString ) ) using ( var command = connection.CreateCommand ( ) ) { command.CommandText = sql ; connection.Open ( ) ; var reader = command.ExecuteReader ( ) ; while ( reader.Read ( ) ) { chunks.Add ( reader.GetString ( 0 ) ) ; // Reads in chunks of ~2K Bytes } } var json = string.Concat ( chunks ) ;",SqlDataReader and SQL Server 2016 FOR JSON splits json in chunks of 2k bytes "C_sharp : Consider the following code : With Visual Studio 2010 ( C # 4 , .NET 4.0 ) , I get the following warning : warning CS0458 : The result of the expression is always 'null ' of type 'bool ? 'This is incorrect ; the result is always false ( of type bool ) : Now , the struct DateTime overloads the > ( greater than ) operator . Any non-nullable struct ( like DateTime ) is implicitly convertible to the corresponding Nullable < > type . The above expression is exactly equivalent towhich also generates the same wrong warning . Here the > operator is the lifted operator . This works by returning false if HasValue of any of its two operands is false . Otherwise , the lifted operator would proceed to unwrap the two operands to the underlying struct , and then call the overload of > defined by that struct ( but this is not necessary in this case where one operand does not HasValue ) .Can you reproduce this bug , and is this bug well-known ? Have I misunderstood something ? This is the same for all struct types ( not simple types like int , and not enum types ) which overload the operator in question . ( Now if we use == instead of > , everything ought to be entirely similar ( because DateTime also overloads the == operator ) . But it 's not similar . If I sayI get no warning ☹ Sometimes you see people accidentally check a variable or parameter for null , not realizing that the type of their variable is a struct ( which overloads == and which is not a simple type like int ) . It would be better if they got a warning . ) Update : With the C # 6.0 compiler ( based on Roslyn ) of Visual Studio 2015 , the incorrect message with isGreater above is changed into a CS0464 with a correct and helpful warning message . Also , the lack of warning with isEqual above is fixed in VS2015 's compiler , but only if you compile with /features : strict . DateTime t = DateTime.Today ; bool isGreater = t > null ; bool isGreater = ( DateTime ? ) t > ( DateTime ? ) null ; DateTime t = DateTime.Today ; bool isEqual = t == null ;",Wrong compiler warning when comparing struct to null "C_sharp : Consider the following Linq to Entities query : If you 're anything like me , your toes curl at the repetition of the product selection logic . This pattern is repeated in another place as well . I first attempted to replace it by an extension method on IEnumerable , which of course does not work : Linq to Entities needs an Expression to parse and translate.So I created this method : The following selection now works perfectly fine : However , this wo n't compile , because IGrouping does not contain an override of Where that accepts an Expression : Casting g to IQueryable compiles , but then yields a `` Internal .NET Framework Data Provider error 1025. '' . Is there any way to wrap this logic in its own method ? return ( from lead in db.Leads join postcodeEnProvincie in postcodeEnProvincies on lead.Postcode equals postcodeEnProvincie.Postcode where ( lead.CreationDate > = range.StartDate ) & & ( lead.CreationDate < = range.EndDate ) group lead by postcodeEnProvincie.Provincie into g select new Web.Models.GroupedLeads ( ) { GroupName = g.Key , HotLeads = g.Count ( l = > l.Type == Data.LeadType.Hot ) , Leads = g.Count ( ) , PriorityLeads = g.Count ( l = > l.Type == Data.LeadType.Priority ) , Sales = g.Count ( l = > l.Sold ) , ProductA = g.Count ( l = > l.Producten.Any ( a = > ( ( a.Name.Equals ( `` productA '' , StringComparison.CurrentCultureIgnoreCase ) ) || ( a.Parent.Name.Equals ( `` productA '' , StringComparison.CurrentCultureIgnoreCase ) ) ) ) ) , ProductB = g.Count ( l = > l.Producten.Any ( a = > ( ( a.Name.Equals ( `` productB '' , StringComparison.CurrentCultureIgnoreCase ) ) || ( a.Parent.Name.Equals ( `` productB '' , StringComparison.CurrentCultureIgnoreCase ) ) ) ) ) , ProductC = g.Count ( l = > l.Producten.Any ( a = > ( ( a.Name.Equals ( `` productC '' , StringComparison.CurrentCultureIgnoreCase ) ) || ( a.Parent.Name.Equals ( `` productC '' , StringComparison.CurrentCultureIgnoreCase ) ) ) ) ) , ProductC = g.Count ( l = > l.Producten.Any ( a = > ( ( a.Name.Equals ( `` productD '' , StringComparison.CurrentCultureIgnoreCase ) ) || ( a.Parent.Name.Equals ( `` productD '' , StringComparison.CurrentCultureIgnoreCase ) ) ) ) ) } ) .ToList ( ) ; public static System.Linq.Expressions.Expression < Func < Data.Lead , bool > > ContainingProductEx ( string productName ) { var ignoreCase = StringComparison.CurrentCultureIgnoreCase ; return ( Data.Lead lead ) = > lead.Producten.Any ( ( product = > product.Name.Equals ( productName , ignoreCase ) || product.Parent.Name.Equals ( productName , ignoreCase ) ) ) ; } var test = db.Leads.Where ( Extensions.ContainingProductEx ( `` productA '' ) ) .ToList ( ) ; return ( from lead in db.Leads join postcodeEnProvincie in postcodeEnProvincies on lead.Postcode equals postcodeEnProvincie.Postcode where ( lead.CreationDate > = range.StartDate ) & & ( lead.CreationDate < = range.EndDate ) group lead by postcodeEnProvincie.Provincie into g select new Web.Models.GroupedLeads ( ) { GroupName = g.Key , HotLeads = g .Where ( l = > l.Type == Data.LeadType.Hot ) .Count ( ) , Leads = g.Count ( ) , PriorityLeads = g .Where ( l = > l.Type == Data.LeadType.Priority ) .Count ( ) , Sales = g .Where ( l = > l.Sold ) .Count ( ) , ProductA = g .Where ( Extensions.ContainingProductEx ( `` productA '' ) ) .Count ( ) , ProductB = g .Where ( Extensions.ContainingProductEx ( `` productB '' ) ) .Count ( ) , ProductC = g .Where ( Extensions.ContainingProductEx ( `` productC '' ) ) .Count ( ) , ProductD = g .Where ( Extensions.ContainingProductEx ( `` productD '' ) ) .Count ( ) } ) .ToList ( ) ;","Using Where ( Expression < Func < T , bool > > ) in IGrouping" "C_sharp : I just wanted to know why sealed classes are not allowed to be generic type constraints ? Let 's suppose i have a simple code snippet in c # as bellowWhen i am instantiating the Derivedclass i am getting 'Base ' is not a valid constraint . A type used as a constraint must be an interface , a non-sealed class or a type parameter . public sealed class Base { public Base ( ) { } } public class Derived < T > where T : Base { public Derived ( ) { } }",Why sealed classes are not allowed to be generic type constraints ? "C_sharp : The background to this question is based on a virtual file system I 'm developing . The concept I 'm using is virutal path providers for different types of storage type i.e local file system , dropbox and amazon s3 . My base class for a virtual file looks like this : The implementation of the second Open method is what my question is all about . If we look at my implementation for the local file system i.e saving a file on disk it looks like this : If I would like to save a file on the local file system this would look something like this : What I want is that if I switch to my amazon s3 virtual path provider I want this code to work directly without any changes so to sum things up , how can I solve this using the amazon s3 sdk and how should i implement my Open ( FileMode fileMode ) method in my amazon s3 virtual path provider ? public abstract class CommonVirtualFile : VirtualFile { public virtual string Url { get { throw new NotImplementedException ( ) ; } } public virtual string LocalPath { get { throw new NotImplementedException ( ) ; } } public override Stream Open ( ) { throw new NotImplementedException ( ) ; } public virtual Stream Open ( FileMode fileMode ) { throw new NotImplementedException ( ) ; } protected CommonVirtualFile ( string virtualPath ) : base ( virtualPath ) { } } public override Stream Open ( FileMode fileMode ) { return new FileStream ( `` The_Path_To_The_File_On_Disk '' ) , fileMode ) ; } const string virtualPath = `` /assets/newFile.txt '' ; var file = HostingEnvironment.VirtualPathProvider.GetFile ( virtualPath ) as CommonVirtualFile ; if ( file == null ) { var virtualDir = VirtualPathUtility.GetDirectory ( virtualPath ) ; var directory = HostingEnvironment.VirtualPathProvider.GetDirectory ( virtualDir ) as CommonVirtualDirectory ; file = directory.CreateFile ( VirtualPathUtility.GetFileName ( virtualPath ) ) ; } byte [ ] fileContent ; using ( var fileStream = new FileStream ( @ '' c : \temp\fileToCopy.txt '' , FileMode.Open , FileAccess.Read ) ) { fileContent = new byte [ fileStream.Length ] ; fileStream.Read ( fileContent , 0 , fileContent.Length ) ; } // write the content to the local file system using ( Stream stream = file.Open ( FileMode.Create ) ) { stream.Write ( fileContent , 0 , fileContent.Length ) ; }",Upload file using a virtual path provider and Amazon S3 SDK "C_sharp : I am calling a web api service that only fails the first time I recycle the application pool . After that all calls work fine.The process is like this..Call Service -- > return OKCall Service -- > return OKCall Service -- > return OKGo to iis and recycle app pool ( I wait 10 secs ) Call Service -- > An internal server error occurred . Please try again later.Call Service -- > return OKCall Service -- > return OKCall Service -- > return OK ... Go to iis and recycle app pool ( I wait 10 secs ) Call Service -- > An internal server error occurred . Please try again later.Call Service -- > return OKCall Service -- > return OKCall Service -- > return OK ... The client is a console application framework 4.0 using this method : And the webapi is framework 4.5 : Unity config : WebApi application pool is framework 4 integrated mode , running as Network Service . ProcessModel Idle Timeout ( minutes 0 ) The only configuration changed from default . IIS 7.5 public static object Send ( string webAddr , object param ) { HttpUtil.IgnoreBadCertificates ( ) ; HttpWebRequest request = null ; object result = null ; request = ( HttpWebRequest ) WebRequest.Create ( webAddr ) ; request.ContentType = `` application/json ; charset=utf-8 '' ; request.Method = `` POST '' ; request.Accept = `` application/json '' ; String u = GetString ( a1 ) ; String p = GetString ( a1 ) + GetString ( a2 ) ; String encoded = System.Convert.ToBase64String ( System.Text.Encoding.UTF8.GetBytes ( u + `` : '' + p ) ) ; request.Headers.Add ( `` Authorization '' , `` Basic `` + encoded ) ; using ( var streamWriter = new StreamWriter ( request.GetRequestStream ( ) ) ) { var myJsonString = Newtonsoft.Json.JsonConvert.SerializeObject ( param ) ; streamWriter.Write ( myJsonString ) ; streamWriter.Flush ( ) ; } var response = ( HttpWebResponse ) request.GetResponse ( ) ; using ( var streamReader = new StreamReader ( response.GetResponseStream ( ) ) ) { result = streamReader.ReadToEnd ( ) ; } return result ; } public class CambiosController : BaseApiController { private ICambioService cambioService ; public CambiosController ( ICambioService cambioService ) { this.cambioService = cambioService ; } [ HttpPost ] [ Authorize ] public HttpResponseMessage Post ( [ FromBody ] CambioRequest cambioRequest ) { HttpResponseMessage response = null ; if ( cambioRequest == null ) { Exception ex = new ArgumentException ( `` cambioRequest '' ) ; return Request.CreateErrorResponse ( HttpStatusCode.BadRequest , ex ) ; } try { var result = this.cambioService.EnviarConfiguracion ( cambioRequest ) ; response = Request.CreateResponse ( HttpStatusCode.OK , result ) ; } catch ( Exception ex ) { response = Request.CreateErrorResponse ( HttpStatusCode.InternalServerError , ex ) ; } return response ; } protected override void Dispose ( bool disposing ) { if ( disposing ) { this.cambioService.Dispose ( ) ; } base.Dispose ( disposing ) ; } public static void RegisterComponents ( ) { LoggerFacility.Debug ( string.Empty , string.Empty , `` UnityConfig.RegisterComponents ( ) '' ) ; var container = new UnityContainer ( ) ; container.RegisterTypes ( AllClasses.FromAssemblies ( BuildManager.GetReferencedAssemblies ( ) .Cast < Assembly > ( ) ) .Where ( x = > x.Name ! = `` IUnitOfWork '' & & x.Name ! = `` IDbContext '' ) , WithMappings.FromMatchingInterface , WithName.Default , overwriteExistingMappings : true ) ; container.RegisterType < IUnitOfWork , UnitOfWork > ( new PerResolveLifetimeManager ( ) ) ; container.RegisterType < IDbContext , ControlConfigContext > ( new PerResolveLifetimeManager ( ) ) ; GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver ( container ) ; }",webapi call fails only when recycling application pool using unity DI "C_sharp : I have a page named `` ReportController.aspx '' whose purpose is to instantiate a report ( class ) based on query string parameters Basically , each time a new report is needed there will be this overhead of adding a case and adding a method . This switch statement could get very very long . I read that is is possible to use a Dictionary to map a Report to ? . How would this look using a Dictionary ( assuming this is a better way ) .Also , CreateReportXReport method basically passes a bunch of additional QueryString values to the report class 's constructor ( each report class has a different constructor ) . switch ( Request.QueryString [ `` Report '' ] ) { case `` ReportA '' : CreateReportAReport ( `` ReportA 's Title '' ) ; break ; case `` ReportB '' : CreateReportBReport ( `` ReportB 's Title '' ) ; break ; case `` ReportC '' : CreateReportCReport ( `` ReportC 's Title '' ) ; break ; case `` ReportD '' : CreateReportDReport ( `` ReportD 's Title '' ) ; break ; ...",Replacement for big switch ? "C_sharp : I 've come across strange behavior of pixel shader in WPF . This problem is 100 % reproducible , so I wrote small demo program . You can download source code here . The root of all evil is tiny class titled MyFrameworkElement : As you can see this framework element renders 2 lines : lower line has permanent coordinates but upper line depends on EndX dependency property . So this framework element is target for pixel shader effect . For simplicity 's sake I use grayscale shader effect found here . So I applied GrayscaleEffect to MyFrameworkElement . You can see result , it looks nice . Until I increase EndX property drastically . Small line is blurred and big line is fine ! But if I remove grayscale effect , all lines will look as they should . Can anybody explain what 's the reason of this blurring ? Or even better how can I solve this problem ? internal sealed class MyFrameworkElement : FrameworkElement { public double EndX { get { return ( double ) this.GetValue ( MyFrameworkElement.EndXProperty ) ; } set { this.SetValue ( MyFrameworkElement.EndXProperty , value ) ; } } public static readonly DependencyProperty EndXProperty = DependencyProperty.Register ( `` EndX '' , typeof ( double ) , typeof ( MyFrameworkElement ) , new FrameworkPropertyMetadata ( 0d , FrameworkPropertyMetadataOptions.AffectsRender ) ) ; protected override void OnRender ( DrawingContext dc ) { dc.DrawLine ( new Pen ( Brushes.Red , 2 ) , new Point ( 0 , 0 ) , new Point ( this.EndX , 100 ) ) ; dc.DrawLine ( new Pen ( Brushes.Green , 3 ) , new Point ( 10 , 300 ) , new Point ( 200 , 10 ) ) ; } }",Blurred picture after applying of shader effect "C_sharp : I 'm required for a certain task to enumerate all handles in the system . The best approach I found so far is using the underdocumented NtQuerySystemInformation with the SystemHandleInformation flag for the class parameter . So far so good . However , running it in 32 bit mode on 64 bit Windows , the required structure is as follows : And for 64 bit Windows ( x64 , I did n't test Itanium , which I hope is n't different ... ) , the structure is as follows : Now , I should change the Object_Pointer to an IntPtr . I hoped for a moment I could do the same with ProcessId , there was a reference saying this was actually a HANDLE which is actually a 64-bit value . However , Reserved is always zero , so I can not merge that into an IntPtr the same way.This is probably not the only scenario where this happens . I 'm looking for a best practice way of dealing with such differences : Using a constant like # if WIN32 ( used internally in the reference source of IntPtr ) would n't work here unless I want to maintain separate binaries.I can write two different functions and two different structs , create a wrapper and use if IntPtr.Size ==4 in code . This works for external functions , but does n't work well with types.I can overload GetType but I 'm not sure where that leads ( might help with Marshalling ? ) .Anything else ? None of these seem ideal , but so far , the only foolproof way seems to be to lard my system with if IsWin64 ( ) statements . I 'd love to hear better approaches than mine . // 32-bit version [ StructLayout ( LayoutKind.Sequential , Pack=1 ) ] public struct SYSTEM_HANDLE_INFORMATION { public uint ProcessID ; public byte ObjectTypeNumber ; public byte Flags ; public ushort Handle ; public uint Object_Pointer ; public UInt32 GrantedAccess ; } // 64-bit version [ StructLayout ( LayoutKind.Sequential , Pack=1 ) ] public struct SYSTEM_HANDLE_INFORMATION { public int Reserved ; // unknown , no documentation found public uint ProcessID ; public byte ObjectTypeNumber ; public byte Flags ; public ushort Handle ; public long Object_Pointer ; public UInt32 GrantedAccess ; }",Preferred approach for conditional compilation for 32-bit versus 64-bit versions of types C_sharp : I have a partial class in a dbml file.Clearly I ca n't put a decorator on it because this is a generated file and you should n't make change in it yourself.So I created another partial class ; The above does n't work but I need something like that so I can validate the email address on the model . public partial class Comment string email public partial class Comment [ IsEmailAddress ] string email,Add property decorator to partial class "C_sharp : My awareness of Generics is that they can help me streamline my pooling , but ca n't figure out how.My pooling system is minimalistic , but messy . And now getting unwieldy and messy , and MESSY . It does n't scale nicely ... My FXDistribrutor.cs class is a component attached to an object in the initial scene , designed to permanently exist throughout all scenes of the game . It has a static reference to itself , so that I can call into it from anywhere easily . More on that contrivance at the end . I 'm not even sure if that 's the 'right ' way to do this . But it works nicely.FXDistributor has a public slot for each type of FX Unit it is able to distribute , and an array for the pool of this type of FX , and an index for the array and a size of the pool.Here are two examples : In the Unity Start call , I fill the pools of each FX Unit : And in the body of the class I have a bunch of methods for each FX type , to provide them to wherever they 're needed : So when I want one of these FX , and to use it , I call like this , from anywhere , into the static reference : How do I streamline this approach with Generics so I can easily and less messily do this sort of thing for a couple of dozen types of FX Units ? public BumperFX BmprFX ; BumperFX [ ] _poolOfBumperFX ; int _indexBumperFX , _poolSize = 10 ; public LandingFX LndngFX ; LandingFX [ ] _poolOfLndngFX ; int _indexLndngFX , _poolSizeLndngFX = 5 ; void Start ( ) { _poolOfBumperFX = new BumperFX [ _poolSize ] ; for ( var i = 0 ; i < _poolSize ; i++ ) { _poolOfBumperFX [ i ] = Instantiate ( BmprFX , transform ) ; } _poolOfLndngFX = new LandingFX [ _poolSizeLndngFX ] ; for ( var i = 0 ; i < _poolSizeLndngFX ; i++ ) { _poolOfLndngFX [ i ] = Instantiate ( LndngFX , transform ) ; } } public LandingFX GimmeLandingFX ( ) { if ( _indexLndngFX == _poolSizeLndngFX ) _indexLndngFX = 0 ; var lndngFX = _poolOfLndngFX [ _indexLndngFX ] ; _indexLndngFX++ ; return lndngFX ; } public BumperFX GimmeBumperFX ( ) { if ( _indexBumperFX == _poolSize ) _indexBumperFX = 0 ; var bumperFX = _poolOfBumperFX [ _indexBumperFX ] ; _indexBumperFX++ ; return bumperFX ; } FXDistributor.sRef.GimmeLandingFX ( ) .Bounce ( bounce.point , bounce.tangentImpulse , bounce.normalImpulse ) ;",How to create Generics Pooling System for components/scripts ? "C_sharp : I 'm lost using the authentication method that comes with MVC 5 Template.I had the need to include the CreateBy user in an entity called client , so after some research I came to this : Model : Controller Method : But I had to change almost everything in the Identity Model : From ToAnd almost 30 changes because of this.But now I have 2 DbContext : Identity Context : My Application Context : My problem now are : Do I need 2 DbContext ? Am I associating the user to the client entity correctly ? I need to create a list of all users , and aditional information , will I read the information from 2 DbContext ? Please , I need some clear guide because I am very confused right now and I really love to build great code , and I think it 's not the case . [ Table ( `` Clients '' ) ] public partial class Client { [ Key ] [ DatabaseGeneratedAttribute ( DatabaseGeneratedOption.Identity ) ] public int Id { get ; set ; } public virtual int UserCreated_Id { get ; set ; } [ ForeignKey ( `` UserCreated_Id '' ) ] public virtual ApplicationUser UserCreated { get ; set ; } } client.UserCreated_Id = User.Identity.GetUserId < int > ( ) ; public class ApplicationUser : IdentityUser public class ApplicationUser : IdentityUser < int , ApplicationUserLogin , ApplicationUserRole , ApplicationUserClaim > public class ApplicationDbContext : IdentityDbContext < ApplicationUser , ApplicationRole , int , ApplicationUserLogin , ApplicationUserRole , ApplicationUserClaim > { public ApplicationDbContext ( ) : base ( `` IPDB '' ) { } public static ApplicationDbContext Create ( ) { return new ApplicationDbContext ( ) ; } } public class MyDbContext : DbContext { public MyDbContext ( ) : base ( `` IPDB '' ) { // Tells Entity Framework that we will handle the creation of the database manually for all the projects in the solution Database.SetInitializer < MyDbContext > ( null ) ; } public DbSet < Client > Clients { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { // ANOTHER CHANGE I HAD TO MADE TO BE ABLE TO SCAFFOLDING modelBuilder.Entity < ApplicationUserLogin > ( ) .HasKey < int > ( l = > l.UserId ) ; modelBuilder.Entity < ApplicationRole > ( ) .HasKey < int > ( r = > r.Id ) ; modelBuilder.Entity < ApplicationUserRole > ( ) .HasKey ( r = > new { r.RoleId , r.UserId } ) ; } }",Correct use of Microsoft.AspNet.Identity 2.0 "C_sharp : I 'm using a single sprite sheet image as the main texture for my breakout game . The image is this : My code is a little confusing , since I 'm creating two elements from the same Texture using a Point , to represent the element size and its position on the sheet , a Vector , to represent its position on the viewport and a Rectangle that represents the element itself.My initialization is a little confusing as well , but it works as expected : And the drawing : The problem is I ca n't detect the collision properly , using this code : What am I doing wrong ? Texture2D sheet ; Point paddleSize = new Point ( 112 , 24 ) ; Point paddleSheetPosition = new Point ( 0 , 240 ) ; Vector2 paddleViewportPosition ; Rectangle paddleRectangle ; Point ballSize = new Point ( 24 , 24 ) ; Point ballSheetPosition = new Point ( 160 , 240 ) ; Vector2 ballViewportPosition ; Rectangle ballRectangle ; Vector2 ballVelocity ; paddleViewportPosition = new Vector2 ( ( GraphicsDevice.Viewport.Bounds.Width - paddleSize.X ) / 2 , GraphicsDevice.Viewport.Bounds.Height - ( paddleSize.Y * 2 ) ) ; paddleRectangle = new Rectangle ( paddleSheetPosition.X , paddleSheetPosition.Y , paddleSize.X , paddleSize.Y ) ; Random random = new Random ( ) ; ballViewportPosition = new Vector2 ( random.Next ( GraphicsDevice.Viewport.Bounds.Width ) , random.Next ( GraphicsDevice.Viewport.Bounds.Top , GraphicsDevice.Viewport.Bounds.Height / 2 ) ) ; ballRectangle = new Rectangle ( ballSheetPosition.X , ballSheetPosition.Y , ballSize.X , ballSize.Y ) ; ballVelocity = new Vector2 ( 3f , 3f ) ; spriteBatch.Draw ( sheet , paddleViewportPosition , paddleRectangle , Color.White ) ; spriteBatch.Draw ( sheet , ballViewportPosition , ballRectangle , Color.White ) ; if ( ballRectangle.Intersects ( paddleRectangle ) ) { ballVelocity.Y = -ballVelocity.Y ; }",Ca n't detect collision properly using Rectangle.Intersects ( ) "C_sharp : I have a requirement of loading assembly of different version ( I already have the assembly with same name in my application ) .I was able to load the assembly and load the method i need to invoke using reflection but when i go to invoke the method by passing my class object as argument , i got the exception that class object can not be converted to the type of argument parameter.Sample Code -Here parameter is an object of a class which i have in assembly but since parameter class is created in the assembly of the current version . And when i try to pass it to the method of previous assembly , i got an exception that it can not be converted.How can i achieve this ? Let me know in case if i need to put on some more information here . Thanks in advance . Assembly myAssembly = Assembly.LoadFrom ( `` Assembly Path for assembly with different version '' ) ; object classObject = myAssembly.CreateInstance ( `` ClassName '' ) ; Type classType = myAssembly.GetType ( `` ClassName '' ) ; MethodInfo myMethod = classType.GetMethod ( `` MyMethod '' , BindingFlags.Instance ) ; // Creating an object of class in the latest assembly and need to pass this// to method in assembly with different version.ClassInBothVesions parameter = new ClassInBothVesions ( ) ; myMethod.Invoke ( classObject , new object [ ] { parameter } ) ;",Use class object across different versions of same assembly using Reflection "C_sharp : < TL ; DR > At a minimum , I 'm looking for a way to conditionally exclude certain properties on the resource from being included in the response on a per-call basis ( See fields below ) . Ideally , I 'd like to implement a REST service with ServiceStack that supports all the major points below . UPDATEWhile I really like ServiceStack 's approach in general and would prefer to use it if possible , if it is n't particularly well suited towards these ideas I 'd rather not bend over backwards bastardizing it to make it work . If that 's the case , can anyone point to another c # framework that might be more appropriate ? I 'm actively exploring other options myself , of course. < /TD ; DR > In this talk entitled Designing REST + JSON APIs , the presenter describes his strategy for Resource References ( via href property on resources ) in JSON . In addition to this , he describes two query parameters ( fields and expand ) for controlling what data is included the response of a call to a REST service . I 've been trying without success to dig into the ServiceStack framework to achieve support for fields in particular but have thus far been unsuccessful . Is this currently possible in ServiceStack ? Ideally the solution would be format agnostic and would therefore work across all of ServiceStack 's supported output formats . I would imagine expand would follow the same strategy . I 'll describe these features here but I think the talk at the link does a better job of explaining them.Lets say we have an Profiles resource with the following properties : givenName , surname , gender , and favColor . The Profiles resource also includes a list of social networks the user belongs to in the socialNetworks property . href - ( 42:22 in video ) Every resource includes a full link to it on the REST service . A call to GET /profiles/123 would return Notice that the socialNetworks property returns an object with just the href value populated . This keeps the response short and focused while also giving the end user enough information to make further requests if desired . The href property , used across the board in this manor , makes it easy ( conceptually anyway ) to reuse resource data structures as children of other resources.fields - ( 55:44 in video ) Query string parameter that instructs the server to only include the specified properties of the desired resource in the REST response . A normal response from GET /profiles/123 would include all the properties of the resource as seen above . When the fields query param is included in the request , only the fields specified are returned . 'GET /propfiles/123 ? fields=surname , favColor ' would return expand - ( 45:53 in video ) Query string parameter that instructs the server to flesh out the specified child resources in the result . Using our example , if you were to call GET /profiles/123 ? expand=socialNetworks you might receive something like { `` href '' : '' https : //host/profiles/123 '' , `` givenName '' : '' Bob '' , `` surname '' : '' Smith '' , `` gender '' : '' male '' , `` favColor '' : '' red '' , `` socialNetworks '' : { `` href '' : '' https : //host/socialNetworkMemberships ? profileId=123 '' } } { `` href '' : '' https : //host/profiles/123 '' , `` surname '' : '' Smith '' , `` favColor '' : '' red '' } { `` href '' : '' https : //host/profiles/123 '' , `` givenName '' : '' Bob '' , `` surname '' : '' Smith '' , `` gender '' : '' male '' , `` favColor '' : '' red '' , `` socialNetworks '' : { `` href '' : '' https : //host/socialNetworkMemberships ? profileId=123 '' , `` items '' : [ { `` href '' : '' https : //host/socialNetworkMemberships/abcde '' , `` siteName '' : '' Facebook '' , `` profileUrl '' : '' http : //www.facebook.com/ ... '' } , ... ] } }",ServiceStack support for conditionally omitting fields from a REST response on a per-call basis "C_sharp : I 'm using Entity Framework code first migrations in my project . One of these migrations populates a database table by reading in data from csv files located in a directory in the project . The project structure looks like this : In my Up ( ) method , I get these files like so : This runs fine on my dev machine but when I deploy this to the test server with Octopus , I get a path not found exception Could not find a part of the path ' C : \Octopus\Applications\Test\Solution\1.1-alpha21\Migrations\CSVFolder'.I 've checked the 'drop ' folder and the output there includes Migrations > CSVFolder . I 've tried a few different ways to get the path to the folder but they work either locally or on the server . What 's the best way to get the path that will work both locally and on the server ? - Soulution - Project - Migrations - CSVFolder - file1.csv - file2.csv - Migration1.cs - Migration2.cs public override void Up ( ) { var migrationsDir = AppDomain.CurrentDomain.BaseDirectory + `` /Migrations/CSVFolder/ '' ; // For some reason , Path.Combine ( ) does n't work for me here so I manually concatenate the strings . var templateFiles = Directory.GetFiles ( migrationsDir , `` *.csv '' ) ; foreach ( var filename in templateFiles ) { Sql ( ) ; // SQL Insert statement here . } }",What is the best way to find directory path from an EF migration script ? "C_sharp : I have the following method I came across in a code review . Inside the loop Resharper is telling me that if ( narrativefound == false ) is incorrect becuase narrativeFound is always true . I do n't think this is the case , because in order to set narrativeFound to true it has to pass the conditional string compare first , so how can it always be true ? Am I missing something ? Is this a bug in Resharper or in our code ? public Chassis GetChassisForElcomp ( SPPA.Domain.ChassisData.Chassis asMaintained , SPPA.Domain.ChassisData.Chassis newChassis ) { Chassis c = asMaintained ; List < Narrative > newNarrativeList = new List < Narrative > ( ) ; foreach ( Narrative newNarrative in newChassis.Narratives ) { bool narrativefound = false ; foreach ( Narrative orig in asMaintained.Narratives ) { if ( string.Compare ( orig.PCode , newNarrative.PCode ) ==0 ) { narrativefound = true ; if ( newNarrative.NarrativeValue.Trim ( ) .Length ! = 0 ) { orig.NarrativeValue = newNarrative.NarrativeValue ; newNarrativeList.Add ( orig ) ; } break ; } if ( narrativefound == false ) { newNarrativeList.Add ( newNarrative ) ; } } } c.SalesCodes = newChassis.SalesCodes ; c.Narratives = newNarrativeList ; return c ; }","Is there unreachable code in this snippet ? I do n't think so , but Resharper is telling me otherwise" "C_sharp : I 've a collection of notes . Depending on the UI requesting those notes , I 'd like to exclude some categories . This is just an example . If the project Notes popup requests notes , I should exclude collection notes . I 'm getting the following error : Type of conditional expression can not be determined because there is no implicit conversion between 'lambda expression ' and 'lambda expression'Thanks for helping Func < Note , bool > excludeCollectionCategory = ( ui == UIRequestor.ProjectNotes ) ? x = > x.NoteCategory ! = `` Collections '' : x = > true ; // -- error : can not convert lambda to lambda",Type of conditional expression can not be determined because there is no implicit conversion between 'lambda expression ' and 'lambda expression ' "C_sharp : I have a computation project with heavy use of log function ( for integers ) , billions of calls . I find the performance of numpy 's log is surprisingly slow.The following code takes 15 to 17 secs to complete : However , the math.log function takes much less time from 3 to 4 seconds.I also tested matlab and C # , which takes about 2 secs and just 0.3 secs respectively . matlabC # Is there any way in python that I can improve the performance of log function ? import numpy as npimport timet1 = time.time ( ) for i in range ( 1,10000000 ) : np.log ( i ) t2 = time.time ( ) print ( t2 - t1 ) import mathimport timet1 = time.time ( ) for i in range ( 1,10000000 ) : math.log ( i ) t2 = time.time ( ) print ( t2 - t1 ) ticfor i = 1:10000000 log ( i ) ; endtoc var t = DateTime.Now ; for ( int i = 1 ; i < 10000000 ; ++i ) Math.Log ( i ) ; Console.WriteLine ( ( DateTime.Now - t ) .TotalSeconds ) ;",What happens in numpy 's log function ? Are there ways to improve the performance ? "C_sharp : ( Windows Phone 8.1 ) In my app , I have a MainPage with a listbox . NavigationCacheMode is set to required to preserve the state when navigating back to the same page . So when I go to another page and come back to my MainPage everthing looks the same as I left it . The Listbox is also in the corrent position . But whenever I touch it , it will jump to the top before it scrolls ... How can I make it so that it resumes scrolling before going to the top first ? EDIT : solvedSeems like Listbox is bugged in WP8.1 , use ListView instead ! public MainPage ( ) { this.InitializeComponent ( ) ; this.DataContext = this ; // cache page this.NavigationCacheMode = NavigationCacheMode.Required ; }",Listbox jumps to top when resuming scroll from last position "C_sharp : Seeing from Artech 's blog and then we had a discussion in the comments . Since that blog is written in Chinese only , I 'm taking a brief explanation here . Code to reproduce : The code gets all FooAttribute and removes the one whose name is `` C '' . Obviously the output is `` A '' and `` B '' ? If everything was going smoothly you would n't see this question . In fact you will get `` AC '' `` BC '' or even correct `` AB '' theoretically ( I got AC on my machine , and the blog author got BC ) . The problem results from the implementation of GetHashCode/Equals in System.Attribute . A snippet of the implementation : It uses Type.GetFields so the properties inherited from base class are ignored , hence the equivalence of the three instances of FooAttribute ( and then the Remove method takes one randomly ) . So the question is : is there any special reason for the implementation ? Or it 's just a bug ? [ AttributeUsage ( AttributeTargets.Class , Inherited = true , AllowMultiple = true ) ] public abstract class BaseAttribute : Attribute { public string Name { get ; set ; } } public class FooAttribute : BaseAttribute { } [ Foo ( Name = `` A '' ) ] [ Foo ( Name = `` B '' ) ] [ Foo ( Name = `` C '' ) ] public class Bar { } //Main methodvar attributes = typeof ( Bar ) .GetCustomAttributes ( true ) .OfType < FooAttribute > ( ) .ToList < FooAttribute > ( ) ; var getC = attributes.First ( item = > item.Name == `` C '' ) ; attributes.Remove ( getC ) ; attributes.ForEach ( a = > Console.WriteLine ( a.Name ) ) ; [ SecuritySafeCritical ] public override int GetHashCode ( ) { Type type = base.GetType ( ) ; //*****NOTICE***** FieldInfo [ ] fields = type.GetFields ( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance ) ; object obj2 = null ; for ( int i = 0 ; i < fields.Length ; i++ ) { object obj3 = ( ( RtFieldInfo ) fields [ i ] ) .InternalGetValue ( this , false , false ) ; if ( ( obj3 ! = null ) & & ! obj3.GetType ( ) .IsArray ) { obj2 = obj3 ; } if ( obj2 ! = null ) { break ; } } if ( obj2 ! = null ) { return obj2.GetHashCode ( ) ; } return type.GetHashCode ( ) ; }",GetHashCode and Equals are implemented incorrectly in System.Attribute ? "C_sharp : I am having a really strange problem with the Messenger system in MVVM Light . It 's hard to explain , so here is small program that demonstrates the issue : If you run the application , this is the console output : As you can see , the second message is never received by recipient A . However , the only difference between B and A is one line : the statement var x = target ; . If you remove this line , A receives the second message.Also , if you remove GC.Collect ( ) ; then A receives the second message . However , this only hides the issue , as in a real program the garbage collector will automatically run eventually.Why is this happening ? I assume that somehow , if the recipient action refers to a variable from it 's containing method scope , it ties the action 's lifetime to that scope so that once out of the scope it can be garbage collected . I do n't understand why this is at all . I also do n't understand why actions that do not reference variables from the scope they are defined in do not have this problem.Can anyone explain what is going on here ? using System ; using GalaSoft.MvvmLight.Messaging ; namespace TestApp { class Program { static void Main ( string [ ] args ) { var prog = new Program ( ) ; var recipient = new object ( ) ; prog.RegisterMessageA ( recipient ) ; prog.RegisterMessageB ( recipient ) ; prog.SendMessage ( `` First Message '' ) ; GC.Collect ( ) ; prog.SendMessage ( `` Second Message '' ) ; } public void RegisterMessageA ( object target ) { Messenger.Default.Register ( this , ( Message msg ) = > { Console.WriteLine ( msg.Name + `` recieved by A '' ) ; var x = target ; } ) ; } public void RegisterMessageB ( object target ) { Messenger.Default.Register ( this , ( Message msg ) = > { Console.WriteLine ( msg.Name + `` received by B '' ) ; } ) ; } public void SendMessage ( string name ) { Messenger.Default.Send ( new Message { Name = name } ) ; } class Message { public string Name { get ; set ; } } } } First Message recieved by AFirst Message received by BSecond Message received by B","Strange behavior with actions , local variables and garbage collection in MVVM light Messenger" "C_sharp : I have a bunch of threads that generate events of type A and type B.My program takes these events , wraps them in a message and sends them across the network . A message can hold either one A event , one B event , or one A event and one B event : Events of type A happen quite frequently , while events of type B occur much less often . So , when a thread generates a B event , my program waits a bit to see if another thread generates an A event and combines the A event and the B event if possible.Here is my code : This works so far . However , there are two problems : If there are lots of A events and lots of B events , the algorithm is not very efficient : Only a certain percentage of B events is attached to A events , even when there are enough A events.If there are no A events generated for a while ( uncommon , but not impossible ) , the algorithm is completely unfair : One thread generating B events has to wait every time , while all other threads can send their B events right away.How can I improve efficiency and fairness of the algorithm ? Constraints : & bullet ; WrapA and WrapB must terminate within a short , deterministic amount of time. & bullet ; SendMessage must be called outside any locks. & bullet ; There is no synchronization mechanism available other than gate. & bullet ; There are not additional threads , tasks , timers , etc . available. & bullet ; Since events of type A happen so frequently in the normal case , busy-waiting in WrapB is fine.Here is a test program that can be used as a benchmark : SendMessage ( new Message ( a : 1 , b : null ) ) ; SendMessage ( new Message ( a : null , b : 2 ) ) ; SendMessage ( new Message ( a : 3 , b : 4 ) ) ; object gate = new object ( ) ; int ? pendingB ; Message WrapA ( int a , int millisecondsTimeout ) { int ? b ; lock ( gate ) { b = pendingB ; pendingB = null ; Monitor.Pulse ( gate ) ; } return new Message ( a , b ) ; } Message WrapB ( int b , int millisecondsTimeout ) { lock ( gate ) { if ( pendingB == null ) { pendingB = b ; Monitor.Wait ( gate , millisecondsTimeout ) ; if ( pendingB ! = b ) return null ; pendingB = null ; } } return new Message ( null , b ) ; } public static class Program { static int counter0 = 0 ; static int counterA = 0 ; static int counterB = 0 ; static int counterAB = 0 ; static void SendMessage ( Message m ) { if ( m ! = null ) if ( m.a ! = null ) if ( m.b ! = null ) Interlocked.Increment ( ref counterAB ) ; else Interlocked.Increment ( ref counterA ) ; else if ( m.b ! = null ) Interlocked.Increment ( ref counterB ) ; else Interlocked.Increment ( ref counter0 ) ; } static Thread [ ] Start ( int threadCount , int eventCount , int eventInterval , int wrapTimeout , Func < int , int , Message > wrap ) { Thread [ ] threads = new Thread [ threadCount * eventCount ] ; for ( int i = 0 ; i < threadCount ; i++ ) { for ( int j = 0 ; j < eventCount ; j++ ) { int k = i * 1000 + j ; int l = j * eventInterval + i ; threads [ i * eventCount + j ] = new Thread ( ( ) = > { Thread.Sleep ( l ) ; SendMessage ( wrap ( k , wrapTimeout ) ) ; } ) ; threads [ i * eventCount + j ] .Start ( ) ; } } return threads ; } static void Join ( params Thread [ ] threads ) { for ( int i = 0 ; i < threads.Length ; i++ ) { threads [ i ] .Join ( ) ; } } public static void Main ( string [ ] args ) { var wrapper = new MessageWrapper ( ) ; var sw = Stopwatch.StartNew ( ) ; // Only A events var t0 = Start ( 10 , 40 , 7 , 1000 , wrapper.WrapA ) ; Join ( t0 ) ; // A and B events var t1 = Start ( 10 , 40 , 7 , 1000 , wrapper.WrapA ) ; var t2 = Start ( 10 , 10 , 19 , 1000 , wrapper.WrapB ) ; Join ( t1 ) ; Join ( t2 ) ; // Only B events var t3 = Start ( 10 , 20 , 7 , 1000 , wrapper.WrapB ) ; Join ( t3 ) ; Console.WriteLine ( sw.Elapsed ) ; Console.WriteLine ( `` 0 : { 0 } '' , counter0 ) ; Console.WriteLine ( `` A : { 0 } '' , counterA ) ; Console.WriteLine ( `` B : { 0 } '' , counterB ) ; Console.WriteLine ( `` AB : { 0 } '' , counterAB ) ; Console.WriteLine ( `` Generated A : { 0 } , Sent A : { 1 } '' , 10 * 40 + 10 * 40 , counterA + counterAB ) ; Console.WriteLine ( `` Generated B : { 0 } , Sent B : { 1 } '' , 10 * 10 + 10 * 20 , counterB + counterAB ) ; } }",Improve efficiency and fairness when combining temporally close events "C_sharp : Odd situation I have here and unfortunately I do n't understand a lot about the Windows network side of things outside of netstat : So I have a proxy that I have configured in my browser ( Firefox 42 ) and am running a simple application that loops through URLs to call them via that proxy . This proxy has credentials in order to use it and I know the proxy works . This is a Windows 7 box.So at some point during this process , the following happens : Browser calls just time out . It does n't ask for credentials at all . ( when the issue goes away , it starts to ask for credentials again ) .Calls in the application timeout no matter what the timeout is ( 7 seconds , 20 seconds , etc ) I 've confirmed the following : In my .net application , I 100 % know I am closing every networkobject and am even aborted the request object after I read theresponse.After a certain amount of time , without any calls , theproblem goes away . When I use this proxy on another server , it100 % works . So I know it 's related to the server I am using and thatproxy IP address.I 've looked at the resource manager and there are n't a lot of active TCP connections open . Although I do n't know if that means anything.If I use another proxy , THAT proxy works . It 's like it 's IP specific , which is baffling me because it 's just a web proxy object in the code.What would cause this ? It usually happens after 4-7 calls with the proxy and releases the issue after 30-40 minutes.Edit 7 : Also happens with AWS instances . Tried that approach . zzz ... Edit 6 : Does n't go away with a server restart either . You can restart and 15 minutes later SAME proxy times out . Eventually works again.Edit 5 : Wrote a similar test with Java and Python . Same result.Edit 4 : This is how it works : Edit 3 : These questions appears to be very similar : Http Post WebRequest getting timed outHttpWebRequest and GetResponse hangs after 1 request ; other solutions does n't work for meWebRequest.GetResponse locks up ? HttpWebRequest times out on second callEdit 2 : Looking at Wireshark , I 'm seeing a TCP transmission in the info for the proxy affected . But does n't that happen with other proxies at the same time ? So is that coming from the proxy server itself ? It does n't make sense to me since I am not even getting a response back and the request is n't even being processed.Edit : Adding code for calls in code . This method is called in a while loop over and over again : Call to Proxy 1 ... Good ! Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Good ! Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Timeout ... Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! Call to Proxy 1 ... Good ! Call to Proxy 2 ... Good ! Call to Proxy 3 ... Good ! Call to Proxy 4 ... Good ! String html = null ; HttpWebRequest request = null ; WebProxy webProxy = null ; try { request = ( HttpWebRequest ) WebRequest.Create ( url ) ; webProxy = new WebProxy ( proxyIP , proxyPort ) ; webProxy.Credentials = new NetworkCredential ( proxyUser , proxyPass ) ; request.Proxy = webProxy ; request.KeepAlive = false ; request.Timeout = 5000 ; request.ReadWriteTimeout = 5000 ; request.Method = `` GET '' ; request.UserAgent = generateAgentString ( ) ; using ( WebResponse resp = ( WebResponse ) request.GetResponse ( ) ) { using ( Stream strm = resp.GetResponseStream ( ) ) { StreamReader reader = new StreamReader ( strm , Encoding.UTF8 ) ; try { html = reader.ReadToEnd ( ) ; } catch { Console.WriteLine ( `` Failed '' ) ; html = null ; } finally { strm.Flush ( ) ; reader.BaseStream.Dispose ( ) ; reader.Dispose ( ) ; strm.Dispose ( ) ; resp.Dispose ( ) ; } } } if ( request ! = null ) { request.Abort ( ) ; } } catch ( Exception e ) { Console.WriteLine ( e ) ; }",HttpWebRequests using WebProxy work and then fail after time "C_sharp : This code snippet is from C # in DepthThe output of the above code snippet is When the main method is changed to The output of the above code snippet is I can not fathom why ? EDIT : Once you understand string-interning following questions do n't apply . How are the parameters received at the Generic method AreReferencesEqual in the second code snippet ? What changes to the string type when it is concatenated to make the == operator not call the overloaded Equals method of the String type ? static bool AreReferencesEqual < T > ( T first , T second ) where T : class { return first == second ; } static void Main ( ) { string name = `` Jon '' ; string intro1 = `` My name is `` + name ; string intro2 = `` My name is `` + name ; Console.WriteLine ( intro1 == intro2 ) ; Console.WriteLine ( AreReferencesEqual ( intro1 , intro2 ) ) ; } True False static void Main ( ) { string intro1 = `` My name is Jon '' ; string intro2 = `` My name is Jon '' ; Console.WriteLine ( intro1 == intro2 ) ; Console.WriteLine ( AreReferencesEqual ( intro1 , intro2 ) ) ; } True True",Operator overloading in Generic Methods "C_sharp : In a few words : blocking Win up after Win + Tab makes Windows think Win is still down , so then pressing S with the Win key up for example will open the search charm rather than just type `` s '' ... until the user presses Win again . Not blocking it means the Windows Start menu will show up . I 'm in a conundrum ! I have no trouble hooking into shortcuts using Alt + Tab using LowLevelKeyboardHook , or Win + Some Ubounded Key using RegisterHotKey . The problem happens only with the Win key using LowLevelKeyboardHook.In the example below , I 'm taking over the Win up event when the Win + Tab combination is detected . This results in making every following keystrokes behave as if the Win key was still down.You can find the complete code here ( note that it should replace your Program.cs in an empty WinForms project to run ) : https : //gist.github.com/christianrondeau/bdd03a3dc32a7a718d62 - press Win + Tab and the Form title should update each time the shortcut is pressed . Note that the intent of hooking into this specific combination is to provide an Alt + Tab alternative without replacing Alt + Tab itself . An answer providing the ability to launching custom code using Win + Tab will also be accepted . Here are my ideas , for which I could not find documentation . All would potentially answer my question successfully.Tell Windows to `` cancel '' the Win up without actually triggering itPrevent Windows from launching the Start menu onceHook directly in the Windows ' Win + event rather than manually hooking into the keystrokes ( This would be by far my first choice if that exists ) private static IntPtr HookCallback ( int nCode , IntPtr wParam , IntPtr lParam ) { if ( nCode ! = HC_ACTION ) return CallNextHookEx ( _hookID , nCode , wParam , lParam ) ; var keyInfo = ( Kbdllhookstruct ) Marshal.PtrToStructure ( lParam , typeof ( Kbdllhookstruct ) ) ; if ( keyInfo.VkCode == VK_LWIN ) { if ( wParam == ( IntPtr ) WM_KEYDOWN ) { _isWinDown = true ; } else { _isWinDown = false ; if ( _isWinTabDetected ) { _isWinTabDetected = false ; return ( IntPtr ) 1 ; } } } else if ( keyInfo.VkCode == VK_TAB & & _isWinDown ) { _isWinTabDetected = true ; if ( wParam == ( IntPtr ) WM_KEYDOWN ) { return ( IntPtr ) 1 ; } else { _isWinTabDetected = true ; Console.WriteLine ( `` WIN + TAB Pressed '' ) ; return ( IntPtr ) 1 ; } } return CallNextHookEx ( _hookID , nCode , wParam , lParam ) ; } } }",How to hook Win + Tab using LowLevelKeyboardHook "C_sharp : If I have a method chain like the following : assuming I 've defined method1 ( ) , method2 ( ) and method3 ( ) asand methodThrowsException ( ) asWhen running the code , is it possible to know which specific line of code has thrown the Exception , or will it just consider all the method chaining as just one line ? I 've done a simple test and it seems it considers them all as just one line but Method Chaining says Putting methods on separate lines also makes debugging easier as error messages and debugger control is usually on a line by line basis.Am I missing something , or does that just not apply to C # ? ThanksEdit : here is what i currently get : alt text http : //img163.imageshack.us/img163/4503/83077881.png var abc = new ABC ( ) ; abc.method1 ( ) .method2 ( ) .methodThrowsException ( ) .method3 ( ) ; public ABC method1 ( ) { return this ; } public ABC method3 ( ) { throw new ArgumentException ( ) ; }",Method chaining and exceptions in C # "C_sharp : I need to bind a GroupBox to a BindingSource , which in turn is bound to the following object : I followed this answer to create a custom GroupBox . I also set the data bindings as follows : However , when loading an existing object , I get the following exception : DataBinding can not find a row in the list that is suitable for all bindings.The exception occurs when setting the data source : What am I missing ? Is there an alternative to get radio buttons to bind to a datasource , specifically a BindingSource ? public class CustomerType { public int Id { get ; set ; } public string Name { get ; set ; } public MemberType MemberType { get ; set ; } } public enum MemberType { Adult , Child } groupBoxMemberType.DataBindings.Add ( `` Selected '' , this.bindingSource , `` MemberType '' ) ; customerType = customerTypeRequest.Load ( id ) ; bindingSource.DataSource = customerType ; //raises exception",Custom group box not binding to bindingsource "C_sharp : First , some background info : I am making a compiler for a school project . It is already working , and I 'm expending a lot of effort to bug fix and/or optimize it . I 've recently run into a problem with is that I discovered that the ILGenerator object generates an extra leave instruction when you call any of the following member methods : So , you start a try statement with a call to BeginExceptionBlock ( ) , add a couple of catch clauses with BeginCatchBlock ( ) , possibly add a finally clause with BeginFinallyBlock ( ) , and then end the protected code region with EndExceptionBlock ( ) . The methods I listed automatically generate a leave instruction branching to the first instruction after the try statement . I do n't want these , for two reasons . One , because it always generates an unoptimized leave instruction , rather than a leave.s instruction , even when it 's branching just two bytes away . And two , because you ca n't control where the leave instruction goes.So , if you wanted to branch to some other location in your code , you have to add a compiler-generated local variable , set it depending on where you want to go inside of the try statement , let EndExceptionBlock ( ) auto-generate the leave instruction , and then generate a switch statement below the try block . OR , you could just emit a leave or leave.s instruction yourself , before calling one of the previous methods , resulting in an ugly and unreachable extra 5 bytes , like so : Both of these options are unacceptable to me . Is there any way to either prevent the automatic generation of leave instructions , or else any other way to specify protected regions rather than using these methods ( which are extremely annoying and practically undocumented ) ? EDITNote : the C # compiler itself does this , so it 's not as if there is a good reason to force it on us . For example , if you have .NET 4.5 beta , disassemble the following code and check their implementation : ( exception block added internally ) BeginCatchBlock ( ) BeginExceptFilterBlock ( ) BeginFaultBlock ( ) BeginFinallyBlock ( ) EndExceptionBlock ( ) L_00ca : leave.s L_00e5L_00cc : leave L_00d1 public static async Task < bool > TestAsync ( int ms ) { var local = ms / 1000 ; Console.WriteLine ( `` In async call , before await `` + local.ToString ( ) + `` -second delay . `` ) ; await System.Threading.Tasks.Task.Delay ( ms ) ; Console.WriteLine ( `` In async call , after await `` + local.ToString ( ) + `` -second delay . `` ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Press any key to continue . `` ) ; Console.ReadKey ( false ) ; return true ; }",Reflection.Emit.ILGenerator Exception Handling `` Leave '' instruction "C_sharp : I have a datagrid that outputs 90 rows after being bound to a datatable . The rows values are the 1-90 ascending . What I want to achieve : If the number is found in an array/range/list of numbers then highlight it green . I have managed to get it to highlight the cell based on 1 value , but I want to highlight several cells if they are found in the range . you can see I have a trigger property of the value 1 . This works fine , but as above , how do I change this so if a cell is in the range set in c # in backend then highlight it green . binding to datatable : The actual making of the datatable : Thanks for any help guys . If you need any more info or I have been to vague or unclear about anything please do ask and i will do my best to respond ASAP . Also please excuse any ignorance I may have , I am very new to wpf . I will do my best . < DataGrid Name= '' grid '' ItemsSource= '' { Binding } '' Height= '' 300 '' Width= '' 900 '' AutoGenerateColumns= '' False '' VerticalScrollBarVisibility= '' Disabled '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Top '' RowHeight= '' 40 '' > < DataGrid.Resources > < Style x : Key= '' BackgroundColourStyle '' TargetType= '' { x : Type TextBlock } '' > < Style.Triggers > < Trigger Property= '' Text '' Value= '' 1 '' > < Setter Property= '' Background '' Value= '' LightGreen '' / > < /Trigger > < /Style.Triggers > < /Style > < /DataGrid.Resources > < DataGrid.Columns > < DataGridTextColumn Binding= '' { Binding Path=Number } '' ElementStyle= '' { StaticResource BackgroundColourStyle } '' MinWidth= '' 40 '' > < /DataGridTextColumn > < /DataGrid.Columns > < DataGrid.ItemsPanel > < ItemsPanelTemplate > < WrapPanel Orientation= '' Vertical '' / > < /ItemsPanelTemplate > < /DataGrid.ItemsPanel > < /DataGrid > calledGrid.DataContext = calledNumbers.DefaultView ; DataSet dataSet = new DataSet ( `` myDS '' ) ; this.bingoCalls ( dataSet ) ; DataTable numbersTable = new DataTable ( `` Numbers '' ) ; numbersTable.Columns.Add ( `` Number '' , typeof ( Int32 ) ) ; for ( int i = 1 ; i < 91 ; i++ ) { numbersTable.Rows.Add ( i ) ; } dataSet.Tables.Add ( numbersTable ) ;",Highlight cells if found "C_sharp : I would like to split up an existing sorted list into multiple sublists , based on the entries of another list.Let 's say I have an array like this : and another list , which defines at which places myList should be split : What 's the shortest way to get a nested list where myList is split at the values defined in borders , i.e . like this : I have already solved it by manually looping through the lists , but I can imagine it 's easier and shorter using Linq.EDIT : There is one simplification : numbers ca n't be the same as the borders , so it 's impossible that a number is contained in myList and borders at the same time . List < int > myList = [ 1,3,7,23,56,58,164,185 ] ; List < int > borders = [ 4,59,170 ] ; [ [ 1,3 ] , [ 7,23,56,58 ] , [ 164 ] , [ 185 ] ]",Split List into sublists based on border values "C_sharp : Is there a possibility for a continue or break to have a bigger scope than the currently running loop ? In the following example , I desire to to continue on the outer for-loop when expr is true , although it is called in the inner for-loop , so that neither [ some inner code ] nor [ some outer code ] is executed.In the above for ( int outerCounter=0 ; outerCounter < 20 ; outerCounter++ ) { for ( int innerCounter=0 ; innerCounter < 20 ; innerCounter++ ) { if ( expr ) { [ continue outer ] ; // here I wish to continue on the outer loop } [ some inner code ] } [ some outer code ] }",continue and break with an extended scope "C_sharp : I set background image to form in my project C # winform , but when set Form property to then disappear my background image.Does anyone help me ? RightToLeft=Yes and RightToLeftLayout=True",Hidden background image C # winform in right to left layout ? "C_sharp : Recently i had an issue making Log4Net work ( described here ) but after that it was OK.I have left this behind a while because i needed to develop some modules and i left the logging somewhat behind . Now that i look , i have even tried changing the name of the log file and the location ( set it statically ) , it is creating it but not writing anything to it in both cases.This is my log4Net config file : This is my Global.asaxHow i declare it : I than use it sometimes like this : Or for Context logging i would use it like this : The file is created , but no content is written to it.Can anyone suggest me where or what to look for ? UPDATE : As suggested by stuartd i have added this in the web.config : Which writes the following content ( pastebin ) Note that i have removed the first section which i did n't saw before and i think it is redundant ? Either way with or without it it does n't work . Here is the output WITH the first part NOT commented out ( in its original state ) I tried the following as well : https : //logging.apache.org/log4net/release/config-examples.htmlhttps : //csharp.today/log4net-tutorial-great-library-for-logging/I am clueless on why it can create it but not write to it ... I can not seem to find anything on the web neither , all issues are regarding the creation of the file , not writing to it . < ? xml version= '' 1.0 '' ? > < configuration > < log4net > < root > < level value= '' ALL '' / > < appender-ref ref= '' console '' / > < appender-ref ref= '' file '' / > < /root > < appender name= '' console '' type= '' log4net.Appender.ConsoleAppender '' > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % date % level % logger - % message % newline '' / > < /layout > < /appender > < appender name= '' file '' type= '' log4net.Appender.RollingFileAppender '' > < file value= '' ApplicationLogging.log '' / > < appendToFile value= '' true '' / > < rollingStyle value= '' Size '' / > < maxSizeRollBackups value= '' 5 '' / > < maximumFileSize value= '' 10MB '' / > < staticLogFileName value= '' true '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % date [ % thread ] % level % logger - % message % newline '' / > < /layout > < /appender > < /log4net > < /configuration > [ assembly : XmlConfigurator ( ConfigFile = `` log4net.config '' , Watch = true ) ] XmlConfigurator.Configure ( ) ; ILog logger = LogManager.GetLogger ( MethodBase.GetCurrentMethod ( ) .DeclaringType ) ; logger.Info ( `` Application started . `` ) ; readonly ILog logger = LogManager.GetLogger ( System.Reflection.MethodBase.GetCurrentMethod ( ) .DeclaringType ) ; logger.Info ( `` some logging here '' ) ; context.Database.Log = ( dbLog = > logger.Debug ( dbLog ) ) ; < appSettings > < add key= '' log4net.Internal.Debug '' value= '' true '' / > < /appSettings > < system.diagnostics > < trace autoflush= '' true '' > < listeners > < add name= '' textWriterTraceListener '' type= '' System.Diagnostics.TextWriterTraceListener '' initializeData= '' C : \log4net.txt '' / > < /listeners > < /trace > < /system.diagnostics > < ! -- < appender name= '' console '' type= '' log4net.Appender.ConsoleAppender '' > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % date % level % logger - % message % newline '' / > < /layout > < /appender > -- >",Log4Net is creating file but not writing to it "C_sharp : In the process of writing a T4 text template I ran into an issue I 'm struggling to get by . I need to know the type of the enum I 'm processing.I have enums that are based on byte and ushort . I need the T4 text template to write code to cast the enum to the correct value type in order to serialize the enum and put it into a byte array.This is an example enum of type byteAnd this is my T4 text templateNotice the part where I wroteHere I have my enum information in the variable codeEnum and this is where my problem is . How do I get byte or ushort type from codeEnum ? I 'm not using Reflection here as Type.GetType ( ) does not work well if the assembly have not been compiled . namespace CodeEnumType { public enum MyEnum : byte { Member1 = 0 , Member2 = 1 , } } < # @ template hostspecific= '' true '' language= '' C # '' # > < # @ output extension= '' .cs '' # > < # @ assembly name= '' EnvDte '' # > < # @ import namespace= '' EnvDTE '' # > < # @ import namespace= '' System.Collections.Generic '' # > < # var serviceProvider = this.Host as IServiceProvider ; var dte = serviceProvider.GetService ( typeof ( DTE ) ) as DTE ; var project = dte.Solution.FindProjectItem ( this.Host.TemplateFile ) .ContainingProject as Project ; var projectItems = GetProjectItemsRecursively ( project.ProjectItems ) ; foreach ( var projectItem in projectItems ) { var fileCodeModel = projectItem.FileCodeModel ; if ( fileCodeModel == null ) { continue ; } CodeElements codeElements = fileCodeModel.CodeElements ; ProcessCodeElements ( codeElements ) ; } # > < # +public void ProcessCodeElements ( CodeElements codeElements ) { if ( codeElements == null ) { return ; } foreach ( CodeElement codeElement in codeElements ) { switch ( codeElement.Kind ) { case vsCMElement.vsCMElementNamespace : CodeNamespace codeNamespace = codeElement as CodeNamespace ; CodeElements childCodeElements = codeNamespace.Members ; ProcessCodeElements ( childCodeElements ) ; break ; case vsCMElement.vsCMElementEnum : CodeEnum codeEnum = codeElement as CodeEnum ; WriteLine ( codeEnum.Name ) ; // // here I would like the enum type // break ; } } } public IEnumerable < ProjectItem > GetProjectItemsRecursively ( ProjectItems items ) { if ( items == null ) { yield break ; } foreach ( ProjectItem item in items ) { yield return item ; var childItems = GetProjectItemsRecursively ( item.ProjectItems ) ; foreach ( ProjectItem childItem in childItems ) { yield return childItem ; } } } # > // // here I would like the enum type //",How to get enum type in a T4 template "C_sharp : I have a ASP MVC 4 app that uses Structuremap . I 'm trying to add logging to my application via Structuremap interception.In a Registry , I scan a specific assembly in order to register all of it 's types with the default convention : The interceptor : I can add the interceptor for one specific plugin type like this : but I want to make structuremap create logging proxies for all the types that were scanned in the registry.Is there a way to achieve this ? public class ServicesRegistry : Registry { public ServicesRegistry ( ) { Scan ( x = > { x.AssemblyContainingType < MyMarkerService > ( ) ; x.WithDefaultConventions ( ) ; } ) ; } } public class LogInterceptor : IInterceptor { public void Intercept ( IInvocation invocation ) { var watch = Stopwatch.StartNew ( ) ; invocation.Proceed ( ) ; watch.Stop ( ) ; //log the time } } var proxyGenerator = new ProxyGenerator ( ) ; container.Configure ( x = > x.For < IServiceA > ( ) .Use < ServiceA > ( ) .DecorateWith ( instance = > proxyGenerator.CreateInterfaceProxyWithTarget ( instance , new LogInterceptor ( ) ) ) ) ;",Structuremap interception for registry scanned types C_sharp : I want to get the screen workarea size in Silverlight . Now I can get the screen size by using below code : But it returns whole screen size that includes the TaskBar also . But I want to get only workarea size that excludes taskbar and so on . Like SystemParameters.WorkArea in WPF.Can anyone guide me to get only screen workarea size in Silverlight ? actualWidth = ( double ) System.Windows.Browser.HtmlPage.Window.Eval ( `` screen.width '' ) ; actualHeight = ( double ) System.Windows.Browser.HtmlPage.Window.Eval ( `` screen.height '' ) ;,How can I get screen workarea ( not whole screen size ) size in Silverlight ? C_sharp : In picture : How does AsEnumerable Methods Knows that the type should be DataRow ? I 've searched in Reflector and Datatable does Not implement IEnumerable..And the AsEnumerable code is : What am I missing ? public static IEnumerable < TSource > AsEnumerable < TSource > ( this IEnumerable < TSource > source ) { return source ; },Datatable implements IEnumerable ? "C_sharp : One of my classes has a property of type Guid . This property can read and written simultaneously by more than one thread . I 'm under the impression that reads and writes to a Guid are NOT atomic , therefore I should lock them.I 've chosen to do it like this : ( Inside my class , all access to the Guid is also done through that property rather than accessing _testKey directly . ) I have two questions : ( 1 ) Is it really necessary to lock the Guid like that to prevent torn reads ? ( I 'm pretty sure it is . ) ( 2 ) Is that a reasonable way to do the locking ? Or do I need to do it like the following : [ EDIT ] This article does confirm that Guids will suffer from torn reads : http : //msdn.microsoft.com/en-us/magazine/jj863136.aspx public Guid TestKey { get { lock ( _testKeyLock ) { return _testKey ; } } set { lock ( _testKeyLock ) { _testKey = value ; } } } get { Guid result ; lock ( _testKeyLock ) { result = _testKey ; } return result ; }",Making Guid properties threadsafe "C_sharp : Possible Duplicate : C # foreach vs functional each This is a question about coding for readability.I have an XDocument and a List < string > of the names of the elements that contain sensitive information that I need to mask ( replace with underscores in this example ) .This can be written in two ways , using traditional foreach loops , or using .ForEach methods with lamba syntax.orWhich approach do you think is the most readable , and why ? If you prefer the second example , how would you present it for maximum readability ? XDocument xDoc ; List < string > propertiesToMask ; foreach ( string propertyToMask in propertiesToMask ) { foreach ( XElement element in xDoc.Descendants ( propertyToMask ) ) { element.SetValue ( new string ( ' _ ' , element.Value.Length ) ) ; } } propertiesToMask .ForEach ( propertyToMask = > xDoc.Descendants ( propertyToMask ) .ToList ( ) .ForEach ( element = > element.SetValue ( new string ( ' _ ' , element.Value.Length ) ) ) ) ;",foreach ( ... in ... ) or .ForEach ( ) ; that is the question C_sharp : Why does : shows 2But if I see the IL code i see : The LDC at line # 1 indicates : Push 0 onto the stack as int32.So there must been 4 bytes occupied.But sizeOf shows 2 bytes ... What am I missing here ? how many byte does short actually take in mem ? I 've heard about a situations where there is a padding to 4 bytes so it would be faster to deal with . is it the case also here ? ( please ignore the syncRoot and the GC root flag byte i 'm just asking about 2 vs 4 ) short a=0 ; Console.Write ( Marshal.SizeOf ( a ) ) ; /*1*/ IL_0000 : ldc.i4.0 /*2*/ IL_0001 : stloc.0 /*3*/ IL_0002 : ldloc.0 /*4*/ IL_0003 : box System.Int16/*5*/ IL_0008 : call System.Runtime.InteropServices.Marshal.SizeOf/*6*/ IL_000D : call System.Console.Write,Int16 - bytes capacity in.net ? "C_sharp : The basic outline of my problem is shown in the code below . I 'm hosting a WebBrowser control in a form and providing an ObjectForScripting with two methods : GiveMeAGizmo and GiveMeAGizmoUser . Both methods return the respective class instances : In JavaScript , I create an instance of both classes , but I need to pass the first instance to a method on the second instance . The JS code looks a little like this : This is where I 've hit a wall . My C # method GizmoUser.doSomethingWith ( ) can not cast the object back to a Gizmo type . It throws the following error : Unable to cast COM object of type 'System.__ComObject ' to interface type 'Gizmo'Unsure how to proceed , I tried a couple of other things : Safe casting Gizmo g = oGizmo as Gizmo ; ( g is null ) Having the classes implement IDispatch and calling InvokeMember , as explained here . The member `` name '' is null.I need this to work with .NET framework version lower than 4.0 , so I can not use dynamic . Does anybody know how I can get this working ? [ ComVisible ] public class Gizmo { public string name { get ; set ; } } [ ComVisible ] public class GizmoUser { public void doSomethingWith ( object oGizmo ) { Gizmo g = ( Gizmo ) oGizmo ; System.Diagnostics.Debug.WriteLine ( g.name ) ; } } var // Returns a Gizmo instance gizmo = window.external.GiveMeAGizmo ( ) , // Returns a GizmoUser instance gUser = window.external.GiveMeAGizmoUser ( ) ; gizmo.name = 'hello ' ; // Passes Gizmo instance back to C # codegUser.doSomethingWith ( gizmo ) ;",Passing a C # class instance back to managed code from JavaScript via COM "C_sharp : I have to design a solution for a task , and I would like to use something theoretically similar to C # 's ExpressionVisitor.For curiosity I opened the .NET sources for ExpressionVisitor to have a look at it . From that time I 've been wondering why the .NET team implemented the visitor as they did.For example MemberInitExpression.Accept looks like this : My - probably noob - question is : does it make any sense ? I mean should n't the Accept method itself be responsible of how it implements the visiting within itself ? I mean I 've expected something like this ( removing the internal visibility to be overridable from outside ) : But this code is in the base ExpressionVisitor 's VisitMemberInit method , which gets called from MemberInitExpression.Accept . So seems like not any benefit of the Accept implementation here.Why not just process the tree in the base ExpressionVisitor , and forget about all the Accept methods ? I hope you understand my points , and hope someone could shed some light on the motivation behind this implementation . Probably I do n't understand the Visitor pattern at all ? ... protected internal override Expression Accept ( ExpressionVisitor visitor ) { return visitor.VisitMemberInit ( this ) ; } protected override Expression Accept ( ExpressionVisitor visitor ) { return this.Update ( visitor.VisitAndConvert ( this.NewExpression , `` VisitMemberInit '' ) , visitor.Visit ( this.Bindings , VisitMemberBinding ) ) ; }",What is the motivation of C # ExpressionVisitor 's implementation ? "C_sharp : I am trying to figure out how to get this file uploaded to my ftp server in C # . When it calls getResponse ( ) on ftpwebrequest it is throwing an error that says `` 550 - access denied '' . I can not figure out why . I can connect to the server with Filezilla just fine using the same credentials.Here is my code that does the connection : private void UploadFileToFTP ( HttpPostedFile file , string server , string user , string pass ) { string uploadUrl = server + file.FileName ; string uploadFileName = Path.GetFileName ( file.FileName ) ; Stream streamObj = file.InputStream ; Byte [ ] buffer = new Byte [ file.ContentLength ] ; streamObj.Read ( buffer , 0 , buffer.Length ) ; streamObj.Close ( ) ; streamObj = null ; try { SetMethodRequiresCWD ( ) ; FtpWebRequest ftp = ( FtpWebRequest ) FtpWebRequest.Create ( uploadUrl ) ; //ftp.Method = WebRequestMethods.Ftp.MakeDirectory ; ftp.Method = WebRequestMethods.Ftp.UploadFile ; ftp.UsePassive = true ; ftp.Credentials = new NetworkCredential ( user , pass ) ; FtpWebResponse CreateForderResponse = ( FtpWebResponse ) ftp.GetResponse ( ) ; if ( CreateForderResponse.StatusCode == FtpStatusCode.PathnameCreated ) { string ftpUrl = string.Format ( `` { 0 } / { 1 } '' , uploadUrl , uploadFileName ) ; FtpWebRequest requestObj = FtpWebRequest.Create ( ftpUrl ) as FtpWebRequest ; requestObj.KeepAlive = true ; requestObj.UseBinary = true ; requestObj.Method = WebRequestMethods.Ftp.UploadFile ; requestObj.Credentials = new NetworkCredential ( user , pass ) ; Stream requestStream = requestObj.GetRequestStream ( ) ; requestStream.Write ( buffer , 0 , buffer.Length ) ; requestStream.Flush ( ) ; requestStream.Close ( ) ; requestObj = null ; } } catch ( WebException e ) { String status = ( ( FtpWebResponse ) e.Response ) .StatusDescription ; } }",ftpwebrequest.getresponse is throwing 550 access denied C_sharp : it wo n't compile.it seems like Test.Write is always trying to call BinaryWriter.Write ( bool ) . any suggestions ? class Test { public BinaryWriter Content { get ; private set ; } public Test Write < T > ( T data ) { Content.Write ( data ) ; return this ; } } 1 . The best overloaded method match for 'System.IO.BinaryWriter.Write ( bool ) ' has some invalid arguments2 . Argument 1 : can not convert from 'T ' to 'bool ',calling an overloaded method in generic method C_sharp : My application loads all library assemblies located in its executing path and executes preknown methods against contained classes.I now need to do the same with an assembly that references my application assembly . Is this possible and are there any negative implications that I should be aware of ? Master Assembly : Child Assemblies : public abstract class TaskBase { public abstract void DoWork ( ) ; } LoadAssemblyFromFile ( `` Assembly0001.dll '' ) ; Assembly0001.Task1.DoWork ( ) ; public sealed class Task1 : MasterAssembly.TaskBase { public override void DoWork { /* whatever */ } },Load an assembly at run time that references the calling assembly "C_sharp : I have developed some extension methods for objects , which I do n't want to be used/shown in intellisense for objects which implements IEnumerable . Conceptually I want something like as followsIs it possible to impose this kind of constraint anyway in C # ? EditSorry , I put the question in a wrong way . I know the allowable constraints in C # , what I want to know is that if there is any other way to accomplish this ? public static T SomeMethod < T > ( this object value ) where T ! = IEnumerable { }",How to specify a type parameter which does NOT implement a particular interface ? "C_sharp : I have a migration job and I need to validate the target data when done . To notify the admin of the success/failure of validations , I use a counter to compare the number of rows from table Foo in Database1 to the number of rows from table Foo in Database2.Each row from Database2 is validated against the corresponding row in Database1 . To speed up the process , I use a Parallel.ForEach loop.My initial problem was that the count was always different from what I expected . I later found that the += and -= operations are not thread-safe ( not atomic ) . To correct the problem , I updated the code to use Interlocked.Increment on the counter variable . This code prints a count that is closer to the actual count , but still , it seems to be different on each execution and it does n't give the result I expect : After some experiments with other ways of making the increment thread-safe , I found that wrapping the increment in a SyncLock on a dummy reference object gives the expected result : Why does n't the first code snippet work as expected ? The most confusing thing is the Breakpoint Hit Count giving unexpected results.Is my understanding of Interlocked.Increment or of atomic operations flawed ? I would prefer not to use SyncLock on a dummy object , and I hope there 's a way to do it cleanly.Update : I run the example in Debug mode on Any CPU.I use ThreadPool.SetMaxThreads ( 60 , 60 ) upper in the stack , because I 'm querying an Access database at some point . Could this cause a problem ? Could the call to Increment mess with the Parallel.ForEach loop , forcing it to exit before all tasks are done ? Update 2 ( Methodology ) : My tests are executed with code as close as possible to what is displayed here , with the exception of object types and query string.The query always give the same number of results , and I always verify objects.Count on a breakpoint before continuing to Parallel.ForEach.The only code that changes in between the executions is Interlocked.Increment replaced by SyncLock locker and countObjects += 1.Update 3I created a SSCCE by copying my code in a new console app and replacing external classes and code.This is the Main method of the console app : This is the definition of Class1 : I still note the same behavior when switching MyParallelFunction from Interlocked.Increment to SyncLock . Private countObjects As IntegerPrivate Sub MyMainFunction ( ) Dim objects As List ( Of MyObject ) 'Query with Dapper , unrelevant to the problem . Using connection As New System.Data.SqlClient.SqlConnection ( `` aConnectionString '' ) objects = connection.Query ( `` SELECT * FROM Foo '' ) 'Returns around 81000 rows . End Using Parallel.ForEach ( objects , Sub ( u ) MyParallelFunction ( u ) ) Console.WriteLine ( String.Format ( `` Count : { 0 } '' , countObjects ) ) 'Prints `` Count : 80035 '' or another incorrect count , which seems to differ on each execution of MyMainFunction.End SubPrivate Sub MyParallelFunction ( obj As MyObject ) Interlocked.Increment ( countObjects ) 'Breakpoint Hit Count is at around 81300 or another incorrect number when done . 'Continues executing unrelated code using obj ... End Sub Private countObjects As IntegerPrivate locker As SomeTypePrivate Sub MyMainFunction ( ) locker = New SomeType ( ) Dim objects As List ( Of MyObject ) 'Query with Dapper , unrelevant to the problem . Using connection As New System.Data.SqlClient.SqlConnection ( `` aConnectionString '' ) objects = connection.Query ( `` SELECT * FROM Foo '' ) 'Returns around 81000 rows . End Using Parallel.ForEach ( objects , Sub ( u ) MyParallelFunction ( u ) ) Console.WriteLine ( String.Format ( `` Count : { 0 } '' , countObjects ) ) 'Prints `` Count : 81000 '' .End SubPrivate Sub MyParallelFunction ( obj As MyObject ) SyncLock locker countObjects += 1 'Breakpoint Hit Count is 81000 when done . End SyncLock 'Continues executing unrelated code using obj ... End Sub Sub Main ( ) Dim oClass1 As New Class1 oClass1.MyMainFunction ( ) End Sub Imports System.ThreadingPublic Class Class1 Public Class Dummy Public Sub New ( ) End Sub End Class Public Class MyObject Public Property Id As Integer Public Sub New ( p_Id As Integer ) Id = p_Id End Sub End Class Public Property countObjects As Integer Private locker As Dummy Public Sub MyMainFunction ( ) locker = New Dummy ( ) Dim objects As New List ( Of MyObject ) For i As Integer = 1 To 81000 objects.Add ( New MyObject ( i ) ) Next Parallel.ForEach ( objects , Sub ( u As MyObject ) MyParallelFunction ( u ) End Sub ) Console.WriteLine ( String.Format ( `` Count : { 0 } '' , countObjects ) ) 'Interlock prints an incorrect count , different in each execution . SyncLock prints the correct count . Console.ReadLine ( ) End Sub 'Interlocked Private Sub MyParallelFunction ( ByVal obj As MyObject ) Interlocked.Increment ( countObjects ) End Sub 'SyncLock 'Private Sub MyParallelFunction ( ByVal obj As MyObject ) ' SyncLock locker ' countObjects += 1 ' End SyncLock 'End SubEnd Class",Why does Interlocked.Increment give an incorrect result in a Parallel.ForEach loop ? "C_sharp : I 've got the following sample code . Oddly enough , the MouseMove events fire properly , however when substituted with MouseEnter , nothing happens when the mouse moves over the ComboBoxItem . Any idea how to fix this ? I actually need an event to occur when the user hovers over a ComboBoxItem , as well as another event when the hovering leaves the item.EDIT : var comboBoxItem1 = new ComboBoxItem ( ) ; var comboBoxItem2 = new ComboBoxItem ( ) ; cmb.Items.Add ( comboBoxItem1 ) ; cmb.Items.Add ( comboBoxItem2 ) ; comboBoxItem1.Content = `` 1 '' ; comboBoxItem1.MouseMove += ( s , args ) = > { MessageBox.Show ( `` 1 '' ) ; } ; comboBoxItem2.Content = `` 2 '' ; comboBoxItem2.MouseMove += ( s , args ) = > { MessageBox.Show ( `` 2 '' ) ; } ; StackPanel spCondition = new StackPanel ( ) ; spCondition.Orientation = Orientation.Horizontal ; ComboBox cmbValue1 = new ComboBox ( ) ; cmbValue1.IsTextSearchEnabled = false ; cmbValue1.IsEditable = true ; cmbValue1.Width = 70 ; cmbValue1.LostFocus += cmbValue_LostFocus ; cmbValue1.PreviewMouseLeftButtonDown += cmbValue_MouseLeftButtonDown ; cmbValue1.SelectionChanged += cmbValue_SelectionChanged ; Border border = new Border ( ) ; border.Child = cmbValue1 ; spCondition.Children.Add ( border ) ; private void cmbValue_MouseLeftButtonDown ( object sender , MouseButtonEventArgs e ) { ComboBox cmb = sender as ComboBox ; cmb.Items.Clear ( ) ; //Iterates through all virtual tables foreach ( TableContainer table in parentTable.ParentVisualQueryBuilder.ListOpenUnjoinedTables ) { ComboBoxItem item = new ComboBoxItem ( ) ; item.MouseMove += item_MouseMove ; if ( table.IsVirtual == false ) { item.Content = `` [ `` + table.TableDescription + `` ] '' ; } else { item.Content = `` [ `` + table.View.Name + `` ] '' ; } item.Tag = table ; cmb.Items.Add ( item ) ; } }",ComboBoxItem MouseEnter event not firing "C_sharp : Context : I am prototyping in prep for ( maybe ) converting my WinForms app to WPF.I make very simple tree view event handler for which the code is : and the XAML is : When I ran it , I fully expected to see my data grid get populated but the == comparison failed on the second line of code above.The debugger shows this : QUESTION : why were there no compile or runtime errors ? ( same question another way : what is actually being compared such that the == operator outputs FALSE ? ) var treeViewItem = ( TreeViewItem ) e.NewValue ; var treeViewItemTag = treeViewItem.Tag ; if ( treeViewItemTag == `` ViewForAMs '' ) { ObjectQuery < AccountManagerView > oq = entities.AccountManagerViews ; var q = from c in oq select c ; dataGrid1.ItemsSource = q.ToList ( ) ; } < Window x : Class= '' AccountingWpfApplication1.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' Loaded= '' Window_Loaded '' > < DockPanel > < TreeView Name= '' treeView1 '' ItemsSource= '' { Binding Folders } '' SelectedItemChanged= '' treeView1_SelectedItemChanged '' > < TreeViewItem Header= '' Account Manager View '' Tag= '' ViewForAMs '' / > < /TreeView > < DataGrid AutoGenerateColumns= '' True '' Name= '' dataGrid1 '' / > < /DockPanel > < /Window >",what 's the underlying reason this == comparison fails ? ( surprising result for me ) "C_sharp : I just ran into an error when I was using the Newtonsoft.Json SerializeObject method . It has been asked before here , but there was no answer from the people working with Newtonsoft as to why this happens.Basically , when calling SerializeObject like this : I get errors in a lot of Equals methods I have overridden in my classes : And of course I realize that it 's `` easy '' to fix , by checking like this : But the real question is : Why does Json.Net send in other types of objects in the Equals method of the class ? More specifically , Json.Net seems to send in a lot of other properties in the class , instead of another object of the same type.To me , it 's completely weird . Any input would be appreciated.I am using `` Version 8.0.0.0 '' according to Visual Studio.UPDATE 1It 's easy to test , as it is reproducible : And then just place this code in Program.cs or anywhere else : and you will get the TypeCast Exception : string json = Newtonsoft.Json.JsonConvert.SerializeObject ( from , new JsonSerializerSettings ( ) { TypeNameHandling = TypeNameHandling.All } ) ; public override bool Equals ( object obj ) { if ( obj == null ) return false ; CapacityConfiguration cc = ( CapacityConfiguration ) obj ; // < -- TypeCastException here ; other Properties of the same class are sent in as parameter ! } public override bool Equals ( object obj ) { if ( obj is CapacityConfiguration == false ) return false ; CapacityConfiguration cc = ( CapacityConfiguration ) obj ; } public class JsonTestClass { public string Name { get ; set ; } public List < int > MyIntList { get ; set ; } public override bool Equals ( object obj ) { if ( obj == null ) return false ; JsonTestClass jtc = ( JsonTestClass ) obj ; return true ; } } JsonTestClass c = new JsonTestClass ( ) ; c.Name = `` test '' ; c.MyIntList = new List < int > ( ) ; c.MyIntList.Add ( 1 ) ; string json = Newtonsoft.Json.JsonConvert.SerializeObject ( c , new JsonSerializerSettings ( ) { TypeNameHandling = TypeNameHandling.All } ) ;",Why does Json.Net call the Equals method on my objects when serializing ? "C_sharp : I do n't know how to phrase this question without using an example , so here we go ... I have defined a class like this : With this constructor : And a method called Run : Now , if I do this : then the orchestration will try to run File.Copy 5 times before it return false , meaning the job has failed ( the background here is that I was trying to rescue som files from a disk that only worked now and then ) The Orchestration class is generic and I can use it to run any method that has three parameters . My question is this : Can I define the Orchestration-class in a manner that the number of parameters does not need to be determined in advance ? My goal then would be to enable it to run any method , not only methods that takes three parameters ... public class Orchestration < T1 , T2 , T3 > { public Orchestration ( Action < T1 , T2 , T3 > action , int maxNumberOfRetries ) public bool Run ( T1 one , T2 two , T3 three ) var orchestration = new Orchestration < string , string , bool > ( File.Copy , 5 ) ; orchestration.Run ( `` c : \filename.txt '' , `` d : \filename.txt '' , true )",Generic class with dynamic number of types "C_sharp : When working with C # 8 and the new non-nullable references , I realized that events are treated like fields . This means that they will cause a warning 90 % of the time since they wo n't be initialized until someone subscribes to it.Consider the following event : You get the following warning on the line of the constructor declaration.CS8618 C # Non-nullable event is uninitialized . Consider declaring the event as nullable.If you make it nullable , the warning disappears of course . However , this looks very weird to me.An alternative would be assigning it a no-op , but this seems even worse.What 's the correct way to handle this situation and get rid of the warning without just disabling it ? Are there any official guidelines for this ? public event EventHandler IdleTimeoutReached ; public event EventHandler ? IdleTimeoutReached ; public event EventHandler IdleTimeoutReached = new EventHandler ( ( o , e ) = > { } ) ;",Guidelines for events since non-nullable references "C_sharp : I am new to unity and currently trying to make a LAN multiplayer RPG game.FYI , I have followed the official unity lan multiplayer guide and everything went well.https : //unity3d.com/learn/tutorials/topics/multiplayer-networking/introduction-simple-multiplayer-exampleSo far I got the players to load in and they are able to move . I wrote the following code below ( under the void update routine ) so that when the player is moving , it will randomize a number between 1 & 50 every 1 second and if the number is 25 , we have randomly `` encountered an enemy '' . When any player encounters an enemy I made it so everyone on the network goes to the `` battle scene '' .The code above works fine but I am not sure how , instead of loading everyone , to load only certain players into the battle scene.For example : Players enter a name before Hosting/Finding LAN gamePlayer 1 = JoePlayer 2 = BobPlayer 3 = BillyPlayer 4 = JimOn a preset label/text that loads the text in it saying `` Joe , Billy '' . Now when ANY player finds an encounter , I want to ONLY load the players name `` Joe '' and `` Billy '' to the next scene while the others do not.Is this possible ? Any kind of help will be greatly appreciated.Thanks All if ( Input.GetKey ( `` up '' ) || Input.GetKey ( `` down '' ) || Input.GetKey ( `` left '' ) || Input.GetKey ( `` right '' ) ) { if ( Time.time > NextActionTime ) { NextActionTime = Time.time + Period ; EnemyEncounter = Random.Range ( 1 , 50 ) ; if ( EnemyEncounter == 25 ) { NetworkManager.singleton.ServerChangeScene ( `` Scene2 '' ) ; } } }",Lan Multiplayer Scene Change "C_sharp : Short version : We can get the typeof Func < T , T > using : but what if I want to get the type of Func < T , bool > , what should I use , or is it possible to do ? Clearly this does n't compile : Long version : Consider the following scenario , I have two similar method and I want to get the second one ( Func < T , int > ) using Reflection : I 'm trying this : But since the generic type definition of Func < T , bool > and Func < T , int > are equal it gives me the first method . To fix this I can do the following : Then I get the correct method but I do not like this way . And it seems like a overhead for more complex situations . What I want to do is get the type of Func < T , bool > like in my failed attempt above , then instead of using Linq I can use this overload of GetMethod and do something like the following : Note : Ofcourse Func < T , T > is just an example , question is not specific to any type . typeof ( Func < , > ) typeof ( Func < , bool > ) public void Foo < T > ( Func < T , bool > func ) { } public void Foo < T > ( Func < T , int > func ) { } var methodFoo = typeof ( Program ) .GetMethods ( ) .FirstOrDefault ( m = > m.Name == `` Foo '' & & m.GetParameters ( ) [ 0 ] .ParameterType .GetGenericTypeDefinition ( ) == typeof ( Func < , > ) ) ; var methodFoo = typeof ( Program ) .GetMethods ( ) .FirstOrDefault ( m = > m.Name == `` Foo '' & & m.GetParameters ( ) [ 0 ] .ParameterType .GetGenericArguments ( ) [ 1 ] == typeof ( int ) ) ; var methodFoo = typeof ( Program ) .GetMethod ( `` Foo '' , BindingFlags.Public | BindingFlags.Instance , null , new [ ] { typeof ( Func < , bool > ) } , // ERROR typeof ( Func < , > ) does n't work either null ) ;","Is there a way to get typeof Func < T , bool > ?" "C_sharp : In my project , I have a class structure as shown in the image.The green classes are old codes , that runs very well . The classes in red boxes are newly added codes . There 're no compiler errors , however when click play in Unity and runs into the new code , the three classes ca n't be initialized correctly.And unity console gives warning that says `` The class named 'DataMgrBase ` 2 ' is generic . Generic MonoBehaviours are not supported ! UnityEngine.GameObject : AddComponent ( ) '' at this line : `` instance = obj.AddComponent ( ) ; '' How can I solve this problem ? Following are some code for your reference , thanks ! Implementation of singleton base class : Implementation of DataMgrBase : using UnityEngine ; using System.Collections ; public class UnitySingletonPersistent < T > : MonoBehaviour where T : Component { private static T instance ; public static T Instance { get { if ( instance == null ) { instance = FindObjectOfType < T > ( ) ; if ( instance == null ) { GameObject obj = new GameObject ( ) ; obj.name = typeof ( T ) .Name ; obj.hideFlags = HideFlags.DontSave ; instance = obj.AddComponent < T > ( ) ; } } return instance ; } } public virtual void Awake ( ) { DontDestroyOnLoad ( this.gameObject ) ; if ( instance == null ) { instance = this as T ; } else { Destroy ( gameObject ) ; } } } public class DataMgrBase < TKey , TValue > : UnitySingletonPersistent < DataMgrBase < TKey , TValue > > { protected Dictionary < TKey , TValue > dataDict ; public override void Awake ( ) { base.Awake ( ) ; dataDict = new Dictionary < TKey , TValue > ( ) ; } public TValue GetDataForKey ( TKey key ) { TValue data ; if ( dataDict.TryGetValue ( key , out data ) ) { return data ; } else { data = LoadDataForKey ( key ) ; if ( data ! = null ) { dataDict.Add ( key , data ) ; } return data ; } } virtual protected TValue LoadDataForKey ( TKey key ) { if ( dataDict.ContainsKey ( key ) ) { return GetDataForKey ( key ) ; } else { return default ( TValue ) ; } } }",How to make Unity singleton base class to support generics ? "C_sharp : At some point in the last couple of months , a lot of message along the lines of started spamming my Visual Studio output window making it hard to find actual trace and debug messages . Where are these messages coming from , and how do I disable them ? To try to solve this problem , I have tried several things . Most of the answers point to configuring the checkboxes in the output window . If I uncheck `` Program Output '' the problem messages go away , but so do the messages I want to keep . I tried creating a custom TraceListener and set a breakpoint in the Write and WriteLine methods in the hopes that the call stack would tell me where the messages were being generated from . I discovered that these messages are not coming from the typical Diagnotics.Debug or Diagnotics.Trace methods.I tried redirecting the console via Console.SetOut ( ) to a custom TextWriter that I could set breakpoints within . Again , I could not find anything.Any help would be appreciated . Event 7 was called with 5 argument ( s ) , but it is defined with 6 paramenter ( s ) .Event 10 was called with 5 argument ( s ) , but it is defined with 6 paramenter ( s ) .Event 10 was called with 5 argument ( s ) , but it is defined with 6 paramenter ( s ) .",Filter custom message from Visual Studio 2015 output window "C_sharp : When you overload an operator , such as operator + , the compiled CIL looks something like this : Why use the name op_Addition here and not , say , the name + ? I 'm suggesting that the CIL syntax should have beenAnd the member name , when looking for it , would have been + rather than op_Addition.Note : This is a question about language design ; `` because the spec says so '' is not a helpful answer . .method public hidebysig specialname static bool op_Addition ( ... ) { ... } .method public hidebysig specialname static bool + ( ... ) { ... }",Why use the name 'op_Addition ' for operator '+ ' rather than the name '+ ' ? "C_sharp : I was following a tutorial showing how to create a Binary search algorithm from scratch . However I recieve the error `` Use of unassigned local variable 'Pivot ' '' . I 'm new to the language and have only tried much simpler languages previously.I apologise for the lack of internal documentation and appauling use of white space . The error is near the bottom of the code labled using `` // '' Here is the program : I 'm sorry if this is actually something really simple but I do n't have anyone to teach me directly and I 'm out of ideas . using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Binary_Search_2 { class Program { static void Main ( string [ ] args ) { int [ ] arr = new int [ 10 ] ; Random rnd = new Random ( ) ; for ( int i = 0 ; i < arr.Length ; i++ ) { arr [ i ] = rnd.Next ( 1 , 10 ) ; } Array.Sort ( arr ) ; for ( int i = 0 ; i < arr.Length ; i++ ) { Console.Write ( `` { 0 } , '' , arr [ i ] ) ; } int Start = 0 ; int End = arr.Length ; int Center = Start + End / 2 ; int Pivot ; while ( arr [ 6 ] > 0 ) { while ( arr [ 6 ] < arr [ Center ] ) { End = Center ; Center = ( End + Start ) / 2 ; if ( Pivot == arr [ Center ] ) { Console.WriteLine ( `` The Index is { 0 } '' , arr [ Center ] ) ; } break ; } while ( arr [ 6 ] > arr [ Center ] ) { Start = Center ; Center = ( End + Start ) / 2 ; if ( Pivot == arr [ Center ] ) //**This is where the error occurs . ** { Console.WriteLine ( `` The index is { 0 } '' , arr [ Center ] ) ; } } } } } }",Binary search algorithm turns up error - Use of unassigned local variable "C_sharp : What 's up with this , anyway ? I do a simple multiplication : And at the end of the multiplication , z shows a value of : -5670418394979206991This has clearly overflowed , but no exception is raised . I 'd like one to be raised , but ... Note that this is on Windows Phone 7 , but I do n't think this has any bearing on the issue . Or does it ? Int64 x = 11111111111 ; Int64 y = 11111111111 ; Int64 z = x * y ;",Should n't this cause an Overflow ? It does n't ! "C_sharp : I have a website stored on azure for which I got an SSL certificate . I am trying to redirect www.mywebsite.com to https : //www.mywebsite.com but with no success.I am using the following code that should change the configuration of IIS where my project is deployed : But when I type my URL it does not redirect to https.By the way , rewrite appears unrecorgnized by Intellisense . < system.webServer > < rewrite > < rules > < rule name= '' Redirect to HTTPS '' > < match url= '' ( . * ) '' / > < conditions > < add input= '' { HTTPS } '' pattern= '' off '' ignoreCase= '' true '' / > < add input= '' { URL } '' pattern= '' / $ '' negate= '' true '' / > < add input= '' { REQUEST_FILENAME } '' matchType= '' IsFile '' negate= '' true '' / > < /conditions > < action type= '' Redirect '' url= '' https : // { SERVER_NAME } / { R:1 } '' redirectType= '' SeeOther '' / > < /rule > < /rules > < /rewrite >",Redirect website from http to https "C_sharp : I am developing a C # windows form application containing a service based data based . when I test my application it 's database works fine but after publishing and installing the program when program tries to open sqlconnection , this error appears : System.Data.SqlClient.SqlException ( 0x80131904 ) : An attempt to attach an auto-named database for file C : \Users\Behnam\AppData\Local\Apps\2.0\Data\5XVOVXV1.3VG\M5T04ZK7.QBJ\tahl..tion_45c3791d6509222d_0001.0000_be1c7cc05811ecf0\Data\AppData\TahlilGar.mdf failed . A database with the same name exists , or specified file can not be opened , or it is located on UNC share.This is my ConnectionString : I also tried : User Instance= True ; but it 's result is : The user instance login flag is not allowed when connecting to a user instance of SQL Server . The connection will be closed.How can I fix this issue ? Edit : I checked the mentioned path and there was not my .mdf file . so i copied it from my project and it worked fine after that . now why my mdf file is not copying when publishing and installing in the expected path . < add name= '' BA '' connectionString= '' Data Source= ( LocalDB ) \v11.0 ; AttachDbFilename=|DataDirectory|\AppData\TahlilGar.mdf ; Integrated Security=True ; '' providerName= '' System.Data.SqlClient '' / >",Database file not copied during publishing so installed application throws exception "C_sharp : I 'm very familiar with using a transaction RDBMS , but how would I make sure that changes made to my in-memory data are rolled back if the transaction fails ? What if I 'm not even using a database ? Here 's a contrived example : In my example , I might want the changes made to the items in the list to somehow be rolled back , but how can I accomplish this ? I am aware of `` software transactional memory '' but do n't know much about it and it seems fairly experimental . I 'm aware of the concept of `` compensatable transactions '' , too , but that incurs the overhead of writing do/undo code.Subversion seems to deal with errors updating a working copy by making you run the `` cleanup '' command.Any ideas ? UPDATE : Reed Copsey offers an excellent answer , including : Work on a copy of data , update original on commit.This takes my question one level further - what if an error occurs during the commit ? We so often think of the commit as an immediate operation , but in reality it may be making many changes to a lot of data . What happens if there are unavoidable things like OutOfMemoryExceptions while the commit is being applied ? On the flipside , if one goes for a rollback option , what happens if there 's an exception during the rollback ? I understand things like Oracle RDBMS has the concept of rollback segments and UNDO logs and things , but assuming there 's no serialisation to disk ( where if it is n't serialised to disk it did n't happen , and a crash means you can investigate those logs and recover from it ) , is this really possible ? UPDATE 2 : An answer from Alex made a good suggestion : namely that one updates a different object , then , the commit phase is simply changing the reference to the current object over to the new object . He went further to suggest that the object you change is effectively a list of the modified objects.I understand what he 's saying ( I think ) , and I want to make the question more complex as a result : How , given this scenario , do you deal with locking ? Imagine you have a list of customers : Now , you want to make a change to some of those customers , how do you apply those changes without locking and replacing the entire list ? For example : How do I commit ? This ( Alex 's suggestion ) will mean locking all customers while replacing the list reference : Whereas if I loop through , modifying the reference in the original list , it 's not atomic , a and falls foul of the `` what if it crashes partway through '' problem : public void TransactionalMethod ( ) { var items = GetListOfItems ( ) ; foreach ( var item in items ) { MethodThatMayThrowException ( item ) ; item.Processed = true ; } } var customers = new Dictionary < CustomerKey , Customer > ( ) ; var customerTx = new Dictionary < CustomerKey , Customer > ( ) ; foreach ( var customer in customers.Values ) { var updatedCust = customer.Clone ( ) ; customerTx.Add ( GetKey ( updatedCust ) , updatedCust ) ; if ( CalculateRevenueMightThrowException ( customer ) > = 10000 ) { updatedCust.Preferred = true ; } } lock ( customers ) { customers = customerTx ; } foreach ( var kvp in customerTx ) { customers [ kvp.Key ] = kvp.Value ; }",How do I make an in-memory process transactional ? "C_sharp : I am using Convert an array of different value types to a byte array solution for my objects to byte array conversion.But I have a small issue that causes a big problem . There are `` byte '' type of data in mids of object [ ] , I do n't know how to keep `` byte '' as is . I need keep same bytes-length before and after.I tried add `` byte '' type into the dictionary like this : there is no syntext complaining , but I traced this code , after the program executed the original `` byte '' becomes byte [ 2 ] .What happens here ? How to keep byte value authentic in this solution ? Thanks ! private static readonlyDictionary < Type , Func < object , byte [ ] > > Converters = new Dictionary < Type , Func < object , byte [ ] > > ( ) { { typeof ( byte ) , o = > BitConverter.GetBytes ( ( byte ) o ) } , { typeof ( int ) , o = > BitConverter.GetBytes ( ( int ) o ) } , { typeof ( UInt16 ) , o = > BitConverter.GetBytes ( ( UInt16 ) o ) } , ... } ; public static void ToBytes ( object [ ] data , byte [ ] buffer ) { int offset = 0 ; foreach ( object obj in data ) { if ( obj == null ) { // Or do whatever you want throw new ArgumentException ( `` Unable to convert null values '' ) ; } Func < object , byte [ ] > converter ; if ( ! Converters.TryGetValue ( obj.GetType ( ) , out converter ) ) { throw new ArgumentException ( `` No converter for `` + obj.GetType ( ) ) ; } byte [ ] obytes = converter ( obj ) ; Buffer.BlockCopy ( obytes , 0 , buffer , offset , obytes.Length ) ; offset += obytes.Length ; } } byte [ ] obytes = converter ( obj ) ;","C # convert object [ ] into byte [ ] , but how to keep byte object as byte ?" "C_sharp : While working with large arrays , I am doing unsafe pointer computations like the following : It works as expected . But for inplace operations , I need the c pointer on the right side as well : The pointer gets incremented before the dereference happens . This is correct according to precedence rules ( ++ before * ) . But now the new value is written to the incremented address , not to the original . Why is this so ? I found this SO question : dereference and advance pointer in one statement ? . But it handles the *c++ expression on the right side only . Why would the write access be different from the read access ? Also , a link to the preceedence rules for pointer types in the C # spec would be highly appreciated . Could n't find them so far . @ EDIT : Please note , we are talking about C # here , not C or C++ . Even if I expect the difference to be not too big here . Also , like in the example above , I know , the problem can be prevented by incrementing the pointer in the next code line . I want to know , why the behaviour is as described anyway . *c++ = *a++ - *b++ ; [ STAThread ] unsafe static void Main ( string [ ] args ) { double [ ] arr = new double [ ] { 2 , 4 , 6 , 8 , 10 } ; double scalar = 1 ; fixed ( double* arrP = arr ) { double* end = arrP + arr.Length ; double* p = arrP ; double* p2 = arrP ; while ( p < end ) { // gives : 3,5,7,9,2,4827634676971E+209 *p++ = *p - scalar ; // gives correct result : 1,3,5,7,9 //*p = *p - scalar ; //p++ ; } } Console.WriteLine ( String.Join < double > ( `` , '' , arr ) ) ; Console.ReadKey ( ) ; }",why does *p++ = *p - a give strange results ? "C_sharp : Trying to make a simple bacteria-killing game using WinForm in C # , but the bacteria ( I am using Panel for the time being ) does n't seem to move around at random.Specifically , the problem I am having is , the bacteria tries to move towards the upper left corner and move around there only . Ideally , the bacteria needs to move around the rectangle range evenly , but I am not sure how to achieve that.Look at the gif file below.As you can see the red Panel moves around the upper left corner only . How can I get it to move everywhere evenly and randomly ? Here is my code : I tried changing the +10 to +12 , leaving -10 as it is , but now this only made the bacteria move to the bottom right corner only . I am at a loss . Can anyone please help ? private Panel _pnlBacteria ; //Panel representing a piece of bacteriaprivate Random r = new Random ( ) ; //For randomly-generated valuesprivate int _prevX ; //Stores the previous X locationprivate int _prevY ; //Stores the previous Y locationpublic Form1 ( ) { InitializeComponent ( ) ; _pnlBacteria = new Panel ( ) ; /* Get more property assignments to this._pnlBacteria ( omitted ) */ //Bacteria 's start position is also randomly selected _prevX = r.Next ( 50 , 300 ) ; _prevY = r.Next ( 50 , 500 ) ; } //Timer runs every 100 seconds changing the location of the bacteriaprivate void TmrMoveBacteria_Tick ( object sender , EventArgs e ) { int x , y ; //Get random values for X and Y based on where the bacteria was previously //and move randomly within ±10 range . Also it can not go off the screen . do { x = r.Next ( _prevX - 10 , _prevX + 10 ) ; y = r.Next ( _prevY - 10 , _prevY + 10 ) ; } while ( ( y < = 0 ) || ( y > = 500 ) || ( x < = 0 ) || ( x > = 300 ) ) ; //Save the new location to be used in the next Tick round as previous values _prevX = x ; _prevY = y ; //Apply the actual location change to the bacteria panel _pnlBacteria.Top = y ; _pnlBacteria.Left = x ; }",Random values seem to be not really random ? "C_sharp : I 'm looking at the generated code by ASP.NET MVC 1.0 , and was wondering ; what do the double question marks mean ? Related : ? ? Null Coalescing Operator — > What does coalescing mean ? // This constructor is not used by the MVC framework but is instead provided for ease// of unit testing this type . See the comments at the end of this file for more// information.public AccountController ( IFormsAuthentication formsAuth , IMembershipService service ) { FormsAuth = formsAuth ? ? new FormsAuthenticationService ( ) ; MembershipService = service ? ? new AccountMembershipService ( ) ; }",What does `` ? ? '' mean ? "C_sharp : I have a small issue that I ca n't seem to get right.I have a textbox where I 'm adding `` Search hint '' I 'm using this XAML snippet Because background of the window is not white I am getting a result as shown in picture . I tried to bind width multiple different ways , but nothing seem to work , can you please suggest ? I want it to look like this thank you ! < TextBox x : Name= '' txtboxSearch '' Height= '' 22 '' Margin= '' 3,35,111,0 '' TextWrapping= '' Wrap '' VerticalAlignment= '' Top '' BorderThickness= '' 1 '' MaxLines= '' 1 '' MaxLength= '' 256 '' Grid.Column= '' 2 '' BorderBrush= '' # FF828790 '' > < TextBox.Style > < Style TargetType= '' TextBox '' xmlns : sys= '' clr-namespace : System ; assembly=mscorlib '' > < Style.Resources > < VisualBrush x : Key= '' CueBannerBrush '' AlignmentX= '' Left '' AlignmentY= '' Center '' Stretch= '' None '' > < VisualBrush.Visual > < TextBox Text= '' Search '' Foreground= '' LightGray '' FontStyle= '' Italic '' / > < /VisualBrush.Visual > < /VisualBrush > < /Style.Resources > < Style.Triggers > < Trigger Property= '' Text '' Value= '' { x : Static sys : String.Empty } '' > < Setter Property= '' Background '' Value= '' { StaticResource CueBannerBrush } '' / > < /Trigger > < Trigger Property= '' Text '' Value= '' { x : Null } '' > < Setter Property= '' Background '' Value= '' { StaticResource CueBannerBrush } '' / > < /Trigger > < Trigger Property= '' IsKeyboardFocused '' Value= '' True '' > < Setter Property= '' Background '' Value= '' White '' / > < /Trigger > < /Style.Triggers > < /Style > < /TextBox.Style > < /TextBox >",Bind width of a textbox inside VisualBrush C_sharp : I can get type of constructor parameter like this : Now I want to create stub object from this type . Is is possible ? I tried with autofixture : .. but it does n't work : Could you help me out ? Type type = paramInfo.ParameterType ; public TObject Stub < TObject > ( ) { Fixture fixture = new Fixture ( ) ; return fixture.Create < TObject > ( ) ; } Type type = parameterInfo.ParameterType ; var obj = Stub < type > ( ) ; //Compile error ! ( `` can not resolve symbol type '' ),How to generate a stub object of an arbitrary Type not known at compile time using AutoFixture "C_sharp : All , I 've got a security server which sole purpose is to provide bearer tokens from a single endpoint : http : //example.com/tokenExample request : Example response : We have an angular application which uses this endpoint to authenticate , and does so just fine.What we are trying to achieve without much success is to create an MVC application which uses the same server to authenticate , we 'd like the code to sit on top of Identity 2.0 if possible.In our AccountController ( example project ) we have our Login ( LoginModel model ) method which handles login and looks like this ( same as example project template ) : We have our own implemention of IUserStore , UserManager , SignInManager.I 've considered overridingThe default implementation of PasswordSignInAsync calls UserManager.FindByNameAsync however this would mean I 'd have to expose a lookup method on my security server to confirm a username exists which really does n't sound good.I must be missing something and I know it would n't be this complicated , our MVC app needs to use cookie authentication but also maintain the bear token for subsequent calls to our other resource server . ( I appreciate I might be mixing up technologies here , hence the question ) .This is also running on OWIN . POST http : //example.com/token HTTP/1.1User-Agent : FiddlerContent-Type : x-www-form-urlencodedHost : example.comContent-Length : 73grant_type=password & username=example @ example.com & password=examplePassword HTTP/1.1 200 OKCache-Control : no-cachePragma : no-cacheContent-Type : application/json ; charset=UTF-8Expires : -1Server : Microsoft-IIS/10.0X-Powered-By : ASP.NETDate : Tue , 16 Aug 2016 12:04:39 GMT { `` access_token '' : `` xxxx '' , `` token_type '' : `` bearer '' , `` expires_in '' : 17999 , `` refresh_token '' : `` xxxx '' , `` .issued '' : `` Tue , 16 Aug 2016 12:04:38 GMT '' , `` .expires '' : `` Tue , 16 Aug 2016 17:04:38 GMT '' } var result = await _signInManager.PasswordSignInAsync ( model.UserName , model.Password , model.RememberMe , shouldLockout : false ) ; public Task < SignInStatus > PasswordSignInAsync ( string userName , string password , bool isPersistent , bool shouldLockout ) on ` SignInManager < , > ` and make a web call across to the security server .",ASP.NET Identity 2.0 Authenticate against our own bearer server "C_sharp : I need to service localized data . All response Dtos which are localized share the same properties . I.e . I defined an interface ( ILocalizedDto ) to mark those Dtos . On the request side , there is a ILocalizedRequest for requests which demand localization.Using IPlugin I already managed to implement the required feature . However I am quite sure that the implementation is not thread safe and additionally I do n't know if I could use IHttpRequest.GetHashCode ( ) as identifier for one request/response cycle.What would be the correct way to implement a ServiceStack plugin which makes use of both request and response Dto ? I.e . is there some IHttpRequest.Context to store data in or is it possible to get the request dto at response time ? internal class LocalizationFeature : IPlugin { public static bool Enabled { private set ; get ; } /// < summary > /// Activate the localization mechanism , so every response Dto which is a < see cref= '' ILocalizedDto '' / > /// will be translated . /// < /summary > /// < param name= '' appHost '' > The app host < /param > public void Register ( IAppHost appHost ) { if ( Enabled ) { return ; } Enabled = true ; var filter = new LocalizationFilter ( ) ; appHost.RequestFilters.Add ( filter.RequestFilter ) ; appHost.ResponseFilters.Add ( filter.ResponseFilter ) ; } } // My request/response filterpublic class LocalizationFilter { private readonly Dictionary < int , ILocalizedRequest > localizedRequests = new Dictionary < int , ILocalizedRequest > ( ) ; public ILocalizer Localizer { get ; set ; } public void RequestFilter ( IHttpRequest req , IHttpResponse res , object requestDto ) { var localizedRequest = requestDto as ILocalizedRequest ; if ( localizedRequest ! = null ) { localizedRequests.Add ( GetRequestId ( req ) , localizedRequest ) ; } } public void ResponseFilter ( IHttpRequest req , IHttpResponse res , object response ) { var requestId = GetRequestId ( req ) ; if ( ! ( response is ILocalizedDto ) || ! localizedRequests.ContainsKey ( requestId ) ) { return ; } var localizedDto = response as ILocalizedDto ; var localizedRequest = localizedRequests [ requestId ] ; localizedRequests.Remove ( requestId ) ; Localizer.Translate ( localizedDto , localizedRequest.Language ) ; } private static int GetRequestId ( IHttpRequest req ) { return req.GetHashCode ( ) ; } }",How to write a ServiceStack plugin which needs both request and response Dtos "C_sharp : Currently I am working on a project using Kinect which requires me to know the where the person is looking at that time , for which I figured out I need to find the line of sight of that person.Right now , I can find the head point of the skeleton of the person but ca n't track the eye movement.Here point.X and point.Y are the head points of the skeleton . if ( body.TrackingState == SkeletonTrackingState.Tracked ) { Joint joint = body.Joints [ JointType.Head ] ; SkeletonPoint skeletonPoint = joint.Position ; // 2D coordinates in pixels System.Drawing.Point point = new System.Drawing.Point ( ) ; if ( _mode == CameraMode.Color ) { // Skeleton-to-Color mapping ColorImagePoint colorPoint = _sensor.CoordinateMapper.MapSkeletonPointToColorPoint ( skeletonPoint , ColorImageFormat.RgbResolution640x480Fps30 ) ; point.X = colorPoint.X ; point.Y = colorPoint.Y ; //Console.WriteLine ( `` X == `` + point.X + `` Y == `` + point.Y ) ; X = ( int ) Math.Floor ( point.X + 0.5 ) ; Y = ( int ) Math.Floor ( point.Y + 0.5 ) ; } // DRAWING ... Ellipse ellipse = new Ellipse { Fill = System.Windows.Media.Brushes.LightBlue , Width = 20 , Height = 20 } ; Canvas.SetLeft ( ellipse , point.X - ellipse.Width / 2 ) ; Canvas.SetTop ( ellipse , point.Y - ellipse.Height / 2 ) ; canvas.Children.Add ( ellipse ) ; }",How to detect the line of sight of a person using kinect ? "C_sharp : I have switched to enable nullable in my project that uses C # 8 . Now I have the following class : Compiler of course complains that it can not guarantee that these properties wo n't be null . I ca n't see any other way of ensuring this than adding a constructor that accepts non-nullable strings.This seems fine for a small class , but if I have 20 properties , is this the only way to list them all in a constructor ? Is it possible somehow to e.g . enforce it with the initializer : P.S . There is a good answer that suggests using iniatlizer for properties , but that does not always work e.g . for types like e.g . Type that one can not just intialize to some random value public class Request { public string Type { get ; set ; } public string Username { get ; set ; } public string Key { get ; set ; } } var request = new Request { Type = `` Not null '' , Username = `` Not null '' } ; // Get an error here that Key is null",Is constructor the only way to initialize non-nullable properties in a class in C # ? "C_sharp : I 've been reading the answer to a similar question , but I 'm still a little confused ... Abel had a great answer , but this is the part that I 'm unsure about : ... declaring a variable volatile makes it volatile for every single access . It is impossible to force this behavior any other way , hence volatile can not be replaced with Interlocked . This is needed in scenarios where other libraries , interfaces or hardware can access your variable and update it anytime , or need the most recent version.Does Interlocked guarantee visibility of the atomic operation to all threads , or do I still have to use the volatile keyword on the value in order to guarantee visibility of the change ? Here is my example : Update : I was a bad sport and I changed the original example , so here it is again : volatile int value = 100000 ; // < -- do I need the volitile keyword// ... .public void AnotherThreadMethod ( ) { while ( Interlocked.Decrement ( ref value ) > 0 ) { // do something } } public void AThreadMethod ( ) { while ( value > 0 ) { // do something } } public class CountDownLatch { private volatile int m_remain ; // < -- - do I need the volatile keyword here ? private EventWaitHandle m_event ; public CountDownLatch ( int count ) { Reset ( count ) ; } public void Reset ( int count ) { if ( count < 0 ) throw new ArgumentOutOfRangeException ( ) ; m_remain = count ; m_event = new ManualResetEvent ( false ) ; if ( m_remain == 0 ) { m_event.Set ( ) ; } } public void Signal ( ) { // The last thread to signal also sets the event . if ( Interlocked.Decrement ( ref m_remain ) == 0 ) m_event.Set ( ) ; } public void Wait ( ) { m_event.WaitOne ( ) ; } }",Does Interlocked guarantee visibility to other threads in C # or do I still have to use volatile ? "C_sharp : The following code has the disadvantage that the worker thread will neither terminate immediately nor perform a final action after the main thread resets the waithandle . Instead , it will continue doing what it is doing until it reaches the next iteration of the loop , at which point it will be blocked indefinitely.The following code has the disadvantage that it uses the Abort ( ) method ( there are people who say it should be avoided at all costs ) , but accomplishes exactly what I 'm looking for : force the worker thread to break out of the loop as soon as the main thread tells it to do so , perform a final operation , and exit.Since neither solution is ideal , what 's the proper way to implement the functionality I 'm looking for ? ( I 'd prefer a solution that does n't involve .net 4.5 's tasks ) static void Main ( ) { ManualResetEvent m = new ManualResetEvent ( true ) ; // or bool b = true Thread thread = new Thread ( new ThreadStart ( delegate ( ) { while ( m.WaitOne ( ) ) //or while ( b ) { //do something } //perform final operation and exit } ) ) ; thread.Start ( ) ; //do something m.Reset ( ) ; //or b = false //do something else } static void Main ( ) { Thread thread = new Thread ( new ThreadStart ( delegate ( ) { try { while ( true ) { //do something } } catch ( ThreadAbortException e ) { //perform final operation and exit } } ) ) ; thread.Start ( ) ; //do something thread.Abort ( ) ; //do something else }",what 's the proper way to tell a thread that is executing a loop to break out of the loop and do something else ? "C_sharp : The template method pattern provides that the abstract base class has a not overridable method : this method implements the common algorithm and should not overridden in the subclasses . In Java the template method is declared final within the abstract base class , in C # the sealed keyword has a similar meaning , but a not overridden method can not be declared sealed.How can I solve this problem ? Why can not prevent a method can be overridden by subclasses ( in C # ) ? public abstract class Base { protected abstract AlgorithmStep1 ( ) ; protected abstract AlgorithmStep2 ( ) ; public sealed void TemplateMethod ( ) // sealed : compile error { AlgorithmStep1 ( ) ; AlgorithmStep2 ( ) ; } }",Implementing the Template Method pattern in C # "C_sharp : I 'm working on an small C # ( WPF + SQLite ) application where I 'm implementing RadGridView from Telerik.I want to merge all columns where is the same ID like in the table . Right now my data looks like this ( this is my view ) .And this is what I want to achive in my RadGridView.The solution and the problem is merge option who radgridview has . But it mergers all data who are the same value . And it looks okay but the functionality is bad.It does what I sad but when I try to click the merged cell after double click it does this . ( In this example I clicked surname1 cell ) This is my radgridview , the red marked is where i double clicked , and the green cells are one who I want to not to merge + after clicking that row I want it to be selected . ╔════╤═══════╤══════════╤══════╗║ id │ ime │ surname │ year ║╠════╪═══════╪══════════╪══════╣║ 1 │ Name1 │ Surname1 │ 1994 ║╟────┼───────┼──────────┼──────╢║ 1 │ Name1 │ Surname1 │ 1995 ║╟────┼───────┼──────────┼──────╢║ 2 │ Name2 │ Surname2 │ 1996 ║╟────┼───────┼──────────┼──────╢║ 3 │ Name3 │ Surname3 │ 1996 ║╚════╧═══════╧══════════╧══════╝ ╔════╤═══════╤══════════╤═══════╗║ id │ ime │ surname │ year ║╠════╪═══════╪══════════╪═══════╣║ 1 │ Name1 │ Surname1 │ 1994 ║║ │ │ │ 1995 ║╟────┼───────┼──────────┼───────╢║ 2 │ Name2 │ Surname2 │ 1996 ║╟────┼───────┼──────────┼───────╢║ 3 │ Name3 │ Surname3 │ 1996 ║╚════╧═══════╧══════════╧═══════╝ ╔════╤═══════╤══════════╤═══════╗║ id │ ime │ surname │ year ║╠════╪═══════╪══════════╪═══════╣║ 1 │ Name1 │ Surname1 │ 1994 ║╟────────────┼──────────┤ 1995 ║║ │ Surname1 │ ║╟────────────┼──────────┼───────╢║ 2 │ Name2 │ Surname2 │ 1996 ║╟────┼───────┼──────────┼───────╢║ 3 │ Name3 │ Surname3 │ 1996 ║╚════╧═══════╧══════════╧═══════╝",Telerik radgridview merge/group "C_sharp : CongigureService ( ) { } I need here the other Authentication with AzureAD . ¿How ? The Configure Method of Startup.csWith this code , only can access the ADFS Token and this users , can obtains result from the controllers . However , the AzureAD user 's ca n't obtain accessI do n't know how make this code for double token authorization , and our controllers can response if one token is from ADFS or other token is from AzureAD I need the Authorize attribute in our Controller can accept two difernts tokens . One token , is provided from one private ADFS , and other token is provided from AzureAd . Several Ionic clients go to over ADFS , other Ionic clients go to over Azure AD My Dev Scenario : Asp.Net Core 2.2 WebApiMy actual startup.cs ( abreviated ) services.AddAuthentication ( JwtBearerDefaults.AuthenticationScheme ) .AddJwtBearer ( ( options = > { options.Audience = Configuration [ `` Adfs : Audience '' ] ; options.Authority = Configuration [ `` Adfs : Issuer '' ] ; options.SaveToken = true ; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false } ; } ) ) ; Configure ( … ) { app.UseAuthentication ( ) }",How add Two diferents Tokens in asp.net core webapi "C_sharp : Example text ( I 've highlighted the desired / 's ) : pair [ @ Key=2 ] /Items/Item [ Person/Name='Martin ' ] /DateI 'm trying to get each forward slash that is n't within a square bracket , anyone slick with Regex able to help me on this ? The use would be : I 've done it with this code , but was wondering if there was a simpler Regex that would do the same thing : string [ ] result = Regex.Split ( text , pattern ) ; private string [ ] Split ( ) { List < string > list = new List < string > ( ) ; int pos = 0 , i = 0 ; bool within = false ; Func < string > add = ( ) = > Format.Substring ( pos , i - pos ) ; //string a ; for ( ; i < Format.Length ; i++ ) { //a = add ( ) ; char c = Format [ i ] ; switch ( c ) { case '/ ' : if ( ! within ) { list.Add ( add ( ) ) ; pos = i + 1 ; } break ; case ' [ ' : within = true ; break ; case ' ] ' : within = false ; break ; } } list.Add ( add ( ) ) ; return list.Where ( s = > ! string.IsNullOrEmpty ( s ) ) .ToArray ( ) ; }",Get forward slash except within square brackets "C_sharp : https : //github.com/laravel/framework/blob/5.1/src/Illuminate/Encryption/Encrypter.phpi am using the code above , it works when i decrypt anything from Laravel . problem is when i encrypt a string from c # , i can not decrypt it in php.sometimes there are `` values '' after the decrypted text . encrypting the output , and decrypting it in php works . public static string Encrypt ( this string plainText ) { RijndaelManaged aes = new RijndaelManaged ( ) ; aes.KeySize = 256 ; aes.BlockSize = 128 ; aes.Padding = PaddingMode.Zeros ; aes.Mode = CipherMode.CBC ; aes.Key = Encoding.Default.GetBytes ( key ) ; aes.GenerateIV ( ) ; ICryptoTransform AESEncrypt = aes.CreateEncryptor ( aes.Key , aes.IV ) ; byte [ ] buffer = Encoding.ASCII.GetBytes ( plainText ) ; String encryptedText = Convert.ToBase64String ( Encoding.Default.GetBytes ( Encoding.Default.GetString ( AESEncrypt.TransformFinalBlock ( buffer , 0 , buffer.Length ) ) ) ) ; String mac = `` '' ; using ( var hmacsha256 = new HMACSHA256 ( Encoding.Default.GetBytes ( key ) ) ) { hmacsha256.ComputeHash ( Encoding.Default.GetBytes ( Convert.ToBase64String ( aes.IV ) + encryptedText ) ) ; mac = ByteArrToString ( hmacsha256.Hash ) ; } var keyValues = new Dictionary < string , object > { { `` iv '' , Convert.ToBase64String ( aes.IV ) } , { `` value '' , encryptedText } , { `` mac '' , mac } , } ; JavaScriptSerializer serializer = new JavaScriptSerializer ( ) ; //return serializer.Serialize ( keyValues ) ; return Convert.ToBase64String ( Encoding.ASCII.GetBytes ( serializer.Serialize ( keyValues ) ) ) ; } public static string Decrypt ( this string cipherText ) { RijndaelManaged aes = new RijndaelManaged ( ) ; aes.KeySize = 256 ; aes.BlockSize = 128 ; aes.Padding = PaddingMode.Zeros ; aes.Mode = CipherMode.CBC ; aes.Key = Encoding.Default.GetBytes ( key ) ; dynamic payload = GetJsonPayload ( cipherText ) ; //return Encoding.Default.GetString ( Convert.FromBase64String ( cipherText ) ) ; //cipherText = Convert.ToBase64String ( Encoding.Default.GetBytes ( payload [ `` value '' ] ) ) ; aes.IV = Convert.FromBase64String ( payload [ `` iv '' ] ) ; ICryptoTransform AESDecrypt = aes.CreateDecryptor ( aes.Key , aes.IV ) ; byte [ ] buffer = Convert.FromBase64String ( payload [ `` value '' ] ) ; return ( Encoding.Default.GetString ( AESDecrypt.TransformFinalBlock ( buffer , 0 , buffer.Length ) ) ) .ToString ( ) ; }",need help Converting laravel Crypt to C # "C_sharp : What 's C # 's equivalence of the following Python 's min/max code : It seems that C # 's Enumerable.Min is very close . But according to its MSDN doc , it always returns the minimizing VALUE ( not the original object ) . Am I missing anything ? EDITPlease note - I 'm not inclined to achieve this by sorting first , since sorting ( O ( nlogn ) ) is computationally heavier than finding the minimum ( O ( n ) ) .Please also note - Dictionary is not a desired approach either . It can not handle cases where there are duplicate keys - ( 1 , `` cat '' ) and ( 1 , `` tiger '' ) . More importantly , dictionary can not handle cases where the items to be processed is a complex class . E.g. , finding minimum over a list of animal objects , using age as the key : pairs = [ ( 2 , '' dog '' ) , ( 1 , `` cat '' ) , ( 3 , `` dragon '' ) , ( 1 , `` tiger '' ) ] # Returns the PAIR ( not the number ) that minimizes on pair [ 0 ] min_pair = min ( pairs , key=lambda pair : pair [ 0 ] ) # this will return ( 1 , 'cat ' ) , NOT 1 class Animal { public string name ; public int age ; }",What 's the C # equivalence of Python 's min/max "C_sharp : I Ca n't find [ Serializable ] in DNX Core 5.0I try with 'using System ' . Its working for DNX 4.5.1 but not for 5.0What packages should I add to make this work ? My Project json [ Serializable ] public class WorkItem { } { `` webroot '' : `` wwwroot '' , `` version '' : `` 1.0.0-* '' , `` dependencies '' : { `` Microsoft.AspNet.Server.IIS '' : `` 1.0.0-beta7 '' , `` Microsoft.AspNet.Server.WebListener '' : `` 1.0.0-beta7 '' , `` _my.DataAccess.Common '' : `` 1.0.0-* '' , `` _my.DependencyInjection.Common '' : `` 1.0.0-* '' , `` System.Runtime.Serialization '' : `` 4.0.0.0 '' } , `` commands '' : { `` web '' : `` Microsoft.AspNet.Hosting -- config hosting.ini '' } , `` frameworks '' : { `` dnx451 '' : { `` frameworkAssemblies '' : { `` System.Runtime.Serialization '' : `` 4.0.0.0 '' } } , `` dnxcore50 '' : { } } , `` publishExclude '' : [ `` node_modules '' , `` bower_components '' , `` **.xproj '' , `` **.user '' , `` **.vspscc '' ] , `` exclude '' : [ `` wwwroot '' , `` node_modules '' , `` bower_components '' ] }",I Ca n't find [ Serializable ] in DNX Core 5.0 C_sharp : I have following string : The / character is the separator between various elements in the string . I need to get the last two elements of the string . I have following code for this purpose . This works fine . Is there any faster/simpler code for this ? CODE string source = `` Test/Company/Business/Department/Logs.tvs/v1 '' ; static void Main ( ) { string component = String.Empty ; string version = String.Empty ; string source = `` Test/Company/Business/Department/Logs.tvs/v1 '' ; if ( ! String.IsNullOrEmpty ( source ) ) { String [ ] partsOfSource = source.Split ( '/ ' ) ; if ( partsOfSource ! = null ) { if ( partsOfSource.Length > 2 ) { component = partsOfSource [ partsOfSource.Length - 2 ] ; } if ( partsOfSource.Length > 1 ) { version = partsOfSource [ partsOfSource.Length - 1 ] ; } } } Console.WriteLine ( component ) ; Console.WriteLine ( version ) ; Console.Read ( ) ; },Getting substring between two separators in an arbitrary position "C_sharp : Case 1 : Case 2 : Are both cases identical ? My purpose is that : - I am copying a value to string variable.Converting string to bytes arrayusing Marshal.Alloc ( sizeofBytesArray ) to get IntPtr ptrToArraymarshal.copy ( array,0 , ptrToArray , sizeofBytesArray ) Sending this ptrToArray to a vb6 application by using a structure and passing structure via SendMessage win32 api.On VB6 app : -I am picking up the value from the structure that gives me the address of the array.using CopyMemory to copy the bytesarray data into a string..More Code : int i ; int* pi = & i ; int i ; IntPtr pi = & i ; string aString = text ; byte [ ] theBytes = System.Text.Encoding.Default.GetBytes ( aString ) ; // Marshal the managed struct to a native block of memory . int myStructSize = theBytes.Length ; IntPtr pMyStruct = Marshal.AllocHGlobal ( myStructSize ) ; //int* or IntPtr is good ? try { Marshal.Copy ( theBytes , 0 , pMyStruct , myStructSize ) ; ... ... ... ... ...",Pointer declaration syntax using & and Intptr . Are both identical ? "C_sharp : I 'm trying to insert 5 records into a SQL Server database table from DataGridView using C # .From my code it takes input of several records but insert only first record in database . Can anybody help me to save 5 records in database by a single click of save button ? Here is my code : DataSet ds = new DataSet ( ) ; SqlConnection cs = new SqlConnection ( @ '' Data Source=DELL-PC ; Initial Catalog=Image_DB ; Integrated Security=True '' ) ; SqlDataAdapter da = new SqlDataAdapter ( ) ; SqlCommand cmd = new SqlCommand ( ) ; BindingSource Input = new BindingSource ( ) ; DataView dview = new DataView ( ) ; private void Form1_Load ( object sender , EventArgs e ) { //create a DataGridView Image Column DataGridViewImageColumn dgvImage = new DataGridViewImageColumn ( ) ; //set a header test to DataGridView Image Column dgvImage.HeaderText = `` Images '' ; dgvImage.ImageLayout = DataGridViewImageCellLayout.Stretch ; DataGridViewTextBoxColumn dgvId = new DataGridViewTextBoxColumn ( ) ; dgvId.HeaderText = `` ID '' ; DataGridViewTextBoxColumn dgvName = new DataGridViewTextBoxColumn ( ) ; dgvName.HeaderText = `` Name '' ; dataGridView1.Columns.Add ( dgvId ) ; dataGridView1.Columns.Add ( dgvName ) ; dataGridView1.Columns.Add ( dgvImage ) ; dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill ; dataGridView1.RowTemplate.Height = 120 ; dataGridView1.AllowUserToAddRows = false ; } // button add data to dataGridView // insert image from pictureBox to dataGridView private void btn_Add_Click ( object sender , EventArgs e ) { MemoryStream ms = new MemoryStream ( ) ; pictureBox1.Image.Save ( ms , pictureBox1.Image.RawFormat ) ; byte [ ] img = ms.ToArray ( ) ; dataGridView1.Rows.Add ( txt_UserID.Text , txt_Name.Text , img ) ; } // browse image in pictureBox1 Click private void pictureBox1_Click ( object sender , EventArgs e ) { OpenFileDialog opf = new OpenFileDialog ( ) ; opf.Filter = `` Choose Image ( *.jpg ; *.png ; *.gif ) |*.jpg ; *.png ; *.gif '' ; if ( opf.ShowDialog ( ) == DialogResult.OK ) { pictureBox1.Image = Image.FromFile ( opf.FileName ) ; } } private void btn_Save_Click ( object sender , EventArgs e ) { for ( int i = 5 ; i < dataGridView1.Rows.Count ; i++ ) { string col1 = dataGridView1 [ 0 , dataGridView1.CurrentCell.RowIndex ] .Value.ToString ( ) ; string col2 = dataGridView1 [ 1 , dataGridView1.CurrentCell.RowIndex ] .Value.ToString ( ) ; string col3 = dataGridView1 [ 2 , dataGridView1.CurrentCell.RowIndex ] .Value.ToString ( ) ; string insert_sql = `` INSERT INTO Input ( UserID , UserName , PassImage ) VALUES ( ' '' + col1 + `` ' , ' '' + col2 + `` ' , ' '' + col3 + `` ' ) '' ; this.getcom ( insert_sql ) ; } MessageBox.Show ( `` Record Added '' ) ; } public SqlConnection GetSqlConnection ( ) //connection function { string str_sqlcon = `` Data Source=DELL-PC ; Initial Catalog=Image_DB ; Integrated Security=True '' ; SqlConnection mycon = new SqlConnection ( str_sqlcon ) ; mycon.Open ( ) ; return mycon ; } public void getcom ( string sqlstr ) //function for adding rows { SqlConnection sqlcon = this.GetSqlConnection ( ) ; // Watch out same string type as GetSQLConnection function SqlCommand sqlcom = new SqlCommand ( sqlstr , sqlcon ) ; sqlcom.ExecuteNonQuery ( ) ; sqlcom.Dispose ( ) ; sqlcon.Close ( ) ; sqlcon.Dispose ( ) ; }",How to store multiple records in SQL Server using DataGridView "C_sharp : I need to provide xml file for download around with 6,00,000 records ( data may increase ) but not allowed to save file on disk.I was facing issue in directly writing xml to stream & then providing for download , so i have first created xml file on disk & writing data to it and trying to read it in byes & provide for download and then delete file from disk . But getting `` system.outofmemoryexception '' in `` Byte [ ] b = File.ReadAllBytes ( filepath ) ; '' .Below is my code : Is there any other way to handle large number of records ? string name = string.Format ( `` { 0 : yyyyMMddHHmmss } '' , DateTime.Now ) ; string filename = `` TestFile.xml '' ; string filepath = ConfigurationManager.AppSettings [ `` XmlFiles '' ] + `` \\ '' + filename ; DataTable dataTable = dsData.Tables [ 0 ] ; FileStream fs =new FileStream ( filepath , FileMode.Create ) ; XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true } ; using ( XmlWriter xmlWriter = XmlWriter.Create ( fs , xws ) ) { xmlWriter.WriteStartElement ( `` root '' ) ; foreach ( DataRow dataRow in dataTable.Rows ) { xmlWriter.WriteStartElement ( `` datanode '' ) ; foreach ( DataColumn dataColumn in dataTable.Columns ) { xmlWriter.WriteElementString ( dataColumn.ColumnName.Replace ( `` \n\r '' , `` `` ) .Replace ( `` \n '' , `` `` ) .Replace ( `` \r '' , `` `` ) , Convert.ToString ( dataRow [ dataColumn ] ) .Replace ( `` \n\r '' , `` `` ) .Replace ( `` \n '' , `` `` ) .Replace ( `` \r '' , `` `` ) ) ; } xmlWriter.WriteEndElement ( ) ; } xmlWriter.WriteEndElement ( ) ; xmlWriter.Flush ( ) ; xmlWriter.Close ( ) ; } fs.Close ( ) ; Byte [ ] b = File.ReadAllBytes ( filepath ) ; if ( File.Exists ( filepath ) ) File.Delete ( filepath ) ; string s = string.Format ( `` { 0 : yyyyMMddHHmmss } '' , DateTime.Now ) ; HttpContext.Current.Response.ContentType = `` application/xml '' ; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8 ; HttpContext.Current.Response.AppendHeader ( `` Content-Disposition '' , `` attachment ; filename= '' + s + `` .xml '' + `` '' ) ; HttpContext.Current.Response.BinaryWrite ( b ) ; HttpContext.Current.Response.End ( ) ;",Provide XML file for download with large number of records in asp.net c # "C_sharp : Suppose I have the following code : What is the .NET runtime actually doing here ? Is it parsing and converting the attributes to integers each of the 100 times , or is it smart enough to figure out that it should cache the parsed values and not repeat the computation for each element in the range ? Moreover , how would I go about figuring out something like this myself ? Thanks in advance for your help . var X = XElement.Parse ( @ '' < ROOT > < MUL v= ' 2 ' / > < MUL v= ' 3 ' / > < /ROOT > '' ) ; Enumerable.Range ( 1 , 100 ) .Select ( s = > X.Elements ( ) .Select ( t = > Int32.Parse ( t.Attribute ( `` v '' ) .Value ) ) .Aggregate ( s , ( t , u ) = > t * u ) ) .ToList ( ) .ForEach ( s = > Console.WriteLine ( s ) ) ;",Does LINQ cache computed values ? "C_sharp : Okay one more function that it 's not yet working . I am basically calling some C++ functions from C # by using P/Invoke . The problematic function does query a show laser device for some device related information , such as minimal and maximal scan rates and maximal points per second.The problematic function is : Here 's the C++ header file that I was given . That 's a link to the very brief C++ SDK description . I do n't have the sources to rebuild the DLL file and I also do n't have the *.pdb file ( the manufacturer can not supply it ) : This is the complete C # test code I am currently using . All the functions work fine , except for GetDeviceInfo ( ... ) : On line 73 line 64 ( cp . screenshot ) : I receive the following error : This is the stack trace ( ca n't provide better stack trace without the DLL 's *.pdb file I guess ) : MonchaTestSDK.exe ! MonchaTestSDK.Program.Main ( string [ ] args ) Line 73 + 0xa bytes C # mscoreei.dll ! 73a8d91b ( ) [ Frames below may be incorrect and/or missing , no symbols loaded for mscoreei.dll ] mscoree.dll ! 73cae879 ( ) mscoree.dll ! 73cb4df8 ( ) kernel32.dll ! 74a08654 ( ) ntdll.dll ! 77354b17 ( ) ntdll.dll ! 77354ae7 ( ) Some disassembly : Any idea what I am doing wrong here ? Update 1 : Suggested debug options : As suggested in the comments , I tried to enable native/unmanaged code debugging : Debug > Windows > Exceptions Settings > `` Win32 Exceptions '' checkbox ticked Project > Properties > Debug tab > `` Enable unmanaged code debugging '' checkbox ticked I still do n't get any meaningful exception stack . The manufacturer ca n't supply me the DLL 's *.pdb file.Here 's an image showing the debugger when stopped at the problematic line ( debug settings are also shown ) : Update 2 : Minimal Required Code ( cp . comment of mpromonet ) This is the minimal required code to be able to call GetDeviceInfo ( ... ) : This leads to the exact same error as before : Removing the call GetDeviceInfo ( 0 , ref pDevInfo ) ; from the code above allows the program to exit without any error.Update 3 : Removing char [ ] deviceType from DeviceInfo struct completelyI removed char [ ] deviceType from the struct defintion : When I run my C # test code now , I successfully receive maxScanrate , minScanrate and maxNumOfPoints back from the C++ DLL . Here 's the corresponding console output : Finally ending in the following error message : Exception thrown at 0x67623A68 ( clr.dll ) in MonchaTestSDK.exe : 0xC0000005 : Access violation reading location 0x00000000.Final UpdateI finally got an updated DLL from the manufacturer . There was indeed a bug within the SDK that caused the stack to get corrupted . So basically the following solution now works fine without any issues : Thank you all for the great support ! int GetDeviceInfo ( DWORD deviceIndex , DeviceInfo* pDeviceInfo ) ; # pragma once # ifdef STCL_DEVICES_DLL # define STCL_DEVICES_EXPORT extern `` C '' _declspec ( dllexport ) # else # define STCL_DEVICES_EXPORT extern `` C '' _declspec ( dllimport ) # endifenum SD_ERR { SD_ERR_OK = 0 , SD_ERR_FAIL , SD_ERR_DLL_NOT_OPEN , SD_ERR_INVALID_DEVICE , //device with such index does n't exist SD_ERR_FRAME_NOT_SENT , } ; # pragma pack ( 1 ) struct LaserPoint { WORD x ; WORD y ; byte colors [ 6 ] ; } ; struct DeviceInfo { DWORD maxScanrate ; DWORD minScanrate ; DWORD maxNumOfPoints ; char type [ 32 ] ; } ; /////////////////////////////////////////////////////////////////////////////Must be called when starting to use//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int OpenDll ( ) ; /////////////////////////////////////////////////////////////////////////////All devices will be closed and all resources deleted//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT void CloseDll ( ) ; /////////////////////////////////////////////////////////////////////////////Search for .NET devices ( Moncha.NET now ) ///Must be called after OpenDll , but before CreateDeviceList ! ///In pNumOfFoundDevs can return number of found devices ( optional ) //////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int SearchForNETDevices ( DWORD* pNumOfFoundDevs ) ; /////////////////////////////////////////////////////////////////////////////Creates new list of devices - previous devices will be closed///pDeviceCount returns device count//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int CreateDeviceList ( DWORD* pDeviceCount ) ; /////////////////////////////////////////////////////////////////////////////Returns unique device name///deviceIndex is zero based device index//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int GetDeviceIdentifier ( DWORD deviceIndex , WCHAR** ppDeviceName ) ; /////////////////////////////////////////////////////////////////////////////Send frame to device , frame is in following format : ///WORD x///WORD y///byte colors [ 6 ] ///so it 's 10B point ( = > dataSize must be numOfPoints * 10 ) ///scanrate is in Points Per Second ( pps ) //////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int SendFrame ( DWORD deviceIndex , byte* pData , DWORD numOfPoints , DWORD scanrate ) ; /////////////////////////////////////////////////////////////////////////////Returns true in pCanSend if device is ready to send next frame//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int CanSendNextFrame ( DWORD deviceIndex , bool* pCanSend ) ; /////////////////////////////////////////////////////////////////////////////Send DMX if device supports it - pDMX must be ( ! ! ! ) 512B long//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int SendDMX ( DWORD deviceIndex , byte* pDMX ) ; /////////////////////////////////////////////////////////////////////////////Send blank point to position x , y//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int SendBlank ( DWORD deviceIndex , WORD x , WORD y ) ; /////////////////////////////////////////////////////////////////////////////Get device info//////////////////////////////////////////////////////////////////////////STCL_DEVICES_EXPORT int GetDeviceInfo ( DWORD deviceIndex , DeviceInfo* pDeviceInfo ) ; using System ; using System.Threading ; using System.Runtime.InteropServices ; namespace MonchaTestSDK { public class Program { [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern int OpenDll ( ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern void CloseDll ( ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern int SearchForNETDevices ( ref UInt32 pNumOfFoundDevs ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern int CreateDeviceList ( ref UInt32 pDeviceCount ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern int GetDeviceIdentifier ( UInt32 deviceIndex , out IntPtr ppDeviceName ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern int SendFrame ( UInt32 deviceIndex , LaserPoint [ ] pData , UInt32 numOfPoints , UInt32 scanrate ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern int CanSendNextFrame ( UInt32 deviceIndex , ref bool pCanSend ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // OK public static extern int SendBlank ( UInt32 deviceIndex , UInt16 x , UInt16 y ) ; [ DllImport ( `` ..\\..\\dll\\StclDevices.dll '' , CallingConvention = CallingConvention.Cdecl ) ] // FAILS public static extern int GetDeviceInfo ( UInt32 deviceIndex , ref DeviceInfo pDeviceInfo ) ; [ StructLayout ( LayoutKind.Sequential , Pack=1 ) ] public struct LaserPoint { public UInt16 x ; public UInt16 y ; [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 6 ) ] public byte [ ] colors ; } [ StructLayout ( LayoutKind.Sequential , CharSet=CharSet.Ansi ) ] public struct DeviceInfo { public UInt32 maxScanrate ; public UInt32 minScanrate ; public UInt32 maxNumOfPoints ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 32 ) ] public string deviceType ; } public static void Main ( string [ ] args ) { Console.WriteLine ( `` Moncha SDK\n '' ) ; OpenDll ( ) ; Console.WriteLine ( `` StclDevices.dll is open . `` ) ; UInt32 deviceCount1 = 0 ; int r1 = SearchForNETDevices ( ref deviceCount1 ) ; Console.WriteLine ( `` SearchForNETDevices ( ) [ `` + r1+ '' ] : `` +deviceCount1 ) ; UInt32 deviceCount2 = 0 ; int r2 = CreateDeviceList ( ref deviceCount2 ) ; Console.WriteLine ( `` CreateDeviceList ( ) [ `` +r2+ '' ] : `` +deviceCount2 ) ; IntPtr pString ; int r3 = GetDeviceIdentifier ( 0 , out pString ) ; string devname = Marshal.PtrToStringUni ( pString ) ; Console.WriteLine ( `` GetDeviceIdentifier ( ) [ `` +r3+ '' ] : `` +devname ) ; DeviceInfo pDevInfo = new DeviceInfo ( ) ; pDevInfo.type = `` '' ; int r4 = GetDeviceInfo ( 0 , ref pDevInfo ) ; Console.WriteLine ( `` GetDeviceInfo ( ) [ `` +r4+ '' ] : `` ) ; Console.WriteLine ( `` - min : `` +pDevInfo.minScanrate ) ; Console.WriteLine ( `` - max : `` + pDevInfo.maxScanrate ) ; Console.WriteLine ( `` - points : `` + pDevInfo.maxNumOfPoints ) ; Console.WriteLine ( `` - type : `` + pDevInfo.deviceType ) ; Thread.Sleep ( 5000 ) ; CloseDll ( ) ; } } } int r4 = GetDeviceInfo ( 0 , ref pDevInfo ) ; An unhandled exception of type 'System.NullReferenceException ' occured in MonchaTestSDK.exeAdditional information : Object reference not set to an instance of an object int r4 = GetDeviceInfo ( 0 , ref pDevInfo ) ; 05210749 int 3 0521074A push ebp 0521074B cwde 0521074C xor ecx , ecx 0521074E call 0521011C 05210753 int 3 05210754 test dword ptr [ eax-1 ] , edx 05210757 ? ? ? ? 05210758 dec dword ptr [ ebx-0AF7Bh ] 0521075E dec dword ptr [ ecx-6F466BBBh ] public static void Main ( string [ ] args ) { OpenDll ( ) ; UInt32 deviceCount = 0 ; CreateDeviceList ( ref deviceCount ) ; DeviceInfo pDevInfo = new DeviceInfo ( ) ; GetDeviceInfo ( 0 , ref pDevInfo ) ; // error occurs on this line CloseDll ( ) ; } An unhandled exception of type 'System.NullReferenceException ' occured in MonchaTestSDK.exeAdditional information : Object reference not set to an instance of an object [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Ansi , Pack = 1 ) ] public struct DeviceInfo { public UInt32 maxScanrate ; public UInt32 minScanrate ; public UInt32 maxNumOfPoints ; // [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 32 ) ] //public string deviceType ; } GetDeviceInfo ( ) [ 0 ] : - min : 1000 - max : 40000 - points : 3000 [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Ansi , Pack = 1 ) ] public struct DeviceInfo { public UInt32 maxScanrate ; public UInt32 minScanrate ; public UInt32 maxNumOfPoints ; [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 32 ) ] public string deviceType ; } private void queryDeviceProperties ( UInt32 index ) { HwDeviceInfo pDevInfo = new HwDeviceInfo ( ) ; int code = GetDeviceInfo ( index , ref pDevInfo ) ; if ( code==0 ) { Console.WriteLine ( pDevInfo.minScanrate ) ; Console.WriteLine ( pDevInfo.maxScanrate ) ; Console.WriteLine ( pDevInfo.maxNumOfPoints ) ; Console.WriteLine ( pDevInfo.type ) ; } else { Console.WriteLine ( `` Error Code : `` +code ) ; } }",How to call a C++ function with a struct pointer parameter from C # ? "C_sharp : Consider the collectionThe question is : How can I write a LINQ query to group Person on Age and then count number of person with in each group having the same name ? I tried using group by operator , nested queries all possibilities still could not figure out the exact query . Regards , Jeez List < Person > people = new List < Person > { new Person { Name = `` A '' , SSN= '' 1 '' , Age = 23 } , new Person { Name = `` A '' , SSN= '' 2 '' , Age = 23 } , new Person { Name = `` B '' , SSN= '' 3 '' , Age = 24 } , new Person { Name = `` C '' , SSN= '' 4 '' , Age = 24 } , new Person { Name = `` D '' , SSN= '' 5 '' , Age = 23 } } ;",complex LINQ query "C_sharp : I searched a lot on my performance problem and tried all sorts of different things , but I just ca n't seem to get it to work fast enough . Here 's my problem to it 's simplest form : I 'm using entity framework 5 and I want to be able to lazy load child instances of a parent when the user selects that parent , so I do n't have to pull the entire database . However I have been having performance problems with lazy loading the children . I think the problem is the wire up of the navigation properties between the Parent and the children . I 'm also thinking it must be something I did wrong because I believe this is a simple case.So I put up a program to test a single lazy load to isolate the problem.Here 's the Test : I created a POCO Parent class and a Child POCO Class . Parent has n Children and Child has 1 Parent . There 's only 1 parent in the SQL Server database and 25 000 children for that single parent . I tried different methods to load this data . Whenever I load either the children and the parent in the same DbContext , it takes a really long time . But if I load them in different DbContexts , it loads really fast . However , I want those instances to be in the same DbContext.Here is my test setup and everything you need to replicate it : POCOs : DbContext : TSQL Script to create the Database and data : App.config containing the connection string : Test console class : Here are the results of those test : Load only the parent from DbSet:0,972 secondsLoad only the children from DbSet:0,714 secondsLoad the parent from DbSet:0,001 seconds , then load the children from DbSet:8,6026 secondsLoad the children from DbSet:0,6864 seconds , then load the parent from DbSet:7,5816159 secondsLoad the parent from DbSet:0 seconds , then load the children from Parent 's lazy loaded navigation property:8,5644549 secondsLoad the parent from DbSet and children from include:8,6428788 secondsLoad the parent from DbSet and children from include:9,1416586 seconds with everything turned offAnalysisWhenever the parent and the children are in the same DbContext , it takes a long time ( 9 seconds ) to wire everything up . I even tried turning off everything from proxy creation to lazy loading , but to no avail . Can someone please help me ? public class Parent { public int ParentId { get ; set ; } public string Name { get ; set ; } public virtual List < Child > Childs { get ; set ; } } public class Child { public int ChildId { get ; set ; } public int ParentId { get ; set ; } public string Name { get ; set ; } public virtual Parent Parent { get ; set ; } } public class Entities : DbContext { public DbSet < Parent > Parents { get ; set ; } public DbSet < Child > Childs { get ; set ; } } USE [ master ] GOIF EXISTS ( SELECT name FROM sys.databases WHERE name = 'PerformanceParentChild ' ) alter database [ PerformanceParentChild ] set single_user with rollback immediate DROP DATABASE [ PerformanceParentChild ] GOCREATE DATABASE [ PerformanceParentChild ] GOUSE [ PerformanceParentChild ] GOBEGIN TRAN T1 ; SET NOCOUNT ONCREATE TABLE [ dbo ] . [ Parents ] ( [ ParentId ] [ int ] CONSTRAINT PK_Parents PRIMARY KEY , [ Name ] [ nvarchar ] ( 200 ) NULL ) GOCREATE TABLE [ dbo ] . [ Children ] ( [ ChildId ] [ int ] CONSTRAINT PK_Children PRIMARY KEY , [ ParentId ] [ int ] NOT NULL , [ Name ] [ nvarchar ] ( 200 ) NULL ) GOINSERT INTO Parents ( ParentId , Name ) VALUES ( 1 , 'Parent ' ) DECLARE @ nbChildren int ; DECLARE @ childId int ; SET @ nbChildren = 25000 ; SET @ childId = 0 ; WHILE @ childId < @ nbChildrenBEGIN SET @ childId = @ childId + 1 ; INSERT INTO [ dbo ] . [ Children ] ( ChildId , ParentId , Name ) VALUES ( @ childId , 1 , 'Child # ' + convert ( nvarchar ( 5 ) , @ childId ) ) ENDCREATE NONCLUSTERED INDEX [ IX_ParentId ] ON [ dbo ] . [ Children ] ( [ ParentId ] ASC ) GOALTER TABLE [ dbo ] . [ Children ] ADD CONSTRAINT [ FK_Children.Parents_ParentId ] FOREIGN KEY ( [ ParentId ] ) REFERENCES [ dbo ] . [ Parents ] ( [ ParentId ] ) GOCOMMIT TRAN T1 ; < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < connectionStrings > < add name= '' Entities '' providerName= '' System.Data.SqlClient '' connectionString= '' Server=localhost ; Database=PerformanceParentChild ; Trusted_Connection=true ; '' / > < /connectionStrings > < /configuration > class Program { static void Main ( string [ ] args ) { List < Parent > parents ; List < Child > children ; Entities entities ; DateTime before ; TimeSpan childrenLoadElapsed ; TimeSpan parentLoadElapsed ; using ( entities = new Entities ( ) ) { before = DateTime.Now ; parents = entities.Parents.ToList ( ) ; parentLoadElapsed = DateTime.Now - before ; System.Diagnostics.Debug.WriteLine ( `` Load only the parent from DbSet : '' + parentLoadElapsed.TotalSeconds + `` seconds '' ) ; } using ( entities = new Entities ( ) ) { before = DateTime.Now ; children = entities.Childs.ToList ( ) ; childrenLoadElapsed = DateTime.Now - before ; System.Diagnostics.Debug.WriteLine ( `` Load only the children from DbSet : '' + childrenLoadElapsed.TotalSeconds + `` seconds '' ) ; } using ( entities = new Entities ( ) ) { before = DateTime.Now ; parents = entities.Parents.ToList ( ) ; parentLoadElapsed = DateTime.Now - before ; before = DateTime.Now ; children = entities.Childs.ToList ( ) ; childrenLoadElapsed = DateTime.Now - before ; System.Diagnostics.Debug.WriteLine ( `` Load the parent from DbSet : '' + parentLoadElapsed.TotalSeconds + `` seconds '' + `` , then load the children from DbSet : '' + childrenLoadElapsed.TotalSeconds + `` seconds '' ) ; } using ( entities = new Entities ( ) ) { before = DateTime.Now ; children = entities.Childs.ToList ( ) ; childrenLoadElapsed = DateTime.Now - before ; before = DateTime.Now ; parents = entities.Parents.ToList ( ) ; parentLoadElapsed = DateTime.Now - before ; System.Diagnostics.Debug.WriteLine ( `` Load the children from DbSet : '' + childrenLoadElapsed.TotalSeconds + `` seconds '' + `` , then load the parent from DbSet : '' + parentLoadElapsed.TotalSeconds + `` seconds '' ) ; } using ( entities = new Entities ( ) ) { before = DateTime.Now ; parents = entities.Parents.ToList ( ) ; parentLoadElapsed = DateTime.Now - before ; before = DateTime.Now ; children = parents [ 0 ] .Childs ; childrenLoadElapsed = DateTime.Now - before ; System.Diagnostics.Debug.WriteLine ( `` Load the parent from DbSet : '' + parentLoadElapsed.TotalSeconds + `` seconds '' + `` , then load the children from Parent 's lazy loaded navigation property : '' + childrenLoadElapsed.TotalSeconds + `` seconds '' ) ; } using ( entities = new Entities ( ) ) { before = DateTime.Now ; parents = entities.Parents.Include ( p = > p.Childs ) .ToList ( ) ; parentLoadElapsed = DateTime.Now - before ; System.Diagnostics.Debug.WriteLine ( `` Load the parent from DbSet and children from include : '' + parentLoadElapsed.TotalSeconds + `` seconds '' ) ; } using ( entities = new Entities ( ) ) { entities.Configuration.ProxyCreationEnabled = false ; entities.Configuration.AutoDetectChangesEnabled = false ; entities.Configuration.LazyLoadingEnabled = false ; entities.Configuration.ValidateOnSaveEnabled = false ; before = DateTime.Now ; parents = entities.Parents.Include ( p = > p.Childs ) .ToList ( ) ; parentLoadElapsed = DateTime.Now - before ; System.Diagnostics.Debug.WriteLine ( `` Load the parent from DbSet and children from include : '' + parentLoadElapsed.TotalSeconds + `` seconds with everything turned off '' ) ; } } }",CodeFirst loading 1 parent linked to 25 000 children is slow "C_sharp : I had a discussion today about refactoring this ( # 1 ) With this ( # 2 ) My intuition was that # 1 was better for the following reasons : # 1 is simpler than # 2 in the sense that it requires no knowledge of Util library , just basic c # knowledge # 1 will not remove the resharper ability to rename the string passed to ArgumentNullException constructor. # 2 will increase the dependencies for the code ( must have access to the dll containing the dll ) The stacktrace will not be the same for # 2 as it would be for # 1My questions here are : Is my intuition correct ? Could the fact that we are throwing the exception from another assembly not become trouble in some scenarios ? public void MyFunc ( object myArgument ) { if ( myArgument == null ) throw new ArgumentNullException ( `` myArgument '' ) ; ... . //inside a shared assembly in a class called Guardpublic static void AgainstArgumentNull ( object obj , string message ) { if ( obj == null ) throw new ArgumentNullException ( message ) ; } public void MyFunc ( object myArgument ) { Guard.AgainstArgumentNull ( myArgument , `` myArgument '' ) ; ... .","Throwing exception in c # , guard" "C_sharp : We have a DataGridView with data in a form . To enable quick search , we added TextBox to DataGridView.Controls and highlight cells which contain text from TextBox.However , there is an issue . DataGridView consumes the Left arrow ← , Right arrow → , Home and End ( with or without Shift ) keys even if the cursor is in TextBox , and the user can not change the caret position or select text from the keyboard.TextBox generates a PreviewKeyDown event and nothing more happens.Simplified code : Type 123 in TextBox and then try the Right arrow , Left arrow , End , or Home . DataGridView change the selected cell , but the TextBox caret does n't move.TextBox works just fine if not inside a DataGridView ( no problem at all when using the same method adding it into TreeView for example ) . TextBox acts similar to the Quick search Panel in the browser and has to be on top of the DataGridView . Adding a TextBox to a Form ( or to be more specific , to a DataGridView parent ) creates its own set of issues ( tracking Location , Size , Visibility , ... ) and is not acceptable.What can be done to make sure that TextBox receive those keys and change the caret position or select text ? public partial class TestForm : Form { public TestForm ( ) { InitializeComponent ( ) ; Width = 400 ; Height = 400 ; var txt = new TextBox { Dock = DockStyle.Bottom , BackColor = Color.Khaki } ; var dgv = new DataGridView { Dock = DockStyle.Fill , ColumnCount = 3 , RowCount = 5 } ; dgv.Controls.Add ( txt ) ; Controls.Add ( dgv ) ; dgv.PreviewKeyDown += DgvOnPreviewKeyDown ; dgv.KeyDown += DgvOnKeyDown ; txt.PreviewKeyDown += TxtOnPreviewKeyDown ; txt.KeyDown += TxtOnKeyDown ; } private void DgvOnPreviewKeyDown ( object sender , PreviewKeyDownEventArgs e ) { Debug.WriteLine ( String.Format ( `` Dgv Key Preview { 0 } '' , e.KeyCode ) ) ; e.IsInputKey = true ; } private void DgvOnKeyDown ( object sender , KeyEventArgs e ) { Debug.WriteLine ( String.Format ( `` Dgv Key { 0 } '' , e.KeyCode ) ) ; } private void TxtOnPreviewKeyDown ( object sender , PreviewKeyDownEventArgs e ) { Debug.WriteLine ( String.Format ( `` Txt Key Preview { 0 } '' , e.KeyCode ) ) ; } private void TxtOnKeyDown ( object sender , KeyEventArgs e ) { Debug.WriteLine ( String.Format ( `` Txt Key { 0 } '' , e.KeyCode ) ) ; } }",Handle navigation keys in TextBox inside DataGridView "C_sharp : If I 'm creating a dynamic type like so : Is it possible to set the GetAccessor method to an expression tree . They 're much easier to work with than straight IL . TypeBuilder dynaType = dynaModule.DefineType ( typeof ( T ) .Name + `` _ORMProxy '' ) ; dynaType.AddInterfaceImplementation ( typeof ( IServiceTable ) ) ; // ( 1 ) Implement : ( String ) IServiceTable.TableName { get ; } FieldBuilder tableNameField = dynaType.DefineField ( `` tableName '' , typeof ( String ) , FieldAttributes.Private ) ; MethodBuilder tableNamePublicGetAccessor = dynaType.DefineMethod ( `` get_tableName '' , MethodAttributes.Public ) ; tableNamePublicGetAccessor ...",Is it possible to use an expression tree to define a method body for dynamic types ? "C_sharp : I 've recently started experimenting with PostSharp and I found a particularly helpful aspect to automate implementation of INotifyPropertyChanged . You can see the example here . The basic functionality is excellent ( all properties will be notified ) , but there are cases where I might want to suppress notification.For instance , I might know that a particular property is set once in the constructor and will never change again . As such , there is no need to emit the code for NotifyPropertyChanged . The overhead is minimal when classes are not frequently instantiated and I can prevent the problem by switching from an automatically generated property to a field-backed property and writing to the field . However , as I 'm learning this new tool , it would be helpful to know if there is a way to tag a property with an attribute to suppress the code generation . I 'd like to be able to do something like this : [ NotifyPropertyChanged ] public class MyClass { public double SomeValue { get ; set ; } public double ModifiedValue { get ; private set ; } [ SuppressNotify ] public double OnlySetOnce { get ; private set ; } public MyClass ( ) { OnlySetOnce = 1.0 ; } }",Suppressing PostSharp Multicast with Attribute "C_sharp : I use EF 4.2 code first in my mvc3 project.miniprofiler works fine ( sql + mvc ) , but I 've got an issue with async tasks.I perform 'em this way ( is this method ok ? I feel a bit uneasy with this new DatabaseContext ( ) ) I 've got proper line in Application_Start : The excpetion is thrown during the first operation with db in action ( consistantUser ) ; here is the trace : at MvcMiniProfiler.MiniProfiler.AddSqlTiming ( SqlTiming stats ) in C : \Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\MiniProfiler.cs : line 274 at MvcMiniProfiler.SqlTiming..ctor ( DbCommand command , ExecuteType type , MiniProfiler profiler ) in C : \Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\SqlTiming.cs : line 137 at MvcMiniProfiler.SqlProfiler.ExecuteStartImpl ( DbCommand command , ExecuteType type ) in C : \Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs : line 39 at MvcMiniProfiler.SqlProfilerExtensions.ExecuteStart ( SqlProfiler sqlProfiler , DbCommand command , ExecuteType type ) in C : \Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\SqlProfiler.cs : line 93 at MvcMiniProfiler.MiniProfiler.MvcMiniProfiler.Data.IDbProfiler.ExecuteStart ( DbCommand profiledDbCommand , ExecuteType executeType ) in C : \Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\MiniProfiler.IDbProfiler.cs : line 14 at MvcMiniProfiler.Data.ProfiledDbCommand.ExecuteDbDataReader ( CommandBehavior behavior ) in C : \Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbCommand.cs : line 158 at System.Data.Common.DbCommand.ExecuteReader ( CommandBehavior behavior ) at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands ( EntityCommand entityCommand , CommandBehavior behavior ) what am I doing wrong ? Any help will be appreciated.EDIT : I tried to initialize MiniProfiler ( MiniProfilerEF.Initialize ( ) ; ) again , in the thread where backgroung task is performd ( before initiating DatabaseContext ) , and there is another exception now : Unable to cast object of type 'MvcMiniProfiler.Data.EFProfiledDbConnection ' to type 'System.Data.SqlClient.SqlConnectionIn fact , it 's not neccessary to profile the queries in the background thread , but it crashes the whole thread , so the application does n't work properly , and I have to disavble the whole profiler . Is there a way to disable it for that , background , thread to prevent it from crashing ? public static void PerformAsycAction ( this User user , Action < User > action ) { ThreadPool.QueueUserWorkItem ( _ = > { var context = new DatabaseContext ( ) ; MiniProfilerEF.Initialize ( ) ; var consistantUser = context.Set < User > ( ) .Get ( user.Id ) ; action ( consistantUser ) ; context.SaveChanges ( ) ; } ) ; } protected void Application_Start ( ) { MiniProfilerEF.Initialize ( ) ; ... }","MiniProfiler , EntityFramework code first and background tasks nullreference" "C_sharp : I have problem with date formate while hosting site which is developed using C # .net MVC .In my development machine ( OS : Windows 7 , .net Framework 4.5 ) date formate for Spanish-Panama ( es-PA ) is mm/dd/yy and in server machine ( OS : Windows 8 , .net Framework 4.5 ) it is giving d/m/yy format for same culture.I checked it with by using simple console application.Output on development machine is : 10/08/2015Output on server machine is : 8/10/15I also checked by changing Language and Regional but in both machine default format is different.Why format is different in different machine for same culture ? Is there any solution for this ? public static void Main ( ) { DateTime dt = DateTime.Now ; Thread.CurrentThread.CurrentCulture = new CultureInfo ( `` es-PA '' ) ; Console.WriteLine ( dt.ToString ( `` d '' ) ) ; Console.ReadLine ( ) ; }",Why is the date format different for the same culture on different computers or OS ? "C_sharp : In my ASP.NET MVC site , my set up allows users to have roles , and roles have permissions . Generally , these permissions are set for a controller . In my site 's main navigational menu , an Authenticated user can see all items , even if they are n't authorized to access that page . Currently I can only configure the menu based off if the user is authenticated : I 'm wondering , what 's the best way to pass the user 's permissions to a view , only for the sake of configuring the menu for that user ? Is there some common way of doing it , or will I have to implement this myself ? I have n't found much information on it , but maybe I 'm using the wrong search terms.Thanks for any advice.EDITSorry I may not have been clear enough . This is my main nav menu , in the _Layout page . Also , permissions assigned to a role are very configurable by an admin ( they can also create and delete roles ) , so checking if the user is in a role wo n't meet my needs . @ if ( Request.IsAuthenticated ) { }",Best Way To Access User Permissions From View "C_sharp : I want to build type dynamically like this : The code I write is : I think I had problem in building constructor and Depth property getter method.Please help me get out of this.Instance is not created as well.Thanks public class Sample { Sample Parent { get ; set ; } public Sample ( Sample parent ) { Parent = parent ; } public int Depth { get { if ( Parent == null ) return -1 ; else return Parent.Depth + 1 ; } } } const string assemblyName = `` SampleAssembly '' ; const string parentPproperty = `` Parent '' ; const string depthProperty = `` Depth '' ; const string typeName = `` Sample '' ; const string assemblyFileName = assemblyName + `` .dll '' ; AppDomain domain = AppDomain.CurrentDomain ; AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly ( new AssemblyName ( assemblyName ) , AssemblyBuilderAccess.RunAndSave ) ; ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule ( assemblyName , assemblyFileName ) ; TypeBuilder typeBuilder = moduleBuilder.DefineType ( typeName , TypeAttributes.Public ) ; FieldBuilder parentField = typeBuilder.DefineField ( $ '' _ { parentPproperty } '' , typeBuilder , FieldAttributes.Private ) ; PropertyBuilder propertyBuilder = typeBuilder.DefineProperty ( parentPproperty , PropertyAttributes.None , parentField.FieldType , Type.EmptyTypes ) ; MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig ; MethodBuilder getParentMethod = typeBuilder.DefineMethod ( $ '' get_ { propertyBuilder.Name } '' , getSetAttr , parentField.FieldType , Type.EmptyTypes ) ; ILGenerator il = getParentMethod.GetILGenerator ( ) ; il.Emit ( OpCodes.Ldarg_0 ) ; il.Emit ( OpCodes.Ldfld , parentField ) ; il.Emit ( OpCodes.Ret ) ; propertyBuilder.SetGetMethod ( getParentMethod ) ; MethodBuilder setParentMethod = typeBuilder.DefineMethod ( $ '' set_ { propertyBuilder.Name } '' , qetSetAttr , null , Type.EmptyTypes ) ; il = setParentMethod.GetILGenerator ( ) ; il.Emit ( OpCodes.Ldarg_0 ) ; il.Emit ( OpCodes.Ldarg_1 ) ; il.Emit ( OpCodes.Stfld , parentField ) ; il.Emit ( OpCodes.Ret ) ; propertyBuilder.SetSetMethod ( setParentMethod ) ; parentField = typeBuilder.DefineField ( $ '' _ { depthProperty } '' , typeBuilder , FieldAttributes.Private ) ; propertyBuilder = typeBuilder.DefineProperty ( depthProperty , PropertyAttributes.None , parentField.FieldType , Type.EmptyTypes ) ; MethodBuilder getDepthMethod = typeBuilder.DefineMethod ( $ '' get_ { depthProperty } '' , getSetAttr , parentField.FieldType , Type.EmptyTypes ) ; il = getDepthMethod.GetILGenerator ( ) ; LocalBuilder lb = il.DeclareLocal ( typeof ( bool ) ) ; il.Emit ( OpCodes.Ldarg_0 ) ; il.Emit ( OpCodes.Call , getParentMethod ) ; il.Emit ( OpCodes.Ldnull ) ; il.Emit ( OpCodes.Ceq ) ; il.Emit ( OpCodes.Stloc_0 ) ; il.Emit ( OpCodes.Ldloc_0 ) ; il.Emit ( OpCodes.Brfalse_S ) ; il.Emit ( OpCodes.Ldc_I4_1 ) ; il.Emit ( OpCodes.Stloc_1 ) ; il.Emit ( OpCodes.Br_S ) ; il.Emit ( OpCodes.Ldarg_0 ) ; il.Emit ( OpCodes.Call , getParentMethod ) ; il.Emit ( OpCodes.Callvirt , getDepthMethod ) ; il.Emit ( OpCodes.Ldc_I4_1 ) ; il.Emit ( OpCodes.Add ) ; il.Emit ( OpCodes.Stloc_1 ) ; il.Emit ( OpCodes.Br_S ) ; il.Emit ( OpCodes.Ldloc_1 ) ; il.Emit ( OpCodes.Ret ) ; propertyBuilder.SetGetMethod ( getDepthMethod ) ; ConstructorBuilder constructor = typeBuilder.DefineConstructor ( MethodAttributes.Public , CallingConventions.HasThis , new Type [ ] { typeBuilder } ) ; il= constructor.GetILGenerator ( ) ; il.Emit ( OpCodes.Ldarg_0 ) ; il.Emit ( OpCodes.Call , typeof ( object ) .GetConstructor ( Type.EmptyTypes ) ) ; il.Emit ( OpCodes.Ldarg_0 ) ; il.Emit ( OpCodes.Ldarg_1 ) ; il.Emit ( OpCodes.Call , setParentMethod ) ; il.Emit ( OpCodes.Ret ) ; Type type = typeBuilder.CreateType ( ) ; var obj1 = Activator.CreateInstance ( type , null ) ; var obj2 = Activator.CreateInstance ( type , obj1 ) ; assemblyBuilder.Save ( assemblyFileName ) ;",Reflection Emit for Property Getter "C_sharp : I 've looked around on SO , I ca n't find a sufficient answer to my question.I have a wrapper class called Title defined like thisI am using this class in an ASP MVC project . Right now I defined a controller like this : and this works fine.However , I wish to automatically bind the posted string value to the Title constructor , thus accepting a Title instead of a string as a parameter : This however , does not work , as I will get the error : The parameters dictionary contains a null entry for parameter , meaning the model binder ca n't bind the string to the Title parameter.The HTML responsible for posting the title data : My question exists of two parts:1 . Why is it not possible to do this , I would expect the bodel binder to use the defined implicit operator to create a Title instance.2 . Is there a way to still accomplish getting the desired behavior , without explicitly creating a modelbinder ? public class Title { private readonly string _title ; public Title ( string title ) { _title = title ; } public static implicit operator Title ( string title ) { return new Title ( title ) ; } } public ActionResult Add ( string title ) { //stuff } public ActionResult Add ( Title title ) { //stuff } < form method= '' post '' action= '' /Page/Add '' id= '' add-page-form '' > < div class= '' form-group '' > < label for= '' page-title '' > Page title < /label > < input type= '' text '' name= '' title '' id= '' page-title '' > < /div > < /form >",Binding a string to a parameter using an implicit operator in ASP MVC "C_sharp : I 'll start this by saying I 'm definitely working a bit above my paygrade here . I 'll be doing my best to describe this problem and make it easiest to answer.I 've made a Blazor project in Visual Studio and this is connected to the GitHub repository here in the gh-pages branch . After reading Blazor 's hosting and deploying guide here , I published the project in Visual Studio and copied the files in the /bin/Release/netstandard2.0/publish/ChargeLearning/dist folder to the root of the repository resulting in a repository with this file structure : At this point I think am already neck-deep in bad practice.Regardless , attempting to load the index.html results in 404 errors in the console for most of the files in the html header like bootstrap ( as the blazor deploying guide warned ) .So I followed the instructions there as best as I could , attempting to implement this single page app ( SPA ) fix for gh-pages linked in the guide.I added the 404.html file to the ChargeLearning repository now when I load the page it displays just one 404 error , for the blazor.webassembly.js file . I then add the redirect script from the SPA fix to my willthamic.github.io repository which when I open the direct url to the blazor.webassembly.js file seems to redirect properly but github shows my home page and I now realize that it has been severely mangled and now images are n't loading.I feel like I am doing a lot of things wrong here which makes it difficult to isolate and solve a single problem at once . If you have specific advice on how to properly deploy this or even small things on how to do what I 'm trying to do a little more properly I would greatly appreciate it.Thanks in advance . ChargeLearning ChargeLearning _content _framework css sample-data ChargeLearning.sln index.html",Properly publishing/deploying a blazor project to github pages C_sharp : if I have the following bool : Will the following three lines of code store the same results in success : I found an article stating that 1 is a shortcut for 2 - but is 2 the same as 3 or is my application going to explode on execution of this line ... bool success = true ; 1 - success & = SomeFunctionReturningABool ( ) ; 2 - success = success & SomeFunctionReturningABool ( ) ; 3 - success = success & & SomeFunctionReturningABool ( ) ;,c # Assignment operator & = "C_sharp : First , remember that a .NET String is both IConvertible and ICloneable.Now , consider the following quite simple code : Then try the following ( inside some method ) : When one compiles this , one gets no compiler error or warning . When running it , it looks like the method called depends on the order of the interface list in my class declaration for HungryWolf . ( Try swapping the two interfaces in the comma ( , ) separated list . ) The question is simple : Should n't this give a compile-time warning ( or throw at run-time ) ? I 'm probably not the first one to come up with code like this . I used contravariance of the interface , but you can make an entirely analogous example with covarainace of the interface . And in fact Mr Lippert did just that a long time ago . In the comments in his blog , almost everyone agrees that it should be an error . Yet they allow this silently . Why ? -- -Extended question : Above we exploited that a String is both Iconvertible ( interface ) and ICloneable ( interface ) . Neither of these two interfaces derives from the other.Now here 's an example with base classes that is , in a sense , a bit worse.Remember that a StackOverflowException is both a SystemException ( direct base class ) and an Exception ( base class of base class ) . Then ( if ICanEat < > is like before ) : Test it with : Still no warning , error or exception . Still depends on interface list order in class declaration . But the reason why I think it 's worse is that this time someone might think that overload resolution would always pick SystemException because it 's more specific than just Exception.Status before the bounty was opened : Three answers from two users.Status on the last day of the bounty : Still no new answers received . If no answers show up , I shall have to award the bounty to Moslem Ben Dhaou . //contravariance `` in '' interface ICanEat < in T > where T : class { void Eat ( T food ) ; } class HungryWolf : ICanEat < ICloneable > , ICanEat < IConvertible > { public void Eat ( IConvertible convertibleFood ) { Console.WriteLine ( `` This wolf ate your CONVERTIBLE object ! `` ) ; } public void Eat ( ICloneable cloneableFood ) { Console.WriteLine ( `` This wolf ate your CLONEABLE object ! `` ) ; } } ICanEat < string > wolf = new HungryWolf ( ) ; wolf.Eat ( `` sheep '' ) ; class Wolf2 : ICanEat < Exception > , ICanEat < SystemException > // also try reversing the interface order here { public void Eat ( SystemException systemExceptionFood ) { Console.WriteLine ( `` This wolf ate your SYSTEM EXCEPTION object ! `` ) ; } public void Eat ( Exception exceptionFood ) { Console.WriteLine ( `` This wolf ate your EXCEPTION object ! `` ) ; } } static void Main ( ) { var w2 = new Wolf2 ( ) ; w2.Eat ( new StackOverflowException ( ) ) ; // OK , one overload is more `` specific '' than the other ICanEat < StackOverflowException > w2Soe = w2 ; // Contravariance w2Soe.Eat ( new StackOverflowException ( ) ) ; // Depends on interface order in Wolf2 }",No warning or error ( or runtime failure ) when contravariance leads to ambiguity "C_sharp : I discovered that a list of concrete objects can not be added to a list of interface object.Instead , one needs to use the following code : What is the rational behind this ? public static void AddJob ( List < IJob > masterJobs , List < Job > jobs ) { masterJobs.AddRange ( jobs ) ; //fail to compile } public static void AddJob ( List < IJob > masterJobs , List < Job > jobs ) { masterJobs.AddRange ( jobs.Cast < IJob > ( ) ) ; }",List < IJob > .AddRange ( List < Job > ) Does n't Work "C_sharp : If i overload the ! operator in a class , what type should it return ? In a book I found this ( partial listing ) : It does compile , but I would expect the ! operator to return a MyType instance , something likeIn fact , I would expect the compiler to demand that the ! operator returns a MyType . But it doesn't.So ... why does n't the return type of the ! operator have to be the containing type ? You do have to make the return type of ++ or -- be the containing type . public class MyType { public int IntField { get ; set ; } public MyType ( int intField ) { IntField = intField ; } public static bool operator ! ( MyType mt ) { return ( mt.IntField < = 0 ) ; } public static MyType operator ! ( MyType mt ) { var result = new MyType ( -mt.IntField ) ; return result ; }",What type should an overload of the negation operator ( ! ) have ? "C_sharp : Ok , this is a far stretched corner case we stumbled upon , but it made me curious.Consider the following code : Will this code compile ? No , it wo n't if you have fail on all warnings ; you 'll get a member foo is assigned but never used warning.This code is , to all purposes , the same as : Which compiles just fine , so what is the problem here ? Note that the = > syntax is not the issue , its returning the assignment expression which seems to befuddle the compiler . public class Foo { private int foo ; public int Reset ( ) = > foo = 0 ; //remember , assignment expressions //return something ! } public class Foo { private int foo ; public int Reset ( ) { foo = 0 ; return foo ; } }",False C # compiler warning ? "C_sharp : NOTE : Before reading the subject and instantly marking this as a duplicate , please read the entire question to understand what we are after . The other questions which describe getting the BindingExpression , then calling UpdateTarget ( ) method does not work in our use-case . Thanks ! TL : DR VersionUsing INotifyPropertyChanged I can make a binding re-evaluate even when the associated property has n't changed simply by raising a PropertyChanged event with that property 's name . How can I do the same if instead the property is a DependencyProperty and I do n't have access to the target , only the source ? OverviewWe have a custom ItemsControl called MembershipList which exposes a property called Members of type ObservableCollection < object > . This is a separate property from the Items or ItemsSource properties which otherwise behave identical to any other ItemsControl . It 's defined like such ... What we are trying to do is style all members from Items/ItemsSource which also appear in Members differently from those which do n't . Put another way , we 're trying to highlight the intersection of the two lists.Note that Members may contain items which are not in Items/ItemsSource at all . That fact is why we ca n't simply use a multi-select ListBox where SelectedItems has to be a subset of Items/ItemsSource . In our usage , that is not the case.Also note we do not own either the Items/ItemsSource , or the Members collections , therefore we ca n't simply add an IsMember property to the items and bind to that . Plus , that would be a poor design anyway since it would restrict the items to belonging to one single membership . Consider the case of ten of these controls , all bound to the same ItemsSource , but with ten different membership collections.That said , consider the following binding ( MembershipListItem is a container for the MembershipList control ) ... It 's pretty straight forward . When the Members property changes , that value is passed through the MembershipTest converter and the result is stored in the IsMember property on the target object.However , if items are added to or removed from the Members collection , the binding of course does not update because the collection instance itself has n't changed , only its contents.In our case , we do want it to re-evaluate for such changes.We considered adding an additional binding to Count as such ... ... which was close since additions and removals are now tracked , but this does n't work if you replace one item for another since the count does n't change.I also attempted to create a MarkupExtension that internally subscribed to the CollectionChanged event of the Members collection before returning the actual binding , thinking I could use the aforementioned BindingExpression.UpdateTarget ( ) method call in the event handler , but the problem there is I do n't have the target object from which to get the BindingExpression to call UpdateTarget ( ) on from within the ProvideValue ( ) override . In other words , I know I have to tell someone , but I do n't know who to tell.But even if I did , using that approach you quickly run into issues where you would be manually subscribing containers as listener targets to the CollectionChanged event which would cause issues when the containers start to get virtualized , which is why it 's best to just use a binding which automatically and correctly gets re-applied when a container is recycled . But then you 're right back to the start of this problem of not being able to tell the binding to update in response to the CollectionChanged notifications.Solution A - Using Second DependencyProperty for CollectionChanged eventsOne possible solution which does work is to create an arbitrary property to represent the CollectionChanged , adding it to the MultiBinding , then changing it whenever you want to refresh the binding.To that effect , here I first created a boolean DependencyProperty called MembersCollectionChanged . Then in the Members_PropertyChanged handler , I subscribe ( or unsubscribe ) to the CollectionChanged event , and in the handler for that event , I toggle the MembersCollectionChanged property which refreshes the MultiBinding.Here 's the code ... Note : To avoid a memory leak , the code here really should use a WeakEventManager for the CollectionChanged event . However I left it out because of brevity in an already long post.And here 's the binding to use it ... This did work but to someone reading the code is n't exactly clear of its intent . Plus it requires creating a new , arbitrary property on the control ( MembersCollectionChanged here ) for each similar type of usage , cluttering up your API . That said , technically it does satisfy the requirements . It just feels dirty doing it that way.Solution B - Use INotifyPropertyChangedAnother solution using INotifyPropertyChanged is show below . This makes MembershipList also support INotifyPropertyChanged . I changed Members to be a standard CLR-type property instead of a DependencyProperty . I then subscribe to its CollectionChanged event in the setter ( and unsubscribe the old one if present ) . Then it 's just a matter of raising a PropertyChanged event for Members when the CollectionChanged event fires.Here is the code ... Again , this should be changed to use the WeakEventManager.This seems to work fine with the first binding at the top of the page and is very clear what it 's intention is.However , the question remains if it 's a good idea to have a DependencyObject also support the INotifyPropertyChanged interface in the first place . I 'm not sure . I have n't found anything that says it 's not allowed and my understanding is a DependencyProperty actually raises its own change notification , not the DependencyObject it 's applied/attached to so they should n't conflict . Coincidentally that 's also why you ca n't simply implement the INotifyCollectionChanged interface and raise a PropertyChanged event for a DependencyProperty . If a binding is set on a DependencyProperty , it is n't listening to the object 's PropertyChanged notifications at all . Nothing happens . It falls on deaf ears . To use INotifyPropertyChanged , you have to implement the property as a standard CLR property . That 's what I did in the code above , which again , does work.I 'd just like to find out how you can do the equivalent of raising a PropertyChanged event for a DependencyProperty without actually changing the value , if that 's even possible . I 'm starting to think it is n't . public static readonly DependencyProperty MembersProperty = DependencyProperty.Register ( `` Members '' , typeof ( ObservableCollection < object > ) , typeof ( MembershipList ) , new PropertyMetadata ( null ) ) ; public ObservableCollection < object > Members { get { return ( ObservableCollection < object > ) GetValue ( MembersProperty ) ; } set { SetValue ( MembersProperty , value ) ; } } < Style TargetType= '' { x : Type local : MembershipListItem } '' > < Setter Property= '' IsMember '' > < Setter.Value > < MultiBinding Converter= '' { StaticResource MembershipTest } '' > < Binding / > < ! -- Passes the DataContext to the converter -- > < Binding Path= '' Members '' RelativeSource= '' { RealtiveSource AncestorType= { x : Type local : MembershipList } } '' / > < /MultiBinding > < /Setter.Value > < /Setter > < /Style > < Style TargetType= '' { x : Type local : MembershipListItem } '' > < Setter Property= '' IsMember '' > < Setter.Value > < MultiBinding Converter= '' { StaticResource MembershipTest } '' > < Binding / > < ! -- Passes the DataContext to the converter -- > < Binding Path= '' Members '' RelativeSource= '' { RealtiveSource AncestorType= { x : Type local : MembershipList } } '' / > < Binding Path= '' Members.Count '' FallbackValue= '' 0 '' / > < /MultiBinding > < /Setter.Value > < /Setter > < /Style > public static readonly DependencyProperty MembersCollectionChangedProperty = DependencyProperty.Register ( `` MembersCollectionChanged '' , typeof ( bool ) , typeof ( MembershipList ) , new PropertyMetadata ( false ) ) ; public bool MembersCollectionChanged { get { return ( bool ) GetValue ( MembersCollectionChangedProperty ) ; } set { SetValue ( MembersCollectionChangedProperty , value ) ; } } public static readonly DependencyProperty MembersProperty = DependencyProperty.Register ( `` Members '' , typeof ( ObservableCollection < object > ) , typeof ( MembershipList ) , new PropertyMetadata ( null , Members_PropertyChanged ) ) ; // Added the change handlerpublic int Members { get { return ( int ) GetValue ( MembersProperty ) ; } set { SetValue ( MembersProperty , value ) ; } } private static void Members_PropertyChanged ( DependencyObject d , DependencyPropertyChangedEventArgs e ) { var oldMembers = e.OldValue as ObservableCollection < object > ; var newMembers = e.NewValue as ObservableCollection < object > ; if ( oldMembers ! = null ) oldMembers.CollectionChanged -= Members_CollectionChanged ; if ( newMembers ! = null ) oldMembers.CollectionChanged += Members_CollectionChanged ; } private static void Members_CollectionChanged ( object sender , System.Collections.Specialized.NotifyCollectionChangedEventArgs e ) { // 'Toggle ' the property to refresh the binding MembersCollectionChanged = ! MembersCollectionChanged ; } < Style TargetType= '' { x : Type local : MembershipListItem } '' > < Setter Property= '' IsMember '' > < Setter.Value > < MultiBinding Converter= '' { StaticResource MembershipTest } '' > < Binding / > < ! -- Passes in the DataContext -- > < Binding Path= '' Members '' RelativeSource= '' { RealtiveSource AncestorType= { x : Type local : MembershipList } } '' / > < Binding Path= '' MembersCollectionChanged '' RelativeSource= '' { RealtiveSource AncestorType= { x : Type local : MembershipList } } '' / > < /MultiBinding > < /Setter.Value > < /Setter > < /Style > private ObservableCollection < object > _members ; public ObservableCollection < object > Members { get { return _members ; } set { if ( _members == value ) return ; // Unsubscribe the old one if not null if ( _members ! = null ) _members.CollectionChanged -= Members_CollectionChanged ; // Store the new value _members = value ; // Wire up the new one if not null if ( _members ! = null ) _members.CollectionChanged += Members_CollectionChanged ; RaisePropertyChanged ( nameof ( Members ) ) ; } } private void Members_CollectionChanged ( object sender , NotifyCollectionChangedEventArgs e ) { RaisePropertyChanged ( nameof ( Members ) ) ; }",Is it possible to force a binding based on a DependencyProperty to re-evaluate programmatically ? "C_sharp : I have a method with this return type : It makes some further async calls ( unknown number ) each of which return a task of enumerable T , and then wants to concat the results for the return.Now it 's easy enough to await all and concat the results to produce the single enumerable , but i 'd like the enumerable to be available as soon as the first call returns , with potential waits for the caller / enumerator if any calls are still pending when available results run out.Do i have to hand-roll a concat for this , working around the lack of enumerator support when it 's wrapped in a task < > ? Or there 's already a library call in TPL or elsewhere which could help me . I did look at IX , but it 's still on experimental release and do n't want to fold it in.On a side note , is what i 'm trying an anti-pattern ? I can think of one complication , exception handling - from the caller 's side , the call can complete successfully and he starts using the enumerable but it can blow up midway through that ... public async Task < IEnumerable < T > > GetAll ( ) var data1 = src1.GetAll ( ) ; var data2 = src2.GetAll ( ) ; var data3 = src3.GetAll ( ) ; //and so on",How to concat async enumerables ? "C_sharp : Consider the following code : A and B are almost exactly the same thing , but one has a bug I will miss.Is there a way I can get catch the first case at compile time ? EDIT : Some of the answers & comments want to explain to me that properties and fields are n't the same thing . I know that already . They explain why the compiler does n't have a warning here ; I get that . But I wrote a bug , and I do n't like writing bugs . So my question is `` How can I make sure I never , ever write this bug ever again ? '' class C { public int A { get ; set ; } public int B ; public C ( int a , int b ) { this.A = A ; // Oops , bug ! Should be ` this.A = a ` . No warning this.B = B ; // Oops , bug ! Should be ` this.B = b ` . ` warning CS1717 : Assignment made to same variable ; did you mean to assign something else ? ` } }",Is there an automated way to catch property self-assignment ? "C_sharp : This is short code sample to quickly introduce you what is my question about : The output is : Why is this order and how can I change the network to get the output below ? So I am wondering why should all other blocks ( or tasks here ) wait for the delayed block ? UPDATESince you guys asked me to explain my problem more detailed I made this sample that is more closer to the real pipeline I am working on . Let 's say the application downloads some data and computes hash based on returned response.Let 's take a look at the order of the requests : This definitely makes sense . All the requests are made as soon as possible . The slow fourth request is in end of list.Now let us see what output we have : You can see that all the hashes after third were computed right after fourth response came.So based on these two facts we can say that all downloaded pages were waiting for slow fourth request to be done . It would be better to not wait for fourth request and compute hashes as soon as data is downloaded . Is there any way I can achieve this ? using System ; using System.Linq ; using System.Threading.Tasks ; using System.Threading.Tasks.Dataflow ; namespace DataflowTest { class Program { static void Main ( string [ ] args ) { var firstBlock = new TransformBlock < int , int > ( x = > x , new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 } ) ; var secondBlock = new TransformBlock < int , string > ( async x = > { if ( x == 12 ) { await Task.Delay ( 5000 ) ; return $ '' { DateTime.Now } : Message is { x } ( This is delayed message ! ) `` ; } return $ '' { DateTime.Now } : Message is { x } '' ; } , new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 } ) ; var thirdBlock = new ActionBlock < string > ( s = > Console.WriteLine ( s ) , new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 } ) ; firstBlock.LinkTo ( secondBlock ) ; secondBlock.LinkTo ( thirdBlock ) ; var populateTask = Task.Run ( async ( ) = > { foreach ( var x in Enumerable.Range ( 1 , 15 ) ) { await firstBlock.SendAsync ( x ) ; } } ) ; populateTask.Wait ( ) ; secondBlock.Completion.Wait ( ) ; } } } 09.08.2016 15:03:08 : Message is 109.08.2016 15:03:08 : Message is 509.08.2016 15:03:08 : Message is 609.08.2016 15:03:08 : Message is 709.08.2016 15:03:08 : Message is 809.08.2016 15:03:08 : Message is 909.08.2016 15:03:08 : Message is 1009.08.2016 15:03:08 : Message is 1109.08.2016 15:03:08 : Message is 309.08.2016 15:03:08 : Message is 209.08.2016 15:03:08 : Message is 409.08.2016 15:03:13 : Message is 12 ( This is delayed message ! ) 09.08.2016 15:03:08 : Message is 1509.08.2016 15:03:08 : Message is 1309.08.2016 15:03:08 : Message is 14 09.08.2016 15:03:08 : Message is 109.08.2016 15:03:08 : Message is 509.08.2016 15:03:08 : Message is 609.08.2016 15:03:08 : Message is 709.08.2016 15:03:08 : Message is 809.08.2016 15:03:08 : Message is 909.08.2016 15:03:08 : Message is 1009.08.2016 15:03:08 : Message is 1109.08.2016 15:03:08 : Message is 309.08.2016 15:03:08 : Message is 209.08.2016 15:03:08 : Message is 409.08.2016 15:03:08 : Message is 1509.08.2016 15:03:08 : Message is 1309.08.2016 15:03:08 : Message is 1409.08.2016 15:03:13 : Message is 12 ( This is delayed message ! ) using System ; using System.Diagnostics ; using System.Linq ; using System.Net.Http ; using System.Security.Cryptography ; using System.Text ; using System.Threading.Tasks ; using System.Threading.Tasks.Dataflow ; namespace DataflowTest { class Program { static void Main ( string [ ] args ) { var firstBlock = new TransformBlock < int , string > ( x = > x.ToString ( ) , new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 } ) ; var secondBlock = new TransformBlock < string , Tuple < string , string > > ( async x = > { using ( var httpClient = new HttpClient ( ) ) { if ( x == `` 4 '' ) await Task.Delay ( 5000 ) ; var result = await httpClient.GetStringAsync ( $ '' http : //scooterlabs.com/echo/ { x } '' ) ; return new Tuple < string , string > ( x , result ) ; } } , new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 } ) ; var thirdBlock = new TransformBlock < Tuple < string , string > , Tuple < string , byte [ ] > > ( x = > { using ( var algorithm = SHA256.Create ( ) ) { var bytes = Encoding.UTF8.GetBytes ( x.Item2 ) ; var hash = algorithm.ComputeHash ( bytes ) ; return new Tuple < string , byte [ ] > ( x.Item1 , hash ) ; } } , new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 } ) ; var fourthBlock = new ActionBlock < Tuple < string , byte [ ] > > ( x = > { var output = $ '' { DateTime.Now } : Hash for element # { x.Item1 } : { GetHashAsString ( x.Item2 ) } '' ; Console.WriteLine ( output ) ; } , new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 } ) ; firstBlock.LinkTo ( secondBlock ) ; secondBlock.LinkTo ( thirdBlock ) ; thirdBlock.LinkTo ( fourthBlock ) ; var populateTasks = Enumerable.Range ( 1 , 10 ) .Select ( x = > firstBlock.SendAsync ( x ) ) ; Task.WhenAll ( populateTasks ) .ContinueWith ( x = > firstBlock.Complete ( ) ) .Wait ( ) ; fourthBlock.Completion.Wait ( ) ; } private static string GetHashAsString ( byte [ ] bytes ) { var sb = new StringBuilder ( ) ; int i ; for ( i = 0 ; i < bytes.Length ; i++ ) { sb.AppendFormat ( `` { 0 : X2 } '' , bytes [ i ] ) ; if ( i % 4 == 3 ) sb.Append ( `` `` ) ; } return sb.ToString ( ) ; } } } 09.08.2016 20:44:53 : Hash for element # 3 : 4D0AB933 EE521204 CA784F3E 248EC698 F9E4D5F3 8F23A78F 3A00E069 29E73E3209.08.2016 20:44:53 : Hash for element # 2 : 4D0AB933 EE521204 CA784F3E 248EC698 F9E4D5F3 8F23A78F 3A00E069 29E73E3209.08.2016 20:44:53 : Hash for element # 1 : 4D0AB933 EE521204 CA784F3E 248EC698 F9E4D5F3 8F23A78F 3A00E069 29E73E3209.08.2016 20:44:58 : Hash for element # 6 : FC86E4F8 A83036BA 365BC7EE F9371778 59A11186 ED12A43C 3885D686 5004E6B309.08.2016 20:44:58 : Hash for element # 8 : FC86E4F8 A83036BA 365BC7EE F9371778 59A11186 ED12A43C 3885D686 5004E6B309.08.2016 20:44:58 : Hash for element # 9 : FC86E4F8 A83036BA 365BC7EE F9371778 59A11186 ED12A43C 3885D686 5004E6B309.08.2016 20:44:58 : Hash for element # 10 : FC86E4F8 A83036BA 365BC7EE F9371778 59A11186 ED12A43C 3885D686 5004E6B309.08.2016 20:44:58 : Hash for element # 4 : 44A63CBF 8E27D0DD AFE5A761 AADA4E49 AA52FE8E E3D7DC82 AFEAAF1D 72A9BC7F09.08.2016 20:44:58 : Hash for element # 5 : FC86E4F8 A83036BA 365BC7EE F9371778 59A11186 ED12A43C 3885D686 5004E6B309.08.2016 20:44:58 : Hash for element # 7 : FC86E4F8 A83036BA 365BC7EE F9371778 59A11186 ED12A43C 3885D686 5004E6B3",Why do blocks run in this order ? "C_sharp : I want to compare two objects of different versions and display their differences in UI.First I call a method to know if there is any difference between the two objectsThe method is : If the above method returns true , I call the GetDifferences method to get the differences which is : For each difference I create an object of type ObjectDifference and add it to the array . The highlighted portion is the one where I am stuck ! If the object contains another complex object , My program does give me the differences but I dont know which type it belonged toFor example , I have two objects of type Namewhile comparing two objects the output I get is plain -firstname - John Mary LastName - cooper LorofficeNo - 22222 44444 MobileNo - 989898 089089 HomeNo - 4242 43535The Hierarchy that officeNo is of type PhoneNumber is lost , which is important for me to display.How should I maintain this type of tree while creating differences ? Hope I am able to make my problem understood . public bool AreEqual ( object object1 , object object2 , Type comparisionType ) public ObjectDifference [ ] GetObjectDifferences ( object object1 , object object2 , Type comparisionType ) { ArrayList memberList = new ArrayList ( ) ; ArrayList differences = new ArrayList ( ) ; memberList.AddRange ( comparisionType.GetProperties ( ) ) ; memberList.AddRange ( comparisionType.GetFields ( ) ) ; for ( int loopCount = 0 ; loopCount < memberList.Count ; loopCount++ ) { object objVal1 = null ; object objVal2 = null ; MemberInfo member = ( ( MemberInfo ) memberList [ loopCount ] ) ; switch ( ( ( MemberInfo ) memberList [ loopCount ] ) .MemberType ) { case MemberTypes.Field : objVal1 = object1 ! = null ? ( ( FieldInfo ) memberList [ loopCount ] ) .GetValue ( object1 ) : null ; objVal2 = object2 ! = null ? ( ( FieldInfo ) memberList [ loopCount ] ) .GetValue ( object2 ) : null ; break ; case MemberTypes.Property : objVal1 = object1 ! = null ? ( ( PropertyInfo ) memberList [ loopCount ] ) .GetValue ( object1 , null ) : null ; objVal2 = object2 ! = null ? ( ( PropertyInfo ) memberList [ loopCount ] ) .GetValue ( object2 , null ) : null ; break ; default : break ; } if ( AreValuesDifferentForNull ( objVal1 , objVal2 ) ) { ObjectDifference obj = new ObjectDifference ( objVal1 , objVal2 , member , member.Name ) ; differences.Add ( obj ) ; } else if ( AreValuesDifferentForPrimitives ( objVal1 , objVal2 ) ) { ObjectDifference obj = new ObjectDifference ( objVal1 , objVal2 , member , member.Name ) ; differences.Add ( obj ) ; } else if ( AreValuesDifferentForList ( objVal1 , objVal2 ) ) { ObjectDifference [ ] listDifference = GetListDifferences ( ( ICollection ) objVal1 , ( ICollection ) objVal2 , member ) ; differences.AddRange ( listDifference ) ; } else if ( ( ! AreValuesEqual ( objVal1 , objVal2 ) ) & & ( objVal1 ! = null || objVal2 ! = null ) ) { ObjectDifference obj = new ObjectDifference ( objVal1 , objVal2 , member , member.Name ) ; differences.Add ( obj ) ; } } return ( ObjectDifference [ ] ) differences.ToArray ( typeof ( ObjectDifference ) ) ; } public class ObjectDifference { private readonly object objectValue1 ; private readonly object objectValue2 ; private readonly System.Reflection.MemberInfo member ; private readonly string description ; public object ObjectValue1 { get { return objectValue1 ; } } public object ObjectValue2 { get { return objectValue2 ; } } public System.Reflection.MemberInfo Member { get { return member ; } } public string Description { get { return description ; } } public ObjectDifference ( object objVal1 , object objVal2 , System.Reflection.MemberInfo member , string description ) { this.objectValue1 = objVal1 ; this.objectValue2 = objVal2 ; this.member = member ; this.description = description ; } } class Name { string firstName , LastName ; List phNumber ; } class PhoneNumber { string officeNo , MobileNo , HomeNo ; }",How to diff two versions of same object ? "C_sharp : Why does string interpolation prefer overload of method with string instead of IFormattable ? Imagine following : I have objects with very expensive ToString ( ) . Previously , I did following : Now , I wanted to have the IsDebugEnabled logic inside Debug ( IFormattable ) , and call ToString ( ) on objects in message only when necessary.This , however , calls the Debug ( string ) overload . static class Log { static void Debug ( string message ) ; static void Debug ( IFormattable message ) ; static bool IsDebugEnabled { get ; } } if ( Log.IsDebugEnabled ) Log.Debug ( string.Format ( `` Message { 0 } '' , expensiveObject ) ) ; Log.Debug ( $ '' Message { expensiveObject } '' ) ;",Overloaded string methods with string interpolation "C_sharp : Over the years , and again recently , I have heard discussion that everyone should use Path.Combine instead of joining strings together with `` \\ '' , for example : I 'm failing to see the benefit that the former version provides over the latter and I was hoping someone could explain . string myFilePath = Path.Combine ( `` c : '' , `` myDoc.txt '' ) ; // vs. string myFilePath = `` C : '' + `` \\myDoc.txt '' ;",Why is Path.Combine better than `` \\ '' ? "C_sharp : I know that you can directly invoke the static constructor of a type and I know that you can create an instance of an object without calling the constructor , but is there a way to run the constructor of a type ( .ctor ) on an already existing instance ? I 'm looking for something like : I am aware that I should never really need to do this , I am more wondering if it is possible to re-invoke the constructor/initializer on an already created object . public static void Reinitialize < T > ( T instance ) { var initializer = typeof ( T ) .GetHiddenConstructorThatDoesntNew ( typeof ( int ) , typeof ( string ) ) ; // call the constructor ( int , string ) on instance initializer.Invoke ( instance , 7 , `` Bill '' ) ; }",Is it possible to directly invoke a constructor on an already created instance ? "C_sharp : Basically I have been programing for a little while and after finishing my last project can fully understand how much easier it would have been if I 'd have done TDD . I guess I 'm still not doing it strictly as I am still writing code then writing a test for it , I do n't quite get how the test becomes before the code if you do n't know what structures and how your storing data etc ... but anyway ... Kind of hard to explain but basically lets say for example I have a Fruit objects with properties like id , color and cost . ( All stored in textfile ignore completely any database logic etc ) This is all just for example . But lets say I have this is a collection of Fruit ( it 's a List < Fruit > ) objects in this structure . And my logic will say to reorder the fruitids in the collection if a fruit is deleted ( this is just how the solution needs to be ) .E.g . if 1 is deleted , object 2 takes fruit id 1 , object 3 takes fruit id2.Now I want to test the code ive written which does the reordering , etc.How can I set this up to do the test ? Here is where I 've got so far . Basically I have fruitManager class with all the methods , like deletefruit , etc . It has the list usually but Ive changed hte method to test it so that it accepts a list , and the info on the fruit to delete , then returns the list . Unit-testing wise : Am I basically doing this the right way , or have I got the wrong idea ? and then I test deleting different valued objects / datasets to ensure method is working properly . FruitID FruitName FruitColor FruitCost 1 Apple Red 1.2 2 Apple Green 1.4 3 Apple HalfHalf 1.5 [ Test ] public void DeleteFruit ( ) { var fruitList = CreateFruitList ( ) ; var fm = new FruitManager ( ) ; var resultList = fm.DeleteFruitTest ( `` Apple '' , 2 , fruitList ) ; //Assert that fruitobject with x properties is not in list ? how } private static List < Fruit > CreateFruitList ( ) { //Build test data var f01 = new Fruit { Name = `` Apple '' , Id = 1 , etc ... } ; var f02 = new Fruit { Name = `` Apple '' , Id = 2 , etc ... } ; var f03 = new Fruit { Name = `` Apple '' , Id = 3 , etc ... } ; var fruitList = new List < Fruit > { f01 , f02 , f03 } ; return fruitList ; }",Unit Testing - Am I doing it right ? "C_sharp : I 'm getting this warning but ca n't figure out the problem ... CodeContracts : warning : The Boolean condition d1.Count ! = d2.Count always evaluates to a constant value . If it ( or its negation ) appear in the source code , you may have some dead code or redundant checkThe code is as follows : The // Equality check goes here part can be as is , or replaced by a proper implementation and I still get the same warning . public static bool DictionaryEquals < TKey , TValue > ( IDictionary < TKey , TValue > d1 , IDictionary < TKey , TValue > d2 ) { if ( d1 == d2 ) return true ; if ( d1 == null || d2 == null ) return false ; if ( d1.Count ! = d2.Count ) return false ; // < -- warning here // Equality check goes here return true ; }","CodeContracts : Boolean condition evaluates to a constant value , why ?" "C_sharp : This one has always puzzled me , but i 'm guessing there is a very sensible explanation of why it happens . When you have a collection initializer the compiler allows a trailing comma , e.g . and Anyone know why this trailing comma is allowed by the compiler ? new Dictionary < string , string > { { `` Foo '' , `` Bar `` } , } ; new List < string > { `` Foo '' , } ;",Why can you have a comma at the end of a collection initializer ? "C_sharp : We got a special multivalue attribute . Let 's call it ourOwnManagedBy which can contain users or groups ( their DN ) that manages the current group.How can I retrieve a list of all groups that a specific user manages ( with the help of managedBy and ourOwnManagedBy ) ? For instance . Let 's say that the user is member of the group GlobalAdministrators and that the group ApplicationAdministrators has GlobalAdministrations as a member . And finally the group MyApplication which has ApplicationAdministrators in the ourOwnManagedBy attribute.User is member of GlobalAdministrators GlobalAdministrators is member of ApplicationAdministrators MyApplication got ApplicationAdministrators in ourOwnManagedByHow do I use that information to find all groups that a specific user manages ? Is it possible to do some kind of recursive check in custom attributes ( that contains DNs of users and groups ) ? UpdateI 've tried to use a directory search filter like this : but I might have missunderstood what 1.2.840.113556.1.4.1941 does ? ( MSDN page ) string.Format ( `` ( ourOwnManagedBy:1.2.840.113556.1.4.1941 : = { 0 } ) '' , dn ) ;",Finding all groups that a user manages "C_sharp : In a WebControl , i have a property Filters defined like this : This webcontrol is a DataSource , i created this property because i want to have the possiblity to filter data easily , eg : It works great , however , if I change code to this : It does n't works anymore , I get this error : Type System.Web.UI.Page in Assembly ' ... ' is not marked as serializable.What happened : The serializer inspect the dictionary . It sees it contains a anonymous delegate ( lambda here ) Since the delegate is defined in a class , it tries to serialize the whole class , in this case System.Web.UI.Page This class is not marked as Serializable It throws an exception because of 3.Is there any convenient solution to solve this ? I can not mark all web pages where i use the datasource as [ serializable ] for obvious reasons.EDIT 1 : something I do n't understand . If I store the Dictionary in the Session object ( which use a BinaryFormatter vs LosFormatter for ViewState ) , it works ! I have no idea how it is possible . Maybe BinaryFormatter can serialize any class , even these who are not [ serializable ] ? EDIT 2 : smallest code to reproduce the problem : public Dictionary < string , Func < T , bool > > Filters { get { Dictionary < string , Func < T , bool > > filters = ( Dictionary < string , Func < T , bool > > ) ViewState [ `` filters '' ] ; if ( filters == null ) { filters = new Dictionary < string , Func < T , bool > > ( ) ; ViewState [ `` filters '' ] = filters ; } return filters ; } } //in page load DataSource.Filters.Add ( `` userid '' , u = > u.UserID == 8 ) ; //in page load int userId = int.Parse ( DdlUsers.SelectedValue ) ; DataSource.Filters.Add ( `` userid '' , u = > u.UserID == userId ) ; void test ( ) { Test test = new Test ( ) ; string param1 = `` parametertopass '' ; test.MyEvent += ( ) = > Console.WriteLine ( param1 ) ; using ( MemoryStream ms = new MemoryStream ( ) ) { BinaryFormatter bf = new BinaryFormatter ( ) ; bf.Serialize ( ms , test ) ; //bang } } [ Serializable ] public class Test { public event Action MyEvent ; }",Is there a way to store an anonymous delegate in a viewstate ? "C_sharp : I have the following classes : How do I dispose the SqlConnection object that is instantiated when GetConnection ( ) is passed as parameter in my SqlDataAdapter constructor ? Will it get disposed automatically when I dispose my Adapt object in the method that called GetDataAdapter ( ) ? If it 's not possible to dispose it , how do you suggest to proceed ? Thanks for any help . private static readonly string ConnectionString = `` Dummy '' ; public static SqlConnection GetConnection ( ) { SqlConnection Connection = new SqlConnection ( ConnectionString ) ; return Connection ; } public static SqlDataAdapter GetDataAdapter ( string Query ) { SqlDataAdapter Adapt = new SqlDataAdapter ( Query , GetConnection ( ) ) ; return Adapt ; }",Dispose object that has been instantiated as method parameter c # "C_sharp : I have a stored procedure that I execute with context.Database.SqlQuery < MyObject > ( `` MyProc '' ) MyObject has a readonly property : So I get the error : System.IndexOutOfRangeException : IsSomething at System.Data.ProviderBase.FieldNameLookup.GetOrdinal etcWhich is because MyProc does n't have IsSomething in the result columns ( I 'm 100 % sure that 's probably the reason ) .Should n't it just ignore it since it 's [ NotMapped ] ? Do I need to set something else for SqlQuery ? To make things even more weird , I only see it on production , from the logs of Stackify , and the page seems to load properly without any errors in the browser . [ NotMapped ] public bool IsSomething { get { return this.otherproperty == `` something '' ; } }","EF SqlQuery tries to map object property , even though it 's attributed [ NotMapped ]" "C_sharp : I 'm using ML.NET 0.7 and have a MulticlassClassification model with the following result class : I 'd like to know the scores and the corresponding labels on the Scores property . Feels like I should be able to make the property a Tuple < string , float > or similar to get the label that the score represents.I understand that there was a method on V0.5 : But ca n't seem to find the equivalent in V0.7.Can this be done ? if so how ? public class TestClassOut { public string Id { get ; set ; } public float [ ] Score { get ; set ; } public string PredictedLabel { get ; set ; } } model.TryGetScoreLabelNames ( out scoreLabels ) ;",ML.Net 0.7 - Get Scores and Labels for MulticlassClassification "C_sharp : I want to create a treeview in c # which will group file by prefix ( here the prefix is a marked by the separator _ ) . The following files should give this tree : Files list : Corresponding tree : Here 's my attempt of code : But I miss a few ones in the final result : How can I get its back ? Even when I debug step by step I ca n't find the logical way to do it . p_ap_a_testp_LIGp_pp_p_cp_p_c2p_p_cccp_p_testp_tresTestLineGraph1TestLineGrpah | -- p_ | -- p_a | -- p_a_test | -- p_LIG | -- p_p | -- p_p_ | -- p_p_c | -- p_p_c2 | -- p_p_ccc | -- p_p_test | -- p_tresTestLineGraph1TestLineGrpah private GraphUINode ( List < string > subNodes , GraphUINode parent , string name , int lvl = 0 ) : base ( parent.m_viewDataSubControl ) { parent.Nodes.Add ( this ) ; this.Name = name ; this.Text = name ; string currentPrefix = `` '' ; int pertinentSubNodes = 0 ; while ( pertinentSubNodes < subNodes.Count -1 & & subNodes [ pertinentSubNodes ] .Split ( ' _ ' ) .Length < 2+ lvl ) pertinentSubNodes++ ; for ( int i = 0 ; i < = lvl ; i++ ) { currentPrefix += subNodes [ pertinentSubNodes ] .Split ( ' _ ' ) [ i ] + `` _ '' ; } List < String > children = new List < string > ( ) ; foreach ( string child in subNodes ) { // The child is in the same group than the previous one if ( child.StartsWith ( currentPrefix ) ) { children.Add ( child ) ; } else { // Create a node only if needed if ( children.Count > 1 ) { // Create the new node new GraphUINode ( children , this , currentPrefix , lvl + 1 ) ; children.Clear ( ) ; children.Add ( child ) ; } else { new GraphTemplateNode ( this , m_viewDataSubControl , child ) ; } currentPrefix = `` '' ; for ( int i = 0 ; i < = lvl ; i++ ) { currentPrefix += child.Split ( ' _ ' ) [ i ] + `` _ '' ; } } } }",Creating a Treeview recursively "C_sharp : I was just browsing and came across this question : Action vs delegate eventThe answer from nobug included this code : Resharper also generates similar code when using the `` create raising method '' quick-fix.My question is , why is this line necessary ? : Why is it better than writing this ? : protected virtual void OnLeave ( EmployeeEventArgs e ) { var handler = Leave ; if ( handler ! = null ) handler ( this , e ) ; } var handler = Leave ; protected virtual void OnLeave ( EmployeeEventArgs e ) { if ( Leave ! = null ) Leave ( this , e ) ; }",Event handler raising method convention C_sharp : I have designed a telemetry logger for few separate platforms using the composite patternNow i want to be able to get an instance of `` Many '' from Windsor containerbut have encountered a few problems : if all ILoggers are in the container how can i make sure i get the `` Many '' implementation and not `` A '' or `` B '' ? I tried following this example Castle Windsor : How do I inject all implementations of interface into a ctor ? and use container.Kernel.Resolver.AddSubResolver ( newCollectionResolver ( container.Kernel ) ) ; to register a class with IEnumerable dependancy but ifthat class also implements IComponent wont it create a circulardependency ? Is what I 'm attempting even possible ? public interface ILogger { void Log ( ) ; } public class A : ILogger { public void Log ( ... ) ; } public class B : ILogger { public void Log ( ... ) ; } public class Many : ILogger { private readonly List < ILogger > m_loggers ; public Many ( IEnumerable < ILogger > loggers ) { m_loggers = loggers.ToList ( ) ; } public void Log ( ) { m_loggers.ForEach ( c = > c.Log ( ) ) ; } },"C # , Castle Windsor and The Composite design pattern" "C_sharp : What is the proper way to use ArrayPool with reference types ? I was assuming that it would be full of objects that were just 'newed up ' with the default constructor.For example , in the code below , all the Foobars are null when you first rent from the ArrayPool . 2 Questions : Since the objects returned from .Rent are initially all null , do I need to fill up the array pool with initialized objects first ? When returning the rented objects do I need to clear each object ? For example , foobar.Name = null ; foobar.Place = null etc ... public class Program { public class Foobar { public string Name { get ; set ; } public string Place { get ; set ; } public int Index { get ; set ; } } public static void Main ( ) { ArrayPool < Foobar > pool = ArrayPool < Foobar > .Shared ; var foobars = pool.Rent ( 5 ) ; foreach ( var foobar in foobars ) { // prints `` true '' Console.WriteLine ( $ '' foobar is null ? ans= { foobar == null } '' ) ; } } }",Proper usage of ArrayPool < T > with a reference type "C_sharp : I am trying to load a RenderWindowControl from vtk libraries on my WPF proyect using ActiViz.NET and Visual Studio 2013 . The library works fine since I did a new project just to practice on itbut when I tried to integrate it into my work , I got a null RenderWindowControl this time . This is my code : MainWindow.xaml : VtkTabView.xaml : VtkTabView.xaml.cs : RenderControl.RenderWindow is null on WindowLoaded ( VtkTabView.xaml.cs ) and I do not know why . Might it be because I load UITabView from a second xamp and I lose the content of RenderControl ? , it is the only difference I see compare to the example I did . < Window x : Class= '' myProject.Views.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : VtkTab= '' clr-namespace : myProject.Views.UITabs.VtkTab '' x : Name= '' Mainwindow '' MinHeight= '' 600 '' MinWidth= '' 800 '' Title= '' { Binding Title } '' Height= '' 720 '' Width= '' 1280 '' Icon= '' { StaticResource ApplicationIcon } '' Loaded= '' OnLoaded '' DataContext= '' { Binding Main , Source= { StaticResource ViewModelLocator } } '' Style= '' { StaticResource WindowStyle } '' mc : Ignorable= '' d '' > < DockPanel > < TabControl > ... . ... . < VtkTab : VtkTabView / > ... . ... . < /TabControl > < /DockPanel > < /Window > < UserControl x : Class= '' myProject.Views.UITabs.VtkTab.VtkTabView '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : vtk= '' clr-namespace : Kitware.VTK ; assembly=Kitware.VTK '' Loaded= '' WindowLoaded '' Height= '' 480 '' Width= '' 640 '' > < WindowsFormsHost Name= '' Wfh '' > < vtk : RenderWindowControl x : Name= '' RenderControl '' / > < /WindowsFormsHost > < /UserControl > public partial class UITabView { protected static Random _random = new Random ( ) ; vtkActor actor = vtkActor.New ( ) ; public VtkTabView ( ) { InitializeComponent ( ) ; var sphere = vtkSphereSource.New ( ) ; sphere.SetThetaResolution ( 8 ) ; sphere.SetPhiResolution ( 16 ) ; var shrink = vtkShrinkPolyData.New ( ) ; shrink.SetInputConnection ( sphere.GetOutputPort ( ) ) ; shrink.SetShrinkFactor ( 0.9 ) ; var move = vtkTransform.New ( ) ; move.Translate ( _random.NextDouble ( ) , _random.NextDouble ( ) , _random.NextDouble ( ) ) ; var moveFilter = vtkTransformPolyDataFilter.New ( ) ; moveFilter.SetTransform ( move ) ; moveFilter.SetInputConnection ( shrink.GetOutputPort ( ) ) ; var mapper = vtkPolyDataMapper.New ( ) ; mapper.SetInputConnection ( moveFilter.GetOutputPort ( ) ) ; // The actor links the data pipeline to the rendering subsystem actor.SetMapper ( mapper ) ; actor.GetProperty ( ) .SetColor ( 1 , 0 , 0 ) ; } private void WindowLoaded ( object sender , RoutedEventArgs e ) { var renderer = RenderControl.RenderWindow.GetRenderers ( ) .GetFirstRenderer ( ) ; renderer.AddActor ( actor ) ; } }",NullReferenceException loading RenderWindowControl for vtk in WPF "C_sharp : Below is a simple test fixture . It succeeds in Debug builds and fails in Release builds ( VS2010 , .NET4 solution , x64 ) : It seems code optimization wreaks some havoc ; if I disable it on the Release build , it works as well . That was rather puzzling to me . Below , I 've used ILDASM to disassemble the 2 versions of the build : Debug IL : Release IL : It seems a store and load is optimized away . Targeting earlier versions of the .NET framework made the problem go away , but that may just be a fluke . I found this behaviour somewhat unnerving , can anybody explain why the compiler would think it safe to do an optimization that produces different observable behaviour ? Thanks in advance . [ TestFixture ] public sealed class Test { [ Test ] public void TestChecker ( ) { var checker = new Checker ( ) ; Assert.That ( checker.IsDateTime ( DateTime.Now ) , Is.True ) ; } } public class Checker { public bool IsDateTime ( object o ) { return o is DateTime ; } } .method public hidebysig instance bool IsDateTime ( object o ) cil managed { // Code size 15 ( 0xf ) .maxstack 2 .locals init ( bool V_0 ) IL_0000 : nop IL_0001 : ldarg.1 IL_0002 : isinst [ mscorlib ] System.DateTime IL_0007 : ldnull IL_0008 : cgt.un IL_000a : stloc.0 IL_000b : br.s IL_000d IL_000d : ldloc.0 IL_000e : ret } // end of method Validator : :IsValid .method public hidebysig instance bool IsDateTime ( object o ) cil managed { // Code size 10 ( 0xa ) .maxstack 8 IL_0000 : ldarg.1 IL_0001 : isinst [ mscorlib ] System.DateTime IL_0006 : ldnull IL_0007 : cgt.un IL_0009 : ret } // end of method Validator : :IsValid",Can C # 'is ' operator suffer under release mode optimization on .NET 4 ? "C_sharp : Here is a really simple .net < - > COM interop example using events.This example works just fine as long as i either use regasm or the register for com interop option in Visual studio build options for the .net library.But I need to deploy using registration free interop enabled side-by-side manifests . The application runs just fine in side-by-side mode , it 's just that the events seems to disappear . I suspect it 's some thread marshalling issue , but I ca n't seem to find the correct solution.This is of course an attempt to replicate an issue I have with a slightly more complicated interop integration . There is one difference between the issues I 'm having here compared to the real issues : Both solutions fail to properly sink events raised in the .net code while running on reg-free deployment , and both solutions works as expected when the .net dlls are registered in the registry.However : on the `` real '' project I get a runtime error when it fails from System.Reflection.Target . On this simplified example it just fails silently.I 'm thoroughly stuck on this one , so any and all suggestions and solutions will be very much welcomed . I 've put the complete code on github if anyone needs to play around with it before answering : https : //github.com/Vidarls/InteropEventTestThe .net partThe COM ( VB6 ) partI currently have the following files / folder structure for deploy : Content of manifest files : Interop.Event.Test.manifestInteropEventTest.manifesttester.exe.manifest using System.Runtime.InteropServices ; using System.Threading.Tasks ; namespace InteropEventTest { [ Guid ( `` E1BC643E-0CCF-4A91-8499-71BC48CAC01D '' ) ] [ InterfaceType ( ComInterfaceType.InterfaceIsIUnknown ) ] [ ComVisible ( true ) ] public interface ITheEvents { void OnHappened ( string theMessage ) ; } [ Guid ( `` 77F1EEBA-A952-4995-9384-7228F6182C32 '' ) ] [ ComVisible ( true ) ] public interface IInteropConnection { void DoEvent ( string theMessage ) ; } [ Guid ( `` 2EE25BBD-1849-4CA8-8369-D65BF47886A5 '' ) ] [ ClassInterface ( ClassInterfaceType.None ) ] [ ComSourceInterfaces ( typeof ( ITheEvents ) ) ] [ ComVisible ( true ) ] public class InteropConnection : IInteropConnection { [ ComVisible ( false ) ] public delegate void Happened ( string theMessage ) ; public event Happened OnHappened ; public void DoEvent ( string theMessage ) { if ( OnHappened ! = null ) { Task.Factory.StartNew ( ( ) = > OnHappened ( theMessage ) ) ; } } } } Private WithEvents tester As InteropEventTest.InteropConnectionPrivate Sub Command1_Click ( ) Call tester.DoEvent ( Text1.Text ) End SubPrivate Sub Form_Load ( ) Set tester = New InteropConnectionEnd SubPrivate Sub tester_OnHappened ( ByVal theMessage As String ) Text2.Text = theMessageEnd Sub Root|- > [ D ] Interop.Event.Tester |- > Interop.Event.Tester.manifest|- > [ D ] InteropEventTest |- > InteropEventTest.dll|- > InteropEventTest.manifest|- > InteropEventTest.tlb|- > tester.exe|- > tester.exe.manifest < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > < assembly xmlns= '' urn : schemas-microsoft-com : asm.v1 '' manifestVersion= '' 1.0 '' > < assemblyIdentity name= '' Interop.Event.Tester '' version= '' 1.0.0.0 '' type= '' win32 '' processorArchitecture= '' x86 '' / > < /assembly > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > < assembly xmlns= '' urn : schemas-microsoft-com : asm.v1 '' manifestVersion= '' 1.0 '' > < assemblyIdentity name= '' InteropEventTest '' version= '' 1.0.0.0 '' type= '' win32 '' / > < clrClass name= '' InteropEventTest.InteropConnection '' clsid= '' { 2EE25BBD-1849-4CA8-8369-D65BF47886A5 } '' progid= '' InteropEventTest.InteropConnection '' runtimeVersion= '' v4.0.30319 '' threadingModel= '' Both '' / > < file name= '' InteropEventTest.tlb '' > < typelib tlbid= '' { 5CD6C635-503F-4103-93B0-3EBEFB91E500 } '' version= '' 1.0 '' helpdir= '' '' flags= '' hasdiskimage '' / > < /file > < comInterfaceExternalProxyStub name= '' ITheEvents '' iid= '' { E1BC643E-0CCF-4A91-8499-71BC48CAC01D } '' proxyStubClsid32= '' { 00020424-0000-0000-C000-000000000046 } '' baseInterface= '' { 00000000-0000-0000-C000-000000000046 } '' tlbid= '' { 5CD6C635-503F-4103-93B0-3EBEFB91E500 } '' / > < /assembly > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > < assembly xmlns= '' urn : schemas-microsoft-com : asm.v1 '' manifestVersion= '' 1.0 '' > < assemblyIdentity name= '' tester.exe '' version= '' 1.0.0.0 '' type= '' win32 '' processorArchitecture= '' x86 '' / > < dependency > < dependentAssembly > < assemblyIdentity name= '' InteropEventTest '' version= '' 1.0.0.0 '' type= '' win32 '' / > < /dependentAssembly > < /dependency > < dependency > < dependentAssembly > < assemblyIdentity name= '' Interop.Event.Tester '' version= '' 1.0.0.0 '' type= '' win32 '' processorArchitecture= '' x86 '' / > < /dependentAssembly > < /dependency > < /assembly >",Events raised in .net code is does not seem to occur in COM code when deployed with Side by side manifests "C_sharp : MSDN Documentation and many examples of using ReaderWriterLockSlim class recommends using the following pattern : But I 'm curious if it 's completely safe . Is it possible that some exception will happen after lock is acquired , but before the try statement so that lock is stuck in the locked state ? The most obvious candidate is ThreadAbortException . I understand that probability of this situation is extreemely small , but the consequences are extreemely bad - so I think it worth thinking about it . I do n't believe compiler understands this pattern and prevents processor from interrupting thread before try statement.If there is theoretical possibility that this code is unsafe , and is there ways to make it safer ? cacheLock.EnterWriteLock ( ) ; try { //Do something } finally { cacheLock.ExitWriteLock ( ) ; }",Is it completely safe to use pattern of ReaderWriterLockSlim.EnterXXX ( ) with consequent try-finally clause "C_sharp : The problem : I get the following error when I build : `` '.Controllers.ControllerBase ' does not contain a constructor that takes 0 arguments '' My base controller looks like this : An example controller that makes use of the Base..This seems to be tripping T4MVC.Should I just not be passing params into the base constructor ? public abstract class ControllerBase : Controller { public CompanyChannel < IAuthorizationService > authorizationServiceClient ; public ControllerBase ( CompanyChannel < IAuthorizationService > authService ) { this.authorizationServiceClient = authService ; } } public partial class SearchController : ControllerBase { protected CompanyChannel < IComplaintTaskService > complaintTaskServiceChannel ; protected IComplaintTaskService taskServiceClient ; protected ComplaintSearchViewModel searchViewModel ; # region `` Constructor `` public SearchController ( CompanyChannel < IComplaintTaskService > taskService , CompanyChannel < IAuthorizationService > authService , ComplaintSearchViewModel viewModel ) : base ( authService ) { searchViewModel = viewModel ; this.complaintTaskServiceChannel = taskService ; this.taskServiceClient = complaintTaskServiceChannel.Channel ; } # endregion public virtual ActionResult Index ( ) { return View ( ) ; } }",T4MVC not passing parameters to base controller so generated code does not build "C_sharp : What would be the proper way of optimizing the following kind of statements : Now , if I 'm willing to take only some of the first elements , I could use something like : And so , if my sequence from BuildSequence actually contains several thousands of elements , I obviously do n't want all of them to be constructed , because I would only need 5 of them.Does LINQ optimize this kind of operations or I would have to invent something myself ? IEnumerable < T > sequence = BuildSequence ( ) ; // 'BuildSequence ' makes some tough actions and uses 'yield return'// to form the resulting sequence . sequence.Take ( 5 ) ;",C # LINQ optimization "C_sharp : I have an arbitrarily defined JSON document , and I want to be able to apply a JSONPath expression like a whitelist filter for properties : All selected nodes and their ancestors back to the root node remain , all other nodes are removed . If the nodes do n't exist , I should end up with an empty document.There did n't seem to be anything similar to this built into JSON.Net and I could n't find similar examples anywhere , so I built my own . I opted to copy selected nodes into a newly built document rather than try and remove all nodes that did n't match . Given that there could be multiple matches and documents could be large , it needed to be able to handle merging the multiple selection results efficiently into a single tree/JSON document.My attempt sort of works , but I 'm getting strange results . The process involves a MergedAncestry method which iterates over the SelectTokens results , calls GetFullAncestry ( which recursively builds the tree to that node ) , then merges the results . It seems the merging of JArrays is happening at the wrong level though , as you can see under `` Actual results '' below.My questions : Is there a better/faster/built-in way to achieve this ? If not , what am I doing wrong ? Code : Example JSON : See DotNetFiddle for full code and tests '' Filter '' JSONPath : Expected results : Actual results : public static void Main ( ) { string json = @ '' ... '' ; // snipped for brevity - see DotNetFiddle : https : //dotnetfiddle.net/wKN1Hj var root = ( JContainer ) JToken.Parse ( json ) ; var t3 = root.SelectTokens ( `` $ .Array3B. [ * ] .Array3B1. [ * ] . * '' ) ; // See DotNetFiddle for simpler examples that work Console.WriteLine ( $ '' { MergedAncestry ( t3 ) .ToString ( ) } '' ) ; // Wrong output ! Console.ReadKey ( ) ; } // Returns a single document merged using the full ancestry of each of the input tokensstatic JToken MergedAncestry ( IEnumerable < JToken > tokens ) { JObject merged = null ; foreach ( var token in tokens ) { if ( merged == null ) { // First object merged = ( JObject ) GetFullAncestry ( token ) ; } else { // Subsequent objects merged merged.Merge ( ( JObject ) GetFullAncestry ( token ) , new JsonMergeSettings { // union array values together to avoid duplicates MergeArrayHandling = MergeArrayHandling.Union } ) ; } } return merged ? ? new JObject ( ) ; } // Recursively builds a new tree to the node matching the ancestry of the original nodestatic JToken GetFullAncestry ( JToken node , JToken tree = null ) { if ( tree == null ) { // First level : start by cloning the current node tree = node ? .DeepClone ( ) ; } if ( node ? .Parent == null ) { // No parents left , return the tree we 've built return tree ; } // Rebuild the parent node in our tree based on the type of node JToken a ; switch ( node.Parent ) { case JArray _ : return GetFullAncestry ( node.Parent , new JArray ( tree ) ) ; case JProperty _ : return GetFullAncestry ( node.Parent , new JProperty ( ( ( JProperty ) node.Parent ) .Name , tree ) ) ; case JObject _ : return GetFullAncestry ( node.Parent , new JObject ( tree ) ) ; default : return tree ; } } { `` Array3A '' : [ { `` Item_3A1 '' : `` Desc_3A1 '' } ] , `` Array3B '' : [ { `` Item_3B1 '' : `` Desc_3B1 '' } , { `` Array3B1 '' : [ { `` Item_1 '' : `` Desc_3B11 '' } , { `` Item_2 '' : `` Desc_3B12 '' } , { `` Item_3 '' : `` Desc_3B13 '' } ] } , { `` Array3B2 '' : [ { `` Item_1 '' : `` Desc_3B21 '' } , { `` Item_2 '' : `` Desc_3B22 '' } , { `` Item_3 '' : `` Desc_3B23 '' } ] } ] } $ .Array3B. [ * ] .Array3B1. [ * ] . * { `` Array3B '' : [ { `` Array3B1 '' : [ { `` Item_1 '' : `` Desc_3B11 '' } , { `` Item_2 '' : `` Desc_3B12 '' } , { `` Item_3 '' : `` Desc_3B13 '' } ] } ] } { `` Array3B '' : [ { `` Array3B1 '' : [ { `` Item_1 '' : `` Desc_3B11 '' } ] } , { `` Array3B1 '' : [ { `` Item_2 '' : `` Desc_3B12 '' } ] } , { `` Array3B1 '' : [ { `` Item_3 '' : `` Desc_3B13 '' } ] } ] }",Using JSONPath to filter properties in JSON documents "C_sharp : Im sitting with a brain teaser that I can not seem to complete . I am trying to create a specific folder structure . The structure is explained here : In the root folder specified , the application should create 10 folders , ' 0 ' - '10 ' . Inside each of these , should again be folders ' 0 ' - '10 ' , and etc . This must go on to a user defined level.Using for loops , I have managed to get this so far , but can imagine that a recursive function will look a lot less messy , but melts my brain at the same time trying to figure it out D : As you can see , this is quite messy . If you run the code , it will create the desired folder structure , but I want it done recursively . Im trying to expand my way of thinking , and this seems to be a real brain teaser . Any help would be greatly appreciated static void Main ( string [ ] args ) { string basePath = Path.Combine ( Environment.CurrentDirectory , `` Lib '' ) ; for ( int a = 0 ; a < 10 ; a++ ) { CreateFolders ( basePath ) ; basePath = Path.Combine ( basePath , a.ToString ( ) ) ; for ( int b = 0 ; b < 10 ; b++ ) { CreateFolders ( basePath ) ; basePath = Path.Combine ( basePath , b.ToString ( ) ) ; for ( int c = 0 ; c < 10 ; c++ ) { CreateFolders ( basePath ) ; basePath = Path.Combine ( basePath , c.ToString ( ) ) ; for ( int d = 0 ; d < 10 ; d++ ) { CreateFolders ( basePath ) ; basePath = Path.Combine ( basePath , d.ToString ( ) ) ; basePath = Helpers.DirMoveBack ( basePath ) ; } basePath = Helpers.DirMoveBack ( basePath ) ; } basePath = Helpers.DirMoveBack ( basePath ) ; } basePath = Helpers.DirMoveBack ( basePath ) ; } Console.ReadLine ( ) ; } // Creates folders ' 0 ' - ' 9 ' in the specified pathstatic void CreateFolders ( string path ) { for ( int a = 0 ; a < 10 ; a++ ) { Directory.CreateDirectory ( string.Format ( `` { 0 } \\ { 1 } '' , path , a ) ) ; Console.WriteLine ( string.Format ( `` { 0 } \\ { 1 } '' , path , a ) ) ; } } public static class Helpers { // Moves the directory back one step public static string DirMoveBack ( string path ) { for ( int a = path.Length - 1 ; a > 0 ; a -- ) if ( path [ a ] == '\\ ' ) return path.Substring ( 0 , a ) ; return path ; } }",Recursive Folder creation "C_sharp : In my code , a method is being called repeatedly within a loop like so : The method is likely to throw exceptions , but I do n't want the code to exit the loop after the first exception.Furthermore , the code above is being called from a web api controller , so I need a way to pass all the exception information back to the controller , where it will be handled ( log exception and return error response to the client ) .What I 've done so far is catch and store all the exception in a list.Considering that rethrowing all the errors in the list is not an option , what is the best approach to return the exception information to the controller ? foreach ( var file in files ) { SomeMethod ( file ) ; } var errors = new List < Exception > ( ) ; foreach ( var file in files ) { try { SomeMethod ( file ) ; } catch ( Exception ex ) { errors.Add ( ex ) ; } }",Handling multiple exceptions in a loop "C_sharp : In .Net4.5 , I find that the result of is true.The result I expect is false . I do n't know why . Can you help me ? Update : In the beginning , I was validating the regular expression ^- ? [ 1-9 ] \d*|0 $ which is used to match integer found on the internet and I find that the string with multiple 0 matches the regular expression . System.Text.RegularExpressions.Regex.IsMatch ( `` 00000000000000000000000000000 '' , `` ^ [ 1-9 ] |0 $ '' )",`` 00000000000000000000000000000 '' matches Regex `` ^ [ 1-9 ] |0 $ '' "C_sharp : I 'm having an issue with my Rabbit queues that is currently only reacting to the first message in queue , after that any other messages being pushed are being ignored.I start with instantiating the connection and declaring the queue in my IQueueConnectionProvider : That IQueueConnectionProvider is then used in my IQueueListener as a dependency with just one method : My log file ends up being just one line `` MESSAGE RECEIVED '' , however I can see in the Rabbit ui interface that my other services are pushing the messages to that queue just fine.Is there something I 'm missing here ? var connectionFactory = new ConnectionFactory ( ) { HostName = hostName } ; var connection = _connectionFactory.CreateConnection ( ) ; var channel = connection.CreateModel ( ) ; public void ListenToQueue ( string queue ) { var channel = _queueConnectionProvider.GetQueue ( ) ; var consumer = new EventingBasicConsumer ( channel ) ; consumer.Received += ( model , ea ) = > { string path = @ '' d : \debug.log.txt '' ; File.AppendAllLines ( path , new List < string > ( ) { `` MESSAGE RECEIVED '' , Environment.NewLine } ) ; var body = ea.Body ; var message = Encoding.UTF8.GetString ( body ) ; channel.BasicAck ( ea.DeliveryTag , false ) ; } ; channel.BasicConsume ( queue , true , consumer ) ; }",RabbitMQ only listens to the first message on a queue "C_sharp : Currently I 'm using Autofac for IoC and at two composition roots ( one for the front-end and one for the back-end ) I register and resolve the components spanned across Service , Business and Data layers.As of now I have a single one like 'AccountingModule ' . Now I 'm going to add several new Modules to the application , with a name like InventoryModule , ... My question is should I split each module classes among the layers ( Solution 1 ) or have all layers separately for each module ( Solution 2 ) Solution 1 : orSolution 2 : Edit 1Edit 2Architecture : Service Layer ( AccountingMoudle , InventoryModule , ... ) Business Layer ( AccountingMoudle , InventoryModule , ... ) Data Layer ( AccountingModule , InventoryModule , ... ) AccountingModule ( Service Layer , Business Layer , Data Layer ) InventoryModule ( Service Layer , Business Layer , Data Layer ) + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+ + -- -- -- -- -- -- -- -- -- -- -- -- -- -- ++ -- +AccountingServiceComponent +-+InventoryServiceComponent| Weak Dependency |+ -- +AccountingBusinessComponent < -- -- -- -- -- -- -- -- -- + +-+InventoryBusinessComponent| |+ -- +AccountingDataComponent +-+InventoryDataComponent + + +-+ GetDocumentByID ( int id ) + -- +GetProductByID ( int id ) | | +-+ SaveDocument ( Document d ) + -- +SaveProduct ( Product p )",Autofac Modules in N-Tier Architecture "C_sharp : I want to be able to use Linq 's '.where ' statement with my class 'Books ' ( a list of 'Book ' ) that implements interface IEnumerable.And I get the following error : Error 1 'Assignment2CuttingPhilip.Books ' does not contain a definition for 'Where ' and no extension method 'Where ' accepting a first argument of type 'Assignment2CuttingPhilip.Books ' could be found ( are you missing a using directive or an assembly reference ? ) C : \Users\Alex\Dropbox\cos570 CSharp\Assignment2CuttingPhilip\Assignment2CuttingPhilip\Assignement2PhilipCutting.cs 132 33 Assignment2CuttingPhilipMy Code is as follows : It should be pretty straight forward do this , but why cant I use my Enumerable Books list with Linq in C # ? Should n't I be able to make an enumerable list that I can query with Fluent Linq commands ? ThanksPhil //THE PROBLEM IS HERE.IEnumerable list3 = bookList.Where ( n = > n.author.Length > = 14 ) ; using System ; using System.Collections ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace Assignment2CuttingPhilip { public class Book { public string title ; public string author ; public Book ( string title , string author ) { this.title = title ; this.author = author ; } public override string ToString ( ) { return `` Title : \ ' '' + title + `` \ ' , Author : '' + author ; } } public class Books : IEnumerable { private Book [ ] _books ; public Books ( Book [ ] bArray ) { _books = new Book [ bArray.Length ] ; for ( int i = 0 ; i < bArray.Length ; i++ ) { _books [ i ] = bArray [ i ] ; } } IEnumerator IEnumerable.GetEnumerator ( ) { return ( IEnumerator ) GetEnumerator ( ) ; } public BooksEnum GetEnumerator ( ) { return new BooksEnum ( _books ) ; } } public class BooksEnum : IEnumerator { public Book [ ] _books ; int position = -1 ; public BooksEnum ( Book [ ] list ) { _books = list ; } public bool MoveNext ( ) { position++ ; return ( position < _books.Length ) ; } public void Reset ( ) { position = -1 ; } object IEnumerator.Current { get { return Current ; } } public Book Current { { try { return _books [ position ] ; } catch ( IndexOutOfRangeException ) { throw new InvalidOperationException ( ) ; } } } } class Assignement2PhilipCutting { static void Main ( string [ ] args ) { Book [ ] bookArray = new Book [ 3 ] { new Book ( `` Advance C # super stars '' , `` Prof Suad Alagic '' ) , new Book ( `` Finding the right lint '' , `` Philip Cutting '' ) , new Book ( `` Cat in the hat '' , `` Dr Sues '' ) } ; Books bookList = new Books ( bookArray ) ; IEnumerable List = from Book abook in bookList where abook.author.Length < = 14 select abook ; IEnumerable list2 = bookArray.Where ( n = > n.author.Length > = 14 ) ; //**THE PROBLEM IS HERE** . IEnumerable list3 = bookList.Where ( n = > n.author.Length > = 14 ) ; foreach ( Book abook in List ) { Console.WriteLine ( abook ) ; } } } }",My Enumerable class does not work with Linq statements like .where in c # "C_sharp : I have created an extension method as such..Which works great for the purposes I needed , however I now have a requirement to create a method with the same signature which checks if only exclusively those values have been set.Basically something like this.The only way I can think of doing this is by getting all available enumeration values checking which are set and confirming that only the two provided have been.Is there another way to solve this problem using some sort of bitwise operation ? public static bool AllFlagsSet < T > ( this T input , params T [ ] values ) where T : struct , IConvertible { bool allSet = true ; int enumVal = input.ToInt32 ( null ) ; foreach ( T itm in values ) { int val = itm.ToInt32 ( null ) ; if ( ! ( ( enumVal & val ) == val ) ) { allSet = false ; break ; } } return allSet ; } public static bool OnlyTheseFlagsSet < T > ( this T input , params T [ ] values ) where T : struct , IConvertible { }",Check if exclusively only these flags set in enumeration "C_sharp : I have some objects : Then I am trying to do something like Which throws an error similar to Could not create an instance of type MyObject ... Type is an interface or abstract class and can not be instantiated . Path 'MyField.IMyEntity.MyInt ' I ca n't change the field or entity , as that is in another group 's codebase . The MyObject class is in mine . Is there a way to deserialize this object ? I 've tried a few things with JsonSerializerSettings here JSON.NET - how to deserialize collection of interface-instances ? but to no avail . public class MyObject { public MyField Field { get ; set ; } } public class MyField { [ JsonProperty ] public Entity MyEntity { get ; set ; } public IEntity IMyEntity { get ; set ; } } public interface IEntity { string MyStr { get ; } } public class Entity : IEntity { } JsonConvert.DeserializeObject < MyObject > ( myObjStr ) ;",C # Json.Deserialize with Object with Child class with interfaces "C_sharp : My Question Is ThisWhat configuration step have I missed to make Mvc Surface Controllers work in Umbraco ? My theory is that since there is a folder in the default Umbraco install called /umbraco/ which is used to connect to the CMS that the physical path is interfiering with the route /umbraco/surface/ { Controller } / { Action } thus resulting in the ASP.NET YSOD ( and an IIS 404 when I try to access a controller on that route that is n't defined . ) Background InformationI have added this class to my App_Code folder in a freshly downloaded copy of Umbraco 6.1.6 : When I navigate to what I think should be the route for my Index ( ) method , I get a YSOD that says the resource could not be found : the code is not executed and the above error is displayed ; however , if I change the Uri to garbage I get an IIS 404 error : I started getting this in an existing site , thinking my site was screwed up I tried it in a new copy of Umbraco 6.1.6 and got the exact same results . For the record , I have also tried MembersSurfaceController and its associated Uri , which has the exact same result as above . YSOD when I hit the valid route , and IIS 404 when I don't.I have changed my umbracoSettings.config to MVC in the /config/ directory as well.updateI 'm using the out-of-the-box web.config file , which has this : On my default Umbraco site I do n't have any rewrite rules defined ; but on my actual site I have several rewrite rules in place . I 'm thinking that 's not causing it since I 'm seeing the same behavior on both sites though ... I have tried removing UrlRewrite completely I get the same results . public class MembersController : SurfaceController { public ActionResult Index ( ) { return Content ( `` Hello , Member ! `` ) ; } } < system.webServer > < validation validateIntegratedModeConfiguration= '' false '' / > < modules runAllManagedModulesForAllRequests= '' true '' > < remove name= '' UrlRewriteModule '' / > < add name= '' UrlRewriteModule '' type= '' UrlRewritingNet.Web.UrlRewriteModule , UrlRewritingNet.UrlRewriter '' / > . .. ...",Why am I getting the Yellow Screen Of Death on an Umbraco SurfaceController on a default/OOTB Umbraco installation ? "C_sharp : I am using the Repository pattern for EF and have ran into a problem in that I can not figure out how to set the connection string for the DbContext through a variable . Currently my constructor is parameterless ( it has to be to fit with he pattern ) i.e.EMDataContext used to take a string in its constructor to define the ConnectionString but can no longer do that so how do I actually tell the EMDataContext what to connect to when its created in this fashion ? IUnitOfWork uow = new UnitOfWork < EMDataContext > ( ) ; DeviceService deviceService = new DeviceService ( uow ) ; var what = deviceService.GetAllDevices ( ) ; public UnitOfWork ( ) { _ctx = new TContext ( ) ; _repositories = new Dictionary < Type , object > ( ) ; _disposed = false ; }",How to specify connection string when using db context "C_sharp : I 'm hoping to find a better way ( maybe with a nice linq expression ) to convert a string list like `` 41,42x,43 '' to a list of valid long 's . The below code works , but just feels ugly . string addressBookEntryIds = `` 41,42x,43 '' ; var ids = addressBookEntryIds.Split ( new [ ] { ' , ' , ' ; ' } , StringSplitOptions.RemoveEmptyEntries ) ; var addressBookEntryIdList =new List < long > ( ) ; foreach ( var rec in ids ) { long val ; if ( Int64.TryParse ( rec , out val ) ) { addressBookEntryIdList.Add ( val ) ; } }",Looking for a clean way to convert a string list to valid List < long > in C # C_sharp : Is there a rule of thumb to follow when to use the new keyword and when not to when declaring objects ? OR List < MyCustomClass > listCustClass = GetList ( ) ; List < MyCustomClass > listCustClass = new List < MyCustomClass > ( ) ; listCustClass = GetList ( ) ;,To `` new '' or not to `` new '' "C_sharp : i have this code in C # : It is not working . How can I tell it to call the method I gave it ? Secondly , I want t3 and t4 to be activated after t1 and t2 finish running . How can I do that ? Third , I want t1 and t2 to not block ( so that t2 would n't have to wait until t1 finishes ) . Is what I did correct ? Thread t1 = new Thread ( functionsActivations ( 3 , 4000 , 0 , 4 ) ) ; Thread t2 = new Thread ( functionsActivations ( 3 , 4000 , 5 , 9 ) ) ; t1.start ( ) ; t2.Start ( ) ; Thread t3 = new Thread ( functionsActivations ( 4 , 4000 , 0 , 4 ) ) ; Thread t4 = new Thread ( functionsActivations ( 4 , 4000 , 5 , 9 ) ) ;",activating threads C # "C_sharp : I am embedding IronPython into my game engine , where you can attach scripts to objects . I do n't want scripts to be able to just access the CLR whenever they want , because then they could pretty much do anything.Having random scripts , especially if downloaded from the internet , being able to open internet connections , access the users HDD , or modify the internal game state is a very bad thing.Normally people would just suggest , `` Use a seperate AppDomain '' . However , unless I am severely mistaken , cross-AppDomains are slow . Very slow . Too slow for a game engine . So I am looking at alternatives.I thought about compiling a custom version of IronPython that stops you from being able import clr or any namespace , thus limiting it to the standard library.The option I would rather go with goes along the following lines : I read this in another stack overflow post.Assume that instead of setting __ builtins_._ import__ to none , I instead set it to a custom function that lets you load the standard API.The question is , using the method outlined above , would there be any way for a script to be able to be able to get access to the clr module , the .net BCL , or anything else that could potentially do bad things ? Or should I go with modifying the source ? A third option ? __builtins__.__import__ = None # Stops imports workingreload = None # Stops reloading working ( specifically stops them reloading builtins # giving back an unbroken __import___ !",Embedded IronPython Security "C_sharp : There are quite a few other questions similiar to this but none of them seem to do what I 'm trying to do . I 'd like pass in a list of string and query or likeI 've been playing around with a.sysid.Contains ( ) but have n't been able to get anywhere . SELECT ownerid where sysid in ( `` , `` , `` ) -- i.e . List < string > var chiLst = new List < string > ( ) ; var parRec = Lnq.attlnks.Where ( a = > a.sysid IN chiList ) .Select ( a = > a.ownerid ) ;",LINQ flavored IS IN Query "C_sharp : I am attempting to write a filter that wraps data to follow the JSON API spec and so far I 've got it working on all cases where I directly return an ActionResult , such as ComplexTypeJSON . I am trying to get it to work in situations like ComplexType where I do not have to run the Json function constantly.However , by the time public override void OnActionExecuted ( ActionExecutedContext filterContext ) runs when I navigate to ComplexType , the filterContext.Result is a Content Result , that is just a string where filterContext.Result.Content is simply : Is there a way I can set something up to make ComplexType become JsonResult rather than ContentResult ? For context , here are the exact files : TestController.csJSONApiFilter.cs [ JSONAPIFilter ] public IEnumerable < string > ComplexType ( ) { return new List < string > ( ) { `` hello '' , `` world '' } ; } [ JSONAPIFilter ] public JsonResult ComplexTypeJSON ( ) { return Json ( new List < string > ( ) { `` hello '' , `` world '' } ) ; } `` System.Collections.Generic.List ` 1 [ System.String ] '' namespace MyProject.Controllers { using System ; using System.Collections.Generic ; using System.Web.Mvc ; using MyProject.Filters ; public class TestController : Controller { [ JSONAPIFilter ] public IEnumerable < string > ComplexType ( ) { return new List < string > ( ) { `` hello '' , `` world '' } ; } [ JSONAPIFilter ] public JsonResult ComplexTypeJSON ( ) { return Json ( new List < string > ( ) { `` hello '' , `` world '' } ) ; } // GET : Test [ JSONAPIFilter ] public ActionResult Index ( ) { return Json ( new { foo = `` bar '' , bizz = `` buzz '' } ) ; } [ JSONAPIFilter ] public string SimpleType ( ) { return `` foo '' ; } [ JSONAPIFilter ] public ActionResult Throw ( ) { throw new InvalidOperationException ( `` Some issue '' ) ; } } } namespace MyProject.Filters { using System ; using System.Collections.Generic ; using System.Linq ; using System.Web.Mvc ; using MyProject.Exceptions ; using MyProject.Models.JSONAPI ; public class JSONAPIFilterAttribute : ActionFilterAttribute , IExceptionFilter { private static readonly ISet < Type > IgnoredTypes = new HashSet < Type > ( ) { typeof ( FileResult ) , typeof ( JavaScriptResult ) , typeof ( HttpStatusCodeResult ) , typeof ( EmptyResult ) , typeof ( RedirectResult ) , typeof ( ViewResultBase ) , typeof ( RedirectToRouteResult ) } ; private static readonly Type JsonErrorType = typeof ( ErrorModel ) ; private static readonly Type JsonModelType = typeof ( ResultModel ) ; public override void OnActionExecuted ( ActionExecutedContext filterContext ) { if ( filterContext == null ) { throw new ArgumentNullException ( `` filterContext '' ) ; } if ( IgnoredTypes.Any ( x = > x.IsInstanceOfType ( filterContext.Result ) ) ) { base.OnActionExecuted ( filterContext ) ; return ; } var resultModel = ComposeResultModel ( filterContext.Result ) ; var newJsonResult = new JsonResult ( ) { JsonRequestBehavior = JsonRequestBehavior.AllowGet , Data = resultModel } ; filterContext.Result = newJsonResult ; base.OnActionExecuted ( filterContext ) ; } public override void OnActionExecuting ( ActionExecutingContext filterContext ) { var modelState = filterContext.Controller.ViewData.ModelState ; if ( modelState == null || modelState.IsValid ) { base.OnActionExecuting ( filterContext ) ; } else { throw new ModelStateException ( `` Errors in ModelState '' ) ; } } public virtual void OnException ( ExceptionContext filterContext ) { if ( filterContext == null ) { throw new ArgumentNullException ( `` filterContext '' ) ; } if ( filterContext.Exception == null ) return ; // Todo : if modelstate error , do not provide that message // set status code to 404 var errors = new List < string > ( ) ; if ( ! ( filterContext.Exception is ModelStateException ) ) { errors.Add ( filterContext.Exception.Message ) ; } var modelState = filterContext.Controller.ViewData.ModelState ; var modelStateErrors = modelState.Values.SelectMany ( x = > x.Errors ) .Select ( x = > x.ErrorMessage ) .ToList ( ) ; if ( modelStateErrors.Any ( ) ) errors.AddRange ( modelStateErrors ) ; var errorCode = ( int ) System.Net.HttpStatusCode.InternalServerError ; var errorModel = new ErrorModel ( ) { status = errorCode.ToString ( ) , detail = filterContext.Exception.StackTrace , errors = errors , id = Guid.NewGuid ( ) , title = filterContext.Exception.GetType ( ) .ToString ( ) } ; filterContext.ExceptionHandled = true ; filterContext.HttpContext.Response.Clear ( ) ; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true ; filterContext.HttpContext.Response.StatusCode = errorCode ; var newResult = new JsonResult ( ) { Data = errorModel , JsonRequestBehavior = JsonRequestBehavior.AllowGet } ; filterContext.Result = newResult ; } private ResultModel ComposeResultModel ( ActionResult actionResult ) { var newModelData = new ResultModel ( ) { } ; var asContentResult = actionResult as ContentResult ; if ( asContentResult ! = null ) { newModelData.data = asContentResult.Content ; return newModelData ; } var asJsonResult = actionResult as JsonResult ; if ( asJsonResult == null ) return newModelData ; var dataType = asJsonResult.Data.GetType ( ) ; if ( dataType ! = JsonModelType ) { newModelData.data = asJsonResult.Data ; } else { newModelData = asJsonResult.Data as ResultModel ; } return newModelData ; } } }",Is it possible to intercept an action from becoming a ContentResult ? "C_sharp : Attempting to make a protected internal member of a protected internal class within a public class results with the following issue : Inconsistent accessibility : field type 'what.Class1.ProtectedInternalClass ' is less accessible than field 'what.Class1.SomeDataProvider.data'The accessibility should be equivalent , as far as I know.Where am I mistaken ? Origination class : Verifying protected and internal properties , same assembly : Verifying protected and internal properties , different assembly : using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace what { public class Class1 { // This class can not be modified , is only // here to produce a complete example . public class PublicClass { public PublicClass ( ) { } } protected internal class ProtectedInternalClass : PublicClass { public ProtectedInternalClass ( ) { } public void SomeExtraFunction ( ) { } } public class SomeDataProvider { public int AnInterestingValue ; public int AnotherInterestingValue ; protected internal ProtectedInternalClass data ; // < -- - Occurs here . public PublicClass Data { get { return data ; } } } public static SomeDataProvider RetrieveProvider ( ) { SomeDataProvider provider = new SomeDataProvider ( ) ; provider.data = new ProtectedInternalClass ( ) ; provider.data.SomeExtraFunction ( ) ; return provider ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace what { public class Class2 : Class1 { public Class2 ( ) { var pi = new ProtectedInternalClass ( ) ; var provider = new SomeDataProvider ( ) ; provider.data = pi ; } // no errors here } public class Class3 { public Class3 ( ) { var pi = new Class1.ProtectedInternalClass ( ) ; var provider = new Class1.SomeDataProvider ( ) ; provider.data = pi ; } // no errors here } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace some_other_assembly { public class Class4 : what.Class1 { public Class4 ( ) { var pi = new ProtectedInternalClass ( ) ; var provider = new SomeDataProvider ( ) ; provider.data = pi ; } // no errors here } public class Class5 { public Class5 ( ) { var pi = new what.Class1.ProtectedInternalClass ( ) ; // < -- - Inaccessible due to protection level , as it should be . var provider = new what.Class1.SomeDataProvider ( ) ; provider.data = pi ; // < -- - Intellisense implies inaccessible , but not indicated via error . } } }",Inconsistent accessibility with protected internal member C_sharp : I 'm just getting curious about the following code : As I 've understood the static class Container will be initialized when the following code executes : Am I right ? Any explanations on static generic classes/members initialization would be appreciated . Thanks in advance . public static class Container < T > { public static readonly T [ ] EmptyArray = new T [ 0 ] ; } ... var emptyArray = Container < int > .EmptyArray ; ...,Generic static fields initialization C_sharp : I just implemented Clone from ICloneable and realized that the event subscriptions from my source instance also followed . Is there a good way to clear all those ? Currently I am using a couple of these loops for every event I have to clear everything.This works fine but clutters the code a bit . Mostly worried to get event dangling . foreach ( var eventhandler in OnIdChanged.GetInvocationList ( ) ) { OnIdChanged -= ( ItemEventHandler ) eventhandler ; } foreach ( var eventhandler in OnNameChanged.GetInvocationList ( ) ) { ...,Clear All Event subscriptions ( Clone linked ) "C_sharp : I 'm writing a web page , and it calls some web services . The calls looked like this : During code review , somebody said that I should change it to : Why ? What 's the difference ? var Data1 = await WebService1.Call ( ) ; var Data2 = await WebService2.Call ( ) ; var Data3 = await WebService3.Call ( ) ; var Task1 = WebService1.Call ( ) ; var Task2 = WebService2.Call ( ) ; var Task3 = WebService3.Call ( ) ; var Data1 = await Task1 ; var Data2 = await Task2 ; var Data3 = await Task3 ;",When to use the `` await '' keyword "C_sharp : I have a simple try/catch blockThe catch is never executed and the runtime reports 'OracleException was unhandled ' at [ 1 ] which just makes my head spin . Clearly , I have a catch statement for the associated exception type . I 've even tried the fully qualified type , Oracle.DataAccess.Client.OracleException at [ 2 ] and still the exception is unhandled . The only way I can actually get the catch to work is by catching System.Exception at [ 2 ] . What is causing this odd behavior ? try { // Open the connection _connection.Open ( ) ; // [ 1 ] } catch ( OracleException ex ) // [ 2 ] { // Handle the exception int x = ex.ErrorCode ; }",Odd Try/Catch Behavior "C_sharp : The following code is intended to recursively check or un-check parent or child nodes as required.For instance , at this position , A , G , L , and T nodes must be unchecked if we un-check any one of them.The problem with the following code is , whenever I double-click any node the algorithm fails to achieve its purpose.The tree-searching algorithm starts here : Driver ProgramExpected to happen : Take a look at the screenshot of the application . A , G , L , and T are checked . If I uncheck , say , L , - T should be unchecked as T is a child of L. - G and A should be unchecked as they will have no children left.What is happening : This application code works fine if I single-click any node . If I double-click a node , that node becomes checked/unchecked but the same change is not reflected on the parent and children . Double-click also freezes the application for a while.How can I fix this issue and obtain the expected behavior ? // stack is used to traverse the tree iteratively . Stack < TreeNode > stack = new Stack < TreeNode > ( ) ; private void treeView1_AfterCheck ( object sender , TreeViewEventArgs e ) { TreeNode selectedNode = e.Node ; bool checkedStatus = e.Node.Checked ; // suppress repeated even firing treeView1.AfterCheck -= treeView1_AfterCheck ; // traverse children stack.Push ( selectedNode ) ; while ( stack.Count > 0 ) { TreeNode node = stack.Pop ( ) ; node.Checked = checkedStatus ; System.Console.Write ( node.Text + `` , `` ) ; if ( node.Nodes.Count > 0 ) { ICollection tnc = node.Nodes ; foreach ( TreeNode n in tnc ) { stack.Push ( n ) ; } } } //traverse parent while ( selectedNode.Parent ! =null ) { TreeNode node = selectedNode.Parent ; node.Checked = checkedStatus ; selectedNode = selectedNode.Parent ; } // `` suppress repeated even firing '' ends here treeView1.AfterCheck += treeView1_AfterCheck ; string str = string.Empty ; } using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Drawing ; using System.Windows.Forms ; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } # region MyRegion private void button1_Click ( object sender , EventArgs e ) { TreeNode a = new TreeNode ( `` A '' ) ; TreeNode b = new TreeNode ( `` B '' ) ; TreeNode c = new TreeNode ( `` C '' ) ; TreeNode d = new TreeNode ( `` D '' ) ; TreeNode g = new TreeNode ( `` G '' ) ; TreeNode h = new TreeNode ( `` H '' ) ; TreeNode i = new TreeNode ( `` I '' ) ; TreeNode j = new TreeNode ( `` J '' ) ; TreeNode k = new TreeNode ( `` K '' ) ; TreeNode l = new TreeNode ( `` L '' ) ; TreeNode m = new TreeNode ( `` M '' ) ; TreeNode n = new TreeNode ( `` N '' ) ; TreeNode o = new TreeNode ( `` O '' ) ; TreeNode p = new TreeNode ( `` P '' ) ; TreeNode q = new TreeNode ( `` Q '' ) ; TreeNode r = new TreeNode ( `` R '' ) ; TreeNode s = new TreeNode ( `` S '' ) ; TreeNode t = new TreeNode ( `` T '' ) ; TreeNode u = new TreeNode ( `` U '' ) ; TreeNode v = new TreeNode ( `` V '' ) ; TreeNode w = new TreeNode ( `` W '' ) ; TreeNode x = new TreeNode ( `` X '' ) ; TreeNode y = new TreeNode ( `` Y '' ) ; TreeNode z = new TreeNode ( `` Z '' ) ; k.Nodes.Add ( x ) ; k.Nodes.Add ( y ) ; l.Nodes.Add ( s ) ; l.Nodes.Add ( t ) ; l.Nodes.Add ( u ) ; n.Nodes.Add ( o ) ; n.Nodes.Add ( p ) ; n.Nodes.Add ( q ) ; n.Nodes.Add ( r ) ; g.Nodes.Add ( k ) ; g.Nodes.Add ( l ) ; i.Nodes.Add ( m ) ; i.Nodes.Add ( n ) ; j.Nodes.Add ( b ) ; j.Nodes.Add ( c ) ; j.Nodes.Add ( d ) ; a.Nodes.Add ( g ) ; a.Nodes.Add ( h ) ; a.Nodes.Add ( i ) ; a.Nodes.Add ( j ) ; treeView1.Nodes.Add ( a ) ; treeView1.ExpandAll ( ) ; button1.Enabled = false ; } # endregion",WinForms TreeView checking/unchecking hierarchy "C_sharp : I am working with Code First EntityFramework ( version= '' 6.1.0 '' ) and EntityFramework.Extended ( version= '' 6.1.0.96 , the latest build at the moment from here . The DbContext exposes the DbSets which are accessed like : Today I decided to try Future Queries of the EntityFramework.Extended library , and ended pretty much soon , without an idea of how to proceed.Here is the sample code : Regarding the Future ( ) documentation I should get only one query to the DB which is what the Future ( ) method provides . The query should be launched at u.ToList ( ) ; but what happens is that I get an error like this : JIT Compiler encountered an internal limitation.A stack trace dive tells me this : at EntityFramework.Future.FutureQueryBase 1.GetResult ( ) at EntityFramework.Future.FutureQuery 1.GetEnumerator ( ) at System.Collections.Generic.List 1..ctor ( IEnumerable 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable 1 source ) at App.Program.Main ( String [ ] args ) in c : \Users\ ... \App\Program.cs : line 25I really do n't know what I 'm missing out . I 've checked that my ConnectionString has MultipleResultSets set to TRUE . I 've tested this with earlier build releases of EF.Exteneded but the same error occured.Any idea would greatly help . var set = ctx.Set < MyEntity > ( ) ; using ( var ctx = new MyDbContext ( ) ) { var u = ctx.Set < User > ( ) .Future ( ) ; var c = ctx.Set < Country > ( ) .Future ( ) ; var users = u.ToList ( ) ; }",EntityFramework.Extended Future error ( JIT Compiler internal limitation ) "C_sharp : Consider the console application below , featuring a method with a generic catch handler that catches exceptions of type TException.When this console application is built with the 'Debug ' configuration and executed under the Visual Studio debugger ( i.e . through the *.vshost.exe ) this fails , in both Visual Studio 2005 and Visual Studio 2008.I believe this problem only came about after I installed Visual Stuido 2008.Under the following circumstances the code behaves as expected : If built with 'Release ' configuration , it succeeds.If executed via the *.exe directly , rather than through Visual Studio ( F5 ) , it succeeds.If attaching a debugger by putting System.Diagnostics.Debugger.Launch ( ) ; on line 1 of Main ( ) it still succeeds.When the console application is launched from within Visual Studio ( 2005 or 2008 ) , and therefore executed under ConsoleApplication.vshost.exe , it fails.Here is my output for the failure caseWhat is causing this peculiar failure ? using System ; class Program { static void Main ( ) { Console.WriteLine ( Environment.Version ) ; CatchAnException < TestException > ( ) ; Console.ReadKey ( ) ; } private static void CatchAnException < TException > ( ) where TException : Exception { Console.WriteLine ( `` Trying to catch a < { 0 } > ... '' , typeof ( TException ) .Name ) ; try { throw new TestException ( ) ; } catch ( TException ex ) { Console.WriteLine ( `` *** PASS ! *** '' ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Caught < { 0 } > in 'catch ( Exception ex ) ' handler . `` , ex.GetType ( ) .Name ) ; Console.WriteLine ( `` *** FAIL ! *** '' ) ; } Console.WriteLine ( ) ; } } internal class TestException : Exception { } 2.0.50727.3068Trying to catch a < TestException > ... *** FAIL ! ***Caught < TestException > in 'catch ( Exception ex ) ' handler . Expected : < TestException > Actual : < TestException > Result of typeof ( TException ) == ex.GetType ( ) is True",Why does catch ( TException ) handling block behaviour differ under the debugger after installing Visual Studio 2008 ? "C_sharp : I have something similar to the following code on domain.com : It works great communicating with my .NET API . response.data has all of the data my server needs to give me . However we have a new security token that we are passing to the client from the API and we are passing it in back to the client in the packet header . I know that the token is being passed back because I can read it in the packet on the network tab in chrome debugger . However response.headers ( ) only contains content-type : '' application/json ; charset=utf-8 '' It does n't have what is in the packet . Any one have an idea ? The data is returned from the API like so ( C # ) HttpContext.Current.Response.AppendHeader ( `` session '' , Guid.NewGuid ( ) .ToString ( ) ) ; So i would expect response to have a header called session , but it does not . It is however in the packet . $ http.post ( `` http : //api.domain.com/Controller/Method '' , JSON.stringify ( data ) , { headers : { 'Content-Type ' : 'application/json ' } } ) .then ( function ( response ) { console.log ( response ) ; } , function ( response ) { // something went wrong } ) ; }",How can I read headers sent from my API with angular ? "C_sharp : Given the statementsWhat can we assert in a unit test about d ? For example this does not work : The best way I found so far is to convert the value back : Which would be the same as the brute way to sayThis question is NOT about double and float precision in general but really JUST about the pragmatic question how a unit test can best describe the confines of d. In my case , d is the result of a conversion that occurs in code generated by light weight code generation . While testing this code generation , I have to make assertions about the outcome of this function and this finally boils down to the simple question above . float f = 7.1f ; double d = f ; Console.WriteLine ( d == 7.1d ) ; // falseConsole.WriteLine ( d < 7.1d + float.Epsilon ) ; // true by luckConsole.WriteLine ( d > 7.1d - float.Epsilon ) ; // false ( less luck ) float f2 = ( float ) d ; Console.WriteLine ( f2 == f ) ; // true Console.WriteLine ( d == 7.1f ) ; // 7.1f implicitly converted to double as above",Float to Double conversion - Best assertion in a unit test ? "C_sharp : Here is my Interval definition : In the code above , I feed the IScheduler in both Interval & ObserveOn from a SchedulerProvider so that I can unit test faster ( TestScheduler.AdvanceBy ) . Also , DoWork is an async method.In my particular case , I want the DoWork function to be called every 5 seconds . The issue here is that I want the 5 seconds to be the time between the end of DoWork and the start of the other . So if DoWork takes more than 5 seconds to execute , let 's say 10 seconds , the first call would be at 5 seconds and the second call at 15 seconds.Unfortunately , the following test proves it does not behave like that : The DoWork calls the CustomQueryAsync and the test fails saying that is was called twice . It should only be called once because of the delay forced with .Callback ( ( ) = > Thread.Sleep ( 1000 ) ) .What am I doing wrong here ? My actual implementation comes from this example . m_interval = Observable.Interval ( TimeSpan.FromSeconds ( 5 ) , m_schedulerProvider.EventLoop ) .ObserveOn ( m_schedulerProvider.EventLoop ) .Select ( l = > Observable.FromAsync ( DoWork ) ) .Concat ( ) .Subscribe ( ) ; [ Fact ] public void MultiPluginStatusHelperShouldWaitForNextQuery ( ) { m_queryHelperMock .Setup ( x = > x.CustomQueryAsync ( ) ) .Callback ( ( ) = > Thread.Sleep ( 10000 ) ) .Returns ( Task.FromResult ( new QueryCompletedEventData ( ) ) ) .Verifiable ( ) ; var multiPluginStatusHelper = m_container.GetInstance < IMultiPluginStatusHelper > ( ) ; multiPluginStatusHelper.MillisecondsInterval = 5000 ; m_testSchedulerProvider.EventLoopScheduler.AdvanceBy ( TimeSpan.FromMilliseconds ( 5000 ) .Ticks ) ; m_testSchedulerProvider.EventLoopScheduler.AdvanceBy ( TimeSpan.FromMilliseconds ( 5000 ) .Ticks ) ; m_queryHelperMock.Verify ( x = > x.CustomQueryAsync ( ) , Times.Once ) ; }",Reactive extension fixed Interval between async calls when call is longer than Interval length "C_sharp : This is related to my other question How to cancel background printing . I am trying to better understand the CancellationTokenSource model and how to use it across thread boundaries.I have a main window ( on the UI thread ) where the code behind does : which correctly calls the CloseWindow code when it is closed : With the selection of a menu item , a second window is created on a background thread : In the MainWindowViewModel ( on the UI thread ) , I put : With its constructor of : Now my problem . When closing the MainWindow on the UI thread , windowClosingCTS.Cancel ( ) causes an immediate call to the delegate registered with ct , i.e . previewWindow.Close ( ) is called . This now throws immediately back to the `` If ( Windows ! = null ) with : `` The calling thread can not access this object because a different thread owns it . `` So what am I doing wrong ? public MainWindow ( ) { InitializeComponent ( ) ; Loaded += ( s , e ) = > { DataContext = new MainWindowViewModel ( ) ; Closing += ( ( MainWindowViewModel ) DataContext ) .MainWindow_Closing ; } ; } private void CloseWindow ( IClosable window ) { if ( window ! = null ) { windowClosingCTS.Cancel ( ) ; window.Close ( ) ; } } // Print Preview public static void PrintPreview ( FixedDocument fixeddocument , CancellationToken ct ) { // Was cancellation already requested ? if ( ct.IsCancellationRequested ) ct.ThrowIfCancellationRequested ( ) ; ... ... ... ... ... ... ... ... ... ... . // Use my custom document viewer ( the print button is removed ) . var previewWindow = new PrintPreview ( fixedDocumentSequence ) ; //Register the cancellation procedure with the cancellation token ct.Register ( ( ) = > previewWindow.Close ( ) ) ; previewWindow.ShowDialog ( ) ; } } public CancellationTokenSource windowClosingCTS { get ; set ; } // Constructor public MainMenu ( ) { readers = new List < Reader > ( ) ; CloseWindowCommand = new RelayCommand < IClosable > ( this.CloseWindow ) ; windowClosingCTS = new CancellationTokenSource ( ) ; }",How to use CancellationTokenSource to close a dialog on another thread ? "C_sharp : I was reading a book illustrated C # 2012 in the section Combining Delegates point not notice that ? Purpose of the delegates are immutable . Combining Delegates All the delegates you ’ ve seen so far have had only a single method in their invocation lists . Delegates can be “ combined ” by using the addition operator . The result of the operation is the creation of a new delegate , with an invocation list that is the concatenation of copies of the invocation lists of the two operand delegates . For example , the following code creates three delegates . The third delegate is created from the combination of the first two . Although the term combining delegates might give the impression that the operand delegates are modified , they are not changed at all . In fact , delegates are immutable . After a delegate object is created , it can not be changed . Figure 15-6 illustrates the results of the preceding code . Notice that the operand delegates remain unchanged . MyDel delA = myInstObj.MyM1 ; MyDel delB = SClass.OtherM2 ; MyDel delC = delA + delB ; // Has combined invocation list",What is the purpose of the delegates are immutable in c # ? "C_sharp : Given the following code , why is n't the static constructor of `` Outer '' called after the first line of `` Main '' ? namespace StaticTester { class Program { static void Main ( string [ ] args ) { Outer.Inner.Go ( ) ; Console.WriteLine ( ) ; Outer.Go ( ) ; Console.ReadLine ( ) ; } } public static partial class Outer { static Outer ( ) { Console.Write ( `` In Outer 's static constructor\n '' ) ; } public static void Go ( ) { Console.Write ( `` Outer Go\n '' ) ; } public static class Inner { static Inner ( ) { Console.Write ( `` In Inner 's static constructor\n '' ) ; } public static void Go ( ) { Console.Write ( `` Inner Go\n '' ) ; } } } }",Why is n't the static constructor of the parent class called when invoking a method on a nested class ? "C_sharp : I want to identify an OS , but not by a String as I want to map this as an ID.Several ways of going about this , so my question is : Does anyone have a list of all the possible answers this produces ? Or , is there a way to reverse lookup the Caption field based on any other field ? By looking at https : //msdn.microsoft.com/en-us/library/windows/desktop/aa394239 ( v=vs.85 ) .aspx there does n't seem to be enough info to recreate the Caption from all the other properties.Here 's a sample of this result on my machine : Then again that link is n't verbose enough , as Google tells me that OperatingSystemSKU has more than 26 items , as I 've found 49 or even 103.Another route is with Environment.OSVersion but I think it 's even worse than what i 'm looking at.So either I build a table for some form of lookup , or I reverse lookup an existing internal library.My current solution is to get the OS Version and cross-reference a list I made from https : //en.wikipedia.org/wiki/List_of_Microsoft_Windows_versionsUpdate : Instead of sending a string with the OS Name , to my API , for bandwidth concerns , I want to send a unique ID that I can reverse lookup to retrieve the OS from the ID.I 'm currently building this database dynamically , using the string value of the OS and then an ID every other time.I would like a solution that can retrieve the Caption field if I have some of the other fields of Win32_OperatingSystem and assuming that both client and server side have the latest dlls/SDKs.TIA var name = ( from x in new System.Management.ManagementObjectSearcher ( `` SELECT * FROM Win32_OperatingSystem '' ) .Get ( ) .OfType < System.Management.ManagementObject > ( ) select x.GetPropertyValue ( `` Caption '' ) ) .FirstOrDefault ( ) ; BootDevice : \Device\HarddiskVolume1BuildNumber : 10586BuildType : Multiprocessor FreeCaption : Microsoft Windows 10 Pro NCodeSet : 1252CountryCode : 1CreationClassName : Win32_OperatingSystemCSCreationClassName : Win32_ComputerSystemCSDVersion : CSName : DESKTOP-6UJPPDSCurrentTimeZone : 120DataExecutionPrevention_32BitApplications : TrueDataExecutionPrevention_Available : TrueDataExecutionPrevention_Drivers : TrueDataExecutionPrevention_SupportPolicy : 2Debug : FalseDescription : Distributed : FalseEncryptionLevel : 256ForegroundApplicationBoost : 2FreePhysicalMemory : 2027936FreeSpaceInPagingFiles : 4486600FreeVirtualMemory : 2611432InstallDate : 20151223101608.000000+120LargeSystemCache : LastBootUpTime : 20160215101020.112003+120LocalDateTime : 20160225114508.446000+120Locale : 0409Manufacturer : Microsoft CorporationMaxNumberOfProcesses : 4294967295MaxProcessMemorySize : 137438953344MUILanguages : System.String [ ] Name : Microsoft Windows 10 Pro N|C : \WINDOWS|\Device\Harddisk0\Partition2NumberOfLicensedUsers : 0NumberOfProcesses : 157NumberOfUsers : 2OperatingSystemSKU : 49Organization : OSArchitecture : 64-bitOSLanguage : 1033OSProductSuite : 256OSType : 18OtherTypeDescription : PAEEnabled : PlusProductID : PlusVersionNumber : PortableOperatingSystem : FalsePrimary : TrueProductType : 1RegisteredUser : developerSerialNumber : 00332-00331-71784-AA054ServicePackMajorVersion : 0ServicePackMinorVersion : 0SizeStoredInPagingFiles : 4637884Status : OKSuiteMask : 272SystemDevice : \Device\HarddiskVolume2SystemDirectory : C : \WINDOWS\system32SystemDrive : C : TotalSwapSpaceSize : TotalVirtualMemorySize : 12910660TotalVisibleMemorySize : 8272776Version : 10.0.10586WindowsDirectory : C : \WINDOWS",Identify system operating system by id "C_sharp : I would like to preface that I have not used Dynamic Objects very often , and only recently came across this problem . I have a specific scenario that I will explain below , but I was wondering what exactly were the advantages of implementing a dynamic object compared to creating a class for that object.I have a method that takes a dynamic object as a parameter . For the sake of length I will not post much code just enough to get the point across : In this case , inputObject will have properties that help identify the employee taxes without directly being related to the employee class . Primarily I have given the inputObject the following properties : Are there any advantages to making this it 's own class versus using a dynamic object ? Are there any benefits one way or the other ? public static Tax GetEmployeeTax ( string Id , Employee employee , dynamic inputObject ) { var temp = new Employee ( ) ; //use the dynamic object propertiesreturn temp ; } dynamic dynamicEmployeeTax = new ExpandoObject ( ) ; dynamicEmployeeTax.FederalTaxInfo = `` Some information '' ; dynamicEmployeeTax.StateTaxInfo = `` Some other information '' ;",What is the advantage of using an Dynamic object over creating a class of that object ? "C_sharp : I have a list of about 10,000 staff members in a List < T > and I have a ListBox which contains a subset of those staff , depending on the search term in a text box.Say a Staff object has the following publicly exposed properties : I could write a function like this : and then do something like : The filtering is re-evaluated every time the user changes the contents of the tbSrch box.This works , and it 's not awfully slow , but I was wondering if I could make it any faster ? I have tried to re-write the whole thing to be multi-threaded , however with only 10,000 staff members the overhead seemed to take away the bulk of the benefit . Also , there were a bunch of other bugs like if searching for `` John '' , the user first presses `` J '' which spools up the threads , but when the user presses the `` o '' another set are spooled up before the first lot have had a chance to return their results . A lot of the time , the results get returned in a jumbled order and all sorts of nasty things happen.I can think of a few tweaks that would make the best-case scenario significantly better , but they would also make the worst-case scenario a lot worse.Do you have any ideas on how this can be improved ? Great suggestions I 've implemented far , and their results : Add a delay on the ValueChanged event so that if the user types a 5-character name quickly on the keyboard , it only performs 1 search at the end rather than 5 in series.Pre-evaluate ToLower ( ) and store in the Staff class ( as a [ NonSerialized ] attribute so it does n't take up extra space in the save file ) .Add a get property in Staff which returns all the search criteria as a single , long , lower-case , concatenated string . Then run a single Contains ( ) on that . ( This string is stored in the Staff object so it only gets constructed once . ) So far , these have lowered search times from around 140ms to about 60ms ( though these numbers are highly subjective depending on the actual search performed and number of results returned ) . string FirstNamestring LastNamestring MiddleName int StaffID int CostCentre bool staffMatchesSearch ( Staff stf ) { if ( tbSrch.Text.Trim ( ) == string.Empty ) return true ; // No search = match always . string s = tbSrch.Text.Trim ( ) .ToLower ( ) ; // Do the checks in the order most likely to return soonest : if ( stf.LastName.ToLower ( ) .Contains ( s ) ) return true ; if ( stf.FirstName.ToLower ( ) .Contains ( s ) ) return true ; if ( stf.MiddleName.ToLower ( ) .Contains ( s ) ) return true ; if ( stf.CostCentre.ToString ( ) .Contains ( s ) ) return true ; // Yes , we want partial matches on CostCentre if ( stf.StaffID.ToString ( ) .Contains ( s ) ) return true ; // And also on StaffID return false ; } tbSrch_TextChanged ( object sender , EventArgs e ) { lbStaff.BeginUpdate ( ) ; lbStaff.Items.Clear ( ) ; foreach ( Staff stf in staff ) if ( staffMatchesSearch ( stf ) ) lbStaff.Items.Add ( stf ) ; lbStaff.EndUpdate ( ) ; }",High-speed string matching in C # "C_sharp : I want a method like OrderBy ( ) that always orders ignoring accented letters and to look at them like non-accented . I already tried to override OrderBy ( ) but seems I ca n't do that because that is a static method.So now I want to create a custom lambda expression for OrderBy ( ) , like this : However , I 'm getting this error : Error 2 The type arguments for method 'System.Linq.Enumerable.OrderBy < TSource , TKey > ( System.Collections.Generic.IEnumerable < TSource > , System.Func < TSource , TKey > , System.Collections.Generic.IComparer < TKey > ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.Seems it does n't like StringComparer . How can I solve this ? Note : I already tried to use RemoveDiacritics ( ) from here but I do n't know how to use that method in this case . So I tried to do something like this which seems nice too . public static IOrderedEnumerable < TSource > ToOrderBy < TSource , TKey > ( this IEnumerable < TSource > source , Func < TSource , TKey > keySelector ) { if ( source == null ) return null ; var seenKeys = new HashSet < TKey > ( ) ; var culture = new CultureInfo ( `` pt-PT '' ) ; return source.OrderBy ( element = > seenKeys.Add ( keySelector ( element ) ) , StringComparer.Create ( culture , false ) ) ; }",OrderBy ignoring accented letters "C_sharp : is it possible to extend the query-keywords of Linq ( like : select , where , etc . ) with own definitions ? Codeexample to make it clearer : I think it 's not possible , but still hoping ; ) System.Collections.Generic.List < string > aList = new System.Collections.Generic.List < string > { `` aa '' , `` ab '' , `` ba '' , `` bb '' } ; // instead ofstring firstString = ( from item in aList where item.StartsWith ( `` a '' ) select item ) .First ( ) ; // would be nicestring firstString = from item in aList where item.StartsWith ( `` a '' ) selectFirst item ; // or something elsefrom item in aListwhere item.StartsWith ( `` a '' ) WriteLineToConsole item ;",Is it possible to extend the Query-Keywords in C # / LINQ ? "C_sharp : I am manually binding an entity framework code first table to a datagridview . When I set the AutoSizeMode to AllCells and add an instance to the table I get a NullReferenceException during Add.The code runs like this : Here is the relevant part from the stack trace : The table Persons is otherwise empty . When I remove the AutoSize - Instruction everything is fine.Plattform : WInForms in .Net 4.5.1 using Studio 2013 ; Running Win8 Pro , EF 6.1.3Edit : Removed typo that introduced a second gridview dbContext.Persons.Load ( ) ; myDataGridView.DataSource = dbContext.Persons.Local.ToBindingList ( ) ; myDataGridView.Columns [ `` Description '' ] .AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells ; Person p = new Person ( ) ; p.Name = `` Tester Alfred '' ; p.Description = `` Description '' ; //no more properties , only those two ( Id Property is annotated as [ Key ] dbContext.Persons.Add ( p ) ; // this throws a NullReferenceException System.Data.Entity.Core.Objects.ObjectContext.AddSingleObject ( EntitySet entitySet , IEntityWrapper wrappedEntity , String argumentName ) bei System.Data.Entity.Core.Objects.ObjectContext.AddObject ( String entitySetName , Object entity ) bei System.Data.Entity.Internal.Linq.InternalSet ` 1. < > c__DisplayClassd. < Add > b__c ( ) bei System.Data.Entity.Internal.Linq.InternalSet ` 1.ActOnSet ( Action action , EntityState newState , Object entity , String methodName ) bei System.Data.Entity.Internal.Linq.InternalSet ` 1.Add ( Object entity ) bei System.Data.Entity.DbSet ` 1.Add ( TEntity entity )",NullReferenceException when setting AutoSizeMode to AllCells in DataGridView "C_sharp : According to examples provided by ASP.NET Core 2.2 documentation in MSDN , it is possible to inject HttpClient to a typed clients ( service-classes ) by adding the following line to Startup.cs : From controller class it will look like ( from now I will use GitHub as a simplification for a domain model ) : However , I use MediatR library in my project , so my project structure looks a bit different . I have 2 projects - GitHubFun.Api , GitHubFun.Core - ASP.NET Core 2.2 API project and .NET Core 2.2 class library respectively.My controller : And my handler class : When I make HTTP request and call an API method , it successfully injects IMediator , but throws an exception on _mediator.Send ( command ) line.Exception body : System.InvalidOperationException : Error constructing handler for request of type MediatR.IRequestHandler ` 2 [ IDocs.CryptoServer.Core.Commands.ExtractX509Command , IDocs.CryptoServer.Core.Commands.ExtractX509CommandResult ] . Register your handlers with the container . See the samples in GitHub for examples . -- - > System.InvalidOperationException : Unable to resolve service for type 'System.Net.Http.HttpClient ' while attempting to activate 'IDocs.CryptoServer.Core.Handlers.ExtractX509CommandHandler ' ( ExtractX509CommandHandler - is just a real domain model , instead of GetGitHubRepositoryHandler ) .It seems that ASP.NET Core DI can not resolve DI and inject HttpClient to handler.My Startup.cs has the following lines : // Startup.csservices.AddHttpClient < GitHubService > ( ) ; // GitHubController.cspublic class GitHubController : Controller { private readonly GitHubService _service ; public GitHubController ( GitHubService service ) { _service = service ; } } // GitHubController.cspublic class GitHubController : Controller { private readonly IMediator _mediator ; public GitHubController ( IMediator mediator ) { _mediator= mediator ; } public async Task < IActionResult > GetGitHubRepositoryInfo ( GetGitHubRepositoryCommand command ) { _mediator.Send ( command ) ; } } // GetGitHubRepositoryHandler.cspublic class GetGitHubRepositoryHandler : IRequestHandler < GetGitHubRepositoryCommand , GetGitHubRepositoryCommandResult > { private HttpClient _httpClient ; public GetGitHubRepositoryHandler ( HttpClient httpClient ) { _httpClient = httpClient ; } } services.AddHttpClient < ExtractX509CommandHandler > ( ) ; services.AddMediatR ( typeof ( Startup ) .Assembly , typeof ( ExtractX509CommandHandler ) .Assembly ) ;",Can not inject HttpClient in typed client while using with IMediatR library "C_sharp : We often have a need to turn a string with values separated by some character into a list . I want to write a generic extension method that will turn the string into a list of a specified type . Here is what I have so far : But I get an error . Can not convert type 'string ' to type 'T'.Is there a better way to do this or do I need to create multiple extension methods for the different types of lists and do Convert.ToInt32 ( ) , etc ? UPDATEI 'm trying to do things like this : or public static List < T > ToDelimitedList < T > ( this string value , string delimiter ) { if ( value == null ) { return new List < T > ( ) ; } var output = value.Split ( new string [ ] { delimiter } , StringSplitOptions.RemoveEmptyEntries ) ; return output.Select ( x = > ( T ) x ) .ToList ( ) ; } var someStr = `` 123,4,56,78,100 '' ; List < int > intList = someStr.ToDelimitedList < int > ( `` , '' ) ; var someStr = `` true ; false ; true ; true ; false '' ; List < bool > boolList = someStr.ToDelimitedList < bool > ( `` ; '' ) ;",How can I write a generic extension method for converting a delimited string to a list ? "C_sharp : I have an < asp : FileUpload > control with the property AllowMultiple set to true : In my JavaScript function , I simulate a click on the invisible button : In the code-behind , I save the files to a temporary folder , and I display the uploaded images in the < asp : Image > controls : This is working perfectly but I need some help . When I loop through FileUpload.PostedFiles , the order of the selected images is alphabetical I think . I would like to keep the order of the user 's selection . Is this possible ? < asp : fileupload id= '' FileUpload '' runat= '' server '' allowmultiple= '' true '' cssclass= '' fileUpload btn btn-sm btn-default '' onchange= '' preloadImages ( ) '' / > < div class= '' field col-md-2 col-md-offset-1 immScarpePreview MainPreviewBox '' > < asp : image id= '' Image1 '' runat= '' server '' visible= '' false '' cssclass= '' img-responsive '' / > < asp : button id= '' ImmButton '' runat= '' server '' text= '' Upload '' onclick= '' ImmButton_Click '' cssclass= '' hidden '' / > < /div > < script > function preloadImages ( ) { $ ( ' # < % =ImmButton.ClientID % > ' ) .trigger ( 'click ' ) ; } < /script > protected void ImmButton_Click ( object sender , EventArgs e ) { if ( FileUpload.HasFile ) { try { int cont = 0 ; byte [ ] fileData = null ; foreach ( HttpPostedFile file in FileUpload.PostedFiles ) { if ( cont == 0 ) { using ( var binaryReader = new BinaryReader ( file.InputStream ) ) fileData = binaryReader.ReadBytes ( file.ContentLength ) ; File.WriteAllBytes ( Server.MapPath ( `` immScarpe/tmp/ '' + file.FileName ) , fileData ) ; setImage1 ( `` immScarpe/tmp/ '' + file.FileName ) ; } else if ( cont == 1 ) { using ( var binaryReader = new BinaryReader ( file.InputStream ) ) fileData = binaryReader.ReadBytes ( file.ContentLength ) ; File.WriteAllBytes ( Server.MapPath ( `` immScarpe/tmp/ '' + file.FileName ) , fileData ) ; setImage2 ( `` immScarpe/tmp/ '' + file.FileName ) ; } else if ( cont == 2 ) //and so on ... //so on ... cont++ ; } } catch ( Exception ex ) { //error writing file Console.Write ( ex.Message ) ; } } } private void setImage1 ( string image ) //all equals for all the 5 images { Image1.ImageUrl = image ; Image1.Visible = true ; }",Maintain order of selected files in FileUpload with AllowMultiple=true "C_sharp : I 'm writing some C # heavy in mathematics . Many lines in sequence using plenty of abs ( ) , min ( ) , max ( ) , sqrt ( ) , etc . Using C # is the plain normal way , I must preface each function with `` Math . '' For exampleI 'd rather write code like in C : This is easier to read and looks more natural to scientists and engineers . The normal C # way hides the good bits in a fog of `` Math . '' Is there a way in C # to do this ? After some googling I found an example which lead me to trybut the `` using '' statement produced an error , `` System.Math.Min ( decimal , decimal ) is a method but is used like a type '' but otherwise this looked like a good solution . ( What is 'decimal ' , anyway ? ) double x = Math.Min ( 1+Math.Sqrt ( A+Math.Max ( B1 , B2 ) ) , Math.Min ( Math.Cos ( Z1 ) , Math.Cos ( Z2 ) ) ) ; double x = min ( 1+sqrt ( A+max ( B1 , B2 ) ) , min ( cos ( Z1 ) , cos ( Z2 ) ) ) ; using min = Math.Min ; ... double x = min ( a , b ) ;",How to avoid `` Math . '' in front of every math function in C # ? "C_sharp : Sometimes , I come across a property that , when I try to rename it using the built-in Visual Studio refactoring option , I get a dialog that says : The file `` could not be refactored . Object reference not set to an instance of an object . Do you wish to continue with the refactoring ? [ ] Ignore further refactoring errors [ Yes ] [ No ] The dialog actually shows empty apostrophes when referring to the file . Google does n't provide any help . I 'm beginning to think this is an obscure Visual Studio bug and that I should report it to Microsoft Connect . Thought I 'd see if any of you have come across it before first.FYI , my solution/projects build fine . The property is not referenced in any XAML . I tried deleting my `` .suo '' file , my `` bin '' directory , and my `` obj '' folder , then rebuilding , but still no dice . I have the latest Microsoft updates . The problem occurs with both Visual C # 2008 Express and Visual Studio 2008 Professional . Though it should not matter , the property looks like this : I have no problem renaming other properties in the same class in the same file , such as this one : Any ideas ? Note that I realize I could just find all reference to the property and manually rename it , but I 'd like to get to the bottom of this error dialog . private MigrationRequestViewModel Request { get ; set ; } private MigrationRequestViewModel RequestSnapshot { get ; set ; }",C # Obscure error : file `` could not be refactored "C_sharp : I got following query Currently my tests show that end result is actually goodOrdered , like I want it . Can I expect that to always be true or I should provide an order by statement that will force to keep goodOrdered order ( it will make query more complex , because goodOrdered can look like 1 , 9 , 2 , 7 , 6 ) ? IEnumerable < string > values = from first in goodOrderedjoin second in badOrdered on first.ToLower ( ) equalssecond.ToLower ( ) select second ;",Is Linq to objects join default order specified when no order by is used ? "C_sharp : So I have the following code : I 've checked innumerable articles here and other sites with no luck.Basically , the code checks for a running instance of the app and if there is one , it switches to the main window of the running one . If not , it launches the app.In Debug mode it all works as expected , the problem starts when I switch my configuration to Release : the app always starts ( with Mutex seemingly doing nothing ) .I 've added conditionally compiled dumps that show in which mode the app is starting and the output changes based on the configuration , but sadly , so does the behaviour of the app.This may be a race condition but I am not sure.More code will be posted if needed.Thanks . ... private static void Main ( string [ ] args ) { string file=DateTime.Now.ToFileTime ( ) .ToString ( ) ; File.AppendAllText ( file , `` Mutex\r\n '' ) ; bool CreatedNew ; Mutex mutex=new Mutex ( true , AppDomain.CurrentDomain.FriendlyName , out CreatedNew ) ; if ( CreatedNew ) { # if DEBUG File.AppendAllText ( file , `` Launching in DEBUG mode\r\n '' ) ; # else File.AppendAllText ( file , `` Launching in RELEASE mode\r\n '' ) ; # endif //Program.Launch ( ) ; Program.ProcessArgsAndLaunch ( args ) ; } else { File.AppendAllText ( file , `` Handling dupe\r\n '' ) ; Program.HandleDuplicate ( ) ; } } ...",C # mutex in release mode behaves different than in debug mode "C_sharp : I have added a `` Unit Test Library '' project to my solution containing a simple test class : But I am unable to make the test show up in the text explorer window . I have tried cleaning/rebuilding the solution , removing/re-adding references to MSTest and editing the .csproj file to make sure the project is marked as a test-project.The whole solution is under source control and my colleague ( working with the same code ) is having no problem running the test.Any ideas ? namespace Metro_test { [ TestClass ] public class UnitTest1 { [ TestMethod ] public void TestMethod1 ( ) { Assert.Equals ( 0 , 1 ) ; } } }",Visual Studio 2012 unable to find my tests "C_sharp : Let 's say I have an method that calls another async method immediately or similar : Is there any specific reason that Foo2 needs/should have async/await , as opposed to simply calling : In a consumer , this would still be awaited , likeso , regardless of : All those statements will compile . Will the compiler generate different IL for the two different methods ? //Main methodpublic async Task < int > Foo1 ( int x ) { var result = await DoingSomethingAsync ( x ) ; return DoSomethingElse ( result ) ; } //other methodpublic async Task < int > Foo2 ( Double double ) { return await Foo1 ( Convert.ToInt32 ( double ) ) ; } //other methodpublic Task < int > Foo3 ( Double double ) { return Foo1 ( Convert.ToInt32 ( double ) ) ; } int x = await Foo1 ( 1 ) ; int x = await Foo2 ( 1D ) ; int x = await Foo3 ( 1D ) ;",Does a pass-through async method really need the await/async pattern ? "C_sharp : Expression.Convert generally throws in InvalidOperationException when `` No conversion operator is defined between expression.Type and type . `` The return type parameter of Func < > is covariant for reference types.It is n't covariant for value types . Variance applies only to reference types ; if you specify a value type for a variant type parameter , that type parameter is invariant for the resulting constructed type.However , Expression.Convert believes it is possible.No InvalidOperationException is thrown when calling Expression.Convert . The expression tree compiles correctly , but when I call the created delegate , I get an expected InvalidCastException.Is this a bug ? ( I reported it as a bug on Microsoft Connect . ) How to properly check whether a type can be converted to another type ? Some answers seem to refer to using Convert . I would very much prefer a method which does n't have to use exception handling as logic.It seems the entire variance logic is n't properly supported . It correctly complains about not being able to convert from Func < SomeType > to Func < SomeOtherType > , but it does n't complain about converting from Func < object > to Func < string > .Interestingly , once SomeType and SomeOtherType are in the same class hierarchy ( SomeOtherType extends from SomeType ) , it never throws the exception . If they are n't , it does . // This works.Func < SomeType > a = ( ) = > new SomeType ( ) ; Func < object > b = a ; // This does n't work ! Func < int > five = ( ) = > 5 ; Func < object > fiveCovariant = five ; Func < int > answer = ( ) = > 42 ; Expression answerExpression = Expression.Constant ( answer ) ; // No InvalidOperationException is thrown at this line.Expression converted = Expression.Convert ( answerExpression , typeof ( Func < object > ) ) ;",Expression.Convert does n't throw InvalidOperationException for invariant value type parameters ? "C_sharp : I am using NHibernate , and have problems with this query ... I have a class Item which I want to fetch using its Id . All fine . However , I also want a bool property on the Item class to be set to true if some other condition is set . Specifically this property is named IsMarked , telling if the Item is marked/stared/flagged for the user that requested it , and this information is set on a table giving the relation between Item and User . Currently I 'm fetching the Item , and then finding the reference - updating the property to true if the reference could be found . Can I do this in one query instead ? var item = Session.Get < Item > ( itemId ) ; var flaggedResult = Session.CreateCriteria < ItemWithUserFlag > ( ) .Add ( Restrictions.Eq ( `` User.Id '' , userId ) ) .Add ( Restrictions.Eq ( `` Item '' , item ) ) .List < ItemWithUserFlag > ( ) ; if ( flaggedResult.Count > 0 ) item.IsMarked = true ; return item ;",Setting value based on different table in NHibernate query "C_sharp : I have been delving into C # recently , and I wonder if anyone would mind just checking my write up on it , to make sure it is accurate ? Example : Calculating factorials with the use of an Extension method.For example if you wanted to extend the int type you could create a class e.g.NumberFactorial and create a method e.g . Static Void Main , that calls e.g . int x = 3Then prints out the line ( once its returned from the extension method ) Create a public static method that contains the keyword `` this '' e.g . this int xperform the logic and the parameter is then fed back to the inital method for output.The code is below : using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { int x = 3 ; Console.WriteLine ( x.factorial ( ) ) ; Console.ReadLine ( ) ; } } public static class MyMathExtension { public static int factorial ( this int x ) { if ( x < = 1 ) return 1 ; if ( x == 2 ) return 2 ; else return x * factorial ( x - 1 ) ; } } }",Extension Methods in C # - Is this correct ? "C_sharp : I 'm trying to implement Multi-Layer Perceptrons ( MLP ) neural networks using EmguCV 3.1 ( a dot NET wrapper for OpenCV library ) in C # ( Windows Form ) . In order to practice with this library I decide to implement OR operation using MLP . I create MLP using `` Initialize '' method and learn it using `` Train '' method as below : Where MIN_ACTIVATION_FUNCTION , and MAX_ACTIVATION_FUNCTION are equal to -1.7159 and 1.7159 , respectively ( according to OpenCV Documentation ) . After 1000000 iterations of ( as you see in my code in stop condition ) , I test my network for prediction using Predict method as below : Here is a sample of what NETWORK predicts : -0.00734469-0.031849180.02080269-0.006674092I expect be some thing like this : -1.7+1.7+1.7+1.7What is wrong among my codes ? Note that I also use 0 , 1 for MIN_ACTIVATION_FUNCTION and MAX_ACTIVATION_FUNCTION values but I still do not any good results.Update 1 : I edit my codes as first answer refers me ( even I test my code with idea referenced in comments ) . Now I get NaN when call predict method . private void Initialize ( ) { NETWORK.SetActivationFunction ( ANN_MLP.AnnMlpActivationFunction.SigmoidSym ) ; NETWORK.SetTrainMethod ( ANN_MLP.AnnMlpTrainMethod.Backprop ) ; Matrix < double > layers = new Matrix < double > ( new Size ( 4 , 1 ) ) ; layers [ 0 , 0 ] = 2 ; layers [ 0 , 1 ] = 2 ; layers [ 0 , 2 ] = 2 ; layers [ 0 , 3 ] = 1 ; NETWORK.SetLayerSizes ( layers ) ; } private void Train ( ) { // providing data for input Matrix < float > input = new Matrix < float > ( 4 , 2 ) ; input [ 0 , 0 ] = MIN_ACTIVATION_FUNCTION ; input [ 0 , 1 ] = MIN_ACTIVATION_FUNCTION ; input [ 1 , 0 ] = MIN_ACTIVATION_FUNCTION ; input [ 1 , 1 ] = MAX_ACTIVATION_FUNCTION ; input [ 2 , 0 ] = MAX_ACTIVATION_FUNCTION ; input [ 2 , 1 ] = MIN_ACTIVATION_FUNCTION ; input [ 3 , 0 ] = MAX_ACTIVATION_FUNCTION ; input [ 3 , 1 ] = MAX_ACTIVATION_FUNCTION ; //providing data for output Matrix < float > output = new Matrix < float > ( 4 , 1 ) ; output [ 0 , 0 ] = MIN_ACTIVATION_FUNCTION ; output [ 1 , 0 ] = MAX_ACTIVATION_FUNCTION ; output [ 2 , 0 ] = MAX_ACTIVATION_FUNCTION ; output [ 3 , 0 ] = MAX_ACTIVATION_FUNCTION ; // mixing input and output for training TrainData mixedData = new TrainData ( input , Emgu.CV.ML.MlEnum.DataLayoutType.RowSample , output ) ; // stop condition = 1 million iterations NETWORK.TermCriteria = new MCvTermCriteria ( 1000000 ) ; // training NETWORK.Train ( mixedData ) ; } private void Predict ( ) { Matrix < float > input = new Matrix < float > ( 1 , 2 ) ; input [ 0 , 0 ] = MIN_ACTIVATION_FUNCTION ; input [ 0 , 1 ] = MIN_ACTIVATION_FUNCTION ; Matrix < float > output = new Matrix < float > ( 1 , 1 ) ; NETWORK.Predict ( input , output ) ; MessageBox.Show ( output [ 0 , 0 ] .ToString ( ) ) ; ////////////////////////////////////////////// input [ 0 , 0 ] = MIN_ACTIVATION_FUNCTION ; input [ 0 , 1 ] = MAX_ACTIVATION_FUNCTION ; NETWORK.Predict ( input , output ) ; MessageBox.Show ( output [ 0 , 0 ] .ToString ( ) ) ; ////////////////////////////////////////////// input [ 0 , 0 ] = MAX_ACTIVATION_FUNCTION ; input [ 0 , 1 ] = MIN_ACTIVATION_FUNCTION ; NETWORK.Predict ( input , output ) ; MessageBox.Show ( output [ 0 , 0 ] .ToString ( ) ) ; //////////////////////////////////////////////// input [ 0 , 0 ] = MAX_ACTIVATION_FUNCTION ; input [ 0 , 1 ] = MAX_ACTIVATION_FUNCTION ; NETWORK.Predict ( input , output ) ; MessageBox.Show ( output [ 0 , 0 ] .ToString ( ) ) ; }",Multi-Layer Perceptrons in EmguCV "C_sharp : I am trying to test how much performant ( Or not ) the `` in '' keyword added to C # is . The in keyword should be able to pass a readonly reference to a value type into a method , instead of first copying the value then passing it in . By bypassing this copy , in should be faster , but in my tests it does n't seem any faster at all . I am using BenchMarkDotNet to benchmark my code . The code looks like : As you can see , I 'm including a loop to use the `` ref '' keyword which also passes by reference , but is not readonly . This does seem to be faster . The results of this test are : So using `` in '' does n't seem to be faster at all . I feel like it 's possible that something is being optimized in a way I do n't anticipate and that 's accounting for the performance difference . I have tried increasing the size of the struct up to 16 decimal fields , but again , it did n't make a difference between in and by value . How can I structure my benchmark test to truly see the difference between in , ref , and passing by value ? public struct Input { public decimal Number1 { get ; set ; } public decimal Number2 { get ; set ; } } public class InBenchmarking { const int loops = 50000000 ; Input inputInstance ; public InBenchmarking ( ) { inputInstance = new Input { } ; } [ Benchmark ] public decimal DoSomethingRefLoop ( ) { decimal result = 0M ; for ( int i = 0 ; i < loops ; i++ ) { result = DoSomethingRef ( ref inputInstance ) ; } return result ; } [ Benchmark ] public decimal DoSomethingInLoop ( ) { decimal result = 0M ; for ( int i = 0 ; i < loops ; i++ ) { result = DoSomethingIn ( inputInstance ) ; } return result ; } [ Benchmark ( Baseline = true ) ] public decimal DoSomethingLoop ( ) { decimal result = 0M ; for ( int i = 0 ; i < loops ; i++ ) { result = DoSomething ( inputInstance ) ; } return result ; } public decimal DoSomething ( Input input ) { return input.Number1 ; } public decimal DoSomethingIn ( in Input input ) { return input.Number1 ; } public decimal DoSomethingRef ( ref Input input ) { return input.Number1 ; } } Method | Mean | Error | StdDev | Scaled | ScaledSD | -- -- -- -- -- -- -- -- -- - | -- -- -- -- - : | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- - : | -- -- -- -- - : | DoSomethingRefLoop | 20.15 ms | 0.3967 ms | 0.6058 ms | 0.41 | 0.03 | DoSomethingInLoop | 48.88 ms | 0.9756 ms | 2.5529 ms | 0.98 | 0.08 | DoSomethingLoop | 49.84 ms | 1.0872 ms | 3.1367 ms | 1.00 | 0.00 |",C # 7.2 In Keyword Performance "C_sharp : I wonder if someone could explain why in this codethe 'return value ; ' statement throws an null reference exception when called with : It works as expected when called with : Note : The following compiles and runs just fineThe stacktrace : public class SomeClass { public T GenericMethod < T > ( dynamic value ) { return ( T ) value ; } } new SomeClass ( ) .GenericMethod < object > ( new object ( ) ) ; // throws System.NullReferenceException new SomeClass ( ) .GenericMethod < string > ( `` SomeString '' ) ; // returns SomeStringnew SomeClass ( ) .GenericMethod < object > ( `` SomeString '' ) ; // returns SomeString public class SomeOtherClass { public T GenericMethod < T > ( object value ) { return ( T ) value ; } } System.NullReferenceException : Object reference not set to an instance of an object . at Microsoft.CSharp.RuntimeBinder.ExpressionTreeCallRewriter.GenerateLambda ( EXPRCALL pExpr ) at Microsoft.CSharp.RuntimeBinder.Semantics.ExprVisitorBase.Visit ( EXPR pExpr ) at Microsoft.CSharp.RuntimeBinder.ExpressionTreeCallRewriter.Rewrite ( TypeManager typeManager , EXPR pExpr , IEnumerable ` 1 listOfParameters ) at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.BindCore ( DynamicMetaObjectBinder payload , IEnumerable ` 1 parameters , DynamicMetaObject [ ] args , DynamicMetaObject & deferredBinding ) at Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind ( DynamicMetaObjectBinder payload , IEnumerable ` 1 parameters , DynamicMetaObject [ ] args , DynamicMetaObject & deferredBinding ) at Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind ( DynamicMetaObjectBinder action , RuntimeBinder binder , IEnumerable ` 1 args , IEnumerable ` 1 arginfos , DynamicMetaObject onBindingError ) at Microsoft.CSharp.RuntimeBinder.CSharpConvertBinder.FallbackConvert ( DynamicMetaObject target , DynamicMetaObject errorSuggestion ) at System.Dynamic.DynamicMetaObject.BindConvert ( ConvertBinder binder ) at System.Dynamic.DynamicMetaObjectBinder.Bind ( Object [ ] args , ReadOnlyCollection ` 1 parameters , LabelTarget returnLabel ) at System.Runtime.CompilerServices.CallSiteBinder.BindCore [ T ] ( CallSite ` 1 site , Object [ ] args ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1 [ T0 , TRet ] ( CallSite site , T0 arg0 )",Why does a dynamic parameter in a generic method throw a null reference exception when using an Object ? "C_sharp : I 'm working with strings , which could contain surrogate unicode characters ( non-BMP , 4 bytes per character ) . When I use `` \Uxxxxxxxxv '' format to specify surrogate character in F # - for some characters it gives different result than in the case of C # . For example : C # : Gives : Length : 2 , is surrogate : TrueF # : Gives : Length : 2 , is surrogate : falseNote : Some surrogate characters works in F # ( `` \U0010011 '' , `` \U00100011 '' ) , but some of them does n't work.Q : Is this is bug in F # ? How can I handle allowed surrogate unicode characters in strings with F # ( Does F # has different format , or only the way is to use Char.ConvertFromUtf32 0x1D11E ) Update : s.ToCharArray ( ) gives for F # [ | 0xD800 ; 0xDF41 | ] ; for C # { 0xD834 , 0xDD1E } string s = `` \U0001D11E '' ; bool c = Char.IsSurrogate ( s , 0 ) ; Console.WriteLine ( String.Format ( `` Length : { 0 } , is surrogate : { 1 } '' , s.Length , c ) ) ; let s = `` \U0001D11E '' let c = Char.IsSurrogate ( s , 0 ) printf `` Length : % d , is surrogate : % b '' s.Length c",Issue with surrogate unicode characters in F # "C_sharp : In my .NET Core project , I have below settings in Configure method : I have not registerd any IOptions and I am injecting it in a controllerThe IOptions is getting resolved with the default instance , and I get to know error only when I am trying to use it ( and when I expect the value to be not null ) .Can I somehow get it to fail , stating the instance type is not registered or something similar ? I just want to catch errors as early as possible . public void ConfigureServices ( IServiceCollection services ) { services .AddMvc ( ) .SetCompatibilityVersion ( CompatibilityVersion.Version_2_2 ) ; //services.AddOptions < UploadConfig > ( Configuration.GetSection ( `` UploadConfig '' ) ) ; } [ Route ( `` api/ [ controller ] '' ) ] [ ApiController ] public class HelloWorldController : ControllerBase { public HelloWorldController ( IOptions < UploadConfig > config ) { var config1 = config.Value.Config1 ; } }",why IOptions is getting resolved even if not registered "C_sharp : Why a generic method which constrains T to class would have boxing instructions in the generates MSIL code ? I was quite surprised by this since surely since T is being constrained to a reference type the generated code should not need to perform any boxing.Here is the c # code : Here is the generated IL : Notice the box ! ! T instructions.Why this is being generated ? How to avoid this ? protected void SetRefProperty < T > ( ref T propertyBackingField , T newValue ) where T : class { bool isDifferent = false ; // for reference types , we use a simple reference equality check to determine // whether the values are 'equal ' . We do not use an equality comparer as these are often // unreliable indicators of equality , AND because value equivalence does NOT indicate // that we should share a reference type since it may be a mutable . if ( propertyBackingField ! = newValue ) { isDifferent = true ; } } .method family hidebysig instance void SetRefProperty < class T > ( ! ! T & propertyBackingField , ! ! T newValue ) cil managed { .maxstack 2 .locals init ( [ 0 ] bool isDifferent , [ 1 ] bool CS $ 4 $ 0000 ) L_0000 : nop L_0001 : ldc.i4.0 L_0002 : stloc.0 L_0003 : ldarg.1 L_0004 : ldobj ! ! T L_0009 : box ! ! T L_000e : ldarg.2 L_000f : box ! ! T L_0014 : ceq L_0016 : stloc.1 L_0017 : ldloc.1 L_0018 : brtrue.s L_001e L_001a : nop L_001b : ldc.i4.1 L_001c : stloc.0 L_001d : nop L_001e : ret }",Why does generic method with constraint of T : class result in boxing ? "C_sharp : Given an input stringI need to find and replace each operator with a string that contains the operatorpractical application : From a backend ( c # ) , i have the following stringwhich i need to translate to : and returned to the screen which can be run in an eval ( ) function.So far I haveCaution : i can not do a blanket input.Replace ( ) in the foreach loop , as it may incorrectly replace ( 12/123 ) - it should only match the first 12 to replaceCaution2 : I can use string.Remove and string.Insert , but that mutates the string after the first match , so it throws off the calculation of the next matchAny pointers appreciated 12/312*3/12 ( 12*54 ) / ( 3/4 ) some12text/some3textsome12text*some2text/some12text ( some12text*some54text ) / ( some3text/some4text ) 34*157 document.getElementById ( `` 34 '' ) .value*document.getElementById ( `` 157 '' ) .value var pattern = @ '' \d+ '' ; var input = `` 12/3 ; Regex r = new Regex ( pattern ) ; var matches = r.Matches ( input ) ; foreach ( Match match in matches ) { // im at a loss what to match and replace here }",Regex match and replace operators in math operation "C_sharp : I would like to use Linq expression trees to call the indexer of a Span < T > . The code looks like : Yet , this code fails because myValue is of type Single & ( aka ref struct ) instead of type Single ( aka struct ) .How to evaluate a Span < T > from an expression tree ? var spanGetter = typeof ( Span < > ) .MakeGenericType ( typeof ( float ) ) .GetMethod ( `` get_Item '' ) ; var myFloatSpan = Expression.Parameter ( typeof ( Span < float > ) , `` s '' ) ; var myValue = Expression.Call ( myFloatSpan , spanGetter , Expression.Constant ( 42 ) ) ; var myAdd = Expression.Add ( myValue , Expression.Constant ( 13f ) ) ;",How to get a value out of a Span < T > with Linq expression trees ? "C_sharp : I 'm trying to configure DI for an Excel VSTO project . The generated code-behind for a given worksheet offers me a event called Startup , which is reponsible to set event handlers for events like Startup , Change , BeforeDoubleClick and so on.I think is generally a good practice do avoid code in code-behind files.What I do is create external classes that are responsible to manipulate the worksheet and call external code like web services , databases and domain logic.I can create successfully a Factory to be consumed by the codebehind file and instantiate the worksheet logic class.For example : The code above is inside the code-behind file Visual Studio generates and it 's minimal . The responsibility to show the popup is delegated to a distinct object . The factory object is responsible to talk with Ninject and get the object for me . This proxy is generated automatically using Ninject.Extensions.Factory project as I pass an interface like this : In the application startup , I have defined the the bindings and the binding for the factory itself : The problem is : How can I inject this factory in the generated code of VSTO worksheet ? I do n't like the idea of calling _kernel.Get < IExpenseWorksheetFactory > inside the Startup method of the worksheet . Is it possible to look for all available instances of Sheet1 and force the injection of the factory ? // ... inside Sheet1.csprivate IExpenseWorksheetFactory _factory ; void ExpensesBeforeRightClick ( Excel.Range target , ref bool cancel ) { Application.EnableEvents = false ; var popup = _factory.CreateContextMenu ( ) ; popup.ShowContextMenu ( target , ref cancel ) ; Application.EnableEvents = true ; } // ... rest of Sheet1.cs /// < summary > /// Abstract Factory for creating Worksheet logic objects . Meant to be used with Ninject Factory extension./// < /summary > public interface IExpenseWorksheetFactory { ExpenseWorksheet CreateWorksheet ( ) ; ExpenseWorksheet.ContextMenus CreateContextMenu ( ) ; ExpenseWorksheet.Events CreateEventHandlers ( ) ; } //instantiate the kernel in app 's Composition Root_kernel = new StandardKernel ( ) ; //worksheet related stuff - seems to be ok to be singleton_kernel.Bind < ExpenseWorksheet > ( ) .ToSelf ( ) .InSingletonScope ( ) ; _kernel.Bind < ExpenseWorksheet.Events > ( ) .ToSelf ( ) .InSingletonScope ( ) ; _kernel.Bind < ExpenseWorksheet.ContextMenus > ( ) .ToSelf ( ) .InSingletonScope ( ) ; // '' automagic '' factories_kernel.Bind < IExpenseWorksheetFactory > ( ) .ToFactory ( ) ;",Dependency Injection inside Excel VSTO and Ninject.Extensions.Factory "C_sharp : I have a C # method which uses object as a generic container to return a data array which could be declared using different data types . Below a simplified example of such a method : I need to convert all the returned array elements to double but so far I could not find a way . Ideally I would like to perform something like : Which miserably fails because ConvertAll does not accept types defined at runtime . I have also tried intermediate conversions to a dynamic variable , to no avail . Is there any way to perform such type conversion in a simple manner ? void GetChannelData ( string name , out object data ) { // Depending on `` name '' , the underlying type of // `` data '' can be different : int [ ] , byte [ ] , float [ ] ... // Below I simply return int [ ] for the sake of example int [ ] intArray = { 0 , 1 , 2 , 3 , 4 , 5 } ; data = intArray ; } object objArray ; GetChannelData ( `` test '' , out objArray ) ; double [ ] doubleArray = Array.ConvertAll < objArray.GetType ( ) .GetElementType ( ) , double > ( objArray , item = > ( double ) item ) ;",C # converting an array returned as a generic object to a different underlying type "C_sharp : One method is a standard async method , like this one : I have tested two implementations , one that use await and the other uses .Wait ( ) The two implementations are not equal at all because the same tests are failing with the await version but not the Wait ( ) one.The goal of this method is to `` execute a Task returned by the input function , and retry by executing the same function until it works '' ( with limitations to stop automatically if a certain number of tries is reached ) .This works : And this ( with async t = > and the usage of await instead of t = > and the usage of .Wait ( ) does n't work at all because the result of the recursive call is not awaited before the final return ; is executed : I 'm trying to understand why this simple change does change everything , when it 's supposed to do the exact same thing : waiting the ContinueWith completion.If I extract the task ran by the ContinueWith method , I do see the state of the ContinueWith function passing to `` ranToCompletion '' before the return of the inner await completes.Why ? Is n't it supposed to be awaited ? Concrete testable behaviourWhy does var hello = o ; is reached before o=10 ? Is n't the # 1 await supposed to hang on before the execution can continue ? private static async Task AutoRetryHandlerAsync_Worker ( Func < Task < bool > > taskToRun , ... ) private static async Task AutoRetryHandlerAsync_Worker ( Func < Task < bool > > taskToRun , ... ) { try { await taskToRun ( ) ; } catch ( Exception ) { // Execute later , and wait the result to complete await Task.Delay ( currentDelayMs ) .ContinueWith ( t = > { // Wait for the recursive call to complete AutoRetryHandlerAsync_Worker ( taskToRun ) .Wait ( ) ; } ) ; // Stop return ; } } private static async Task AutoRetryHandlerAsync_Worker ( Func < Task < bool > > taskToRun , ... ) { try { await taskToRun ( ) ; } catch ( Exception ) { // Execute later , and wait the result to complete await Task.Delay ( currentDelayMs ) .ContinueWith ( async t = > { // Wait for the recursive call to complete await AutoRetryHandlerAsync_Worker ( taskToRun ) ; } ) ; // Stop return ; } } public static void Main ( string [ ] args ) { long o = 0 ; Task.Run ( async ( ) = > { // # 1 await await Task.Delay ( 1000 ) .ContinueWith ( async t = > { // # 2 await await Task.Delay ( 1000 ) .ContinueWith ( t2 = > { o = 10 ; } ) ; } ) ; var hello = o ; } ) ; Task.Delay ( 10000 ) .Wait ( ) ; }",Understanding async/await vs Wait in C # with `` ContinueWith '' behavior "C_sharp : I see the following code sometimes , and have no idea what the expression is actually testing . public static void Something ( string [ ] value ) { if ( value is { } ) { DoSomethingElse ( ) ; } }",What does `` is { } '' mean ? "C_sharp : In a C # /WPF application I added a TypeConverter attribute to some of my enums in order to display a localized text instead of the text of the enum : I have implemented LocalizedEnumTypeConverter to perform this task.The problem arises when I try to use the same approach with an enum that is defined in another assembly , that has no access to LocalizedEnumTypeConverter , and it is shared with other applications ( that is , I can not add a reference to the assembly where LocalizedEnumTypeConverter is defined ) .Is there a way to add the TypeConverter attribute in runtime ? This way I can leave the enum in the other assembly without the TypeConverter attribute , and then add it in runtime in my application . [ TypeConverter ( typeof ( LocalizedEnumTypeConverter ) ) ] public enum MyEnum { EnumVal1 = 0 , EnumVal2 = 1 , EnumVal3 = 2 , }",Add TypeConverter attribute to enum in runtime C_sharp : Possible Duplicate : What is the difference between a field and a property in C # Can someone explain the diffrence if any between these two properties ? public string City { get ; set ; } public string City ;,Public accessors vs public properties of a class "C_sharp : Strings are reference types , but they are immutable . This allows for them to be interned by the compiler ; everywhere the same string literal appears , the same object may be referenced.Delegates are also immutable reference types . ( Adding a method to a multicast delegate using the += operator constitutes assignment ; that 's not mutability . ) And , like , strings , there is a `` literal '' way to represent a delegate in code , using a lambda expression , e.g . : The right-hand side of that statement is an expression whose type is Func < int > ; but nowhere am I explicitly invoking the Func < int > constructor ( nor is an implicit conversion happening ) . So I view this as essentially a literal . Am I mistaken about my definition of `` literal '' here ? Regardless , here 's my question . If I have two variables for , say , the Func < int > type , and I assign identical lambda expressions to both : ... what 's preventing the compiler from treating these as the same Func < int > object ? I ask because section 6.5.1 of the C # 4.0 language specification clearly states : Conversions of semantically identical anonymous functions with the same ( possibly empty ) set of captured outer variable instances to the same delegate types are permitted ( but not required ) to return the same delegate instance . The term semantically identical is used here to mean that execution of the anonymous functions will , in all cases , produce the same effects given the same arguments.This surprised me when I read it ; if this behavior is explicitly allowed , I would have expected for it to be implemented . But it appears not to be . This has in fact gotten a lot of developers into trouble , esp . when lambda expressions have been used to attach event handlers successfully without being able to remove them . For example : Is there any reason why this behavior—one delegate instance for semantically identical anonymous methods—is not implemented ? Func < int > func = ( ) = > 5 ; Func < int > x = ( ) = > 5 ; Func < int > y = ( ) = > 5 ; class EventSender { public event EventHandler Event ; public void Send ( ) { EventHandler handler = this.Event ; if ( handler ! = null ) { handler ( this , EventArgs.Empty ) ; } } } class Program { static string _message = `` Hello , world ! `` ; static void Main ( ) { var sender = new EventSender ( ) ; sender.Event += ( obj , args ) = > Console.WriteLine ( _message ) ; sender.Send ( ) ; // Unless I 'm mistaken , this lambda expression is semantically identical // to the one above . However , the handler is not removed , indicating // that a different delegate instance is constructed . sender.Event -= ( obj , args ) = > Console.WriteLine ( _message ) ; // This prints `` Hello , world ! '' again . sender.Send ( ) ; } }",Why are lambda expressions not `` interned '' ? "C_sharp : I have a WPF application that has a main window . In that I have a frame , the frame content is a page.Now in page is 4 viewport3D that contain Viewport2DVisual3D and in that I have image element.Problem : on some PCs my application runs well but on some PCs my application does n't render viewport3d or it does n't render the frame . Dunno but it does n't show anything in main window.The problem occurs on an Acer laptop Model.Rendered : Not Rendered : EDIT : This issue occurred again when I placed the frame in a grid . ( I show this page in a frame , that frame is the main content of my window : when I place the frame in a grid it did n't show objects ) Seems This Occure on laptop with shared graphicsEDIT 2 : < Page x : Class= '' MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Loaded= '' Page_Loaded_1 '' x : Name= '' myMainPage '' FlowDirection= '' RightToLeft '' > < Page.Resources > < Style TargetType= '' ContentControl '' x : Key= '' MenuItemsStyle '' > < Setter Property= '' Background '' Value= '' Transparent '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate > < Viewport3D VerticalAlignment= '' Stretch '' HorizontalAlignment= '' Stretch '' ClipToBounds= '' False '' > < Viewport3D.Camera > < PerspectiveCamera x : Name= '' myCam '' FieldOfView= '' 90 '' Position= '' { Binding ElementName=myMainWindow , Path=CameraHeight } '' NearPlaneDistance= '' 1 '' FarPlaneDistance= '' 10 '' / > < /Viewport3D.Camera > < ModelVisual3D > < ModelVisual3D.Content > < Model3DGroup > < DirectionalLight Color= '' # FFFFFFFF '' Direction= '' 0,0 , -1 '' / > < /Model3DGroup > < /ModelVisual3D.Content > < /ModelVisual3D > < Viewport2DVisual3D x : Name= '' V2d3d '' > < Viewport2DVisual3D.Transform > < Transform3DGroup > < RotateTransform3D > < RotateTransform3D.Rotation > < AxisAngleRotation3D Axis= '' 0,1,0 '' Angle= '' 0 '' x : Name= '' aar3D '' / > < /RotateTransform3D.Rotation > < /RotateTransform3D > < /Transform3DGroup > < /Viewport2DVisual3D.Transform > < Viewport2DVisual3D.Material > < DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial= '' True '' Brush= '' White '' / > < /Viewport2DVisual3D.Material > < Viewport2DVisual3D.Geometry > < MeshGeometry3D Positions= '' { Binding ElementName=myMainWindow , Path=MeshPosions } '' TextureCoordinates= '' 0,0 0,1 1,1 1,0 '' TriangleIndices= '' 0 1 2 0 2 3 '' / > < /Viewport2DVisual3D.Geometry > < Border Name= '' mainBorder '' VerticalAlignment= '' Stretch '' HorizontalAlignment= '' Stretch '' > < Border.Style > < Style TargetType= '' Border '' > < Setter Property= '' BorderThickness '' Value= '' 1.2 '' / > < Setter Property= '' Background '' > < Setter.Value > < SolidColorBrush Color= '' Transparent '' / > < /Setter.Value > < /Setter > < Setter Property= '' BorderBrush '' > < Setter.Value > < SolidColorBrush Color= '' Transparent '' / > < /Setter.Value > < /Setter > < /Style > < /Border.Style > < ContentPresenter VerticalAlignment= '' Stretch '' HorizontalAlignment= '' Stretch '' Content= '' { TemplateBinding ContentControl.Content } '' > < ContentPresenter.Triggers > < EventTrigger RoutedEvent= '' ContentPresenter.MouseLeftButtonDown '' > // Axis Animation < /EventTrigger > < /ContentPresenter.Triggers > < /ContentPresenter > < /Border > < /Viewport2DVisual3D > < /Viewport3D > < /ControlTemplate > < /Setter.Value > < /Setter > < Style.Triggers > < EventTrigger RoutedEvent= '' ContentControl.MouseLeftButtonDown '' > //Axis Animation < /EventTrigger > < EventTrigger RoutedEvent= '' ContentControl.MouseEnter '' > //ScaleAnimation < /EventTrigger > < EventTrigger RoutedEvent= '' ContentControl.MouseLeave '' > //ScaleAnimation < /EventTrigger > < /Style.Triggers > < /Style > < /Page.Resources > < Page.Triggers > < EventTrigger RoutedEvent= '' Loaded '' > //Load Object Scale And Fade In < /EventTrigger > < /Page.Triggers > < Grid Name= '' MainGrid '' > < Canvas Name= '' MainCanvas '' VerticalAlignment= '' Stretch '' HorizontalAlignment= '' Stretch '' FlowDirection= '' LeftToRight '' > < ContentControl Opacity= '' 0 '' Name= '' MenuItem1 '' Style= '' { StaticResource MenuItemsStyle } '' MouseDown= '' MenuItem1_MouseDown '' Panel.ZIndex= '' 1 '' > < Image Source= '' /IsargaranProject ; component/Images/isargari.jpg '' / > < ContentControl.RenderTransform > < ScaleTransform ScaleX= '' 0.7 '' ScaleY= '' 0.7 '' x : Name= '' MenuItem1ST '' / > < /ContentControl.RenderTransform > < /ContentControl > < /Canvas > < /Grid > < /Page >",3d object not rendered "C_sharp : Just for testing I downloaded a PNG file via http ( in this case from a JIRA server via API ) For the http request I have a quite `` standart '' class HttpFileManager I just add for completeness : Later in my script I doIn resume the problem lies in the for and back converting inandThe result looks like thisOn the top the original image ; on the bottom the re-uploaded one.As you can see it grows from 40kb to 59kb so by the factor 1,475 . The same applies to larger files so that a 844kb growed to 1,02Mb.So my question isWhy is the uploaded image bigger after EncodeToPNG ( ) than the original image ? andIs there any compression that could/should be used on the PNG data in order to archive the same compression level ( if compression is the issue at all ) ? First I thought maybe different Color depths but both images are RGBA-32bitUpdateHere are the two imagesoriginal ( 40kb ) ( taken from here ) re-uploaded ( 59kb ) Update 2I repeated the test with a JPG file and EncodeToJPG ( ) and the result seems to be even worse : On the top the original image ; on the bottom the re-uploaded one.This time it went from 27kb to 98kb so factor 2,63 . Strangely the filesize also was constant 98kb no matter what I put as quality parameter for EncodeToJPG ( ) . public static class HttpFileManager { public void DownloadImage ( string url , Action < Texture > successCallback = null , Credentials credentials = null , Action < UnityWebRequest > errorCallback = null ) { StartCoroutine ( DownloadImageProcess ( url , successCallback , credentials , errorCallback ) ) ; } private static IEnumerator DownloadImageProcess ( string url , Action < Texture > successCallback , Credentials credentials , Action < UnityWebRequest > errorCallback ) { var www = UnityWebRequestTexture.GetTexture ( url ) ; if ( credentials ! = null ) { // This simply adds some headers to the request required for JIRA api // it is not relevant for this question AddCredentials ( www , credentials ) ; } yield return www.SendWebRequest ( ) ; if ( www.isNetworkError || www.isHttpError ) { Debug.LogErrorFormat ( `` Download from { 0 } failed with { 1 } '' , url , www.error ) ; errorCallback ? .Invoke ( www ) ; } else { Debug.LogFormat ( `` Download from { 0 } complete ! `` , url ) ; successCallback ? .Invoke ( ( ( DownloadHandlerTexture ) www.downloadHandler ) .texture ) ; } } public static void UploadFile ( byte [ ] rawData , string url , Action < UnityWebRequest > successcallback , Credentials credentials , Action < UnityWebRequest > errorCallback ) private static IEnumerator UploadFileProcess ( byte [ ] rawData , string url , Action < UnityWebRequest > successCallback , Credentials credentials , Action < UnityWebRequest > errorCallback ) { var form = new WWWForm ( ) ; form.AddBinaryData ( `` file '' , rawData , '' Test.png '' ) ; var www = UnityWebRequest.Post ( url , form ) ; www.SetRequestHeader ( `` Accept '' , `` application/json '' ) ; if ( credentials ! = null ) { // This simply adds some headers to the request required for JIRA api // it is not relevant for this question AddCredentials ( www , credentials ) ; } yield return www.SendWebRequest ( ) ; if ( www.isNetworkError || www.isHttpError ) { Debug.LogErrorFormat ( `` Upload to { 0 } failed with code { 1 } { 2 } '' , url , www.responseCode , www.error ) ; errorCallback ? .Invoke ( www ) ; } else { Debug.LogFormat ( `` Upload to { 0 } complete ! `` , url ) ; successCallback ? .Invoke ( www ) ; } } } public Texture TestTexture ; // Begin the downloadpublic void DownloadTestImage ( ) { _httpFileManager.DownloadImage ( ImageGetURL , DownloadImageSuccessCallback , _credentials ) ; } // After Download store the Textureprivate void DownloadImageSuccessCallback ( Texture newTexture ) { TestTexture = newTexture ; } // Start the uploadpublic void UploadTestImage ( ) { var data = ( ( Texture2D ) TestTexture ) .EncodeToPNG ( ) ; _httpFileManager.UploadFile ( data , ImagePostUrl , UploadSuccessCallback , _credentials ) ; } // After Uploadingprivate static void UploadSuccessCallback ( UnityWebRequest www ) { Debug.Log ( `` Upload worked ! `` ) ; } ( DownloadHandlerTexture ) www.downloadHandler ) .texture ( ( Texture2D ) TestTexture ) .EncodeToPNG ( ) ;",PNG file grows in Unity after applying downloaded texture and convert back to PNG via EncodeToPNG "C_sharp : I 'm using the FormsCommunityToolkit NuGet Package to make it so all of my Entries in my Xamarin.Forms app select all of their text when a user clicks on them . The example on their GitHub for using this effect on an Entry in XAML is this : This works if you put it on each individual Entry in your code , but I have a lot of Entries and would like to set it as the default in my App.xaml folder . I tried this : This method works for setting the default Keyboard for all entries , but setting the Effects in this way crashes the app with this error : Does anybody know a way of doing this so I do n't need to add the code to all of my Entries ? < Entry Placeholder= '' focus this entry . '' VerticalOptions= '' Start '' Text = `` FOCUS THIS ! `` > < Entry.Effects > < effects : SelectAllTextEntryEffect / > < /Entry.Effects > < /Entry > < Style TargetType= '' Entry '' > < Setter Property= '' Keyboard '' Value= '' Text '' / > < ! -- Defaults to capitalize first word -- > < Setter Property= '' Effects '' Value= '' effects : SelectAllTextEntryEffect '' / > < /Style > Ca n't resolve EffectsProperty on Entry",Xamarin.Forms adding Effect to all Entries in XAML "C_sharp : In my domain layer all domain objects emit events ( of type InvalidDomainObjectEventHandler ) to indicate invalid state when the IsValid property is called.On an aspx codebehind , I have to manually wire up the events for the domain object like this : Note that the same method is called in each case since the InvalidDomainobjectEventArgs class contains the message to display.Is there any way I can write a single statement to wire up all events of type InvalidDomainObjectEventHandler in one go ? ThanksDavid _purchaseOrder.AmountIsNull += new DomainObject.InvalidDomainObjectEventHandler ( HandleDomainObjectEvent ) ; _purchaseOrder.NoReason += new DomainObject.InvalidDomainObjectEventHandler ( HandleDomainObjectEvent ) ; _purchaseOrder.NoSupplier += new DomainObject.InvalidDomainObjectEventHandler ( HandleDomainObjectEvent ) ; _purchaseOrder.BothNewAndExistingSupplier += new DomainObject.InvalidDomainObjectEventHandler ( HandleDomainObjectEvent ) ;",C # : Hook up all events from object in single statement "C_sharp : Alright so this is what I haveAnd when I try to load up some broken python codeThis gives me a SecurityException instead of letting me see the actual exception from the code.If I set the PermissionSet ( PermissionState.Unrestricted ) it works fine.Any ideas on what permissions I need in order to catch these blasted errors ? private static AppDomain CreateSandbox ( ) { var permissions = new PermissionSet ( PermissionState.None ) ; permissions.AddPermission ( new SecurityPermission ( SecurityPermissionFlag.Execution ) ) ; permissions.AddPermission ( new FileIOPermission ( FileIOPermissionAccess.Read| FileIOPermissionAccess.PathDiscovery , AppDomain.CurrentDomain.BaseDirectory ) ) ; var appinfo = new AppDomainSetup ( ) ; appinfo.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory ; return AppDomain.CreateDomain ( `` Scripting sandbox '' , null , appinfo , permissions , fullTrustAssembly ) ; } try { var src = engine.CreateScriptSourceFromString ( s.Python , SourceCodeKind.Statements ) ; src.Execute ( ActionsScope ) ; } catch ( Exception e ) { ExceptionOperations eo = engine.GetService < ExceptionOperations > ( ) ; string error = eo.FormatException ( e ) ; Debug.WriteLine ( error ) ; } System.Security.SecurityException was caught Message=Request failed . Source=Microsoft.Scripting GrantedSet= < PermissionSet class= '' System.Security.PermissionSet '' version= '' 1 '' > < IPermission class= '' System.Security.Permissions.FileIOPermission , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' version= '' 1 '' Read= '' F : \Programming\OCTGN\octgnFX\Octgn\bin\ReleaseMode with Debug\ '' PathDiscovery= '' F : \Programming\OCTGN\octgnFX\Octgn\bin\ReleaseMode with Debug\ '' / > < IPermission class= '' System.Security.Permissions.SecurityPermission , mscorlib , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' version= '' 1 '' Flags= '' Execution '' / > < /PermissionSet > PermissionState= < PermissionSet class= '' System.Security.PermissionSet '' version= '' 1 '' Unrestricted= '' true '' / > RefusedSet= '' '' Url=file : ///F : /Programming/OCTGN/octgnFX/Octgn/bin/ReleaseMode with Debug/Microsoft.Scripting.DLL StackTrace : at Microsoft.Scripting.SyntaxErrorException.GetObjectData ( SerializationInfo info , StreamingContext context ) at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData ( Object serObj , String & typeName , String & assemName , String [ ] & fieldNames , Object [ ] & fieldValues ) at Microsoft.Scripting.Hosting.ScriptSource.Execute ( ScriptScope scope ) at Octgn.Scripting.Engine.LoadScripts ( ) in F : \Programming\OCTGN\octgnFX\Octgn\Scripting\Engine.cs : line 58 InnerException :",Sandboxed ironpython in c # SecurityException "C_sharp : This looks like a bug in lifting to null of operands on generic structs.Consider the following dummy struct , that overrides operator== : Now consider the following expressions : All three compile and run as expected . When they 're compiled ( using .Compile ( ) ) they produce the following code ( paraphrased to English from the IL ) : The first expression that takes only MyStruct ( not nullable ) args , simply calls op_Equality ( our implementation of operator == ) The second expression , when compiled , produces code that checks each argument to see if it HasValue . If both do n't ( both equal null ) , returns true . If only one has a value , returns false . Otherwise , calls op_Equality on the two values.The third expression checks the nullable argument to see if it has a value - if not , returns false . Otherwise , calls op_Equality . So far so good.Next step : do the exact same thing with a generic type - change MyStruct to MyStruct < T > everywhere in the definition of the type , and change it to MyStruct < int > in the expressions.Now the third expression compiles but throws a runtime exception InvalidOperationException with the following message : The operands for operator 'Equal ' do not match the parameters of method 'op_Equality'.I would expect generic structs to behave exactly the same as non-generic ones , with all the nullable-lifting described above.So my questions are : Why is there a difference between generic and non-generic structs ? What is the meaning of this exception ? Is this a bug in C # /.NET ? The full code for reproducing this is available on this gist . struct MyStruct { private readonly int _value ; public MyStruct ( int val ) { this._value = val ; } public override bool Equals ( object obj ) { return false ; } public override int GetHashCode ( ) { return base.GetHashCode ( ) ; } public static bool operator == ( MyStruct a , MyStruct b ) { return false ; } public static bool operator ! = ( MyStruct a , MyStruct b ) { return false ; } } Expression < Func < MyStruct , MyStruct , bool > > exprA = ( valueA , valueB ) = > valueA == valueB ; Expression < Func < MyStruct ? , MyStruct ? , bool > > exprB = ( nullableValueA , nullableValueB ) = > nullableValueA == nullableValueB ; Expression < Func < MyStruct ? , MyStruct , bool > > exprC = ( nullableValueA , valueB ) = > nullableValueA == valueB ;",Why are generic and non-generic structs treated differently when building expression that lifts operator == to nullable ? "C_sharp : ValueTuple types , declared as fields , can be mutable : or readonly : and this ( im ) mutability applies to each member . I would expect it to be stretched to const declarations as well : But this statement does not compile.Is there a certain case where it is an undesirable feature , or is it just something not implemented ? EDITOK , I understand now . My question was based on the assumption that the C # compiler treats ValueTuples differently than other types , regarding the keyword readonly . So , if it is already an exception , why not make another exception for consts . But , in fact , this logic seems to be applied to all structs . So this will not work : class Foo { ( int , int ) bar = ( 0 , 1 ) ; } class Foo { readonly ( int , int ) bar = ( 0 , 1 ) ; } class Foo { const ( int , int ) bar = ( 0 , 1 ) ; } class Foo { readonly ExampleStruct field ; void Method ( ) { field.structField = 2 ; } } struct ExampleStruct { public int structField ; }",Why can ValueTuple not be const ? "C_sharp : I 'm trying to use Reflection.Emit in C # to emit a using ( x ) { ... } block.At the point I am in code , I need to take the current top of the stack , which is an object that implements IDisposable , store this away in a local variable , implement a using block on that variable , and then inside it add some more code ( I can deal with that last part . ) Here 's a sample C # piece of code I tried to compile and look at in Reflector : This looks like this in Reflector : I have no idea how to deal with that `` .try ... '' part at the end there when using Reflection.Emit.Can someone point me in the right direction ? Edit : After asked about the code by email , I 'll post my fluent interface code here , but it is n't going to be much use to anyone unless you grab some of my class libraries , and that 's a bit of code as well . The code I was struggling with was part of my IoC project , and I needed to generate a class to implement automatic logging of method calls on a service , basically a decorator class for services that auto-generates the code.The main loop of the method , that implements all the interface methods , is this : EmitUsing spits out the BeginExceptionBlock that Jon answered with , so that 's what I needed to know.The above code is from LoggingDecorator.cs , the IL extensions are mostly in ILGeneratorExtensions.Designer.cs , and other files in the LVK.Reflection namespace . public void Test ( ) { TestDisposable disposable = new TestDisposable ( ) ; using ( disposable ) { throw new Exception ( `` Test '' ) ; } } .method public hidebysig instance void Test ( ) cil managed { .maxstack 2 .locals init ( [ 0 ] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable disposable , [ 1 ] class LVK.Reflection.Tests.UsingConstructTests/TestDisposable CS $ 3 $ 0000 , [ 2 ] bool CS $ 4 $ 0001 ) L_0000 : nop L_0001 : newobj instance void LVK.Reflection.Tests.UsingConstructTests/TestDisposable : :.ctor ( ) L_0006 : stloc.0 L_0007 : ldloc.0 L_0008 : stloc.1 L_0009 : nop L_000a : ldstr `` Test '' L_000f : newobj instance void [ mscorlib ] System.Exception : :.ctor ( string ) L_0014 : throw L_0015 : ldloc.1 L_0016 : ldnull L_0017 : ceq L_0019 : stloc.2 L_001a : ldloc.2 L_001b : brtrue.s L_0024 L_001d : ldloc.1 L_001e : callvirt instance void [ mscorlib ] System.IDisposable : :Dispose ( ) L_0023 : nop L_0024 : endfinally .try L_0009 to L_0015 finally handler L_0015 to L_0025 } foreach ( var method in interfaceType.GetMethods ( ) ) { ParameterInfo [ ] methodParameters = method.GetParameters ( ) ; var parameters = string.Join ( `` , `` , methodParameters .Select ( ( p , index ) = > p.Name + `` = { `` + index + `` } '' ) ) ; var signature = method.Name + `` ( `` + parameters + `` ) '' ; type.ImplementInterfaceMethod ( method ) .GetILGenerator ( ) // object [ ] temp = new object [ param-count ] .variable < object [ ] > ( ) // # 0 .ldc ( methodParameters.Length ) .newarr ( typeof ( object ) ) .stloc_0 ( ) // copy all parameter values into array .EmitFor ( Enumerable.Range ( 0 , methodParameters.Length ) , ( il , i ) = > il .ldloc_0 ( ) .ldc ( i ) .ldarg_opt ( i + 1 ) .EmitIf ( methodParameters [ i ] .ParameterType.IsValueType , a = > a .box ( methodParameters [ i ] .ParameterType ) ) .stelem ( typeof ( object ) ) ) // var x = _Logger.Scope ( LogLevel.Debug , signature , parameterArray ) .ld_this ( ) .ldfld ( loggerField ) .ldc ( LogLevel.Debug ) .ldstr ( signature ) .ldloc ( 0 ) .call_smart ( typeof ( ILogger ) .GetMethod ( `` Scope '' , new [ ] { typeof ( LogLevel ) , typeof ( string ) , typeof ( object [ ] ) } ) ) // using ( x ) { ... } .EmitUsing ( u = > u .ld_this ( ) .ldfld ( instanceField ) .ldargs ( Enumerable.Range ( 1 , methodParameters.Length ) .ToArray ( ) ) .call_smart ( method ) .EmitCatch < Exception > ( ( il , ex ) = > il .ld_this ( ) .ldfld ( loggerField ) .ldc ( LogLevel.Debug ) .ldloc ( ex ) .call_smart ( typeof ( ILogger ) .GetMethod ( `` LogException '' , new [ ] { typeof ( LogLevel ) , typeof ( Exception ) } ) ) ) ) .ret ( ) ; }",Using Reflection.Emit to emit a `` using ( x ) { ... } '' block ? "C_sharp : Maybe a little tricky , but I wonder why . In System.Linq.Enumerable.cs of System.Core.dll we have : In my code I 'm doing something evil : If I uncomment CommentedExtensions , I 'll get a compile error saying `` this call is ambiguous blabla '' as expected . But why I did n't get this error at the first time ? It 's also ambiguous ! EDIT After another test , I found that I wo n't get compile errors if the extension methods are in different namespaces , even they are completely the same . Why it 's allowed ? It brings ambiguous call of methods in c # .EDIT2 I know in fact the two Count are different in IL . In fact it 's calling and my evil extension method is calling : so they are different . But still I think it 's a bad smell . Do we have `` real '' extension methods ? which can prevent the evil behavior ? public static int Count < TSource > ( this IEnumerable < TSource > source ) ; namespace Test { public static class Extensions { public static int Count < TSource > ( this IEnumerable < TSource > source ) { return -1 ; //evil code } } //commented temporarily //public static class CommentedExtensions // { // public static int Count < TSource > ( this IEnumerable < TSource > source ) // { // return -2 ; //another evil code // } // } public static void Main ( string [ ] args ) { Console.WriteLine ( Enumerable.Range ( 0,10 ) .Count ( ) ) ; // -1 , evil code works Console.Read ( ) ; } } Enumerable.Count ( Enumerable.Range ( 0,10 ) ) MyExtension.Count ( Enumerable.Range ( 0,10 ) )",Extension methods and compile-time checking "C_sharp : I want to differentiate between these two json inputs in an action in Asp.Net Core : and I have an ordinary class like this in C # : I want to run a partial update of an object that can accept null as the value , but when the field will not be in the input it means I do n't want to update this field at all ( something else from setting it to null ) . { `` field1 '' : null , `` field2 '' : null } { `` field1 '' : null , } public class MyData { public string Field1 { get ; set ; } public string Field2 { get ; set ; } }",How to differentiate between null and non existing data in JSON in Asp.Net Core model binding ? "C_sharp : With following code I get the following result in de-CH culture : Though what I really want is `` Oktobär '' because I am translating into a dialect.Can I override which month names are returned in de-CH culture ? The names that it returns for other cultures should stay the same . var dateFormat = new DateTime ( 2016 , 10 , 12 ) .ToString ( `` MMMM '' ) ; //Oktober",Change month names that are returned from ToString ( `` MMMM '' ) to own names "C_sharp : I have code with mixed EF and normal SQL calls . The whole thing runs on Azure , so we use ReliableSqlConnection . We are using TransactionScope and we do n't have the Distributed Transaction Manager ( Azure again ) . Therefore I have to pass the ReliableSqlConnection to every SQL call.Now the problem is how to pass the ReliableSqlConnection into a EF call ? If found this post : How to use ADO.net Entity Framework with an existing SqlConnection ? Which would lead to this code : But neither can I convert a ReliableSqlConnection to DbConnection , nor does UniversalModelEntities accept a EntityConnection . MetadataWorkspace workspace = new MetadataWorkspace ( new string [ ] { `` res : //*/ '' } , new Assembly [ ] { Assembly.GetExecutingAssembly ( ) } ) ; using ( var scope = new TransactionScope ( ) ) using ( var conn = DatabaseUtil.GetConnection ( ) ) using ( EntityConnection entityConnection = new EntityConnection ( workspace , ( DbConnection ) conn ) ) using ( var db = new UniversalModelEntities ( entityConnection ) ) { //Do EF things //Call other SQL commands return db.SaveChanges ( ) ; }",Using the same SqlConnection for EntityFramework and `` normal '' SQL calls C_sharp : I am experimenting with ManipulationMode in XAML for an Windows store app . I want to have as many settings directly in my xaml so I do n't have to use the code behind so much . When I found a solution to get my swipe recognition working I found something to do in code behind like the following : Now I tried to get this working by using some xaml code . I then used thisThis works fine but I did n't find a way to use ManipulationMode TranslateX AND TranslateY at the same time.I tried to add some boolean operators in the attribute and the following snippet inside my grid.What do I get wrong or is it not possible to make this in pure XAML ? Thanks Hermann myGrid.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY ; < Grid Style= '' { StaticResource LayoutRootStyle } '' ManipulationMode= '' TranslateY '' ManipulationCompleted= '' manipulationCompleted '' > < Grid.ManipulationMode > < ManipulationModes > TranslateX < /ManipulationModes > < ManipulationModes > TranslateY < /ManipulationModes > < /Grid.ManipulationMode >,Can i choose more then one value for an attribute in XAML ? C_sharp : I sort of ran into this today when writing some code . Take the following as an example : Is there any difference between these two or are they compiled to exactly the same thing ? Is there a convention for one over the other ? So I know this is n't a critical question ( both work ) . I 'm just very curious about what the difference ( s ) might be ! EDIT - Modified the code example to be closer to what my original scenario actually is . I wanted the question to be clear so I replaced the variable with a constant . Did n't realize the compiler would to the arithmetic automatically ( thereby changing the answers to this question ) long valueCast = ( long ) ( 10 + intVariable ) ; long valueTyped = 10L + intVariable ;,Is there a difference between cast and strong type assignment ? "C_sharp : Is there a way in Log4Net or NLog ( or some other logger ) to output logs in an execution-stack-nested XML or JSON format , such that if function A ( ) calls B ( 7 ) that calls C ( `` something '' ) , it 'll output something like : or even better : Why ? so I 'd be able to use ( e.g . ) XML Notepad or some JSON-viewer ( do n't know of any remarkable one ... ) to quickly fold ( irrelevant ) or unfold ( relevant ) sub-calls when trying to understand what went wrong . I use PostSharp to log ( currently using mere indentation ) every method entry/exit and exceptions < Method name= '' A '' > < Method name= '' B '' params= '' ( int ) 7 '' > < Method name= '' C '' params= '' ( string ) 'something ' '' / > < /Method > < /Method > < Method name= '' A '' > < Method name= '' B '' params= '' ( int ) 7 '' > < Params > < int > 7 < /int > < /Params > < Method name= '' C '' > < Params > < string > something < /string > < /Params > < /Method > < /Method > < /Method >",Is there a way in Log4Net or NLog ( or some other logger ) to output logs in an execution-stack-nested XML or JSON format ? "C_sharp : I 'm adding some unit tests for my ASP.NET Core Web API , and I 'm wondering whether to unit test the controllers directly or through an HTTP client . Directly would look roughly like this : ... whereas through an HTTP client would look roughly like this : Searching online , it looks like both ways of testing an API seem to be used , but I 'm wondering what the best practice is . The second method seems a bit better because it naively tests the actual JSON response from the Web API without knowing the actual response object type , but it 's more difficult to inject mock repositories this way - the tests would have to connect to a separate local Web API server that itself was somehow configured to use mock objects ... I think ? [ TestMethod ] public async Task GetGroups_Succeeds ( ) { var controller = new GroupsController ( _groupsLoggerMock.Object , _uowRunnerMock.Object , _repoFactoryMock.Object ) ; var groups = await controller.GetGroups ( ) ; Assert.IsNotNull ( groups ) ; } [ TestMethod ] public void GetGroups_Succeeds ( ) { HttpClient.Execute ( ) ; dynamic obj = JsonConvert.DeserializeObject < dynamic > ( HttpClient.ResponseContent ) ; Assert.AreEqual ( 200 , HttpClient.ResponseStatusCode ) ; Assert.AreEqual ( `` OK '' , HttpClient.ResponseStatusMsg ) ; string groupid = obj [ 0 ] .id ; string name = obj [ 0 ] .name ; string usercount = obj [ 0 ] .userCount ; string participantsjson = obj [ 0 ] .participantsJson ; Assert.IsNotNull ( name ) ; Assert.IsNotNull ( usercount ) ; Assert.IsNotNull ( participantsjson ) ; }",Is it best practice to test my Web API controllers directly or through an HTTP client ? "C_sharp : I want to send a collection of integers to a post method on a web core api.The method is ; This is just for testing , I put a break point on the return statement and the inspectionIds payload is null.In Postman I haveEDIT : I have just removed the square brackets from the signature . I was trying both IEnumerable < int > and int [ ] but neither worked [ HttpPost ( `` open '' ) ] public IActionResult OpenInspections ( [ FromBody ] IEnumerable < int > inspectionIds ) { return NoContent ( ) ; // ...","Can not send a collection of integers to a Web Core Api Post method , it is set to null" "C_sharp : I am looking at this codeThe AsSequential ( ) is supposed to make the resulting array sorted . Actually it is sorted after its execution , but if I remove the call to AsSequential ( ) , it is still sorted ( since AsOrdered ( ) ) is called.What is the difference between the two ? var numbers = Enumerable.Range ( 0 , 20 ) ; var parallelResult = numbers.AsParallel ( ) .AsOrdered ( ) .Where ( i = > i % 2 == 0 ) .AsSequential ( ) ; foreach ( int i in parallelResult.Take ( 5 ) ) Console.WriteLine ( i ) ;",Using AsSequential in order to preserve order "C_sharp : I am retrieving an unencrypted key from a MemoryStream , converting it to some kind of string , and using that string with .Net 's crypto functions to encrypt data . I need to make sure the unencrypted key is wiped from memory after using it . I found SecureString , which I think will take care of the string , but I 'm not sure how to wipe the memory of the key before it becomes a SecureString.So the way everything works is : MemoryStream - > char [ ] - > SecureStringSecureString is passed the pointer to the char array , so it wipes the char array when it is finished ? This is it 's constructor : There is an example implementing it here.However , once the SecureString wipes the data ( if it wipes the data ) , I still need to know how to wipe the data in the MemoryStream , and any intermediate objects I have to create in order to get the char [ ] . So this question boils down to two parts : How does one read a MemoryStream straight into a char [ ] without producing anything else in memory ? ( And if that is n't possible , what is the ideal transition ? ie , MemoryStream - > string - > char [ ] ? ) and , How does one overwrite the memory used by the MemoryStream ( and any other signatures created in the MemStream- > char [ ] process ) when finished ? SecureString ( Char* , int32 )",MemoryStream to SecureString : Wiping the memory "C_sharp : Let me start with , I am not sure if this is possible . I am learning generics and I have several repositories in my app . I am trying to make an Interface that takes a generic type and converts it to something that all of the repositories can inherit from . Now on to my question.Is it possible to use a generic to determine what to find by ? To clarify a little better I was considering to be a string , int or whatever type I wanted to search for . What I am hoping for is I can say x.something where the something is equal to the variable passed in.I can set any repository to my dbcontext using theAny Suggestions ? public interface IRepository < T > { IEnumerable < T > FindAll ( ) ; IEnumerable < T > FindById ( int id ) ; IEnumerable < T > FindBy < A > ( A type ) ; } public IEnumerable < SomeClass > FindBy < A > ( A type ) { return _context.Set < SomeClass > ( ) .Where ( x = > x . == type ) ; // I was hoping to do x.type and it would use the same variable to search . } public IDbSet < TEntity > Set < TEntity > ( ) where TEntity : class { return base.Set < TEntity > ( ) ; }",Trying to use a generic with Entity Framework "C_sharp : I 'm trying to implement ( In App Billing ) for Xamarin forms solution by using plugin InAppBilling I could n't find any full code example or documentation for this plugin except this one I follow the instruction step by step but when i run my code I got this exception { System.NullReferenceException : Current Context/Activity is null , ensure that the MainApplication.cs file is setting the CurrentActivity in your source code so the In App Billing can use it . at Plugin.InAppBilling.InAppBillingImplementation.get_Context ( ) [ 0x00000 ] in C : \projects\inappbillingplugin\src\Plugin.InAppBilling.Android\InAppBillingImplementation.cs:59 at Plugin.InAppBilling.InAppBillingImplementation.ConnectAsync ( Plugin.InAppBilling.Abstractions.ItemType itemType ) [ 0x00000 ] in C : \projects\inappbillingplugin\src\Plugin.InAppBilling.Android\InAppBillingImplementation.cs:372 at myproject.MainPage+d__28.MoveNext ( ) [ 0x00051 ] in C : \Users\xuser\source\repos\myproject\MainPage.xaml.cs:415 } My sample code This code in ( Shared/Portable Class Libraries/.NET Standard ) MainPage.xaml.csAnd This code in Droid Project public partial class MainPage : ContentPage { void OnPurchased ( object sender , EventArgs e ) { InAppBilling ( ) ; } async void InAppBilling ( ) { try { var productId = `` xxxxx.xxxx_appbilling '' ; var connected = await CrossInAppBilling.Current.ConnectAsync ( ) ; if ( ! connected ) { //Could n't connect to billing , could be offline , alert user return ; } //try to purchase item var purchase = await CrossInAppBilling.Current.PurchaseAsync ( productId , ItemType.InAppPurchase , `` apppayload '' ) ; if ( purchase == null ) { //Not purchased , alert the user } else { //Purchased , save this information var id = purchase.Id ; var token = purchase.PurchaseToken ; var state = purchase.State ; } } catch ( Exception ex ) { //Something bad has occurred , alert user } finally { //Disconnect , it is okay if we never connected await CrossInAppBilling.Current.DisconnectAsync ( ) ; } } } public class MainActivity : global : :Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnActivityResult ( int requestCode , Result resultCode , Intent data ) { base.OnActivityResult ( requestCode , resultCode , data ) ; InAppBillingImplementation.HandleActivityResult ( requestCode , resultCode , data ) ; } }",Xamarin - Android - Plugin.InAppBilling Exception "C_sharp : I have a method to generate fully qualified URLs that I wrote which I would like to have as static so its easy to call from models as needed.I 'm still having problems however with being able to decide if its thread safe or not . Here is the code.What I know already is:1 ) The two strings passed in will be thread safe since they are immutable reference types.2 ) All objects instantiated within a static method can be considered thread safe since they exist only on the stack for that specific thread.What I 'm unsure of is:1 ) How does the use of HttpContext.Current and RouteTable.Routes play in this method ? They are both static properties that I 'm passing into the constructors.My questions are:1 ) What are the implications of using these static properties ? 2 ) Does the rest of my understanding of the safeness of this method ring true ? 3 ) What rules can I keep in mind in the future to help determine thread safeness in situations like this ? public string GenerateURLFromModel ( string action , string controller ) { HttpContextWrapper wrapper = new HttpContextWrapper ( HttpContext.Current ) ; Uri url = HttpContext.Current.Request.Url ; UrlHelper urlHelper = new UrlHelper ( new RequestContext ( wrapper , RouteTable.Routes.GetRouteData ( wrapper ) ) ) ; return url.AbsoluteUri.Replace ( url.PathAndQuery , urlHelper.Action ( action , controller ) ) ; }",c # thread safety when referencing static properties on other classes "C_sharp : I have a class called Question that has a property called Type . Based on this type , I want to render the question to html in a specific way ( multiple choice = radio buttons , multiple answer = checkboxes , etc ... ) . I started out with a single RenderHtml method that called sub-methods depending on the question type , but I 'm thinking separating out the rendering logic into individual classes that implement an interface might be better . However , as this class is persisted to the database using NHibernate and the interface implementation is dependent on a property , I 'm not sure how best to layout the class.The class in question : Based on the QuestionType enum property , I 'd like to render the following ( just an example ) : Currently , I have one big switch statement in a function called RenderHtml ( ) that does the dirty work , but I 'd like to move it to something cleaner . I 'm just not sure how.Any thoughts ? EDIT : Thanks to everyone for the answers ! I ended up going with the strategy pattern using the following interface : And the following implementation : The modified Question class uses an internal dictionary like so : Looks pretty clean to me . : ) public class Question { public Guid ID { get ; set ; } public int Number { get ; set ; } public QuestionType Type { get ; set ; } public string Content { get ; set ; } public Section Section { get ; set ; } public IList < Answer > Answers { get ; set ; } } < div > [ Content ] < /div > < div > < input type= '' [ Depends on QuestionType property ] '' / > [ Answer Value ] < input type= '' [ Depends on QuestionType property ] '' / > [ Answer Value ] < input type= '' [ Depends on QuestionType property ] '' / > [ Answer Value ] ... < /div > public interface IQuestionRenderer { string RenderHtml ( Question question ) ; } public class MultipleChoiceQuestionRenderer : IQuestionRenderer { # region IQuestionRenderer Members public string RenderHtml ( Question question ) { var wrapper = new HtmlGenericControl ( `` div '' ) ; wrapper.ID = question.ID.ToString ( ) ; wrapper.Attributes.Add ( `` class '' , `` question-wrapper '' ) ; var content = new HtmlGenericControl ( `` div '' ) ; content.Attributes.Add ( `` class '' , `` question-content '' ) ; content.InnerHtml = question.Content ; wrapper.Controls.Add ( content ) ; var answers = new HtmlGenericControl ( `` div '' ) ; answers.Attributes.Add ( `` class '' , `` question-answers '' ) ; wrapper.Controls.Add ( answers ) ; foreach ( var answer in question.Answers ) { var answerLabel = new HtmlGenericControl ( `` label '' ) ; answerLabel.Attributes.Add ( `` for '' , answer.ID.ToString ( ) ) ; answers.Controls.Add ( answerLabel ) ; var answerTag = new HtmlInputRadioButton ( ) ; answerTag.ID = answer.ID.ToString ( ) ; answerTag.Name = question.ID.ToString ( ) ; answer.Value = answer.ID.ToString ( ) ; answerLabel.Controls.Add ( answerTag ) ; var answerValue = new HtmlGenericControl ( ) ; answerValue.InnerHtml = answer.Value + `` < br/ > '' ; answerLabel.Controls.Add ( answerValue ) ; } var stringWriter = new StringWriter ( ) ; var htmlWriter = new HtmlTextWriter ( stringWriter ) ; wrapper.RenderControl ( htmlWriter ) ; return stringWriter.ToString ( ) ; } # endregion } public class Question { private Dictionary < QuestionType , IQuestionRenderer > _renderers = new Dictionary < QuestionType , IQuestionRenderer > { { QuestionType.MultipleChoice , new MultipleChoiceQuestionRenderer ( ) } } ; public Guid ID { get ; set ; } public int Number { get ; set ; } public QuestionType Type { get ; set ; } public string Content { get ; set ; } public Section Section { get ; set ; } public IList < Answer > Answers { get ; set ; } public string RenderHtml ( ) { var renderer = _renderers [ Type ] ; return renderer.RenderHtml ( this ) ; } }",.NET class design question "C_sharp : I 'm using the 3.5 library for microsoft code contractsI get the compiler message : '' Error 18 Contract section within try block in method 'Controller.RetrieveById ( System.Int32 ) ' UPDATE : I figured it out with your help : Move to top Check against Contract.ResultContract.Ensures ( Contract.Result ( ) ! = null , `` object must not be null `` ) ; public object RetrieveById ( int Id ) { //stuff happens ... Contract.Ensures ( newObject ! = null , `` object must not be null '' ) ; return newProject ; //No error message if I move the Contract.Ensures to here //But it is n't asserting/throwing a contract exception here either }",What does `` Contract ca n't be in try block '' mean ? "C_sharp : I found very nice answer on a question about building Expression Tree for Where query.Expression.Lambda and query generation at runtime , simplest `` Where '' exampleCan someone help me and show me how this example could be implemented in the scenario with nested property . I mean instead of : With that solution : How can I build the tree for the following ? var result = query.Where ( item = > item.Name == `` Soap '' ) var item = Expression.Parameter ( typeof ( Item ) , `` item '' ) ; var prop = Expression.Property ( item , `` Name '' ) ; var soap = Expression.Constant ( `` Soap '' ) ; var equal = Expression.Equal ( prop , soap ) ; var lambda = Expression.Lambda < Func < Item , bool > > ( equal , item ) ; var result = queryableData.Where ( lambda ) ; var result = query.Where ( item = > item.Data.Name == `` Soap '' ) .","Expression.Lambda and query generation at runtime , nested property “ Where ” example" "C_sharp : I 'm having trouble building predicates in a foreach loop . The variable that contains the value the enumerator is currently on is something I need to put in the predicate.So , is failing me . The expressions ORed together in Predicate basically all use the same t from inputEnumerable , when of course I want each expression ORed into Predicate to use a different t from inputEnumerable.I looked at the predicate in the debugger after the loop and it is in what looks like IL . Anyways each lambda in there looks exactly the same.Can anyone tell me what I might be doing wrong here ? Thanks , Isaac IQueryable query = getIQueryableSomehow ( ) ; Predicate = PredicateBuilder.False < SomeType > ( ) ; foreach ( SomeOtherType t in inputEnumerable ) { Predicate = Predicate.Or ( x = > x.ListInSomeType.Contains ( t ) ) } var results = query.Where ( Predicate ) ;",Trouble with using predicatebuilder in a foreach loop "C_sharp : I 'm having some trouble explaining the question in a single line for the title , but hopefully this description will provide you with enough insight to fully understand my question : I have a few variables in a Word document . Every variable has a Value which is a number ( starting from 0 up to the number of variables ) . A SortedDictionary is being filled out with these variables , but it 's possible that a variable has been deleted before , so there 's a 'gap ' so to say . Example:5 Variables are being added to a SortedDictionary < int , string > where the first number is the int and the string corresponds to the string part of the SortedDictionary.Now one of the variables is deleted so the dictionary is filled out like this : Eventually all of the SortedDictionary entries are added into a list box and I 'm using the first number as the index for the insertion . You can imagine that it will give an error when it tries to add an item into index 2 when index 1 does n't exist , but index 0 does.The way I want to solve it is when the user calls the DeleteVariable ( ) method and a variable is taken away , all the variables should automatically update their value ( number ) so when the SortedDictionary gets all the variables the list box no longer gives an error because all the numbers match ( no gaps ) .Please advise . 0 `` name 1 '' 1 `` name 2 '' 2 `` name 3 '' 0 `` name 1 '' 2 `` name 3 ''",What 's the easiest way to fill gaps in a list of numbers ? "C_sharp : I currently have some crude google code.. that works but I want to swap to an enum.Currently I need a byte to represent some bit flags that are set , I currently have this : used in line.. with ConvertToByte from this site ... However I wanted to use an enum as I touched on , so I created it as so : and thenBut how do I then get eventMessages to a byte ( 0x07 ) I think ! so I can append that to my byte array ? BitArray bitArray =new BitArray ( new bool [ ] { true , true , false , false , false , false , false , false } ) ; new byte [ ] { ConvertToByte ( bitArray ) } ) private static byte ConvertToByte ( BitArray bits ) // http : //stackoverflow.com/questions/560123/convert-from-bitarray-to-byte { if ( bits.Count ! = 8 ) { throw new ArgumentException ( `` incorrect number of bits '' ) ; } byte [ ] bytes = new byte [ 1 ] ; bits.CopyTo ( bytes , 0 ) ; return bytes [ 0 ] ; } [ Flags ] public enum EventMessageTypes { None = 0 , aaa = 1 , bbb = 2 , ccc = 4 , ddd = 8 , eee = 16 , fff = 32 , All = aaa | bbb | ccc | ddd | eee | fff // All Events } // Do bitwise OR to combine the values we want EventMessageTypes eventMessages = EventMessageTypes.aaa | EventMessageTypes.bbb | EventMessageTypes.ccc ;",Change from bitarray to enum "C_sharp : Initial situationI have an application that uses an existing database , currently using NHibernate as O/R-Mapper.Now I need to migrate to Entity Framework 6.1.1 using Code First and Fluent API Configuration.But now I have a problem with a part of the data model because it uses different types of inheritance strategies ( TPT and TPH ) StructureNote : Posting the complete data model here seemed a bit too enormous to me so I reproduced the problem I face in a small POC program.The column used as discrimator in the table is called TypeBased on this answer I added an abstract class Intermediate_TPH as intermediate layer : Some sample data : Entry with ID=3 is of type Inherited_TPTCodeThese are my entity classes and my context class : Running the following code will give me an error.OutputThe program produces the following output : 1 : Simpson 2 : Johnson 3 : Smith ( More details about SMITH ) 4 : Miller ( More details about MILLER ) An error occurred while preparing the command definition . See the inner exception for details . ( 26,10 ) : error 3032 : Problem in mapping fragments starting at lines 14 , 26 : EntityTypes PoC.Inherited_TPH , PoC.Inherited_TPT are being mapped to the same rows in table BaseEntity . Mapping conditions can be used to distinguish the rows that these types are mapped to.QuestionAs you can see , the mapping seems to work because I can load all data from Inherited_TPT and Inherited_TPH . But when accessing another entity , I get an exception.How do I need to configure the mapping to get rid of this error and be able to access the existing database structure ? CLASS | TABLE | TYPE -- -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- + -- -- -- BaseEntity ( abstract ) | BaseTable |Inherited_TPH | BaseTable | 1Inherited_TPT | Inherited_TPT | 2 class MyContext : DbContext { public MyContext ( string connectionString ) : base ( connectionString ) { } public DbSet < Inherited_TPH > TPH_Set { get ; set ; } public DbSet < Inherited_TPT > TPT_Set { get ; set ; } public DbSet < SomethingElse > Another_Set { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { modelBuilder .Entity < BaseEntity > ( ) .ToTable ( `` BaseTable '' ) ; modelBuilder .Entity < Inherited_TPH > ( ) .Map ( t = > t.Requires ( `` Type '' ) .HasValue ( 1 ) ) ; modelBuilder .Entity < Intermediate_TPT > ( ) .Map ( t = > t.Requires ( `` Type '' ) .HasValue ( 2 ) ) ; modelBuilder .Entity < Intermediate_TPT > ( ) .Map < Inherited_TPT > ( t = > t.ToTable ( `` Inherited_TPT '' ) ) ; modelBuilder .Entity < SomethingElse > ( ) .ToTable ( `` SomethingElse '' ) .HasKey ( t = > t.Id ) ; } } public abstract class BaseEntity { public virtual int Id { get ; set ; } public virtual string Title { get ; set ; } } public class Inherited_TPH : BaseEntity { } public abstract class Intermediate_TPT : BaseEntity { } public class Inherited_TPT : Intermediate_TPT { public virtual string Comment { get ; set ; } } public class SomethingElse { public virtual string Description { get ; set ; } public virtual int Id { get ; set ; } } static void Main ( string [ ] args ) { Database.SetInitializer < MyContext > ( null ) ; var ctx = new MyContext ( @ '' Data Source= ( local ) ; Initial Catalog=nh_ef ; Integrated Security=true '' ) ; try { // Accessing Inherited_TPH works just fine foreach ( var item in ctx.TPH_Set ) Console.WriteLine ( `` { 0 } : { 1 } '' , item.Id , item.Title ) ; // Accessing Inherited_TPT works just fine foreach ( var item in ctx.TPT_Set ) Console.WriteLine ( `` { 0 } : { 1 } ( { 2 } ) '' , item.Id , item.Title , item.Comment ) ; // The rror occurs when accessing ANOTHER entity : foreach ( var item in ctx.Another_Set ) Console.WriteLine ( `` { 0 } : { 1 } '' , item.Id , item.Description ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message ) ; if ( ex.InnerException ! = null ) { Console.WriteLine ( ex.InnerException.Message ) ; } } }",How can I mix TPH and TPT in Entity Framework 6 ? "C_sharp : I have a UserControl with a Grid that is subscribed to a Holding event . The problem is that the Holding event fires for the item I targeted as well as some other items in the ListView . I 'm using the control as a DataTemplate , by the way.User control code-behind : User Control contents : I was unable to use storyboards on items contained in a DataTemplate , so that forced me to use move its contents to a UserControl.Does this issue have to do with virtualization ? How can I fix this ? Alternatives will do.UPDATE : Some SO posts suggested that the recycling mode caused items to be reused . I 've added VirtualizingStackPanel.VirtualizationMode= '' Standard '' to my ListView but the problem surprisingly persists.So now I need to figure out a way to prevent other items from repeating the same opacity value ( which is not databound because it is set via a storyboard ) .UPDATE 2 : Now the Description that fades in upon holding the displayed item completely disappears when it goes out of view : < ListView ItemsSource= '' { Binding ... } '' Margin= '' 0 , 0 , 0 , 0 '' > ... < ListView.ItemTemplate > < DataTemplate > < local : MyUserControl/ > < /DataTemplate > < /ListView.ItemTemplate > < /ListView > private bool isDescriptionVisible = false ; private void Grid_Holding ( object sender , HoldingRoutedEventArgs e ) { if ( ! isDescriptionVisible ) { DescriptionFadeIn.Begin ( ) ; isDescriptionVisible = true ; } } private void Grid_Tapped ( object sender , TappedRoutedEventArgs e ) { if ( isDescriptionVisible ) { DescriptionFadeOut.Begin ( ) ; isDescriptionVisible = false ; } } < Grid.Resources > < Storyboard x : Name= '' FadeIn '' > < DoubleAnimation Storyboard.TargetProperty= '' Opacity '' Storyboard.TargetName= '' DescriptionLayer '' Duration= '' 0:0:0.3 '' To= '' .8 '' / > < /Storyboard > < Storyboard x : Name= '' FadeOut '' > < DoubleAnimation Storyboard.TargetProperty= '' Opacity '' Storyboard.TargetName= '' DescriptionLayer '' Duration= '' 0:0:0.3 '' To= '' 0 '' / > < /Storyboard > < /Grid.Resources > < Grid Margin= '' 0 , 0 , 0 , 48 '' Holding= '' Grid_Holding '' Tapped= '' Grid_Tapped '' > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' 1* '' / > < /Grid.RowDefinitions > < Image Source= '' { Binding Img } '' Stretch= '' UniformToFill '' Height= '' 240 '' Width= '' 450 '' / > < Grid x : Name= '' DescriptionLayer '' Background= '' Black '' Opacity= '' 0 '' > < TextBlock Text= '' { Binding Description } '' FontSize= '' 16 '' TextWrapping= '' Wrap '' Margin= '' 0 , 9 , 0 , 0 '' MaxHeight= '' 170 '' TextTrimming= '' CharacterEllipsis '' / > < /Grid > < StackPanel Grid.Row= '' 1 '' Margin= '' 12 '' > < TextBlock Text= '' { Binding Author } '' FontSize= '' 16 '' / > < TextBlock Text= '' { Binding Title } '' FontSize= '' 18 '' / > < /StackPanel > < /Grid > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < VirtualizingStackPanel/ > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel >",Holding event fires on untouched items in ListView "C_sharp : Possible Duplicate : When you use flag ( Enum ) you have a limit of 64 . What are the alternative when you reach the limit ? I have the following [ Flags ] enum that has to contain 33 elements : The value for the last item appears to be too large . Has anyone dealt with this before ? Any ideas how this can be resolved / worked around ? [ Flags ] public enum Types { None = 0 , Alarm = 1 , Exit = 2 , Panic = 4 , Fire = 8 , Tamper = 16 , Key = 32 , Line = 64 , FTC = 128 , Unused = 256 , tech_1 = 512 , // ... tech_2 through _7 omitted for brevity tech_8 = 65536 , fire_1 = 131072 , // ... fire_2 through _11 omitted for brevity fire_12 = 268435456 , Key = 536870912 , Exit = 1073741824 , Gas = 2147483648 , // Can not convert source type uint to target type int }",Flags enum with too many items ; last value is too large . How can I resolve this ? "C_sharp : I wanted to add a principle onto the thread by myself , without using the Identity mechanism which really reminds me the old membership/forms authentication mechanics.So I 've managed ( successfully ) to create a request with principle : MyAuthMiddleware.csThe Configure method : And here is the Action in the Controller : ( Notice Authorize attribute ) Ok Let 's try calling this method , Please notice that this does work : So where is the problem ? Please notice that there is an [ Authorize ] attribute . Now let 's remove setting principle on the thread ( by removing this line ) : But now when I navigate to : I 'm being redirected to : But I 'm expecting to see Unauthorized error.I 'm after WebApi alike responses . This is not a website but an API.Question : Why do n't I see the Unauthorized error ? And how can I make it appear ? Nb here is my ConfigureServices : EDITCurrently What I 've managed to do is to use OnRedirectionToLogin : But it will be really disappointing if that 's the way to go . I 'm expecting it to be like webapi . public class MyAuthMiddleware { private readonly RequestDelegate _next ; public MyAuthMiddleware ( RequestDelegate next ) { _next = next ; } public async Task Invoke ( HttpContext httpContext ) { var claims = new List < Claim > { new Claim ( `` userId '' , `` 22222222 '' ) } ; ClaimsIdentity userIdentity = new ClaimsIdentity ( claims , '' MyAuthenticationType '' ) ; ClaimsPrincipal principal = new ClaimsPrincipal ( userIdentity ) ; httpContext.User = principal ; await _next ( httpContext ) ; } } public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { //app.UseAuthentication ( ) ; //removed it . I will set the thread manually if ( env.IsDevelopment ( ) ) app.UseDeveloperExceptionPage ( ) ; app.UseMyAuthMiddleware ( ) ; // < -- -- -- -- -- Myne app.UseMvc ( ) ; app.Run ( async context = > { await context.Response.WriteAsync ( `` Hello World ! `` ) ; } ) ; } [ HttpGet ] [ Route ( `` data '' ) ] [ Authorize ] public IActionResult GetData ( ) { var a=User.Claims.First ( f = > f.Type == `` userId '' ) ; return new JsonResult ( new List < string > { `` a '' , `` b '' , a.ToString ( ) , User.Identity.AuthenticationType } ) ; } //httpContext.User = principal ; // line is remarked http : //localhost:5330/api/cities/data http : //localhost:5330/Account/Login ? ReturnUrl= % 2Fapi % 2Fcities % 2Fdata public void ConfigureServices ( IServiceCollection services ) { services.AddAuthentication ( CookieAuthenticationDefaults.AuthenticationScheme ) .AddCookie ( CookieAuthenticationDefaults.AuthenticationScheme , a = > { a.LoginPath = `` '' ; a.Cookie.Name = `` myCookie '' ; } ) ; services.AddMvc ( ) ; }",Asp.net Core action does not return 401 when using Authorize attribute on a thread without a principle ? "C_sharp : I have an interface called IEditorSpecialObject is an abstract class.Here´s my problem : I have a class which inherits from SpecialObject and a view which implements this IEditor interfaceNow , I have to check whether View implements IEditor < SpecialObject > But IEditor is always falseIs there any possibility to check if View is IEditor < SpecialObject > ? EditI have a method which is called when a closing event is raised.The views which are passed to this method can implement IEditor , but they also can implement another interface . In example IViewI have some classes called Person , Address and so on . They all inherits from SpecialObject.In some case e.Item inherits from IEditor or from IEditorBecause of that , I have to cast to my base class to access the defaut property fields public interface IEditor < T > where T : SpecialObject public class View : IEditor < Person > Boolean isEditor = View is IEditor < SpecialObject > void Closing ( object sender , MyEventArgs e ) { if ( e.Item is IView ) { // DO some closing tasks if ( e.Item is IEditor < SpecialObject > ) // always false { // Do some special tasks var editor = e.Item as IEditor < SpecialObject > ; var storedEditObect = editor.StoredObject ; // more tasks } } else if ( e.Item is ISomeOtherView ) { } }",C # generic cast C_sharp : Is there Scala equivalent of C # as keyword ? Scala 's asInstanceOf throws java.lang.ClassCastException : var something = obj as MyClass ; val something = obj.asInstanceOf [ MyClass ],Is there Scala equivalent of C # `` as '' keyword ? "C_sharp : Assume a system with multiple concurrent producers that each strives to persist some graph of objects with the following common entities uniquely identifiable by their names : For example , producer A saves some CommonEntityMeetings , while producer B saves CommonEntitySets . Either of them has to persist CommonEntitys related to their particular items.Basically , the key points are : There are independent producers . They operate concurrently . Theoretically ( though that may change and is not yet exactly true now ) they will operate through the same Web Service ( ASP.Net Web API ) , just with their respective endpoints/ '' resources '' . So ideally proposed solution should not rely on that.They strive to persist different graphs of objects that contain possibly not yet existing CommonEntity/CommonEntityGroup objects.CommonEntity/CommonEntityGroup are immutable once created and will never be modified or removed thereafter.CommonEntity/CommonEntityGroup are unique according to some of their properties ( Name and related common entity if any ( e.g . CommonEntity is unique by CommonEntity.Name+CommonEntityGroup.Name ) ) .Producers do not know/care about IDs of those CommonEntities - they usually just pass DTOs with Names ( unique ) of those CommonEntities and related information . So any Common ( Group ) Entity has to be found/created by Name.There is acertain possibility that producers will try to create the sameCommonEntity/CommonEntityGroup at the same time.Though it is muchmore likely that such CommonEntity/CommonEntityGroup objects will alreadyexist in db.So , with Entity Framework ( database first , though it probably does n't matter ) as DAL and SQL Server as storage what is an efficient and reliable way to ensure that all those producers will successfully persist their intersecting object graphs at the same time ? Taking into account that UNIQUE INDEX already ensures that there wo n't be duplicate CommonEntities ( Name , GroupName pair is unique ) I can see the following solutions : Ensure that each CommonEntity/CommonGroupEntity is found/created+SaveChanged ( ) before building the rest of the object 's graph.In such a case when SaveChanges is called for related entities there wo n't be any index violations due to other producers creating the same entities a moment before.To achieve it I will have some With this approach there will be multiple calls to SaveChanges and each CommonEntity will have its own sort of a Repository , though it seems to be the most reliable solution.Just create the entire graph and rebuild it from scratch if Index violations occurA bit ugly and inefficient ( with 10 CommonEntities we may have to retry it 10 times ) , but simple and more or less reliable.Just create the entire graph and replace duplicate entries if Index violations occurNot sure that there is an easy and reliable way to replace duplicate entries in more or less complex object graphs , though both case specific and more generic reflection-based solution can be implemented.Still , like a previous solution it may require multiple retries.Try to move this logic to database ( SP ) Doubt that it will be any easier to handle inside stored procedure . It will be the same optimistic or pessimistic approaches just implemented on database side . Though it may provide better performance ( not an issue in this case ) and put the insertion logic into one common place.Using SERIALIZABLE isolation level/TABLOCKX+SERIALIZABLE table hint in Stored Procedure - it should definitely work , but I 'd prefer not to lock the tables exclusively more than it is actually necessary , because actual race is quite rare . And as it is already mentioned in the title , I 'd like to find some optimistic concurrency approach.I would probably try the first solution , but perhaps there are better alternatives or some potential pitfalls . CREATE TABLE CommonEntityGroup ( Id INT NOT NULL IDENTITY ( 1 , 1 ) PRIMARY KEY , Name NVARCHAR ( 100 ) NOT NULL ) ; GOCREATE UNIQUE INDEX IX_CommonEntityGroup_Name ON CommonEntityGroup ( Name ) GOCREATE TABLE CommonEntity ( Id INT NOT NULL IDENTITY ( 1 , 1 ) PRIMARY KEY , Name NVARCHAR ( 100 ) NOT NULL , CommonEntityGroupId INT NOT NULL , CONSTRAINT FK_CommonEntity_CommonEntityGroup FOREIGN KEY ( CommonEntityGroupId ) REFERENCES CommonEntityGroup ( Id ) ) ; GOCREATE UNIQUE INDEX IX_CommonEntity_CommonEntityGroupId_Name ON CommonEntity ( CommonEntityGroupId , Name ) GO public class CommonEntityGroupRepository // sort of { public CommonEntityGroupRepository ( EntitiesDbContext db ) ... // CommonEntityRepository will use this class/method internally to create parent CommonEntityGroup . public CommonEntityGroup FindOrCreateAndSave ( String groupName ) { return this.TryFind ( groupName ) ? ? // db.FirstOrDefault ( ... ) this.CreateAndSave ( groupName ) ; } private CommonEntityGroup CreateAndSave ( String groupName ) { var group = this.Db.CommonEntityGroups.Create ( ) ; group.Name = groupName ; this.Db.CommonGroups.Add ( group ) try { this.Db.SaveChanges ( ) ; return group ; } catch ( DbUpdateException dbExc ) { // Check that it was Name Index violation ( perhaps make indices IGNORE_DUP_KEY ) return this.Find ( groupName ) ; // TryFind that throws exception . } } }",What is an efficient way to handle inserts of unique `` immutable '' entities by multiple producers with optimistic concurrency approach ? "C_sharp : Are DateTime functions in an EF query evaluated by the SQL Server , as where DateTime functions outside of the query expression are evaluated by the machine running the IL ? I have an application that has SalesOrdersI run an EF query and get different results when I do this : Than when I do this : I think this is because DateTime.UtcNow in an Entity Framework query is evaluated by the SQL Server , vs DateTime.UtcNow outside of the query is evaluated by the machine that 's running the IL ; I 'm basing that off this answer . I 'm in Azure platform as a service , debugging locally with an Azure SQL DB , if that matters . public class SalesOrder { public Int32 OrderID { get ; set ; } public DateTime Expiration { get ; set ; } } DateTime utcnow = DateTime.UtcNow ; var open = ( from a in context.SalesOrders where a.Expiration > utcnow select a ) .ToList ( ) ; var open = ( from a in context.SalesOrders where a.Expiration > DateTime.UtcNow select a ) .ToList ( ) ;",Datetime.UtcNow in Entity Framework query evaluated different than DateTime.UtcNow in C # IL "C_sharp : I 'm defining an interface in a .NETStandard library that is a factory for a HttpClient instances : The < FrameworkTarget > element in the .csproj file is set to netstandard1.1 ( HttpClient requires 1.1 ) ..NETStandard.Library 1.6.1 is referenced by default ( although not explicitly specified in the .csproj file ) .In the same solution , I start with a .NET Standard project and set the < FrameworkTargets > element to netcoreapp1.1 ; net461.I have some tests to test just creating an implementation of the interface ( I would n't normally test this , but this reduces it to the smallest self contained reproducible example ) .To aid in this , I have a private implementation of IHttpClientFactory : Then the tests : Basically , making a call through a variable with a type of the interface implementation , and a variable with a type of the implementing class ( that does n't matter though ) .When running the tests ( through Resharper , or dotnet test ) in .NETCoreApp 1.1 framework has all tests passing . However , when running on the .NET Framework 4.6.1 , I get a System.TypeLoadException stating that there is no implementation : Why does n't the test pass when running on the .NET Framework 4.6.1 ? There 's most certainly an implementation.I thought it could be because System.Net.Http was n't referenced in the test project ( not necessary in the interface definition because .NETStandard 1.6.1 is referenced , which references System.Net.Http ) so I made sure to add that , but the test still fails under the .NET Framework 4.6.1.The full setup can be found here : https : //github.com/OneFrameLink/Ofl.Net.Http.Abstractions/tree/c2bc5499b86e29c2e0a91282ca7dabcc1acc1176InfoVS.NET 2017.NET CLI : 1.1.0.NET Desktop Framework : 4.61.NET Core : 1.1 namespace Ofl.Net.Http { public interface IHttpClientFactory { Task < HttpClient > CreateAsync ( HttpMessageHandler handler , bool disposeHandler , CancellationToken cancellationToken ) ; } } private class HttpClientFactory : IHttpClientFactory { # region Implementation of IHttpClientFactory public Task < HttpClient > CreateAsync ( HttpMessageHandler handler , bool disposeHandler , CancellationToken cancellationToken ) { // Return a new client . return Task.FromResult ( new HttpClient ( ) ) ; } # endregion } [ Fact ] public async Task Test_CreateAsync_Interface_Async ( ) { // Cancellation token . CancellationToken cancellationToken = CancellationToken.None ; // The client factory . IHttpClientFactory factory = new HttpClientFactory ( ) ; // Not null . Assert.NotNull ( factory ) ; // Create client . HttpClient client = await factory.CreateAsync ( null , true , cancellationToken ) .ConfigureAwait ( false ) ; // Not null . Assert.NotNull ( client ) ; } [ Fact ] public async Task Test_CreateAsync_Concrete_Async ( ) { // Cancellation token . CancellationToken cancellationToken = CancellationToken.None ; // The client factory . var factory = new HttpClientFactory ( ) ; // Not null . Assert.NotNull ( factory ) ; // Create client . HttpClient client = await factory.CreateAsync ( null , true , cancellationToken ) .ConfigureAwait ( false ) ; // Not null . Assert.NotNull ( client ) ; } System.TypeLoadException : Method 'CreateAsync ' in type 'HttpClientFactory ' from assembly 'Ofl.Net.Http.Abstractions.Tests , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null ' does not have an implementation . at Ofl.Net.Http.Abstractions.Tests.HttpClientFactoryTests. < Test_CreateAsync_Interface_Async > d__1.MoveNext ( ) at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start [ TStateMachine ] ( TStateMachine & stateMachine ) at Ofl.Net.Http.Abstractions.Tests.HttpClientFactoryTests.Test_CreateAsync_Interface_Async ( )",Interface in .NETStandard 1.1 library does not have implementation in .NET 4.61 "C_sharp : It is fairly common to take an Expression tree , and convert it to some other form , such as a string representation ( for example this question and this question , and I suspect Linq2Sql does something similar ) .In many cases , perhaps even most cases , the Expression tree conversion will always be the same , i.e . if I have a functionthen any call with the same argument will always return the same result for example : So , in essence , the function call with a particular argument is really just a constant , except time is wasted at runtime re-computing it continuously.Assuming , for the sake of argument , that the conversion was sufficiently complex to cause a noticeable performance hit , is there any way to pre-compile the function call into an actual constant ? EditIt appears that there is no way to do this exactly within C # itself . The closest you can probably come within c # is the accepted answer ( though of course you would want to make sure that the caching itself was n't slower than regenerating ) . To actually convert to true constants , I suspect that with some work , you could use something like mono-cecil to modify the bytecodes after compilation . public string GenerateSomeSql ( Expression < Func < TResult , TProperty > > expression ) GenerateSomeSql ( x = > x.Age ) //suppose this will always return `` select Age from Person '' GenerateSomeSql ( x = > x.Ssn ) //suppose this will always return `` select Ssn from Person ''",Precompile Lambda Expression Tree conversions as constants ? "C_sharp : After reading Jon Skeet article , and this article from msdn , I still have a question Let 's say I have this code : Now let 's say I have 2 threads . which runs DoWork . ( let 's ignore for now , race conditions ) Will they both see the same g or each thread will have its own item ? ? ( value ) Will they both see the same mp or each thread will have its own item ? ? ( instance ) Will they both see the same i or each thread will have its own item ? ( value ) Will they both see the same mp2 or each thread will have its own item ? ( instance ) if they both see the same , why would I need static ? I 've searched a lot about this topic , and could n't find any article which states : Different Threads , ref types and value types ... ) MyPerson mp = new MyPerson ( ) ; //Field int g=0 ; //Field public void DoWork ( ) { int i ; MyPerson mp2 = new MyPerson ( ) ; ... }","Threading in C # , value types and reference types clarification ?" "C_sharp : I 'm assuming .NET DirectoryInfo and FileInfo objects are similar to Java 's java.io.File , i.e . they represent abstract paths and are n't necessarily connected to existing physical paths.I can do what I 'm trying to do ( empty out a folder and create it if it does n't exist ) in a different way that works , but I 'd like to understand why this does not : UPDATE : I tried the same code after a reboot and it worked fine . I still want to know what the similarities are to Java File objects and whether deleting a folder a DirectoryInfo object references can screw things up , but that is on the back burner now . using System.IO ; namespace TestWipeFolder { internal class Program { private static void Main ( string [ ] args ) { var di = new DirectoryInfo ( @ '' C : \foo\bar\baz '' ) ; if ( di.Exists ) { di.Delete ( true ) ; } // This does n't work . C : \foo\bar is still there but it does n't remake baz . di.Create ( ) ; } } }",Why wo n't a DirectoryInfo instance ( re ) create a folder after deleting it ? C_sharp : I saw this function in a source written by my coworkerI wonder if there is a scenario in which the guid might not be unique ? The code is used in a multithread scenario and clientsById is a dictionary of GUID and an object private String GetNewAvailableId ( ) { String newId = Guid.NewGuid ( ) .ToString ( ) ; while ( clientsById.ContainsKey ( newId ) ) { newId = Guid.NewGuid ( ) .ToString ( ) ; } return newId ; },Do I need to verify the uniqueness of a GUID ? "C_sharp : We are currently experiencing the following error ( from the logs ) when using our Windows Azure App : This error comes and goes we have n't been able to understand exactly what causes it.We 've tried everything ! Any help that anyone could provide would be awesome.The entire error message from the log is : System.Runtime.Serialization.SerializationException Assembly 'EntityFrameworkDynamicProxies-Marriott.emergePortal.Common , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null ' is not found . System.Web.HttpException ( 0x80004005 ) : Exception of type 'System.Web.HttpException ' was thrown . -- - > System.Runtime.Serialization.SerializatioFnException : Assembly 'EntityFrameworkDynamicProxies-Marriott.emergePortal.Common , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null ' is not found . at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode ( XmlReaderDelegator xmlReader , Int32 declaredTypeID , Type declaredType , String name , String ns ) at ReadArrayOfPropertyEnrollmentFromXml ( XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue ( XmlReaderDelegator xmlReader , XmlObjectSerializerReadContext context ) at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode ( XmlReaderDelegator xmlReader , Int32 declaredTypeID , Type declaredType , String name , String ns ) at ReadArrayOfPropertyEnrollmentFromXml ( XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString [ ] , XmlDictionaryString [ ] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue ( XmlReaderDelegator xmlReader , XmlObjectSerializerReadContext context ) at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode ( XmlReaderDelegator xmlReader , Int32 declaredTypeID , Type declaredType , String name , String ns ) at ReadArrayOfanyTypeFromXml ( XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString , XmlDictionaryString , CollectionDataContract ) at System.Runtime.Serialization.CollectionDataContract.ReadXmlValue ( XmlReaderDelegator xmlReader , XmlObjectSerializerReadContext context ) at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode ( XmlReaderDelegator xmlReader , Int32 declaredTypeID , Type declaredType , String name , String ns ) at ReadSerializableSessionStateStoreDataFromXml ( XmlReaderDelegator , XmlObjectSerializerReadContext , XmlDictionaryString [ ] , XmlDictionaryString [ ] ) at System.Runtime.Serialization.ClassDataContract.ReadXmlValue ( XmlReaderDelegator xmlReader , XmlObjectSerializerReadContext context ) at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeInSharedTypeMode ( XmlReaderDelegator xmlReader , Int32 declaredTypeID , Type declaredType , String name , String ns ) at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize ( XmlReaderDelegator xmlReader , Type declaredType , String name , String ns ) at System.Runtime.Serialization.NetDataContractSerializer.InternalReadObject ( XmlReaderDelegator xmlReader , Boolean verifyObjectName ) at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions ( XmlReaderDelegator reader , Boolean verifyObjectName , DataContractResolver dataContractResolver ) at System.Runtime.Serialization.XmlObjectSerializer.ReadObject ( XmlDictionaryReader reader ) at Microsoft.ApplicationServer.Caching.NetDataContractCacheObjectSerializer.Deserialize ( Stream stream ) at Microsoft.ApplicationServer.Caching.DataCacheObjectSerializationProvider.DeserializeUserObject ( Byte [ ] [ ] serializedData , ValueFlagsVersion flagsType ) at Microsoft.ApplicationServer.Caching.SocketClientProtocol.GetAndLock ( String key , TimeSpan timeout , DataCacheLockHandle & lockHandle , String region , Boolean lockKey , IMonitoringListener listener ) at Microsoft.ApplicationServer.Caching.DataCache. < > c__DisplayClass8a. < GetAndLock > b__89 ( ) at Microsoft.ApplicationServer.Caching.DataCache.GetAndLock ( String key , TimeSpan timeout , DataCacheLockHandle & lockHandle ) at Microsoft.Web.DistributedCache.DataCacheForwarderBase. < > c__DisplayClass31 ` 1. < PerformCacheOperation > b__30 ( ) at Microsoft.Web.DistributedCache.DataCacheRetryWrapper.PerformCacheOperation ( Action action ) at Microsoft.Web.DistributedCache.DataCacheForwarderBase.GetAndLock ( String key , TimeSpan timeout , DataCacheLockHandle & lockHandle ) at Microsoft.Web.DistributedCache.BlobBasedSessionStoreProvider.GetItem ( HttpContextBase context , String id , Boolean acquireWriteLock , Boolean & locked , TimeSpan & lockAge , Object & lockId , SessionStateActions & actions ) at Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider.GetItemExclusive ( HttpContext context , String id , Boolean & locked , TimeSpan & lockAge , Object & lockId , SessionStateActions & actions ) at System.Web.SessionState.SessionStateModule.GetSessionStateItem ( ) at System.Web.SessionState.SessionStateModule.PollLockedSessionCallback ( Object state ) at System.Web.SessionState.SessionStateModule.EndAcquireState ( IAsyncResult ar ) at System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion ( IAsyncResult ar )",Unsolvable ( as of yet ) serialization error "C_sharp : Although this code works ... I feel that it can benefit from using LINQ . This program will be used on a tablet with Atom processors , so i 'm just looking for the least resources/cycles used . private void AllowOtherSelectors ( bool value ) { foreach ( var c in this.Parent.Controls ) { if ( c == this ) continue ; if ( ! ( c is RoundGroupedSelector ) ) continue ; var rgs = c as RoundGroupedSelector ; rgs.AllowMultiple = value ; } }",How can I change same property in multiple Objects using LINQ ? "C_sharp : I would like to be able to include the file with a given order while creating a zip while using DotNet Zip.Files do n't appear in the sequence they were added to the zip.For now the order appears to be random.I would like to have the files xyz-Header , xyz-Summary included first and then the rest of the files . xyz-Header.csv xyz-Summary.csv xyz-Male.csv xyz-Female.csvxyz and names for other files are programmatically determined but Header and Summary files are always included.Code SnippetI would appreciate any help on this . private MemoryStream GetZip ( ) { ZipFile zip = new ZipFile ( ) ; List < string , string > files = getFiles ( ) ; zip.AddEntry ( `` xyz-Header.csv '' , getHeader ( files ) ) ; zip.AddEntry ( `` xyz-Summary '' , getSummary ( files ) ) ; foreach ( var x in files ) { zip.AddEntry ( `` xyz- '' + x.Item1 + `` .csv '' , x.Item2 ) ; } MemoryStream memoryStream = new MemoryStream ( ) ; zip.Save ( memoryStream ) ; memoryStream.position = 0 ; return memoryStream ; }",How to give an Order to the files included in zip file created with dotnet Zip "C_sharp : I have a line of code that looks like this : Is it possible to write something more elegant than this ? Something like : I know that my example is n't possible , but is there a way to make this look `` cleaner '' ? if ( obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float ) if ( obj is byte , int , long )",If statement simplification in C # "C_sharp : I trying to handle to following character : ⨝ ( http : //www.fileformat.info/info/unicode/char/2a1d/index.htm ) If you checking whether an empty string starting with this character , it always returns true , this does not make any sense ! Why is that ? // visual studio 2008 hides lines that have this char literally ( bug in visual studio ? ! ? ) so i wrote it 's unicode instead.char specialChar = ( char ) 10781 ; string specialString = specialChar.ToString ( ) ; // prints 1Console.WriteLine ( specialString.Length ) ; // prints 10781Console.WriteLine ( ( int ) specialChar ) ; // prints falseConsole.WriteLine ( string.Empty.StartsWith ( `` A '' ) ) ; // both prints true WTF ? ! ? Console.WriteLine ( string.Empty.StartsWith ( specialString ) ) ; Console.WriteLine ( string.Empty.StartsWith ( ( ( char ) 10781 ) .ToString ( ) ) ) ;",string.Empty.StartsWith ( ( ( char ) 10781 ) .ToString ( ) ) always returns true ? C_sharp : Possible Duplicate : C # “ as ” cast vs classic cast I want to know what happens under the hood of the .Net CLR when I do something likeand how the second line differs from string myStr = myObj.ToString ( ) or string myStr = myObj as string ; looking around I found generics answers such as `` the compiler inserts code there '' but I 'm not satisfied ... I 'm looking for deep undertanding of the cast mechanics ... Oh the compiler inserts code ? Show me ! The compiler optmizes the code ? How ? When ? Pls get as close to the metal as you can ! ! ! object myObj = `` abc '' ; string myStr = ( string ) myObj ;,What is a cast under the hood "C_sharp : I 'm working on a visual studio add-in that takes SQL queries in your project , plays the request and generates a C # wrapper class for the results . I want to do a simplest possible dependency injection , where projects using my add-in supply a class that can provide the project 's db connection string , among other things.This interface is defined in my add-in ... And the question : How do I define and instantiate the concrete implementation , then use it from the add-in ? Progress ? The interface above is defined in the add-in . I 've created a reference in the target project to the add-in , written the concrete implementation , and put the name of this class in the target project web.config . Now I need to load the target project from the add-in to use my concrete class.If I use Assembly.Load ( ) ... I can successfully load my class , but I lock the target assembly and can no longer compile the target project.If I create a temporary app domain ... I get a file not found exception on the call ad.Load ( ) , even though the bytes of my dll are in memory.If I use CreateInstanceFromAndUnwrap ( ) ... I get an InvalidCastException . `` Unable to cast transparent proxy to type QueryFirst.IQueryFirst_TargetProject '' This makes me think I 'm very close ? Why would an explicit cast work fine with Assembly.Load ( ) , but fail when the same assembly is loaded in a newly created AppDomain ? [ Serializable ] public interface IDesignTimeQueryProcessing { public string ConnectionString { get ; } ... } var userAssembly = Assembly.LoadFrom ( GetAssemblyPath ( userProject ) ) ; IQueryFirst_TargetProject iqftp = ( IQueryFirst_TargetProject ) Activator.CreateInstance ( userAssembly.GetType ( typeName.Value ) ) ; AppDomain ad = AppDomain.CreateDomain ( `` tmpDomain '' , null , new AppDomainSetup { ApplicationBase = Path.GetDirectoryName ( targetAssembly ) } ) ; byte [ ] assemblyBytes = File.ReadAllBytes ( targetAssembly ) ; var userAssembly = ad.Load ( assemblyBytes ) ; AppDomain ad = AppDomain.CreateDomain ( `` tmpDomain '' , null , new AppDomainSetup { ApplicationBase = Path.GetDirectoryName ( targetAssembly ) } ) ; IQueryFirst_TargetProject iqftp = ( IQueryFirst_TargetProject ) ad.CreateInstanceFromAndUnwrap ( targetAssembly , typeName.Value ) ;",Dependency injection for a visual studio add-in "C_sharp : I have a context menu in LongListSelector.This list is created and updated in runtime.Here 's the method that handles click event on menu itemThe following method populates the SavedGames listSo , when the SavedGames collection is populaed for the first time it work perfect , but when the collections changes ( delete some old items , add new ) I observe some strange behaviour . When the OnClick event is fired I see menuItem.DataContext is not for the menu item I clicked but for some old menu items which were deleted . < phone : PanoramaItem Header= '' { Binding Path=LocalizedResources.SavedGamesHeader , Source= { StaticResource LocalizedStrings } } '' Orientation= '' Horizontal '' > < phone : LongListSelector Margin= '' 0,0 , -22,2 '' ItemsSource= '' { Binding SavedGames } '' > < phone : LongListSelector.ItemTemplate > < DataTemplate > < StackPanel Orientation= '' Vertical '' Margin= '' 12,2,0,20 '' Width= '' 432 '' > < toolkit : ContextMenuService.ContextMenu > < toolkit : ContextMenu > < toolkit : MenuItem Header= '' Remove '' Click= '' RemoveSave_OnClick '' / > < /toolkit : ContextMenu > < /toolkit : ContextMenuService.ContextMenu > < Image Margin= '' 10,5,10,0 '' Height= '' 173 '' Width= '' 248 '' Source= '' { Binding Screen } '' Stretch= '' Fill '' HorizontalAlignment= '' Left '' > < /Image > < StackPanel Width= '' 311 '' Margin= '' 8,5,0,0 '' HorizontalAlignment= '' Left '' > < TextBlock Tap= '' Save_OnTap '' Tag= '' { Binding SavedGame } '' Text= '' { Binding SaveName } '' TextWrapping= '' Wrap '' Margin= '' 10,0 '' Style= '' { StaticResource PhoneTextExtraLargeStyle } '' FontSize= '' { StaticResource PhoneFontSizeMedium } '' Foreground= '' White '' FontWeight= '' Bold '' FontFamily= '' Arial Black '' HorizontalAlignment= '' Left '' / > < TextBlock Text= '' { Binding GameName } '' TextWrapping= '' Wrap '' Margin= '' 10 , -2,10,0 '' Style= '' { StaticResource PhoneTextSubtleStyle } '' HorizontalAlignment= '' Left '' / > < StackPanel Orientation= '' Horizontal '' HorizontalAlignment= '' Left '' > < TextBlock Text= '' Created on : '' Margin= '' 10 , -2,10,0 '' Style= '' { StaticResource PhoneTextSubtleStyle } '' / > < TextBlock Text= '' { Binding Created } '' TextWrapping= '' Wrap '' Margin= '' 5 , -2,10,0 '' Style= '' { StaticResource PhoneTextSubtleStyle } '' / > < /StackPanel > < /StackPanel > < /StackPanel > < /DataTemplate > < /phone : LongListSelector.ItemTemplate > < /phone : LongListSelector > < /phone : PanoramaItem > private void RemoveSave_OnClick ( object sender , RoutedEventArgs e ) { var menuItem = ( MenuItem ) sender ; var saveViewModel = menuItem.DataContext as SavesViewModel ; EmuStorageMgr.Instance.DeleteSave ( saveViewModel.SavedGame.SaveFolder ) ; App.ViewModel.RescanSaves ( ) ; } public ObservableCollection < SavesViewModel > SavedGames { get ; private set ; } public void RescanSaves ( ) { SavedGames.Clear ( ) ; var saves = EmuStorageMgr.Instance.GetSaves ( ) ; foreach ( var save in saves ) { SavedGames.Add ( new SavesViewModel ( save ) ) ; } this.IsSavesLoaded = true ; NotifyPropertyChanged ( `` SavedGames '' ) ; }",ContextMenu in DataTemplate Binding issue "C_sharp : Lets say I have an interface like this : Is there any way to force the implementer of the interface to implement parts of it explicitly ? Something like : Edit : As to why I care about whether the interface is implemented explicitly or not ; it 's not like it matters as far as functionality goes , but it could be helpful to hide some unnecessary details from people using the code . I 'm trying to mimic multiple inheritance in my system , using this pattern : If the MovableComponent property was implemented explicitly , it would , in most cases , be hidden from whoever was using the class . Hope that explanation was n't too horrible . public interface MyInterface { int Property1 { get ; } void Method1 ( ) ; void Method2 ( ) ; } public interface MyInterface { int Property1 { get ; } explicit void Method1 ( ) ; explicit void Method2 ( ) ; } public interface IMovable { MovableComponent MovableComponent { get ; } } public struct MovableComponent { private Vector2 position ; private Vector2 velocity ; private Vector2 acceleration ; public int Method1 ( ) { // Implementation } public int Method2 ( ) { // Implementation } } public static IMovableExtensions { public static void Method1 ( this IMovable movableObject ) { movableObject.MovableComponent.Method1 ( ) ; } public static void Method2 ( this IMovable movableObject ) { movableObject.MovableComponent.Method2 ( ) ; } } public class MovableObject : IMovable { private readonly MovableComponent movableComponent = new MovableComponent ( ) ; public MovableComponent MovableComponent { get { return movableComponent ; } // Preferably hiddem , all it 's methods are available through extension methods . } } class Program { static void Main ( string [ ] args ) { MovableObject movableObject = new MovableObject ( ) ; movableObject.Method1 ( ) ; // Extension method movableObject.Method2 ( ) ; // Extension method movableObject.MovableComponent // Should preferably be hidden . } }",Is it possible to force explicit implementation of an interface ( or parts of it ) ? "C_sharp : I was trying to implement drag and drop in treeview .I generate the root nodes first then if I drag any item over the treeview I want to put it under exact root nodes.I need something like so that from tNode I can find it 's root node and can populate it under that parent node.can anybody help me out with findNodeAtPoint ( ) functionality . private void treeView1_DragOver ( object sender , DragEventArgs e ) { TreeNode tNode = FindNodeAtPoint ( e.X , e.Y ) ; } private TreeNode FindNodeAtPoint ( int x , int y ) { Point p = new Point ( x , y ) ; p = PointToClient ( p ) ; ... ... ... ... ... . ... ... ... ... ... . ... ... ... ... ... . }",Finding exact node C # "C_sharp : I am trying to get user input , parse it and then display with String.Format ( ) , formatting thousands with comas.Basically I want to keep all decimals ( including trailing zeroes ) that were provided and just add formatting for thousands.I tried : So , if user provides1000 I will display 1,0001000.00 = > 1,000.001000.0 = > 1,000.01,000.5 = > 1,000.5 String.Format ( `` { 0 : # ,0. # # # # # # } '' , Decimal.Parse ( input ) ) ; String.Format ( `` { 0 : # ,0. # # # # # # } '' , Double.Parse ( input ) ;","C # Convert string to double/decimal and back to string , keeping trailing zeroes , adding comas for thousands" "C_sharp : As the title says , I noticed that the categories are not shown in a **PropertyGrid* ( in its default collection editor ) for a collection ( Of T ) , when all the properties of class `` T '' are read-only.The code below represents the code structure I have : C # : VB.NET : The problem is with TestProperty3 . When it is read-only , the category ( `` Category 1 '' ) is not shown in the property grid ... But if I do the property editable , then the category is shown ... C : # VB.NET : More than that , let 's imagine that in TestClass3 are declared 10 properties ( instead of 1 like in this example ) , and 9 of them are read-only , and 1 is editable , then , in this circumstances all the categories will be shown . On the other side , if all the 10 properties are read-only , then categories will not be shown.This behavior of the PeopertyGrid is very annoying and unexpected for me . I would like to see my custom categories regardless of whether in my class are declared properties with a setter or without it.What alternatives I have to show categories having all the properties of my class read-only ? . Maybe writing a custom TypeConverter or collection editor could fix this annoying visual representation behavior ? . [ TypeConverter ( typeof ( ExpandableObjectConverter ) ) ] public class TestClass1 { public TestClass2 TestProperty1 { get ; } = new TestClass2 ( ) ; } [ TypeConverter ( typeof ( ExpandableObjectConverter ) ) ] public sealed class TestClass2 { [ TypeConverter ( typeof ( CollectionConverter ) ) ] public ReadOnlyCollection < TestClass3 > TestProperty2 { get { List < TestClass3 > collection = new List < TestClass3 > ( ) ; for ( int i = 0 ; i < = 10 ; i++ ) { collection.Add ( new TestClass3 ( ) ) ; } return collection.AsReadOnly ( ) ; } } } [ TypeConverter ( typeof ( ExpandableObjectConverter ) ) ] public sealed class TestClass3 { [ Category ( `` Category 1 '' ) ] public string TestProperty3 { get ; } = `` Test '' ; } < TypeConverter ( GetType ( ExpandableObjectConverter ) ) > Public Class TestClass1 Public ReadOnly Property TestProperty1 As TestClass2 = New TestClass2 ( ) End Class < TypeConverter ( GetType ( ExpandableObjectConverter ) ) > Public NotInheritable Class TestClass2 < TypeConverter ( GetType ( CollectionConverter ) ) > Public ReadOnly Property TestProperty2 As ReadOnlyCollection ( Of TestClass3 ) Get Dim collection As New List ( Of TestClass3 ) For i As Integer = 0 To 10 collection.Add ( New TestClass3 ( ) ) Next Return collection.AsReadOnly ( ) End Get End PropertyEnd Class < TypeConverter ( GetType ( ExpandableObjectConverter ) ) > Public NotInheritable Class TestClass3 < Category ( `` Category 1 '' ) > Public ReadOnly Property TestProperty3 As String = `` Test '' End Class [ Category ( `` Category 1 '' ) ] public string TestProperty3 { get ; set ; } = `` Test '' ; < Category ( `` Category 1 '' ) > Public Property TestProperty3 As String = `` Test ''","Categories are not shown in PropertyGrid for a collection < T > , when all the properties of < T > are read-only" "C_sharp : I 'm using a certain method body to call stored procedures , with the following sample code : What bugs me I have most of the above code repeating time and time again in my cs file for every different procedure I call.Obviously I can clear it up and have the one Function being called with the procedure name as a variable , but how do I feed it different number of Parameters ( with different Data Types - int , string bool - never anything else ) for the different procedures I use ? I can have few different functions with different number of parameters ( 0-10 ) , but I feel there is a better way of doing this ? public void StoredProcedureThatIsBeingcalled ( int variable_1 , int variable_2 , out DataSet ds ) { using ( SqlConnection con = new SqlConnection ( DatabaseConnectionString ) ) { ds = new DataSet ( `` DsToGoOut '' ) ; using ( SqlCommand cmd = new SqlCommand ( `` StoredProcedureThatIsBeingcalled '' , DbConn.objConn ) ) { cmd.CommandType = CommandType.StoredProcedure ; cmd.Parameters.Add ( new SqlParameter ( `` @ variable_1 '' , variable_1 ) ) ; cmd.Parameters.Add ( new SqlParameter ( `` @ variable_2 '' , variable_2 ) ) ; try { con.Open ( ) ; SqlDataAdapter objDataAdapter = new SqlDataAdapter ( ) ; objDataAdapter.SelectCommand = cmd ; objDataAdapter.Fill ( ds ) ; con.Close ( ) ; } catch ( Exception ex ) { //sql_log_err } } } }",Minimize code repeatednesses when calling Stored Procedures "C_sharp : I have base class AInhereted BStatic class S with extension methodExample we create instance of type B and invoke Method on it , we expect that it will be public override void Method ( B parameter ) actual result is public virtual void Method ( object parameter ) .Why compiler does n't select more suitible method ? ? ? UPD And why it is not extension method ? public class A { public virtual void Method ( A parameter ) { Console.WriteLine ( MethodBase.GetCurrentMethod ( ) ) ; } public virtual void Method ( B parameter ) { Console.WriteLine ( MethodBase.GetCurrentMethod ( ) ) ; } } public class B : A { public virtual void Method ( object parameter ) { Console.WriteLine ( MethodBase.GetCurrentMethod ( ) ) ; } public override void Method ( A parameter ) { Console.WriteLine ( MethodBase.GetCurrentMethod ( ) ) ; } public override void Method ( B parameter ) { Console.WriteLine ( MethodBase.GetCurrentMethod ( ) ) ; } } public static class S { public static void Method ( this B instance , B parameter ) { Console.WriteLine ( MethodBase.GetCurrentMethod ( ) ) ; } } var b = new B ( ) ; b.Method ( new B ( ) ) ; // B.Method ( Object parameter ) Why ? ? ?",Why overloaded methods have lower priority than instance method C_sharp : I have two classes one is derived from CheckBoxList and the second one from DropDownList . The code inside them is exactly the same . The only difference is that I need first one at places where I need to show checkboxlist and second one to show dropdownlist . Below is my code : The second oneNow as you can see the internal code is exactly the same which I want to avoid . How can I make a common class for it so as to remove code duplicacy ? using System ; using System.Collections.ObjectModel ; using System.Web.UI.WebControls ; namespace Sample { public class MyCheckBoxList : CheckBoxList { public int A { get ; set ; } public int B { get ; set ; } protected override void OnLoad ( EventArgs e ) { //dummy task Collection < int > ints = new Collection < int > ( ) ; // ... ... .. this.DataSource = ints ; this.DataBind ( ) ; } } } using System ; using System.Collections.ObjectModel ; using System.Web.UI.WebControls ; namespace Sample { public class MyDropDownList : DropDownList { public int A { get ; set ; } public int B { get ; set ; } protected override void OnLoad ( EventArgs e ) { //dummy task Collection < int > ints = new Collection < int > ( ) ; // ... ... .. this.DataSource = ints ; this.DataBind ( ) ; } } },How to make a common subclass to remove duplicate code "C_sharp : I showed this struct to a fellow programmer and they felt that it should be a mutable class . They felt it is inconvenient not to have null references and the ability to alter the object as required . I would really like to know if there are any other reasons to make this a mutable class . [ Serializable ] public struct PhoneNumber : IEquatable < PhoneNumber > { private const int AreaCodeShift = 54 ; private const int CentralOfficeCodeShift = 44 ; private const int SubscriberNumberShift = 30 ; private const int CentralOfficeCodeMask = 0x000003FF ; private const int SubscriberNumberMask = 0x00003FFF ; private const int ExtensionMask = 0x3FFFFFFF ; private readonly ulong value ; public int AreaCode { get { return UnmaskAreaCode ( value ) ; } } public int CentralOfficeCode { get { return UnmaskCentralOfficeCode ( value ) ; } } public int SubscriberNumber { get { return UnmaskSubscriberNumber ( value ) ; } } public int Extension { get { return UnmaskExtension ( value ) ; } } public PhoneNumber ( ulong value ) : this ( UnmaskAreaCode ( value ) , UnmaskCentralOfficeCode ( value ) , UnmaskSubscriberNumber ( value ) , UnmaskExtension ( value ) , true ) { } public PhoneNumber ( int areaCode , int centralOfficeCode , int subscriberNumber ) : this ( areaCode , centralOfficeCode , subscriberNumber , 0 , true ) { } public PhoneNumber ( int areaCode , int centralOfficeCode , int subscriberNumber , int extension ) : this ( areaCode , centralOfficeCode , subscriberNumber , extension , true ) { } private PhoneNumber ( int areaCode , int centralOfficeCode , int subscriberNumber , int extension , bool throwException ) { value = 0 ; if ( areaCode < 200 || areaCode > 989 ) { if ( ! throwException ) return ; throw new ArgumentOutOfRangeException ( `` areaCode '' , areaCode , @ '' The area code portion must fall between 200 and 989 . `` ) ; } else if ( centralOfficeCode < 200 || centralOfficeCode > 999 ) { if ( ! throwException ) return ; throw new ArgumentOutOfRangeException ( `` centralOfficeCode '' , centralOfficeCode , @ '' The central office code portion must fall between 200 and 999 . `` ) ; } else if ( subscriberNumber < 0 || subscriberNumber > 9999 ) { if ( ! throwException ) return ; throw new ArgumentOutOfRangeException ( `` subscriberNumber '' , subscriberNumber , @ '' The subscriber number portion must fall between 0 and 9999 . `` ) ; } else if ( extension < 0 || extension > 1073741824 ) { if ( ! throwException ) return ; throw new ArgumentOutOfRangeException ( `` extension '' , extension , @ '' The extension portion must fall between 0 and 1073741824 . `` ) ; } else if ( areaCode.ToString ( ) [ 1 ] == ' 9 ' ) { if ( ! throwException ) return ; throw new ArgumentOutOfRangeException ( `` areaCode '' , areaCode , @ '' The second digit of the area code can not be greater than 8 . `` ) ; } else { value |= ( ( ulong ) ( uint ) areaCode < < AreaCodeShift ) ; value |= ( ( ulong ) ( uint ) centralOfficeCode < < CentralOfficeCodeShift ) ; value |= ( ( ulong ) ( uint ) subscriberNumber < < SubscriberNumberShift ) ; value |= ( ( ulong ) ( uint ) extension ) ; } } public override bool Equals ( object obj ) { return obj ! = null & & obj.GetType ( ) == typeof ( PhoneNumber ) & & Equals ( ( PhoneNumber ) obj ) ; } public bool Equals ( PhoneNumber other ) { return this.value == other.value ; } public override int GetHashCode ( ) { return value.GetHashCode ( ) ; } public override string ToString ( ) { return ToString ( PhoneNumberFormat.Separated ) ; } public string ToString ( PhoneNumberFormat format ) { switch ( format ) { case PhoneNumberFormat.Plain : return string.Format ( @ '' { 0 : D3 } { 1 : D3 } { 2 : D4 } { 3 : # } '' , AreaCode , CentralOfficeCode , SubscriberNumber , Extension ) .Trim ( ) ; case PhoneNumberFormat.Separated : return string.Format ( @ '' { 0 : D3 } - { 1 : D3 } - { 2 : D4 } { 3 : # } '' , AreaCode , CentralOfficeCode , SubscriberNumber , Extension ) .Trim ( ) ; default : throw new ArgumentOutOfRangeException ( `` format '' ) ; } } public ulong ToUInt64 ( ) { return value ; } public static PhoneNumber Parse ( string value ) { var result = default ( PhoneNumber ) ; if ( ! TryParse ( value , out result ) ) { throw new FormatException ( string.Format ( @ '' The string `` '' { 0 } '' '' could not be parsed as a phone number . `` , value ) ) ; } return result ; } public static bool TryParse ( string value , out PhoneNumber result ) { result = default ( PhoneNumber ) ; if ( string.IsNullOrEmpty ( value ) ) { return false ; } var index = 0 ; var numericPieces = new char [ value.Length ] ; foreach ( var c in value ) { if ( char.IsNumber ( c ) ) { numericPieces [ index++ ] = c ; } } if ( index < 9 ) { return false ; } var numericString = new string ( numericPieces ) ; var areaCode = int.Parse ( numericString.Substring ( 0 , 3 ) ) ; var centralOfficeCode = int.Parse ( numericString.Substring ( 3 , 3 ) ) ; var subscriberNumber = int.Parse ( numericString.Substring ( 6 , 4 ) ) ; var extension = 0 ; if ( numericString.Length > 10 ) { extension = int.Parse ( numericString.Substring ( 10 ) ) ; } result = new PhoneNumber ( areaCode , centralOfficeCode , subscriberNumber , extension , false ) ; return result.value ! = 0 ; } public static bool operator == ( PhoneNumber left , PhoneNumber right ) { return left.Equals ( right ) ; } public static bool operator ! = ( PhoneNumber left , PhoneNumber right ) { return ! left.Equals ( right ) ; } private static int UnmaskAreaCode ( ulong value ) { return ( int ) ( value > > AreaCodeShift ) ; } private static int UnmaskCentralOfficeCode ( ulong value ) { return ( int ) ( ( value > > CentralOfficeCodeShift ) & CentralOfficeCodeMask ) ; } private static int UnmaskSubscriberNumber ( ulong value ) { return ( int ) ( ( value > > SubscriberNumberShift ) & SubscriberNumberMask ) ; } private static int UnmaskExtension ( ulong value ) { return ( int ) ( value & ExtensionMask ) ; } } public enum PhoneNumberFormat { Plain , Separated }",Should this immutable struct be a mutable class ? "C_sharp : I seem to be getting an odd value.How do I get the number of rows in my array : The output should be 2 . double [ , ] lookup = { { 1,2,3 } , { 4,5,6 } } ;","double [ , ] type , how to get the # of rows ?" "C_sharp : There are a lot of questions on SO about static vs dynamic typing , but I have n't found a lot about a language having both . Let me explain.It seems that dynamically typed languages have an edge when it comes to rapid prototyping , e.g . Python or Perl , while statically typed languages ( like C++ , OCaml ) allow for more compile-time checks and optimizations.I 'm wondering if there is a language that would allow both : first , rapidly prototype with dynamic typing , generic ( i.e . accepting any type ) print functions for easy debugging and REPL , and adaptation to changing design choicesthen , change a few things and compile the code into a library , with static typing for more safety tests and best performance . The things one changes to allow static typing could be for instance : declaring variables ( but not annotating everything , thanks to type inference ) , adding a compiler switch , using specific functions instead of generic ones , etc.In C # the default is static typing , but you can write : in which case fooVar is dynamically typed.It seems that OCaml with http : //www.lexifi.com/blog/runtime-types also offer something like this.Please no subjective advice about which language is best , only objective features ! dynamic fooVar = new FooClass ( ) ;",Is there a language that allows both static and dynamic typing ? "C_sharp : I have an observable sequence . When the first element is inserted , I would like to start a timer and batch subsequent inserted elements during the timespan of the timer . Then , the timer would n't start again until another element is inserted in the sequence.So something like this : would produce : I tried with Observable.Buffer ( ) and a timespan but from my experimentation , I can see that the timer is started as soon as we subscribe to the observable sequence and is restarted as soon as the previous timer is completed.So having the same sequence as the previous example and using the Buffer ( ) with a timespan , I would have something like this : which would produce this : Here is how I tested this behavior with the Buffer : With the output : Anyone has an idea on how to do this ? Thanks in advance ! -- -- -- -- |=====timespan====| -- -- -- -- -- -- -- -|=====timespan====| -- -- -- -- -- -- -- > 1 2 3 4 5 6 7 8 [ 1,2,3,4,5 ] , [ 6,7,8 ] |=====timespan====|=====timespan====|=====timespan====|=====timespan====| -- > 1 2 3 4 5 6 7 8 [ 1,2,3,4 ] , [ 5 ] , [ 6,7 ] , [ 8 ] var source = Observable.Concat ( Observable.Timer ( TimeSpan.FromSeconds ( 6 ) ) .Select ( o = > 1 ) , Observable.Timer ( TimeSpan.FromSeconds ( 1 ) ) .Select ( o = > 2 ) , Observable.Timer ( TimeSpan.FromSeconds ( 3 ) ) .Select ( o = > 3 ) , Observable.Never < int > ( ) ) ; Console.WriteLine ( `` { 0 } = > Started '' , DateTime.Now ) ; source.Buffer ( TimeSpan.FromSeconds ( 4 ) ) .Subscribe ( i = > Console.WriteLine ( `` { 0 } = > [ { 1 } ] '' , DateTime.Now , string.Join ( `` , '' , i ) ) ) ; 4/24/2015 7:01:09 PM = > Started4/24/2015 7:01:13 PM = > [ ] 4/24/2015 7:01:17 PM = > [ 1,2 ] 4/24/2015 7:01:21 PM = > [ 3 ] 4/24/2015 7:01:25 PM = > [ ] 4/24/2015 7:01:29 PM = > [ ] 4/24/2015 7:01:33 PM = > [ ]",RX - Group/Batch bursts of elements in an observable sequence "C_sharp : I 'm working in C # 4.0 ( winforms ) , debugging an application with 10+ threads . While debugging , there is a drop down to select which thread I should be debugging ( only accessible during a breakpoint ) .These show up as `` Win32 Thread '' , `` Worker Thread '' , `` RPC Callback Thread '' , etc ... I 'd love to name them from within my code . I 'm running all my threads via background workers . Edit : my solution . This may not work 100 % of the time , but it does exactly what it needs to . If the labels are wrong in some case , thats OK in the context I 'm working with.At every backgroundworker 's *_dowork event , I put the following line of code in : Which is ... ReportData.TrySetCurrentThreadName ( String.Format ( `` { 0 } . { 1 } '' , MethodBase.GetCurrentMethod ( ) .DeclaringType , MethodBase.GetCurrentMethod ( ) .Name ) ) ; public static void TrySetCurrentThreadName ( String threadName ) { if ( System.Threading.Thread.CurrentThread.Name == null ) { System.Threading.Thread.CurrentThread.Name = threadName ; } }",Is it possible to name a thread in the Visual Studio debugger ? "C_sharp : I have a series of lists : I also have a series of values I 'm looking for in a property of foo : I 'm catching the references to all the foo'ses in which a a given property ( say , bar ) has a value contained in latter list . I 'm doing it like this : I need every foo that has matched the filtering function in a single IEnumerable < foo > so that I can call a method in all of them in one go , like this : So my question is ... Is there a way to gather every foo in a single collection without having to resort to something like : I mean , is there some more elegant way to do something like this with Linq ? I 'm looking for something like : Or even better : I do n't want to modify the original lists of foo because I need them as they are for another operation later on in the code . List < foo > spamSpamAndSpam ; List < foo > spamSpamSpamSausageEggsAndSpam ; List < foo > spamSpamSpamSausageEggsBaconAndSpam ; List < foo > spamSpamSpamSpamSpamWithoutSpam ; List < foo > spamSpamSpamSpamSpamSpamSpamSpamSpamLovelySpamWonderfulSpam ; List < string > Brian= new List < string > ( ) ; Brian.Add ( `` Always '' ) ; Brian.Add ( `` Look '' ) ; Brian.Add ( `` On '' ) ; Brian.Add ( `` The '' ) ; Brian.Add ( `` Bright '' ) ; Brian.Add ( `` Side '' ) ; Brian.Add ( `` Of '' ) ; Brian.Add ( `` Life '' ) ; func < foo , bool > deadParrot = x = > Brian.Contains ( x.bar ) ; IEnumerable < foo > okLumberjacks = spamSpamAndSpam.Where ( deadParrot ) ; okLumberjacks = okLumberjacks.Concat ( spamSpamSpamSpamSausageEggsAndSpam.Where ( deadParrot ) ) ; // And so on , concatenating the results of Where ( ) from every list of < foo > . foreach ( foo incontinentRunner in okLumberjacks ) { incontinentRunner.SillyWalk ( ) ; } ni = ni.Concat ( someList.Where ( filter ) ) ; okLumberjacks = spamSpamAndSpam . And ( spamSpamSpamSausageEggsAndSpam ) . And ( spamSpamSpamSausageEggsBaconAndSpam ) /* etc */ .Where ( deadParrot ) ; okLumberjacks = spanishInquisition.Where ( deadParrot ) ; // Where the type of spanishInquisition is List < List < foo > > .",Query multiple lists in one go "C_sharp : i am creating a postgreSQL database reader which also includes a method for a user to type their own query . i want to protect the database by checking if the typed query contains any modifying code . this is my check : is this the right method to check for a edit-safe query or is there an other , more reliable way to achieve this ? i know about granting rights to users but that is not working because i do n't have a super-user account . private bool chech_unwanted_text ( string query ) { if ( query.Contains ( `` DELETE '' ) || query.Contains ( `` delete '' ) || query.Contains ( `` CREATE '' ) || query.Contains ( `` create '' ) || query.Contains ( `` COPY '' ) || query.Contains ( `` copy '' ) || query.Contains ( `` INSERT '' ) || query.Contains ( `` insert '' ) || query.Contains ( `` DROP '' ) || query.Contains ( `` drop '' ) || query.Contains ( `` UPDATE '' ) || query.Contains ( `` update '' ) || query.Contains ( `` ALTER '' ) || query.Contains ( `` alter '' ) ) { return false ; } else return true ; }",check for read only query string "C_sharp : I am facing this problem . I have a stored procedure which returns 6 rows when I execute it.But when I am retrieving the rows in my app by using ExecuteReader , it only returns only 5 rows . Why is it losing a row ? ? My stored procedure consists of 5 union statements which are getting filled from a single table : dbase is my database object . And cmd is the SqlCommand used to call the stored procedure.UserID is parameter is passingStored procedure code is : dbase.AddInParameter ( cmd , `` @ LoginUser '' , DbType.String , UserID ) ; try { using ( IDataReader dr = dbase.ExecuteReader ( cmd ) ) if ( dr.Read ( ) ) { dt = new DataTable ( `` DashBoard '' ) ; dt.Load ( dr ) ; } } ALTER PROCEDURE [ dbo ] . [ USP_ViewAdminDashBoard ] ( @ LoginUser varchar ( 75 ) ) -- Add the parameters for the stored procedure hereASBEGIN SET NOCOUNT ON ; SET DATEFORMAT DMY ; DECLARE @ LastLoginDate as DateTime Select @ LastLoginDate = dbo.UDF_GetLastLoginByUser ( @ LoginUser ) Select 'Last Login Date ' , convert ( varchar ( 12 ) , @ LastLoginDate,105 ) Union Select 'Nos . Records pending for Upload ' as Title , convert ( varchar ( 5 ) , COUNT ( s.BatchID ) ) Total from dbo.BREGISTRATIONENTRY s , Dbo.TBL_iBATCH B where B.BatchID = s.BatchID And b.Forwarded = 0 and b.isBatchClosed = 1END",Why does IDataReader lose a row ? "C_sharp : Suppose I have created a wrapper class like the following : The idea here is that the innerFoo might wrap data-access methods or something similarly expensive , and I only want its GetBar and GetBaz methods to be invoked once . So I want to create another wrapper around it , which will save the values obtained on the first run.It 's simple enough to do this , of course : But it gets pretty repetitive if I 'm doing this with 10 different properties and 30 different wrappers . So I figured , hey , let 's make this generic : Which almost gets me where I want , but not quite , because you ca n't ref an auto-property ( or any property at all ) . In other words , I ca n't write this : Instead , I 'd have to change Bar to have an explicit backing field and write explicit getters and setters . Which is fine , except for the fact that I end up writing even more redundant code than I was writing in the first place.Then I considered the possibility of using expression trees : This plays nice with refactoring - it 'll work great if I do this : But it 's not actually safe , because someone less clever ( i.e . myself in 3 days from now when I inevitably forget how this is implemented internally ) could decide to write this instead : Which is either going to crash or result in unexpected/undefined behaviour , depending on how defensively I write the LazyLoad method . So I do n't really like this approach either , because it leads to the possibility of runtime errors which would have been prevented in the first attempt . It also relies on Reflection , which feels a little dirty here , even though this code is admittedly not performance-sensitive.Now I could also decide to go all-out and use DynamicProxy to do method interception and not have to write any code , and in fact I already do this in some applications . But this code is residing in a core library which many other assemblies depend on , and it seems horribly wrong to be introducing this kind of complexity at such a low level . Separating the interceptor-based implementation from the IFoo interface by putting it into its own assembly does n't really help ; the fact is that this very class is still going to be used all over the place , must be used , so this is n't one of those problems that could be trivially solved with a little DI magic.The last option I 've already thought of would be to have a method like : This option is very `` meh '' as well - it avoids Reflection but is still error-prone , and it does n't really reduce the repetition that much . It 's almost as bad as having to write explicit getters and setters for each property.Maybe I 'm just being incredibly nit-picky , but this application is still in its early stages , and it 's going to grow substantially over time , and I really want to keep the code squeaky-clean.Bottom line : I 'm at an impasse , looking for other ideas.Question : Is there any way to clean up the lazy-loading code at the top , such that the implementation will : Guarantee compile-time safety , like the ref version ; Actually reduce the amount of code repetition , like the Expression version ; andNot take on any significant additional dependencies ? In other words , is there a way to do this just using regular C # language features and possibly a few small helper classes ? Or am I just going to have to accept that there 's a trade-off here and strike one of the above requirements from the list ? public class Foo : IFoo { private readonly IFoo innerFoo ; public Foo ( IFoo innerFoo ) { this.innerFoo = innerFoo ; } public int ? Bar { get ; set ; } public int ? Baz { get ; set ; } } int IFoo.GetBar ( ) { if ( ( Bar == null ) & & ( innerFoo ! = null ) ) Bar = innerFoo.GetBar ( ) ; return Bar ? ? 0 ; } int IFoo.GetBaz ( ) { if ( ( Baz == null ) & & ( innerFoo ! = null ) ) Baz = innerFoo.GetBaz ( ) ; return Baz ? ? 0 ; } T LazyLoad < T > ( ref T prop , Func < IFoo , T > loader ) { if ( ( prop == null ) & & ( innerFoo ! = null ) ) prop = loader ( innerFoo ) ; return prop ; } int IFoo.GetBar ( ) { return LazyLoad ( ref Bar , f = > f.GetBar ( ) ) ; // < -- - Wo n't compile } T LazyLoad < T > ( Expression < Func < T > > propExpr , Func < IFoo , T > loader ) { var memberExpression = propExpr.Body as MemberExpression ; if ( memberExpression ! = null ) { // Use Reflection to inspect/set the property } } return LazyLoad ( f = > f.Bar , f = > f.GetBar ( ) ) ; return LazyLoad ( f = > 3 , f = > f.GetBar ( ) ) ; T LazyLoad < T > ( Func < T > getter , Action < T > setter , Func < IFoo , T > loader ) { ... }","Approaches for generic , compile-time safe lazy-load methods" "C_sharp : My simplified LINQ Join plus Where of two tables looks like this : Alternatively I could have used the following syntax that I hope to be equivalent : One difference that occurs to me and that I wonder about is the order of commands . In the lambda-syntax join I add the foo.Year property to my anonymous return type just so I can filter after , while in the other query I can still use foo ( and bar if I wanted to ) in the where clause . I do n't need to add the field foo.Year to my return type here if I do n't want or need to.Unfortunately I do n't have ReSharper or anything similar that could translate the lower statement to a lambda one so that I could compare.What I could in fact do ( and make the upper statement more similar in structure to the lower one ) is add the following line between Where ( .. ) and ToList ( ) in the first one : But does n't this just add `` one more '' anonymous type creation compared to the 2nd statement , or am I mistaken here ? In short : What 's the equivalent Join syntax to the 2nd statement ? Or is the 1st one plus the added Select really equivalent , that is , does the joinQuery internally produce the same code ? var join = context.Foo .Join ( context.Bar , foo = > new { foo.Year , foo.Month } , bar = > new { bar.Year , bar.Month } , ( foo , bar ) = > new { foo.Name , bar.Owner , foo.Year } ) .Where ( anon = > anon.Year == 2015 ) .ToList ( ) ; var joinQuery = from foo in context.Foo join bar in context.Bar on new { foo.Year , foo.Month } equals new { bar.Year , bar.Month } where foo.Year == 2015 select new { foo.Name , bar.Owner } ; var join = joinQuery.ToList ( ) ; .Select ( anon = > new { /* the properties I want */ } )",Equivalence of query and method ( lambda ) syntax of a Join with Where clause "C_sharp : I made an ActionFilterAttribute that has the OnActionExecuted method implemented . That means , it runs after the Action method.But , in certain condition , I want the OnActionExecuted to not be executed.How do I , from the Action method , prevent the ActionFilter from being executed ? For now , I have made this : On the Action method : And on the ActionFilter.OnActionExecuted ( ) : But I think that may exist a more elegant approach . RouteData.Values.Add ( `` CancelActionFilter '' , true ) ; if ( filterContext.RouteData.Values [ `` CancelActionFilter '' ] ! = null ) { return ; }",Skip OnActionExecuted execution "C_sharp : i use generic properties on my project , but i dont know , is there any disadvantage use them , please tell me a scenario , they have a disadvantage ? my part of code below . public class GenericResult < T > { public T Data { get ; set ; } public bool IsSuccess { get ; set ; } public string Message { get ; set ; } } public GenericResult < int > AddCategory ( TCategory tCategory ) { GenericResult < int > result = new GenericResult < int > ( ) ; //business logic validation , dont make sense , only example : ) if ( tCategory.Name.Lenght > 100 ) { result.IsSuccess = false ; result.Message = `` Category Name length is too long '' ; result.Data = 0 ; } //handle .net runtime error//may be database is not aviable . try { result.Data = this.catalogRepository.AddCategory ( tCategory ) ; result.IsSuccess = true ; } catch ( Exception ex ) { result.Data = 0 ; result.IsSuccess = false ; result.Message = ex.Message ; } return result ; } public GenericResult < IEnumerable < TCategory > > GetCategoryHierarchy ( TCategory parentCategory ) { GenericResult < IEnumerable < TCategory > > result = new GenericResult < IEnumerable < TCategory > > ( ) ; try { IEnumerable < TCategory > allCategories = catalogRepository.GetAllCategories ( ) ; result.Data = GetCategoryHierarchy ( allCategories , parentCategory ) ; result.IsSuccess = true ; } catch ( Exception ex ) { result.IsSuccess = false ; result.Data = null ; result.Message = ex.Message ; } return result ; }",Generic property disadvantages ? "C_sharp : I know that there is a similar question here , but I would like to see an example , which clearly shows , what you can not do with interface and can with Type ClassFor comparison I 'll give you an example code : C # code : Correct my example , if not correctly understood class Eq a where ( == ) : : a - > a - > Boolinstance Eq Integer where x == y = x ` integerEq ` y interface Eq < T > { bool Equal ( T elem ) ; } public class Integer : Eq < int > { public bool Equal ( int elem ) { return _elem == elem ; } }",Difference between C # interface and Haskell Type Class C_sharp : Simplified situationWhy it 's impossible to create instance of A in class B using class A protected constructor ? In my mind protected constructor is like protected method so it should be possible to run it in subclass . public class A { protected A ( ) { } protected A Make ( ) { return new A ( ) ; } } public class B : A { A a = new A ( ) ; //inaccessible due to protection level B b = new B ( ) ; private B ( ) { A c = new A ( ) ; //inaccessible due to protection level a = new A ( ) ; //inaccessible due to protection level a = Make ( ) ; } },Instance subclass field using parent protected constructor "C_sharp : Say I have a simple array : Is this as performant : as this ? Will Last ( ) enumerate over the entire array even when it can make the above optimization ? If I passed some other IEnumerable ( say one that was yielded ) , Last ( ) would have to enumerate the sequence . I prefer using Last ( ) , because code looks cleaner , but I would not make a sacrifice if it enumerates the sequence . double [ ] myDoubleArray = new double [ ] { 0 , 1 , 2 , 3 , 4 , 5 } ; double last = myDoubleArray.Last ( ) ; double last = myDoubleArray [ myDoubleArray.Length - 1 ] ;",Enumerable.Last < T > ( ) and C # arrays "C_sharp : I was having a look at the section on memory barriers as described in http : //www.albahari.com/threading/part4.aspxand attempted to make an async/await version of the example provided under 'Do We Really Need Locks and Barriers ? ' : When run under release mode without debugging , the program will never finish as per the original threading example it 's based off.However , I was under the impression with async/await because of the way the context is saved it would prevent these kinds of issues . Or do all thread safety rules still apply when using async/await ? public class Program { static void Main ( string [ ] args ) { TestAsync ( ) ; Console.ReadKey ( true ) ; } private static async void TestAsync ( ) { bool complete = false ; Func < Task > testFunc = async ( ) = > { await Task.Delay ( 1000 ) ; bool toggle = false ; while ( ! complete ) toggle = ! toggle ; } ; var task = testFunc ( ) ; Thread.Sleep ( 2000 ) ; complete = true ; await task ; Console.WriteLine ( `` Done '' ) ; } }",Thread safety on async/await with memory caching "C_sharp : I wrote a application in C # that uses System.IO.GetDirectoires ( ) and System.IO.GetFiles ( ) I now have to convert that to use SFTP . I have experience with PutFiles and GetFiles of WinSCP .NET assembly , but I can not figure out how to get a list of directories . There is a GetFiles in the winscp.exe that I can use for the files but there is no way to get the directories as far as I can tell . Does anyone have a way to do this or is there a library that is easier to work with . // Setup session optionsSessionOptions sessionOptions = new SessionOptions { Protocol = Protocol.Sftp , HostName = `` example.com '' , UserName = `` user '' , Password = `` mypassword '' , SshHostKeyFingerprint = `` ssh-rsa 2048 xx : xx : xx : xx : xx : xx : xx : xx : xx : xx : xx : xx : xx : xx : xx : xx '' } ; using ( Session session = new Session ( ) ) { // Connect session.Open ( sessionOptions ) ; }",WinSCP .NET assembly : How to download directories "C_sharp : the above one is my C # code.what I am trying to achive is to use my own column name , not the column name in the dB.But when i run the code , it displays my custom column and the column name from the db at the same time ( cascaded name ) private void ViewWinLoaded ( object sender , RoutedEventArgs e ) { var stud = from s in data.Students select s ; Student [ ] st=stud.ToArray < Student > ( ) ; datagrid.ItemsSource = st ; } < DataGrid x : Name= '' datagrid '' HorizontalAlignment= '' Left '' Height= '' 232 '' VerticalAlignment= '' Top '' Width= '' 461 '' > < DataGrid.Columns > < DataGridTextColumn Binding= '' { Binding Path=StudentID } '' ClipboardContentBinding= '' { x : Null } '' Header= '' StudentID '' / > < DataGridTextColumn Binding= '' { Binding Path=FirstName } '' ClipboardContentBinding= '' { x : Null } '' Header= '' First Name '' / > < DataGridTextColumn Binding= '' { Binding Path=LastName } '' ClipboardContentBinding= '' { x : Null } '' Header= '' Last Name '' / > < DataGridTextColumn Binding= '' { Binding Path=Gender } '' ClipboardContentBinding= '' { x : Null } '' Header= '' Gender '' / > < DataGridTextColumn Binding= '' { Binding Path=GPA } '' ClipboardContentBinding= '' { x : Null } '' Header= '' GPA '' / > < /DataGrid.Columns > < /DataGrid >",how can i correct wpf datagrid column name redundancy in visual studio 2012 "C_sharp : I use visual studio with Unity . The autocomplete function that visual studio has built in , in conjunction with Tools for Unity , makes the autocomplete , especially with method headers , way too aggressive . For instance , when I type void OnCollisionEnter ( I am given This is a problem because I now have to remove the parenthesis and rename the parameter , when before I would not have to do either . It 's a small thing , but it is extremely aggravating . Is there any way to fix this ? void OnCollisionEnter ( Collision collision ) { } ( )",Visual Studio Autocomplete Too Aggressive With Unity "C_sharp : I have defined the following DataContract which implements IDisposable : And I call the following service method passing an instance of the above data contract : In the implementation of BeginUpload , I simply save metadata in a dictionary as : My question is , immediately after returning from this method , why Dispose ( ) is called even though I 've saved the instance in the dictionary _Dict ? I have verified that Dispose ( ) method is called on the same instance which I have saved in my dictionary , as _Disposed becomes true for the saved object , i.e _Dict [ sessionId ] ._Disposed becomes true ! The service behavior of my service is set as : [ DataContract ] public class RegularFileMetadata : FileMetadataBase , IDisposable { bool _Disposed = false ; //note this ! // ... protected virtual void Dispose ( bool disposing ) { if ( ! _Disposed ) { // ... _Disposed = true ; //note this too ! } } public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } } [ OperationContract ] [ ServiceKnownType ( typeof ( RegularFileMetadata ) ) ] Guid BeginUpload ( FileMetadataBase metadata ) ; Dictionary < Guid , RegularFileMetadata > _Dict ; public Guid BeginUpload ( FileMetadataBase fileMetadata ) { // ... var metadata = fileMetadata as RegularFileMetadata ; Guid sessionId = Guid.NewGuid ( ) ; _Dict.Add ( sessionId , metadata ) ; //metadata SAVED ! return sessionId ; } [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.Single ) ]",Why Dispose is being called on DataContract even though the service still refers to it ? "C_sharp : I wrote my own class which converts C # standard primitives into byte arrays . Later on , I took a look at the BitConverter class source , to see how pros did it.My code example : BitConverter class code : Why are their functions tagged as unsafe and use fixed operator ? Are such functions error prone even if they use unsafe ? Should I just drop mine and use their implementation ? Which is more efficient ? public static byte [ ] getBytes ( short value ) { byte [ ] bytes = new byte [ 2 ] ; bytes [ 0 ] = ( byte ) ( value > > 8 ) ; bytes [ 1 ] = ( byte ) value ; return bytes ; } public unsafe static byte [ ] GetBytes ( short value ) { byte [ ] bytes = new byte [ 2 ] ; fixed ( byte* b = bytes ) * ( ( short* ) b ) = value ; return bytes ; }",How does the GetBytes function work ? C_sharp : Can I get s value here ? I want to display the matched string . FilePrefixList.Any ( s = > FileName.StartsWith ( s ) ),List.Any get matched String "C_sharp : I 'm attempting to follow the answer at this question My struct looks like this in CMy function looks like this in CMy C # struct looks like thisMy C # function declaration looks like thisI 'm calling C # function like thisI 'm marshaling the returned pointers like thisPrinting the struct alias like this Thanks for staying with me..This is what my output looks like on a console application in C # . You can see the native C dll printing to the console it 's values , but my marshaling is messing up somewhere : I have no clue where this garbage text and offset is coming from.I 'm responsible for the .Net side , other team members can change the native C as needed if required , but native C changes need to be cross-platform OSX/Windows/Linux.Thanks in advance . typedef struct drive_info_t { unsigned char drive_alias [ 32 ] ; } drive_info_t ; unsigned int get_drive_info_list ( drive_info_t **list , unsigned int *item_count ) { //fill list in native C //print out in native C printf ( `` list.alias - % s\r\n '' , list [ i ] - > drive_alias ) ; } [ StructLayout ( LayoutKind.Sequential ) ] public struct drive_info_t { [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 32 ) ] public byte [ ] drive_alias ; } [ DllImport ( `` mydll.dll '' , EntryPoint = `` get_drive_info_list '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern uint GetDriveInfoList ( out System.IntPtr ptr_list_info , out System.IntPtr ptr_count ) ; IntPtr ptr_list_info = IntPtr.Zero ; IntPtr ptr_cnt = IntPtr.Zero ; ret = api.GetDriveInfoList ( out ptr_list_info , out ptr_cnt ) ; nAlloc = ptr_cnt.ToInt32 ( ) ; int szStruct = Marshal.SizeOf ( typeof ( api.drive_info_t ) ) ; api.drive_info_t [ ] localStructs = new api.drive_info_t [ nAlloc ] ; for ( int i = 0 ; i < nAlloc ; i++ ) { localStructs [ i ] = ( api.drive_info_t ) Marshal.PtrToStructure ( ptr_list_info , typeof ( api.drive_info_t ) ) ; ptr_list_info = new IntPtr ( ptr_list_info.ToInt32 ( ) + ( szStruct ) ) ; } for ( uint i = 0 ; i < localStructs.Length ; i++ ) { Console.WriteLine ( `` list.alias - { 0 } '' , System.Text.Encoding.Default.GetString ( localStructs [ i ] .drive_alias ) ) ; } ======================== C values ============================list.alias - drv1list.alias - drv2list.alias - drv3list.alias - drv4======================== C # values ============================list.alias - drv1list.alias - o£Q95drv2list.alias - o£Q95drv3list.alias - o£Q95drv4",PInvoke - Marshal an array of structs from pointer "C_sharp : I have two buttons- Button A & Button B . Both are kept hidden initially . Data is fetched from an Observable Collection OCollection . This is what I am trying to acheive:1 ) Initially , both buttons are hidden . ( Done ) 2 ) On the first click ( clicking any list view item ) , Button A should be made visible . ( Done ) 3 ) On rest of the clicks ( clicking any other listview item , other than the one in which button A has been kept visible ) , Button B should be made visible . And visibility of button A should n't change back to Collapsed.NB : Each Listview Item must contain only one Button ( either Button A or Button B ) .OCollection is set as the ItemSource of a ListView.Each ListView Item is a Grid containing a default image.XAML : To acheive 3 , I am comparing the tag of the grid with the button content . It does n't work because the logic is wrong . Well , how can this be acheived without using code behind . I am following MVVM pattern , so adios to Code behind.A sample would be nice because I am just a beginner.Class : < ListView Name= '' lv '' ItemsSource= '' { Binding OCollection } '' Background= '' Linen '' Grid.ColumnSpan= '' 3 '' > < ListView.ItemTemplate > < DataTemplate > < Grid Background= '' LightGray '' Name= '' buttonGrid '' Tag= '' { Binding dumyString } '' > < i : Interaction.Behaviors > < ic : DataTriggerBehavior Binding= '' { Binding ElementName=lv , Path=SelectedValue.dumyString } '' Value= '' { Binding dumyString } '' ComparisonCondition= '' Equal '' > < ic : ChangePropertyAction TargetObject= '' { Binding ElementName=ButtonA } '' PropertyName= '' Visibility '' Value= '' Visible '' / > < /ic : DataTriggerBehavior > < ic : DataTriggerBehavior Binding= '' { Binding ElementName=lv , Path=SelectedValue.dumyString } '' Value= '' { Binding dumyString } '' ComparisonCondition= '' NotEqual '' > < ic : ChangePropertyAction TargetObject= '' { Binding ElementName=ButtonA } '' PropertyName= '' Visibility '' Value= '' Collapsed '' / > < /ic : DataTriggerBehavior > < ic : DataTriggerBehavior Binding= '' { Binding ElementName=lv , Path=buttonGrid.Tag } '' Value= '' { Binding dumyString } '' ComparisonCondition= '' Equal '' > < ic : ChangePropertyAction TargetObject= '' { Binding ElementName=ButtonB } '' PropertyName= '' Visibility '' Value= '' Visible '' / > < /ic : DataTriggerBehavior > < /i : Interaction.Behaviors > < Image Source= '' /Assets/Logo.png '' / > < Button Name= '' ButtonA '' Content= '' ButtonA '' Background= '' Black '' Visibility= '' Collapsed '' / > < Button Name= '' ButtonB '' Content= '' ButtonB '' Background= '' Black '' Visibility= '' Collapsed '' / > < /Grid > < /DataTemplate > < /ListView.ItemTemplate > < /ListView > public class dumyClass { public string dumyString { get ; set ; } }","How to toggle the visibility of two buttons using DataTrigger Behavior in XAML , WP 8.1 ?" "C_sharp : I have been looking into MVVM recently and I seem to get the overall idea . There are a couple of niggly bits though that I do not fully understand and was hopping to get some answers here , cheers ! Is it incorrect to use one data model for the whole application . Usually if I am creating a small utility I would have all of the logical data in one class . This means i can have somethings like the following : If it is OK to have one data model is it ok to have more than one model view , say one representing each window or view ( This is how I envision MVVM working ) .Given then above if one has multiple model views it would seem that the model would have to be declared before the first window ( view ) , where should it be declared ? should the model be passed via a reference to subsequent model views ? Would this not be a source of coupling as the window or page ( view ) would need to know about the model to pass it to its model view since the view instantiates the model view.Sorry if this is a lot of questions , I get the idea of MVVM in a single window or page sense but once I add multiple views my system breaks down . I can get it to work with seperate models accessing an outside source to grab its data but if the data needs to persist between views I get lost.Thanks to all that take the time to respond ! DataStore myData = new DataStore ;",Some MVVM questions ( WPF C # ) "C_sharp : To mark code as a critical section we do this : Why is it necessary to have an object as a part of the lock syntax ? In other words , why ca n't this work the same : Object lockThis = new Object ( ) ; lock ( lockThis ) { //Critical Section } lock { //Critical Section }",C # `` lock '' keyword : Why is an object necessary for the syntax ? "C_sharp : I 've been reading that exceptions should only be for something `` exceptional '' and not used to control the flow of a program . However , with a CQS implementation , this seems impossible unless I start hacking up the implementation to deal with it . I wanted to show how I implemented this to see if this is something really bad or not . I 'm using decorators so commands can not return anything ( other than Task for async ) , so a ValidationResult is out of the question . Let me know ! This example will use ASP.NET MVCController : ( api ) CommandExceptionDecorator is first in the chain : Validation Decorator : Other decorators exist but are n't important for this question.Example of a Command Handler Validator : ( Each rule is run on its own thread under the covers ) Actual Command Handler : When an exception is thrown for broken validation rules , the normal flow is broken . Each step assumes that the previous step succeeded . This makes the code very clean as we do n't care about failures during the actual implementation . All commands end up going through this same logic so we only have to write it once . At the very top of MVC , I handle the BrokenRuleException like this : ( I do AJAX calls , not full page posts ) BrokenRule class has the message and a relation field . This relation allows the UI to tie a message to something on the page ( i.e . a div , or form label , etc . ) to display the message in the correct locationIf I do n't do it like this , the controller would have to call a validation class first , look at the results , and then return it as a 400 with the correct response . Most likely , you would have to call a helper class to convert it correctly . However , then the controller would end up looking like this or something similar : This validation check would need to be repeated on every single command . If it was forgotten , there would be big consequences . With the exception style , the code remains compact and developers do n't have to worry about adding that redundant code everytime.I would really love to get everyones feedback . Thanks ! * Edit *Another possible option would be to have another `` mediator '' for the response itself that could run validation directly first and then continue on : Inside this new ResultMediator class , it would look up the CommandValidator and if there were any validation errors it would simply return BadRequest ( new { BrokenRules = brokenRules } ) and call it good . Is this something that each UI will just have to create and handle ? If there is an exception during this call , however , we 'd have to handle that in this mediator directly . Thoughts ? Edit 2 : Maybe I should explain decorators really quick . For example , I have this CreateCommand ( with a specific namespace in this case ) . There is a CommandHandler that handles this command defined is ICommandHandler . This interface has one method defined as : Each decorator also implements this same interface . Simple Injector allows you to define these new classes , like CommandHandlerExceptionDecorator and CommandHandlerValidationDecorator using that same interface . When the code at the top wants to call the CreateCommandHandler with that CreateCommand , SimpleInjector will first call the last defined decorator ( The ExceptionDecorator in this case ) . This decorator handles all exceptions and logs them for ALL commands since it is defined generically . I only have to write that code once . It then forwards the call to the next decorator . In this case , it could be the ValidationDecorator . This will validated the CreateCommand to make sure it is valid . If it is , it will forward it on to the actual command where it does the creation of the entity . If not , it throws an exception since I ca n't return anything back . CQS states that commands must be void . Task is okay , though , since it is just to implement the async/await style . It is effectively returning nothing . Since I have no way to return broken rules there , I throw an exception . I just wanted to know if this approach was okay since it makes all the code at all the different levels specific to the task ( SRP ) and I only have to write it once across all of the commands now and in the future . Any UI can simply catch any BrokenRuleException that comes out and knows what to do with that data to display it . This can be written generically so we can display any errors for any command as well ( due to the Relation property on the rule ) . That way , we write this all once and are done . The issue , however , is that I keep seeing that User Validation is n't `` exceptional '' , so we should n't throw an exception . The problem with that is it will make my code far more complex and less maintainable if I truly follow that path instead since every command caller has to write the same code to do that . If I only throw one BrokenRuleException for any validation errors , is that still okay ? [ Route ( ApiConstants.ROOT_API_URL_VERSION_1 + `` DigimonWorld2Admin/Digimon/Create '' ) ] public class CreateCommandController : MetalKidApiControllerBase { private readonly IMediator _mediator ; public CreateCommandController ( IMediator mediator ) = > _mediator = mediator ; [ HttpPost ] public async Task Post ( [ FromBody ] CreateCommand command ) = > await _mediator.ExecuteAsync ( command ) ; } public class CommandHandlerExceptionDecorator < TCommand > : ICommandHandler < TCommand > where TCommand : ICommand { private readonly ICommandHandler < TCommand > _commandHandler ; private readonly ILogger _logger ; private readonly IUserContext _userContext ; public CommandHandlerExceptionDecorator ( ICommandHandler < TCommand > commandHandler , ILogger logger , IUserContext userContext ) { Guard.IsNotNull ( commandHandler , nameof ( commandHandler ) ) ; Guard.IsNotNull ( logger , nameof ( logger ) ) ; _commandHandler = commandHandler ; _logger = logger ; _userContext = userContext ; } public async Task ExecuteAsync ( TCommand command , CancellationToken token = default ( CancellationToken ) ) { try { await _commandHandler.ExecuteAsync ( command , token ) .ConfigureAwait ( false ) ; } catch ( BrokenRuleException ) { throw ; // Let caller catch this directly } catch ( UserFriendlyException ex ) { await _logger.LogAsync ( new LogEntry ( LogTypeEnum.Error , _userContext , `` Friendly exception with command : `` + typeof ( TCommand ) .FullName , ex , command ) ) .ConfigureAwait ( false ) ; throw ; // Let caller catch this directly } catch ( NoPermissionException ex ) { await _logger.LogAsync ( new LogEntry ( LogTypeEnum.Error , _userContext , `` No Permission exception with command : `` + typeof ( TCommand ) .FullName , ex , command ) ) .ConfigureAwait ( false ) ; throw new UserFriendlyException ( CommonResource.Error_NoPermission ) ; // Rethrow with a specific message } catch ( ConcurrencyException ex ) { await _logger.LogAsync ( new LogEntry ( LogTypeEnum.Error , _userContext , `` Concurrency error with command : `` + typeof ( TCommand ) .FullName , ex , command ) ) .ConfigureAwait ( false ) ; throw new UserFriendlyException ( CommonResource.Error_Concurrency ) ; // Rethrow with a specific message } catch ( Exception ex ) { await _logger.LogAsync ( new LogEntry ( LogTypeEnum.Error , _userContext , `` Error with command : `` + typeof ( TCommand ) .FullName , ex , command ) ) .ConfigureAwait ( false ) ; throw new UserFriendlyException ( CommonResource.Error_Generic ) ; // Rethrow with a specific message } } } public class CommandHandlerValidatorDecorator < TCommand > : ICommandHandler < TCommand > where TCommand : ICommand { private readonly ICommandHandler < TCommand > _commandHandler ; private readonly IEnumerable < ICommandValidator < TCommand > > _validators ; public CommandHandlerValidatorDecorator ( ICommandHandler < TCommand > commandHandler , ICollection < ICommandValidator < TCommand > > validators ) { Guard.IsNotNull ( commandHandler , nameof ( commandHandler ) ) ; Guard.IsNotNull ( validators , nameof ( validators ) ) ; _commandHandler = commandHandler ; _validators = validators ; } public async Task ExecuteAsync ( TCommand command , CancellationToken token = default ( CancellationToken ) ) { var brokenRules = ( await Task.WhenAll ( _validators.AsParallel ( ) .Select ( a = > a.ValidateCommandAsync ( command , token ) ) ) .ConfigureAwait ( false ) ) .SelectMany ( a = > a ) .ToList ( ) ; if ( brokenRules.Any ( ) ) { throw new BrokenRuleException ( brokenRules ) ; } await _commandHandler.ExecuteAsync ( command , token ) .ConfigureAwait ( false ) ; } } public class CreateCommandValidator : CommandValidatorBase < CreateCommand > { private readonly IDigimonWorld2ContextFactory _contextFactory ; public CreateCommandValidator ( IDigimonWorld2ContextFactory contextFactory ) { _contextFactory = contextFactory ; } protected override void CreateRules ( CancellationToken token = default ( CancellationToken ) ) { AddRule ( ( ) = > Validate.If ( string.IsNullOrEmpty ( Command.Name ) ) ? .CreateRequiredBrokenRule ( DigimonResources.Digipedia_CreateCommnad_Name , nameof ( Command.Name ) ) ) ; AddRule ( ( ) = > Validate.If ( Command.DigimonTypeId == 0 ) ? .CreateRequiredBrokenRule ( DigimonResources.Digipedia_CreateCommnad_DigimonTypeId , nameof ( Command.DigimonTypeId ) ) ) ; AddRule ( ( ) = > Validate.If ( Command.RankId == 0 ) ? .CreateRequiredBrokenRule ( DigimonResources.Digipedia_CreateCommnad_RankId , nameof ( Command.RankId ) ) ) ; AddRule ( async ( ) = > { using ( var context = _contextFactory.Create ( false ) ) { return Validate.If ( ! string.IsNullOrEmpty ( Command.Name ) & & await context.Digimons .AnyAsync ( a = > a.Name == Command.Name , token ) .ConfigureAwait ( false ) ) ? .CreateAlreadyInUseBrokenRule ( DigimonResources.Digipedia_CreateCommnad_Name , Command.Name , nameof ( Command.Name ) ) ; } } ) ; } } public class CreateCommandValidatorHandler : ICommandHandler < CreateCommand > { private const int ExpectedChangesCount = 1 ; private readonly IDigimonWorld2ContextFactory _contextFactory ; private readonly IMapper < CreateCommand , DigimonEntity > _mapper ; public CreateCommandValidatorHandler ( IDigimonWorld2ContextFactory contextFactory , IMapper < CreateCommand , DigimonEntity > mapper ) { _contextFactory = contextFactory ; _mapper = mapper ; } public async Task ExecuteAsync ( CreateCommand command , CancellationToken token = default ( CancellationToken ) ) { using ( var context = _contextFactory.Create ( ) ) { var entity = _mapper.Map ( command ) ; context.Digimons.Add ( entity ) ; await context.SaveChangesAsync ( ExpectedChangesCount , token ) .ConfigureAwait ( false ) ; } } } internal static class ErrorConfiguration { public static void Configure ( IApplicationBuilder app , IHostingEnvironment env , ILoggerFactory loggerFactory , IConfigurationRoot configuration ) { loggerFactory.AddConsole ( configuration.GetSection ( `` Logging '' ) ) ; loggerFactory.AddDebug ( ) ; if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; app.UseBrowserLink ( ) ; } else { app.UseExceptionHandler ( `` /Home/Error '' ) ; } app.UseExceptionHandler ( errorApp = > { errorApp.Run ( async context = > { var error = context.Features.Get < IExceptionHandlerFeature > ( ) ? .Error ; context.Response.StatusCode = GetErrorStatus ( error ) ; context.Response.ContentType = `` application/json '' ; var message = GetErrorData ( error ) ; await context.Response.WriteAsync ( message , Encoding.UTF8 ) ; } ) ; } ) ; } private static string GetErrorData ( Exception ex ) { if ( ex is BrokenRuleException brokenRules ) { return JsonConvert.SerializeObject ( new { BrokenRules = brokenRules.BrokenRules } ) ; } if ( ex is UserFriendlyException userFriendly ) { return JsonConvert.SerializeObject ( new { Message = userFriendly.Message } ) ; } return JsonConvert.SerializeObject ( new { Message = MetalKid.Common.CommonResource.Error_Generic } ) ; } private static int GetErrorStatus ( Exception ex ) { if ( ex is BrokenRuleException || ex is UserFriendlyException ) { return ( int ) HttpStatusCode.BadRequest ; } return ( int ) HttpStatusCode.InternalServerError ; } } public class BrokenRule { public string RuleMessage { get ; set ; } public string Relation { get ; set ; } public BrokenRule ( ) { } public BrokenRule ( string ruleMessage , string relation = `` '' ) { Guard.IsNotNullOrWhiteSpace ( ruleMessage , nameof ( ruleMessage ) ) ; RuleMessage = ruleMessage ; Relation = relation ; } } [ Route ( ApiConstants.ROOT_API_URL_VERSION_1 + `` DigimonWorld2Admin/Digimon/Create '' ) ] public class CreateCommandController : MetalKidApiControllerBase { private readonly IMediator _mediator ; private readonly ICreateCommandValidator _validator ; public CreateCommandController ( IMediator mediator , ICreateCommandValidator validator ) { _mediator = mediator ; _validator = validator } [ HttpPost ] public async Task < IHttpResult > Post ( [ FromBody ] CreateCommand command ) { var validationResult = _validator.Validate ( command ) ; if ( validationResult.Errors.Count > 0 ) { return ValidationHelper.Response ( validationResult ) ; } await _mediator.ExecuteAsync ( command ) ; return Ok ( ) ; } } [ Route ( ApiConstants.ROOT_API_URL_VERSION_1 + `` DigimonWorld2Admin/Digimon/Create '' ) ] public class CreateCommandController : MetalKidApiControllerBase { private readonly IResultMediator _mediator ; public CreateCommandController ( IResultMediator mediator ) = > _mediator = mediator ; [ HttpPost ] public async Task < IHttpAction > Post ( [ FromBody ] CreateCommand command ) = > await _mediator.ExecuteAsync ( command ) ; } Task ExecuteAsync ( TCommand , CancellationToken token ) ;",Validation for a CQS system that throws an exception C_sharp : I need some help with adding an Android.Views.ViewGroup to a XAML page.I have a Xamarin project with a solution structure that looks like this : App1/ViewModels/MyPageViewModel.cs/Views/MyPageView.xaml/MyPageView.xaml.csApp1.Android/MainActivity.cs/MainApplication.csApp1.iOSMyAndroidBindingProject/Jars/customViewGroup.aarNote the customViewGroup.aar that I 've added to the solution using a Xamarin Android Binding Library.The AAR file contains an Android.Views.ViewGroup class that I 'd like to show on MyPage.xaml but I have no clue how to do it . I ca n't seem to find a guide or code sample that fits this exact use case ( nor can I find one that involves adding a simple Android.Views.View to a Xamarin XAML page ) .I 've found examples of adding an Android.Views.ViewGroup to a native Android application ( using Java and XML ) but nothing that shows how to add it to a Xamarin XAML page.Please help ! I 'm including some source code so you can see what I 've tried : MyPage.xamlMyPage.xaml.cs < ContentPage xmlns= '' http : //xamarin.com/schemas/2014/forms '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2009/xaml '' x : Class= '' App1.Views.MyPage '' xmlns : vm= '' clr-namespace : App1.ViewModels ; '' xmlns : androidWidget= '' clr-namespace : Com.CustomAAR ; assembly=Com.CustomAAR ; targetPlatform=Android '' xmlns : formsAndroid= '' clr-namespace : Xamarin.Forms ; assembly=Xamarin.Forms.Platform.Android ; targetPlatform=Android '' Title= '' { Binding Title } '' > < ContentPage.Content > < ContentView x : Name= '' contentViewParent '' > < androidWidget : MyCustomViewGroup x : Arguments= '' { x : Static formsandroid : Forms.Context } '' > < /androidWidget : MyCustomViewGroup > < /ContentView > < ! -- < ContentView IsVisible= '' True '' IsEnabled= '' True '' BindingContext= '' { Binding MyCustomViewGroup } '' > < /ContentView > -- > < /ContentPage.Content > < /ContentPage > public partial class MyPage : ContentPage { MyCustomViewGroupModel viewModel ; public MyPage ( ) { InitializeComponent ( ) ; } public MyPage ( MyCustomViewGroupModel viewModel ) { InitializeComponent ( ) ; # if __ANDROID__ NativeViewWrapper wrapper = ( NativeViewWrapper ) contentViewParent.Content ; MyCustomViewGroup myCustomViewGroup = ( MyCustomViewGroup ) wrapper.NativeView ; //myCustomViewGroup = new MyCustomViewGroup ( Android.App.Application.Context ) ; myCustomViewGroup.SomeAction ( `` '' ) ; # endif BindingContext = this.viewModel = viewModel ; } },Adding an `` Android.Views.ViewGroup '' to a Xamarin XAML page "C_sharp : I implemented a Singleton pattern like this : From Googling around for C # Singleton implementations , it does n't seem like this is a common way to do things in C # . I found one similar implementation , but the SingletonHolder class was n't static , and included an explicit ( empty ) static constructor.Is this a valid , lazy , thread-safe way to implement the Singleton pattern ? Or is there something I 'm missing ? public sealed class MyClass { ... public static MyClass Instance { get { return SingletonHolder.instance ; } } ... static class SingletonHolder { public static MyClass instance = new MyClass ( ) ; } }","Is this a valid , lazy , thread-safe Singleton implementation for C # ?" "C_sharp : I 'm looking at this code of the correct way to do a singleton in java : What is an efficient way to implement a singleton pattern in Java ? I 'm a little confused , how do you add a method to a enumeration ? And the enumeration in the code above , does n't even make sense to me , you have the symbol : how is that a correct line ? I 'm coming from c # , and this syntax got me curious and I 'm hoping someone can explain or make sense of the above.I guess it means java has a more purer idea of an enumeration as it can have behaviour ? public enum Elvis { INSTANCE ; private final String [ ] favoriteSongs = { `` Hound Dog '' , `` Heartbreak Hotel '' } ; public void printFavorites ( ) { System.out.println ( Arrays.toString ( favoriteSongs ) ) ; } } INSTANCE ;",Java enumerations support methods ? But not in c # ? "C_sharp : I would like an elegant , efficient means of taking any unsigned integer and converting it into the smallest byte array it will fit into . For example : so that I can write : and foo will be of different lengths depending on the value of bar . How would I do that ? 250 = byte [ 1 ] 2000 = byte [ 2 ] 80000 = byte [ 3 ] var foo = getBytes ( bar ) ;",c # : Convert an int into the smallest byte array it will fit into "C_sharp : I have two items in my class : One is a public property , and the other is a static method that takes a parameter.I really do not understand why Visual Studio 2010 is unable to see the difference between these two items.Could someone explain this one to me ? Here is the code : Here is the error : Error 1 Ambiguity between 'AcpClasses.AcpPackNShip.IsShipped ' and 'AcpClasses.AcpPackNShip.IsShipped ( string ) ' C : \Users\cp-jpool\My Projects\VS\Live\Common\Classes\AcpPackShip.cs 242 20 CoilPC public bool IsShipped { get { # region ' Test Code ' if ( ! String.IsNullOrEmpty ( TrailerNo ) || ( TruckDate ! = Global.NODATE ) ) { return true ; } # endregion return false ; } } public static bool IsShipped ( string boxNumber ) { var array = GetCrate ( boxNumber ) ; if ( array ! = null ) { foreach ( var item in array ) { if ( item.IsShipped ) { return true ; } } } return false ; }",Ambiguity between Static and Instance Code "C_sharp : Please bear with me , I spent 30+ hours trying to get this work - but without success.At the start of my program I load an Assembly ( dll ) in bytearray and delete it afterwards.Later on in the program I create a new Appdomain , load the byte array and enumerate the types.The types get correctly listed : ass.FullName : plugin , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null ... Plugins.Test ... Now I want to create an instance of that type in the new AppDomainThis call results in System.IO.FileNotFoundException and I do n't know why.When I look in ProcessExplorer under .NET Assemblies - > Appdomain : plugintest I see that the assembly is loaded correctly in the new appdomain.I suspect the exception to occur because the assembly is searched again on disk . But why does the program want to load it again ? How can I create an instance in a new appdomain with an assembly loaded from byte array ? _myBytes = File.ReadAllBytes ( @ '' D : \Projects\AppDomainTest\plugin.dll '' ) ; var domain = AppDomain.CreateDomain ( `` plugintest '' , null , null , null , false ) ; domain.Load ( _myBytes ) ; foreach ( var ass in domain.GetAssemblies ( ) ) { Console.WriteLine ( $ '' ass.FullName : { ass.FullName } '' ) ; Console.WriteLine ( string.Join ( Environment.NewLine , ass.GetTypes ( ) .ToList ( ) ) ) ; } domain.CreateInstance ( `` plugin '' , `` Plugins.Test '' ) ;",AppDomain Assembly not found when loaded from byte array "C_sharp : I am creating custom membership provider for my asp.net application . I have also created a separate class `` DBConnect '' that provides database functionality such as Executing SQL statement , Executing SPs , Executing SPs or Query and returning SqlDataReader and so on ... I have created instance of DBConnect class within Session_Start of Global.asax and stored to a session . Later using a static class I am providing the database functionality throughout the application using the same single session . In short I am providing a single point for all database operations from any asp.net page.I know that i can write my own code to connect/disconnect database and execute SPs within from the methods i need to override . Please look at the code below - ... ... MY PROBLEM - Now what i need is to execute the database part within all these overriden methods from the same database point as described on the top . That is i have to pass the instance of DBConnect existing in the session to this class , so that i can access the methods.Could anyone provide solution on this . There might be some better techniques i am not aware of that . The approach i am using might be wrong . Your suggessions are always welcome.Thanks for sharing your valuable time . public class SGI_MembershipProvider : MembershipProvider { public override bool ChangePassword ( string username , string oldPassword , string newPassword ) { if ( ! ValidateUser ( username , oldPassword ) ) return false ; ValidatePasswordEventArgs args = new ValidatePasswordEventArgs ( username , newPassword , true ) ; OnValidatingPassword ( args ) ; if ( args.Cancel ) { if ( args.FailureInformation ! = null ) { throw args.FailureInformation ; } else { throw new Exception ( `` Change password canceled due to new password validation failure . `` ) ; } } ... .. //Database connectivity and code execution to change password. } ... . }",Providing custom database functionality to custom asp.net membership provider "C_sharp : In the following Window I define a trigger for IsMouseOver . The background color is changed correctly , but it has an gradient effect . See the pic below . How to get rid of the effect ? Only Theme.DataGrid.Row.Background.Hover is moved from separate style file to code excerpt below . ViewModel ( note that this uses our own ViewModel-class that i.e raises PropertyChanged events ) < Window x : Class= '' MyCompany.Application.Shared.UI.Dialogs.SomeWindow xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' Background= '' # FFF3F3F7 '' > < Window.Resources > < SolidColorBrush x : Key= '' Theme.DataGrid.Row.BorderBrush '' Color= '' # FFF3F3F7 '' options : Freeze= '' True '' / > < SolidColorBrush x : Key= '' Theme.DataGrid.Row.Background '' Color= '' White '' options : Freeze= '' True '' / > < SolidColorBrush x : Key= '' Theme.DataGrid.Row.Background.Hover '' Color= '' # FFAEAEB6 '' options : Freeze= '' True '' / > < SolidColorBrush x : Key= '' Theme.DataGrid.Row.Background.Active '' Color= '' # FF0D6AA8 '' options : Freeze= '' True '' / > < SolidColorBrush x : Key= '' Theme.DataGrid.Row.Background.HoverSelected '' Color= '' # FF009AD9 '' options : Freeze= '' True '' / > < SolidColorBrush x : Key= '' Theme.DataGrid.Row.Background.Disabled '' Color= '' # FFAEAEB6 '' options : Freeze= '' True '' / > < SolidColorBrush x : Key= '' Theme.DataGrid.Row.Foreground.Selected '' Color= '' White '' options : Freeze= '' True '' / > < Style x : Key= '' GridView.ColumnHeader.Gripper.Style '' TargetType= '' { x : Type Thumb } '' > < Setter Property= '' Width '' Value= '' 8 '' / > < Setter Property= '' Background '' Value= '' Transparent '' / > < Setter Property= '' Cursor '' Value= '' SizeWE '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type Thumb } '' > < Border Background= '' { TemplateBinding Background } '' Padding= '' { TemplateBinding Padding } '' / > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < Style TargetType= '' { x : Type GridViewColumnHeader } '' > < EventSetter Event= '' FrameworkElement.Loaded '' Handler= '' GridViewColumnHeader_Loaded '' / > < Setter Property= '' FontWeight '' Value= '' Bold '' / > < Setter Property= '' BorderBrush '' Value= '' Transparent '' / > < Setter Property= '' BorderThickness '' Value= '' 0 '' / > < Setter Property= '' Background '' Value= '' { StaticResource Theme.DataGrid.ColumnHeader.Background } '' / > < Setter Property= '' Foreground '' Value= '' Black '' / > < Setter Property= '' HorizontalContentAlignment '' Value= '' Left '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' { x : Type GridViewColumnHeader } '' > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' * '' / > < ColumnDefinition Width= '' 1 '' / > < /Grid.ColumnDefinitions > < Border Grid.Column= '' 0 '' x : Name= '' Border '' BorderBrush= '' { TemplateBinding BorderBrush } '' BorderThickness= '' { TemplateBinding BorderThickness } '' Background= '' { TemplateBinding Background } '' > < ContentPresenter Margin= '' { TemplateBinding Padding } '' HorizontalAlignment= '' { TemplateBinding HorizontalContentAlignment } '' VerticalAlignment= '' { TemplateBinding VerticalContentAlignment } '' / > < /Border > < Thumb Grid.Column= '' 1 '' x : Name= '' PART_HeaderGripper '' HorizontalAlignment= '' Right '' Style= '' { DynamicResource Theme.DataGrid.ColumnHeader.Gripper.Style } '' / > < /Grid > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < Style TargetType= '' { x : Type ListView } '' > < Setter Property= '' BorderThickness '' Value= '' { DynamicResource Theme.DataGrid.BorderThickness } '' / > < Setter Property= '' Background '' Value= '' { StaticResource Theme.TreeView.Background } '' / > < /Style > < Style TargetType= '' { x : Type ListViewItem } '' > < Setter Property= '' Background '' Value= '' White '' / > < Setter Property= '' Foreground '' Value= '' { DynamicResource Theme.DataGrid.Row.Foreground } '' / > < Setter Property= '' VerticalAlignment '' Value= '' Stretch '' / > < Setter Property= '' HorizontalAlignment '' Value= '' Stretch '' / > < Setter Property= '' VerticalContentAlignment '' Value= '' Stretch '' / > < Setter Property= '' HorizontalContentAlignment '' Value= '' Stretch '' / > < Setter Property= '' BorderThickness '' Value= '' 0 '' / > < Setter Property= '' BorderBrush '' Value= '' Transparent '' / > < Setter Property= '' Padding '' Value= '' { DynamicResource Theme.DataGrid.Cell.Padding } '' / > < Setter Property= '' Margin '' Value= '' 1 '' / > < Style.Triggers > < Trigger Property= '' IsMouseOver '' Value= '' True '' > < Setter Property= '' Background '' Value= '' { DynamicResource Theme.DataGrid.Row.Background.Hover } '' / > < /Trigger > < Trigger Property= '' IsSelected '' Value= '' True '' > < Setter Property= '' Background '' Value= '' { DynamicResource Theme.DataGrid.Row.Background.Active } '' < Setter Property= '' Foreground '' Value= '' { DynamicResource Theme.DataGrid.Row.Background.Selected } '' / > < /Trigger > < Trigger Property= '' IsEnabled '' Value= '' False '' > < Setter Property= '' Background '' Value= '' { DynamicResource Theme.DataGrid.Row.Background.Disabled } '' / > < /Trigger > < MultiTrigger > < MultiTrigger.Conditions > < Condition Property= '' IsMouseOver '' Value= '' True '' / > < Condition Property= '' IsSelected '' Value= '' True '' / > < /MultiTrigger.Conditions > < Setter Property= '' Background '' Value= '' { DynamicResource Theme.DataGrid.Row.Background.HoverSelected } '' / > < /MultiTrigger > < /Style.Triggers > < /Style > < /Window.Resources > < StackPanel > < CheckBox Content= '' IsGrouped '' IsChecked= '' { Binding IsGrouped } '' / > < ListView Margin= '' 10 '' ItemsSource= '' { Binding Users } '' > < ListView.View > < GridView AllowsColumnReorder= '' False '' > < GridViewColumn Header= '' Name '' DisplayMemberBinding= '' { Binding Name } '' / > < GridViewColumn Header= '' Age '' DisplayMemberBinding= '' { Binding Age } '' / > < GridViewColumn Header= '' Mail '' DisplayMemberBinding= '' { Binding Mail } '' / > < GridViewColumn Header= '' Group '' DisplayMemberBinding= '' { Binding Group } '' / > < /ListView > < /StackPanel > < /Window > namespace MyCompany.Application.Shared.UI.Dialogs { public class User { public string Name { get ; set ; } public int Age { get ; set ; } public string Mail { get ; set ; } public string Group { get ; set ; } } public class SomeWindowViewModel : ViewModel { List < User > items = new List < User > ( ) ; IEnumerable < User > GetUsers ( ) { foreach ( var item in items ) { yield return item ; } } public ICollectionView Users { get ; } private bool _isGrouped = false ; public bool IsGrouped { get { return _isGrouped ; } set { _isGrouped = value ; if ( value ) { Users.GroupDescriptions.Add ( new PropertyGroupDescription ( `` Group '' ) ) ; } else { Users.GroupDescriptions.Clear ( ) ; } } } public SomeWindowViewModel ( ) { items.Add ( new User ( ) { Name = `` John Doe '' , Age = 42 , Mail = `` john @ doe-family.com '' , Group = `` OneGroup1 '' } ) ; items.Add ( new User ( ) { Name = `` Jane Doe '' , Age = 39 , Mail = `` jane @ doe-family.com '' , Group = `` OneGroup1 '' } ) ; items.Add ( new User ( ) { Name = `` Sammy Doe '' , Age = 7 , Mail = `` sammy.doe @ gmail.com '' , Group = `` TwoGroup2 '' } ) ; items.Add ( new User ( ) { Name = `` Pentti Doe '' , Age = 7 , Mail = `` pena.doe @ gmail.com '' , Group = `` TwoGroup2 '' } ) ; Users = CollectionViewSource.GetDefaultView ( GetUsers ( ) ) ; } } }",How to remove gradient effect appearing for IsMouseOver in WPF ListViewItem 's style ? "C_sharp : I have controllers where the paging will be calculated . But I have 13 different controllers . So to write that calculation in every controller will be tedious.this is the comoplete method : But this is the part of calculation : So I try to build a helper method like this : But I get this error : Thank you [ Route ( `` sort/ { SortColumn } / { SortOrder ? } '' , Name = `` Sort-Product '' ) ] [ Route ( `` page/ { Page : int } / { SortColumn } / { SortOrder ? } '' , Name = `` Paging-Product '' ) ] [ Route ( `` search/ { SearchString } '' ) ] [ Route ( `` index '' ) ] public ActionResult Index ( string searchString , string filter , string currentFilter , string sortColumn , string sortOrder , int ? page ) { IOrderedQueryable < Product > entities = ( IOrderedQueryable < Product > ) db.FilteredProducts ; if ( searchString ! = null ) page = 1 ; else searchString = currentFilter ; if ( filter ! = null ) { string [ ] filters = filter.Split ( new char [ ] { ' . ' } ) ; filter = `` '' ; // filter on form if ( filters.Length > 0 & & ! String.IsNullOrEmpty ( filters [ 0 ] ) ) { FormLibraryEntry formEntry = FormLibraryController.GetFormLibraryEntry ( filters [ 0 ] , StateHelper.GetSchema ( ) ) ; if ( formEntry ! = null ) { entities = ( IOrderedQueryable < Product > ) entities.Where ( s = > s.FormName == formEntry.Id ) ; AddFixedNotification ( String.Format ( Resources.Entity.Environment.FilteredByFormMessage , formEntry.Name ) ) ; filter += filters [ 0 ] ; } } // filter on design template if ( filters.Length > 1 & & ! String.IsNullOrEmpty ( filters [ 1 ] ) ) { var designEntry = DesignTemplateController.GetTemplateLibraryEntry ( filters [ 1 ] , StateHelper.GetSchema ( ) ) ; if ( designEntry ! = null ) { entities = ( IOrderedQueryable < Product > ) entities.Where ( s = > s.TemplateName == designEntry.Id ) ; AddFixedNotification ( String.Format ( Resources.Entity.Environment.FilteredByDesignTemplateMessage , designEntry.Name ) ) ; filter += `` . '' + filters [ 1 ] ; } } } if ( ! String.IsNullOrEmpty ( searchString ) ) { entities = ( IOrderedQueryable < Product > ) entities.Where ( s = > s.Name.ToUpper ( ) .Contains ( searchString.ToUpper ( ) ) || ( ! String.IsNullOrEmpty ( s.FormName ) & & s.FormName.ToUpper ( ) .Contains ( searchString.ToUpper ( ) ) ) || ( ! String.IsNullOrEmpty ( s.UrlName ) & & s.UrlName.ToUpper ( ) .Contains ( searchString.ToUpper ( ) ) ) ) ; AddFixedNotification ( String.Format ( Resources.Entity.Environment.FilteredBySearchTermMessage , searchString ) ) ; } switch ( sortColumn ) { case `` id '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.Id ) : entities.OrderBy ( s = > s.Id ) ; break ; case `` name '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.Name ) : entities.OrderBy ( s = > s.Name ) ; break ; case `` enabled '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.IsEnabled ) : entities.OrderBy ( s = > s.IsEnabled ) ; break ; case `` formname '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.FormName ) : entities.OrderBy ( s = > s.FormName ) ; break ; case `` design '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.TemplateName ) : entities.OrderBy ( s = > s.TemplateName ) ; break ; case `` urlname '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.UrlName ) : entities.OrderBy ( s = > s.UrlName ) ; break ; case `` forms '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.SubmittedForms.Count ( ) ) : entities.OrderBy ( s = > s.SubmittedForms.Count ( ) ) ; break ; case `` modified '' : entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.ModificationDate ) : entities.OrderBy ( s = > s.ModificationDate ) ; break ; default : sortColumn = `` name '' ; sortOrder = `` '' ; entities = ( sortOrder == `` desc '' ) ? entities.OrderByDescending ( s = > s.Name ) : entities.OrderBy ( s = > s.Name ) ; break ; } ViewBag.SortColumn = sortColumn ; ViewBag.SortOrder = sortOrder == `` desc '' ? `` desc '' : `` '' ; ViewBag.SearchString = searchString ; ViewBag.Filter = filter ; int pageSize = StateHelper.GetPageSize ( ) ; int pageNumber = StateHelper.HasPageSizeChanged ? 1 : ( page ? ? 1 ) ; object selectionProduct = ModelHelper.GetSelectedModelId ( `` Product '' ) ; if ( selectionProduct ! = null ) { IEnumerable < IEnumerable < Product > > pp = entities.Partition ( pageSize ) ; int calculatedPage = 0 ; bool found = false ; foreach ( var item in pp ) { calculatedPage++ ; IEnumerable < Product > inner = item as IEnumerable < Product > ; foreach ( var product in inner ) { if ( product.Id == ( int ) selectionProduct ) { found = true ; ViewBag.selectedRowProduct = product.Id ; break ; } } if ( found ) break ; } if ( found ) pageNumber = calculatedPage ; } return View ( entities.ToPagedList ( pageNumber , pageSize ) ) ; } object selectionProduct = ModelHelper.GetSelectedModelId ( `` Product '' ) ; if ( selectionProduct ! = null ) { IEnumerable < IEnumerable < Product > > pp = entities.Partition ( pageSize ) ; int calculatedPage = 0 ; bool found = false ; foreach ( var item in pp ) { calculatedPage++ ; IEnumerable < Product > inner = item as IEnumerable < Product > ; foreach ( var product in inner ) { if ( product.Id == ( int ) selectionProduct ) { found = true ; ViewBag.selectedRowProduct = product.Id ; break ; } } if ( found ) break ; } if ( found ) pageNumber = calculatedPage ; } public static bool FindPage ( Type T , object modelId , IEnumerable < Type > entities , int pageSize , int calculatedPage , int ? id ) { if ( modelId ! = null ) { calculatedPage = 0 ; IEnumerable < IEnumerable < T > > pp = entities.Partition ( pageSize ) ; int page = 0 ; bool found = false ; foreach ( var item in pp ) { page++ ; IEnumerable < Type > inner = item as IEnumerable < Type > ; foreach ( var product in inner ) { if ( id == ( int ) modelId ) { found = true ; break ; } } if ( found ) break ; } if ( found ) calculatedPage = page ; else calculatedPage = 0 ; return found ; } return false ; } The type or namespace name 'T ' could not be found ( are you missing a using directive or an assembly reference ? )",write generic method for paging "C_sharp : ScenarioI 've configured my MVC application to use Forms authentication in the traditional fashion.However , I allow the client to choose how his web application authenticates ( URL Token / Cookie ) , as well as how long his application session should last before expiring ( Timeout ) QuestionIs there a way for me to do this via code ? I 've only seen implementations of this via web.config ? I 'd like to read the settings from the database and apply them in Global.asax - > OnApplicationStart ( ) < authentication mode= '' Forms '' > < forms cookieless= '' UseCookies '' slidingExpiration= '' true '' timeout= '' 1 '' > < /forms > < /authentication >",Configure Forms Authentication Without Web.Config "C_sharp : I wanted to test out the new nullable reference types feature in C # 8.0.I started a new project targeting .NET Core 3.0 , enabled nullable reference types in the .csproj file , and started coding . I created a simple list that takes a string [ ] and returns the string in that array that equals abc . Now , because I am not certain that abc actually exists in the array , I use FirstOrDefault ( ) , which should default to null if a match is not found.My method returns string , which should now be the non-nullable type . Since FirstOrDefault ( ) may return null , I would expect the above method to yield a warning when returning the maybe null arg variable . It does not.Looking at the the signature for FirstOrDefault ( ) in Visual Studio , it is clear why : The method returns a string , not the nullable equivalent string ? I would expect.Using the method body below does yield the warning I expected : Do system libraries ( in this example System.Linq ) really not expose nullability information when targeting .NET Core 3.0 ? using System ; using System.Linq ; public string FindArgument ( string [ ] args ) { var arg = args.FirstOrDefault ( x = > x == `` abc '' ) ; return arg ; } var arg = args.Contains ( `` abc '' ) ? `` abc '' : null ; return arg ;",Nullable reference type information not exposed from FirstOrDefault "C_sharp : I have the following simple code : From what I read when closures are involved , a new type is created by the compiler so it can store the captured variable and maintain a reference to it . However , when I run the following code , both printed lines show 3 . I was expecting 0 and 3 , because the anonymous method has its own variable in the generated class by the compiler . So why does it also modify the outside variable ? static void Main ( string [ ] args ) { int j = 0 ; Func < int > f = ( ) = > { for ( int i = 0 ; i < 3 ; i++ ) { j += i ; } return j ; } ; int myStr = f ( ) ; Console.WriteLine ( myStr ) ; Console.WriteLine ( j ) ; Console.Read ( ) ; }",Closure captured variable modifies the original as well "C_sharp : I 'm using the Permissions Plugin to request fine location permission on Android ; however , every time I call CheckPermissionsAsync , I get a response of Denied . Here 's the code that I 'm using : This is running on the emulator and , to my knowledge , I have n't yet managed to execute the RequestPermissionsAsync call.Is this expected behaviour ? If so , how do I differentiate between Denied ( not asked yet ) and Denied ( asked and refused ) ? EDIT : On further investigation , calling RequestPermissionsAsync does n't seem to make any difference either way . My impression was that it would go to the native platform and display a `` We need permissions.. '' dialogue box . Looking again at the samples a bit more for this plug-in , it almost seems like the answer is to just display the settings and let the user allocate whatever they feel ; it feels a lot like I 'm missing a key part of the puzzle here.EDIT : I 've created a basic replica of the issue here ( obviously I 've removed the Google Maps key ) .EDIT : Following @ FreakyAli 's advice , I ended up with a Main Activity that looks like this ( more or less ) : This works , but it feels like I 'm replicating what the plug-in does . protected override async void OnStart ( ) { PermissionStatus status = await CrossPermissions.Current.CheckPermissionStatusAsync ( Permission.LocationWhenInUse ) ; if ( status == PermissionStatus.Unknown ) { var result = await CrossPermissions.Current.RequestPermissionsAsync ( Permission.LocationWhenInUse ) ; } } if ( ActivityCompat.ShouldShowRequestPermissionRationale ( this , Manifest.Permission.AccessFineLocation ) ) { } else { ActivityCompat.RequestPermissions ( this , new String [ ] { Manifest.Permission.AccessFineLocation } , PERMISSIONS_REQUEST_LOCATION ) ; }",CheckPermissionsAsync always returning Denied on Android "C_sharp : I 'm trying to make use of the OpenID Connect authentication middleware provided by the Katana project.There 's a bug in the implementation which causes a deadlock under these conditions : Running in a host where the request has thread-affinity ( e.g . IIS ) .The OpenID Connect metadata document has not been retrieved or the cached copy has expired.The application calls SignOut for the authentication method.An action happens in the application which causes a write to the response stream.The deadlock happens due to the way the authentication middleware handles the callback from the host signalling that headers are being sent . The root of the problem is in this method : From Microsoft.Owin.Security.Infrastructure.AuthenticationHandlerThe call to Task.Wait ( ) is only safe when the returned Task has already completed , which it has not done in the case of the OpenID Connect middleware.The middleware uses an instance of Microsoft.IdentityModel.Protocols.ConfigurationManager < T > to manage a cached copy of its configuration . This is an asychnronous implementation using SemaphoreSlim as an asynchronous lock and an HTTP document retriever to obtain the configuration . I suspect this to be the trigger of the deadlock Wait ( ) call.This is the method I suspect to be the cause : I have tried adding .ConfigureAwait ( false ) to all of the awaited operations in an effort to marshal continuations onto the thread pool , rather than the ASP.NET worker thread , but I 've not had any success in avoiding the deadlock.Is there a deeper issue I can tackle ? I do n't mind replacing components - I have already created my own experimental implementations of IConfiguratioManager < T > . Is there a simple fix that can be applied to prevent the deadlock ? private static void OnSendingHeaderCallback ( object state ) { AuthenticationHandler handler = ( AuthenticationHandler ) state ; handler.ApplyResponseAsync ( ) .Wait ( ) ; } public async Task < T > GetConfigurationAsync ( CancellationToken cancel ) { DateTimeOffset now = DateTimeOffset.UtcNow ; if ( _currentConfiguration ! = null & & _syncAfter > now ) { return _currentConfiguration ; } await _refreshLock.WaitAsync ( cancel ) ; try { Exception retrieveEx = null ; if ( _syncAfter < = now ) { try { // Do n't use the individual CT here , this is a shared operation that should n't be affected by an individual 's cancellation . // The transport should have it 's own timeouts , etc.. _currentConfiguration = await _configRetriever.GetConfigurationAsync ( _metadataAddress , _docRetriever , CancellationToken.None ) ; Contract.Assert ( _currentConfiguration ! = null ) ; _lastRefresh = now ; _syncAfter = DateTimeUtil.Add ( now.UtcDateTime , _automaticRefreshInterval ) ; } catch ( Exception ex ) { retrieveEx = ex ; _syncAfter = DateTimeUtil.Add ( now.UtcDateTime , _automaticRefreshInterval < _refreshInterval ? _automaticRefreshInterval : _refreshInterval ) ; } } if ( _currentConfiguration == null ) { throw new InvalidOperationException ( string.Format ( CultureInfo.InvariantCulture , ErrorMessages.IDX10803 , _metadataAddress ? ? `` null '' ) , retrieveEx ) ; } // Stale metadata is better than no metadata return _currentConfiguration ; } finally { _refreshLock.Release ( ) ; } }",Solving OnSendingHeaders deadlock with Katana OpenID Connect Middleware "C_sharp : Consider the following code : How come the various versions of Equals return different results ? The EqualityComparer.Default probably calls Object.Equals , so these results match , although inconsistent in themselves . And the normal instance version of Equals both return true . This obviously creates problems when having a method return a Type that actually inherits from TypeDelegator . Imagine for example placing these types as keys in a dictionary , which by default use the EqualityComparer.Default for comparisons . Is there any way to resolve this problem ? I would like all the methods in the code above return true . class MyType : TypeDelegator { public MyType ( Type parent ) : base ( parent ) { } } class Program { static void Main ( string [ ] args ) { Type t1 = typeof ( string ) ; Type t2 = new MyType ( typeof ( string ) ) ; Console.WriteLine ( EqualityComparer < Type > .Default.Equals ( t1 , t2 ) ) ; // < -- false Console.WriteLine ( EqualityComparer < Type > .Default.Equals ( t2 , t1 ) ) ; // < -- true Console.WriteLine ( t1.Equals ( t2 ) ) ; // < -- true Console.WriteLine ( t2.Equals ( t1 ) ) ; // < -- true Console.WriteLine ( Object.Equals ( t1 , t2 ) ) ; // < -- false Console.WriteLine ( Object.Equals ( t2 , t1 ) ) ; // < -- true } }",TypeDelegator equality inconsistency ? "C_sharp : I 've got a question regarding C # .I am currently working on a medical software product , and one of the important things is to make sure that the patient 's data is encrypted . I got two questions regarding this:1 . ) How secure is the Microsoft .NET implementation of AES ( Rijndael ) from System.Security.Cryptography ? Does it have any known security flaws , or am I fine just using the MS implementation ? ( note , I know the basic background of how these algorithms work , but I am not really that deep into it to get an idea of how it works ) .2 . ) Since the data is stored on the same PC as the application , how hard is it to get information from a C # application ? Assuming I have somewhere in the codeI know that an attacker could just go down to the assemble code , and at that point there is nothing at all I can do against this ( the system has to be able to encrypt / decrypt the data ) , but is there like a shortcut for C # to get the encrypPassword , since it is managed , or does something like this still require you to go down to the assemble code ? string encrypPassword = `` ThisIsMyPassword '' ; string encryptedString = EncryptString ( ClearString , encrypPassword ) ; // save encryptedString to harddrive",Disassembling C # "C_sharp : a quick question ; reading this article : http : //blog.stephencleary.com/2016/12/eliding-async-await.htmlit generally tells me , use async/await . Allready doing that . However , he is also saying that you do n't have to use the async part when you are proxying the task . why should be not use async/await when passing through ? Is n't that less convenient , and does this even make sense ? any thoughts anyone ? // Simple passthrough to next layer : elide.Task < string > PassthroughAsync ( int x ) = > _service.DoSomethingPrettyAsync ( x ) ; // Simple overloads for a method : elide.async Task < string > DoSomethingPrettyAsync ( CancellationToken cancellationToken ) { ... // Core implementation , using await . }",eliding async and await in async methods "C_sharp : I 'm trying to play around with ( what I think is ) a factory that creates a repository depending on the enum being passed to the method . Looks like this : RepositoryFactoryIRepositoryFormTypesEnumExtensionsForm64_9C2RepositoryIEntityForm64_9C2 ( stub ) Calling it all as : My problem is my type is always resolving to null . I 'm expecting to get a NotImplementedException , but am instead getting the ArgumentException for not having a valid formType . Prior to implementing IRepository < T > my type/repository was successfully being created ( working code here ) , any ideas ? I 'm only just getting started playing around with factories , generics , and the like - so if I 'm doing something way wrong please advise ! public class RepositoryFactory { public IRepository < IEntity > GetRepository ( FormTypes formType ) { // Represents the IRepository that should be created , based on the form type passed var typeToCreate = formType.GetAttribute < EnumTypeAttribute > ( ) .Type ; // return an instance of the form type repository IRepository < IEntity > type = Activator.CreateInstance ( typeToCreate ) as IRepository < IEntity > ; if ( type ! = null ) return type ; throw new ArgumentException ( string.Format ( `` No repository found for { 0 } '' , nameof ( formType ) ) ) ; } } public interface IRepository < T > where T : class , IEntity { bool Create ( IEnumerable < T > entities ) ; IEnumerable < T > Read ( ) ; bool Update ( IEnumerable < T > entities ) ; bool Delete ( IEnumerable < T > entities ) ; } public enum FormTypes { [ EnumType ( typeof ( Form64_9C2Repository ) ) ] Form64_9C2 , [ EnumType ( typeof ( Form64_9BaseRepository ) ) ] Form64_9Base } public static class EnumExtensions { /// < summary > /// Get the Enum attribute /// < /summary > /// < typeparam name= '' T '' > The attribute < /typeparam > /// < param name= '' enumValue '' > The enum < /param > /// < returns > The type to create < /returns > public static T GetAttribute < T > ( this System.Enum enumValue ) where T : Attribute { FieldInfo field = enumValue.GetType ( ) .GetField ( enumValue.ToString ( ) ) ; object [ ] attribs = field.GetCustomAttributes ( typeof ( T ) , false ) ; T result = default ( T ) ; if ( attribs.Length > 0 ) { result = attribs [ 0 ] as T ; } return result ; } } public class Form64_9C2Repository : IRepository < Form64_9C2 > { public bool Create ( IEnumerable < Form64_9C2 > entities ) { throw new NotImplementedException ( ) ; } public bool Delete ( IEnumerable < Form64_9C2 > entities ) { throw new NotImplementedException ( ) ; } public IEnumerable < Form64_9C2 > Read ( ) { throw new NotImplementedException ( ) ; } public bool Update ( IEnumerable < Form64_9C2 > entities ) { throw new NotImplementedException ( ) ; } } public interface IEntity { } public class Form64_9C2 : IEntity { } class Program { static void Main ( string [ ] args ) { Console.WriteLine ( `` Repository Factory Example \n\n '' ) ; Business.Factory.RepositoryFactory factory = new Business.Factory.RepositoryFactory ( ) ; // Get a 64 9C2 repository var repo9c2 = factory.GetRepository ( FormTypes.Form64_9C2 ) ; Console.WriteLine ( repo9c2 ) ; } }",Activator.CreateInstance with a generic repository "C_sharp : I do n't really understand why await and async do n't improve the performance of my code here like they 're supposed to.Though skeptical , I thought the compiler was supposed to rewrite my method so that the downloads were done in parallel ... but it seems like that 's not actually happening . ( I do realize that await and async do not create separate threads ; however , the OS should be doing the downloads in parallal , and calling back my code in the original thread -- should n't it ? ) Am I using async and await improperly ? What is the proper way to use them ? Code : Output : using System ; using System.Net ; using System.Threading ; using System.Threading.Tasks ; static class Program { static int SumPageSizesSync ( string [ ] uris ) { int total = 0 ; var wc = new WebClient ( ) ; foreach ( var uri in uris ) { total += wc.DownloadData ( uri ) .Length ; Console.WriteLine ( `` Received synchronized data ... '' ) ; } return total ; } static async Task < int > SumPageSizesAsync ( string [ ] uris ) { int total = 0 ; var wc = new WebClient ( ) ; foreach ( var uri in uris ) { var data = await wc.DownloadDataTaskAsync ( uri ) ; Console.WriteLine ( `` Received async 'd CTP data ... '' ) ; total += data.Length ; } return total ; } static int SumPageSizesManual ( string [ ] uris ) { int total = 0 ; int remaining = 0 ; foreach ( var uri in uris ) { Interlocked.Increment ( ref remaining ) ; var wc = new WebClient ( ) ; wc.DownloadDataCompleted += ( s , e ) = > { Console.WriteLine ( `` Received manually async data ... '' ) ; Interlocked.Add ( ref total , e.Result.Length ) ; Interlocked.Decrement ( ref remaining ) ; } ; wc.DownloadDataAsync ( new Uri ( uri ) ) ; } while ( remaining > 0 ) { Thread.Sleep ( 25 ) ; } return total ; } static void Main ( string [ ] args ) { var uris = new string [ ] { // Just found a slow site , to demonstrate the problem : ) `` http : //www.europeanchamber.com.cn/view/home '' , `` http : //www.europeanchamber.com.cn/view/home '' , `` http : //www.europeanchamber.com.cn/view/home '' , `` http : //www.europeanchamber.com.cn/view/home '' , `` http : //www.europeanchamber.com.cn/view/home '' , } ; { var start = Environment.TickCount ; SumPageSizesSync ( uris ) ; Console.WriteLine ( `` Synchronous : { 0 } milliseconds '' , Environment.TickCount - start ) ; } { var start = Environment.TickCount ; SumPageSizesManual ( uris ) ; Console.WriteLine ( `` Manual : { 0 } milliseconds '' , Environment.TickCount - start ) ; } { var start = Environment.TickCount ; SumPageSizesAsync ( uris ) .Wait ( ) ; Console.WriteLine ( `` Async CTP : { 0 } milliseconds '' , Environment.TickCount - start ) ; } } } Received synchronized data ... Received synchronized data ... Received synchronized data ... Received synchronized data ... Received synchronized data ... Synchronous : 14336 millisecondsReceived manually async data ... Received manually async data ... Received manually async data ... Received manually async data ... Received manually async data ... Manual : 8627 milliseconds // Almost twice as fast ... Received async 'd CTP data ... Received async 'd CTP data ... Received async 'd CTP data ... Received async 'd CTP data ... Received async 'd CTP data ... Async CTP : 13073 milliseconds // Why so slow ? ?",Why is the async CTP performing poorly ? "C_sharp : I have a new program I am writing in C # , it will need to read and write binary files that are compatible with vb6 's binary format . I can not change the vb6 program but I can make changes to my program.I have everything working except I am a little iffy about strings.If I write the following in vb6And I write the following in C # I get these two hex stringsIt appears BinaryWriter is not the same between the two when writing strings , vb6 uses a two byte string and C # uses a UTF-7 encoded unsigned int . Also I can not find any resource to what encoding VB is using when it writes a file this way.Are there any built in tools to write the same way vb6 does and if not other than turning the length in to a uint16 are there any other gotchas I need to be aware of ? Private Type PatchRec string As StringEnd TypePrivate Sub Command1_Click ( ) Dim intFileNum As Integer Dim recTest As TestRec intFileNum = FreeFile Open `` E : \testing '' & `` \ '' & `` testfile '' & `` .bin '' For Binary Access Write As # intFileNum recTest.string = `` This is a test string '' Put # intFileNum , , recPatch Close # intFileNumEnd Sub public static void Main ( params string [ ] args ) { using ( var fs = new FileStream ( `` test.bin '' , FileMode.Create , FileAccess.ReadWrite ) ) using ( var bw = new BinaryWriter ( fs ) ) { string str = `` This is a test string '' ; bw.Write ( str ) ; } } vb6 - 15 00 54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 73 74 72 69 6E 67c # - 15 54 68 69 73 20 69 73 20 61 20 74 65 73 74 20 73 74 72 69 6E 67",How to read and write interoperable strings to a binary file between .NET and vb6 "C_sharp : I 'm making a WPF text-editor using TextFormatter . I need to indent the second line in each paragraph . The indentation width in the second line should be like the width of the first word on the first line , including the white space after the first word . Something like that : Second thing : The last line in the paragraph should be in the center.how to make this happen ? Thanks in advance ! ! Indent of second line in Indentation Inde second line in Indentation Indentaof second line in Indentation of second line in Indentation of second line in Inde ntation of second line in",Indentation of second line in WPF TextFormatter "C_sharp : I was just writing a property setter and had a brain-wave about why we do n't have to return the result of a set when a property might be involved in operator = chaining , i.e : ( I 've added the brackets for clarity - but it makes no difference in practise ) I started thinking - where does the C # compiler derive the value that is assigned to a in the above example ? Logic says that it should be from the result of the ( b.c = d ) operation but since that 's implemented with a void set_blah ( value ) method it ca n't be.So the only other options are : Re-read b.c after the assignment and use that valueRe-use dEdit ( since answered and comments from Eric ) - there 's a third option , which is what C # does : use the value written to b.c after any conversions have taken placeNow , to my mind , the correct reading of the above line of code is set a to the result of setting b.c to dI think that 's a reasonable reading of the code - so I thought I 'd test whether that is indeed what happens with a slightly contrived test - but ask yourself if you think it should pass or fail : This test fails.Closer examination of the IL that is generated for the code shows that the true value is loaded on to the stack , cloned with a dup command and then both are popped off in two successive assignments.This technique works perfectly for fields , but to me seems terribly naive for properties where each is actually a method call where the actual final property value is not guaranteed to be the input value.Now I know many people hate nested assignments etc etc , but the fact is the language lets you do them and so they should work as expected.Perhaps I 'm being really thick but to me this suggests an incorrect implementation of this pattern by the compiler ( .Net 4 btw ) . But then is my expectation/reading of the code incorrect ? var a = ( b.c = d ) ; public class TestClass { private bool _invertedBoolean ; public bool InvertedBoolean { get { return _invertedBoolean ; } set { //do n't ask me why you would with a boolean , //but consider rounding on currency values , or //properties which clone their input value instead //of taking the reference . _invertedBoolean = ! value ; } } } [ TestMethod ] public void ExampleTest ( ) { var t = new TestClass ( ) ; bool result ; result = ( t.InvertedBoolean = true ) ; Assert.IsFalse ( result ) ; }",Operator '= ' chaining in C # - surely this test should pass ? "C_sharp : Following the examples on this post and its follow-up question , I am trying to create field getters / setters using compiled expressions.The getter works just great , but I am stuck the setter , as I need the setter to assign any type of fields.Here my setter-action builder : Now , I store the generic setters into a cache list ( because of course , building the setter each time is a performance killer ) , where I cast them as simple `` objects '' : Now I try to set a field value like this : I could simply call a generic method and cast each time , but I am worried about the performance overhead ... Any suggestions ? -- EDITED ANSWERBased on Mr Anderson 's answer , I created a small test program which compares directly setting the value , cached reflection ( where FieldInfo 's are cached ) and the cached multi-type code . I use object inheritance with up to 3 level of inheritance ( ObjectC : ObjectB : ObjectA ) . Full code is of the example can be found here.Single iteration of the test gives following output : Of course , this simply shows the cost of creating the objects - this allows us to measure the offset of creating the cached versions of Reflection and Expressions.Next , let 's run 1.000.000 times : For the sake of completeness : I removed the call to the `` set '' method to highlight the cost of getting the setter ( FieldInfo for the reflection method , Action < object , object > for the expression case ) . Here the results : NOTE : time increase here is not due to the fact that access times are slower for larger dictionaries ( as they have O ( 1 ) access times ) , but due to the fact that the number of times we access it is increased ( 4 times per iteration for ObjectA , 8 for ObjectB , 12 for ObjectC ) ... As one sees , only the creation offset makes a difference here ( which is to be expected ) .Bottom line : we did improve performance by a factor of 2 or more , but we 're still far away from the direct field set 's performance ... Retrieving the correct setter in the list represents a good 10 % of the time.I 'll try with expression trees in place of Reflection.Emit to see if we can further reduce the gap ... Any comment is more than welcome.EDIT 2I added results using the approach using a generic `` Accessor '' class as suggested by Eli Arbel on this post . public static Action < T1 , T2 > GetFieldSetter < T1 , T2 > ( this FieldInfo fieldInfo ) { if ( typeof ( T1 ) ! = fieldInfo.DeclaringType & & ! typeof ( T1 ) .IsSubclassOf ( fieldInfo.DeclaringType ) ) { throw new ArgumentException ( ) ; } ParameterExpression targetExp = Expression.Parameter ( typeof ( T1 ) , `` target '' ) ; ParameterExpression valueExp = Expression.Parameter ( typeof ( T2 ) , `` value '' ) ; // // Expression.Property can be used here as well MemberExpression fieldExp = Expression.Field ( targetExp , fieldInfo ) ; BinaryExpression assignExp = Expression.Assign ( fieldExp , valueExp ) ; // return Expression.Lambda < Action < T1 , T2 > > ( assignExp , targetExp , valueExp ) .Compile ( ) ; } // initialization of the setters dictionary Dictionary < string , object > setters = new Dictionary ( string , object ) ( ) ; Dictionary < string , FieldInfo > fldInfos = new Dictionary ( string , FieldInfo ) ( ) ; FieldInfo f = this.GetType ( ) .GetField ( `` my_int_field '' ) ; setters.Add ( f.Name , GetFieldSetter < object , int > ( f ) ; fldInfos.Add ( f.Name , f ) ; // f = this.GetType ( ) .GetField ( `` my_string_field '' ) ; setters.Add ( f.Name , GetFieldSetter < object , string > ( f ) ; fldInfos.Add ( f.Name , f ) ; void setFieldValue ( string fieldName , object value ) { var setterAction = setters [ fieldName ] ; // TODO : now the problem = > how do I invoke `` setterAction '' with // object and fldInfos [ fieldName ] as parameters ... ? } -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT A -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 0.0036 ms Set reflection : 2.319 ms Set ref.Emit : 1.8186 ms Set Accessor : 4.3622 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT B -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 0.0004 ms Set reflection : 0.1179 ms Set ref.Emit : 1.2197 ms Set Accessor : 2.8819 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT C -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 0.0024 ms Set reflection : 0.1106 ms Set ref.Emit : 1.1577 ms Set Accessor : 2.9451 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT A -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 33.2744 ms Set reflection : 1259.9551 ms Set ref.Emit : 531.0168 ms Set Accessor : 505.5682 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT B -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 38.7921 ms Set reflection : 2584.2972 ms Set ref.Emit : 971.773 ms Set Accessor : 901.7656 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT C -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 40.3942 ms Set reflection : 3796.3436 ms Set ref.Emit : 1510.1819 ms Set Accessor : 1469.4459 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT A -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 3.6849 ms Set reflection : 44.5447 ms Set ref.Emit : 47.1925 ms Set Accessor : 49.2954 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT B -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 4.1016 ms Set reflection : 76.6444 ms Set ref.Emit : 79.4697 ms Set Accessor : 83.3695 ms -- -- -- -- -- -- -- -- -- -- -- -- -- -- OBJECT C -- -- -- -- -- -- -- -- -- -- -- -- -- -- Set direct : 4.2907 ms Set reflection : 128.5679 ms Set ref.Emit : 126.6639 ms Set Accessor : 132.5919 ms",Field getter/setter with expression tree in base class "C_sharp : Given two instances of a class , is it a good and reliable practice to compare them by serializaing them first and then comparing byte arrays ( or possibly hashes of arrays ) . These objects might have complex hierarchical properties but serialization should go as deep as required.By comparison I mean the process of making sure that all propertis of primitive types have equal values , properties of complex types have equal properties of primitive types , etc . As for collection properties , they should be equal to each other : equal elements , same positions : butAnd by serialization I mean standard .NET binary formatter.Thanks . { ' a ' , ' b ' , ' c ' } ! = { ' a ' , ' c ' , ' b ' } { new Customer { Id=2 , Name= '' abc '' } , new Customer { Id=3 , Name= '' def '' } } ! = { new Customer { Id=3 , Name= '' def '' } , new Customer { Id=2 , Name= '' abc '' } } { new Customer { Id=2 , Name= '' abc '' } , new Customer { Id=3 , Name= '' def '' } } == { new Customer { Id=2 , Name= '' abc '' } , new Customer { Id=3 , Name= '' def '' } }",Is it reliable to compare two instances of a class by comparing their serialized byte arrays ? "C_sharp : please check the below exampleITest has subtract ( ) method and Itest2 has add ( ) method.Both are implemented by one concrete class called G.If i just want to expose the ITest through WCF , I have following endpoint configwhen i run this service and check the wsdl , I can see that the methods which are in itest2 also appeared in wsdl . in this example case , subtract ( ) method should only be exposed . But add ( ) method is also exposed.My requirement is to have methods in ITest Interface should only exposed . in this case , i want to expose only subtract ( ) method which is declared in ITest . But both of their implementation resides in Only one concrete class `` G '' . What am I missing here ? Edit : I have given my Service.svc file content : namespace GServices { [ ServiceKnownType ( typeof ( SearchType ) ) ] [ ServiceContract ( SessionMode = SessionMode.Allowed ) ] public interface ITest { [ OperationContract ] int subtract ( int x , int y ) ; } [ ServiceKnownType ( typeof ( SearchType ) ) ] [ ServiceContract ( SessionMode = SessionMode.Allowed ) ] public interface ITest2 { [ OperationContract ] int add ( int x , int y ) ; } public class G : ITest2 , ITest { public int add ( int x , int y ) { return x + y ; } public int subtract ( int x , int y ) { return x + y ; } } } < service name= '' GQS1 '' behaviorConfiguration= '' GQwcfBehaviour '' > < endpoint address= '' DP2Svcs '' binding= '' wsHttpContextBinding '' bindingConfiguration= '' wsHttpEndpointBindingConfig '' contract= '' GServices.itest '' > < identity > < dns value= '' localhost '' / > < /identity > < /endpoint > < /service > < % @ ServiceHost Language= '' C # '' Debug= '' true '' Service= '' GServices.G '' % >",Two Interface and one concrete class in WCF "C_sharp : Consider the following enum declaration and int array : To convert this int [ ] array to an Test [ ] array we can simply do this : I initially tried to do this : However , that throws an exception at runtime : System.ArrayTypeMismatchException : Source array type can not be assigned to destination array type.Question OneIs there a way to do this using Linq and Cast < > without an error , or must I just use Array.Convert ( ) ? Question Two ( added after the first question was answered correctly ) Exactly why does n't it work ? It seems like it 's a case of an implementation detail escaping ... Consider : This causes an error : But this does not : And neither does this : The clear implication is that some kind of optimisation is being done in the .ToList ( ) implementation that causes this exception.Addendum : This also works : or It 's only if the original data is an array that it does n't work . enum Test { None } ; int [ ] data = { 0 } ; Test [ ] result = Array.ConvertAll ( data , element = > ( Test ) element ) ; Test [ ] result = data.Cast < Test > ( ) .ToArray ( ) ; var result = data.Cast < Test > ( ) .ToList ( ) ; // Happens with `` ToList ( ) '' too . var result = new List < Test > ( ) ; foreach ( var item in data.Cast < Test > ( ) ) result.Add ( item ) ; var result = data.Select ( x = > x ) .Cast < Test > ( ) .ToList ( ) ; List < int > data = new List < int > { 0 } ; var result = data.Cast < Test > ( ) .ToList ( ) ; List < int > data = new List < int > { 0 } ; var result = data.Cast < Test > ( ) .ToArray ( ) ;",How to use IEnumerable.Cast < > and .ToArray ( ) to convert int array to an enum array ? "C_sharp : I have written some routines to sharpen a Grayscale image using a 3x3 kernel , The following code is working well in case of non-FFT ( spatial-domain ) convolution , but , not working in FFT-based ( frequency-domain ) convolution.The output image seems to be blurred.I have several problems : ( 1 ) This routine is not being able to generate desired result . It also freezes the application . ( 2 ) This routine gives good result . But , as slow as hell . ( 3 ) The following is my GUI code . SharpenFilter.ApplyWithPadding ( ) works properly if I use an image as a mask . But , does n't work if I use a , say , 3x3 kernel.Output : Source Code : You can download the entire solution from here in this link . -1 -1 -1 -1 9 -1 -1 -1 -1 public static Bitmap ApplyWithPadding ( Bitmap image , Bitmap mask ) { if ( image.PixelFormat == PixelFormat.Format8bppIndexed ) { Bitmap imageClone = ( Bitmap ) image.Clone ( ) ; Bitmap maskClone = ( Bitmap ) mask.Clone ( ) ; ///////////////////////////////////////////////////////////////// Complex [ , ] cPaddedLena = ImageDataConverter.ToComplex ( imageClone ) ; Complex [ , ] cPaddedMask = ImageDataConverter.ToComplex ( maskClone ) ; Complex [ , ] cConvolved = Convolution.Convolve ( cPaddedLena , cPaddedMask ) ; return ImageDataConverter.ToBitmap ( cConvolved ) ; } else { throw new Exception ( `` not a grascale '' ) ; } } public static Bitmap Apply ( Bitmap sourceBitmap ) { Sharpen filter = new Sharpen ( ) ; BitmapData sourceData = sourceBitmap.LockBits ( new Rectangle ( 0 , 0 , sourceBitmap.Width , sourceBitmap.Height ) , ImageLockMode.ReadOnly , PixelFormat.Format32bppArgb ) ; byte [ ] pixelBuffer = new byte [ sourceData.Stride * sourceData.Height ] ; byte [ ] resultBuffer = new byte [ sourceData.Stride * sourceData.Height ] ; Marshal.Copy ( sourceData.Scan0 , pixelBuffer , 0 , pixelBuffer.Length ) ; sourceBitmap.UnlockBits ( sourceData ) ; double blue = 0.0 ; double green = 0.0 ; double red = 0.0 ; int filterWidth = filter.FilterMatrix.GetLength ( 1 ) ; int filterHeight = filter.FilterMatrix.GetLength ( 0 ) ; int filterOffset = ( filterWidth - 1 ) / 2 ; int calcOffset = 0 ; int byteOffset = 0 ; for ( int offsetY = filterOffset ; offsetY < sourceBitmap.Height - filterOffset ; offsetY++ ) { for ( int offsetX = filterOffset ; offsetX < sourceBitmap.Width - filterOffset ; offsetX++ ) { blue = 0 ; green = 0 ; red = 0 ; byteOffset = offsetY * sourceData.Stride + offsetX * 4 ; for ( int filterY = -filterOffset ; filterY < = filterOffset ; filterY++ ) { for ( int filterX = -filterOffset ; filterX < = filterOffset ; filterX++ ) { calcOffset = byteOffset + ( filterX * 4 ) + ( filterY * sourceData.Stride ) ; blue += ( double ) ( pixelBuffer [ calcOffset ] ) * filter.FilterMatrix [ filterY + filterOffset , filterX + filterOffset ] ; green += ( double ) ( pixelBuffer [ calcOffset + 1 ] ) * filter.FilterMatrix [ filterY + filterOffset , filterX + filterOffset ] ; red += ( double ) ( pixelBuffer [ calcOffset + 2 ] ) * filter.FilterMatrix [ filterY + filterOffset , filterX + filterOffset ] ; } } blue = filter.Factor * blue + filter.Bias ; green = filter.Factor * green + filter.Bias ; red = filter.Factor * red + filter.Bias ; if ( blue > 255 ) { blue = 255 ; } else if ( blue < 0 ) { blue = 0 ; } if ( green > 255 ) { green = 255 ; } else if ( green < 0 ) { green = 0 ; } if ( red > 255 ) { red = 255 ; } else if ( red < 0 ) { red = 0 ; } resultBuffer [ byteOffset ] = ( byte ) ( blue ) ; resultBuffer [ byteOffset + 1 ] = ( byte ) ( green ) ; resultBuffer [ byteOffset + 2 ] = ( byte ) ( red ) ; resultBuffer [ byteOffset + 3 ] = 255 ; } } Bitmap resultBitmap = new Bitmap ( sourceBitmap.Width , sourceBitmap.Height ) ; BitmapData resultData = resultBitmap.LockBits ( new Rectangle ( 0 , 0 , resultBitmap.Width , resultBitmap.Height ) , ImageLockMode.WriteOnly , PixelFormat.Format32bppArgb ) ; Marshal.Copy ( resultBuffer , 0 , resultData.Scan0 , resultBuffer.Length ) ; resultBitmap.UnlockBits ( resultData ) ; return resultBitmap ; } string path = @ '' E : \lena.png '' ; string path2 = @ '' E : \mask.png '' ; Bitmap _inputImage ; Bitmap _maskImage ; private void LoadImages_Click ( object sender , EventArgs e ) { _inputImage = Grayscale.ToGrayscale ( Bitmap.FromFile ( path ) as Bitmap ) ; /* _maskImage = Grayscale.ToGrayscale ( Bitmap.FromFile ( path2 ) as Bitmap ) ; */ SharpenFilter filter = new SharpenFilter ( ) ; double [ , ] mask = new double [ , ] { { -1 , -1 , -1 , } , { -1 , 9 , -1 , } , { -1 , -1 , -1 , } , } ; _maskImage = ImageDataConverter.ToBitmap ( mask ) ; inputImagePictureBox.Image = _inputImage ; maskPictureBox.Image = _maskImage ; } Bitmap _paddedImage ; Bitmap _paddedMask ; private void padButton_Click ( object sender , EventArgs e ) { Bitmap lena = Grayscale.ToGrayscale ( _inputImage ) ; Bitmap mask = Grayscale.ToGrayscale ( _maskImage ) ; ////Not working ... //int maxWidth = ( int ) Math.Max ( lena.Width , mask.Width ) ; //int maxHeight = ( int ) Math.Max ( lena.Height , mask.Height ) ; ////This is working correctly in case if I use a png image as a mask . int maxWidth = ( int ) Tools.ToNextPow2 ( Convert.ToUInt32 ( lena.Width + mask.Width ) ) ; int maxHeight = ( int ) Tools.ToNextPow2 ( Convert.ToUInt32 ( lena.Height + mask.Height ) ) ; _paddedImage = ImagePadder.Pad ( lena , maxWidth , maxHeight ) ; _paddedMask = ImagePadder.Pad ( mask , maxWidth , maxHeight ) ; paddedImagePictureBox.Image = _paddedImage ; paddedMaskPictureBox.Image = _paddedMask ; } private void filterButton_Click ( object sender , EventArgs e ) { // Not working properly . // Freezes the application . Bitmap sharp = SharpenFilter.ApplyWithPadding ( _paddedImage , _paddedMask ) ; ////Works well . But , very slow . //Bitmap sharp = SharpenFilter.Apply ( _paddedImage ) ; filteredPictureBox.Image = sharp as Bitmap ; }",FFT Convolution - 3x3 kernel "C_sharp : Versions : ASP Net Core Web API - 2.2 Swashbuckle.AspNetCore - 4.0.1What I currently have ? I have implemented swagger in my Web API project . And I am using JWT authorization with [ Authorize ] attribute on the methods that require it . So I wanted an easy way to be able to send requests that require authorization . In my ConfigureServices class , I 've added the following logic.What this does is the following : It adds one new button in swagger - Authorize . The problem is , it also adds an `` open '' locker icon , next to every method . Even though , some of them require authorization.And when I authorize successfully using the Authorize button ( It basically adds header Authorization to each request ) , I receive a `` closed '' locker on all of them.I know this is probably desired functionality to indicate that an Authorization token will be sent via the request . I want a way to show which methods require authorization and which do n't . What do I want ? For instance , the `` open '' locker for anonymous methods and `` closed '' locker for methods that have [ Authorize ] attribute on them . It could be an additional icon , next to this or to modify the behaviour of this one , no problem . How can I achieve this ? Possible solution ? I believe a possible solution is to make an OperationFilter and go through all methods and attach `` something '' only to those that have [ Authorize ] attribute on them . Is this the best solution ? If so , how would you implement it ? services.AddSwaggerGen ( c = > { // Other swagger options c.AddSecurityDefinition ( `` Bearer '' , new ApiKeyScheme { In = `` header '' , Description = `` Please enter into field the word 'Bearer ' following by space and your JWT token '' , Name = `` Authorization '' , Type = `` apiKey '' } ) ; c.AddSecurityRequirement ( new Dictionary < string , IEnumerable < string > > { { `` Bearer '' , Enumerable.Empty < string > ( ) } , } ) ; // Other swagger options } ) ;",ASP Net Core 2.2 add locker icon only to methods that require authorization - Swagger UI "C_sharp : Is there any where to get the CLR ID at runtime for the current application ? I am monitoring my system using Performance Monitors and the name used for the instance is : I can get all other parameters programmatically but not the r15 which is the runtime ID of the common language runtime ( instance ) that executes your code . I noticed it is always 15 , but it is best to get it dynamically to avoid complications . ApplicationName.exe_p4952_r15_ad1",Getting the CLR ID "C_sharp : In an ASP.net web application I have defined the following Membership provider in the web.config : When I run the application in the debugger , the property Membership.Provider.RequiresQuestionAndAnswer is true . Why ? And how can I fix this ? Update : Ar tuntime , the Membership.Providers collection contains two instances of Provider that are almost identical . The differences are : The first Provider has Name== '' AspNetSqlMembershipProvider '' and RequiresQuestionAndAnswer==trueThe second Provider has Name== '' MyServer '' and RequiresQuestionAndAnswer==false . Now trying to figure out where the first one is coming from . < membership > < providers > < add connectionStringName= '' MyServer '' name= '' MyServer '' type= '' System.Web.Security.SqlMembershipProvider '' enablePasswordReset= '' true '' requiresQuestionAndAnswer= '' false '' enablePasswordRetrieval= '' false '' / > < /providers > < /membership >",requiresQuestionAndAnswer set to false in web.config but RequiresQuestionAndAnswer is true at runtime "C_sharp : I am creating an array with the following CreateArray static method : Where Func looks like : Is it possible to refactor the CreateArray method in something like : public static int [ ] CreateArray ( int size ) { var ret = new int [ size ] ; ret [ 0 ] = 0 ; ret [ 1 ] = 1 ; Parallel.ForEach ( Enumerable.Range ( 2 , size - 2 ) , i = > { ret [ i ] = Func ( i ) .Count ( ) ; } ) ; return ret ; } public static IEnumerable < int > Func ( int i ) { ... } public static int [ ] CreateArray ( int size ) { var tableFromIndex2 = ... return new [ ] { 0 , 1 } .Concat ( tableFromIndex2 ) .ToArray ( ) ; }",Refactor LINQ ForEach to return IEnumerable < T > "C_sharp : I have a synchronous , generic method that looks like thisthe proxy is a WCF service referenceIt just has one method that takes a request and returns a response . But it is used by passing derived requests and returning derived responses . As you can see above the wrapper method is casting the response to the derived type specified by the generic parameter ( TResponse ) .You call the method with derived requests and responsese.g.I am now generating an async service reference so can make use of TasksSo I would like a method that looks like thisthat can be called like thisSo I need a way to cast the Task < Response > to a Task < TResponse > I 've been reading this which seems kind of the opposite of what I need , but cant quite figure out how to bend it to my use caseHow to convert a Task < TDerived > to a Task < TBase > ? any ideas ? public TResponse Execute < TResponse > ( Request request ) where TResponse : Response { return ( TResponse ) proxy.ExecuteRequest ( request ) ; Execute < GetSomeDataResponse > ( new GetSomeDataRequest ( ) ) ; public Task < TResponse > ExecuteAsync < TResponse > ( Request request ) where TResponse : Response { // need to cast to a Task < TResponse > return proxy.ExecuteRequestAsync ( request Task < GetSomeDataResponse > res = ExecuteAsync < GetSomeDataResponse > ( new GetSomeDataRequest ( ) ) ;",Casting a Task < T > to a Task < DerivedT > "C_sharp : This is the signature for the Ok ( ) method in ApiController : And this is my method from my RestController class ( which extends from ApiController ) : Since OkResult implements IHttpActionResult , both of these methods can be called like this : In fact , that 's what I 'm doing in my application.My class PersistenceRestController ( which extends from RestController ) , has these lines of code : This compiles fine , and no warning is raised about method ambiguity . Why is that ? PersistenceRestController has also inherited the protected methods from ApiController so it should have both versions of Ok ( ) ( and it does ) .At execution , the method executed is the one from my RestController.How does the compiler know which method to run ? protected internal virtual OkResult Ok ( ) ; // Note that I 'm not overriding base methodprotected IHttpActionResult Ok ( string message = null ) ; IHttpActionResult result = Ok ( ) ; protected override async Task < IHttpActionResult > Delete ( Key id ) { bool deleted = // ... Attempts to delete entity if ( deleted ) return Ok ( ) ; else return NotFound ( ) ; }",Why are these two methods not ambiguous ? "C_sharp : I 'm wondering , is there any standard way to parse such path-like string : The result must be : ItemName ( Server ) PropertyName ( Name ) , PropertyValue ( MyServerName ) ItemName ( Database ) PropertyName ( Name ) , PropertyValue ( MyDatabaseName ) ItemName ( Table ) PropertyName ( Name ) , PropertyValue ( MyTableName ) PropertyName ( Schema ) , PropertyValue ( MySchemaName ) Most obvious here is to make a regular expression ( and , of course , String.Split ) , but may be there 's a better , standard way ? For the information : the string comes from SMO 's Urn.Value.UPDATE.The answer is found , see below . Server [ @ Name='MyServerName ' ] /Database [ @ Name='MyDatabaseName ' ] /Table [ @ Name='MyTableName ' and @ Schema='MySchemaName ' ]",How to parse this path-like string from SMO ? "C_sharp : I 'm pretty new to C # so bear with me.One of the first things I noticed about C # is that many of the classes are static method heavy . For example ... Why is it : instead of : And why is it : instead of : Feel free to point me to some FAQ on the net . If a detailed answer is in some book somewhere , I 'd welcome a pointer to that as well . I 'm looking for the definitive answer on this , but your speculation is welcome . Array.ForEach ( arr , proc ) arr.ForEach ( proc ) Array.Sort ( arr ) arr.Sort ( )",C # classes - Why so many static methods ? "C_sharp : I am learning C # Deep Copy and Shallow Copy . Here after Change in demo_obj1 , object value is changed but list is not updated but in demo_obj2 object value is changed and also list value updated . Anyone know what is happening here ? ThanksVisual studio 2017.Net framework 4.6Output : public class Demo : ICloneable { public int Value { get ; set ; } public string UID { get ; set ; } public Demo ( int nValue ) { Value = nValue ; } public object Clone ( ) { return this.MemberwiseClone ( ) ; } } public class Program { public static void Print ( List < Demo > objList ) { Console.WriteLine ( ) ; foreach ( Demo objDemo in objList ) { Console.WriteLine ( `` { 0 } = { 1 } '' , objDemo.UID , objDemo.Value ) ; } } public static void Main ( ) { List < Demo > objList = new List < Demo > ( ) ; Demo obj1 = new Demo ( 100 ) ; obj1.UID = `` Demo_obj1 '' ; Demo obj2 = ( Demo ) obj1.Clone ( ) ; obj2.UID = `` Demo_obj2 '' ; objList.Add ( obj1 ) ; objList.Add ( obj2 ) ; Print ( objList ) ; obj1 = obj2 ; obj1.Value = 200 ; Console.WriteLine ( ) ; Console.WriteLine ( obj1.UID + `` = `` + obj1.Value ) ; Console.WriteLine ( obj2.UID + `` = `` + obj2.Value ) ; Print ( objList ) ; Console.ReadKey ( ) ; } } Demo_obj1 = 100Demo_obj2 = 100Demo_obj2 = 200Demo_obj2 = 200Demo_obj1 = 100Demo_obj2 = 200",strange result in Clone ( ) "C_sharp : I am using the standard ASP.NET Core middleware and I would like to allow IP address ranges ( in my case , I am looking for the private IP address ranges ) , to ease development.Currently , my middleware looks like this : But now I would like to add a range of IPs , e.g . 172.16.0.0–172.31.255.255 , in CIDR notation 172.16.0.0/12 . How do I do it ? I tried the following and neither seems to work : http : //172.16.0.0/12:4200http : //172.16.*.*:4200http : //172.16 . *:4200 app.UseCors ( builder = > builder.WithOrigins ( `` http : //localhost:8080 '' , `` https : //test-env.com '' ) .AllowAnyHeader ( ) .AllowAnyMethod ( ) ) ;",Asp.Net Core allow IP ranges in CORS "C_sharp : I want to put some metadata in all resx files in a solution . Is seems like this could be accomplished using the metadata element included in the embedded XSD for resx files : I 'm not 100 % sure that the metadata element should be used to store arbitrary metadata because I was unable to find any documentation about its intended purpose . But it works just fine as long the resx files are edited using a text editor.The problem arises when editing the resx file in Visual Studio 2013 . The default way to open the resource is the `` Managed Resources Editor '' . Unfortunately , the Managed Resource Editor does not make a distinction between data and metadata . This causes the metadata to be silently changed to data on save . This bug ( or perhaps intentional design ) has existed since at least 2010.We have also tried to add elements Managed Resources Editor would n't recognize , but these elements were removed on save . The same thing happened for XML comments . This behavior is more understandable , but does n't leave us with a lot of good options.Here are the possible solutions I 'm aware of : Mandate that no one can use the Managed Resources Editor . This might be fine if it were just me , but I ca n't require this of the whole team . Managed Resources Editor is too useful a tool.Require that everyone manually fix the metadata after using Managed Resources Editor . This is too error prone and burdensome.Submit an issue to the Visual Studio team . We will be doing this , but we need a solution while we wait , and there are no guarantees a fix will ever come.Fork Managed Resources Editor so it behaves how we want . I was unable to find the source and this likely has licensing problems . We are also not interested in maintaining a fork.Write own version of Managed Resource Editor . This is like the above option , but way more work than it is worth for our use case.Just store the metadata in a data tag . This is an obvious hack.It seems like the failure here is n't with resx files themselves , it is with the Visual Studio tools around resx files . However , we are not moving away from Visual Studio any time soon . Are there any solutions I 'm missing ? < xsd : element name= '' metadata '' > < xsd : complexType > < xsd : sequence > < xsd : element name= '' value '' type= '' xsd : string '' minOccurs= '' 0 '' / > < /xsd : sequence > < xsd : attribute name= '' name '' use= '' required '' type= '' xsd : string '' / > < xsd : attribute name= '' type '' type= '' xsd : string '' / > < xsd : attribute name= '' mimetype '' type= '' xsd : string '' / > < xsd : attribute ref= '' xml : space '' / > < /xsd : complexType > < /xsd : element >",How can I add metadata to resx files "C_sharp : I have a small application using WPF and Prism . I have my shell and two modules . I can successfully navigate between them in the `` normal fashion '' ( e.g from a button click ) so I know they are wired up for navigation correctly . However , if I perform some asynchronous operation that fires an event on completion , I ca n't navigate from inside that event handler . The last thing I tried was using Event Aggregation to publish an event back to the UI thread , but it 's still not navigating . The Subscriber to the event gets the event successfully and fires RequestNavigate ( ... ) but the UI does n't update.Now , some code : The viewmodel for my first module LoginModule : The ViewModel for my second module RosterModule : Any tips on what I might be doing wrong ? public class LoginViewModel : ViewModelBase , ILoginViewModel , INavigationAware { ... [ ImportingConstructor ] public LoginViewModel ( IRegionManager regionManager , IUnityContainer container , IEventAggregator eventAggregator ) { _regionManager = regionManager ; _container = container ; _eventAggregator = eventAggregator ; } private DelegateCommand _Login ; public DelegateCommand Login { get { if ( _Login == null ) _Login = new DelegateCommand ( ( ) = > LoginHandler ( ) ) ; return _Login ; } } private void LoginHandler ( ) { _client = new JabberClient ( ) ; _client.Server = `` gmail.com '' ; _client.User = Username ; _client.Password = Password ; ... _client.OnAuthenticate += client_OnAuthenticate ; _client.Connect ( ) ; } private void client_OnAuthenticate ( object sender ) { Console.WriteLine ( `` Authenticated ! `` ) ; _eventAggregator.GetEvent < UserAuthenticatedEvent > ( ) .Publish ( `` '' ) ; } public bool IsNavigationTarget ( NavigationContext navigationContext ) { return true ; } ... } public class RosterViewModel : IRosterViewModel , INavigationAware { private readonly IEventAggregator _eventAggregator ; private readonly IRegionManager _regionManager ; [ ImportingConstructor ] public RosterViewModel ( IRegionManager regionManager , IEventAggregator eventAggregator ) { _regionManager = regionManager ; _eventAggregator = eventAggregator ; _eventAggregator.GetEvent < UserAuthenticatedEvent > ( ) .Subscribe ( o = > { Console.WriteLine ( `` Requesting navigation ... '' ) ; _regionManager.RequestNavigate ( RegionNames.ContentRegion , new Uri ( WellKnownViewNames.RosterView , UriKind.Relative ) ) ; } ) ; } public bool IsNavigationTarget ( NavigationContext navigationContext ) { return true ; } public void OnNavigatedFrom ( NavigationContext navigationContext ) { } public void OnNavigatedTo ( NavigationContext navigationContext ) { Console.WriteLine ( `` I 'm here at the RosterViewModel '' ) ; } }",Ca n't navigate from inside a callback method with Prism "C_sharp : There is something called projected types in WinRT . For example , in metadata , the IXamlType.UnderlyingType is defined as : However when used in a C # app , it changes as follows : My question is - is there any documentation regarding the rules , API , attributes used for such mappings ? TypeName UnderlyingType { get ; } Type UnderlyingType { get ; }",WinRT Projected types documentation "C_sharp : I am currently working on an ASP.NET MVC 3 app where I have a particular view that is setup like a wizard ( using a jQuery plugin ) . Each of the wizard steps is part of a single form , where each `` step '' is split in to its own < div > element . I decided to create partial views for the contents of each `` step '' . I did this for a few reasons . One being that it keeps the code for each step neat and organized . The other being that it allows me to more easily/neatly include or exclude steps from the wizard on the server side.Right now , my `` main '' view looks something like the following : I am wondering if doing something like this would be considered bad practice and if I should just consolidate the code for all `` steps '' in to a single view ? @ using ( Html.BeginForm ) { < div class= '' step '' id= '' step1 '' > @ Html.Partial ( `` Step1 '' ) < /div > < div class= '' step '' id= '' step2 '' > @ Html.Partial ( `` Step2 '' ) < /div > }",Is it considered bad practice to split a single form among multiple partial views ? "C_sharp : A sample method with XML documentation : Write ( null ) throws an exception as expected . Here is an asynchronous method : WriteAsync ( null ) , wo n't throw an exception until awaited . Should I specify the ArgumentNullException in an exception tag anyway ? I think it would make the consumer think that calling WriteAsync may throw an ArgumentNullException and write something like this : What is the best practice for documenting exceptions in asynchronous methods ? // summary and param tags are here when you 're not looking./// < exception cref= '' ArgumentNullException > /// < paramref name= '' text '' / > is null./// < /exception > public void Write ( string text ) { if ( text == null ) throw new ArgumentNullException ( `` text '' , `` Text must not be null . `` ) ; // sync stuff ... } public async Task WriteAsync ( string text ) { if ( text == null ) throw new ArgumentNullException ( `` text '' , `` Text must not be null . `` ) ; // async stuff ... } Task t ; try { t = foo.WriteAsync ( text ) ; } catch ( ArgumentNullException ) { // handling stuff . }",How to document exceptions of async methods ? "C_sharp : I created a CodeAccessSecurityAttribute implementation , witch use stack information to find the target class name , but in some classes the PrincipalPermition is not created , the system uses the previews one instead . What did I miss ? And the usage [ ComVisible ( true ) ] [ AttributeUsageAttribute ( AttributeTargets.Constructor | AttributeTargets.Method , AllowMultiple = true , Inherited = false ) ] public sealed class MyPrincipalPermissionAttribute : CodeAccessSecurityAttribute { public MyPrincipalPermissionAttribute ( SecurityAction action ) : base ( action ) { } public override IPermission CreatePermission ( ) { if ( Unrestricted ) return new PrincipalPermission ( PermissionState.Unrestricted ) ; var stackTrace = new StackTrace ( ) ; var fullnameArray = new List < String > ( ) ; foreach ( var frame in stackTrace.GetFrames ( ) ) { try { var method = frame.GetMethod ( ) ; if ( method ! = null & & method.ReflectedType.IsSubclassOf ( typeof ( BaseClass ) ) ) fullnameArray.Add ( method.ReflectedType.FullName ) ; } catch { } } if ( fullnameArray.Count ( ) > 0 ) return new PrincipalPermission ( null , fullnameArray [ 0 ] , true ) ; return new PrincipalPermission ( PermissionState.Unrestricted ) ; } } public class MyClassCalledFirstWork : BaseClass { [ MyPrincipalPermission ( SecurityAction.Demand ) ] public override void DoSomething ( ) { return ; } } public class MyClassCalledSecondDontWork : BaseClass { [ MyPrincipalPermission ( SecurityAction.Demand ) ] public override void DoSomething ( ) { return ; } }",Why Custom SecurityPermission is not loaded ? "C_sharp : Apologies in advance as I 'm sure someone must have asked this before but I ca n't find it.Just had a surprise , a colleague and I both added the same value in for an enum , and it compiled , e.g.Looks like C/C++ supports this also ( ? ) . Any reason for this behaviour , any cases where it 's useful ? I saw one case with difference human languages ( one = 1 , eins = 1 , etc ) but I 'm not convincedThanks enum MyEnum { mine = 1 , his = 1 }","Enums , overlapping values , C #" "C_sharp : I always use a new object ( ) for this , but I 'm wondering : are there any circumstances in which you would lock on a more specific type ? object theLock = new object ( ) ; ... lock ( theLock ) { ... }",Is there any reason to lock on something other than new object ( ) ? "C_sharp : I have seen a lot of articles recommending not to use the default bot state data storage because microsoft will certainly shutdown this service in march 2018.I am currently developping a stateless bot and do n't need any storage.I have tried to create a fake oneAnd registered it with autofac in global.asaxBut it seems to mess with the context and bot does n't respond to any context.wait ( ) methodsI also tried this : Still have the warning internal class DummyDataStore : IBotDataStore < BotData > { public DummyDataStore ( ) { } public Task < bool > FlushAsync ( IAddress key , CancellationToken cancellationToken ) { return Task.FromResult ( true ) ; } public Task < BotData > LoadAsync ( IAddress key , BotStoreType botStoreType , CancellationToken cancellationToken ) { return Task.FromResult ( new BotData ( ) ) ; } public Task SaveAsync ( IAddress key , BotStoreType botStoreType , BotData data , CancellationToken cancellationToken ) { return Task.CompletedTask ; } } Conversation.UpdateContainer ( builder = > { //Registration of message logger builder.RegisterType < BotMessageLogger > ( ) .AsImplementedInterfaces ( ) .InstancePerDependency ( ) ; //Registration of dummy data storage var store = new DummyDataStore ( ) ; builder.Register ( c = > store ) .As < IBotDataStore < BotData > > ( ) .AsSelf ( ) .SingleInstance ( ) ; } ) ; Conversation.UpdateContainer ( builder = > { var store = new InMemoryDataStore ( ) ; builder.Register ( c = > store ) .Keyed < IBotDataStore < BotData > > ( AzureModule.Key_DataStore ) .AsSelf ( ) .SingleInstance ( ) ; } ) ;","How to get rid of the warning `` Bot Framework State API is not recommended for production environments , and may be deprecated in a future release . ''" "C_sharp : Is there a better way to mimic Covariance in this example ? Ideally I 'd like to do : But KeyValuePair < TKey , TValue > is not covariant.Instead I have to do : Is there a better/cleaner way ? private IDictionary < string , ICollection < string > > foos ; public IEnumerable < KeyValuePair < string , IEnumerable < string > > Foos { get { return foos ; } } public IEnumerable < KeyValuePair < string , IEnumerable < string > > > Foos { get { return foos.Select ( x = > new KeyValuePair < string , IEnumerable < string > > ( x.Key , x.Value ) ) ; } }",KeyValuePair Covariance "C_sharp : how can I get the type name ( in string ) of instance boxed in object.I ca n't use is or as operators.For example : Next I will get it object in another library , where no Student class inside and no reference.And I need something like this : Thanks object a= student1 ; //student1 is instance of Student class string typeName=GetTypeNameInsideObject ( obj1 )",Getting type name of boxed object c # "C_sharp : I am trying to add an HTML link with an image as the anchor , but when I hit send , Outlook automatically embeds the image in the email which makes it more susceptible to being caught as spam . Basically when I add the email , I get the results this guy was looking for by default , but with less code ( granted he wanted to add the image AFTER the signature ) Here 's my code : This adds the picture , looks great and the picture shows up right when the user opens the email ( without having to Allow images ) but I 've been warned that embedded images get caught as spam a lot , and I 've seen a number of the sent emails end up in spam boxes.Is this true that an embedded image is likely to be caught as spam ( I find that weird cause this is the default way outlook handles when you insert some image/chart etc etc ) ? How can I insert an image like standard HTML ( with the image not being embedded in the actual email , even if that means the recipient has to allow the image to be shown ) ? I would rather them get the email than have it end up as spam . var doc = Globals.ThisAddIn.Application.ActiveWindow ( ) .WordEditor ; var pic = doc.Application.Selection.InlineShapes.AddPicture ( `` MY IMAGE URL '' , true ) ; doc.Application.Selection.Hyperlinks.add ( pic , `` MY URL '' ) ;",c # VSTO Outlook link image without it being embedded "C_sharp : I ’ m still working on a WCF solution that should be able to query the backend of the program and return the results.The backend stores a dictionary of objects called Groups and they can be queried with functions like : GetGroup to get a single group by IDGetGroups to get a list of groups by tags.The GetGroup works fine with the WCF Test Client and the application I have built.And it works with the following code form the application : The GetGroups works perfectly with WCF Test Client but not with my application.It sends the query as it should but it does return Null ( please note that this code is form another app and I ’ m using a reference instead of a proxy file ) in new ServiceReference1.programme [ 1 ] ; I am actually guessing what to put there.Interface : Message Contract : Group contact ( sometimes referred as programme ) List < string > values = new List < string > ( ) ; GroupServiceClient client = new GroupServiceClient ( `` WSHttpBinding_IGroupService '' ) ; www.test.co.uk.programme.programme Group = new www.test.co.uk.programme.programme ( ) ; DateTime time = DateTime.Now ; values.Clear ( ) ; client.Open ( ) ; Group.number = textBox1.Text ; client.GetGroup ( ref time , ref Group ) ; GroupStorageMessage toReturn = new GroupStorageMessage ( ) ; toReturn.group = Group ; selectedGroupId = Convert.ToString ( toReturn.group.number ) ; values.Add ( Convert.ToString ( toReturn.group.number ) ) ; values.Add ( Convert.ToString ( toReturn.group.name ) ) ; listBox1.ItemsSource=values ; client.Close ( ) ; ServiceReference1.programme Group = new ServiceReference1.programme ( ) ; ServiceReference1.GroupServiceClient Client = new ServiceReference1.GroupServiceClient ( ) ; DateTime Time = DateTime.Now ; Client.Open ( ) ; string [ ] aa = new string [ 1 ] ; aa [ 0 ] = textBox1.Text ; Group.tags = aa ; Client.GetGroups ( ref Time , Group ) ; ServiceReference1.GroupArrayMessage toReturn = new ServiceReference1.GroupArrayMessage ( ) ; ServiceReference1.programme [ ] Groups = new ServiceReference1.programme [ 1 ] ; toReturn.groups = Groups ; = returns null [ ServiceContract ( Namespace = `` http : //www.Test.co.uk/groupstorage '' ) ] public interface IGroupStorageService { /** * Get a group from the collection of groups */ [ OperationContract ] GroupStorageMessage GetGroup ( GroupStorageMessage message ) ; /** * Add a group to the collection of groups */ [ OperationContract ] void AddGroup ( GroupStorageMessage message ) ; /** * Remove a group from the collection of groups */ [ OperationContract ] void RemoveGroup ( GroupStorageMessage message ) ; /** * Update a group in the collection of groups */ [ OperationContract ] void UpdateGroup ( GroupStorageMessage message ) ; [ OperationContract ] GroupArrayMessage GetGroups ( GroupStorageMessage message ) ; } [ MessageContract ] public class GroupArrayMessage { /** * Message header is the timestamp when the message was created */ [ MessageHeader ( Name = `` time '' ) ] public DateTime Time ; /** * Message body is a collection of Users */ [ MessageBodyMember ( Name = `` groups '' ) ] public Group [ ] Groups ; } [ DataContract ( Namespace = `` http : //www.test.co.uk/programme '' , Name = `` programme '' ) ] public class Group { /** * The number representing the Programme ( Programme ID ) */ [ DataMember ( Name = `` number '' ) ] public string Number ; /** * The name of the Programme */ [ DataMember ( Name = `` name '' ) ] public string Name ; /// < summary > /// Add Tags /// < /summary > [ DataMember ( Name = `` tags '' ) ] public string [ ] Tags ;",WCF querying an array of objects "C_sharp : This question is around how to architect WCF services to make it easy to evolve over time.Its difficult to get the depth of response to this without describing the problem.BackgroundI am developing a large system of WCF services and clients.The server side is `` easy '' to update as there are only 10 servers in question running this code.The clients are very difficult to update , despite the high degree of automation , at 300,000+ WCF clients , updates are something that will always take time , and only achieves a high update success rate over a period of two to three weeks.Data ContractsThe DataContract is difficult to initialise and has a standard MyContractFactory class to initialise obtain the appropriate instance for your machine.ServiceContractsThe DataContract is very common across a range of web services.ClientMy client is plugin based with plugins running in either separate processes or app domains depending on the level of trust we have in that plugin.Implementation 1My initial implementation of this ( default WCF ) ended up with the DataContract in one assembly , ServiceContract , and implementation in its own assembly.The clients ended up with a very ugly , With a copy and paste of the MyContractFactory in nearly every plugin . Whilst the DataContract was the same , the fact that the clients did not include the DataContract assembly meant that it appeared under different namespaces as different objects.Implementation 2The clients now include the DataContract assembly , ServiceContracts are in a separate assembly to the service implementation , clients may include some of the ServiceContract assemblies if it will aid with code reuse ( no more copy and paste ) .QuestionWith the second implementation I am now facing the difficulty of , how do I update my DataContract and ServiceContracts ? Do I update the same assembly and increment the version number ? How do I preserve backwards compatibility whilst all the clients upgrade ? Breaking the clients until they update is not acceptable.Do I create a new assembly with a class that extends MyDataContract , new methods that accept the new type under a new ServiceContract ? Does that mean for every minor change to my contracts I need a new assembly ? How would I stop it from getting to literally hundreds in a couple of years time ? Some other solution ? Regardless of the solutions I think through , they all seem to have a major downside . There does n't seem to be ( at least to me ) of , Preserving backwards compatibility until clients updateKeeping the clients trim with no bloat as the software evolves over timeNot significantly polluting my ServiceContract ( overloads of the OperationContract need a new `` name '' ) . I already have things like the below , and it strikes me a nightmare to maintain over time.Operation Contract complexityI am looking for a solution that has worked over a period of time in a large scale environment . Blog entries and the like are very welcome.Update 1Looking through the limitations of using `` schemaless '' changes , different namespaces seems like the only sure method . However , its not quite working as expected , e.g . belowWith the following serviceand the following configResults in two contracts with two different names , I expected that I can point my clients to , http : //myurl.com/MyService.svc/2012/05 for the old version , and http : //myurl.com/MyService.svc/2012/06 , but it seems like if I want to preserve the ServiceContract name they have to be two separate services rather than separate endpoint addresses for the same service ? Update 2I ended up using the method I have described under update 1 . Whilst the WSDL looks wrong , the service is indeed backwards compatible under older clients when I 've tested this . [ DataContract ] public class MyContract { [ DataMember ] public int Identity { get ; set ; } [ DataMember ] public string Name { get ; set ; } // More members } public class static MyContractFactory { public static MyContract GetMyContract ( ) { // Complex implementation } } namespace MyPrefix.WebServicve1 { [ ServiceContract ] public class IMyInterface1 { [ OperationContract ] public void DoSomethingWithMyContract ( MyContract data ) ; } [ ServiceContract ] public class IMyInterface2 { [ OperationContract ] public void DoSomethingDifferentWithMyContract ( MyContract data ) ; } } MyWebService1.MyContractMyWebService2.MyContract [ OperationContract ] public void DoSomethingWithMyContract ( MyContract data ) ; [ OperationContract ( Name = `` DoSomethingWithMyDataByAdditionalData '' ] public void DoSomethingWithMyContract ( MyContract data , MyContract2 additionalData ) ; [ ServiceContract ( Name = `` IServiceContract '' , Namespace = `` http : //myurl/2012/05 '' ) ] public interface IServiceContract1 { // Some operations } [ ServiceContract ( Name = `` IServiceContract '' , Namespace = `` http : //myurl/2012/06 '' ) ] public interface IServiceContract2 { // Some different operations using new DataContracts } public class MyService : IServiceContract1 , IServiceContract2 { // Implement both operations } < service behaviorConfiguration= '' WcfServiceTests.ServiceBehavior '' name= '' Test.MyService '' > < endpoint address= '' 2012/05 '' binding= '' wsHttpBinding '' contract= '' Test.IServiceContract1 '' > < identity > < dns value= '' localhost '' / > < /identity > < /endpoint > < endpoint address= '' 2012/06 '' binding= '' wsHttpBinding '' contract= '' Test.IServiceContract2 '' > < identity > < dns value= '' localhost '' / > < /identity > < /endpoint > < endpoint address= '' mex '' binding= '' mexHttpBinding '' contract= '' IMetadataExchange '' / > < /service >","WCF Architecture , and Evolution , Version" "C_sharp : So , using the ODataController , you get to control what gets returned if somebody does /odata/Foos ( 42 ) /Bars , because you 'll be called on the FoosController like so : But what if you want to control what gets returned when somebody does /odata/Foos ? $ expand=Bars ? How do you deal with that ? It triggers this method : And I assume it just does an .Include ( `` Bars '' ) on the IQueryable < Foo > that you return , so ... how do I get more control ? In particular , how do I do it in such a way that OData does n't break ( i.e . things like $ select , $ orderby , $ top , etc . continue working . ) public IQueryable < Bar > GetBars ( [ FromODataUri ] int key ) { } public IQueryable < Foo > GetFoos ( ) { }",Controlling what is returned with an $ expand request "C_sharp : I am connecting to a duplex WCF service with an x509 cert , specifying the certificate details in the client config file like this : The code that then connects to the WCF service : I now need to specify the client certificate name that will be used programatically , in code . Is it possible for me to do that ? I can see that I can create my own x509Certificate2 class , but I 'm not sure how to change/set the findValue= '' clientName '' bit ... Thanks < behaviors > < endpointBehaviors > < behavior name= '' ScannerManagerBehavior '' > < clientCredentials > < clientCertificate findValue= '' ClientName '' x509FindType= '' FindBySubjectName '' storeLocation= '' CurrentUser '' storeName= '' My '' / > < serviceCertificate > < authentication certificateValidationMode= '' PeerTrust '' / > < /serviceCertificate > < /clientCredentials > < /behavior > < /endpointBehaviors > < /behaviors > DuplexChannelFactory < IScannerManager > _smFactory = new DuplexChannelFactory < IScannerManager > ( instanceContext , nameOfEndPoint ) ; var _commsChannel = _smFactory.CreateChannel ( ) ;",Dynamically set x509 to use for WCF duplex comms "C_sharp : Problem : When I use Contains ( ) against an IEnumerable < T > of classes that correctly implement IEquatable and override GetHashCode it returns false . If I wrap the match target in a list and perform an Intersect ( ) then the match works correctly . I would prefer to use Contains ( ) .On IEnumerable.Contains ( ) from MSDN : Elements are compared to the specified value by using the default equality comparerOn EqualityComparer < T > .Default Property from MSDN : The Default property checks whether type T implements the System.IEquatable generic interface and if so returns an EqualityComparer that uses that implementation . Otherwise it returns an EqualityComparer that uses the overrides of Object.Equals and Object.GetHashCode provided by T.As far as I understand , implementing IEquatable < T > on my class should mean that the Equals method is used by the default comparer when trying to find a match . I want to use Equals because I want there to be only one way that two objects are the same , I do not want a strategy that the developers have to remember to put in.What I find strange is that if I wrap the match target in a List and then perform an Intersect then the match is correctly found.What am I missing ? Do I have to create an equality comparer too , like the MSDN article ? MSDN suggests that having IEquatable is enough and that it will wrap it for me.Example Console AppNB : GetHashCode ( ) from Jon Skeet here.NET 4.5 Fiddle Example using System ; using System.Collections.Generic ; using System.Linq ; namespace ContainsNotDoingWhatIThoughtItWould { class Program { public class MyEquatable : IEquatable < MyEquatable > { string [ ] tags ; public MyEquatable ( params string [ ] tags ) { this.tags = tags ; } public bool Equals ( MyEquatable other ) { if ( other == null ) { return false ; } if ( this.tags.Count ( ) ! = other.tags.Count ( ) ) { return false ; } var commonTags = this.tags.Intersect ( other.tags ) ; return commonTags.Count ( ) == this.tags.Count ( ) ; } public override int GetHashCode ( ) { int hash = 17 ; foreach ( string element in this.tags.OrderBy ( x = > x ) ) { hash = unchecked ( hash * element.GetHashCode ( ) ) ; } return hash ; } } static void Main ( string [ ] args ) { // Two objects for the search list var a = new MyEquatable ( `` A '' ) ; var ab = new MyEquatable ( `` A '' , `` B '' ) ; IEnumerable < MyEquatable > myList = new MyEquatable [ ] { a , ab } ; // This is the MyEquatable that we want to find var target = new MyEquatable ( `` A '' , `` B '' ) ; // Check that the equality and hashing works var isTrue1 = target.GetHashCode ( ) == ab.GetHashCode ( ) ; var isTrue2 = target.Equals ( ab ) ; var isFalse1 = target.GetHashCode ( ) == a.GetHashCode ( ) ; var isFalse2 = target.Equals ( a ) ; // Why is this false ? var whyIsThisFalse = myList.Contains ( target ) ; // If that is false , why is this true ? var wrappedChildTarget = new List < MyEquatable > { target } ; var thisIsTrue = myList.Intersect ( wrappedChildTarget ) .Any ( ) ; } } }",Why does Contains ( ) return false but wrapping in a list and Intersect ( ) returns true ? "C_sharp : In a program I 'm using the dynamic keyword to invoke the best matching method . However , I have found that the framework crashes with a StackOverflowException under some circumstances.I have tried to simplify my code as much as possible while still being able to re-produce this problem.That program would normally print `` set '' if the newed up instance implements the ISortedSet < TKey > interface and print `` object '' for anything else . But , with the following declarations a StackOverflowException is thrown instead ( as noted in a comment above ) .Whether this is a bug or not it is very troubling that a StackOverflowException is thrown as we are unable to catch it and also pretty much unable to determine in advance whether an exception will be thrown ( and thereby terminate the process ! ) .Can someone please explain what 's going on ? Is this a bug in the framework ? When debugging and switching to `` Disassembly mode '' I 'm seeing this : Register dump at that location : That does n't tell me much more than being an indicator that this indeed must be some kind of bug in the framework.I 've filed a bug report on Microsoft Connect but I 'm interested in knowing what 's going on here . Are my class declarations unsupported in some way ? Not knowing WHY this is happening causes me to worry about other places where we are using the dynamic keyword . Can I not trust that at all ? class Program { static void Main ( string [ ] args ) { var obj = new SetTree < int > ( ) ; var dyn = ( dynamic ) obj ; Program.Print ( dyn ) ; // throws StackOverflowException ! ! // Note : this works just fine for 'everything else ' but my SetTree < T > } static void Print ( object obj ) { Console.WriteLine ( `` object '' ) ; } static void Print < TKey > ( ISortedSet < TKey > obj ) { Console.WriteLine ( `` set '' ) ; } } interface ISortedSet < TKey > { } sealed class SetTree < TKey > : BalancedTree < SetTreeNode < TKey > > , ISortedSet < TKey > { } abstract class BalancedTree < TNode > where TNode : TreeNode < TNode > { } abstract class SetTreeNode < TKey > : KeyTreeNode < SetTreeNode < TKey > , TKey > { } abstract class KeyTreeNode < TNode , TKey > : TreeNode < TNode > where TNode : KeyTreeNode < TNode , TKey > { } abstract class TreeNode < TNode > where TNode : TreeNode < TNode > { } EAX = 02B811B4 EBX = 0641EA5C ECX = 02C3B0EC EDX = 02C3A504 ESI = 02C2564CEDI = 0641E9AC EIP = 011027B9 ESP = 0641E91C EBP = 0641E9B8 EFL = 00000202",StackOverflowException when accessing member of generic type via dynamic : .NET/C # framework bug ? "C_sharp : I 'm trying to connect a share ( let 's say \server\folder ) to my local device X : When calling the function just returns false - the Error says 1200 ( BAD_DEVICE ) .The NetResource looks like this : I already checked with several snippets ( PInvoke ) put i ca n't see any difference . Maybe you can solve this mystery ... EDIT1 [ DllImport ( `` Mpr.dll '' , CharSet = CharSet.Unicode , SetLastError = true ) ] private static extern int WNetAddConnection2 ( [ In ] NetResource lpNetResource , string lpPassword , string lpUsername , int flags ) ; public static bool Connect ( string remoteName , string localName , bool persistent ) { if ( ! IsLocalPathValid ( localName ) ) return false ; var r = new NetResource { dwScope = ResourceScope.RESOURCE_GLOBALNET , dwType = ResourceType.RESOURCETYPE_ANY , dwDisplayType = ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE , dwUsage = ResourceUsage.RESOURCEUSAGE_CONNECTABLE , lpRemoteName = remoteName , lpLocalName = localName } ; return WNetAddConnection2 ( r , null , null , persistent ? 1 : 0 ) == 0 ; } [ StructLayout ( LayoutKind.Sequential ) ] public class NetResource { public ResourceScope dwScope ; public ResourceType dwType ; public ResourceDisplayType dwDisplayType ; public ResourceUsage dwUsage ; public string lpLocalName ; public string lpRemoteName ; public string lpComment ; public string lpProvider ; } Connect ( @ '' \\server\folder '' , `` X : '' , true ) ; lpRemoteName = `` \\\\server\\folder '' ; lpProvider = null ; lpLocalName = `` X : '' ; lpComment = null ; dwUsage = Connectable ; dwType = Any ; dwScope = GlobalNet ; dwDisplayType = Share ;",WNetAddConnection2 returns Error 1200 - Local name is valid "C_sharp : I 'm working on a project targeting netcoreapp1.0 on OSX , and I 'm setting up a script using Roslyn like this : Where Globals is : When I try to run a script that looks like this : The program terminates with this exception : Obviously Console does , in fact , have an overload that takes 2 methods . I looked at the CoreFx sources briefly to see if there were any odd type-forwarding or extension method tricks being used that might need additional care in the script setup , but I did n't see anything unusual there ( maybe I missed something ) .Why would the Roslyn ScriptBuilder then complain about this ? var scriptText = File.ReadAllText ( args [ 0 ] ) ; var scriptOptions = ScriptOptions.Default .WithReferences ( typeof ( System.Object ) .GetTypeInfo ( ) .Assembly ) ; var script = CSharpScript.Create ( scriptText , scriptOptions , typeof ( Globals ) ) ; var scriptArgs = new string [ args.Length-1 ] ; Array.Copy ( args , 1 , scriptArgs , 0 , args.Length-1 ) ; script.RunAsync ( new Globals { Args = scriptArgs } ) .GetAwaiter ( ) .GetResult ( ) ; public class Globals { public string [ ] Args { get ; set ; } } using System ; Console.WriteLine ( `` Args [ 0 ] : { 0 } '' , Args [ 0 ] ) ; $ dotnet run test.csxProject BitThicket.DotNet.ScriptTool ( .NETCoreApp , Version=v1.0 ) was previously compiled . Skipping compilation.Script error : Microsoft.CodeAnalysis.Scripting.CompilationErrorException : ( 7,9 ) : error CS1501 : No overload for method 'WriteLine ' takes 2 arguments at Microsoft.CodeAnalysis.Scripting.ScriptBuilder.ThrowIfAnyCompilationErrors ( DiagnosticBag diagnostics , DiagnosticFormatter formatter ) at Microsoft.CodeAnalysis.Scripting.ScriptBuilder.CreateExecutor [ T ] ( ScriptCompiler compiler , Compilation compilation , CancellationToken cancellationToken ) at Microsoft.CodeAnalysis.Scripting.Script ` 1.GetExecutor ( CancellationToken cancellationToken ) at Microsoft.CodeAnalysis.Scripting.Script ` 1.RunAsync ( Object globals , Func ` 2 catchException , CancellationToken cancellationToken ) at BitThicket.DotNet.ScriptTool.Program.Main ( String [ ] args ) in /Users/ben/proj/bt/dotnet-scriptcs/src/BitThicket.DotNet.ScriptTool/Program.cs : line 63",Roslyn Scripting API on .NET Core : why does compiler complain `` error CS1501 : no overload for WriteLine takes 2 arguments '' ? "C_sharp : I recently needed to build C # specific name ( which must always include global : : specifier ) for an arbitrary type and have come accross following issue : I was expecting that returned value would be same in both cases . However , for some reason the array related part of the value seems to be reversed ( case 1 ) . Is this reversal expected behavior ? // 1 - value : System.String [ , , , ] [ , , ] [ , ] string unexpectedFullName = typeof ( string [ , ] [ , , ] [ , , , ] ) .FullName ; // 2 - value : System.String [ , ] [ , , ] [ , , , ] string expectedFullName = Type.GetType ( `` System.String [ , ] [ , , ] [ , , , ] '' ) .FullName ;",Unexpected value of System.Type.FullName "C_sharp : I 've been reading quite a lot about this interesting topic ( IMO ) . but I 'm not fully understand one thing : Dictionary size is increasing its capacity ( doubles to the closest prime number ) to a prime number ( when reallocation ) : because : So we can see that prime numbers are used here for [ Dictionary Capacity ] because their GreatestCommonFactor is 1. and this helps to avoid collisions . In additionI 've seen many samples of implementing theGetHashCode ( ) : Here is a sample from Jon Skeet : I do n't understand : Question Does prime numbers are used both in : Dictionary capacity and in the generation of getHashCode ? Because in the code above , there is a good chance that the return value will not be a prime number [ please correct me if i 'm wrong ] because of the multiplication by 23 addition of the GetHashCode ( ) value for each field.For Example : ( 11,17,173 are prime number ) 213222 is not a prime.Also there is not any math rule which state : ( not a prime number ) + ( prime number ) = ( prime number ) nor ( not a prime number ) * ( prime number ) = ( prime number ) nor ( not a prime number ) * ( not a prime number ) = ( prime number ) So what am I missing ? int index = hashCode % [ Dictionary Capacity ] ; public override int GetHashCode ( ) { unchecked { int hash = 17 ; // Suitable nullity checks etc , of course : ) hash = hash * 23 + field1.GetHashCode ( ) ; hash = hash * 23 + field2.GetHashCode ( ) ; hash = hash * 23 + field3.GetHashCode ( ) ; return hash ; } } int hash = 17 ; hash = hash * 23 + 11 ; //402 hash = hash * 23 + 17 ; //9263 hash = hash * 23 + 173 //213222 return hash ;","Dictionary < , > Size , GetHashCode and Prime Numbers ?" C_sharp : I 'm trying to obtain region info by ISO 3166-1 TwoLetters country name - `` MD '' .But I 'm obtaining the following exception : Culture name 'MD ' is not supported.This is strange because Microsoft Table of supported countries Moldova is present : http : //msdn.microsoft.com/en-us/library/dd374073.aspx var r = new RegionInfo ( `` MD '' ) ;,Get Region info of Moldova "C_sharp : I 'm using AutoMapper to copy an entity framework object to another identical database . The problem is that it tries to copy the lookup tables.I have tried to exclude them with the AddGlobalIgnore and the ShouldMapProperty but it does n't work . AutoMapper still try to copy those properties . Here 's my code . I would like to ignore the properties that start with `` LU '' I did also tried and dynamic newObject= new NewObject ( ) ; MapperConfiguration config = new MapperConfiguration ( cfg = > { cfg.CreateMissingTypeMaps = true ; cfg.AddGlobalIgnore ( `` LU '' ) ; cfg.ShouldMapProperty = p = > ! p.GetType ( ) .ToString ( ) .StartsWith ( `` LU '' ) ; cfg.ShouldMapField = p = > ! p.GetType ( ) .ToString ( ) .StartsWith ( `` LU '' ) ; } ) ; IMapper mapper = config.CreateMapper ( ) ; newObject = mapper.Map ( objectToCopy , objectToCopy.GetType ( ) , newObject.GetType ( ) ) ; MapperConfiguration config = new MapperConfiguration ( cfg = > { cfg.CreateMissingTypeMaps = true ; cfg.AddGlobalIgnore ( `` LU '' ) ; cfg.ShouldMapProperty = p = > ! p.PropertyType.Name.StartsWith ( `` LU '' ) ; cfg.ShouldMapField = p = > ! p.FieldType.Name.StartsWith ( `` LU '' ) ; } ) ; MapperConfiguration config = new MapperConfiguration ( cfg = > { cfg.CreateMissingTypeMaps = true ; cfg.AddGlobalIgnore ( `` LU '' ) ; cfg.ShouldMapProperty = p = > ! p.Name.StartsWith ( `` LU '' ) ; cfg.ShouldMapField = p = > ! p.Name.StartsWith ( `` LU '' ) ; } ) ;",How to ignore properties based on their type "C_sharp : I have an object called Shape which contains a public int [ , ] coordinate { get ; set ; } field.I have a separate class which has a collection of Shape objects . At a particular point , I wish to check : So in the Shape class I have added the IComparable reference and inserted the CompareTo method : I am however getting an error : How do I therefore phrase the return so that it returns an int and not a bool as it is doing so at the moment ? UPDATEIf I change the return code to : I get the following error mesage : Error 1 'ShapeD.Game_Objects.Shape ' does not implement interface member 'System.IComparable.CompareTo ( ShapeD.Game_Objects.Shape ) ' . 'ShapeD.Game_Objects.Shape.CompareTo ( ShapeD.Game_Objects.Shape ) ' can not implement 'System.IComparable.CompareTo ( ShapeD.Game_Objects.Shape ) ' because it does not have the matching return type of 'int ' . C : \Users\Usmaan\Documents\Visual Studio 2012\Projects\ShapeD\ShapeD\ShapeD\Game Objects\Shape.cs 10 18 ShapeD if ( shapes.Contains ( shape ) ) { // DoSomething } public int CompareTo ( Shape other ) { return this.coordinate.Equals ( other.coordinate ) ; } Can not implicitly convert type 'bool ' to 'int ' return this.coordinate.CompareTo ( other.coordinate ) ;",IComparable in C # "C_sharp : I often find myself doing the following index-counter messiness in a foreach loop to find out if I am on the first element or not . Is there a more elegant way to do this in C # , something along the lines of if ( this.foreach.Pass == 1 ) etc . ? int index = 0 ; foreach ( var websitePage in websitePages ) { if ( index == 0 ) classAttributePart = `` class=\ '' first\ '' '' ; sb.AppendLine ( String.Format ( `` < li '' + classAttributePart + `` > '' + `` < a href=\ '' { 0 } \ '' > { 1 } < /a > < /li > '' , websitePage.GetFileName ( ) , websitePage.Title ) ) ; index++ ; }",Less-verbose way of handling the first pass through a foreach ? "C_sharp : I have some custom editable listbox on my wpf window.I also have a viewmodel class with Property Changed which looks like that : So , I would like to bind my Save button to this property : My question is how to update Save button if one of the listbox rows is changed ? public bool HasChanges { get { return customers.Any ( customer = > customer.Changed ) ; } } < Button IsEnabled= '' { Binding HasChanges , Mode=OneWay } '' ...",How to bind to property with only get accessor "C_sharp : I am working on a mini-framework for `` runnable '' things . ( They are experiments , tests , tasks , etc . ) Now , how can I reconcile ConcurrentBlockRunner and SequentialBlockRunner ? By this I mean : Refer to them by a common ancestor , for use in a collection . ( IEnuerable < T > where T = ? ? ) Provide additional base class functionality . ( Add a property , for example ) .I remedied # 1 by adding another interface that just specified a type parameter to IA < T > : And modified my ConcurrentBlockRunner and SequentialBlockRunner definitions to be : Since ConcurrentBlockRunner and SequentialBlockRunner both use Block for their type parameter , this seems to be a correct solution . However , I ca n't help but feel `` weird '' about it , because well , I just tacked that interface on.For # 2 , I want to add a couple pieces of common data to ConcurrentBlockRunner and SequentialBlockRunner . There are several properties that apply to them , but not to their only common base class , which is all the way up at RunnerBase < T > .This is the first time while using C # that I 've felt multiple inheritance would help . If I could do : Then I could simply add these extra properties to BlockRunnerBase , and everything would just work . Is there a better way ? I know I will be recommended immediately to consider composition , which I began to work with : The problem I encountered ( driving me to write this question ) was that once you compose , you lose type compatibility . In my case , _member was firing an event , so the sender parameter was of type SequentialBlockRunner . However , the event handler was trying to cast it to type BlockRunner , which of course failed . The solution there is not use add/remove to proxy the events , but actually handle them , and raise an event of my own . So much work just to add a couple properties ... // Something that `` runs '' ( in some coordinated way ) multiple `` runnable '' things.interface IRunnableOf < T > where : IRunnable// Provide base-class functionality for a `` runner '' abstract class RunnerBase < T > : IRunnableOf < T > class SequentialRunner < T > : RunnerBase < T > // Same interface , different behavior.class ConcurrentRunner < T > : RunnerBase < T > // other types of runners.class ConcurrentBlockRunner : SequentialRunner < Block > class SequentialBlockRunner : ConcurrentRunner < Block > interface IBlockRunner : IRunnableOf < Block > { } class ConcurrentBlockRunner : SequentialRunner < Block > , IBlockRunnerclass SequentialBlockRunner : ConcurrentRunner < Block > , IBlockRunner abstract class BlockRunnerBase { int Prop1 { get ; set ; } int Prop2 { get ; set ; } class ConcurrentBlockRunner : SequentialRunner < Block > , BlockRunnerBaseclass SequentialBlockRunner : ConcurrentRunner < Block > , BlockRunnerBase class BlockRunner : IBlockRunner { IBlockRunner _member ; int Prop1 { get ; set ; } // Wish I could put these in some base class int Prop2 { get ; set ; } // Lots of proxy calls , and proxy events into _member void Method ( ) { _member.Method ( ) ; } event SomeEvent { add { _member.SomeEvent += value ; } remove { _member.SomeEvent -= value ; } } }",How to deal with Lack of Multiple Inheritance in C # "C_sharp : With this code : Auxiliar class : I 'm getting this list of applications ( Window text - Rect bounds ) : My current not minimized windows are Visual Studio and two Edge windows ( with several tabs each ) . I can understand the fact that only one Edge item was listing the title of the current page . Because I recently recovered from a crash and only that page was loaded.My questions are : Why are my closed Windows Store apps being listed ? ( and even twice ) Why are my Edge tabs being listed ? How can I filter the Edge tabs and the closed Windows Store apps ? EDIT : By `` Filter '' : Only retrieve the apps with visible window . With my use case , only 3 windows are visible.I tried to get the WsStyle and WsEXStyle of each window to compare , but I could n't find any difference.The method IsWindowVisible ( ) fails filter out the Windows Store apps that are not visible . internal static List < DetectedWindow > EnumerateWindows ( ) { var shellWindow = GetShellWindow ( ) ; var windows = new List < DetectedWindow > ( ) ; EnumWindows ( delegate ( IntPtr handle , int lParam ) { if ( handle == shellWindow ) return true ; if ( ! IsWindowVisible ( handle ) ) return true ; if ( IsIconic ( handle ) ) return true ; var length = GetWindowTextLength ( handle ) ; if ( length == 0 ) return true ; var builder = new StringBuilder ( length ) ; GetWindowText ( handle , builder , length + 1 ) ; GetWindowRect ( handle , out Rect rect ) ; windows.Add ( new DetectedWindow ( handle , rect.ToRect ( ) , builder.ToString ( ) ) ) ; return true ; } , IntPtr.Zero ) ; return windows ; } public class DetectedWindow { public IntPtr Handle { get ; private set ; } public Rect Bounds { get ; private set ; } public string Name { get ; private set ; } public DetectedWindow ( IntPtr handle , Rect bounds , string name ) { Handle = handle ; Bounds = bounds ; Name = name ; } } Microsoft Visual Studio - -8 ; -8 ; 1936 ; 1056Microsoft Edge - 0 ; 77 ; 1920 ; 963EnumWindows - Stack Overflow and 7 more pages ‎- Microsoft Edge - -8 ; -8 ; 1936 ; 1056Microsoft Edge - 0 ; 77 ; 1920 ; 963Microsoft Edge - 0 ; 77 ; 1920 ; 963Microsoft Edge - 0 ; 0 ; 1920 ; 1080Microsoft Edge - 0 ; 0 ; 1920 ; 1080Microsoft Edge - 0 ; 8 ; 1920 ; 1040Microsoft Edge - 0 ; 85 ; 1920 ; 963Microsoft Edge - 150 ; 79 ; 1532 ; 42Microsoft Edge - 0 ; 85 ; 1920 ; 963Microsoft Edge - 0 ; 77 ; 1920 ; 963Microsoft Edge - 0 ; 85 ; 1920 ; 963Microsoft Edge - 0 ; 213 ; 1920 ; 964Microsoft Edge - 0 ; 0 ; 1920 ; 1080Microsoft Edge - 484 ; 208 ; 952 ; 174Microsoft Edge - 0 ; 84 ; 1920 ; 964Microsoft Edge - 0 ; 84 ; 1920 ; 964Microsoft Edge - 0 ; 84 ; 1920 ; 964 Microsoft Edge - 0 ; 0 ; 1920 ; 1080Mail - 0 ; 32 ; 1356 ; 693Mail - 278 ; 252 ; 1372 ; 733OneNote - 0 ; 8 ; 1920 ; 1040My notes - OneNote - -8 ; -8 ; 1936 ; 1056Photos - 0 ; 32 ; 1920 ; 1008Photos - -8 ; -8 ; 1936 ; 1056Skype - 0 ; 40 ; 1920 ; 1008Skype - -8 ; -8 ; 1936 ; 1056Store - 0 ; 40 ; 1920 ; 1008Store - -8 ; -8 ; 1936 ; 1056Movies & TV - 0 ; 0 ; 1920 ; 1080Movies & TV - -8 ; -8 ; 1936 ; 1056Groove Music - 0 ; 32 ; 1466 ; 712Groove Music - -7 ; 3 ; 1372 ; 733Settings - 0 ; 40 ; 1920 ; 1008Settings - -8 ; -8 ; 1936 ; 1056Windows Shell Experience Host - 0 ; 0 ; 1920 ; 1080",EnumWindows returns closed Windows Store applications "C_sharp : I 'm fooling around trying to learn the ins an outs of LINQ . I want to convert the following query ( which is working correctly ) from query syntax to method syntax , but I ca n't seem to get it right . Can anyone show me the correct way to accomplish that ? var logQuery = from entry in xDoc.Descendants ( `` logentry '' ) where ( entry.Element ( `` author '' ) .Value.ToLower ( ) .Contains ( matchText ) || entry.Element ( `` msg '' ) .Value.ToLower ( ) .Contains ( matchText ) || entry.Element ( `` paths '' ) .Value.ToLower ( ) .Contains ( matchText ) || entry.Element ( `` revision '' ) .Value.ToLower ( ) .Contains ( matchText ) ) select new { Revision = entry.Attribute ( `` revision '' ) .Value , Author = entry.Element ( `` author '' ) .Value , CR = LogFormatter.FormatCR ( entry.Element ( `` msg '' ) .Value ) , Date = LogFormatter.FormatDate ( entry.Element ( `` date '' ) .Value ) , Message = LogFormatter.FormatComment ( entry.Element ( `` msg '' ) .Value ) , ET = LogFormatter.FormatET ( entry.Element ( `` msg '' ) .Value ) , MergeFrom = LogFormatter.FormatMergeFrom ( entry.Element ( `` msg '' ) .Value ) , MergeTo = LogFormatter.FormatMergeTo ( entry.Element ( `` msg '' ) .Value ) } ;",How to convert query syntax to method syntax "C_sharp : I noticed that quite a lot of code is using following code snippet to invoke event handler . Why does it assign Handler to a local variable before invoking other than invoking the event on Handler directly . Is there any difference between those ? Public event EventHandler Handler ; Protected void OnEvent ( ) { var handler = this.Handler ; If ( null ! =handler ) { handler ( this , new EventArgs ( ) ) ; } }",Assign EventHandler to a local variable before invoking "C_sharp : I am working on some XAML where I have a RibbonComboBox : When it displays , it shows the items horizontally rather than vertically as I expected : How do I style it to place the items vertically ? < RibbonComboBox SelectionBoxWidth= '' 150 '' Grid.Row= '' 0 '' > < RibbonGallery SelectedItem= '' { Binding SelectedUtilityRun , Mode=TwoWay } '' > < RibbonGalleryCategory ItemsSource= '' { Binding UtilityRunLabels } '' / > < /RibbonGallery > < /RibbonComboBox >",WPF RibbonComboBox items listed vertically "C_sharp : Using SimpleInjector , I am trying to register an entity that depends on values retrieved from another registered entity . For example : Settings - Reads settings values that indicate the type of SomeOtherService the app needs.SomeOtherService - Relies on a value from Settings to be instantiated ( and therefore registered ) .Some DI containers allow registering an object after resolution of another object . So you could do something like the pseudo code below : SimpleInjector does not allow registration after resolution . Is there some mechanism in SimpleInjector that allows the same architecture ? container.Register < ISettings , Settings > ( ) ; var settings = container.Resolve < ISettings > ( ) ; System.Type theTypeWeWantToRegister = Type.GetType ( settings.GetTheISomeOtherServiceType ( ) ) ; container.Register ( ISomeOtherService , theTypeWeWantToRegister ) ;",SimpleInjector - Register Object that depends on values from another registered object "C_sharp : I have a .Net 4.5 app that is moving to WPF-based RxUI ( kept up to date , 6.0.3 as of this writing ) . I have a text field that should function as a filter field with the fairly common throttle etc . stuff that was part of the reason for going reactive in the first place.Here is the relevant part of my class.I unit test this using Xunit.net with Resharper 's test runner . I create some test data and run this test : I put a debug statement on the Subscribe action for my FilterText config in the constructor of the class , and it gets called once for each packet item at startup , but it never gets called after I change the FilterText property.Btw , the constructor for the test class contains the following statement to make threading magic work : My problem is basically that the Refresh ( ) method on my view never gets called after I change the FilterText , and I ca n't see why not . Is this a simple problem with my code ? Or is this a problem with a CollectionViewSource thing running in a unit testing context rather than in a WPF context ? Should I abandon this idea and rather have a ReactiveList property that I filter manually whenever a text change is triggered ? Note : This works in the application - the FilterText triggers the update there . It just does n't happen in the unit test , which makes me wonder whether I am doing it wrong.EDIT : As requested , here are the relevant bits of XAML - this is for now just a simple window with a textbox and a datagrid.The TextBox : The datagrid : If anything else is relevant/needed , let me know ! EDIT 2 : Paul Betts recommends not doing the SynchronizationContext setup in the test constructor like I do , probably for very valid reasons . However , I do this because of the way another viewmodel ( FileViewModel ) works - it needs to wait for a MessageBus message to know that packet processing is complete . This is something that I am working actively on trying to avoid - I know the MessageBus is a very convenient bad idea . : ) But this is the cause for the SyncContext stuff . The method that creates the test viewmodel looks like this : I realize this is bad design , so please do n't yell . ; ) But I am taking a lot of legacy code here and moving it into RxUI based MVVM - I ca n't do it all and end up with a perfect design just yet , which is why I am getting unit tests in place for all this stuff so that I can do Rambo refactoring later . : ) public class PacketListViewModel : ReactiveObject { private readonly ReactiveList < PacketViewModel > _packets ; private PacketViewModel _selectedPacket ; private readonly ICollectionView _packetView ; private string _filterText ; /// < summary > /// Gets the collection of packets represented by this object /// < /summary > public ICollectionView Packets { get { if ( _packets.Count == 0 ) RebuildPacketCollection ( ) ; return _packetView ; } } public string FilterText { get { return _filterText ; } set { this.RaiseAndSetIfChanged ( ref _filterText , value ) ; } } public PacketViewModel SelectedPacket { get { return _selectedPacket ; } set { this.RaiseAndSetIfChanged ( ref _selectedPacket , value ) ; } } public PacketListViewModel ( IEnumerable < FileViewModel > files ) { _packets = new ReactiveList < PacketViewModel > ( ) ; _packetView = CollectionViewSource.GetDefaultView ( _packets ) ; _packetView.Filter = PacketFilter ; _filterText = String.Empty ; this.WhenAnyValue ( x = > x.FilterText ) .Throttle ( TimeSpan.FromMilliseconds ( 300 ) /* , RxApp.TaskpoolScheduler*/ ) .DistinctUntilChanged ( ) .ObserveOnDispatcher ( ) .Subscribe ( _ = > _packetView.Refresh ( ) ) ; } private bool PacketFilter ( object item ) { // Filter logic } private void RebuildPacketCollection ( ) { // Rebuild packet list from data source _packetView.Refresh ( ) ; } } [ Fact ] public void FilterText_WhenThrottleTimeoutHasPassed_FiltersProperly ( ) { new TestScheduler ( ) .With ( s = > { // Arrange var fvm = GetLoadedFileViewModel ( ) ; var sut = new PacketListViewModel ( fvm ) ; var lazy = sut.Packets ; // Act sut.FilterText = `` Call '' ; s.AdvanceToMs ( 301 ) ; // Assert var res = sut.Packets.OfType < PacketViewModel > ( ) .ToList ( ) ; sut.Packets.OfType < PacketViewModel > ( ) .Count ( ) .Should ( ) .Be ( 1 , `` only a single packet should match the filter '' ) ; } ) ; } SynchronizationContext.SetSynchronizationContext ( new SynchronizationContext ( ) ) ; < TextBox Name= '' FilterTextBox '' Grid.Column= '' 1 '' VerticalAlignment= '' Center '' Text= '' { Binding FilterText , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' / > < DataGrid ItemsSource= '' { Binding Path=Packets } '' Name= '' PacketDataGrid '' SelectedItem= '' { Binding SelectedPacket } '' AutoGenerateColumns= '' False '' EnableRowVirtualization= '' True '' SelectionMode= '' Single '' SelectionUnit= '' FullRow '' CanUserAddRows= '' False '' CanUserResizeRows= '' False '' > < DataGrid.Columns > ... private FileViewModel GetLoadedFileViewModel ( ) { var mre = new ManualResetEventSlim ( ) ; var fvm = new FileViewModel ( new MockDataLoader ( ) ) ; MessageBus.Current .Listen < FileUpdatedPacketListMessage > ( fvm.MessageToken.ToString ( ) ) .Subscribe ( msg = > mre.Set ( ) ) ; fvm.LoadFile ( `` irrelevant.log '' ) ; mre.Wait ( 500 ) ; return fvm ; }",ReactiveUI vs. ICollectionView "C_sharp : Im doing a project where i have to read the datas from a .txt file and then insert each line into a table using query.Now for example the contents of the text file would be 111111111x222222222x333333333xand so on.Now as you can see that the alternate row is almost repetitive so i would like to remove alternate rows so that the available data becomes 111112222233333and then process the rest of my codes.Is there any way i can do that ? So far i have been using the Array list to get thisThe basic idea is to delete the alternate rows wether it be from the index of the arraylist of from the text file . using ( StreamReader sr = new StreamReader ( Server.MapPath ( `` 03122013114450.txt '' ) , true ) ) { string txtValues = sr.ReadToEnd ( ) ; string [ ] txtValuesArray1 = Regex.Split ( txtValues , `` \r\n '' ) ; ArrayList array = new ArrayList ( ) ; foreach ( string value in txtValuesArray1 ) { array.Add ( value ) ; } for ( int i = 0 ; i < array.Count ; i++ ) { if ( array.Count % 2 ! = 0 ) array.RemoveAt ( i + 2 ) ; else array.RemoveAt ( i + 1 ) ; } }",Deleting alternate rows from the text file using c # "C_sharp : I 'm getting the following error message : string or binary data would be truncatedI 've tried increasing the column size but no luck , I 've doubled checked by code but cant seem to find any issues . Its during an insert : Here is my table definition code : Customer Class SqlCommand insert = new SqlCommand ( @ '' INSERT into orderDetails ( orderID , Name , Phone , Mobile , Email , DelName , DelRoad , DelTown , DelCity , DelCounty , DelPostCode , BilName , BilRoad , BilTown , BilCity , BilCounty , BilPostCode ) values ( @ orderID , @ Name , @ Phone , @ Mobile , @ Email , @ DelName , @ DelRoad , @ DelTown , @ DelCity , @ DelCounty , @ DelPostCode , @ BilName , @ BilRoad , @ BilTown , @ BilCity , @ BilCounty , @ BilPostCode ) '' , connection ) ; insert.Parameters.AddWithValue ( `` @ orderID '' , ID ) ; insert.Parameters.AddWithValue ( `` @ Name '' , name ) ; insert.Parameters.AddWithValue ( `` @ Phone '' , customer.Phone ) ; insert.Parameters.AddWithValue ( `` @ Mobile '' , customer.Mobile ) ; insert.Parameters.AddWithValue ( `` @ Email '' , customer.Email ) ; insert.Parameters.AddWithValue ( `` @ DelName '' , customer.DelName ) ; insert.Parameters.AddWithValue ( `` @ DelRoad '' , customer.DelRoad ) ; insert.Parameters.AddWithValue ( `` @ DelTown '' , customer.DelTown ) ; insert.Parameters.AddWithValue ( `` @ DelCity '' , customer.DelCity ) ; insert.Parameters.AddWithValue ( `` @ DelCounty '' , customer.DelCounty ) ; insert.Parameters.AddWithValue ( `` @ DelPostCode '' , customer.DelPostCode ) ; insert.Parameters.AddWithValue ( `` @ BilName '' , customer.BilName ) ; insert.Parameters.AddWithValue ( `` @ BilRoad '' , customer.BilRoad ) ; insert.Parameters.AddWithValue ( `` @ BilTown '' , customer.BilTown ) ; insert.Parameters.AddWithValue ( `` @ BilCity '' , customer.BilCity ) ; insert.Parameters.AddWithValue ( `` @ BilCounty '' , customer.BilCounty ) ; insert.Parameters.AddWithValue ( `` @ BilPostCode '' , customer.BilPostCode ) ; insert.ExecuteNonQuery ( ) ; CREATE TABLE [ dbo ] . [ orderDetails ] ( [ orderID ] INT NOT NULL , [ Name ] NCHAR ( 100 ) NULL , [ Phone ] NCHAR ( 100 ) NULL , [ Mobile ] NCHAR ( 15 ) NULL , [ Email ] NCHAR ( 15 ) NULL , [ DelName ] NCHAR ( 100 ) NULL , [ DelRoad ] NCHAR ( 100 ) NULL , [ DelTown ] NCHAR ( 100 ) NULL , [ DelCity ] NCHAR ( 100 ) NULL , [ DelCounty ] NCHAR ( 100 ) NULL , [ DelPostCode ] NCHAR ( 100 ) NULL , [ BilName ] NCHAR ( 100 ) NULL , [ BilRoad ] NCHAR ( 100 ) NULL , [ BilTown ] NCHAR ( 100 ) NULL , [ BilCity ] NCHAR ( 100 ) NULL , [ BilCounty ] NCHAR ( 100 ) NULL , [ BilPostCode ] NCHAR ( 100 ) NULL , PRIMARY KEY CLUSTERED ( [ orderID ] ASC ) ) ; public class Customer { public string FirstName { get ; set ; } public string LastName { get ; set ; } public string Phone { get ; set ; } public string Mobile { get ; set ; } public string Email { get ; set ; } public string DelName { get ; set ; } public string DelRoad { get ; set ; } public string DelTown { get ; set ; } public string DelCity { get ; set ; } public string DelCounty { get ; set ; } public string DelPostCode { get ; set ; } public string BilName { get ; set ; } public string BilRoad { get ; set ; } public string BilTown { get ; set ; } public string BilCity { get ; set ; } public string BilCounty { get ; set ; } public string BilPostCode { get ; set ; } public bool sameasDel { get ; set ; } }",string or binary data would be truncated error message "C_sharp : Generally , Constructor is the very first thing to be executed in class when it 's instantiated.But in following case , A member methods of the class are executed first & then the constructor.Why is it so ? A Code Scenario : namespace AbsPractice { class Program { static void Main ( string [ ] args ) { SavingsCustomer sc = new SavingsCustomer ( ) ; CorporateCustomer cc = new CorporateCustomer ( ) ; } } public abstract class Customer { protected Customer ( ) { Console.WriteLine ( `` Constructor of Abstract Customer '' ) ; Print ( ) ; } protected abstract void Print ( ) ; } public class SavingsCustomer : Customer { public SavingsCustomer ( ) { Console.WriteLine ( `` Constructor of SavingsCustomer '' ) ; } protected override void Print ( ) { Console.WriteLine ( `` Print ( ) Method of SavingsCustomer '' ) ; } } public class CorporateCustomer : Customer { public CorporateCustomer ( ) { Console.WriteLine ( `` Constructor of CorporateCustomer '' ) ; } protected override void Print ( ) { Console.WriteLine ( `` Print ( ) Method of CorporateCustomer '' ) ; } } }",Why a member method of class is called before the Constructor "C_sharp : I have a WPF app which may or may not be started with command-line args . I used to have my composition root in the OnStartup ( StartupEventArgs e ) method in the App.xaml code-behind , but this was causing app shutdown issues so I turned App.xaml into a `` Page '' ( rather than `` App Definition '' ) and wrote my own Program class containing my own app entry point , which would become my new composition root location.Since that change , I 've been unable to get the app to start , Ninject ca n't seem to resolve the app 's primary object ( or could it be one of its dependencies ? ) .This exception is making me waste lots of time , and the stack trace is all Ninject-internal , I do n't know what to fix in my code , the way I 'm binding the type that 's now causing this exception has not changed lately : Here 's the Main method / app entry point : The NinjectModule binds IInstaller to such or such implementation , depending on supplied command-line arguments ( e.g . SilentInstaller when QuietInterfaceArgument is specified , ManualInstaller when it 's not , etc . ) .Usually Ninject gives very useful and detailed exception messages - when it 's an ActivationException life is good . But this InvalidCastException leaves me clueless , I 'm not the one performing the invalid cast , and I do n't even know what types are being involved . I just know that I might have written some code that Ninject does n't like , and that maybe it has something to do with the way I 'm binding IInstaller to its implementations , but if I comment-out the `` branching '' part of the NinjectModule to force-bind the specific implementation ( ManualInstaller ) that I 'm after , it still fails with this InvalidCastException.The implementation 's constructor : The corresponding binding code ( rest of dependencies are already bound and there 's no ActivationException so not sure how relevant this is to my issue ) : Do n't hesitate to let me know if anything else is needed to find out what 's going on ... EDITResolving the installer 's dependencies individually yields more information : So I can at least narrow it down to one specific dependency of the type I 'm trying to resolve : the problem is either with the View , or with its sole dependency , the ViewModel . So I did this : So apparently it 's the IProcessHelper implementation that 's problematic - again : And now I no longer get the InvalidCastException.Here 's the problematic class ' constructor and fields : And how the NinjectModule binds it : ** RE-EDIT **With the help of @ jure 's comment , I 've found that the type of ProcessTimeoutSeconds in Properties.Settings.Default is actually set to string - when obviously it wants an int . Bang on ! at DynamicInjector54d92ac63a2e47fda5ffbcc19b9942a9 ( Object [ ] ) at Ninject.Activation.Providers.StandardProvider.Create ( IContext context ) at Ninject.Activation.Context.Resolve ( ) at Ninject.KernelBase. < > c__DisplayClass10. < Resolve > b__c ( IBinding binding ) at System.Linq.Enumerable.WhereSelectEnumerableIterator ` 2.MoveNext ( ) at System.Linq.Enumerable.SingleOrDefault [ TSource ] ( IEnumerable ` 1 source ) at Ninject.Planning.Targets.Target ` 1.GetValue ( Type service , IContext parent ) at Ninject.Planning.Targets.Target ` 1.ResolveWithin ( IContext parent ) at Ninject.Activation.Providers.StandardProvider.GetValue ( IContext context , ITarget target ) at Ninject.Activation.Providers.StandardProvider. < > c__DisplayClass4. < Create > b__2 ( ITarget target ) at System.Linq.Enumerable.WhereSelectArrayIterator ` 2.MoveNext ( ) at System.Linq.Buffer ` 1..ctor ( IEnumerable ` 1 source ) at System.Linq.Enumerable.ToArray [ TSource ] ( IEnumerable ` 1 source ) at Ninject.Activation.Providers.StandardProvider.Create ( IContext context ) at Ninject.Activation.Context.Resolve ( ) at Ninject.KernelBase. < > c__DisplayClass10. < Resolve > b__c ( IBinding binding ) at System.Linq.Enumerable.WhereSelectEnumerableIterator ` 2.MoveNext ( ) at System.Linq.Enumerable.SingleOrDefault [ TSource ] ( IEnumerable ` 1 source ) at Ninject.Planning.Targets.Target ` 1.GetValue ( Type service , IContext parent ) at Ninject.Planning.Targets.Target ` 1.ResolveWithin ( IContext parent ) at Ninject.Activation.Providers.StandardProvider.GetValue ( IContext context , ITarget target ) at Ninject.Activation.Providers.StandardProvider. < > c__DisplayClass4. < Create > b__2 ( ITarget target ) at System.Linq.Enumerable.WhereSelectArrayIterator ` 2.MoveNext ( ) at System.Linq.Buffer ` 1..ctor ( IEnumerable ` 1 source ) at System.Linq.Enumerable.ToArray [ TSource ] ( IEnumerable ` 1 source ) at Ninject.Activation.Providers.StandardProvider.Create ( IContext context ) at Ninject.Activation.Context.Resolve ( ) at Ninject.KernelBase. < > c__DisplayClass10. < Resolve > b__c ( IBinding binding ) at System.Linq.Enumerable.WhereSelectEnumerableIterator ` 2.MoveNext ( ) at System.Linq.Enumerable.SingleOrDefault [ TSource ] ( IEnumerable ` 1 source ) at Ninject.Planning.Targets.Target ` 1.GetValue ( Type service , IContext parent ) at Ninject.Planning.Targets.Target ` 1.ResolveWithin ( IContext parent ) at Ninject.Activation.Providers.StandardProvider.GetValue ( IContext context , ITarget target ) at Ninject.Activation.Providers.StandardProvider. < > c__DisplayClass4. < Create > b__2 ( ITarget target ) at System.Linq.Enumerable.WhereSelectArrayIterator ` 2.MoveNext ( ) at System.Linq.Buffer ` 1..ctor ( IEnumerable ` 1 source ) at System.Linq.Enumerable.ToArray [ TSource ] ( IEnumerable ` 1 source ) at Ninject.Activation.Providers.StandardProvider.Create ( IContext context ) at Ninject.Activation.Context.Resolve ( ) at Ninject.KernelBase. < > c__DisplayClass10. < Resolve > b__c ( IBinding binding ) at System.Linq.Enumerable.WhereSelectEnumerableIterator ` 2.MoveNext ( ) at System.Linq.Enumerable. < CastIterator > d__b1 ` 1.MoveNext ( ) at System.Linq.Enumerable.Single [ TSource ] ( IEnumerable ` 1 source ) at Ninject.ResolutionExtensions.Get [ T ] ( IResolutionRoot root , IParameter [ ] parameters ) at MyProgram.Program.Main ( String [ ] args ) in C : \Dev\MyProject\MyProject.WinPresentation\Program.cs : ligne 40at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.RunInternal ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean preserveSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) [ STAThread ] public static void Main ( string [ ] args ) { var module = new MyAppNinjectModule ( args ) ; var kernel = new StandardKernel ( module ) ; var argsHelper = module.CommandLineArgs ; var logProvider = kernel.Get < ILogProvider > ( ) ; var logger = logProvider.GetLogger ( typeof ( Program ) .Name ) ; if ( argsHelper.LoggingDisabledArgument.IsSpecified ( ) ) logProvider.DisableLogging ( ) ; logger.Info ( log.LogAppStart ) ; var installer = kernel.Get < IInstaller > ( ) ; // > > > InvalidCastException here if ( argsHelper.QuietInterfaceArgument.IsSpecified ( ) ) { // running with -quiet command-line switch : just execute and exit . installer.Execute ( ) ; } else { // instantiate a new App object ( WPF ) , and run it . // installer.Execute ( ) may or may not be executed , depending on user actions . var app = new App ( installer ) ; app.Run ( ) ; } } public ManualInstaller ( IView < MainWindowViewModel > view , IProcessHelper processHelper , ISettingsHelper settingsHelper , ILogProvider logProvider , ISetupBootstrapper installer , bool notifySuccess ) : base ( notifySuccess , processHelper , settingsHelper , logProvider , installer ) var msg = string.Empty ; if ( CommandLineArgs.CompletionMessageArgument.IsSpecified ( ) ) msg = CommandLineArgs.CompletionMessageArgument.ParameterValue ( ) ; Bind < MainWindowViewModel > ( ) .ToSelf ( ) .WithConstructorArgument ( `` completionMessage '' , msg ) ; Bind < IView < MainWindowViewModel > > ( ) .To < MainWindow > ( ) ; Bind < IInstaller > ( ) .To < ManualInstaller > ( ) .WithConstructorArgument ( `` notifySuccess '' , notifySuccess ) ; // resolve installer dependencies : var view = kernel.Get < IView < MainWindowViewModel > > ( ) ; // > > > InvalidCastException herevar processHelper = kernel.Get < IProcessHelper > ( ) ; var settingsHelper = kernel.Get < ISettingsHelper > ( ) ; var bootstrapper = kernel.Get < ISetupBootstrapper > ( ) ; var installer = new ManualInstaller ( view , processHelper , settingsHelper , logProvider , bootstrapper , true ) ; // resolve ViewModel dependencies : var processHelper = kernel.Get < IProcessHelper > ( ) ; // > > > InvalidCastException herevar settingsHelper = kernel.Get < ISettingsHelper > ( ) ; var messenger = kernel.Get < INetworkMessenger > ( ) ; var factory = kernel.Get < IBuildServerFactory > ( ) ; var dialogs = kernel.Get < ICommonDialogs > ( ) ; // resolve ProcessHelper dependencies : var processWrapper = kernel.Get < IProcessWrapper > ( ) ; var wmiWrapper = kernel.Get < IWindowsManagementInstrumentationWrapper > ( ) ; var helper = new ProcessHelper ( processWrapper , wmiWrapper , logProvider , 300 ) ; private readonly ILogProvider _logProvider ; private readonly IProcessWrapper _process ; private readonly IWindowsManagementInstrumentationWrapper _wmi ; public int TimeoutSeconds { get ; private set ; } public ProcessHelper ( IProcessWrapper process , IWindowsManagementInstrumentationWrapper wmiWrapper , ILogProvider logProvider , int timeout ) { _logProvider = logProvider ; _process = process ; _wmi = wmiWrapper ; TimeoutSeconds = timeout ; } Bind < IProcessHelper > ( ) .To < ProcessHelper > ( ) .WithConstructorArgument ( `` timeout '' , Properties.Settings.Default.ProcessTimeoutSeconds ) ;",InvalidCastException at kernel.Get < type > "C_sharp : How can I stop a System.Windows.Forms.SaveFileDialog from prompting twice to replace a selected file , and instead prompt only once ? Either I 'm missing something , there 's something wrong with my install , or the default behaviour is just dumb.I 'm not doing anything special at all , this is in an empty Windows Forms project , targeting .NET Framework 4.7.2.Edit : Added full Program.cs var saveFileDialog = new SaveFileDialog ( ) ; saveFileDialog.ShowDialog ( ) ; // User selects file and clicks `` Save '' within the dialog using System ; using System.Collections.Generic ; using System.Linq ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace WindowsFormsApp1 { static class Program { /// < summary > /// The main entry point for the application . /// < /summary > [ STAThread ] static void Main ( ) { Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; var saveFileDialog = new SaveFileDialog ( ) ; saveFileDialog.ShowDialog ( ) ; } } }",How do I prevent a SaveFileDialog from prompting twice to replace/overwrite a file ? "C_sharp : I have an ASP Calendar Page that pulls an event list from a database . The issue that I am having is that data is shown for the current month but not for the previous and next months when I click on the next and previous months . Does ASP Calendar reload the entire page when a different month is clicked or does it act as a query string property ? Here is the code that I am currently using : protected DataSet dsEvents ; protected void Page_Load ( object sender , EventArgs e ) { Calendar1.FirstDayOfWeek = FirstDayOfWeek.Sunday ; Calendar1.NextPrevFormat = NextPrevFormat.FullMonth ; Calendar1.TitleFormat = TitleFormat.Month ; Calendar1.ShowGridLines = true ; Calendar1.DayStyle.HorizontalAlign = HorizontalAlign.Left ; Calendar1.DayStyle.VerticalAlign = VerticalAlign.Top ; Calendar1.OtherMonthDayStyle.BackColor = System.Drawing.Color.LightGray ; Calendar1.VisibleDate = DateTime.Today ; FillEventDataset ( ) ; GetFirstDayOfNextMonth ( ) ; if ( ! IsPostBack ) { Calendar1.VisibleDate = DateTime.Today ; FillEventDataset ( ) ; GetFirstDayOfNextMonth ( ) ; } } protected DateTime GetFirstDayOfNextMonth ( ) { int monthNumber , yearNumber ; if ( Calendar1.VisibleDate.Month == 12 ) { monthNumber = 1 ; yearNumber = Calendar1.VisibleDate.Year + 1 ; } else { monthNumber = Calendar1.VisibleDate.Month + 1 ; yearNumber = Calendar1.VisibleDate.Year ; } DateTime lastDate = new DateTime ( yearNumber , monthNumber , 1 ) ; return lastDate ; } protected void FillEventDataset ( ) { DateTime firstDate = new DateTime ( Calendar1.VisibleDate.Year , Calendar1.VisibleDate.Month , 1 ) ; DateTime lastDate = GetFirstDayOfNextMonth ( ) ; dsEvents = GetSelectedMonthData ( firstDate , lastDate ) ; } protected DataSet GetSelectedMonthData ( DateTime firstDate , DateTime lastDate ) { DataSet dsMonth = new DataSet ( ) ; using ( SqlConnection conn = new SqlConnection ( connectionString ) ) { SqlCommand comm = new SqlCommand ( `` SELECT EventDate , EventLocation , EventSubject , EventStart FROM EventList WHERE EventDate > = @ FirstDate AND EventDate < = @ LastDate '' , conn ) ; comm.CommandType = CommandType.Text ; comm.Parameters.AddWithValue ( `` @ FirstDate '' , firstDate ) ; comm.Parameters.AddWithValue ( `` @ LastDate '' , lastDate ) ; conn.Open ( ) ; SqlDataAdapter sqlDataAdapter = new SqlDataAdapter ( comm ) ; try { sqlDataAdapter.Fill ( dsMonth ) ; } finally { conn.Close ( ) ; } } return dsMonth ; } protected void Calendar1_DayRender ( object sender , DayRenderEventArgs e ) { e.Day.IsSelectable = false ; e.Cell.ForeColor = System.Drawing.Color.Black ; if ( e.Day.IsOtherMonth ) { e.Cell.Visible = true ; e.Cell.Text = `` '' ; } DateTime nextEvent ; String nextLocation ; String nextSubject ; String nextStart ; if ( dsEvents ! = null ) { foreach ( DataRow dr in dsEvents.Tables [ 0 ] .Rows ) { nextEvent = ( DateTime ) dr [ `` EventDate '' ] ; nextLocation = dr [ `` EventLocation '' ] .ToString ( ) ; nextSubject = dr [ `` EventSubject '' ] .ToString ( ) ; nextStart = dr [ `` EventStart '' ] .ToString ( ) ; if ( nextEvent == e.Day.Date ) { Literal literal1 = new Literal ( ) ; literal1.Text = `` < br/ > '' ; e.Cell.Controls.Add ( literal1 ) ; Label label1 = new Label ( ) ; label1.Text = nextStart.ToString ( ) ; label1.Font.Size = new FontUnit ( FontSize.Small ) ; e.Cell.Controls.Add ( label1 ) ; Literal literal2 = new Literal ( ) ; literal2.Text = `` & nbsp ; & nbsp ; '' ; e.Cell.Controls.Add ( literal2 ) ; Label label2 = new Label ( ) ; label2.Text = nextSubject.ToString ( ) ; label2.Font.Size = new FontUnit ( FontSize.Small ) ; e.Cell.Controls.Add ( label2 ) ; Literal literal3 = new Literal ( ) ; literal3.Text = `` & nbsp ; & nbsp ; '' ; e.Cell.Controls.Add ( literal3 ) ; Label label3 = new Label ( ) ; label3.Text = nextLocation.ToString ( ) ; label3.Font.Size = new FontUnit ( FontSize.Small ) ; e.Cell.Controls.Add ( label3 ) ; } } } } protected void Calendar1_VisibleMonthChanged ( object sender , MonthChangedEventArgs e ) { GetFirstDayOfNextMonth ( ) ; FillEventDataset ( ) ; }",ASP Calendar not showing data for previous and next month C_sharp : Hello suddenly VS2010 has started formatting my if statements in a way that I do n't want and I do n't know how to turn it of..I Used to format if statements without accolades like this.But now VS2010 formats that as follows all the time.I Do n't want this and it drives me nuts . I Do n't have any plugins installed.Can anybody help me ? Where I can adjust this setting ? if ( true ) DoThis ( ) ; if ( true ) DoThis ( ) ;,If statements suddenly get formatted on next line by Visual Studio 2010 "C_sharp : Maybe it is a silly question.The Task class is declared this way : The IAsyncResult interface is declared like this : But the member AsyncWaitHandle does not exist in the Task class or instances . This code : Raises this compilation error : Error 1 'System.Threading.Tasks.Task ' does not contain a definition for 'AsyncWaitHandle ' and no extension method 'AsyncWaitHandle ' accepting a first argument of type 'System.Threading.Tasks.Task ' could be found ( are you missing a using directive or an assembly reference ? ) However , this not only compiles : But also works , since the member exists . What is this sorcery ? It is a compiler trick or is it being hidden in another way ? Cheers . public class Task : IThreadPoolWorkItem , IAsyncResult , IDisposable public interface IAsyncResult { object AsyncState { get ; } WaitHandle AsyncWaitHandle { get ; } bool CompletedSynchronously { get ; } bool IsCompleted { get ; } } System.Threading.Tasks.Task t = new System.Threading.Tasks.Task ( ( ) = > { } ) ; t.AsyncWaitHandle.ToString ( ) ; System.IAsyncResult t = new System.Threading.Tasks.Task ( ( ) = > { } ) ; t.AsyncWaitHandle.ToString ( ) ;","How come Task implements IAsyncResult , but does not contain the AsyncWaitHandle member ?" "C_sharp : I have used Observable.Using with methods that return an IDisposable in the way : But how would we proceed when the stream is created asynchronously ? Like in this : This does n't compile because it says that s is Task < Stream > instead a Stream.What 's the deal ? Observable.Using ( ( ) = > new Stream ( ) , s = > DoSomething ( s ) ) ; Observable.Using ( async ( ) = > await CreateStream ( ) , s = > DoSomething ( s ) ) ; async Task < Stream > CreateStream ( ) { ... } DoSomething ( Stream s ) { ... }",Observable.Using with async Task "C_sharp : I have been playing around with Exceptions to learn more about how I should use them properly . So far , I know that throw keeps the original stack trace ; throw new CustomException ( ... ) is generally used when wanting to add more information about the exception that took place or add/change the message , or even change the type of Exception itself ; and throw ex should never ever be used , unless I want to lose the original stack trace.So I wrote a small program where I could catch and rethrow an exception several times while adding something to the original message.Where GoodException is a custom exception implemented correctly.I 'm expecting the console to display something like this : But instead I 'm getting this : For some reason it only goes as far as the second call . Even though I 'm passing the caught exception as an InnerException , the stack trace is still lost . I 'm aware that if I just wrote throw instead of throwing a new exception , I could keep the original stack trace , but if I do that I wo n't be able to change the original message ( which was the whole point of this exercise ) . So my question is , what can I do to change the Exception message AND keep the original stack trace the whole way ? EDIT : Since an exception should not be used logic control and only caught once , the proper way to keep the original stack trace AND show the new message is to wrap the FourthCall in a try/catch ( where the new Exception with its message is generated ) , and catch it only once all the way up in the FirstCall . public class Sample { static void Main ( string [ ] args ) { new Tester ( ) .FirstCall ( ) ; } } public class Tester { public void FirstCall ( ) { try { SecondCall ( ) ; } catch ( Exception e ) { Console.WriteLine ( e.StackTrace ) ; Console.WriteLine ( e.Message ) ; } } public void SecondCall ( ) { try { ThirdCall ( ) ; } catch ( GoodException ex ) { throw new Exception ( ex.Message , ex ) ; } } public void ThirdCall ( ) { try { FourthCall ( ) ; } catch ( ArithmeticException ae ) { throw new GoodException ( `` Arithmetic mistake : `` + ae.Message , ae ) ; } } public void FourthCall ( ) { int d = 0 ; int x = 10 / d ; } } at PlayingWithExceptions.Tester.FourthCall ( ) in d : \Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs : line 67 at PlayingWithExceptions.Tester.ThirdCall ( ) in d : \Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs : line 59 at PlayingWithExceptions.Tester.SecondCall ( ) in d : \Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs : line 41 at PlayingWithExceptions.Tester.FirstCall ( ) in d : \Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs : line 25Arithmetic mistake : Attempted to divide by zero . at PlayingWithExceptions.Tester.SecondCall ( ) in d : \Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs : line 41 at PlayingWithExceptions.Tester.FirstCall ( ) in d : \Projects\PlayingWithExceptions\PlayingWithExceptions\Trying.cs : line 25Arithmetic mistake : Attempted to divide by zero .",Throwing an exception more than once loses its original stack trace "C_sharp : I was just dealing with strings , and I find myself annoyed that strings can be nullable . So , I have to have all over the place . Would string ? have been so hard for allowing nullability in the relatively few cases where it is needed ( dbs , idiot user inputs , etc. ) . I also find myself irritated with having to export readonly interfaces in the cases where I want some form of const correctness . So , what C # language construct/decision annoys you ? EDIT : Thanks for the isnullorempty function , I had n't seen that before ! Still does n't lessen my annoyance at it being nullable : D if ( ( teststring ? ? string.Empty ) ==string.Empty )",What language decision in C # annoys you ? "C_sharp : I 'm having a problem trying to make my LINQ to SQL queries and the mapping to my domain objects DRY without incurring the cost of multiple round trips to the db . Given this example : The query will make ONE round trip to the DB . Great ! However , the problem I see with this is that eventually , I 'll also have a 'GetProductDetails ' method which will also need to do some of the SAME `` data object - > domain object '' mapping , very similar to that above.To alleviate some of the mapping , I thought it might be a cool idea to extend the partial data object classes to do the mapping for me , like so : Nice ! Now , I could simply rewrite query1 as follows : This makes the code more DRY and more readable . Additionally , other queries that need to do the same type of mapping can simply use the ToDomainObject ( ) method for the mapping . It works , but with a cost . While watching via Profiler , the first query would call the db ONCE , joining tables where necessary . The second query does n't join appropriately , thus making multiple calls to the DB . Is there a way to accomplish what I 'm trying to do : refactor LINQ to SQL queries so that the mapping to domain objects is DRY ( no code duplication ) ? var query1 = from x in db.DBProducts select new MyProduct { Id = x.ProductId , Name = x.ProductName , Details = new MyProductDetail { Id = x.DBProductDetail.ProductDetailId , Description = x.DBProductDetail.ProductDetailDescription } } public partial class DBProduct { MyProduct ToDomainObject ( ) { return new MyProduct { Id = this.ProductId , Name = this.ProductName , Details = this.DBProductDetails.ToDomainObject ( ) } ; } } public partial class DBProductDetail { MyProductDetail ToDomainObject ( ) { return new MyProductDetail { Id = this.ProductDetailId , Description = this.ProductDetailDescription } ; } } var query1 = from x in db.DBProducts select x.ToDomainObject ( ) ;",Linq to Sql DB Object to Domain Object mapping and performance C_sharp : I have added the System.Data.SQLite.Core NuGet package to my LINQPad 5 Query ( Premium ) and then try to execute the following : But I get : DllNotFoundException : Unable to load DLL 'SQLite.Interop.dll ' : The specified module could not be found . ( Exception from HRESULT : 0x8007007E ) How can I tell LINQPad where to find the SQLite Native DLLs ? Please note I do not want to use the IQ Driver . new SQLiteConnection ( `` : memory : '' ) .Dump ( ) ;,Why am I getting DllNotFoundException when adding SQLite Nuget Package to LINQPad ? "C_sharp : Below you can see how I am trying to segregate styles by merging dictionaries ( I 'm skipping namespaces for the sake of cleanliness ) App.xaml : Colors.xaml : HeaderStyle.xaml : During compilation I get a following error : Can not find a Resource with the Name/Key DarkTextForegroundTo make It work we have to merge Colors.xaml inside HeaderStyle.xaml like this : Can anyone explain to me , why I have to reference Colors.xaml in HeaderStyle.xaml ? Ca n't I just reference styles defined in different merged dictionary ? I assume that Colors.xaml is loaded before HeaderStyle.xaml so it should be visible for dictionaries defined later . < Application.Resources > < ResourceDictionary > < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' Style/Colors.xaml '' / > < ResourceDictionary Source= '' Style/HeaderStyle.xaml '' / > < /ResourceDictionary.MergedDictionaries > < /ResourceDictionary > < /Application.Resources > < SolidColorBrush x : Key= '' DarkTextForeground '' Color= '' # 7471b9 '' / > < Style x : Key= '' HeaderTextBlockStyle '' TargetType= '' TextBlock '' > < Setter Property= '' Foreground '' Value= '' { StaticResource DarkTextForeground } '' / > < Setter Property= '' FontWeight '' Value= '' Black '' / > < /Style > < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' Colors.xaml '' / > < /ResourceDictionary.MergedDictionaries > < Style x : Key= '' HeaderTextBlockStyle '' TargetType= '' TextBlock '' > < Setter Property= '' Foreground '' Value= '' { StaticResource DarkTextForeground } '' / > < Setter Property= '' FontWeight '' Value= '' Black '' / > < /Style >",Using style defined in merged dictionary from another merged dictionary C_sharp : I am trying to get all the types defined under a particular userdefined namespace My question Why am i getting these extra type which are not defined under that namespace ? how do i select type that are user defined types ? some one explain me what are these and how they get defined under a userdefined namespace . Assembly.GetEntryAssembly ( ) .GetTypes ( ) .Where ( t = > t.Namespace == `` namespace '' ) < > c__DisplayClass3_0 < > c__DisplayClass4_0 < > c__DisplayClass6_0 < > c__DisplayClass2_0 < > c__DisplayClass2_1 < > c__DisplayClass2_2 < > c__DisplayClass2_3 < > c__DisplayClass2_4 < > c__DisplayClass2_5 < > c__DisplayClass2_6 < > c__DisplayClass2_7 < > c__DisplayClass2_8,Getting all types under a userdefined assembly "C_sharp : I have a templating system that looks similar to old-style ASP code . I run this through a class that rewrites the entire thing into C # source code , compiles , and finally executes it.What I 'm wondering is if there is some kind of # pragma-like directive I can sprinkle the generated C # code with that will make compile errors match the line numbers in my template file ? For instance , let 's say I have this first and only line in my template code : but then in order to compile this I must add a namespace , a class , a method , and some boiler-plate code to it , so this line above , which is line # 1 in my template file , actually ends up being line # 17 ( random number , just for illustrative purposes ) in the C # code . The compiler error will naturally flag my error as being on line # 17 , and not on line # 1.I remember from another programming language I 've used before ( though I ca n't remember which one ) that it had a directive that I could add , which would make error line numbers line up.Is there any such thing in C # 3.5 ? Object o = datta ; // should be data , compiler error",Is there any # pragma or similar directive for generated C # code to match template code line numbers to C # line number ? "C_sharp : I have two streams . One is a flow of data ( could be any type ) , the other is a boolean stream acting as a gate . I need to combine these into a stream that has the following behaviour : When the gate is open ( most recent value was true ) then the datashould flow straight throughWhen the gate is closed ( most recent value was false ) then the datashould be buffered to be released as individual elements when thegate is next openThe solution should preserve all elements of the data and preserveorderI am not really sure how to put this together . The inputs I have been testing with are like this : // a demo data stream that emits every secondvar dataStream = Observable.Interval ( TimeSpan.FromSeconds ( 1 ) ) ; // a demo flag stream that toggles every 5 secondsvar toggle = false ; var gateStream = Observable.Interval ( TimeSpan.FromSeconds ( 5 ) ) .Select ( _ = > toggle = ! toggle ) ;",How can I alternately buffer and flow a live data stream in Rx "C_sharp : I have the following test matrix : I intend to create an algorithm that helps me find every possible word from a given minimum length to a maximum length using adjacent letters only.For example : Minimum : 3 lettersMaximum : 6 lettersBased on the test matrix , I should have the following results : alialmalgaltatiatmatg ... atmeaetc.I created a test code ( C # ) that has a custom class which represents the letters.Each letter knows its neighbors and has a generation counter ( for keeping track of them during traversal ) .Here is its code : I figured out that if I want it to be dynamic , it has to be based on recursion.Unfortunately , the following code creates the first 4 words , then stops . It is no wonder , as the recursion is stopped by the specified generation level.The main problem is that the recursion returns only one level but it would be better to return to the starting point.So , I feel a little stuck , any idea how I should proceed ? a l ig t mj e a public class Letter { public int X { get ; set ; } public int Y { get ; set ; } public char Character { get ; set ; } public List < Letter > Neighbors { get ; set ; } public Letter PreviousLetter { get ; set ; } public int Generation { get ; set ; } public Letter ( char character ) { Neighbors = new List < Letter > ( ) ; Character = character ; } public void SetGeneration ( int generation ) { foreach ( var item in Neighbors ) { item.Generation = generation ; } } } private static void GenerateWords ( Letter input , int maxLength , StringBuilder sb ) { if ( input.Generation > = maxLength ) { if ( sb.Length == maxLength ) { allWords.Add ( sb.ToString ( ) ) ; sb.Remove ( sb.Length - 1 , 1 ) ; } return ; } sb.Append ( input.Character ) ; if ( input.Neighbors.Count > 0 ) { foreach ( var child in input.Neighbors ) { if ( input.PreviousLetter == child ) continue ; child.PreviousLetter = input ; child.Generation = input.Generation + 1 ; GenerateWords ( child , maxLength , sb ) ; } } }",How to find all the possible words using adjacent letters in a matrix "C_sharp : I found that Applications can be assigned to users in this answer but ca n't seem to figure out how to do this using C # . Below is the JSON and the C # I 'm trying.Azure Active Directory : assign user to an application from the gallery via Graph API Assign principal ( user or group ) to application : •resourceId is the objectId of the servicePrincipal that get created in the tenant for the application•id is the default role id of App.•principalId is the objectId of the principal ( user or group ) that is being assigned to the app.HTTP POST https : //graph.windows.net/7fe877e6-a150-4992-bbfe-f517e304dfa0/users/de4b092e-1dd4-4d40-b74d-a2d7096c9495/appRoleAssignments ? api-version=1.5Authorization : Bearer eyJ0eXAiOi -- snip -- JKVBfk_QContent-Type : application/jsonContent-Length : 176 { `` id '' : `` fc60bc23-43df-4a60-baaa-f0b8694e0259 '' , '' principalId '' : `` de4b092e-1dd4-4d40-b74d-a2d7096c9495 '' , '' resourceId '' : `` 93c60e8e-74f9-4add-9ae2-dd9bc0d6edcd '' } AppRoleAssignment appAssignment = new AppRoleAssignment ( ) ; appAssignment.Id = appRole.Id ; appAssignment.PrincipalId = new Guid ( retrievedUser.ObjectId ) ; appAssignment.ResourceId = new Guid ( `` aa9b2f6b-6528-4552-a202-2039ce86d95c '' ) ; appAssignment.UpdateAsync ( ) ;",Azure AD Graph API - Assign user to applications using C # "C_sharp : I 'm very confused by this and it 's starting to make me question my whole understanding of the WPF resource systemI have a multi-window application where each Window-derived object runs on a separate thread with separate dispatcher.I have a Dictionary1.xaml resource dictionary with a named Style object inside it ( it just sets the Background property to Red and is targetted at a TextBox ) . In my App.xaml I reference Dictionary1.xaml via the ResourceDictionary.MergedDictionaries collection . In the XAML of my other windows I have a StaticResource to the style key in a textbox control , which works.I 'm able to open multiple windows but should n't I be getting cross-threading errors ? In the constructor of one of the window classes I did this : Since a Style object is derived from DispatcherObject , does n't that mean it 's only accessible to the thread that owns it ? And if an object is defined in a ResourceDictionary , does n't that mean that by default , it 's a static instance ? How is this even able to work ? Why are n't I getting a cross-threading error ? ( I erroneously reported a question I since deleted about a cross threading error that was caused by something else ) I 'm very confused by this - I thought only frozen Freezable objects were shareable across threads . Why am I allowed to access a DispatcherObject on other threads ? Thread t = new Thread ( ( ) = > { Window1 win = new Window1 ( ) ; win.Show ( ) ; System.Windows.Threading.Dispatcher.Run ( ) ; } ) ; t.SetApartmentState ( ApartmentState.STA ) ; t.Start ( ) ; Style s = ( Style ) TryFindResource ( `` TestKey '' ) ; Console.WriteLine ( ( ( Setter ) s.Setters [ 0 ] ) .Property.Name ) ; // no problems.Dispatcher == this.Dispatcher // false",Why are Freezables already frozen and have a null Dispatcher ( same with Styles ) when stored in Application.Resources ? "C_sharp : We 've developed code that basically returns data for a user 's permissions on an entity.For instance , an entity could be one of the following : We then can assign policies ( and a person can get multiple policies ) that allow a user to perform an action : So basically one policy could say that user A has the right to create a company , but another policy which this same user has says that he does not have the right to create a company . In this case we take the rights that allow before the rights that dont allow . In this example , he/she would be allowed to create a company.So basically you end up with data like so : I have a query which we use to return what is this user 's permission based on the rules we discussed.In this case running the query the result would be : Our app is n't just a bit yes / no for whether they can perform the action or not . We have yes / no / owner only ( for records that should only be edited / deleted by the owner only . Our query is great and is returning the correct data . My question is what data type should I use in C # to basically say : Given an entity ( company ) given an action ( create ) what is the value . Basically at the end of the day I want to build a matrix that looks like this : The rows on the first column represent the entity , the columns after that represent the actions ( create , edit , delete ) . The combination of the 2 for instance index : [ Company ] [ Create ] = Yes would give you the right of the action based on the entity.So what datatype fits this model where I can perform some index like : [ Contact ] [ Edit ] =No.We also have to session this object / come up with a way ( maybe dynamically ) to get the result based on an entity and action.I thought session would be good so that we can check the rights once and only once until the user logs out . -Company-Contact-Project-Issue etc ... -Create-Edit-Delete-Export Policy1 Company Create YesPolicy1 Company Edit YesPolicy1 Company Delete NoPolicy2 Company Create NoPolicy2 Company Edit YesPolicy2 Company Delete No Company create yesCompany edit yesCompany delete no Create Edit DeleteCompany Yes Owner Only YesContact No No NoProject Yes Yes Owner Only",What datatype to use to store user permissions "C_sharp : I have a very simple query which selects items from a table based on matching the month and then grouping by day . These groups are then used as a data source for a repeater which outputs the group elements as entries `` per day '' .The problem is that days that do n't exist ( i.e . there 's no group for ) will naturally not be displayed , so things for the 6th and 8th , when there 's nothing for the 7th , will be seen directly next to each other ( think of a calendar view ) . The question is , given my query below , how could I insert groups with no elements , even when there 's no entry for that day ? I can do this figuring out after the fact , but can I account for it to get the result set at once ? Or can a previous tried & tested approach be recommended ? IQueryable events = Events .Where ( i = > i.Date.Month == date.Month ) .GroupBy ( i = > i.Date.Day ) ;",How to add empty groups to a Linq query result set ? "C_sharp : Basically I 'm realizing that my application is using commas instead of decimals , and i NEVER want to allow this . Anyone know how I can correct ? I ca n't find one thing via google that is to force decimals , it 's all about forcing commas . return String.Format ( `` { 0 } f , { 1 } f , { 2 } f , { 3 } f , { 4 } f , { 5 } f , { 6 } f , { 7 } f , { 8 } f , { 9 } f , { 10 } f , { 11 } f , { 12 } f , { 13 } f , { 14 } f , { 15 } f '' , M.M11 , M.M12 , M.M13 , M.M14 , M.M21 , M.M22 , M.M23 , M.M24 , M.M31 , M.M32 , M.M33 , M.M34 , M.OffsetX , M.OffsetY , M.OffsetZ , M.M44 ) ;",C # - Force String.Format to use decimals and NEVER commas "C_sharp : I am trying to find all the types that a given type is dependent on , including interfaces , abstract classes , enums , structs , etc . I want to load up an assembly , and print out a list of all the types defined within it , and their dependencies.So far I have been able to find all the the external types a CLR assembly depends on using Mono.Cecil , e.g.This list can also be obtained using the mono disasembler , eg `` monodis SomeAssembly.dll -- typeref '' , but this list doesnt seem to include primitives , eg System.Void , System.Int32 , etcI need to treat each type individually , and get all types that a given type depends on , even if the types are defined in the same assembly.Is there any way to do this using Mono.Cecil , or any other project ? I know it can be done by loading the assembly , then iterating over each defined type , then loading the IL of the type and scanning it for references , but I am sure that there is a better way . Ideally it will also work with anonymous inner classes.It should also work if multiple modules are defined in the same assembly . using System ; using Mono.Cecil ; using System.IO ; FileInfo f = new FileInfo ( `` SomeAssembly.dll '' ) ; AssemblyDefinition assemDef = AssemblyFactory.GetAssembly ( f.FullName ) ; List < TypeReference > trList = new List < TypeReference > ( ) ; foreach ( TypeReference tr in assemblyDef.MainModule.TypeReferences ) { trList.Add ( tr.FullName ) ; }",How do I find all the type dependecies of a given type in any CLR based language assembly ? "C_sharp : If I have the following class member : and I want to allow traversal of this list as part of the class ' interface , how would I do it ? Making it public wo n't work because I do n't want to allow the list to be modified directly . private List < object > obs ;",How to allow iteration over a private collection but not modification ? "C_sharp : I 'm integrating my app with Xero which requires two certificates . I uploaded them to Azure with help from this article , but I 'm still unable to connect to the Xero API . I 'm hoping someone has experience integrating a Xero Partner Application with an Azure Web App.I 've uploaded two pfx files ; one is a self-signed certificate and the other is the partner certificate issued by Xero . The latter pfx file contains two certificates ; an Entrust Commercial Private Sub CA1 ( whatever than means ) and a unique Entrust Id certificate for my app.I 'm using the following code to load the certificates by their unique thumbprint : This works fine locally , but on my azure web site I get a 403.7 error : I 've also looked at the following references to try and resolve the issue : Xero Partner SSL configuration in Azure ( Uses a cloud service and not a web app , so I could n't follow the steps at the end ) 403 Forbidden when loading X509Certificate2 from a file ( Thread posted on the Xero forums about the same issue , figured out that the resolution is only for once again ; cloud services ) Xero partner connections and Azure Websites ( Posted solution suggests using a VM ) What I have n't tried yet : Converting my web app to a cloud service ; trying to avoid doing this however I 'm not sure what steps are involved.Using a VM ; I have n't found any detailed steps on how to do this but seems like a better option than above.Screenshot of the error : static X509Certificate2 GetCertificateFromStore ( string thumbprint ) { var store = new X509Store ( StoreLocation.CurrentUser ) ; try { thumbprint = Regex.Replace ( thumbprint , @ '' [ ^\da-zA-z ] '' , string.Empty ) .ToUpper ( ) ; store.Open ( OpenFlags.ReadOnly ) ; var certCollection = store.Certificates ; var currentCerts = certCollection.Find ( X509FindType.FindByTimeValid , DateTime.Now , false ) ; var signingCert = currentCerts.Find ( X509FindType.FindByThumbprint , thumbprint , false ) ; if ( signingCert.Count == 0 ) { throw new Exception ( $ '' Could not find Xero SSL certificate . cert_name= { thumbprint } '' ) ; } return signingCert [ 0 ] ; } finally { store.Close ( ) ; } } The page you are attempting to access requires your browser to have a Secure Sockets Layer ( SSL ) client certificate that the Web server recognizes .",Connect Azure Website to Xero Partner Application "C_sharp : I own the following findings in order to work againts WMQ Secure-Channel : Defined Secure-Channel in the WMQ farmPublic/Private keysUnmanaged Security-Exit assemblyMy question is how to utilize these resources and interact with a Secure Channel using the XMS API ? ( Using C # ) This is what I 've tried so far , but without success : I get the following error when calling it : CWSMQ0006E : An exception was received during the call to the method ConnectionFactory.CreateConnection : CompCode : 2 , Reason : 2195 . During execution of the specified method an exception was thrown by another component . See the linked exception for more information.UPDATE : I found the following Technote which describes my problem and its possible ( not tested ) solution : https : //www-304.ibm.com/support/docview.wss ? uid=swg1IC82112 private IConnectionFactory CreateConnectionFactory ( ) { XMSFactoryFactory factoryFactory = XMSFactoryFactory.GetInstance ( XMSC.CT_WMQ ) ; IConnectionFactory connectionFactory = factoryFactory.CreateConnectionFactory ( ) ; connectionFactory.SetStringProperty ( XMSC.WMQ_HOST_NAME , _wmqHostName ) ; connectionFactory.SetIntProperty ( XMSC.WMQ_PORT , _wmqPort ) ; connectionFactory.SetStringProperty ( XMSC.WMQ_CHANNEL , _wmqChannel ) ; connectionFactory.SetIntProperty ( XMSC.WMQ_CONNECTION_MODE , XMSC.WMQ_CM_CLIENT_UNMANAGED ) ; connectionFactory.SetStringProperty ( XMSC.WMQ_QUEUE_MANAGER , _wmqQueueManager ) ; connectionFactory.SetIntProperty ( XMSC.WMQ_BROKER_VERSION , 0 ) ; connectionFactory.SetStringProperty ( XMSC.WMQ_SECURITY_EXIT , `` MySecurityExitName '' ) ; return ( connectionFactory ) ; }",Working against a Secure-Channel with Security-Exit using XMS .NET API "C_sharp : According to MSDN documentationResumeAutomatic : The computer has woken up automatically to handle an event.Note : If the system detects any user activity after broadcasting ResumeAutomatic , it will broadcast a ResumeSuspend event to let applications know they can resume full interaction with the user.ResumeSuspend : The system has resumed operation after being suspended.Does this mean 'ResumeAutomatic ' is called when the computer wakes up from sleep and 'ResumeSuspend ' is called when the user logs in after entering credentials ? I am using tcp socket to communicate with a server . So in order to reconnect to the service when the system is back from sleeping state , I have the following codeBut I observe that the enum values are random . Below are 3 different traces at 3 different wake up times.20150525 # 094449 : : Power status is : Suspend20150525 # 094716 : : Power status is : ResumeSuspend20150525 # 103431 : : Power status is : Suspend20150525 # 103525 : : Power status is : ResumeSuspend20150525 # 103525 : : Power status is : ResumeAutomatic20150525 # 103558 : : Power status is : Suspend20150525 # 103835 : : Power status is : ResumeAutomatic protected override bool OnPowerEvent ( PowerBroadcastStatus powerStatus ) { Logger.Log ( `` Power status is : `` + powerStatus ) ; if ( powerStatus == PowerBroadcastStatus.ResumeAutomatic ) { ConnectionWatchdog.ReConnect ( ) ; } return base.OnPowerEvent ( powerStatus ) ; }",Difference between ResumeAutomatic & ResumeSuspend modes of Windows Service "C_sharp : I am working on a DI problem that I think I understand the cause of , but I need some suggestions to work around.I have built a stand alone assembly that talks to Sql ( call this assembly a ) , and another assembly that contains business logic ( call this assembly b ) . I created an interface for the db class in the b assembly . Since the interface is n't part of the db assembly , I do n't need any references to the db project , and I can load a reference to the db assembly or a stub if I want to run unit tests at run time and neither assembly needs to know about the other . I can write code in the business logic library that compiles that looks like this : ( pretend that a and b are namespaces in their respective assemblies ) When I try to run this however , I get an invalid cast exception . I think it compiles because the interface matches the class perfectly , but fails at run time because object signature does n't see IDatabase in the inheritance chain of the Database class.In c++ you can get away with casting anything however you want , but c # is a little bit stricter about casting object pointers . Even though the class has all the correct function signatures , it is blowing up because the objects do n't match.Now I could put the db object interface in the assembly with the db object , but then the business logic needs a reference to the db assembly . Also , this just creates complications down the road , because if I write a stub db object in a unit test , I need a reference to the db assembly just for the interface that I am going to use in my test stub object . This does n't seem to be disentangling couplings by doing this ... I could put all the interfaces in a third assembly that is a parent to the db assembly , the business logic , and the unit tests . This is how you can solve circular dependency issues . However , this ties the db assembly to the parent assembly , and makes it a lot less modular to be used with other projects.I am open to suggestions about how I can set up each assembly so that they function independently and can be used for DI . I suppose I could keep the test stub objects in the same assembly as the real code , but that seems weird.Solution : One of the replies below makes the comment that what I was shooting for is basically duck-typing for interfaces . C # does n't support duck typing currently , but I was thinking it might be possible since interface implementation acts in similar way to what you might call a partial class pointer ( or probably more accurately , a collection of function pointers ) . My experiment was showing me otherwise , and that is why.so until Redmond puts 'more mallard ' into c # , looks like we can not reach that final elegant level of decoupling assemblies entirely . a.IDatabaseClass db_class = ( a.IDatabase ) new b.Database ( ) ;",Dependency Injection across assemblies & namespaces "C_sharp : I have a SharePoint DLL that does some licensing things and as part of the code it uses an external C++ DLL to get the serial number of the hardisk.When I run this application on Windows Server 2003 it works fine , but on Windows Server 2008 the whole site ( loaded on load ) crashes and resets continually . This is not Windows Server 2008 R2 and is the same in 64 or 32 bits.If I put a Debugger.Break before the DLL execution then I see the code get to the point of the break and then never come back into the DLL again . I do get some debug assertion warnings from within the function , again only in Windows Server 2008 , but I 'm not sure this is related.I created a console application that runs the C # DLL , which in turn loads the C++ DLL , and this works perfectly on Windows Server 2008 ( although it does show the assertion errors , but I have suppressed these now ) .The assertion errors are not in my code but within ICtypes.c , and not something I can debug.If I put a breakpoint in the DLL it is never hit and the compiler says : If I try to debug into the DLL using Visual Studio.I have tried wrapping the code used to call the DLL in : But this also does not help.I have the source code for this DLL so that is not a problem.If I delete the DLL from the directory I get an error about a missing DLL . If I replace it , back to no error or warning just a complete failure.If I replace this code with a hardcoded string the whole application works fine.Any advice would be much appreciated , I ca n't understand why it works as a console application , yet not when run by SharePoint . This is with the same user account , on the same machine ... This is the code used to call the DLL : `` step in : Stepping over non user code '' SPSecurity.RunWithElevatedPrivileges ( delegate ( ) [ DllImport ( `` idDll.dll '' , EntryPoint = `` GetMachineId '' , SetLastError = true ) ] extern static string GetComponentId ( [ MarshalAs ( UnmanagedType.LPStr ) ] String s ) ; public static string GetComponentId ( ) { Debugger.Break ( ) ; if ( _machine == string.Empty ) { string temp = `` '' ; id= ComponentId.GetComponentId ( temp ) ; } return id ; }",SharePoint fails to load a C++ DLL on Windows 2008 "C_sharp : Jeffrey Richter pointed out in his book 'CLR via C # ' the example of a possible deadlock I do n't understand ( page 702 , bordered paragraph ) .The example is a thread that runs Task and call Wait ( ) for this Task . If the Task is not started it should possible that the Wait ( ) call is not blocking , instead it 's running the not started Task . If a lock is entered before the Wait ( ) call and the Task also try to enter this lock can result in a deadlock.But the locks are entered in the same thread , should this end up in a deadlock scenario ? The following code produce the expected output . No deadlock occured.J . Richter wrote in his book `` CLR via C # '' 4th Edition on page 702 : When a thread calls the Wait method , the system checks if the Task that the thread is waiting for has started executing . If it has , then the thread calling Wait will block until the Task has completed running . But if the Task has not started executing yet , then the system may ( depending on the TaskScheduler ) execute the Trask by using the thread that called Wait . If this happens , then the thread calling Wait does not block ; it executes the Task and returns immediatlely . This is good in that no thread has blocked , thereby reducing resource usage ( by not creating a thread to replace the blocked thread ) while improving performance ( no time is spet to create a thread an there is no contexte switcing ) . But it can also be bad if , for example , thre thread has taken a thread synchronization lock before calling Wait and thren the Task tries to take the same lock , resulting in a deadlocked thread ! If I 'm understand the paragraph correctly , the code above has to end in a deadlock ! ? class Program { static object lockObj = new object ( ) ; static void Main ( string [ ] args ) { Task.Run ( ( ) = > { Console.WriteLine ( `` Program starts running on thread { 0 } '' , Thread.CurrentThread.ManagedThreadId ) ; var taskToRun = new Task ( ( ) = > { lock ( lockObj ) { for ( int i = 0 ; i < 10 ; i++ ) Console.WriteLine ( `` { 0 } from Thread { 1 } '' , i , Thread.CurrentThread.ManagedThreadId ) ; } } ) ; taskToRun.Start ( ) ; lock ( lockObj ) { taskToRun.Wait ( ) ; } } ) .Wait ( ) ; } } /* Console outputProgram starts running on thread 30 from Thread 31 from Thread 32 from Thread 33 from Thread 34 from Thread 35 from Thread 36 from Thread 37 from Thread 38 from Thread 39 from Thread 3*/",CLR via C # 4th Ed . - Confused about waiting for Task deadlock "C_sharp : I am using VS2019 and .NET CORE 2.2 I am getting the warning AL1073 ALINK warning AL1073 : Referenced assembly 'mscorlib.dll ' targets a different processorI know this is close to the question as : ALINK : warning AL1073 : Referenced assembly 'mscorlib.dll ' targets a different processorBUT : I am on .NET CORE 2.2 not on 4.xThe solutions proposed there do not work on .NET corein particular , attempting to add : gives another warning Warning MSB3084 Task attempted to find `` al.exe '' in two locations . 1 ) Under the `` \x64\ '' processor specific directory which is generated based on SdkToolsPath 2 ) The x86 specific directory under `` \x64\ '' which is specified by the SDKToolsPath property . You may be able to solve the problem by doing one of the following : 1 ) Set the `` SDKToolsPath '' property to the location of the Microsoft Windows SDK . C : \Program Files ( x86 ) \Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targetsReally strange , since the location is the same according to the warning ! Additionally : I would be happy to suppress the warning in the build settings , since all my unit tests pass , but adding 1073 to the list has no effect on the AL1073 warning which still appears.Alternatively , the warning suggests : Set the `` SDKToolsPath '' property to the location of the Microsoft Windows SDK , how can I do that ? UPDATE to answer comment : This is hard to reproduce in a simple setup . the project references several Github projects ( fo-dicom ) in particular . The fo-dicom lib uses imaging libs built for 32 and 64 platforms . I did try setting to 64bits but it did not help . I saw other people raise the bug in VS community that the suppression of warning seems buggy : https : //developercommunity.visualstudio.com/content/problem/224196/suppress-warnings-from-project-settings-build-does.html . That issue was closed without follow-up also MSFT stated that the AL 1073 will not be fixed , but I would like to disable ! ca n't have warnings when using continuous integration ... I am now trying to recompile everything in .NET CORE 3.0 , will provide an update if it works.UPDATE : After recompiling in .NET CORE 3.0 I still have the issue.I also found another cause of this issue ( mentione in other SO articles , but for .NET 4.x . Indeed I saw that the issue came up also with resource files however with .NET Core we do not see the `` Generating Satellite Assemblies '' message so it is hard to link the compiler warning to the generation of the resource files.In order to solve the issue I copied the al.exe file from C : \Program Files ( x86 ) \Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools\x64 into my solution into Tools64 and added the following to my .csprojSetting the SDKToolsDirectory directly to the original location did not work . Additional using the absolute path will not in my case where we use a devops build server for continuous integration ( paths may be different ) . copying the al.exe tool locally seems to be an acceptable solution . < PropertyGroup > < TargetFrameworkSDKToolsDirectory Condition= '' ' $ ( PlatformTarget ) ' == 'x64 ' '' > $ ( TargetFrameworkSDKToolsDirectory ) \ $ ( PlatformTarget ) \ < /TargetFrameworkSDKToolsDirectory > < /PropertyGroup > < PropertyGroup > < TargetFrameworkSDKToolsDirectory > ..\Tools64 < /TargetFrameworkSDKToolsDirectory > < /PropertyGroup >",.NET CORE ALINK : warning AL1073 : Referenced assembly 'mscorlib.dll ' targets a different processor "C_sharp : Edit : I just tried this with VS 2010 , and the problem did n't occur . The issue only happens with VS 2012 . Could this really be a bug ? This is also happening on two separate laptops of mine , and even on a friend 's laptop ( that just got the latest code ) .First , a screenshot of the problem . This method is all new code.The debugger is skipping code from my recent check-in . The comments , in the code below , explain what is happening when I debug this method . So there really is n't a need to try and understand the code ; just notice that lines of code are being skipped . If you 're thinking that the code does n't match the assembly being debugged , please bear with me . You 'll see where the debugger recognizes new code , but not existing code . And this behavior is occurring on two different laptops , after deleting the code on disk and getting the latest again . Each comment tells you if the debugger hits a line.The disassembly shows only the lines of code that actually get hit.Now , check this out . If I add a new line of code , the debugger recognizes it , and the other lines of code change , as far as being recognized by the debugger . Just the second line of code , within the method , is new.And here 's a partial snapshot of the disassembly , showing the new line of code : How can this be happening ? Adding to the weirdness , at one point this even returned : Things I 've tried : - Delete source code from hard drive and force a get latest- Repair VS 2012- Do some VS clean-up- Use VS 2010 , change code , check in , get latest with VS 2012- Reboot- Other ( ca n't remember all of them ) [ TestMethod ( ) ] [ DeploymentItem ( `` PrestoCommon.dll '' ) ] public void ApplicationShouldBeInstalledTest_UseCase9 ( ) { // Debugger hits this line ApplicationServer appServerAccessor = new ApplicationServer ( ) ; // Debugger does not hit these next two lines PrivateObject privateObject = new PrivateObject ( appServerAccessor ) ; ApplicationServer appServer = ApplicationServerLogic.GetByName ( `` server10 '' ) ; // Debugger hits this line . Weirdness : both objects are null , and after this line runs , // appServerAccessor is no longer null . appServerAccessor.Id = appServer.Id ; // Skips this line ApplicationWithOverrideVariableGroup appWithValidGroup = appServer.ApplicationsWithOverrideGroup [ 0 ] ; // Debugger hits this line , but F11 does n't take me into the method . appWithValidGroup.CustomVariableGroup = CustomVariableGroupLogic.GetById ( `` CustomVariableGroups/4 '' ) ; // Skips this line Assert.AreEqual ( true , true ) ; } [ TestMethod ( ) ] [ DeploymentItem ( `` PrestoCommon.dll '' ) ] public void ApplicationShouldBeInstalledTest_UseCase9 ( ) { // Debugger hits this line ApplicationServer appServerAccessor = new ApplicationServer ( ) ; // New line . It 's recognized by the debugger , and it shows up in the disassembly . if ( DateTime.Now > DateTime.Now.AddHours ( 1 ) ) { return ; } // Debugger does not hit these next two lines PrivateObject privateObject = new PrivateObject ( appServerAccessor ) ; ApplicationServer appServer = ApplicationServerLogic.GetByName ( `` server10 '' ) ; // Gets hit now . // Debugger hits this line . Weirdness : both objects are null , and after this line runs , // appServerAccessor is no longer null . appServerAccessor.Id = appServer.Id ; // No longer gets hit . // Skips this line ( now it 's getting hit ) ApplicationWithOverrideVariableGroup appWithValidGroup = appServer.ApplicationsWithOverrideGroup [ 0 ] ; // Debugger hits this line , but F11 does n't take me into the method . Now this gets skipped . appWithValidGroup.CustomVariableGroup = CustomVariableGroupLogic.GetById ( `` CustomVariableGroups/4 '' ) ; // Skips this line . Still skipped . Assert.AreEqual ( true , true ) ; } if ( DateTime.Now > DateTime.Now.AddDays ( 1 ) ) { return ; }",Debugger Skipping Latest Checked-in Code in VS 2012 - Works with VS 2010 "C_sharp : I 'm attempting to stream audio and video live from my PC to a publishingpoint on a hosted service . I 've written all the code that I think it should have ( At the moment it 's just test code in a small Console app ) . The code itself does not throw an error , it runs just fine , video is pulled from my webcam , however when trying to send the stream to the publishingpoint I get a DCOM error in the System Event logs `` DCOM was unable to communicate with the computer streamwebtown.com using any of the configured protocols . `` I tried to do the same thing using the actual Expression Encoder 4 client application that comes with the SDK and the video/audio feed works just fine to the same publishingpoint . I 've searched the internet far and wide to see if someone else has run into this problem but have come up empty . Asking the community if they have any ideas ? Code from Application : static void Main ( string [ ] args ) { EncoderDevice video = EncoderDevices.FindDevices ( EncoderDeviceType.Video ) .Count > 0 ? EncoderDevices.FindDevices ( EncoderDeviceType.Video ) [ 0 ] : null ; EncoderDevice audio = EncoderDevices.FindDevices ( EncoderDeviceType.Audio ) .Count > 0 ? EncoderDevices.FindDevices ( EncoderDeviceType.Audio ) [ 0 ] : null ; LiveJob job = new LiveJob ( ) ; if ( video ! = null & & audio ! = null ) { LiveDeviceSource source = job.AddDeviceSource ( video , audio ) ; job.ActivateSource ( source ) ; PushBroadcastPublishFormat publishingPoint = new PushBroadcastPublishFormat ( ) ; publishingPoint.PublishingPoint = new Uri ( `` http : //streamwebtown.com/abc '' ) ; publishingPoint.UserName = `` user '' ; publishingPoint.Password = PullPW ( `` Stream '' ) ; job.ApplyPreset ( LivePresets.VC1Broadband16x9 ) ; job.PublishFormats.Add ( publishingPoint ) ; job.StartEncoding ( ) ; Console.ReadKey ( ) ; job.StopEncoding ( ) ; } } private static SecureString PullPW ( string pw ) { SecureString s = new SecureString ( ) ; foreach ( char c in pw ) s.AppendChar ( c ) ; return s ; }",Expression Encoder 4 SDK throwing DCOM error while Live Streaming C_sharp : I have an implementation of an authenticated HttpClient generator class that resembles this : ... how can I test that the GenerateClient ( ) method has successfully attached the client certificate to the HttpClient class ? ... or am I trying to test the wrong thing ? public class X509Authentication : IClientAuthenticator { protected readonly X509Certificate2 Certificate ; public X509Authentication ( X509Certificate2 certificate ) { if ( certificate == null ) throw new ArgumentNullException ( `` certificate '' ) ; Certificate = certificate ; } public HttpClient GenerateClient ( ) { var clientHandler = new WebRequestHandler ( ) ; clientHandler.ClientCertificates.Add ( Certificate ) ; var request = new HttpClient ( clientHandler ) ; return request ; } public void Dispose ( ) { //nothing to do here . } } [ TestMethod ] public void HttpClientCreationIncludesCertificate ( ) { using ( var auth = new X509Authentication ( _certificate ) ) using ( var client = auth.GenerateClient ( ) ) { Assert ... what ? The certificate ( s ) are not visible here . } },How to test if HttpClient has a client certificate included ? "C_sharp : I have been serializing anonymous types into json quite successfully until now..Is there a workaround ? I 'm gon na try to serialize a dictionary into a json object if not.. dynamic jsObject ; jsObject = new ExpandoObject ( ) ; jsObject.dataUrl = Controller.Url.Action ( `` loadall '' , `` residuals '' , new { EditionId = EditionId , Country = Country , ModelYear = ModelYear , MakeId = ModelId , StyleId = style.Id } ) ; jsObject.id = style.Id ; jsObject.text = style.Name ; jsObject.iconCls = `` sprite-toolbar-flag-us '' ; jsObject.checked = false ; // < -- - < < the problem is here jsObject.leaf = true ; jsObject.IsCustomQuote = style.IsCustomQuote ; return jsObject ;",How can I use a keyword as a property name ? "C_sharp : I 've got a few big arrays/lists of filenames that start the same . Like this : I would like to extract the beginning part that they all have in common.In this case : `` C : \Program Files '' How do I do that ? I thought I might have to compare 2 strings at a time and get the same beginning . I do n't even know how to do that without comparing each character manually ? Then I 'll have to compare each string to every other string ? Will it be O ( n² ) ? Is there a better , faster way ? Edit : Is there also a way without Linq ? C : \Program Files\CCleaner\ ... C : \Program Files\Common Files\ ... C : \Program Files ( x86 ) \Adobe\ ... C : \Program Files ( x86 ) \Common Files\ ...",Get Equal Part of Multiple Strings at the Beginning "C_sharp : I 've encountered a strange behavior in a .NET application that performs some highly parallel processing on a set of in-memory data.When run on a multi-core processor ( IntelCore2 Quad Q6600 2.4GHz ) it exhibits non-linear scaling as multiple threads are kicked off to process the data.When run as a non-multithreaded loop on a single core , the process is able to complete approximately 2.4 million computations per second . When run as four threads you would expect four times as much throughput - somewhere in the neighborhood of 9 million computations per second - but alas , no . In practice it only completes about 4.1 millions per second ... quite a bit short from the expected throughput . Furthermore , the behavior occurs no matter whether I use PLINQ , a thread pool , or four explicitly created threads . Quite strange ... Nothing else is running on the machine using CPU time , nor are there any locks or other synchronization objects involved in the computation ... it should just tear ahead through the data . I 've confirmed this ( to the extent possible ) by looking at perfmon data while the process runs ... and there are no reported thread contentions or garbage collection activity.My theories at the moment : The overhead of all of the techniques ( thread context switches , etc ) is overwhelming the computationsThe threads are not getting assigned to each of the four cores and spend some time waiting on the same processor core .. not sure how to test this theory ... .NET CLR threads are not running at the priority expected or have some hidden internal overhead.Below is a representative excerpt from the code that should exhibit the same behavior : var evaluator = new LookupBasedEvaluator ( ) ; // find all ten-vertex polygons that are a subset of the set of points var ssg = new SubsetGenerator < PolygonData > ( Points.All , 10 ) ; const int TEST_SIZE = 10000000 ; // evaluate the first 10 million records // materialize the data into memory ... var polygons = ssg.AsParallel ( ) .Take ( TEST_SIZE ) .Cast < PolygonData > ( ) .ToArray ( ) ; var sw1 = Stopwatch.StartNew ( ) ; // for loop completes in about 4.02 seconds ... ~ 2.483 million/sec foreach ( var polygon in polygons ) evaluator.Evaluate ( polygon ) ; s1.Stop ( ) ; Console.WriteLine ( `` Linear , single core loop : { 0 } '' , s1.ElapsedMilliseconds ) ; // now attempt the same thing in parallel using Parallel.ForEach ... // MS documentation indicates this internally uses a worker thread pool // completes in 2.61 seconds ... or ~ 3.831 million/sec var sw2 = Stopwatch.StartNew ( ) ; Parallel.ForEach ( polygons , p = > evaluator.Evaluate ( p ) ) ; sw2.Stop ( ) ; Console.WriteLine ( `` Parallel.ForEach ( ) loop : { 0 } '' , s2.ElapsedMilliseconds ) ; // now using PLINQ , er get slightly better results , but not by much // completes in 2.21 seconds ... or ~ 4.524 million/second var sw3 = Stopwatch.StartNew ( ) ; polygons.AsParallel ( Environment.ProcessorCount ) .AsUnordered ( ) // no sure this is necessary ... .ForAll ( h = > evalautor.Evaluate ( h ) ) ; sw3.Stop ( ) ; Console.WriteLine ( `` PLINQ.AsParallel.ForAll : { 0 } '' , s3.EllapsedMilliseconds ) ; // now using four explicit threads : // best , still short of expectations at 1.99 seconds = ~ 5 million/sec ParameterizedThreadStart tsd = delegate ( object pset ) { foreach ( var p in ( IEnumerable < Card [ ] > ) pset ) evaluator.Evaluate ( p ) ; } ; var t1 = new Thread ( tsd ) ; var t2 = new Thread ( tsd ) ; var t3 = new Thread ( tsd ) ; var t4 = new Thread ( tsd ) ; var sw4 = Stopwatch.StartNew ( ) ; t1.Start ( hands ) ; t2.Start ( hands ) ; t3.Start ( hands ) ; t4.Start ( hands ) ; t1.Join ( ) ; t2.Join ( ) ; t3.Join ( ) ; t4.Join ( ) ; sw.Stop ( ) ; Console.WriteLine ( `` Four Explicit Threads : { 0 } '' , s4.EllapsedMilliseconds ) ;",Non-linear scaling of .NET operations on multi-core machine "C_sharp : BackgroundWe 've been migrating a large amount of legacy code & systems to ASP.NET MVC forms . I 've already coded up a number of CRUD type interfaces with MVC 4 , using model binding , validation , attributes etc. , so I 'm fairly familiar with that whole paradigm . So far , all of these forms have been on our backend administration & management applications , where it pays to have very strict input validation . We are launching our first consumer facing application in MVC and are faced with a different type of problem.The ProblemOur legacy forms in this area are the main revenue engine for our company . Usability of the consumer experience is the rule of the day . To that end , we want our forms to be as lenient as possible - the legacy system did a number of things to automatically correct user input ( in entirely custom , non standard ways each time , of course ) . To that end , we do n't so much want input validation as we want sanitation.ExamplesWe ask the user for numerical inputs which have a unit of measure implied . Common ones are currency amounts or square footage . The input label is clear that they do n't need to provide these formats : What is the approximate square footage ? ( example : 2000 ) What is your budget ? ( example : 150 ) People being people , not everyone follows the directions , and we frequently get answers like : approx 21001500 sq . ft. $ 47.50 , give or take ( Okay , I exaggerate on the last one . ) The model that we are ultimately storing into our business logic accepts numeric input type for these fields ( e.g . int & float ) . We can of course use datatype validator attributes ( example [ DataType ( DataType.Currency ) ] for the budget input , or just having the field type be an integer for the square footage ) to clearly indicate to the user they are doing it wrong , providing helpful error messages such as : The square footage must be numbers only.A better user experience , however , would be to attempt to interpret their response as leniently as possible , so they may complete the form with as little interruption as possible . ( Note we have an extensive customer service side who can sort out mistakes on our system afterwards , but we have to get the user to complete the form before we can make contact . ) For the square footage examples above , that would just mean stripping out non-digit characters . For the budget , it would mean stripping out everything that 's not a digit or a decimal point . Only then would we apply the rest of the validation ( is a number , greater than 0 , less than 50000 etc . ) We 're stuck on the best approach to take to accomplish this.Potential SolutionsWe 've considered custom attributes , custom model bindings , and a separate scrubber service class that would live between the model and the database . Here are some of the considerations we 've taken into account trying to decide upon the approach.Custom Validation AttributesI 've read a number of helpful resources on this . ( They have varying degrees of relevancy and recency . A lot of stuff I found searching for this was written for MVC2 or MVC3 and is available with standard attributes in MVC4 . ) Extending ASP.NET MVC ’ s ValidationCustom Validation Attribute in ASP.NET MVC3A lot of questions & topics on input sanitization which were focused on Cross-site scripting attacks or database injection.What I have n't found is anyone doing what I want to do , which would be changing the model value itself . I could obviously create a local copy of the value , sanitize it and provide a pass/fail , but this would result in a lot of duplicate code . I would still have to sanitize any input values again before saving to the database.Changing the model value itself has 3 benefits : It affects subsequent validation rules , which would improve their acceptance rate.The value is closer to what will be put into the database , reducing the additional prep & mapping overhead needed before storage.In the event of the form being rejected for another reason , it gently suggests to the user `` You 're trying to hard on these fields . `` Is this a valid approach ? Is there someone out there who has used validation attributes in this way that I just missed ? Custom Model BindingI read Splitting DateTime - Unit Testing ASP.NET MVC Custom Model Binders which focuses on custom date time input fields with custom validation & parsing done at the model binding layer . This lives a lot closer to the model itself , so it seems like a more appropriate place to be modifying the model values . In fact , the example class DateAndTimeModelBinder : IModelBinder does exactly that in a few places.However , the controller action signature provided for this example does not make use of an overall model class . It looks like thisRather than thisShortly before that , the article does sayFirst , usage . You can either put this Custom Model Binder in charge of all your DateTimes by registering it in the Global.asax : Would that be sufficient to invoke the model binding for the date time field on the single-parameter model example MyModelWithADateTimeProperty ? The other potential draw back that I see here is that the model binder operates on a type , rather than an attribute you can apply to the standard data types . So for example , each set of validation rules I wanted to apply would necessitate a new , custom type . This is n't necessarily bad , but it could get messy and cause a lot of repeated code . Imagine : Not the ugliest model code I 've ever seen , but not the prettiest either.Custom , External scrubber classThis has the fewest questions for me , but it has the most drawbacks as well . I 've done a few things like this before , only to really regret it for one of the following reasons : Being separate from the controller and model , it is nigh impossible to elegantly extend its validation rules to the client side.It thoroughly obfuscates what is and what is n't an acceptable input for the different model fields.It creates some very cumbersome hoops for displaying errors back to the user . You have to pass in your model state to the scrubber service , which makes your scrubber service uniquely tied to the MVC framework . OR you have to make your scrubber service capable of returning errors in a format that the controller can digest , which is rather more logic than is usually recommended for a controller.The QuestionWhich approach would you take ( or , have you taken ) to accomplish this type of sanitization ? What problems did it solve for you ? What problems did you run into ? public ActionResult Edit ( int id , [ DateAndTime ( `` year '' , `` mo '' , `` day '' , `` hh '' , '' mm '' , '' secondsorhwatever '' ) ] DateTime foo ) { public ActionResult Edit ( MyModelWithADateTimeProperty model ) { ModelBinders.Binders [ typeof ( DateTime ) ] = new DateAndTimeModelBinder ( ) { Date = `` Date '' , Time = `` Time '' } ; public class MyDataModel { [ Required ] public CurrencyType BudgetRange { get ; set ; } public PositiveOnlyCurrencyType PaymentAmount { get ; set ; } [ Required ] public StripNonDigitsIntegerType SquareFootage { get ; set ; }",Correcting user input in ASP.NET MVC4 "C_sharp : I 'm trying to load a related modal in Entity Framework Core but for some reason there 's a nested collection being loaded when I have n't asked for it in my Include ( ) call.Here 's my two models -Driver.csDriverStatusType.csDriversService.csNow when I call the GetDriverById ( int id ) method from my controller I get back what I 'm expecting -However the GetAllDrivers ( ) method is returning the nested drivers collection which means the data I 'm getting back is huge -I thought the idea of eager loading was to only include the related models you specify in the include statement but it seems this is not the case . Could someone explain what 's happening here ? public partial class Driver : IBaseEntity { public short DriverId { get ; set ; } public string Surname { get ; set ; } public string Initials { get ; set ; } public byte DriverStatusTypeId { get ; set ; } public DriverStatusType DriverStatusType { get ; set ; } } public partial class DriverStatusType { public DriverStatusType ( ) { Drivers = new HashSet < Driver > ( ) ; } public byte DriverStatusTypeId { get ; set ; } public string DriverStatusTypeName { get ; set ; } public string Description { get ; set ; } public ICollection < Driver > Drivers { get ; set ; } } public class DriverService : IDriverService { public DriverService ( MyContext context ) { Context = context ; } public MyContext Context { get ; } public async Task < IEnumerable < Driver > > GetAllDrivers ( ) { var drivers = await Context .Drivers .Include ( d = > d.DriverStatusType ) .toListAsync ( ) ; return drivers ; } public async Task < Driver > GetDriverById ( int id ) { var driver = await Context .Drivers .Include ( d = > d.DriverStatusType ) .Where ( d = > d.DriverId == id ) .FirstOrDefaultAsync ( ) ; return driver ; } } { `` driverId '' : 1 , `` surname '' : `` Stark '' , `` initials '' : `` T '' , `` driverStatusTypeId '' : 2 , `` driverStatusType '' : { `` driverStatusTypeId '' : 2 , `` driverStatusTypeName '' : `` Available '' , `` description '' : `` This driver is available '' , `` drivers '' : [ ] } } [ { `` driverId '' : 1 , `` surname '' : `` Stark '' , `` initials '' : `` T '' , `` displayText '' : `` Tony Stark '' , `` driverStatusTypeId '' : 2 , `` driverStatusType '' : { `` driverStatusTypeId '' : 2 , `` driverStatusTypeName '' : `` Available '' , `` description '' : `` This driver is available '' , `` drivers '' : [ { `` driverId '' : 2 , `` surname '' : `` Rogers '' , `` initials '' : `` S '' , `` driverStatusTypeId '' : 2 } , { `` driverId '' : 3 , `` surname '' : `` Romanoff '' , `` initials '' : `` N '' , `` driverStatusTypeId '' : 2 } , { `` driverId '' : 4 , `` surname '' : `` Banner '' , `` initials '' : `` B '' , `` driverStatusTypeId '' : 2 } , ...",EF Core Eager Loading nested collections "C_sharp : I read today , in c # strings are immutable , like once created they cant be changed , so how come below code worksHow come the value of variable changed ? ? string str= '' a '' ; str += '' b '' ; str += '' c '' ; str += '' d '' ; str += '' e '' ; console.write ( str ) //output : abcde","if strings are immutable in c # , how come I am doing this ?" "C_sharp : I have a database object class that does a bunch of heavy lifting . I then extend that object and build out the classes that represent the actual objects and fields being modified . It basically looks like this : This way , I can later just instantiate MyObject and start setting the properties via code . The idea is to produce easier , more maintainable code.It works great in practice . However , I 'm noticing that the code for MyObject is pretty repetitive . For example , with FieldX , I end up specifying the `` string '' type inside the get/set , and also having to specify the property name `` FieldX '' in get/set , as well.I 'm wondering if there 's a way to simplify the code further to reduce repetition . I know I can use Reflection : ... inside the get/set calls to get the property name , and I can use GetType ( ) to get the type of value when doing set , but ideally I 'd like to get the original property name from within the base GetValue/SetValue methods ( ideally without parsing the stack trace ) .Ideally , I 'm looking for something like this : Any thoughts ? public class MyObject : DatabaseObject { public string FieldX { get { return GetValue < string > ( `` FieldX '' ) ; } set { SetValue < string > ( `` FieldX '' , value ) ; } } public int FieldY { get { return GetValue < int > ( `` FieldY '' ) ; } set { SetValue < int > ( `` FieldY '' , value ) ; } } } public class DatabaseObject { public T GetValue < T > ( string FieldName ) { // Code that actually gets the right value } public void SetValue < T > ( string FieldName , T value ) { // Code that actually sets the value in the right place } } MethodBase.GetCurrentMethod ( ) .Name.Substring ( 4 ) public string FieldX { get { return GetValue ( ) ; } set { SetValue ( value ) ; } } public int FieldY { get { return GetValue ( ) ; } set { SetValue ( value ) ; } }",C # How to get the name of the property being set "C_sharp : What if any is the performance advantages of using a Lambda to handle async callbacks versus an old-fashioned event handler ? I find that I use this pattern more because it allows me to access method-level data and it does not litter my code with methods : this.Click += ( s , e ) = > { MessageBox.Show ( ( ( MouseEventArgs ) e ) .Location.ToString ( ) ) ; } ;",Performance of C # Lambda versus event handler "C_sharp : I 'm trying to embed some email templates in a class library . This works fine , until I use a filename containing a culture-name with the following notation : templatename.nl-NL.cshtmlThe resource does not seem to be available.Example code : Templates both have build action set to 'EmbeddedResource'.Obvious solution is to use a different notation , but I like this notation . Anyone has a solution for this problem ? namespace ManifestResources { class Program { static void Main ( string [ ] args ) { var assembly = Assembly.GetExecutingAssembly ( ) ; // Works fine var mailTemplate = assembly.GetManifestResourceStream ( `` ManifestResources.mailtemplate.cshtml '' ) ; // Not ok , localized mail template is null var localizedMailTemplate = assembly.GetManifestResourceStream ( `` ManifestResources.mailtemplate.nl-NL.cshtml '' ) ; } } }",Embedded resources in assembly containing culture name in filename will not load "C_sharp : In other words , is it correct to use : instead of : I 'd rather use the first approach because I 'd just define CustomerList once , and every time I needed a customer list I 'd always use the same type . On the other hand , using the name aliasing approach not only forces me to have to redefine it everywhere , but also a different alias could be given every time someone wanted to use it ( think of a big team ) , and thus cause the code to be less readable.Please note that the intention in this case would never be to extend the class , just to create an alias . public class CustomerList : System.Collections.Generic.List < Customer > { /// supposed to be empty } using CustomerList = System.Collections.Generic.List < Customer >",Is it correct to use inheritance instead of name aliasing in c # ? "C_sharp : I ran into an issue today and I have been stumped for some time in trying to get the results I am searching for.I currently have a class that resembles the following : I have a List < InstanceInformation > and I am trying to use LINQ ( or whatever other means to generate paths ( for a file-directory ) based on this list that resemble the following : My issue is the data is currently unstructured as it comes in the previously mentioned form ( List ) and I need a way to group all of the data with the following constraints : Group InstanceIDs by SeriesIDGroup SeriesIDs by StudyIDGroup StudyIDs by PatientIDI currently have something that resembles this : which just groups all of my InstanceIDs by PatientID , and it 's quite hard to cull through all of the data after this massive grouping to see if the areas in between ( StudyID/SeriesID ) are being lost . Any other methods of solving this issue would be more than welcome.This is primarily just for grouping the objects - as I would need to then iterate through them ( using a foreach ) public class InstanceInformation { public string PatientID { get ; set ; } public string StudyID { get ; set ; } public string SeriesID { get ; set ; } public string InstanceID { get ; set ; } } PatientID/StudyID/SeriesID/InstanceID var groups = from instance in instances group instance by instance.PatientID into patientGroups from studyGroups in ( from instance in patientGroups group instance by instance.StudyID ) from seriesGroup in ( from instance in studyGroups group instance by instance.SeriesID ) from instanceGroup in ( from instance in seriesGroup group instance by instance.InstanceID ) group instanceGroup by patientGroups.Key ;",Nested LINQ Query Question "C_sharp : I am working on a new chat bot using Azure Bot Service and QnAMaker . We are using BotBuilder middleware , including custom middleware , to tailor the bot behavior.One of the middlewares will be calling an Azure function and I would like to use the new HttpClientFactory feature with the custom middleware - but this requires dependency injection.How can I use dependency injection in BotBuilder middleware like you do with regular .NET Core middleware ? When you look at the bot configuration in the Startup.cs , you can see how it requires you to new up all of the bot dependencies : Is there a different way to configure the bot that allows for dependency injection ? If MyCustomMiddleware requires a typed HttpClient in its constructor , I have to create a new instance right here , so I do n't get the benefit of the DI and the configuration I just set up . services.AddHttpClient < MyFunctionClient > ( client = > { client.BaseAddress = new Uri ( mySettings.GetValue < string > ( `` myFunctionUrl '' ) ) ; client.DefaultRequestHeaders.Add ( `` x-functions-key '' , mySettings.GetValue < string > ( `` myFunctionKey '' ) ) ; } ) ; services.AddBot < QnAMakerBot > ( options = > { options.CredentialProvider = new ConfigurationCredentialProvider ( Configuration ) ; options.ConnectorClientRetryPolicy = new RetryPolicy ( new BotFrameworkHttpStatusCodeErrorDetectionStrategy ( ) , 3 , TimeSpan.FromSeconds ( 2 ) , TimeSpan.FromSeconds ( 20 ) , TimeSpan.FromSeconds ( 1 ) ) ; var middleware = options.Middleware ; middleware.Add ( new ConversationState < ChatLog > ( new MemoryStorage ( ) ) ) ; middleware.Add ( new MyCustomMiddleware ( ) ) ; // < - I want to inject a typed HttpClient here// ... etc . ... .",Dependency Injection for Azure chat bot middleware ? "C_sharp : Does the C # factory pattern require an upcast ? I want God in class library G to create an Adam in class library A without making G dependant on A . God produces Adams for consumption by Eve in class library E , and it 's OK for Eve to know and depend on Adam . ( edit - this sample keeps getting better and better : ) The solution I could think of is having an AdamFactory in A . This way AdamFactory knows Adam and can easily create it ( possibly by just calling Adam 's constructor ) . God receives an AdamFactory and can order it to CreateAdam.Now , because God is n't allowed to know Adam , AdamFacotry 's CreateAdam must return an object , and this requires Eve to up-cast the object returned by AdamFactory to an Adam.This will work , I think . However , I feel uneasy about up-casting as it 's a no-no . Is this really a must ? P.S . - No Blasphemy intended , and I apologize if someone 's feelings were hurt . It seemed better to use God and Adam instead of Creator and Created because the two latter words are too similar to each other.Edit : Re interfaces suggestion . Let 's assume Adam has two methods : ProvideLove , ProvideFood and ProvideProtection ( we 're keeping this sample kis-safe : ) . Eve uses Adam for these two purposes , but of course God does n't . So why provide God with the knowledge that AdamFactor returns something that implements an IAdam and not just an object ? I do n't get it ! Edit : The working code ( with everybody in the same library , which my goal is to separate to different libraries ) looks something like this : Adam God.LoadAdam ( AdamID theAdamID ) var adam = new Adam ( theAdamId , this ) Adam.Adam ( AdamID theAdamID , God theGod ) _god = theGod _mind = theGod.LoadMind ( theAdamId , this ) Mind God.LoadMind ( AdamID theAdamID , Adam theAdam ) var mind = new Mind ( theAdam ) var mindId = new minId ( theAdamId ) mind.DeserializeFromFile ( minId ) Mind.Mind ( Adam theAdam ) _adam = theAdam",C # factory - is upcast a must ? "C_sharp : I am doing the design of a small project where I did n't use programming against interfaces for all my classes . I found that some classes would hardly ever be needed to change , so I let them be referenced by their client classes as concrete classes.So , let 's say we have ClassB that 'll be consumed be consumed by ClassA : My question is , should I create ClassB in ClassA , or should I pass that responsability `` up '' in the hierarchy ? I 'll depict both cases : orI 'd like to hear about how would you do it and what 'd be the rationale behind it ! Thanks class ClassB { } class ClassA { private ClassB classB ; public ClassA ( ) { this.classB = new ClassB ( ) ; } } class ClassA { private ClassB classB ; public ClassA ( ClassB classB ) { this.classB = classB ; } }",Should I make concrete class dependencies explicit through constructor injection in my classes ? "C_sharp : I am trying to sub-select a Dictionary < String , Double > from a Dictionary < String , String > . To do this , I use a IEnumrable < > .Where so sub-select a Dictionary < String , String > ( which works ) , then cast it to Dictionary < String , Double > ( does n't work ) .My Code : What am I doing wrong ? The reason I need it in a Dictionary < String , Double > format is because I have a method that takes in this type that I need to pass the dictionary data to.Thanks in advance ! SIMILAR QUESTIONS : My question is similar to these : http : //bit.ly/12qjrmE , http : //bit.ly/YmuRHZ and http : //bit.ly/XLQNaB , except that I want the subquery to return a Dictionary type as well . //linesTable is an System.data.DataTable object// ... for loop code in hereDataRow row = linesTable.Rows [ i ] ; //Where i is the loop indexDictionary < String , String > valuesDictionary = row.Table.Columns.Cast < DataColumn > ( ) .ToDictionary ( col = > col.ColumnName , col = > row.Field < String > ( col.ColumnName ) ) ; //ATTEMPT # 1/*Dictionary < String , Double > numericValues = valuesDictionary.Where ( subs = > { double doubleValue ; return double.TryParse ( subs.Value , out doubleValue ) ; } ) .Cast < Dictionary < String , Double > > ( ) ; *///ATTEMPT # 2Dictionary < String , Double > numericValues = valuesDictionary.Where ( subs = > { double doubleValue ; return double.TryParse ( subs.Value , out doubleValue ) ; } ) .ToDictionary < String , Double > ( pair = > pair.Key , pair = > double.Parse ( pair.Value ) ) ;",LINQ Sub-select from Dictionary based on value type "C_sharp : I am using LINQ exprssion to query customers and filter them by state names . I have following query which works fine till the time I have 4 items in my statesArray.I want following exprssion to be created dynamically : For example , create the dynamicQuery like below and then use it something like following , public void GetCustomersForSelectedStates ( string [ ] statesArray ) { var customers = _repo.GetAllCustomers ( ) ; var filteredCustomers = from CUST in customers join ST in States on CT.Tag_Id equals ST.Id where CUST.ID == customer.ID & & ( ST.Name == statesArray [ 0 ] ||ST.Name ==statesArray [ 1 ] || ST.Name== statesArray [ 2 ] ||ST.Name =statesArray [ 3 ] ) //Do something with customers } ( ST.Name == statesArray [ 0 ] ||ST.Name ==statesArray [ 1 ] || ST.Name== statesArray [ 2 ] ||ST.Name =statesArray [ 3 ] ) var dynamicQuery = `` ( `` ; var dynamicQuery = `` ( `` ; for ( int i = 0 ; i < statesArray.Count ( ) ; i++ ) { dynamicQuery += `` ST.Name == '' +statesArray [ 0 ] ; if ( i==statesArray.Count ( ) ) dynamicQuery+= '' ) '' } //Psuedo codevar customers = _repo.GetAllCustomers ( ) ; var filteredCustomers = from CUST in customers join ST in States on CT.Tag_Id equals ST.Id where CUST.ID == customer.ID & & Expression ( dynamicQuery )",Generate dynamic LINQ expression based on array "C_sharp : what I mean by that is : I basically have a class that has too many properties and functions now . To remain performant and understandable , it needs to shrink somehow . But I still need all those properties and methods somewhere.It 's like this right now : In most cases the class needs almost none of those properties . In some cases in needs to be able to grow very selectively and gain a feature or lose a feature.The only solution I have come up with , is that I create a bunch of classes and place some properties in there . I only initialize this classes object when one of those properties is needed , otherwise it remains null.Many problems because of that : I constantly have to check for every single object and feature each frame . If the seed is not initialized I do n't have to calculate anything for it . If it is , I have to.If I decided to put more than 1 property/feature into the Seed class , I need to check every single one of those aswell.It just gets more and more complicated . The problem I have is therefore , that I need granular control over all the features and ca n't split them intelligently into larger subclasses . Any form of subclass would just contain a bunch of properties that need to be checked and updated if wanted.I ca n't exactly create subclasses of Apple , because of the need for such high granular control . It would be madness to create as many classes as there are combinations of properties.My main goal : I want short code . class Apple float seedCount ; ... ... about 25 variables and properties here . void Update ( ) < -- a huge method that checks for each property and updates if so class Apple Seed seed ;",How best design a scalable class ? "C_sharp : I have some code like : and the MessageBox.Show complains saying : `` can not convert from 'int ' to 'string ' '' I seem to remember some cases where values seem to be implicitly converted to string values , but ca n't recall them exactly.What 's the reason behind this decision that any value is n't implicitly convertible to string values ? int value = 5 ; MessageBox.Show ( value ) ;",Why are n't values implicitly convertible to string in C # ? "C_sharp : I know LINQ has a SequenceEquals method . This method makes sure each item value in each collection matches , in the same order.What I 'm looking for is a more `` Equivalent '' type of functionality . Just that both sequences contain the same items , not necessarily in the same order.For example , nUnit has CollectionAssert.AreEqual ( ) and CollectionAssert.AreEquivalent ( ) that do what I 'm explaining.I know that I can do this either by : Ordering the lists ahead of time and using SequenceEqualsUsing Intersect , then seeing if the intersection is equal to the original sequence.Example : var source = new [ ] { 5 , 6 , 7 } ; source.Intersect ( new [ ] { 5 , 7 , 6 } ) .Count ( ) == source.Length ;",Is there a LINQ equivalent method ? "C_sharp : I 'm currently making a chatbot with Microsoft 's Bot Framework . In my flow I have a final dialog that lets the user know , that they are participating in the competition . There is also an error-handling method for unknown input . The two methods are seen here : And here is the AbstractBasicDialog implementation : The call chain starts at this dialog : This works most of the time . The user is told that their registration was a success and the flow exits with the context.Done ( ) call . Sometimes however the chatbot does n't register the dialog as being exited , as seen here : As you can see the chatbot is still in the same Dialog even though I have called the Done ( ) method . This is a general problem in my chatbot , as it happens sometimes in all my dialogs.Do you have any input as to what could be wrong ? EDIT : When debugging this I 've added breakpoints every time it calls context.Call . When my issue arises it stops hitting these breakpoints afterwards . Could this be a side-effect of some DI or something ? This is my DI code : [ Serializable ] public class ConcertCityDialog : AbstractBasicDialog < DialogResult > { private static FacebookService FacebookService = > new FacebookService ( new FacebookClient ( ) ) ; [ LuisIntent ( `` ConcertCity '' ) ] public async Task ConcertCityIntent ( IDialogContext context , LuisResult result ) { var fbAccount = await FacebookService.GetAccountAsync ( context.Activity.From.Id ) ; var selectedCityName = result.Entities.FirstOrDefault ( ) ? .Entity ; concert_city selectedCity ; using ( var concertCityService = new ConcertCityService ( ) ) { selectedCity = concertCityService.FindConcertCity ( selectedCityName ) ; } if ( selectedCity == null ) { await NoneIntent ( context , result ) ; return ; } user_interaction latestInteraction ; using ( var userService = new MessengerUserService ( ) ) { var user = userService.FindByFacebookIdIncludeInteractions ( context.Activity.From.Id ) ; latestInteraction = user.user_interaction.MaxBy ( e = > e.created_at ) ; } latestInteraction.preferred_city_id = selectedCity.id ; latestInteraction.gif_created = true ; using ( var userInteractionService = new UserInteractionService ( ) ) { userInteractionService.UpdateUserInteraction ( latestInteraction ) ; } var shareIntroReply = context.MakeMessage ( ) ; shareIntroReply.Text = `` Great choice ! You are now participating in the competition . If you dare then pass your message \uD83D\uDE0E '' ; await context.PostAsync ( shareIntroReply ) ; var reply = await MessageUtility.MakeShareMessageCard ( context , fbAccount , latestInteraction , false ) ; await context.PostAsync ( reply ) ; context.Done ( DialogResult.Done ) ; } [ LuisIntent ( `` '' ) ] [ LuisIntent ( `` None '' ) ] public async Task NoneIntent ( IDialogContext context , LuisResult result ) { messenger_user user ; using ( var userService = new MessengerUserService ( ) ) { user = userService.FindByFacebookId ( context.Activity.From.Id ) ; } var phrase = CreateMisunderstoodPhrase ( user , result.Query ) ; using ( var misunderstoodPhraseService = new MisunderstoodPhraseService ( ) ) { misunderstoodPhraseService.CreatePhrase ( phrase ) ; } List < concert_city > concertCities ; using ( var concertCityService = new ConcertCityService ( ) ) { concertCities = concertCityService.GetUpcomingConcertCities ( ) .ToList ( ) ; } // Prompt city var reply = context.MakeMessage ( ) ; reply.Text = `` I 'm not sure what you mean \uD83E\uDD14 < br/ > Which Grøn Koncert would you like to attend ? `` ; reply.SuggestedActions = new SuggestedActions { Actions = concertCities.Select ( e = > MessageUtility.MakeQuickAnswer ( e.name ) ) .ToList ( ) } ; await context.PostAsync ( reply ) ; context.Wait ( MessageReceived ) ; } protected override void OnDeserializedCustom ( StreamingContext context ) { } } [ Serializable ] public abstract class AbstractBasicDialog < T > : LuisDialog < T > { protected AbstractBasicDialog ( ) : base ( new LuisService ( new LuisModelAttribute ( ConfigurationManager.AppSettings [ `` LuisAppId '' ] , ConfigurationManager.AppSettings [ `` LuisAPIKey '' ] , domain : ConfigurationManager.AppSettings [ `` LuisAPIHostName '' ] ) ) ) { } [ LuisIntent ( `` Cancel '' ) ] public virtual async Task CancelIntent ( IDialogContext context , LuisResult result ) { var randomQuotes = new List < string > { `` If you say so , I 'll leave you alone for now '' , `` alright then , I 'll leave you alone '' , `` Okay then , I wo n't bother you anymore '' } ; await context.PostAsync ( MessageUtility.RandAnswer ( randomQuotes ) ) ; context.Done ( DialogResult.Cancel ) ; } [ LuisIntent ( `` Start '' ) ] public virtual async Task StartIntent ( IDialogContext context , LuisResult result ) { context.Done ( DialogResult.Restart ) ; } [ LuisIntent ( `` CustomerSupport '' ) ] public async Task CustomerSupportIntent ( IDialogContext context , LuisResult result ) { using ( var userService = new MessengerUserService ( ) ) { var user = userService.FindByFacebookId ( context.Activity.From.Id ) ; if ( user ! = null ) { user.receiving_support = true ; userService.UpdateUser ( user ) ; } } await context.PostAsync ( `` I 'll let customer service know , that you want to talk to them . They will get back to you within 24 hours. < br/ > If at any time you want to return to me , and start passing a message , just type \ '' Stop customer support\ '' . `` ) ; context.Call ( new CustomerSupportDialog ( ) , ResumeAfterCustomerSupport ) ; } private async Task ResumeAfterCustomerSupport ( IDialogContext context , IAwaitable < DialogResult > result ) { context.Done ( await result ) ; } protected misunderstood_phrase CreateMisunderstoodPhrase ( messenger_user user , string phrase ) { return new misunderstood_phrase { phrase = phrase , dialog = GetType ( ) .Name , messenger_user_id = user.id } ; } [ OnDeserialized ] private void OnDeserialized ( StreamingContext context ) { OnDeserializedCustom ( context ) ; } protected abstract void OnDeserializedCustom ( StreamingContext context ) ; } [ Serializable ] public class BasicLuisDialog : LuisDialog < DialogResult > { private static FacebookService FacebookService = > new FacebookService ( new FacebookClient ( ) ) ; public BasicLuisDialog ( ) : base ( new LuisService ( new LuisModelAttribute ( ConfigurationManager.AppSettings [ `` LuisAppId '' ] , ConfigurationManager.AppSettings [ `` LuisAPIKey '' ] , domain : ConfigurationManager.AppSettings [ `` LuisAPIHostName '' ] ) ) ) { } [ LuisIntent ( `` '' ) ] [ LuisIntent ( `` None '' ) ] public async Task NoneIntent ( IDialogContext context , LuisResult result ) { var facebookAccount = await FacebookService.GetAccountAsync ( context.Activity.From.Id ) ; RegisterUser ( facebookAccount , null , out var user ) ; var phrase = CreateMisunderstoodPhrase ( user , result.Query ) ; using ( var misunderstoodPhraseService = new MisunderstoodPhraseService ( ) ) { misunderstoodPhraseService.CreatePhrase ( phrase ) ; } var reply = context.MakeMessage ( ) ; reply.SuggestedActions = new SuggestedActions { Actions = new List < CardAction > { new CardAction { Title = `` Get started '' , Type = ActionTypes.ImBack , Value = `` Get started '' } , new CardAction { Title = `` Customer support '' , Type = ActionTypes.ImBack , Value = `` Customer support '' } } } ; var name = string.IsNullOrEmpty ( facebookAccount.FirstName ) ? `` '' : $ '' { facebookAccount.FirstName } `` ; reply.Text = $ '' Hm , I 'm not sure what you mean { name } \uD83E\uDD14 Here are some ways you can interact with me : '' ; await context.PostAsync ( reply ) ; context.Wait ( MessageReceived ) ; } [ LuisIntent ( `` Greeting '' ) ] [ LuisIntent ( `` Positive '' ) ] [ LuisIntent ( `` Start '' ) ] public async Task GreetingIntent ( IDialogContext context , LuisResult result ) { var rnd = new Random ( ) ; var facebookAccount = await FacebookService.GetAccountAsync ( context.Activity.From.Id ) ; // Initial Greeting var greetings = new List < string > { `` Well hello there '' , `` Hi there '' } ; if ( ! string.IsNullOrEmpty ( facebookAccount.FirstName ) ) { greetings.Add ( `` Hi { 0 } '' ) ; greetings.Add ( `` Hello { 0 } '' ) ; greetings.Add ( `` Welcome { 0 } '' ) ; } if ( facebookAccount.Gender == `` male '' ) greetings.Add ( `` Hey handsome '' ) ; else if ( facebookAccount.Gender == `` female '' ) greetings.Add ( `` Hi gorgeous '' ) ; var randIndex = rnd.Next ( greetings.Count ) ; var greeting = string.Format ( greetings [ randIndex ] , facebookAccount.FirstName ) ; await context.PostAsync ( greeting ) ; await MessageUtility.StartTyping ( context , 300 ) ; country country ; using ( var countryService = new CountryService ( ) ) { country = countryService.FindCountry ( facebookAccount.Locale ) ; } var userHasCountry = RegisterUser ( facebookAccount , country , out var user ) ; // If user contry not found prompt for answer if ( ! userHasCountry ) { var countryReply = context.MakeMessage ( ) ; countryReply.Text = `` You are hard to keep track of - where are you from ? `` ; countryReply.SuggestedActions = new SuggestedActions { Actions = new List < CardAction > { MessageUtility.MakeQuickAnswer ( `` Denmark '' ) , MessageUtility.MakeQuickAnswer ( `` Norway '' ) , MessageUtility.MakeQuickAnswer ( `` Sweden '' ) , MessageUtility.MakeQuickAnswer ( `` Other '' ) } } ; await context.PostAsync ( countryReply ) ; context.Call ( new CountryDialog ( ) , AfterCountryDialog ) ; } else { await FunPrompt ( context , country ) ; } } private async Task AfterCountryDialog ( IDialogContext countryContext , IAwaitable < country > countryAwaitable ) { var country = await countryAwaitable ; var facebookAccount = await FacebookService.GetAccountAsync ( countryContext.Activity.From.Id ) ; using ( var userService = new MessengerUserService ( ) ) { var user = userService.FindByFacebookId ( facebookAccount.Id ) ; user.country = country ; userService.UpdateUser ( user ) ; } var reply = countryContext.MakeMessage ( ) ; reply.Text = `` That 's cool \uD83D\uDE0E '' ; await countryContext.PostAsync ( reply ) ; await MessageUtility.StartTyping ( countryContext , 350 ) ; await FunPrompt ( countryContext , country ) ; } private async Task FunPrompt ( IDialogContext context , country country ) { if ( country ? .name == `` norway '' & & DateTime.Now < new DateTime ( 2018 , 8 , 13 ) ) { var reply = context.MakeMessage ( ) ; reply.Text = `` Unfortunately the competition is n't open in Norway yet . You can still talk to customer support if you want to '' ; reply.SuggestedActions = new SuggestedActions { Actions = new List < CardAction > { MessageUtility.MakeQuickAnswer ( `` Customer support '' ) } } ; await context.PostAsync ( reply ) ; context.Wait ( MessageReceived ) ; } else if ( ( country ? .name == `` denmark '' & & DateTime.Now > = new DateTime ( 2018 , 7 , 29 ) ) || ( country ? .name == `` norway '' & & DateTime.Now > = new DateTime ( 2018 , 10 , 21 ) ) ) { var reply = context.MakeMessage ( ) ; reply.Text = `` The competition has ended . You can still talk to customer support if you want to '' ; reply.SuggestedActions = new SuggestedActions { Actions = new List < CardAction > { MessageUtility.MakeQuickAnswer ( `` Customer support '' ) } } ; await context.PostAsync ( reply ) ; context.Wait ( MessageReceived ) ; } else { await context.PostAsync ( `` Are you up for some fun ? `` ) ; context.Call ( new IntroductionDialog ( ) , ResumeAfterDialog ) ; } } [ LuisIntent ( `` CustomerSupport '' ) ] public async Task CustomerSupportIntent ( IDialogContext context , LuisResult result ) { using ( var userService = new MessengerUserService ( ) ) { var user = userService.FindByFacebookId ( context.Activity.From.Id ) ; if ( user ! = null ) { user.receiving_support = true ; userService.UpdateUser ( user ) ; } } await context.PostAsync ( `` I 'll let customer support know , that you want to talk to them . They should be messaging you shortly. < br/ > You can end your conversation with customer support at any time by typing \ '' Stop customer support\ '' . `` ) ; context.Call ( new CustomerSupportDialog ( ) , ResumeAfterDialog ) ; } private async Task ResumeAfterDialog ( IDialogContext context , IAwaitable < DialogResult > result ) { var resultState = await result ; if ( resultState == DialogResult.Restart ) await GreetingIntent ( context , null ) ; else if ( resultState == DialogResult.CustomerSupport ) await ResumeAfterCustomerSupport ( context ) ; else if ( resultState == DialogResult.Done || resultState == DialogResult.Cancel ) context.Done ( resultState ) ; else context.Wait ( MessageReceived ) ; } private async Task ResumeAfterCustomerSupport ( IDialogContext context ) { using ( var userService = new MessengerUserService ( ) ) { var user = userService.FindByFacebookId ( context.Activity.From.Id ) ; if ( user ! = null ) { user.receiving_support = false ; userService.UpdateUser ( user ) ; } } await context.PostAsync ( `` I hope you got the help you needed . Would you like to pass a message to a friend ? `` ) ; context.Call ( new IntroductionDialog ( ) , ResumeAfterDialog ) ; } private bool RegisterUser ( FacebookAccount fbAccount , country country , out messenger_user user ) { if ( string.IsNullOrEmpty ( fbAccount ? .Id ) ) { user = null ; return false ; } using ( var userService = new MessengerUserService ( ) ) { user = userService.FindByFacebookId ( fbAccount.Id ) ; if ( user ! = null ) return user.country ! = null ; user = new messenger_user { id = fbAccount.Id , country = country } ; userService.CreateUser ( user ) ; return user.country ! = null ; } } protected misunderstood_phrase CreateMisunderstoodPhrase ( messenger_user user , string phrase ) { return new misunderstood_phrase { phrase = phrase , dialog = GetType ( ) .Name , messenger_user_id = user.id } ; } } Conversation.UpdateContainer ( builder = > { builder.RegisterModule ( new DialogModule ( ) ) ; builder.RegisterModule ( new ReflectionSurrogateModule ( ) ) ; builder.RegisterModule ( new DialogModule_MakeRoot ( ) ) ; builder.RegisterModule ( new AzureModule ( Assembly.GetExecutingAssembly ( ) ) ) ; var store = new TableBotDataStore ( ConfigurationManager.ConnectionStrings [ `` StorageConnectionString '' ] .ConnectionString ) ; builder.Register ( c = > store ) .Keyed < IBotDataStore < BotData > > ( AzureModule.Key_DataStore ) .AsSelf ( ) .SingleInstance ( ) ; builder.Register ( c = > new CachingBotDataStore ( store , CachingBotDataStoreConsistencyPolicy .ETagBasedConsistency ) ) .As < IBotDataStore < BotData > > ( ) .AsSelf ( ) .InstancePerLifetimeScope ( ) ; builder.RegisterType < BasicLuisDialog > ( ) .As < LuisDialog < DialogResult > > ( ) .InstancePerDependency ( ) ; } ) ;",Bot Framework messes up dialog state "C_sharp : NOTE : I 've changed this question quite a bit in an attempt to make it point more to the problem . The comments below no longer reflect this question.I 'm trying to get this image from fbcdn : https : //scontent.xx.fbcdn.net/v/t1.0-1/c15.0.50.50/p50x50/10354686_10150004552801856_220367501106153455_n.jpg ? oh=6c801f82cd5a32fd6e5a4258ce00a314 & oe=589AAD2FBrowser gets it just fine . Here 's my code : I get a 403 Forbidden response every time . I thought adding the headers would make it work but no go.This code works for other images on other hosts like this one : https : //s-media-cache-ak0.pinimg.com/564x/ff/f0/c9/fff0c988a4516659d4009f60e0694cb6.jpg public class ReverseProxyController : NancyModule { public ReverseProxyController ( ) { Get [ `` / '' , true ] = async ( parameters , ct ) = > { var result = await GetResult ( parameters , ct ) ; return result ; } ; } private async Task < Response > GetResult ( dynamic parameters , CancellationToken ct ) { var client = new HttpClient ( ) ; string url = Request.Query [ `` url '' ] .Value.ToString ( ) ; if ( url == null ) return null ; client.DefaultRequestHeaders.Add ( `` Access-Control-Allow-Origin '' , `` * '' ) ; client.DefaultRequestHeaders.Add ( `` User-Agent '' , `` Mozilla/5.0 ( Windows NT 6.1 ; WOW64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/54.0.2840.71 Safari/537.36 '' ) ; client.DefaultRequestHeaders.Add ( `` Upgrade-Insecure-Requests '' , `` 1 '' ) ; client.DefaultRequestHeaders.Add ( `` Accept '' , `` text/html , application/xhtml+xml , application/xml ; q=0.9 , image/webp , */* ; q=0.8 '' ) ; client.DefaultRequestHeaders.Add ( `` Accept-Encoding '' , `` gzip , deflate , sdch , br '' ) ; client.DefaultRequestHeaders.Add ( `` Accept-Language '' , `` en-US , en ; q=0.8 , ru ; q=0.6 '' ) ; var response = await client.GetAsync ( url , ct ) ; ct.ThrowIfCancellationRequested ( ) ; switch ( response.StatusCode ) { case HttpStatusCode.OK : var stream = await response.Content.ReadAsStreamAsync ( ) ; return Response.FromStream ( stream , response.Content.Headers.ContentType ! = null ? response.Content.Headers.ContentType.ToString ( ) : `` application/octet-stream '' ) ; default : return Response.AsText ( `` \nError `` + response.StatusCode ) ; } } }",Async NancyFX with HttpClient - GetAsync for fbcdn returns 403 forbidden ? "C_sharp : I have an ASP.NET Core 3.1 project . Typically , I register any dependency using the ConfigureServices ( ) method in the Startup.cs class . But , I find myself having to register lots of dependencies and the ConfigureServices ( ) looks huge ! I know I can probably create an extension method of a static method and call it from the ConfigureService ( ) ` class , but wondering if there is a better way.If there a way to register dependencies in the IoC container without having to define them one at a time like this services.AddScoped < Interface , Class > ( ) ; ... . 200 lines laterservices.AddScoped < ISettings , Settings > ( )",Is there a robust way to register dependencies in ASP.NET Core 3.1 beside adding everything into Startup class ? "C_sharp : Some legacy code I 'm stuck maintaining is stuck in an infinite loop ( and thus I myself seem to be in one ) ; I ca n't figure out why/how , though.Here 's the app 's entry point , where it instantiates the main form ( frmCentral ) : CODE EXHIBIT AfrmCentral 's constructor then calls a ( what 's the opposite of glorified ? ) singleton method named DBConnection.GetInstance ( ) : CODE EXHIBIT BHere 's that `` glorified '' sort-of/kind-of singleton method : CODE EXHIBIT CThat instantiates DBConnection and so its constructor is called : CODE EXHIBIT DI see the *MessageBox.Show ( ) *s from Code Exhibit A ( unless otherwise noted ) , then the same for Code Exhibit B , then Code Exhibit C , then Code Exhibit D , then it goes back and forth between C and D `` until the cows come home . `` I do n't see why the DBConnection constructor and the DBConnection GetInstance ( ) recursively call each other , though ... is there a needle in the haystack I 'm missing , or an elephant hidden in plain sight , or ... ? ? ? UPDATEUPDATE 2Here 's more edifying obscurities : UPDATE 3The uncaught exception code I added : I have not seen any evidence that this handler is ever reached , though ( so far , anyway ) .UPDATE 4Very interesting - after adding a MessageBox.Show ( or two ) to GetFormTitle : ... these are the sequence of of MessageBox.Show ( ) s that I see now : ... followed by a round of more tail-chasing , recursive messages until I warm-boot ( I hate to contradict the Fab 4 , but contrary to popular opinion , Happiness is decidedly NOT a warm boot ! * ) ... so right in the midst of a MessageBox message display , an exception is inserted ! Wholly Pennsylvania Hip-Hop ( Key Rap ) ! That was a superlative show of remote desk debugging , LB2 ! public static int Main ( string [ ] args ) { try { AppDomain currentDomain = AppDomain.CurrentDomain ; currentDomain.UnhandledException += new UnhandledExceptionEventHandler ( GlobalExceptionHandler ) ; string name = Assembly.GetExecutingAssembly ( ) .GetName ( ) .Name ; MessageBox.Show ( string.Format ( `` Executing assembly is { 0 } '' , name ) ) ; // TODO : Remove after testing < = this one is seen IntPtr mutexHandle = CreateMutex ( IntPtr.Zero , true , name ) ; long error = GetLastError ( ) ; MessageBox.Show ( string.Format ( `` Last error int was { 0 } '' , error.ToString ( ) ) ) ; // TODO : Remove after testing < = this one is also seen if ( error == ERROR_ALREADY_EXISTS ) { ReleaseMutex ( mutexHandle ) ; IntPtr hWnd = FindWindow ( `` # NETCF_AGL_BASE_ '' , null ) ; if ( ( int ) hWnd > 0 ) { SetForegroundWindow ( hWnd ) ; } return 0 ; } MessageBox.Show ( `` made it into Main method # 4 '' ) ; // TODO : Remove after testing < = this one is seen ReleaseMutex ( mutexHandle ) ; MessageBox.Show ( `` made it into Main method # 5 '' ) ; // TODO : Remove after testing < = this one is seen DeviceInfo devIn = DeviceInfo.GetInstance ( ) ; MessageBox.Show ( `` made it into Main method # 6 '' ) ; // TODO : Remove after testing < = this one is seen Wifi.DisableWifi ( ) ; MessageBox.Show ( `` made it into Main method # 7 '' ) ; // TODO : Remove after testing < = this one is seen // Instantiate a new instance of Form1 . frmCentral f1 = new frmCentral ( ) ; f1.Height = devIn.GetScreenHeight ( ) ; f1.Text = SSCS.GetFormTitle ( `` SSCS HHS '' , `` '' , `` '' ) ; MessageBox.Show ( `` made it before Application.Run ( ) in Main method '' ) ; // TODO : Remove after testing < = this one is NOT seen Application.Run ( f1 ) ; devIn.Close ( ) ; Application.Exit ( ) ; return 0 ; } catch ( Exception ex ) { SSCS.ExceptionHandler ( ex , `` Main '' ) ; return 0 ; } } // Main ( ) method public frmCentral ( ) { try { // // Required for Windows Form Designer support // InitializeComponent ( ) ; MessageBox.Show ( `` made it past InitializeComponent ( ) in frmCentral constructor '' ) ; // < = this displays devIn = DeviceInfo.GetInstance ( ) ; MessageBox.Show ( `` made it past DeviceInfo.GetInstance ( ) in frmCentral constructor '' ) ; // < = this displays dbconn = DBConnection.GetInstance ( ) ; MessageBox.Show ( `` made it past DBConnection.GetInstance ( ) in frmCentral constructor '' ) ; WindowState = FormWindowState.Maximized ; UpdateMenuItemSelectable = false ; ResetConnectionFetchForm = false ; AllowNewItems = true ; listboxWork.Focus ( ) ; MessageBox.Show ( `` made it through frmCentral constructor '' ) ; // < = this one does NOT display } catch ( Exception ex ) { SSCS.ExceptionHandler ( ex , `` frmCentral ( ) '' ) ; } } // frmCentral Constructor // Singleton pattern , or at least a derivation thereofpublic static DBConnection GetInstance ( ) { MessageBox.Show ( `` made it into DBConnection.GetInstance ( ) '' ) ; try { if ( instance == null ) { MessageBox.Show ( `` made it into DBConnection.GetInstance ( ) ; instance was null '' ) ; instance = new DBConnection ( ) ; } } catch ( Exception ex ) { SSCS.ExceptionHandler ( ex , `` DBConnection.GetInstance '' ) ; } return instance ; } private DBConnection ( ) { try { // Connection String string conStr = `` Data Source = `` + filename ; string cmpStr = conStr + `` .tmp '' ; MessageBox.Show ( string.Format ( `` made it into DBConnection constructor . cmpStr == { 0 } '' , cmpStr ) ) ; // TODO : Comment out or remove if ( File.Exists ( filename+ '' .tmp '' ) ) File.Delete ( filename+ '' .tmp '' ) ; engine = new SqlCeEngine ( conStr ) ; MessageBox.Show ( string.Format ( `` SqlCeEngine created . conStr == { 0 } '' , conStr ) ) ; // TODO : Comment out or remove if ( File.Exists ( filename ) ) { MessageBox.Show ( string.Format ( `` file { 0 } exists '' , filename ) ) ; // TODO : Comment out or remove } else { // Create the SQL Server CE database engine.CreateDatabase ( ) ; MessageBox.Show ( `` Made it past call to engine.CreateDatabase ( ) '' ) ; // TODO : Comment out or remove } engine.Dispose ( ) ; objCon = new SqlCeConnection ( conStr ) ; MessageBox.Show ( `` Made it past call to new SqlCeConnection ( conStr ) '' ) ; // TODO : Comment out or remove objCon.Open ( ) ; } catch ( Exception ex ) { SSCS.ExceptionHandler ( ex , `` DBConnection.DBConnection '' ) ; } } public static void ExceptionHandler ( Exception ex , string location ) { try { MessageBox.Show ( `` Exception : `` + ex.Message + `` \n\nLocation : `` + location , GetFormTitle ( `` SSCS : `` + ex.GetType ( ) .FullName , '' '' , '' '' ) ) ; } catch ( Exception exc ) { MessageBox.Show ( `` Exception Handler generated an exception ! \n '' + exc.Message + `` \n\nCalling Location : `` + location , GetFormTitle ( `` SSCS : `` + exc.GetType ( ) .FullName , '' '' , '' '' ) ) ; } } public static string GetFormTitle ( string formName , string serialNo , string siteNo ) { string titleBar = formName == `` '' ? `` SSCS HHS '' : formName ; if ( ( serialNo == `` '' ) ) { User person = new User ( ) ; person.getUserFromTable ( ) ; serialNo = person.getSerialNo ( ) ; } if ( frmCentral.HashSiteMapping.ContainsKey ( siteNo ) ) { siteNo = ( string ) frmCentral.HashSiteMapping [ siteNo ] ; } if ( serialNo ! = `` '' ) titleBar += `` - `` + serialNo + ( siteNo == `` '' ? `` '' : `` Site # '' + siteNo ) ; return titleBar ; } currentDomain.UnhandledException += new UnhandledExceptionEventHandler ( GlobalExceptionHandler ) ; static void GlobalExceptionHandler ( object sender , UnhandledExceptionEventArgs args ) { Exception e = ( Exception ) args.ExceptionObject ; MessageBox.Show ( string.Format ( `` GlobalExceptionHandler caught { 0 } ; Compact Framework Version == { 1 } '' , e.Message , Environment.Version.ToString ( ) ) ) ; } public static string GetFormTitle ( string formName , string serialNo , string siteNo ) { MessageBox.Show ( string.Format ( `` GetFormTitle ( ) reached . formName == { 0 } ; serialNo == { 1 } ; siteNo == { 2 } '' , formName , serialNo , siteNo ) ) ; // TODO : Remove after testing string titleBar = formName == `` '' ? `` SSCS HHS '' : formName ; if ( ( serialNo == `` '' ) ) { User person = new User ( ) ; person.getUserFromTable ( ) ; serialNo = person.getSerialNo ( ) ; } if ( frmCentral.HashSiteMapping.ContainsKey ( siteNo ) ) { siteNo = ( string ) frmCentral.HashSiteMapping [ siteNo ] ; } if ( serialNo ! = `` '' ) titleBar += `` - `` + serialNo + ( siteNo == `` '' ? `` '' : `` Site # '' + siteNo ) ; MessageBox.Show ( string.Format ( `` titleBar val about to be returned . Val is { 0 } '' , titleBar ) ) ; // TODO : Remove after testing return titleBar ; } 0 ) Made it into DBConnection.GetInstance ( ) 1 ) Made it into DBConnection.GetInstance ( ) instance was null2 ) Made it to DBConnection constructor cmpStr == ... .3 ) Sqlceengine created . conStr == ... 4 ) File \My Documents\HHSDB.SDF exists5 ) Made it past call to new SqlCeConnection ( conStr ) 6 ) GetFormTitle ( ) reached . fromName == SSCS : System.Data.SqlserverCe.SqlCeException ; serial No == ; siteNo == * Let 's have no attempts at humor revolving around warm booty , now !",How is this causing an endless loop ? "C_sharp : In the process of writing an `` Off By One '' mutation tester for my favourite mutation testing framework ( NinjaTurtles ) , I wrote the following code to provide an opportunity to check the correctness of my implementation : now this seems simple enough , and it did n't strike me that there would be a problem trying to mutate all the literal integer constants in the IL . After all , there are only 3 ( the 0 , the 1 , and the ++ ) . WRONG ! It became very obvious on the first run that it was never going to work in this particular instance . Why ? Because changing the code to only adds 0 ( zero ) to the sum , and this obviously has no effect . Different story if it was the multiple set , but in this instance it was not.Now there 's a fairly easy algorithm for working out the sum of integerswhich I could have fail the mutations easily , since adding or subtracting 1 from either of the constants there will result in an error . ( given that max > = 0 ) So , problem solved for this particular case . Although it did not do what I wanted for the test of the mutation , which was to check what would happen when I lost the ++ - effectively an infinite loop . But that 's another problem.So - My Question : Are there any trivial or non-trivial cases where a loop starting from 0 or 1 may result in a `` mutation off by one '' test failure that can not be refactored ( code under test or test ) in a similar way ? ( examples please ) Note : Mutation tests fail when the test suite passes after a mutation has been applied.Update : an example of something less trivial , but something that could still have the test refactored so that it failed would be the followingMutation testing against this code would fail when changing the var i=0 to var i=1 if the test input you gave it was new [ ] { 0,1,2,3,4,5,6,7,8,9 } . However change the test input to new [ ] { 9,8,7,6,5,4,3,2,1,0 } , and the mutation testing will fail . So a successful refactor proves the testing . public int SumTo ( int max ) { int sum = 0 ; for ( var i = 1 ; i < = max ; i++ ) { sum += i ; } return sum ; } public int SumTo ( int max ) { int sum = 0 ; for ( var i = 0 ; i < = max ; i++ ) { sum += i ; } return sum ; } sum = max * ( max + 1 ) / 2 ; public int SumArray ( int [ ] array ) { int sum = 0 ; for ( var i = 0 ; i < array.Length ; i++ ) { sum += array [ i ] ; } return sum ; }",Off By One errors and Mutation Testing "C_sharp : I 'm currently trying to get a RichTextBox with basic formatting working for my new beta notes software , Lilly Notes . Brian Lagunas ' article on the subject put me in the right direction , however I 'm having a bit of an issue . If you click on underlined text , the Underline button becomes pressed , so the state is being recognised . However if I serialize it to RTF and then deserialize it back into the RichTextBox , then it does n't get detected . Since the code in Lilly Notes is not trivial to demonstrate here , I have created a SSCCE to demonstrate the problem.First , MainWindow.xaml : This is what it looks like : In the codebehind , I have code to detect the state of the formatting when the selection changes , and update the state of the Underline button accordingly . This is no different from Brian Lagunas ' method.Then I have a method ( and another helper method ) which saves the RTF to a string and then applies it to the RichTextBox . Again I 'm doing this just to keep it simple - in Lilly Notes , I 'm saving that string to a database , and then loading it back when the the application is run again.After I click the Save and Reload button , and the RTF gets serialized to a string and deserialized back into the RichTextBox , underline detection does not work any more , and when I click the underlined text , the button remains as if the underline was not working : Now , when I debugged this , I noticed this : Initially , when you click on a piece of underlined text , you get a TextDecorationCollection with a Count of 1 . But after saving and reloading , you get a Count of zero , which is why the detection is not working.Note that this problem applies only to underline/strikethrough , which belong to the TextDecorationCollection in WPF . Bold and Italic do not exhibit this issue.Is this happening because I am doing something wrong , or is this a bug with the RichTextBox ? You can find the SSCCE code here at my BitBucket repo . < Window x : Class= '' WpfRichTextBoxUnderline.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' Title= '' MainWindow '' Height= '' 350 '' Width= '' 525 '' > < DockPanel LastChildFill= '' True '' > < Button Name= '' SaveAndReloadButton '' Content= '' Save and Reload '' DockPanel.Dock= '' Bottom '' Click= '' SaveAndReloadButton_Click '' / > < ToggleButton Name= '' UnderlineButton '' DockPanel.Dock= '' Top '' Width= '' 20 '' Command= '' { x : Static EditingCommands.ToggleUnderline } '' CommandTarget= '' { Binding ElementName=RichText } '' > < ToggleButton.Content > < TextBlock Text= '' U '' TextDecorations= '' Underline '' / > < /ToggleButton.Content > < /ToggleButton > < RichTextBox Name= '' RichText '' SelectionChanged= '' RichTextBox_SelectionChanged '' / > < /DockPanel > < /Window > private void RichTextBox_SelectionChanged ( object sender , RoutedEventArgs e ) { if ( this.RichText.Selection ! = null ) { object currentValue = this.RichText.Selection.GetPropertyValue ( Inline.TextDecorationsProperty ) ; this.UnderlineButton.IsChecked = ( currentValue == DependencyProperty.UnsetValue ) ? false : currentValue ! = null & & currentValue.Equals ( TextDecorations.Underline ) ; } } public Stream GenerateStreamFromString ( string s ) { MemoryStream stream = new MemoryStream ( ) ; StreamWriter writer = new StreamWriter ( stream ) ; writer.Write ( s ) ; writer.Flush ( ) ; stream.Position = 0 ; return stream ; } private async void SaveAndReloadButton_Click ( object sender , RoutedEventArgs e ) { string data = null ; var range = new TextRange ( this.RichText.Document.ContentStart , this.RichText.Document.ContentEnd ) ; using ( var memoryStream = new MemoryStream ( ) ) { range.Save ( memoryStream , DataFormats.Rtf ) ; memoryStream.Position = 0 ; using ( StreamReader reader = new StreamReader ( memoryStream ) ) { data = await reader.ReadToEndAsync ( ) ; } } // load var stream = GenerateStreamFromString ( data ) ; range = new TextRange ( this.RichText.Document.ContentStart , this.RichText.Document.ContentEnd ) ; range.Load ( stream , DataFormats.Rtf ) ; }",Underline not detected after reloading RTF "C_sharp : I have the following code line : Is there any way , in C # 6 , to make this code shorter ? I have a been looking at a few ? examples but for this case I ca n't find a shorter solution ... Project = x.Project == null ? null : new Model { ... }",Condition with null in C # 6 "C_sharp : I run into this scenario frequently . At first glance , I think , “ That ’ s poor coding ; I ’ m executing a method twice and necessarily getting the same result. ” But upon thinking that , I have to wonder if the compiler is as smart as I am and can come to the same conclusion.Does the behavior of the compiler depend on the contents of the GetOtherThing method ? Say it looks like this ( somewhat similar to my real code right now ) : That will , barring very poorly handled asynchronous changes to whatever store these objects are coming from , definitely return the same thing if run twice in a row . But what if it looked like this ( nonsensical example for the sake of argument ) : Running that twice in a row would result in the creation of two different objects , with different Ids in all likelihood . What would the compiler do in these situations ? Is it as inefficient as it seems to do what I showed in my first listing ? Doing some of the work myselfI ran something very similar to that first code listing and put a breakpoint in the GetOtherThing instance method . The breakpoint was hit once . So , it looks like the result is indeed cached . What would happen in the second case , where the method might return something different each time ? Would the compiler optimize incorrectly ? Are there any caveats to the result that I found ? EDITThat conclusion was invalid . See comments under @ usr ’ s answer . var newList = oldList.Select ( x = > new Thing { FullName = String.Format ( `` { 0 } { 1 } '' , x.FirstName , x.LastName ) , OtherThingId = x.GetOtherThing ( ) ! = null : x.GetOtherThing ( ) .Id : 0 // Might call x.GetOtherThing ( ) twice ? } ) ; public OtherThing GetOtherThing ( ) { if ( this.Category == null ) return null ; return this.Category.OtherThings.FirstOrDefault ( t = > t.Text == this.Text ) ; } public OtherThing GetOtherThing ( ) { return new OtherThing { Id = new Random ( ) .Next ( 100 ) } ; }",Will the C # compiler optimize this code ? "C_sharp : I have the following situation : In a 3rd party library ( can not be modified ) : In my own code : From C 's implementation of method M I want to call A 's ( but not B 's ! ! ) . Can I ? Any tricks accepted , reflection included . I tried reflection already , but using the MethodInfo that I get from typeof ( A ) still generates a virtual call ( calling C 's implementation with subsequent stack overflow ) .Deriving C from A is out of the question due to the complexity of reimplementing B . class A { public virtual void M ( ) { } } class B : A { public override void M ( ) { } } class C : B { public override void M ( ) { } }",How to invoke ( non virtually ) the original implementation of a virtual method ? "C_sharp : Using my cusom EventArgs such as : from msdn e.g : I have 2 questions : 1 ) looking at the marked code : I do n't see a reason why it should be copied to another param ( regarding threads ) since we have the event keyowrd , no one can touch its invocation list ( no outsider code to the class I mean ) 2 ) If I 'm not mistaken , the DemoEvent function should be virtual , so it can be overridden in sub classes ... ( I 'm sure I 've seen it somewhere ) the strange thing is that resharper also wo n't add virtual : so if I have this code : it suggests me : and when I press it : so again my 2 questions : 1 ) What is the scenario which this line EventHandler < MyEventArgs > temp = SampleEvent ; will solve , regarding thread safty ? 2 ) Should n't the function be virtual ? ( I 'm sure I 've seen this pattern with virtual ) public event EventHandler < MyEventArgs > SampleEvent ; public class HasEvent { // Declare an event of delegate type EventHandler of // MyEventArgs . public event EventHandler < MyEventArgs > SampleEvent ; public void DemoEvent ( string val ) { // Copy to a temporary variable to be thread-safe . EventHandler < MyEventArgs > temp = SampleEvent ; if ( temp ! = null ) temp ( this , new MyEventArgs ( val ) ) ; } }",EventHandler < TEventArgs > thread safety in C # ? "C_sharp : I already opened an issue in Azure/azure-functions-host and I have a repo with the repro steps , but I 'm posting this here in case there is something inherently wrong with what I 'm doing , or someone has already stumbled open this issue.My goal : I want to run in an azure function some code that lives in a class library in an existing visual studio solution.This code happens to use entity framework core in order to read and write to a SQL Server database.While trying to isolate the issues I was facing , I ended up with the following scenario : Repro steps : In Visual Studio : File > New > Project > Azure FunctionsSelect Azure Functions v2 Preview ( .NET Core ) Select Http triggerSelect Storage EmulatorSelect Access rights FunctionInstall using nuget Microsoft.EntityFrameworkCore version 2.0.2Add an invocation to anything from the EFCore packageIn my case I added the following line : Ensure the azure storage emulator is runningRun the function from visual studio ( F5 ) Hit the url printed in the consoleExpected behavior : along with the default behavior of the example Http trigger function I expect to see the following line printed with each invocation : Actual behavior : the app throws an exception at runtime and outputs the following [ 11-Apr-18 6:33:59 AM ] Executing 'Function1 ' ( Reason='This function was programmatically called via the host APIs . ' , Id=6faabfd8-eb96-4d71-906c-940028a7978a ) [ 11-Apr-18 6:33:59 AM ] Executed 'Function1 ' ( Failed , Id=6faabfd8-eb96-4d71-906c-940028a7978a ) [ 11-Apr-18 6:33:59 AM ] System.Private.CoreLib : Exception while executing function : Function1 . FunctionApp1 : Could not load file or assembly 'Microsoft.EntityFrameworkCore , Version=2.0.2.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60 ' . Could not find or load a specific file . ( Exception from HRESULT : 0x80131621 ) . System.Private.CoreLib : Could not load file or assembly 'Microsoft.EntityFrameworkCore , Version=2.0.2.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60'.Current conjecture : while researching this issue I found something that might be related : The Azure functions runtime already has a set of packages available , one of those being Newtonsoft.Json in a specific version . In the case a newer version of Newtonsoft.Json is referenced from the project a similar behavior is observed.Here 's a StackOverflow question . Here 's a github issue log.Info ( typeof ( DbContext ) .AssemblyQualifiedName ) ; Microsoft.EntityFrameworkCore.DbContext , Microsoft.EntityFrameworkCore , Version=2.0.2.0 , Culture=neutral , PublicKeyToken=adb9793829ddae60",Unable to load Entity Framework Core into C # azure function "C_sharp : I am trying to do some automated web testing of my ASP.NET application . I was hoping to use the AutoRollback attribute from Xunit.net extensions to undo any database changes that were made during the test . AutoRollback uses TransactionScope to start a transaction before the test and roll it back afterwards . When I try to hit my web application during a transaction , it always times out . It seems like this should work , any ideas ? Here is my test : [ Fact ] [ AutoRollback ] public void Entity_should_be_in_list ( ) { Entity e = new Entity { Name = `` Test '' , } ; dataContext.Entities.InsertOnSubmit ( e ) ; dataContext.SubmitChanges ( ) ; selenium.Open ( `` http : //localhost/MyApp '' ) ; Assert.True ( selenium.IsTextPresent ( `` Test '' ) ) ; }",Can TransactionScope rollback be used with Selenium or Watin ? "C_sharp : in my create view I want to give the user the possibility to create a list of objects ( of the same type ) . Therefore I created a table in the view including each inputfield in each row . The number of rows respective `` creatable '' objects is a fixed number.Lets say there is a class Book including two properties title and author and the user should be able two create 10 or less books.How can I do that ? I do n't know how to pass a list of objects ( that are binded ) to the controller . I tried : And in the view it is : As booklist is null , it does n't work and I do n't know how to put all created objects in this list.If you have any suggestions I would be very thankful . [ HttpPost ] [ ValidateAntiForgeryToken ] public ActionResult Create ( ICollection < Book > bookList ) { if ( ModelState.IsValid ) { foreach ( var item in bookList ) db.Books.Add ( item ) ; db.SaveChanges ( ) ; return RedirectToAction ( `` Index '' ) ; } return View ( articlediscounts ) ; } < fieldset > < legend > Book < /legend > < table id= '' tableBooks '' class= '' display '' cellspacing= '' 0 '' width= '' 100 % '' > < thead > < tr > < th > Title < /th > < th > Author < /th > < /tr > < /thead > < tbody > @ for ( int i = 0 ; i < 10 ; i++ ) { < tr > < td > < div class= '' editor-field '' > @ Html.EditorFor ( model = > model.Title ) @ Html.ValidationMessageFor ( model = > model.Title ) < /div > < /td > < td > < div class= '' editor-field '' > @ Html.EditorFor ( model = > model.Author ) @ Html.ValidationMessageFor ( model = > model.Author ) < /div > < /td > < /tr > } < /tbody > < /table > < p > < input type= '' submit '' value= '' Create '' / > < /p > < /fieldset >",Create more than one object of the same type in the same view "C_sharp : This converts false to 0 and true to 1 , can someone explain to me how the t ? 1 : 0 works ? // Example bool is truebool t = true ; // Convert bool to intint i = t ? 1 : 0 ; Console.WriteLine ( i ) ; // 1",c # Can someone explain this boolean logic "C_sharp : UPDATEI 've just had a thought that may well be relevant to this issue . I 'm using a code first approach with this project . Originally my ZoneMapping class was defined as you can see below , however the database only had a single PrimaryKey field in the database . I believe because EF had n't interpreted the data quite correctly.At this point I made a modification to my migration SQL script output to add the additional primary key that I applied to the database . I 've just updated the migration instead from : I 've just tried adding an additional PrimaryKey manually in the migration after the PostcodeKey one has been defined.Unfortunately I 'm still getting my error - I 'm assuming this migration is n't used to build the EF 'model ' in code , but I 'm wondering if it thinks that there can only be a single entry with any given PostcodeKey which may explain the situation ? I 'm posting a new question based on Linq Except not functioning as expected - duplicate items because I feel that enough has been discovered that the question is invalid , and Except is not the problem at all.The problem I have is that I have a Linq Where clause that seems to be returning the wrong data . The data in my database looks like : The class that represents this data has a compound key : So I 'm executing the following code , which results in different IDs : The SQL ( or ToString ( ) for these two items is identical ) . So the only difference is that one is a new context , while the other has been passed in and used for some other stuff . The code that creates the context returning the wrong result is : This then registers a ClassMap in the library that I 'm using where : I do a lookup using the context : I ca n't see anything strange going on here , I 've verified the SQL generated by Entity Framework , verified the database is the same one - I ca n't understand why the wrong record would be returned . Can anyone shed any light on this ? CreateTable ( `` dbo.NetC_EF_ZoneMapping '' , c = > new { PostcodeKey = c.String ( nullable : false , maxLength : 128 ) , Zone_ID = c.Int ( ) , } ) .PrimaryKey ( t = > t.PostcodeKey ) .ForeignKey ( `` dbo.NetC_EF_Zone '' , t = > t.Zone_ID ) .Index ( t = > t.Zone_ID ) ; .PrimaryKey ( t = > t.Zone_ID ) /// < summary > /// Represents a mapping between a postcode and a zone/// < /summary > [ Table ( `` NetC_EF_ZoneMapping '' ) ] public class ZoneMapping { /// < summary > /// Gets or sets the postcode identifier /// < /summary > [ Key ] public String PostcodeKey { get ; set ; } /// < summary > /// Gets or sets the Zone identifier /// < /summary > [ Key ] public Zone Zone { get ; set ; } } var result = this.context.ZoneMappings.Include ( `` Zone '' ) .Where ( z = > z.Zone.ID == 257 & & z.PostcodeKey == `` 2214 '' ) ; var result2 = new FreightContext ( ) .ZoneMappings.Include ( `` Zone '' ) .Where ( z = > z.Zone.ID == 257 & & z.PostcodeKey == `` 2214 '' ) ; if ( result.First ( ) .Zone.ID ! = result2.First ( ) .Zone.ID ) throw new InvalidOperationException ( ) ; // Copy the contents of the posted file to a memory stream using ( StreamReader sr = new StreamReader ( fileUpload.PostedFile.InputStream ) ) using ( FreightContext context = new FreightContext ( ) ) { // Attempt to run the import ZoneMappingCSVImporter importer = new ZoneMappingCSVImporter ( sr , context , System.Globalization.CultureInfo.CurrentUICulture ) ; var items = importer.GetItems ( ) .ToList ( ) ; importer.SaveItems ( items ) ; this.successBox.Value = `` Import completed and added `` + items.Count ( ) + `` zones mappings . `` ; } public ZoneMappingCSVImporter ( TextReader textReader , FreightContext context , CultureInfo culture ) : base ( textReader , context , culture ) { this.reader.Configuration.RegisterClassMap ( new ZoneMappingMap ( this.context ) ) ; } /// < summary > /// Initializes a new instance of the < see cref= '' ZoneMap '' / > class . /// < /summary > public ZoneMappingMap ( FreightContext context ) { if ( context == null ) throw new ArgumentNullException ( `` context '' ) ; Map ( m = > m.PostcodeKey ) ; Map ( m = > m.Zone ) .ConvertUsing ( row = > { // Grab the name of the zone then go find this in the database String name = row.GetField < String > ( `` Zone '' ) ; return context.Zones.Where ( z = > String.Compare ( z.Name , name , true ) == 0 ) .FirstOrDefault ( ) ; } ) ; }",Where returns wrong record "C_sharp : I 'm trying to create a multi-column unique index using a shadow property . I know I can solve this problem with just adding a property , but I would like to see if this is possible in a way to keep my model clean.To create a multi-column index you have the following option in Fluent API : But I do n't want to clutter my model with an extra AlbumId property and thus would like to use a shadow property , for a single column this works as followed : I tried the following : However my IDE throws the following error : Invalid anonymous type member declarator . Anonymous type members must be declared with a member assignment , simple name or member access.Anybody has an idea how to do this with using a shadow properties or is this just not possible ? edit : various grammar arrors . modelBuilder.Entity < AlbumTrack > ( ) .HasIndex ( t = > new { t.TrackNumber , t.AlbumId ) .IsUnique ( ) ; modelBuilder.Entity < AlbumTrack > ( ) .HasIndex ( t = > EF.Property < int > ( t , '' AlbumId '' ) ) .IsUnique ( ) ; modelBuilder.Entity < AlbumTrack > ( ) .HasIndex ( t = > new { t.TrackNumber , EF.Property < int > ( t , '' AlbumId '' ) } ) .IsUnique ( ) ;",EF can you make a Mutli-column Index using shadow properties ? "C_sharp : I 'm looking for ways to obfuscate the following c # /silverlight source code : So far all I can come up with to hide it is encoding the strings as arrays of ascii ... All I want is for the source code to be unreadable , this is for an easter egg . Security is not a priority for me.I do n't want the presence of an easter egg to be known . I 'm trying to obfuscate the program flow so it does n't appear like there is a line of code likeI 've seen stuff on like the obfuscated c contest where hello world turns into globbidy gook . Anything similar that people know of for c # ? if ( searchBox.Text.Equals ( `` string literal '' ) ) { MessageBox.Show ( `` another string literal '' ) ; } if ( specialcase ) doEasterEgg ( ) ;",Ways to obfuscate c # /silverlight source code "C_sharp : I have the following base class : and the following derived classes : and I also have this function that is provided by a service : My problem is how can I call this function generically ? I want to call it with something that looks like this : This of course does n't work because at this point T is not known . How can I accomplish something similar to this ? EntityLogicalName and EntityNumberOfChars are characteristics that all Base derived classes have and they never change for each derived class . Can I get them from the Base class without instantiating objects or some other way that I am not seeing ? public class Base { public string LogicalName { get ; set ; } public int NumberOfChars { get ; set ; } public Base ( ) { } public Base ( string logicalName , int numberOfChars ) { LogicalName = logicalName ; NumberOfChars = numberOfChars ; } } public class Derived1 : Base { public const string EntityLogicalName = `` Name1 '' ; public const int EntityNumberOfChars = 30 ; public Derived1 ( ) : base ( EntityLogicalName , EntityNumberOfChars ) { } } public class Derived2 : Base { public const string EntityLogicalName = `` Name2 '' ; public const int EntityNumberOfChars = 50 ; public Derived2 ( ) : base ( EntityLogicalName , EntityNumberOfChars ) { } } public IEnumerable < T > GetEntities < T > ( string entityName , int numberOfChars ) where T : Base { //Some code to get the entities } public void TestEntities < T > ( ) where T : Base { var entities = GetEntities < T > ( T.EntityLogicalName , T.EntityNumberOfChars ) ; //some other code to test the entities }",Access const with generics C # "C_sharp : I need to initialize my object like below : but in CodeDOM I could only find : and this is using parentheses to initialize instead of brackets . is there a CodeDOM approach for this ? ( I already make my code using stringBuilder but I 'm looking for a CodeDOM approach ) thanks var obj = new EduBranch { Id = model.Id , WorklevelId = model.WorklevelId , EdulevelId = model.EdulevelId , Title = model.Title , StartEduYearId = model.StartEduYearId , EndEduYearId = model.EndEduYearId , } ; var objectCreate1 = new CodeObjectCreateExpression ( `` EduBranch '' , new CodeExpression [ ] { } ) ;",How to initialize object with CodeDOM ? "C_sharp : I am trying to randomly choose from e.g . 4 numbers . I need to compare the probability of these 2 algorithms.1 # 2 # Am I right if I think that it is the same ? The probability of statement1 in the first code is 1/4 and in the second code it is 250/1000 so it ’ s 1/4 too . But someone has told me when I use bigger range of random numbers like in code 2 # it ’ s statistically more accurate . I ’ ve made project which repeats many times those codes , but I ’ m not sure it shows me some results . int a = random.Next ( 0 , 4 ) ; if ( a = 0 ) statement1 if ( a = 1 ) statement2 if ( a = 2 ) statement3 if ( a = 3 ) statement4 int a = random.Next ( 0 , 1000 ) if ( a < 250 ) statement1 if ( a > = 250 & & a < 500 ) statement2 if ( a > = 500 & & a < 750 ) statement3 if ( a > = 750 ) statement4",Random numbers probability "C_sharp : It is possible in C # to add variance annotation to type parameter , constrained to be value type : Why is this allowed by compiler if variance annotation makes completely no sense in a such situation ? interface IFoo < in T > where T : struct { void Boo ( T x ) ; }","C # variance annotation of a type parameter , constrained to be value type" "C_sharp : My team and I came accross a weird behavior with JSON.NET deserialization in C # .We have a simple ViewModel with a IOrderedEnumerable < long > : Then , we just want to POST/PUT this viewmodel in an API controllerCalling this API with a json that look like that : With this call , we saw that the constructor was n't called ( which can be explained by the fact that it 's not a default constructor ) . But the strange thing is that if we change the type of the collection to IEnumerable or IList , the constructor is properly called.If we change the constructor of TestClass to be a default one : The object retrieve by the controller will not be null.And if we change the type of the collection to IEnumerable and we keep the constructor with a parameter ( public TestClass ( string name ) ) , it 'll work also.Another strange thing is that the object test in the controller is `` null '' . Not only the orderedDatas is null , but the entire object.If we add an attribute [ JsonObject ] on the class , and an [ JsonIgnore ] on the property orderedData , it works.For now , we changed the object to a simple List and it 's working fine , but we were wondering why the JSON deserialization act different depending on the type of the collection.If we use directly the JsonConvert.Deserialize : we can saw the actual exception : Can not create and populate list type System.Linq.IOrderedEnumerable ` 1 [ System.Int64 ] . Path 'orderedDatas ' , line 1 , position 33.Any idea / help is appreciated.Thanks ! ** Edit : thanks for your answers . There is one thing that I keep finding weird ( I put it in bold ) , if you have any idea to explain this behavior , please tell me ** public class TestClass { public IOrderedEnumerable < long > orderedDatas { get ; set ; } public string Name { get ; set ; } public TestClass ( string name ) { this.Name = name ; this.orderedDatas = new List < long > ( ) .OrderBy ( p = > p ) ; } } [ HttpPost ] public IHttpActionResult Post ( [ FromBody ] TestClass test ) { return Ok ( test ) ; } { Name : `` tiit '' , `` orderedDatas '' : [ 2 , 3 , 4 ] , } public class TestClass { public IOrderedEnumerable < long > orderedDatas { get ; set ; } public string Name { get ; set ; } public TestClass ( ) { this.Name = `` default '' ; this.orderedDatas = new List < long > ( ) .OrderBy ( i = > i ) ; } } var json = `` { Name : 'tiit ' , 'orderedDatas ' : [ 2,3,4,332232 ] } '' ; var result = JsonConvert.DeserializeObject < TestClass > ( json ) ;",Deserialization of IOrderedEnumerable < T > with JSON.NET "C_sharp : I 'm new to AutoFixture , so I do n't know if the following idea is going to make sense or be a reasonable thing to do . I 've got an application that I 'm in charge of integration testing , and it makes heavy use of Castle Windsor . To simplify dependency management and make my tests more like the application code , I 've been building the Windsor container in my test initialize method and the using container.Resolve to instantiate the code I 'm testing . I 'd like to move away from that approach since it has limited my flexibility in certain situations . What I 'd like to do is have tests that look something like this : To make this happen , I can do the following : Doing this does work , but what I 'd like to avoid is needing to copy every interface to implementation mapping from the Windsor container into the AutoFixture IFixture . [ Theory ] [ Dependency ] public void TestWithDependencies ( IThing thing ) { thing.Hello ( ) ; } public sealed class DependencyAttribute : AutoDataAttribute { public DependencyAttribute ( ) : base ( new Fixture ( ) .Customize ( new WindsorCustomization ( ) ) ) { } } public class WindsorCustomization : ICustomization { public WindsorCustomization ( ) { // build container here using SUT installers } public void Customize ( IFixture fixture ) { fixture.Inject < IThing > ( new Thing ( ) ) ; } }",Technique for using AutoFixture to integration test an application using Castle Windsor "C_sharp : When implementing dynamic dispatch using dynamic on a generic class , and the generic type parameter is a private inner class on another class , the runtime binder throws an exception.For example : Here , a RuntimeBinderException will be thrown with the message 'Dispatcher.CallDispatch ( int ) ' is inaccessible due to its protection levelThe reason for the inaccessibility is that the type parameter T is the private CallType which Dispatcher < T > can not access . Therefore , CallDispatch must be inaccessible - but it is n't , because it 's accessible as T.Is this a bug with dynamic , or is this not supposed to be supported ? using System ; public abstract class Dispatcher < T > { public T Call ( object foo ) { return CallDispatch ( ( dynamic ) foo ) ; } protected abstract T CallDispatch ( int foo ) ; protected abstract T CallDispatch ( string foo ) ; } public class Program { public static void Main ( ) { TypeFinder d = new TypeFinder ( ) ; Console.WriteLine ( d.Call ( 0 ) ) ; Console.WriteLine ( d.Call ( `` '' ) ) ; } private class TypeFinder : Dispatcher < CallType > { protected override CallType CallDispatch ( int foo ) { return CallType.Int ; } protected override CallType CallDispatch ( string foo ) { return CallType.String ; } } private enum CallType { Int , String } }",Is this a bug in dynamic ? "C_sharp : I am currently porting a .NET codebase in MonoTouch and I 'm currently working on a method that receives an Expression < T > . I 'm trying to compile it , and then dynamically invoke it.Here 's what I did : This works fine in the iOS Simulator , the result `` 12 '' is printed in my console . But then I tried it on an iPad , and I received the following exception.What am I doing wrong and how could I make it work ? // Here 's an example of what I could receiveExpression < Action < int > > expression = ( a = > Console.WriteLine ( a * 2 ) ) ; // And here 's what I 'm trying to do to invoke itexpression.Compile ( ) .DynamicInvoke ( 6 ) ; Object reference not set to an instance of an object at System.Linq.jvm.Runner.CreateDelegate ( ) at System.Linq.Expressions.LambdaExpression.Compile ( ) at System.Linq.Expressions.Expression ` 1 [ System.Action ` 1 [ System.Int32 ] ] .Compile ( ) at TestSolution2.AppDelegate.FinishedLaunching ( MonoTouch.UIKit.UIApplication app , MonoTouch.Foundation.NSDictionary options )",Compiling lambdas and invoking delegates on the device in Monotouch "C_sharp : I am currently writing a simple WPF file copy app that copies files in parallel . So far it works great ! It does everything I want it to do . The meat of the operation is in the following block of code : I can implement ParallelOptions and limit the maximum number of threads to 4 as well , but I was wondering if there is a way to accurately keep track of what each thread would be doing in that case ? For example , say I have some portion of my UI that is dedicated to the current `` Status '' of the copy operation . I would want to have 4 rows in a Grid that each had a particular thread and which file it was currently copying.I know I can use Interlocked to manipulate variables that are outside of the Parallel loop , but how would I keep track of thread-specific variables from inside of the Parallel loop and use those variables to keep the UI up to date on which thread is working on which file ? Parallel.ForEach ( Directory.GetFiles ( dir ) .ToList ( ) , file = > { _destDetail.CurrOp = string.Format ( `` Copying file : { 0 } '' , Path.GetFileName ( file ) ) ; File.Copy ( file , file.Replace ( _destDetail.Source , _destDetail.Dest ) , true ) ; if ( _destDetail.Progress < _destDetail.MaxProgress ) _destDetail.Progress++ ; } ) ;",Keep track of Parallel Foreach threads "C_sharp : This snippet is not compiled in LINQPad.The compiler 's error message is : No overload for 'UserQuery.IsNull ( object ) ' matches delegate 'System.Func'It works for a string array , but does n't work for int [ ] . It 's apparently related to boxing , but I want to know the details . void Main ( ) { ( new [ ] { 0,1,2,3 } ) .Where ( IsNull ) .Dump ( ) ; } static bool IsNull ( object arg ) { return arg == null ; }",Why does n't delegate contravariance work with value types ? "C_sharp : I 'm poking around a few dlls within the XNA framework using ILSpy and came across this : What is the exclamation mark for in the above ? Is it an issue with ILSpy , or something else ? Note , the class has a separate destructor : private unsafe void ~KerningHelper ( ) . class KerningHelper { private void ! KerningHelper ( ) { ( ( IDisposable ) this ) .Dispose ( ) ; } }",Odd class member syntax shown in ILSpy "C_sharp : Note : I already checked msdn , it does n't address my actual question , see below.I 'm trying to use the obsolete attribute on a ( obviously obsolete ) constructor in one of my classes . Here 's the scenario : I want to be able to force the developer to update to the new constructor without affecting already existing and deployed code . This way I can deploy my code to production just fine , but from a developers perspective , whenever they go into their code , instead of just getting a `` warning '' which I 'm sure they 'll just ignore , I want them to get a compile error because the status quo is no longer ok.So my question is , will this affect only developers , or all calling apps , or do I have the whole thing wrong ? sample code : Any and all help will be appreciated , thanks in advance ! public class MyClass { private string _userID ; //new code [ Obsolete ( `` This constructor is obsolete , please use other constructor . `` , true ) ] public MyClass ( ) { _userID = `` '' ; //defaulting to empty string for all those using this constructor } public MyClass ( string userID ) { _userID = userID ; //this is why they need to use this constructor } }","Uses for [ Obsolete ( string , bool ) ] attribute for .NET" "C_sharp : Can anyone point me to an example of or briefly describe how one would go about creating a custom implementation of a WCF RIA Services DomainService using Linq to SQL as the data access layer but without the use of the .dbml file ( this is because the Linq to SQL model is generated by a custom tool , is heavily cutomized , and is of a fairly large database with 50+ tables ) and without the VS2010 wizard for creating a DomainService ( the wizard is dependant on the .dbml file being available ) Here 's a really simple shell of what I tried myself so far : This seems to work so far . Does anyone see any problem with this approach that I might be missing ? I do n't want to go too far down the wrong road with this if someone has already tried this way and found some major problems with it.Thanks for everyone 's input . [ EnableClientAccess ( ) ] public class SubscriptionService : DomainService { [ Query ( IsDefault = true ) ] public IQueryable < Subscription > GetSubscriptionList ( ) { SubscriptionDataContext dc = new SubscriptionDataContext ( ) ; var subs = dc.Subscription.Where ( x = > x.Status == STATUS.Active ) .Select ( x = > new Subscription { ID = x.ID , Name = x.Name } ) .ToList ( ) ; return subs.AsQueryable ( ) ; } public void InsertSubscription ( Subscription sub ) { if ( ! sub.ID.IsEmpty ( ) ) { SubscriptionDataContext dc = new SubscriptionDataContext ( ) ; Subscription tmpSub = dc.GetByID < Subscription > ( sub.ID ) ; if ( tmpSub ! = null ) { tmpSub.Name = sub.Name ; dc.Save ( tmpSub ) ; } else { tmpSub = new Subscription ( ) ; tmpSub.Name = sub.Name ; dc.Save ( tmpSub ) ; } } } public void UpdateSubscription ( Subscription sub ) { if ( ! sub.ID.IsEmpty ( ) ) { SubscriptionDataContext dc = new SubscriptionDataContext ( ) ; Subscription tmpSub = dc.GetByID < Subscription > ( sub.ID ) ; if ( tmpSub ! = null ) { tmpSub.Name = sub.Name ; dc.Save ( tmpSub ) ; } } } public void DeleteSubscription ( Subscription sub ) { if ( ! sub.ID.IsEmpty ( ) ) { SubscriptionDataContext dc = new SubscriptionDataContext ( ) ; Subscription tmpSub = dc.GetByID < Subscription > ( sub.ID ) ; if ( tmpSub ! = null ) { dc.Delete ( tmpSub ) ; } } } }",Custom implementation of a DomainService using Linq to SQL "C_sharp : I have 2 test projects in solution.First project ( `` VDoc '' ) declare VDocQuery type.Second project ( `` VDocQueryTest '' ) calls VDocQuery constructor.I get 2 VDocQuery 's ITypeSymbol 's ( one from each project ) , compare it , but get false result.Steps:1 . Get first ITypeSymbol ( from VDoc project with SemanticModel.LookupNamespacesAndTypes ( ) method ) .2 . Get second ITypeSymbol from VDocQueryTest project ( from ObjectCreationExpressionSyntax.GetTypeInfo ( ) .Type ) 3 . Compare it with ITypeSymbol.Equals ( ITypeSymbol ) .I expected true result , but get false result.Question : How to correctly compare ITypeSymbols from different projects within one solution ? Code example : VDocQuery.cs : VDocQueryUse.cs : class Program { static void Main ( string [ ] args ) { string solutionPath = @ '' ..\..\..\StaticAnalysis.sln '' ; MSBuildWorkspace workspace = MSBuildWorkspace.Create ( ) ; Solution solution = workspace.OpenSolutionAsync ( solutionPath ) .Result ; var vdocProject = FindProjectByName ( `` VDoc '' , solution ) ; SemanticModel semanticModel = vdocProject.Documents.First ( ) .GetSemanticModelAsync ( ) .Result ; var nsVDocQueryFunctionalTest = ( INamespaceOrTypeSymbol ) semanticModel.LookupNamespacesAndTypes ( 0 , null , `` VDocQueryFunctionalTest '' ) .First ( ) ; var tVDocQuery = ( ITypeSymbol ) semanticModel.LookupNamespacesAndTypes ( 0 , nsVDocQueryFunctionalTest , `` VDocQuery '' ) .First ( ) ; TypeInfo ti = GetFromVDocRef ( solution ) ; bool result1 = ti.Type.Equals ( tVDocQuery ) ; // false , expected = true ? //these 2 lines added after Jason Malinowski answer var sVDocQuerySource = SymbolFinder.FindSourceDefinitionAsync ( ti.Type , solution ) .Result ; bool result2 = sVDocQuerySource.Equals ( tVDocQuery ) ; // false , expected = true ? //this line solved the problem , thanks to @ Tamas bool result3 = ti.Type.DeclaringSyntaxReferences.FirstOrDefault ( ) ? .Equals ( tVDocQuery.DeclaringSyntaxReferences.FirstOrDefault ( ) ) ? ? false ; } private static TypeInfo GetFromVDocRef ( Solution solution ) { var vdocQueryTestProject = FindProjectByName ( `` VDocQueryTest '' , solution ) ; var vdocQueryTestProjectSemanticModel = vdocQueryTestProject.Documents.First ( ) .GetSemanticModelAsync ( ) .Result ; var compilationUnit = ( CompilationUnitSyntax ) vdocQueryTestProject.Documents.First ( ) .GetSyntaxRootAsync ( ) .Result ; var ns = ( NamespaceDeclarationSyntax ) compilationUnit.Members [ 0 ] ; var cls = ( ClassDeclarationSyntax ) ns.Members [ 0 ] ; var method = ( MethodDeclarationSyntax ) cls.Members [ 0 ] ; var stat = ( ExpressionStatementSyntax ) method.Body.Statements [ 0 ] ; var newExpr = ( ObjectCreationExpressionSyntax ) stat.Expression ; var ti = vdocQueryTestProjectSemanticModel.GetTypeInfo ( newExpr ) ; return ti ; } static Project FindProjectByName ( string projectName , Solution solution ) { var project = solution.Projects.SingleOrDefault ( p = > p.Name == projectName ) ; return project ; } } using System.Collections.Generic ; namespace VDocQueryFunctionalTest { public class VDocQuery { public VDocQuery ( ) { } public void AddFields ( string docType , params string [ ] fields ) { } public List < VDoc > Execute ( ) { return null ; } } } using VDocQueryFunctionalTest ; namespace VDocQueryTest { static class VDocQueryUse { public static void VDocQueryUseTest ( ) { new VDocQuery ( ) ; } } }",How to compare type symbols ( ITypeSymbol ) from different projects in Roslyn ? C_sharp : I need to match the entire following statement : Basically whenever there is a { there needs to be a corresponding } with however many embedded { } are inside the original tag . So for example { { match } } or { { ma { { tch } } } } or { { m { { a { { t } } c } } h } } .I have this right now : This does not quite work . { { CalendarCustom|year= { { { year| { { # time : Y } } } } } |month=08|float=right } } ( \ { \ { .+ ? ( : ? \ } \ } [ ^\ { ] + ? \ } \ } ) ),regex embedded { { matching "C_sharp : I 'm trying to display the Address toolbar from the Windows Taskbar in my own WinForm . I can get the CLSID of the Address toobar ( { 01E04581-4EEE-11d0-BFE9-00AA005B4383 } ) , and I can get an IDeskBand reference to it . But ... then what ? I 've tried hosting it in an AxHost , but the Address toolbar is not an ActiveX control . I 've tried callingoras well as various other interfaces and their methods , but nothing I do seems to get me anywhere . I 'd be overjoyed if I could actually see that toolbar appear anywhere . But I ca n't seem to bridge the gap between having the IDeskBand reference and plugging it into my Windows Form.Has anybody attempted this before , and gotten further than I have ? Guid bandCLSID = new Guid ( `` { 01E04581-4EEE-11d0-BFE9-00AA005B4383 } '' ) ; Type bandType = Type.GetTypeFromCLSID ( bandCLSID ) ; IDeskBand deskband = ( IDeskBand ) Activator.CreateInstance ( bandType ) ; ( deskband as IOleObjectWithSite ) .SetSite ( various interfaces ) ; ( deskband as IDockingWindow ) .ShowDW ( true ) ;",Host IDeskBand in a Windows Form C_sharp : I have come across some code during a code-review where a old coworker has done the following : This string is used in a regex expression as a replacement for what is matched . My question is what is the purpose of adding the @ literal sign to the beginning of an empty string . There should not be anything to literally interpret.Would there be any difference in impact between : @ '' '' ; and `` '' ; ? const string replacement = @ '' '' ;,Empty String Literal "C_sharp : SA1125 : UseShorthandForNullableTypes has this description ( taken from StyleCop 4.7 settings editor application ) : Enforces the use of the shorthand of a nullable type rather than the Nullable < T > except inside a typeof ( ) .Is there a reason why it has the exception for typeof ( ) statement ? typeof ( int ? ) compiles just as fine - is this just a preference of StyleCop authors or is there a deeper reasoning ? Edit : since the official documentation does not mention this exception , I tested the following code : Result : only the first line raises the SA1125 warning.Edit 2 : The work item for StyleCop asking to fix this behavior var x = new Nullable < int > ( ) ; var y = new int ? ( ) ; var z = typeof ( Nullable < int > ) ; var v = typeof ( int ? ) ;",SA1125 : why enforce `` int ? '' as opposed to `` Nullable < int > '' but not within `` typeof ( ) '' ? "C_sharp : I have the following LINQ expression : Basically , I 'm trying to remove duplicates from an array by summing up their total amounts . So if I have 2 items of IngredientId x , one with Amt 5 and the other with Amt 10 , I want a single item of Ingredient x with the Amt 15 . Easy enough right ? Now , to completely break everything , Amt is actually a float ? , not a float . However , when I Sum a group with all null amounts , I get 0.0 instead of null.Here 's what I want : Should convert to : But instead I get : Is there a way to re-work my LINQ query to facilitate this ? Hopefully my question is clear enough : ) pantry = ( from p in items group p by p.IngredientId into g select new PantryItem ( ) { IngredientId = g.Key , Amt = g.Sum ( p = > p.Amt ) } ) ; x - nullx - nully - 5y - 10z - 10z - null x - nully - 15z - 10 x - 0.0y - 15z - 10",LINQ wo n't sum a group with a float ? property "C_sharp : Recently I made a couple of measures about Linq and Plinq.I ca n't see in which situation has a real significant benefit of Plinq.I 've found many examples such as : This is totally useless example , because it can be parallized with degree of 10000 and yes then will be faster 10000 times , but it 's rare in a business application to loop 10000 times and making `` IO jobs '' . If somebody can mention an example please post it.Plinq is only available for Linq to Objects and Linq to XML.Not suggested to use it in application which runs on webserver ( it has own thread management ) .So our opportunities are reduced to desktop applications which have multiple cores.Usually I write linq queries which runs sequentially in fractions of a second . If I parallize it and it really will run parallel then will be faster , but who cares ? I think it is still fast enough . The end user wo n't see any difference.I can imagine an example when somebody gets all data from DB and running query in memory . Then maybe it 's useful , but it 's a wrong design . TPL is a good stuff for asyncron programming , but I 'm still not sure Plinq is a useful tool.Does anybody have positive experience about that ? Enumerable.Range ( 0 , 10000 ) .AsParallel ( ) .ForAll ( _ = > Thread.Sleep ( 50000 ) ) ;",Has got any real benefit of PLINQ ? "C_sharp : We 're trying to receive payment with cryptocurrencies using coinpayment IPN . We are able to create a request and able to do a payment . However , not able to get success or failure response while user come back to the seller side.Here is how payment request created : This will be redirected to the coinpayment site , once payment done , it is showing the following screen.And trying to get data when user click on back to seller 's site , I have tried to get data using Request.Form , but not getting any value in form.The same thing , working with this woocommerce code , but I have no idea of PHP and how they are dealing with it.Any thought to get IPN response ? Note : there is no development documentation or sample code available for IPN in .NET EditI 'm trying to get value from IPN success public ActionResult IPN ( ) { var uri = new UriBuilder ( `` https : //www.coinpayments.net/index.php '' ) ; uri.SetQueryParam ( `` cmd '' , `` _pay_auto '' ) ; uri.SetQueryParam ( `` merchant '' , `` merchant_key '' ) ; uri.SetQueryParam ( `` allow_extra '' , `` 0 '' ) ; uri.SetQueryParam ( `` currency '' , `` USD '' ) ; uri.SetQueryParam ( `` reset '' , `` 1 '' ) ; uri.SetQueryParam ( `` success_url '' , `` http : //localhost:49725/home/SuccessResponse '' ) ; //todo : redirect to confirm success page uri.SetQueryParam ( `` key '' , `` wc_order_5b7b84b91a882 '' ) ; uri.SetQueryParam ( `` cancel_url '' , `` http : //localhost:49725/home/FailiureResponse '' ) ; uri.SetQueryParam ( `` order_id '' , `` 36 '' ) ; uri.SetQueryParam ( `` invoice '' , `` PREFIX-36 '' ) ; uri.SetQueryParam ( `` ipn_url '' , `` http : //localhost:49725/ ? wc-api=WC_Gateway_Coinpayments '' ) ; uri.SetQueryParam ( `` first_name '' , `` John '' ) ; uri.SetQueryParam ( `` last_name '' , `` Smith '' ) ; uri.SetQueryParam ( `` email '' , `` a @ a.com '' ) ; uri.SetQueryParam ( `` want_shipping '' , `` 1 '' ) ; uri.SetQueryParam ( `` address1 '' , `` 228 Park Ave S & address2 '' ) ; uri.SetQueryParam ( `` city '' , `` New York '' ) ; uri.SetQueryParam ( `` state '' , `` NY '' ) ; uri.SetQueryParam ( `` zip '' , `` 10003-1502 '' ) ; uri.SetQueryParam ( `` country '' , `` US '' ) ; uri.SetQueryParam ( `` item_name '' , `` Order 33 '' ) ; uri.SetQueryParam ( `` quantity '' , `` 1 '' ) ; uri.SetQueryParam ( `` amountf '' , `` 100.00000000 '' ) ; uri.SetQueryParam ( `` shippingf '' , `` 0.00000000 '' ) ; return Redirect ( uri.ToString ( ) ) ; } Public ActionResult SuccessResponse ( ) { var ipn_version = Request.Form [ `` ipn_version '' ] ; var ipn_id = Request.Form [ `` ipn_id '' ] ; var ipn_mode = Request.Form [ `` ipn_mode '' ] ; var merchant = Request.Form [ `` merchant '' ] ; var txn_id = Request.Form [ `` txn_id '' ] ; var status = Request.Form [ `` status '' ] ; return Content ( status ) ; }",How to get response from IPN cryptocurrencies "C_sharp : In Double.PositiveInfinity docs it 's written that : This constant is returned when the result of an operation is greater than MaxValue.However , when I try to add a number to maximum value of double , it does n't return infinity . I 've tried running this : Why is it happening ? Why is n't it showing maxVal as infinity ? Here is a working fiddle . double maxVal = Double.MaxValue ; maxVal = maxVal + 10000000000000000000 ; Console.WriteLine ( maxVal + `` `` + Double.IsInfinity ( maxVal ) ) ; //prints 1.79769313486232E+308 False",Why does n't adding a number to Double.MaxValue makes it Double.PositiveInfinity ? "C_sharp : I 've been using Dependency Injection for a while , and now I want to give a talk about IoC and DI to a group of new developers . I remember explaining it to one guy personally and he asked me : '' Why not just use : instead of going through all the DI trouble . `` My answer was : `` Unit testing requires mocks and stubs . '' - but we do not write unit tests in my company so it did not convince him . I told him that concrete implementation is bad since you are tightly coupled to one implementation . Changing one component will cause change in another.Can you give an example for such code ? Can you give me more reasons why this code is bad ? It seem so obvious to me that I have trouble explaining it : - ) private IMyInterface _instance = new MyImplementaion ( ) ;",Why is coupling to dependencies with the new keyword considered bad ? "C_sharp : Lets assume you have a function that returns a lazily-enumerated object : You also have two functions that consume two separate IEnumerables , for example : How can you call ConsumeChicken and ConsumeGoat without a ) converting FarmsInEachPen ( ) ToList ( ) beforehand because it might have two zillion records , b ) no multi-threading.Basically : But without forcing the double enumeration.I can solve it with multithread , but it gets unnecessarily complicated with a buffer queue for each list.So I 'm looking for a way to split the AnimalCount enumerator into two int enumerators without fully evaluating AnimalCount . There is no problem running ConsumeGoat and ConsumeChicken together in lock-step.I can feel the solution just out of my grasp but I 'm not quite there . I 'm thinking along the lines of a helper function that returns an IEnumerable being fed into ConsumeChicken and each time the iterator is used , it internally calls ConsumeGoat , thus executing the two functions in lock-step . Except , of course , I do n't want to call ConsumeGoat more than once.. struct AnimalCount { int Chickens ; int Goats ; } IEnumerable < AnimalCount > FarmsInEachPen ( ) { ... . yield new AnimalCount ( x , y ) ; ... . } ConsumeChicken ( IEnumerable < int > ) ; ConsumeGoat ( IEnumerable < int > ) ; ConsumeChicken ( FarmsInEachPen ( ) .Select ( x = > x.Chickens ) ) ; ConsumeGoats ( FarmsInEachPen ( ) .Select ( x = > x.Goats ) ) ;",`` Unzip '' IEnumerable dynamically in C # or best alternative "C_sharp : I have inherited some code that tries to set a property : In current usage the exception is caught and thrown a lot , so I would like to make a check first : This runs much faster . However , my one concern is that IsAssignableFrom could return false for some pair of types where SetValue would in fact succeed . ( This would cause us to look for the manual conversion when we do n't need to , and possibly fail to set a value altogether . ) The spec for SetValue says value can not be converted to the type of PropertyTypewhich is not exactly the same as assignability . ( If IsAssignableFrom returns true in cases where SetValue fails , that 's fine - the manual conversion will still happen . ) Can someone confirm for me whether this is possible or not ? object target = ... // some instance on which we want to set a propertyobject value = ... // some value - in this case , a stringvar propertyInfo = ... // some property of target - in this case , not a stringtry { propertyInfo.SetValue ( obj , value , null ) ; } catch ( ArgumentException ) { // We go off and look for our own way of converting between // the type of value and the type of the property . } if ( propertyInfo.PropertyType.IsAssignableFrom ( value.GetType ( ) ) { // Try/catch as above } else { // Do the manual conversion as if the exception had been thrown . }",Check whether PropertyInfo.SetValue will throw an ArgumentException "C_sharp : I have 2 properties contractor1 and contractor2 in a model , how can I use a single remote validation for both of themRemote Validation function in the ControllerThis does n't work . Can you please help me with this ? [ Display ( Name = '' Contractor 1 : '' ) ] [ Remote ( `` ValidateContractor '' , `` Contracts '' ) ] public string Cntrctr1 { get ; set ; } [ Display ( Name = `` Contractor 2 : '' ) ] [ Remote ( `` ValidateContractor '' , `` Contracts '' ) ] ` enter code here ` public string Cntrctr2 { get ; set ; } public JsonResult ValidateContractor1 ( string Cntrctr ) { var valid = Validations.ValidateContractor ( Cntrctr ) ; if ( ! valid ) { return Json ( `` Enter correct contractor '' , JsonRequestBehavior.AllowGet ) ; } else { return Json ( true , JsonRequestBehavior.AllowGet ) ; } } public static bool ValidateContractor ( string CntrctrNM ) { bool valid ; using ( var entities = new CAATS_Entities ( ) ) { var result = ( from t in entities.PS_VENDOR_V where ( t.VNDR_1_NM ) .Equals ( CntrctrNM ) select t ) .FirstOrDefault ( ) ; if ( result ! = null ) { valid = true ; } else { valid = false ; } } return valid ; }",Same Remote Validation for 2 different properties in a model "C_sharp : While trying to connect to the Core Service I get the following error : The HTTP request was forbidden with client authentication scheme 'Anonymous'The Tridion environment is configured with SSO from SiteMinder.Here 's my code : Does anybody have experience of interacting with the Core Service with an authentication type other than Windows ? UPDATE : I now get the error : The HTTP request was forbidden with client authentication scheme 'Basic'.What clientCredentialType should be used in the /webservices/web.config for the bindings ? When I uncomment the SsoAgentHttpModule in the /webservies/web.config we get a 500 error on the webservice , so SDL told us to leave this commented out . I take it that this module is required for the CoreService to authenticate with authentication scheme 'Basic ' ? public static ICoreService2010 GetTridionClient ( ) { var binding = new BasicHttpBinding ( ) { Name = `` BasicHttpBinding_TridionCoreService '' , CloseTimeout = new TimeSpan ( 0 , 1 , 0 ) , OpenTimeout = new TimeSpan ( 0 , 1 , 0 ) , ReceiveTimeout = new TimeSpan ( 0 , 10 , 0 ) , SendTimeout = new TimeSpan ( 0 , 1 , 0 ) , AllowCookies = false , BypassProxyOnLocal = false , HostNameComparisonMode = HostNameComparisonMode.StrongWildcard , MaxBufferSize = 4194304 , // 4MB MaxBufferPoolSize = 4194304 , MaxReceivedMessageSize = 4194304 , MessageEncoding = WSMessageEncoding.Text , TextEncoding = System.Text.Encoding.UTF8 , TransferMode = TransferMode.Buffered , UseDefaultWebProxy = true , ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas ( ) { MaxDepth = 32 , MaxStringContentLength = 4194304 , // 4MB MaxArrayLength = 4194304 , MaxBytesPerRead = 4194304 , MaxNameTableCharCount = 16384 } , Security = new BasicHttpSecurity ( ) { Mode = BasicHttpSecurityMode.TransportCredentialOnly , Transport = new HttpTransportSecurity ( ) { ClientCredentialType = HttpClientCredentialType.None , } , Message = new BasicHttpMessageSecurity ( ) { ClientCredentialType = BasicHttpMessageCredentialType.UserName } } } ; string hostname = ConfigurationManager.AppSettings [ `` TridionUrl '' ] ; string username = ConfigurationManager.AppSettings [ `` TridionUsername '' ] ; hostname = string.Format ( `` { 0 } { 1 } { 2 } '' , hostname.StartsWith ( `` http '' ) ? `` '' : `` http : // '' , hostname , hostname.EndsWith ( `` / '' ) ? `` '' : `` / '' ) ; var endpoint = new EndpointAddress ( hostname + `` /webservices/CoreService.svc/basicHttp_2010 '' ) ; var factory = new ChannelFactory < ICoreService2010 > ( binding , endpoint ) ; factory.Credentials.UserName.UserName = username ; return factory.CreateChannel ( ) ; }",Tridion 2011 Core Service : Unable to connect in a SSO environment "C_sharp : I am trying to integrate my web service to authenticate using Azure AD . The response from Azure AD varies each time . When i open my site in firefox normal browser , the IsAuthenticated as true . IsAuthenticatedAsTrueOpening in a private browser , the IsAuthenticated is false . IsAuthenticatedAsFalseThe only difference i can see is , the IsAuthenticated true is from ClaimsIdentity and IsAuthenticated false is from GenericIdentity.The following is my startup.auth code.The following is my code to send the authentication request to AzureAD public partial class Startup { private static string clientId = ConfigurationManager.AppSettings [ `` ClientId '' ] ; private static string aadInstance = ConfigurationManager.AppSettings [ `` AADInstance '' ] ; private static string tenantId = ConfigurationManager.AppSettings [ `` TenantId '' ] ; private static string postLogoutRedirectUri = ConfigurationManager.AppSettings [ `` PostLogoutRedirectUri '' ] ; private static string authority = aadInstance + tenantId ; public void ConfigureAuth ( IAppBuilder app ) { app.SetDefaultSignInAsAuthenticationType ( CookieAuthenticationDefaults.AuthenticationType ) ; app.UseCookieAuthentication ( new CookieAuthenticationOptions ( ) ) ; app.UseOpenIdConnectAuthentication ( new OpenIdConnectAuthenticationOptions { ClientId = clientId , Authority = authority , PostLogoutRedirectUri = postLogoutRedirectUri } ) ; } } public void LoginUsingAzure ( ) { HttpContext.GetOwinContext ( ) .Authentication.Challenge ( new AuthenticationProperties { RedirectUri = `` / '' } , OpenIdConnectAuthenticationDefaults.AuthenticationType ) ; }",Azure AD API returns System.Security.Principal.GenericIdentity.IsAuthenticated as false always "C_sharp : The WPF code below hangs forever when network connection is lost for 3 or more minutes . When connection is restored it neither throws nor continues downloading nor timeouts . If network connection is lost for a shorter period say half a minute , it throws after connection is restored . How can i make it more robust to survive network outage ? UPDATE Current solution is based on restarting Timer in DownloadProgressChangedEventHandler , so the timer fires only if no DownloadProgressChanged events occur within the timeout . Looks like an ugly hack , still looking for a better solution . using System ; using System.Net ; using System.Net.NetworkInformation ; using System.Windows ; namespace WebClientAsync { public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; NetworkChange.NetworkAvailabilityChanged += ( sender , e ) = > Dispatcher.Invoke ( delegate ( ) { this.Title = `` Network is `` + ( e.IsAvailable ? `` available '' : `` down '' ) ; } ) ; } const string SRC = `` http : //ovh.net/files/10Mio.dat '' ; const string TARGET = @ '' d : \stuff\10Mio.dat '' ; private async void btnDownload_Click ( object sender , RoutedEventArgs e ) { btnDownload.IsEnabled = false ; btnDownload.Content = `` Downloading `` + SRC ; try { using ( var wcl = new WebClient ( ) ) { wcl.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials ; await wcl.DownloadFileTaskAsync ( new Uri ( SRC ) , TARGET ) ; btnDownload.Content = `` Downloaded '' ; } } catch ( Exception ex ) { btnDownload.Content = ex.Message + Environment.NewLine + ( ( ex.InnerException ! = null ) ? ex.InnerException.Message : String.Empty ) ; } btnDownload.IsEnabled = true ; } } } using System ; using System.Net ; using System.Threading ; using System.Threading.Tasks ; using System.Windows ; namespace WebClientAsync { public partial class MainWindow : Window { const string SRC = `` http : //ovh.net/files/10Mio.dat '' ; const string TARGET = @ '' d : \stuff\10Mio.dat '' ; // Time needed to restore network connection const int TIMEOUT = 30 * 1000 ; public MainWindow ( ) { InitializeComponent ( ) ; } private async void btnDownload_Click ( object sender , RoutedEventArgs e ) { btnDownload.IsEnabled = false ; btnDownload.Content = `` Downloading `` + SRC ; CancellationTokenSource cts = new CancellationTokenSource ( ) ; CancellationToken token = cts.Token ; Timer timer = new Timer ( ( o ) = > { // Force async cancellation cts.Cancel ( ) ; } , null //state , TIMEOUT , Timeout.Infinite // once ) ; DownloadProgressChangedEventHandler handler = ( sa , ea ) = > { // Restart timer if ( ea.BytesReceived < ea.TotalBytesToReceive & & timer ! = null ) { timer.Change ( TIMEOUT , Timeout.Infinite ) ; } } ; btnDownload.Content = await DownloadFileTA ( token , handler ) ; // Note ProgressCallback will fire once again after awaited . timer.Dispose ( ) ; btnDownload.IsEnabled = true ; } private async Task < string > DownloadFileTA ( CancellationToken token , DownloadProgressChangedEventHandler handler ) { string res = null ; WebClient wcl = new WebClient ( ) ; wcl.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials ; wcl.DownloadProgressChanged += handler ; try { using ( token.Register ( ( ) = > wcl.CancelAsync ( ) ) ) { await wcl.DownloadFileTaskAsync ( new Uri ( SRC ) , TARGET ) ; } res = `` Downloaded '' ; } catch ( Exception ex ) { res = ex.Message + Environment.NewLine + ( ( ex.InnerException ! = null ) ? ex.InnerException.Message : String.Empty ) ; } wcl.Dispose ( ) ; return res ; } } }",.Net DownloadFileTaskAsync robust WPF code "C_sharp : I solved my task , but I do n't like how it works . It looks too heavy for me . If you can suggest me a better way to do exactly the same it would be awesome ! So here is my pain : ) I have a table in SQL DB which contains charts with business data and they are developed by separate department and they are adding them randomly ( at least from my point of view ) . The year range is 1995-2012 ( 3 ) but both of those dates should be flexible because every next month new data appear and they 'll try to add more data for the past.Now it looks like this : To achive this goal I created this model : Here is Controller which contains GetMethod to show View as presented above and Post method to get this Model back parse it and create anothe View with charts.And the last part is actually a View to represent this checkbox field : So user can only choose months of the years if we have charts for them . The year range can change in the future . We must show chart on separate page . We must remember the model ( I keep it in session ) if user decided to go back and select a couple more months.So what I do n't like in this solution:1 . Model is heavy , hard to use , to create and parse . Not easy to add new parameters . 2 . View contains a lot of hidden fields because of model3 . Controller is okay except creation and parse the model.I 'm pretty new for web dev , but I 'm not a newby in software development and I want it look better if it 's possible.I really feel that I 'm missing something here . I appreciate your ideas , suggestions and anything that could simplify this code . Thanks ! UPDATE : I want to clarify why I use so many parameters.I ca n't use only one DateTime because each chart has start DateTime and end DateTime ( begin and the end of the month ) and TypeId . Besides I need somehow to build table in view and put each control in right place . Now I 'm using name of months for this purpose . I also need to know on the View side is control enabled ( if user can select it ) and then on the POST method I need to know which of them was selected so I have bool IsEnabled { get ; set ; } and bool IsSelected { get ; set ; } and other parameters . using System ; using System.Collections.Generic ; namespace MvcApplication1.Models { [ Serializable ] public class MonthlyModel { public int TypeId { get ; set ; } public List < YearDTO > Items { get ; set ; } } [ Serializable ] public class YearDTO { public DateTime Year { get ; set ; } public MonthDTO January { get ; set ; } public MonthDTO February { get ; set ; } public MonthDTO March { get ; set ; } public MonthDTO April { get ; set ; } public MonthDTO May { get ; set ; } public MonthDTO June { get ; set ; } public MonthDTO July { get ; set ; } public MonthDTO August { get ; set ; } public MonthDTO September { get ; set ; } public MonthDTO October { get ; set ; } public MonthDTO November { get ; set ; } public MonthDTO December { get ; set ; } } [ Serializable ] public class MonthDTO { public DateTime start { get ; set ; } public DateTime end { get ; set ; } public int priceTypeId { get ; set ; } public bool IsEnabled { get ; set ; } public bool IsSelected { get ; set ; } } } using System ; using System.Collections.Generic ; using System.Web.Mvc ; using MvcApplication1.Models ; namespace MvcApplication1.Controllers { public class HistoricalController : Controller { [ HttpGet ] public ActionResult Monthly ( ) { int typeId = -1 ; try { typeId = Convert.ToInt32 ( RouteData.Values [ `` id '' ] ) ; } catch ( Exception ) { } MonthlyModel mm ; if ( Session [ String.Format ( `` MonthlySelect { 0 } '' , typeId ) ] ! = null ) { mm = ( MonthlyModel ) Session [ String.Format ( `` MonthlySelect { 0 } '' , typeId ) ] ; } else { mm = GetMonthlyModel ( typeId ) ; } return View ( mm ) ; } private MonthlyModel GetMonthlyModel ( int typeId ) { MonthlyModel mm = new MonthlyModel ( ) ; var list = ChartManager.GetAvailableMonthlyCharts ( typeId , 1 , 3 , new DateTime ( 1995 , 1 , 1 ) , DateTime.Today ) ; foreach ( Tuple < DateTime , DateTime , bool , int > val in list ) { var start = val.Item1 ; var end = val.Item2 ; var exists = val.Item3 ; var pti = val.Item4 ; var items = mm.Items ? ? ( mm.Items = new List < YearDTO > ( ) ) ; int idx = items.FindIndex ( f = > f.Year.Year == start.Year ) ; if ( idx == -1 ) { items.Add ( new YearDTO { Year = new DateTime ( start.Year , 1 , 1 ) } ) ; idx = items.FindIndex ( f = > f.Year.Year == start.Year ) ; } switch ( start.Month ) { case 1 : items [ idx ] .January = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 2 : items [ idx ] .February = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 3 : items [ idx ] .March = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 4 : items [ idx ] .April = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 5 : items [ idx ] .May = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 6 : items [ idx ] .June = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 7 : items [ idx ] .July = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 8 : items [ idx ] .August = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 9 : items [ idx ] .September = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 10 : items [ idx ] .October = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 11 : items [ idx ] .November = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; case 12 : items [ idx ] .December = new MonthDTO { start = start , end = end , priceTypeId = pti , IsEnabled = exists , IsSelected = false } ; break ; } } mm.metalId = typeId ; return mm ; } [ HttpPost ] public ActionResult MonthlyCharts ( MonthlyModel model ) { List < ChartDTO > list = new List < ChartDTO > ( ) ; foreach ( YearDTO dto in model.Items ) { var val = dto.January ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.February ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.March ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.April ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.May ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.June ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.July ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.August ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.September ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.October ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.November ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; val = dto.December ; if ( val.IsSelected ) list.Add ( ChartManager.GetChart ( val.start , val.end , model.metalId , 1 , val.priceTypeId ) ) ; } Session [ String.Format ( `` MonthlySelect { 0 } '' , model.metalId ) ] = model ; ModelState.Clear ( ) ; return View ( list ) ; } } } @ model MvcApplication1.Models.MonthlyModel @ { ViewBag.Title = `` Monthly charts `` ; Layout = `` ~/Views/Shared/_Layout.cshtml '' ; } < h2 > @ ( ViewBag.Title ) < /h2 > < div id= '' choice-container '' > @ using ( Html.BeginForm ( `` MonthlyCharts '' , `` Historical '' , FormMethod.Post ) ) { @ Html.TextBox ( `` metalId '' , Model.metalId , new { @ type = `` hidden '' } ) < table > < tr > < th > Year < /th > < th > January < /th > < th > February < /th > < th > March < /th > < th > April < /th > < th > May < /th > < th > June < /th > < th > July < /th > < th > August < /th > < th > September < /th > < th > October < /th > < th > November < /th > < th > December < /th > < th > < /th > < /tr > @ for ( int i = 0 ; i < Model.Items.Count ( ) ; i++ ) { < tr > < td > @ Html.Label ( `` Items [ `` + i + `` ] .Year '' , Model.Items [ i ] .Year.ToString ( @ '' yyyy '' ) ) @ Html.TextBox ( `` Items [ `` + i + `` ] .Year '' , Model.Items [ i ] .Year , new { @ type = `` hidden '' } ) < /td > < td > < div align=center class= '' editor-field '' > @ if ( Model.Items [ i ] .January.IsEnabled ) { @ Html.CheckBox ( `` Items [ `` + i + `` ] .January.IsSelected '' , Model.Items [ i ] .January.IsSelected , new { @ class = `` chk '' } ) } else { @ Html.CheckBox ( `` Items [ `` + i + `` ] .January.IsSelected '' , Model.Items [ i ] .January.IsSelected , new { @ disabled = `` disabled '' } ) } @ Html.TextBox ( `` Items [ `` + i + `` ] .January.IsEnabled '' , Model.Items [ i ] .January.IsEnabled , new { @ type = `` hidden '' } ) @ Html.TextBox ( `` Items [ `` + i + `` ] .January.start '' , Model.Items [ i ] .January.start , new { @ type = `` hidden '' } ) @ Html.TextBox ( `` Items [ `` + i + `` ] .January.end '' , Model.Items [ i ] .January.end , new { @ type = `` hidden '' } ) @ Html.TextBox ( `` Items [ `` + i + `` ] .January.priceTypeId '' , Model.Items [ i ] .January.priceTypeId , new { @ type = `` hidden '' } ) < /div > < /td > @ * ... . 11 times ... . * @ < /tr > } < /table > < input type= '' submit '' class= '' button '' value= '' Get the image '' / > } < /div >",Better way to show model for month-year calendar and interact with user "C_sharp : I just started a new project a few weeks ago and decided to give EF Code First a try , I used NHIbernate before and i loved the idea of having an ORM out-of-the-bow from MS , and so far it 's been great - until i started making complex objects.My project tiers are as follows : Azure WCF Role - to handle the DAL with EF Code First.Azure WebSite Role with MVC 4 with Knockout - to deal with the client . ( I created the WCFRole for the future where we 'll need access to the service from different platforms ) Here is the very basic EF Code First design that i 'm having trouble with : -I 'm transferring only DTOs between the service and site , and made a generic mapper to map inner DTOs if any exist.- I have a City table , and an Address Object with a City Property ( we need the City as a property for special functions and not just name ) The client knows the list of Cities , and is returning a new Address with an existing cityWhen i try to add the new Address , a new city is created with the data of the old existing one , I already got that this happens because EF does n't know how to merge disconnected objects and from what i read does n't support any merge abitiy , and that the simple not so comfortable solution is just managing the Object State - change the City object state to Unchanged.But handling this with a big complex db design sounds horriblemy question - What is the best practice/ easy way of handling this ? I thought about solutions like - overriding the SaveChanges method going though all objects and if ID is not null/0/some other convention to change it from Added to Unchanged - can this solution be done ? my 2nd question -because i have a lot of experience with NHibernate ( with connected objects ) - I was wondering what NHibernate 's take on this ? i read somewhere that NHibernate does have an AutoMagic Merge ability to reconnect disconnected complex objects , is this true ? will my basic disconnected Address- > City design will work out-of-the-box with that AutoMagic Merge ? And what are the ramifications of using that ? Thanks a lot : ) Update : a simplified code for the issue.Adding new Address : The `` FromDto '' is the generic Mapper extension , it creates the new address with all the Information , including the City ( and the City.ID property ) This will result in creating a new city instead of using a reference to the old city . public class Address { public int ID { get ; set ; } public virtual City City { get ; set ; } } public class City { public int ID { get ; set ; } public string Name { get ; set ; } public virtual Zone Zone { get ; set ; } } public class MyContext : DbContext { public MyContext ( ) : base ( `` TransportService '' ) { } public virtual DbSet < City > Cities { get ; set ; } public virtual DbSet < Address > Addresses { get ; set ; } protected override void OnModelCreating ( DbModelBuilder modelBuilder ) { base.OnModelCreating ( modelBuilder ) ; modelBuilder.Entity < Address > ( ) .HasRequired ( x = > x.City ) .WithMany ( ) .WillCascadeOnDelete ( true ) ; } } public void Add ( AddressDto address ) { using ( var context = new MyContext ( ) ) { context.Addresses.Add ( address.FromDto < Address > ( ) ) ; context.SaveChanges ( ) ; } }",EF vs Nhibernate Merge Disconnected Object Graph "C_sharp : I am following this tutorial and I am working with the Dictionary that I have found out is the equivalent to the Hashtable in Java.I created my Dictionary like so : Though my dilemma is that when using Dictionary I can not use get , written in Java like so : How do I accomplish the same thing . Meaning getting x : y as the result ? private Dictionary < String , Tile > tiles = new Dictionary < String , Tile > ( ) ; Tile tile = tiles.get ( x + `` : '' + y ) ;",How do I use C # generic Dictionary like the Hashtable is used in Java ? "C_sharp : I have code like this in C # : I do n't know how to convert this C # struct to F # and implement the struct into an array like my code above . namespace WumpusWorld { class PlayerAI { //struct that simulates a cell in the AI replication of World Grid struct cellCharacteristics { public int pitPercentage ; public int wumpusPercentage ; public bool isPit ; public bool neighborsMarked ; public int numTimesvisited ; } private cellCharacteristics [ , ] AIGrid ; //array that simulates World Grid for the AI private enum Move { Up , Down , Right , Left , Enter , Escape } ; //enum that represents integers that trigger movement in WumpusWorldForm class Stack < int > returnPath ; //keeps track of each move of AI to trace its path back bool returntoBeg ; //flag that is triggered when AI finds gold int numRandomMoves ; //keeps track of the number of random moves that are done public PlayerAI ( ) { AIGrid = new cellCharacteristics [ 5 , 5 ] ; cellCharacteristics c ; returntoBeg = false ; returnPath = new Stack < int > ( ) ; numRandomMoves = 0 ; for ( int y = 0 ; y < 5 ; y++ ) { for ( int x = 0 ; x < 5 ; x++ ) { c = new cellCharacteristics ( ) ; c.isPit = false ; c.neighborsMarked = false ; c.numTimesvisited = 0 ; AIGrid [ x , y ] = c ; } } } } }",Converting C # struct to F # "C_sharp : I have the following code : Running the above on my machine under Releae , finishes in around 18 seconds and removing the RegexOptions.Compiled makes it run in 13 seconds.My understanding was that including this flag would make the match faster but in my example it is resulting in ~30 % lower performance.What am I missing here ? static void Main ( string [ ] args ) { const string RegXPattern = @ '' /api/ ( ? < controller > \w+ ) / ( ? < action > \w+ ) / ? $ '' ; var regex = new Regex ( RegXPattern , RegexOptions.IgnoreCase | RegexOptions.Compiled ) ; const string InputToMatch = `` /api/person/load '' ; regex.IsMatch ( InputToMatch ) ; // Warmup var sw = Stopwatch.StartNew ( ) ; for ( int i = 0 ; i < 10000000 ; i++ ) { var match = regex.IsMatch ( InputToMatch ) ; } sw.Stop ( ) ; Console.WriteLine ( sw.Elapsed.ToString ( ) ) ; Console.ReadLine ( ) ; }",Why does the C # RegexOptions.Compiled makes the match slower ? "C_sharp : In the following example , & amp ; and & # 916 ; are OK but & Delta ; is not ( the latter two are both Δ ) . The compiler issues a warning similar to : What are the supported character entities for XML comments ? warning CS1570 : XML comment on 'XXX.DocumentedMethod ( ) ' has badly formed XML -- 'Reference to undefined entity 'Delta ' . ' /// < summary > /// & amp ; & Delta ; & # 916 ; /// < /summary > public void DocumentedMethod ( ) { }",What are the supported character entities for XML comments ? "C_sharp : I am trying to use polymorphism in generic type parameters in C # . I have reviewed several other questions on SO ( 1 , 2 , 3 , 4 , 5 , 6 ) , but I 'm still not clear why this does n't work ( or if it 's even allowed ) .BackgroundI have the following classes : and an instance of my derived generic type : The basicsThe following statements are all true : The problemWhen I try to use my derived class as a type parameter in another generic type I get some unexpected behavior . Given the following lazy instance : The following is true : But these are false when I expected them to be true : Why is this ? Should they be true or have I misunderstood how generics work ? public class Base { } public class Derived < T > : Base { } public class Foo { } var derived = new Derived < Foo > ( ) ; derived is Objectderived is Basederived is Derived < Foo > var lazy = new Lazy < Derived < Foo > > ( ) ; lazy is Lazy < Derived < Foo > > lazy is Lazy < Object > lazy is Lazy < Base >",Polymorphism in generic type parameters "C_sharp : I want to create a 3D Graph in 4 quadrants form in C # .NET . For instant , I could do as shown below . If you see the corner of the chart begins with ( -150 , -200 ) . I wish to start with ( 0,0 ) and the extend into 4 quadrant form.Kindly enlighten me how can I transform this 3D graph in 4 quadrant form ? Below is the corresponding code : I want my 3D graph to have 4 quadrants like this : Thanks @ TaW . I got the code right . void prepare3dChart ( Chart chart , ChartArea ca ) { ca.Area3DStyle.Enable3D = true ; Series s = new Series ( ) ; chart.Series.Add ( s ) ; s.ChartType = SeriesChartType.Bubble ; s.MarkerStyle = MarkerStyle.Diamond ; s [ `` PixelPointWidth '' ] = `` 100 '' ; s [ `` PixelPointGapDepth '' ] = `` 1 '' ; chart.ApplyPaletteColors ( ) ; addTestData ( chart ) ; } void addTestData ( Chart chart ) { Random rnd = new Random ( 9 ) ; double x = 0 , y = 0 , z = 0 ; for ( int i = 0 ; i < 100 ; i++ ) { AddXY3d ( chart.Series [ 0 ] , x , y , z ) ; x = Math.Sin ( i / 11f ) * 88 + rnd.Next ( 3 ) ; y = Math.Cos ( i / 10f ) * 88 + rnd.Next ( 5 ) ; z = ( Math.Sqrt ( i * 2f ) * 88 + rnd.Next ( 6 ) ) ; } } int AddXY3d ( Series s , double xVal , double yVal , double zVal ) { int p = s.Points.AddXY ( xVal , yVal , zVal ) ; s.Points [ p ] .Color = Color.Transparent ; return p ; } private void chart1_PostPaint ( object sender , ChartPaintEventArgs e ) { Chart chart = sender as Chart ; if ( chart.Series.Count < 1 ) return ; if ( chart.Series [ 0 ] .Points.Count < 1 ) return ; ChartArea ca = chart.ChartAreas [ 0 ] ; List < List < PointF > > data = new List < List < PointF > > ( ) ; foreach ( Series s in chart.Series ) data.Add ( GetPointsFrom3D ( ca , s , s.Points.ToList ( ) , e.ChartGraphics ) ) ; renderLines ( data , e.ChartGraphics.Graphics , chart , true ) ; renderPoints ( data , e.ChartGraphics.Graphics , chart , 6 ) ; } List < PointF > GetPointsFrom3D ( ChartArea ca , Series s , List < DataPoint > dPoints , ChartGraphics cg ) { var p3t = dPoints.Select ( x = > new Point3D ( ( float ) ca.AxisX.ValueToPosition ( x.XValue ) , ( float ) ca.AxisY.ValueToPosition ( x.YValues [ 0 ] ) , ( float ) ca.AxisY.ValueToPosition ( x.YValues [ 1 ] ) ) ) .ToArray ( ) ; ca.TransformPoints ( p3t.ToArray ( ) ) ; return p3t.Select ( x = > cg.GetAbsolutePoint ( new PointF ( x.X , x.Y ) ) ) .ToList ( ) ; } void renderLines ( List < List < PointF > > data , Graphics graphics , Chart chart , bool curves ) { for ( int i = 0 ; i < chart.Series.Count ; i++ ) { if ( data [ i ] .Count > 1 ) using ( Pen pen = new Pen ( Color.FromArgb ( 64 , chart.Series [ i ] .Color ) , 2.5f ) ) if ( curves ) graphics.DrawCurve ( pen , data [ i ] .ToArray ( ) ) ; else graphics.DrawLines ( pen , data [ i ] .ToArray ( ) ) ; } } void renderPoints ( List < List < PointF > > data , Graphics graphics , Chart chart , float width ) { for ( int s = 0 ; s < chart.Series.Count ; s++ ) { Series S = chart.Series [ s ] ; for ( int p = 0 ; p < S.Points.Count ; p++ ) using ( SolidBrush brush = new SolidBrush ( Color.FromArgb ( 64 , S.Color ) ) ) graphics.FillEllipse ( brush , data [ s ] [ p ] .X - width / 2 , data [ s ] [ p ] .Y - width / 2 , width , width ) ; } } void prepare3dChart ( Chart chart , ChartArea ca ) { ca.Area3DStyle.Enable3D = true ; ca.BackColor = Color.Transparent ; ca.AxisX.Minimum = -300 ; ca.AxisX.Maximum = 300 ; ca.AxisY.Minimum = -300 ; ca.AxisY.Maximum = 300 ; ca.AxisX.Crossing = 0 ; // move both axes.. ca.AxisY.Crossing = 0 ; // to the middle ca.AxisX.Interval = 50 ; ca.AxisY.Interval = 50 ; ca.AxisX.MajorGrid.LineColor = Color.LightGray ; ca.AxisY.MajorGrid.LineColor = Color.LightGray ; chart.Series.Clear ( ) ; Series s = new Series ( ) ; chart.Series.Add ( s ) ; s.ChartType = SeriesChartType.Bubble ; s.MarkerStyle = MarkerStyle.Diamond ; s [ `` PixelPointWidth '' ] = `` 100 '' ; s [ `` PixelPointGapDepth '' ] = `` 1 '' ; chart.ApplyPaletteColors ( ) ; addTestData ( chart ) ; }",Can we create 3D graph in 4 quadrants in C # .NET winform ? "C_sharp : In C # , I would like to have the option to handle errors in a more “ functional ” way , rather than always using the default exception-throwing model . In some scenarios , the throwing model is great , because it allows you to force your code to stop executing if something unexpected happens . However , the throwing model has several major drawbacks : Exception throwing is basically a whole secondary system of application control flow that subverts the main control flow system . When a method is called , its body is executed and then effectively control returns to the caller , regardless of whether it was due to a return or throw statement . If control returned to the caller from a throw statement , control will immediately move to its caller if there is no appropriate try/catch in scope ; whereas if control returned from a return statement , control continues as normal . I know the implementation is way more complicated and subtle than that , but I think that ’ s an appropriate conceptual summary . This double system can be generally confusing , both at design time and runtime in different ways.The throwing system gets more awkward in parallel or asynchronous scenarios , as seen in the treatments of errors by System.Threading.Tasks.Task . Any exceptions thrown by a Task executing are stored in an AggregateException and accessed through the Task.Exception property by the calling code . So while the Tasks execution may be aborted , the calling code must look for errors stored in object properties , using normal C # control flow.Aside from XML comments , there is no metadata about whether a method might throw exceptions , or which it might throw . Exceptions behave as an alternate form of method output , but are largely ignored by the type system . For example , the method int Divide ( int x , int y ) could result in either an integer or a DivideByZeroException , but the signature of this method does not suggest anything regarding errors . Conversely , I ’ ve often heard complaints about Java ’ s checked exceptions , where every specific exception type a method can throw must be added to its signature , which can get very wordy . To me the simplest middle ground would be a generic type like Nullable < T > that contains either a value or an exception . A method like Divide would then have this signature : Fallible < int > Divide ( int x , int y ) . Any operations using the result would then need to deal with the error case . Methods could also take Fallible parameters to allow easier chaining.Here is an implementation of Fallible I sketched out : And the questions : Is there already something like Fallible < T > for .NET ? Perhaps a class in the Task Parallel Library , Reactive Extensions , or the F # core libraries ? Are there any major deficiencies in the implementation above ? Are there any conceptual problems with control flow that I may be overlooking ? public class Fallible < T > : IEquatable < Fallible < T > > { # region Constructors public Fallible ( ) { //value defaults to default ( T ) //exception defaults to null } public Fallible ( T value ) : this ( ) { this.value = value ; } public Fallible ( Exception error ) : this ( ) { if ( error == null ) throw new ArgumentNullException ( nameof ( error ) ) ; Error = error ; } public Fallible ( Func < T > getValue ) : this ( ) { if ( error == null ) throw new ArgumentNullException ( nameof ( getValue ) ) ; try { this.value = getValue ( ) ; } catch ( Exception x ) { Error = x ; } } # endregion # region Properties public T Value { get { if ( ! HasValue ) throw new InvalidOperationException ( `` Can not get Value if HasValue is false . `` ) ; return value ; } } private T value ; public Exception Error { get ; } public bool HasValue = > Error == null ; # endregion # region Equality public bool Equals ( Fallible < T > other ) = > ( other ! = null ) & & Equals ( Error , other.Error ) & & Equals ( Value , other.Value ) ; public override bool Equals ( object obj ) = > Equals ( obj as Fallible < T > ) ; public static bool operator == ( Fallible < T > a , Fallible < T > b ) { if ( a == null ) return b == null ; return a.Equals ( b ) ; } public static bool operator ! = ( Fallible < T > a , Fallible < T > b ) { if ( a == null ) return b ! = null ; return ! a.Equals ( b ) ; } public override int GetHashCode ( ) = > HasValue ? Value.GetHashCode ( ) : Error.GetHashCode ( ) ; # endregion public override string ToString ( ) = > HasValue ? $ '' Fallible { { { Value } } } '' : $ '' Fallible { { { Error.GetType ( ) } : { Error.Message } } } '' ; }",Is there a .NET type like a ( value OR error ) discriminated union ? "C_sharp : When calling .Max ( x = > x.SomeInt ) on an IEnumerable , you commonly are happy to return `` 0 '' if the enumerable contains no elements . However LINQ 's implementation of .Max ( x = > x.SomeInt ) crashes as the sequence contains no elements.Therefore a .MaxOrDefault ( x = > x.SomeInt ) function would be useful.We should not simply call .Any ( ) then .Max ( func ) because this causes a legitimate `` possible multiple enumeration '' warning in Resharper.I have implemented one as follows : However this has the downside of having to enumerate into a list first , which is suboptimal and should be unnecessary.Is there a better way ? public static TResult MaxOrDefault < T , TResult > ( this IEnumerable < T > enumerable , Func < T , TResult > func ) { var list = enumerable.ToList ( ) ; if ( ! list.Any ( ) ) return default ( TResult ) ; return list.Max ( func ) ; }",How to implement MaxOrDefault ( x = > x.SomeInt ) LINQ extension ? "C_sharp : I was just curious why C # arrays return true for their IsSerializable property . Arrays do not have any Serializable attribute , and they also do n't implement the ISerializable interface , so why is the IsSerializable property set to true ? When I try the below code , it outputs `` True '' in the console : The output is : Try it onlineMy .NET runtime version is 3.5 . Console.WriteLine ( new string [ 0 ] .GetType ( ) .IsSerializable ) ; True",Why C # Arrays type IsSerializable property is True ? "C_sharp : Note : I noticed some errors in my posted example - editing to fix itThe official C # compiler does some interesting things if you do n't enable optimization.For example , a simple if statement : becomes something like the following if optimized : but if we disable optimization , it becomes something like this : I ca n't quite get my head around this . Why all that extra code , which is seemingly not present in the source ? In C # , this would be the equivalent of : Does anyone know why it does this ? int x ; // ... //if ( x == 10 ) // do something ldloc.0ldc.i4.s 10ceqbne.un.s do_not_do_something// do somethingdo_not_do_something : ldloc.0ldc.i4.s 10ceqldc.i4.0ceqstloc.1ldloc.1brtrue.s do_not_do_something// do somethingdo_not_do_something : int x , y ; // ... //y = x == 10 ; if ( y ! = 0 ) // do something",MS C # compiler and non-optimized code "C_sharp : I am creating an Orchard module where i want to add a WebApi controller.My Module.txt : I have added an ApiRoutes class : Then i have added an apicontroller : I am on Localhost and the home url is : http : //localhost:30321/OrchardLocalWhen i go to http : //localhost:30321/OrchardLocal/api/ModuleName/ConsumptionI get a Not Found page.Can anyone shed some light ? Name : ModuleNameAntiForgery : enabledAuthor : The Orchard TeamWebsite : http : //orchardproject.netVersion : 1.0OrchardVersion : 1.0Description : Description for the moduleFeatures : ModuleName : Description : Description for feature ModuleName . using Orchard.Mvc.Routes ; using Orchard.WebApi.Routes ; using System ; using System.Collections.Generic ; using System.Linq ; using System.Web ; using System.Web.Http ; namespace ModuleName { public class ModuleNameApiRoutes : IHttpRouteProvider { public void GetRoutes ( ICollection < RouteDescriptor > routes ) { foreach ( var routeDescriptor in GetRoutes ( ) ) { routes.Add ( routeDescriptor ) ; } } public IEnumerable < RouteDescriptor > GetRoutes ( ) { return new [ ] { new HttpRouteDescriptor { Name = `` ModuleName '' , Priority = 5 , RouteTemplate = `` api/modulename/ { controller } / { id } '' , Defaults = new { area = `` ModuleName '' , id = RouteParameter.Optional } } } ; } } } using Newtonsoft.Json.Linq ; using Orchard ; using Orchard.Data ; using ModuleName.Models ; using System ; using System.Collections.Generic ; using System.Linq ; using System.Net ; using System.Net.Http ; using System.Web.Http ; namespace ModuleName.Controllers { public class ConsumptionController : ApiController { public IOrchardServices Services { get ; private set ; } private readonly IRepository < Vessel_ConsumptionPartRecord > _repository ; public ConsumptionController ( IOrchardServices orchardServices , IRepository < Vessel_ConsumptionPartRecord > repository ) { _repository = repository ; } // GET : Home public HttpResponseMessage Get ( ) { ... } } }",WebApi Route returns Not Found in Orchard Module "C_sharp : I have two entities Candidate and CandidateLocation where a Candidate can have multiple CandidateLocation entries.A CandidateLocation contains the CandidateId , an ISO Country Code ( e.g . US , GB ) and a type column ( 1 = Permitted , 2 = Restricted ) .Rules dictate that if the Candidate does not have any 'Permitted ' entries in the CandidateLocation table they can work anywhere . If they have an explicit 'Permitted ' location they can only work in the explicitly permitted locations . They can not work in explicilty restricted locations.To try an demonstrate this please see the image below ( Candidates can have multiple locations I have kept it to one to simplify the illustration ) In SQL one way of achieving this would be the following queryIf anyone knows how to achieve this using linq & Navigation Properties I would greatly appreciate the help.Many thanks SELECT *FROM CandidateWHERE Candidate.IsArchived = 0 AND -- Do not inlude restricted locations ( RestrictionStatus = 2 ) Candidate.CandidateId NOT IN ( SELECT CandidateId FROM CandidateLocation WHERE IsArchived = 0 AND CountryISOCode = @ Location AND RestrictionStatus = 2 ) AND ( -- Include Explicit Permitted Locations Candidate.CandidateId IN ( SELECT CandidateId FROM CandidateLocation WHERE IsArchived = 0 AND CountryISOCode = @ Location AND RestrictionStatus = 1 ) OR -- Include Candidates with no Explicit Permitted Locations Candidate.CandidateId NOT IN ( SELECT CandidateId FROM CandidateLocation WHERE IsArchived = 0 AND RestrictionStatus = 1 ) )",Linq Navigation Properties complex where ID in ( select id from ... ) C_sharp : I am playing around with FluentSecurity library for asp.net mvc . One of the interfaces exposed by this library is ISecurityContext as shown below : When I try to access `` Data '' property ( as shown below ) it is not available . Although the other two methods seems to be accessible . What am I missing ? Thanks . public interface ISecurityContext { dynamic Data { get ; } bool CurrenUserAuthenticated ( ) ; IEnumerable < object > CurrenUserRoles ( ) ; } public class ExperimentalPolicy : ISecurityPolicy { public PolicyResult Enforce ( ISecurityContext context ) { dynamic data = context.Data ; // Data property is not accessible . } },C # Accessing dynamic property on interface "C_sharp : I am trying to remove redundant semicolons in the code using a custom syntax rewriter.The following syntax rewriter covers most scenarios as in the Sample class.However when the semicolon has a leading or trailing trivia , returning null from the VisitEmptyStatement method removes the trivia , which is unintended.I could n't determine how to return a node with only the leading and trailing trivia removing the semicolon . I tried to replace the semicolon token with another token using node.WithSemicolonToken ( SyntaxToken ) method , which turns out to be accepting only tokens of type SyntaxKind.SemicolonToken or throws an ArgumentException . public class Sample { public void Foo ( ) { Console.WriteLine ( `` Foo '' ) ; ; } } public class EmptyStatementRemoval : CSharpSyntaxRewriter { public override SyntaxNode VisitEmptyStatement ( EmptyStatementSyntax node ) { return null ; } } public class Sample { public void Foo ( ) { Console.WriteLine ( `` Foo '' ) ; # region SomeRegion //Some other code # endregion ; } }",Removing redundant semicolons in code with SyntaxRewriter "C_sharp : I 'm trying the following : So , how could I compare both values ? And why do this error occur ? Thanks in advance ! T value1 = el.value ; // it 's of type T alreadyT value2 = default ( T ) ; if ( value1 ! = value2 ) // gives the following error : Operator ' ! = ' can not be applied to operands of type 'T ' and 'T ' { // ... }",Ca n't compare T value1 with T value2 = default ( T ) . Why and how to do that on C # ? "C_sharp : If one static data member depends on another static data member , does C # /.NET guarantee the depended static member is initialized before the dependent member ? For example , we have one class like : When Foo.b is accessed , is it always `` abcdef '' or can be `` def '' ? If this is not guaranteed , is there any better way to make sure depended member initialized first ? class Foo { public static string a = `` abc '' ; public static string b = Foo.a + `` def '' ; }",Does C # resolve dependencies among static data members automatically ? "C_sharp : I am a beginner and learning web development using ASP.Net MVC 5 framework in C # language . I came across below code : Scenrio 1 : No New Keyword used in Object Creation.Scenrio 2 : New Keyword used in Object Creation.I am a beginner and I tried both code , and both code works fine for me . Question 1 : Why both code works fine ? Question 2 : When to use `` new '' and when not to `` use '' . Can some one tell me one example for both scenario.Question 3 : What is the difference between both of them.Can some one please guide me a little . [ AuthorizeFunc ] [ BlockWidget ] public PartialViewResult WidgetPayments ( ) { PaymentFormMV data ; // No New Keyword used if ( SimUtils.IsDelayedPaymentAllowed ) { data = Pay.GetData ( PaymentPageMode.DelayedPayment ) ; } else { data = PayHelp.GetData ( PaymentPageMode.MakePayment ) ; } return PartialView ( `` PaymentsWrapper '' , data ) ; } [ AuthorizeFunc ] [ BlockWidget ] public PartialViewResult WidgetPayments ( ) { PaymentFormMV data = new PaymentFormMV ( ) ; // New Keyword used if ( SimUtils.IsDelayedPaymentAllowed ) { data = Pay.GetData ( PaymentPageMode.DelayedPayment ) ; } else { data = PayHelp.GetData ( PaymentPageMode.MakePayment ) ; } return PartialView ( `` PaymentsWrapper '' , data ) ; }",When to use NEW keyword in C # when creating an object in ASP.NET MVC 5 "C_sharp : Basically I have a custom List class that contains different fruits . Assume that each fruit has an ID number that is stored in the list.Is it better to have : orThings to consider : All IDs are of type int.The type of the fruit will not affect the implementation of the List itself . It will only be used by the client of the list , like an external method , etc.I would like to use the one that is clearer , better in design , faster , more efficient , etc . Additionally if these above 2 techniques are not the best , please suggest your ideas.EDIT : Btw Fruit is an enum if that was n't clear . new AppleList ( ) ; new OrangeList ( ) ; new LemonList ( ) ; new FruitList < Fruit.Apple > ( ) ; new FruitList < Fruit.Orange > ( ) ; new FruitList < Fruit.Lemon > ( ) ;",Generics or not Generics C_sharp : Obviously this does n't work because String.Trim returns the Trimmed version as a new String . And you ca n't do line = line.Trim ( ) . So is the only way to do this an old-school for loop ? Note I am restricted to Visual Studio 2005 i.e . .Net 2.0 String [ ] lines = System.IO.File.ReadAllLines ( path ) ; foreach ( String line in lines ) { line.Trim ( ) ; } for ( int i=0 ; i < lines.Length ; ++i ) { lines [ i ] = lines [ i ] .Trim ( ) ; },Trim the contents of a String array in C # "C_sharp : I have a new-style csproj project file that overrides IntermediateOutputPath . It looks like this : The problem is , my Visual Studio extension ca n't access IntermediateOutputPath property . Project.Properties seems to have much less stuff compared to old project format.I 've also tried project.ConfigurationManager.ActiveConfiguration.Properties with the similar success.Is there any way to get this information from Visual Studio extension ? < PropertyGroup > < TargetFramework > netstandard1.6 < /TargetFramework > < IntermediateOutputPath > new\path\to\obj < /IntermediateOutputPath > < /PropertyGroup >",How to get IntermediateOutputPath from Visual Studio extension and new csproj format "C_sharp : I am calling a DLL function written in Delphi XE2 from C # using P/Invoke . It appears to be working when calls are made sequentially from a single thread . However , when multiple threads are calling the function , the C # host application throws System.AccessViolationException seemingly at random.Why does the code below trigger an access violation and how do I fix this ? Minimum Delphi library code for reproducing the problem : Minimum C # host application code to reproduce the problem : Additional information : Platform is x64 Windows 7 . C # host application built for x86 in .NET 4.0 , Delphi DLL compiled for 32-bit.The library appears to be working OK when used in a multi-threaded Delphi host application.An MSVC version of the DLL with the function signature extern __declspec ( dllexport ) void __stdcall Test ( char testByte ) works fine with the C # host ( which suggests this is somehow specific to Delphi ) .The code will not fail if the library function has no return value ( void ) and arguments.Changing the calling convention in both code to cdecl did not help.Any ideas would be much appreciated . library pinvokeproblem ; { $ R *.res } uses Windows , SysUtils ; procedure Test ( const testByte : byte ) ; stdcall ; begin OutputDebugString ( PWideChar ( IntToStr ( testByte ) ) ) ; end ; exports Test ; end . [ DllImport ( `` pinvokeproblem.dll '' , CallingConvention = CallingConvention.StdCall , EntryPoint = `` Test '' ) ] private static extern void Test ( byte testByte ) ; public static void Main ( string [ ] args ) { for ( int i = 1 ; i < = 1000 ; i++ ) // more iterations = better chance to fail { int threadCount = 10 ; Parallel.For ( 1 , threadCount , new ParallelOptions { MaxDegreeOfParallelism = threadCount } , test = > { byte byteArgument = 42 ; Test ( byteArgument ) ; Console.WriteLine ( String.Format ( `` Iteration { 0 } : { 1 } '' , test , byteArgument ) ) ; } ) ; } }",Access violation when calling Delphi DLL from C # in a multi-threaded environment "C_sharp : Ok , this may get lengthy . I am trying to do two things : I want to have a class that implements an interface by holding an instance of another class that every call is routed to . I also want to intercept all method calls and do something.Doing both on their own works great . Combining them seems to work only in one execution order and as Murphy has it , it 's the wrong one ( at least for me ) .I 'd like to inject the composition first so that the interception of all calls will also intercept those that were previously injected . I have tried to influence the execution order of the two aspects byAspectRoleDependency , making the interceptor depend on the composer to run firstAspectPriority , also making the composer run first.As the tests always yieldit obviously does n't work . Do you have a clue why my execution order has not changed ? Did I do something wrong , did I miss a detail in the documentation ? What can I do to intercept my composition-injected methods as well ? namespace ConsoleApplication13 { using System ; using System.Reflection ; using PostSharp ; using PostSharp.Aspects ; using PostSharp.Aspects.Dependencies ; using PostSharp.Extensibility ; [ Serializable ] [ ProvideAspectRole ( `` COMPOSER '' ) ] public sealed class ComposeAspectAttribute : CompositionAspect { [ NonSerialized ] private readonly Type interfaceType ; private readonly Type implementationType ; public ComposeAspectAttribute ( Type interfaceType , Type implementationType ) { this.interfaceType = interfaceType ; this.implementationType = implementationType ; } // Invoked at build time . We return the interface we want to implement . protected override Type [ ] GetPublicInterfaces ( Type targetType ) { return new [ ] { this.interfaceType } ; } // Invoked at run time . public override object CreateImplementationObject ( AdviceArgs args ) { return Activator.CreateInstance ( this.implementationType ) ; } } [ Serializable ] [ ProvideAspectRole ( `` INTERCEPTOR '' ) ] [ MulticastAttributeUsage ( MulticastTargets.Method ) ] [ AspectRoleDependency ( AspectDependencyAction.Order , AspectDependencyPosition.After , `` COMPOSER '' ) ] public sealed class InterceptAspectAttribute : MethodInterceptionAspect { public override void CompileTimeInitialize ( MethodBase method , AspectInfo aspectInfo ) { base.CompileTimeInitialize ( method , aspectInfo ) ; // Warning in VS output Message.Write ( method , SeverityType.Warning , `` XXX '' , `` Method : `` + method.Name ) ; } public override void OnInvoke ( MethodInterceptionArgs args ) { Console.WriteLine ( `` Intercepted before '' ) ; args.Proceed ( ) ; Console.WriteLine ( `` Intercepted after '' ) ; } } interface ITest { void Call ( ) ; } class TestImpl : ITest { public void Call ( ) { Console.WriteLine ( `` CALL remote implemented '' ) ; } } [ InterceptAspect ( AspectPriority = 1 ) ] [ ComposeAspect ( typeof ( ITest ) , typeof ( TestImpl ) , AspectPriority = 2 ) ] class Test { // this should , after compilation , have all methods of ITest , implemented through an instance of TestImpl , which get intercepted before TestImpl is called public void CallLocalImplementedTest ( ) { Console.WriteLine ( `` CALL local implemented '' ) ; } } class Program { static void Main ( ) { var test = new Test ( ) ; ITest t = Post.Cast < Test , ITest > ( test ) ; Console.WriteLine ( `` TEST # 1 '' ) ; t.Call ( ) ; Console.WriteLine ( `` TEST # 2 '' ) ; test.CallLocalImplementedTest ( ) ; Console.ReadLine ( ) ; } } } TEST # 1CALL remote implementedTEST # 2Intercepted beforeCALL local implementedIntercepted after",Ordering of Postsharp Aspects execution "C_sharp : I am trying to connect to a SSL SOAP service host by C # using Service Reference.This is my request message : This is the message that my service sends to the host . But the host returns as below : Security processor was unable to find a security header in the message . This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties . This can occur if the service is configured for security and the client is not using security.This is my config file : Although when I send the same XML via SOAPUI or other HTTP Post methods it works fine.I also extract and attached the certificate and user/pass as below : I am not sure whether the method that I am getting the certificate is correct or not and also why HTTP Post works but my Service Reference Call does not.Thanks in advance for your help.Cheers < s : Envelope xmlns : s= '' http : //schemas.xmlsoap.org/soap/envelope/ '' xmlns : u= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd '' > < s : Header > < VsDebuggerCausalityData xmlns= '' http : //schemas.microsoft.com/vstudio/diagnostics/servicemodelsink '' > uIDPo/zwMmtdsVhFsAVDkQbiV/4AAAAA1zXtnc72UEm+4tlKzvCxsvN6OC2prvRIljIX4XzHKEYACQAA < /VsDebuggerCausalityData > < o : Security s : mustUnderstand= '' 1 '' xmlns : o= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd '' > < u : Timestamp u : Id= '' _0 '' > < u : Created > 2016-03-18T12:45:27.558Z < /u : Created > < u : Expires > 2016-03-18T12:50:27.558Z < /u : Expires > < /u : Timestamp > < o : UsernameToken u : Id= '' uuid-2c7986ba-eee5-4411-90a9-a02b625c55ff-1 '' > < o : Username > MyUserName < /o : Username > < o : Password Type= '' http : //docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0 # PasswordText '' > MyPlainPassword < /o : Password > < /o : UsernameToken > < /o : Security > < /s : Header > < s : Body xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < generateId xmlns= '' http : //com.vedaadvantage/dp3/Enterprise/StandardTradeCreditCommercial/IndividualCommercialService '' / > < /s : Body > < /s : Envelope > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < system.serviceModel > < bindings > < customBinding > < binding name= '' myBinding '' > < textMessageEncoding messageVersion= '' Soap11 '' / > < security authenticationMode= '' UserNameOverTransport '' messageSecurityVersion= '' WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 '' > < /security > < httpsTransport / > < /binding > < /customBinding > < /bindings > < client > < endpoint address= '' https : // { URL } '' binding= '' customBinding '' bindingConfiguration= '' myBinding '' contract= '' ServiceReference2.MyService '' name= '' IndividualCommercialService '' / > < /client > < /system.serviceModel > < /configuration > private static X509Certificate2 DownloadSslCertificate ( string strDNSEntry ) { X509Certificate2 cert = null ; using ( TcpClient client = new TcpClient ( ) ) { //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 ; client.Connect ( strDNSEntry , 443 ) ; SslStream ssl = new SslStream ( client.GetStream ( ) , false , new RemoteCertificateValidationCallback ( ValidateServerCertificate ) , null ) ; try { ssl.AuthenticateAsClient ( strDNSEntry ) ; } catch ( AuthenticationException e ) { //log.Debug ( e.Message ) ; ssl.Close ( ) ; client.Close ( ) ; return cert ; } catch ( Exception e ) { //log.Debug ( e.Message ) ; ssl.Close ( ) ; client.Close ( ) ; return cert ; } cert = new X509Certificate2 ( ssl.RemoteCertificate ) ; ssl.Close ( ) ; client.Close ( ) ; return cert ; } } private static void Main ( string [ ] args ) { var proxy = new MyService ( ) ; var uri = proxy.Endpoint.Address.Uri ; var cer = DownloadSslCertificate ( uri.DnsSafeHost ) ; EndpointIdentity identity = EndpointIdentity.CreateDnsIdentity ( cer.Subject.Replace ( `` CN= '' , `` '' ) ) ; EndpointAddress address = new EndpointAddress ( proxy.Endpoint.Address.Uri , identity ) ; proxy.Endpoint.Address = address ; proxy.ClientCredentials.UserName.UserName = `` MyUserName '' ; proxy.ClientCredentials.UserName.Password = `` MyPlainPassword '' ; proxy.ClientCredentials.ServiceCertificate.DefaultCertificate = cer ; proxy.HellowWorld ( ) ; }",Connect to SSL SOAP Host via `` Service Reference '' and pass Security Header "C_sharp : I want to create within a function a named lambda function , so that I can call it repeatedly afterwards in the same function.I used to do this synchronously/without tasks withbut in this case I want to call the pingable function as a task , so I would need a Task return type.This is where I am stuck.For all below , I am getting compile errors : I can declare the function normally though , but then I can not call it as a task : All the lines I have marked with a * produce copmile errors.http : //dotnetcodr.com/2014/01/17/getting-a-return-value-from-a-task-with-c/ seems to have a hint at a solution , but the sample there does not allow for not provided input parameters . ( Sample taken from there and simplified : ) How to create and call named Task lambdas in C # , and I would like to declare them on a function rather than class level.I want the named lambda in order to call it multiple times ( several urls in this case ) .Edit/update since you asked for code : This already makes use of the solution proposed here . Func < string , bool > pingable = ( url ) = > return pingtest ( url ) ; * Func < string , Task < bool > > pingable = ( input ) = > { return pingtest ( url ) ; } ; * Task < bool > pingable = new Task < bool > ( ( input ) = > { return pingtest ( url ) ; } ) ; Func < string , bool > pingable = ( input ) = > { return pingtest ( url ) ; } ; var tasks = new List < Task > ( ) ; * tasks.Add ( async new Task ( ping ( `` google.de '' ) ) ) ; Task < int > task = new Task < int > ( obj = > { return obj + 1 ; } , 300 ) ; Func < string , Task < bool > > ping = url = > Task.Run ( ( ) = > { try { Ping pinger = new Ping ( ) ; PingReply reply = pinger.Send ( url ) ; return reply.Status == IPStatus.Success ; } catch ( Exception ) { return false ; } } ) ; var tasks = new List < Task > ( ) ; tasks.Add ( ping ( `` andreas-reiff.de '' ) ) ; tasks.Add ( ping ( `` google.de '' ) ) ; Task.WaitAll ( tasks.ToArray ( ) ) ; bool online = tasks.Select ( task = > ( ( Task < bool > ) task ) .Result ) .Contains ( true ) ;",named async lambda function "C_sharp : I 've just written a small example checking , how C # 's optimizer behaves in case of indexers . The example is simple - I just wrap an array in a class and try to fill its values : once directly and once by indexer ( which internally accesses the data exactly the same way as the direct solution does ) .Many SO posts taught me , that a programmer should highly trust optimizer to do its job . But in this case results are quite surprising : ( Compiled in Release configuration with the optimizations on , I double-checked ) .That 's a huge difference - no way being a statistical error ( and it 's both scalable and repeatable ) .It 's a very unpleasant surprise : in this case I 'd expect the compiler to inline the indexer ( it even does not include any range-checking ) , but it did n't do it . Here 's the disassembly ( note , that my comments are guesses on what is going on ) : DirectBy indexerThat 's a total disaster ( in terms of code optimization ) . So my questions are : Why this code ( quite simple , actually ) was not optimized properly ? How can I modify this code , such that it is optimized as I wanted it to be ( if possible ) ? Can a programmer rely on C # 's optimizer as much as on C++ 's one ? Ok , I know , that the last one is hard to answer . But lately I read many questions about C++ performance and was amazed how much can optimizer do ( for example , total inlining of std : :tie , two std : :tuple ctors and overloaded opeartor < on the fly ) .Edit : ( in response to comments ) It seems , that actually that was still my fault , because I checked the performance while running the IDE . Now I ran the same program out of IDE and attached to it by debugger on-the-fly . Now I get : DirectIndexerThese codes are exactly the same ( in terms of CPU instructions ) . After running , the indexer version achieved even better results than direct one , but only ( I guess ) because of cache'ing . After putting the tests inside a loop , everything went back to normal : Well ; lesson learned . Even though compiling in Release mode , there is a huge difference , whether program is run in IDE or standalone . Thanks @ harold for the idea . public class ArrayWrapper { public ArrayWrapper ( int newWidth , int newHeight ) { width = newWidth ; height = newHeight ; data = new int [ width * height ] ; } public int this [ int x , int y ] { get { return data [ y * width + x ] ; } set { data [ y * width + x ] = value ; } } public readonly int width , height ; public readonly int [ ] data ; } public class Program { public static void Main ( string [ ] args ) { ArrayWrapper bigArray = new ArrayWrapper ( 15000 , 15000 ) ; Stopwatch stopwatch = new Stopwatch ( ) ; stopwatch.Start ( ) ; for ( int y = 0 ; y < bigArray.height ; y++ ) for ( int x = 0 ; x < bigArray.width ; x++ ) bigArray.data [ y * bigArray.width + x ] = 12 ; stopwatch.Stop ( ) ; Console.WriteLine ( String.Format ( `` Directly : { 0 } ms '' , stopwatch.ElapsedMilliseconds ) ) ; stopwatch.Restart ( ) ; for ( int y = 0 ; y < bigArray.height ; y++ ) for ( int x = 0 ; x < bigArray.width ; x++ ) bigArray [ x , y ] = 12 ; stopwatch.Stop ( ) ; Console.WriteLine ( String.Format ( `` Via indexer : { 0 } ms '' , stopwatch.ElapsedMilliseconds ) ) ; Console.ReadKey ( ) ; } } Directly : 1282 msVia indexer : 2134 ms bigArray.data [ y * bigArray.width + x ] = 12 ; 000000a2 mov eax , dword ptr [ ebp-3Ch ] // Evaluate index of array000000a5 mov eax , dword ptr [ eax+4 ] 000000a8 mov edx , dword ptr [ ebp-3Ch ] 000000ab mov edx , dword ptr [ edx+8 ] 000000ae imul edx , dword ptr [ ebp-10h ] 000000b2 add edx , dword ptr [ ebp-14h ] // ... until here000000b5 cmp edx , dword ptr [ eax+4 ] // Range checking000000b8 jb 000000BF 000000ba call 6ED23CF5 // Throw IndexOutOfRange000000bf mov dword ptr [ eax+edx*4+8 ] ,0Ch // Assign value to array bigArray [ x , y ] = 12 ; 0000015e push dword ptr [ ebp-18h ] // Push x and y00000161 push 0Ch // ( prepare parameters ) 00000163 mov ecx , dword ptr [ ebp-3Ch ] 00000166 mov edx , dword ptr [ ebp-1Ch ] 00000169 cmp dword ptr [ ecx ] , ecx 0000016b call dword ptr ds : [ 004B27DCh ] // Call the indexer ( ... ) data [ y * width + x ] = value ; 00000000 push ebp 00000001 mov ebp , esp 00000003 sub esp,8 00000006 mov dword ptr [ ebp-8 ] , ecx 00000009 mov dword ptr [ ebp-4 ] , edx 0000000c cmp dword ptr ds : [ 004B171Ch ] ,0 // Some additional checking , I guess ? 00000013 je 0000001A 00000015 call 6ED24648 0000001a mov eax , dword ptr [ ebp-8 ] // Evaluating index0000001d mov eax , dword ptr [ eax+4 ] 00000020 mov edx , dword ptr [ ebp-8 ] 00000023 mov edx , dword ptr [ edx+8 ] 00000026 imul edx , dword ptr [ ebp+0Ch ] 0000002a add edx , dword ptr [ ebp-4 ] // ... until here0000002d cmp edx , dword ptr [ eax+4 ] // Range checking00000030 jb 00000037 00000032 call 6ED23A5D // Throw IndexOutOfRange exception00000037 mov ecx , dword ptr [ ebp+8 ] 0000003a mov dword ptr [ eax+edx*4+8 ] , ecx // Actual assignment } 0000003e nop 0000003f mov esp , ebp 00000041 pop ebp 00000042 ret 8 // Returning bigArray.data [ y * bigArray.width + x ] = 12 ; 000000ae mov eax , dword ptr [ ebp-10h ] 000000b1 imul eax , edx 000000b4 add eax , ebx 000000b6 cmp eax , edi 000000b8 jae 000001FA 000000be mov dword ptr [ ecx+eax*4+8 ] ,0Ch bigArray [ x , y ] = 12 ; 0000016b mov eax , dword ptr [ ebp-14h ] 0000016e imul eax , edx 00000171 add eax , ebx 00000173 cmp eax , edi 00000175 jae 000001FA 0000017b mov dword ptr [ ecx+eax*4+8 ] ,0Ch Directly : 573 msVia indexer : 353 msDirectly : 356 msVia indexer : 362 msDirectly : 351 msVia indexer : 370 msDirectly : 351 msVia indexer : 354 msDirectly : 359 msVia indexer : 356 ms",Poor C # optimizer performance ? "C_sharp : Same question as this one , but for C # 7.0 instead of 6.0 : Is there a way to assign a value to an explicitly-implemented read-only ( getter only ) interface property in a constructor ? Or is it still the same answer , i.e . use the backing-field work-around ? For example : Work-around : interface IPerson { string Name { get ; } } class MyPerson : IPerson { string IPerson.Name { get ; } internal MyPerson ( string withName ) { // does n't work ; Property or indexer 'IPerson.Name ' // can not be assigned to -- it is read only ( ( IPerson ) this ) .Name = withName ; } } class MyPerson : IPerson { string _name ; string IPerson.Name { get { return _name ; } } internal MyPerson ( string withName ) { _name = withName ; } }",Assign a value to an explicitly-implemented readonly interface property in a constructor "C_sharp : If you have this code : The resulting array elements are : Now if you reverse the order of the separators , The resulting array elements are : From these 2 examples I feel inclined to conclude that the Split method recursively tokenizes as it goes through each element of the array from left to right.However , once we throw in separators that contain alphanumeric characters into the equation , it is clear that the above theory is wrong.results in : 1 . `` 5 '' 2 . `` .7 '' results in : 1 . `` 5 '' 2 . `` .7 '' This time we obtain the same output , which means that the rule theorized based on the first set of examples no longer applies . ( ie : if separator precedence was always determined based on the position of the separator within the array , then in the last example we would have obtained `` 5 . '' & `` 7 '' instead of `` 5 '' & `` .7 '' .As to why I am wasting my time trying to guess how .NET standard API 's work , it 's because I want to implement similar functionality for my java apps , but neither StringTokenizer nor org.apache.commons.lang.StringUtils provide the ability to split a String using multiple multi-character separators ( and even if I were to find an API that does provide this ability , it would be hard to know if it always tokenizes using the same algorithm used by the String.Split method . `` ... ... '' .Split ( new String [ ] { `` ... '' , `` .. '' } , StringSplitOptions.None ) ; 1. `` '' 2. `` '' 3. `` '' `` ... ... '' .Split ( new String [ ] { `` .. '' , `` ... '' } , StringSplitOptions.None ) ; 1. `` '' 2. `` '' 3. `` '' 4. `` '' `` 5.x.7 '' .Split ( new String [ ] { `` .x '' , `` x . `` } , StringSplitOptions.None ) `` 5.x.7 '' .Split ( new String [ ] { `` x . `` , `` .x '' } , StringSplitOptions.None )",how does the String.Split method determine separator precedence when passed multiple multi-character separators ? "C_sharp : I am aware of the fact that I always have to override Equals ( object ) and GetHashCode ( ) when implementing IEquatable < T > .Equals ( T ) .However , I do n't understand , why in some situations the Equals ( object ) wins over the generic Equals ( T ) .For example why is the following happening ? If I declare IEquatable < T > for an interface and implement a concrete type X for it , the general Equals ( object ) is called by a Hashset < X > when comparing items of those type against each other . In all other situations where at least one of the sides is cast to the Interface , the correct Equals ( T ) is called.Here 's a code sample to demonstrate : public interface IPerson : IEquatable < IPerson > { } //Simple example implementation of Equals ( returns always true ) class Person : IPerson { public bool Equals ( IPerson other ) { return true ; } public override bool Equals ( object obj ) { return true ; } public override int GetHashCode ( ) { return 0 ; } } private static void doEqualityCompares ( ) { var t1 = new Person ( ) ; var hst = new HashSet < Person > ( ) ; var hsi = new HashSet < IPerson > ( ) ; hst.Add ( t1 ) ; hsi.Add ( t1 ) ; //Direct comparison t1.Equals ( t1 ) ; //IEquatable < T > .Equals ( T ) hst.Contains ( t1 ) ; //Equals ( object ) -- > why ? both sides inherit of IPerson ... hst.Contains ( ( IPerson ) t1 ) ; //IEquatable < T > .Equals ( T ) hsi.Contains ( t1 ) ; //IEquatable < T > .Equals ( T ) hsi.Contains ( ( IPerson ) t1 ) ; //IEquatable < T > .Equals ( T ) }",Why does Equals ( object ) win over Equals ( T ) when using an inherited object in Hashset or other Collections ? "C_sharp : I 'm trying to get started with SimpleInjector as an IOC Container and up to now I 'm pretty happy with it . But right now I 'm stuck on a problem I ca n't solve . I searched on SO and in the documentation , but it seems to be not answered yet . I 've seen the howto doc from SimpleInjector but that does n't cover open generic interfaces.I have two generic interfaces like these : And one open generic implementation for those two : In my Application I 'm setting up SimpleInjector like this : What I 'm trying to archive is : I 'd like to get exactly the same instance when asking for a IEventPublisher or an IEventSubscriber . And furthermore this Instance shall be a singleton for any T.I 've tested this with these lines : Unfortunatly p and s do n't refer to the same instance . Anyone happens to know a solution to this problem ? public interface IEventPublisher < TEvent > { void Publish ( TEvent Event ) ; } public interface IEventSubscriber < TEvent > { void Subscribe ( Action < TEvent > CallBack ) ; } class EventMediator < T > : IEventPublisher < T > , IEventSubscriber < T > { List < Action < T > > Subscriptions = new List < Action < T > > ( ) ; public void Publish ( T Event ) { foreach ( var Subscription in this.Subscriptions ) Subscription.Invoke ( Event ) ; } public void Subscribe ( Action < T > CallBack ) { this.Subscriptions.Add ( CallBack ) ; } } this.Container = new SimpleInjector.Container ( ) ; this.Container.RegisterOpenGeneric ( typeof ( IEventPublisher < > ) , typeof ( EventMediator < > ) , Lifestyle.Singleton ) ; this.Container.RegisterOpenGeneric ( typeof ( IEventSubscriber < > ) , typeof ( EventMediator < > ) , Lifestyle.Singleton ) ; this.Container.Verify ( ) ; class DummyEvent { } var p = this.Container.GetInstance < IEventPublisher < DummyEvent > > ( ) ; var s = this.Container.GetInstance < IEventSubscriber < DummyEvent > > ( ) ; var areSame = ( object.ReferenceEquals ( p , s ) ) ;",SimpleInjector HowTo Register multiple Open Generic Interfaces for a Single Generic Implementation "C_sharp : In the context of a console application making use of async/await constructs , I would like to know if it 's possible for `` continuations '' to run in parallel on multiple threads on different CPUs.I think this is the case , as continuations are posted on the default task scheduler ( no SynchronizationContext in console app ) , which is the thread pool.I know that async/await construct do not construct any additional thread . Still there should be at least one thread constructed per CPU by the thread pool , and therefore if continuations are posted on the thread pool , it could schedule task continuations in parrallel on different CPUs ... that 's what I thought , but for some reason I got really confused yesterday regarding this and I am not so sure anymore.Here is some simple code : SomeOperationAsync does not create any thread in itself , and let 's say for the sake of the example that it just sends some request asynchronously relying on I/O completion port so not blocking any thread at all.Now , if I call Start method which will issue 1000 async operations , is it possible for the continuation code of the async method ( after the await ) to be run in parallel on different CPU threads ? i.e do I need to take care of thread synchronization in this case and synchronize access to field `` i '' ? public class AsyncTest { int i ; public async Task DoOpAsync ( ) { await SomeOperationAsync ( ) ; // Does the following code continuation can run // in parrallel ? i++ ; // some other continuation code ... . } public void Start ( ) { for ( int i=0 ; i < 1000 ; i++ ) { var _ = DoOpAsync ( ) ; } // dummy variable to bypass warning } }",Task continuation parallel execution with async/await "C_sharp : I 'm interesting in some design choices of C # language . There is a rule in C # spec that allows to use method groups as the expressions of is operator : Condition above is always false , as the specification says : 7.10.10 The is operator • If E is a method group or the null literal , of if the type of E is a reference type or a nullable type and the value of E is null , the result is false.My questions : what is the purpose/point/reason of allowing to use the C # language element with no runtime representation in CLR like method groups inside the such `` runtime '' operator like is ? class Foo { static void Main ( ) { if ( Main is Foo ) Main ( ) ; } }",C # Language Design : method group inside ` is ` operator "C_sharp : I am using Visual studio 2015 community report viewer version 12 to show rdlc reports in my c # project . here is normal A4 page reportits works fine for windows xp , vista , win 7 on client PCs but when same application is installed on Windows 10 64 bit then I am facing problem like belowas you can see in above image there are unnecessary margins are coming from right and bottom side as well as font size also reduced . but when I export report to PDF then there is no problem in generated PDF its same as report which I designed.What was I Tried : I Installed MICROSOFT® REPORT VIEWER 2015 RUNTIME from https : //www.microsoft.com/en-us/download/details.aspx ? id=45496Installed Microsoft® SQL Server® 2014 Feature Pack ( System CLR Types For SQL Server 2014 ) tried to Export RDLC directly to Printer using below codeCode for Print ClassCode on Print Buttonbut its also printing same as describe abovethe same application is running on my PC with Windows 10 64 bit but not working after deployment on client PC having Windows 10 64bitOn Client PC .Net 4.0 framework , SQL Server 2008 , Windows 10 64 bit installedHow to resolve it . public static class _cWainfoPrintReport { private static int m_currentPageIndex ; private static IList < Stream > m_streams ; public static Stream CreateStream ( string name , string fileNameExtension , Encoding encoding , string mimeType , bool willSeek ) { Stream stream = new MemoryStream ( ) ; m_streams.Add ( stream ) ; return stream ; } public static void _mExport ( LocalReport report , bool print = true , double _pageWightInches = 8.27 , double _pageHeightInches = 11.69 , double _MarginTopInches = 0.025 , double _MarginLeftInches = 0.025 , double _MarginRightInches = 0.025 , double _MarginBottomInches = 0.025 ) { string deviceInfo = @ '' < DeviceInfo > < OutputFormat > EMF < /OutputFormat > < PageWidth > '' + _pageWightInches + `` in < /PageWidth > < PageHeight > '' + _pageHeightInches + `` in < /PageHeight > < MarginTop > '' + _MarginTopInches + `` in < /MarginTop > < MarginLeft > '' + _MarginLeftInches + `` in < /MarginLeft > < MarginRight > '' + _MarginRightInches + `` in < /MarginRight > < MarginBottom > '' + _MarginBottomInches + `` in < /MarginBottom > < /DeviceInfo > '' ; Warning [ ] warnings ; m_streams = new List < Stream > ( ) ; report.Render ( `` Image '' , deviceInfo , CreateStream , out warnings ) ; foreach ( Stream stream in m_streams ) stream.Position = 0 ; if ( print ) { _mPrint ( _pageWightInches , _pageHeightInches , _MarginTopInches , _MarginLeftInches , _MarginRightInches , _MarginBottomInches ) ; } report.ReleaseSandboxAppDomain ( ) ; } // Handler for PrintPageEvents public static void _mPrintPage ( object sender , PrintPageEventArgs ev ) { Metafile pageImage = new Metafile ( m_streams [ m_currentPageIndex ] ) ; // Adjust rectangular area with printer margins . Rectangle adjustedRect = new Rectangle ( ev.PageBounds.Left - ( int ) ev.PageSettings.HardMarginX , ev.PageBounds.Top - ( int ) ev.PageSettings.HardMarginY , ev.PageBounds.Width , ev.PageBounds.Height ) ; // Draw a white background for the report ev.Graphics.FillRectangle ( Brushes.White , adjustedRect ) ; // Draw the report content ev.Graphics.DrawImage ( pageImage , adjustedRect ) ; // Prepare for the next page . Make sure we have n't hit the end . m_currentPageIndex++ ; ev.HasMorePages = ( m_currentPageIndex < m_streams.Count ) ; } public static PaperSize CalculatePaperSize ( double WidthInCentimeters , double HeightInCentimetres ) { int Width = int.Parse ( ( Math.Round ( ( WidthInCentimeters * 0.393701 ) * 100 , 0 , MidpointRounding.AwayFromZero ) ) .ToString ( ) ) ; int Height = int.Parse ( ( Math.Round ( ( HeightInCentimetres * 0.393701 ) * 100 , 0 , MidpointRounding.AwayFromZero ) ) .ToString ( ) ) ; PaperSize NewSize = new PaperSize ( ) ; NewSize.RawKind = ( int ) PaperKind.Custom ; NewSize.Width = Width ; NewSize.Height = Height ; NewSize.PaperName = `` Letter '' ; return NewSize ; } public static void _mPrint ( double _pageWightInches = 8.27 , double _pageHeightInches = 11.69 , double _MarginTopInches = 0.025 , double _MarginLeftInches = 0.025 , double _MarginRightInches = 0.025 , double _MarginBottomInches = 0.025 ) { if ( m_streams == null || m_streams.Count == 0 ) throw new Exception ( `` Error : no stream to print . `` ) ; PrintDocument printDoc = new PrintDocument ( ) ; PaperSize RequiredPaperSize = CalculatePaperSize ( _pageWightInches * 2.54 , _pageHeightInches * 2.54 ) ; bool FoundMatchingPaperSize = false ; for ( int index = 0 ; index < printDoc.PrinterSettings.PaperSizes.Count ; index++ ) { if ( printDoc.PrinterSettings.PaperSizes [ index ] .Height == RequiredPaperSize.Height & & printDoc.PrinterSettings.PaperSizes [ index ] .Width == RequiredPaperSize.Width ) { printDoc.PrinterSettings.DefaultPageSettings.PaperSize = printDoc.PrinterSettings.PaperSizes [ index ] ; printDoc.DefaultPageSettings.PaperSize = printDoc.PrinterSettings.PaperSizes [ index ] ; FoundMatchingPaperSize = true ; break ; } } if ( ! printDoc.PrinterSettings.IsValid ) { throw new Exception ( `` Error : can not find the default printer . `` ) ; } else { printDoc.PrintPage += new PrintPageEventHandler ( _mPrintPage ) ; m_currentPageIndex = 0 ; printDoc.Print ( ) ; } } public static void _mPrintToPrinter ( this LocalReport report ) { _mExport ( report ) ; } public static void _mDisposePrint ( ) { if ( m_streams ! = null ) { foreach ( Stream stream in m_streams ) stream.Close ( ) ; m_streams = null ; } } } PrintViewer _PJobEntry = new PrintViewer ( ) ; DataTable dt = new DataSet1.MainTableDataTable ( ) ; dt.Rows.Add ( 'vales for dataset ' ) ; _PJobEntry._RptView.LocalReport.DataSources.Add ( new ReportDataSource ( `` DataSet1 '' , dt ) ) ; _PJobEntry._RptView.LocalReport.ReportEmbeddedResource = `` WAINFOBUSSOLN.Printing.RptSaleInvoice02.rdlc '' ; _PJobEntry._RptView.SetDisplayMode ( DisplayMode.PrintLayout ) ; _cWainfoPrintReport._mExport ( _PJobEntry._RptView.LocalReport , true , 8.27 , 11.69 , 0.25 , 0.25 , 0.28 , 0.25 ) ;",Visual studio 2015 community report viewer version 12 Error getting extra margin using c # "C_sharp : I 'm working on creating an open source project for creating .NET UML Sequence Diagrams that leverages a javascript library called js-sequence-diagrams . I am not sure Roslyn is the right tool for the job , but I thought I would give it a shot so I have put together some proof of concept code which attempts to get all methods and their invocations and then outputs these invocations in a form that can be interpreted by js-sequence-diagrams . The code generates some output , but it does not capture everything . I can not seem to capture invocations via extension methods , invocations of static methods in static classes . I do see invocations of methods with out parameters , but not in any form that extends the BaseMethodDeclarationSyntaxHere is the code ( keep in mind this is proof of concept code and so I did not entirely follow best-practices , but I am not requesting a code review here ... also , I am used to using Tasks so I am messing around with await , but am not entirely sure I am using it properly yet ) https : //gist.github.com/SoundLogic/11193841Any guidance here would be much appreciated ! using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; using System.Reflection.Emit ; using System.Threading.Tasks ; using Microsoft.CodeAnalysis ; using Microsoft.CodeAnalysis.CSharp ; using Microsoft.CodeAnalysis.CSharp.Syntax ; using Microsoft.CodeAnalysis.Formatting ; using Microsoft.CodeAnalysis.MSBuild ; using Microsoft.CodeAnalysis.FindSymbols ; using System.Collections.Immutable ; namespace Diagrams { class Program { static void Main ( string [ ] args ) { string solutionName = `` Diagrams '' ; string solutionExtension = `` .sln '' ; string solutionFileName = solutionName + solutionExtension ; string rootPath = @ '' C : \Workspace\ '' ; string solutionPath = rootPath + solutionName + @ '' \ '' + solutionFileName ; MSBuildWorkspace workspace = MSBuildWorkspace.Create ( ) ; DiagramGenerator diagramGenerator = new DiagramGenerator ( solutionPath , workspace ) ; diagramGenerator.ProcessSolution ( ) ; # region reference //TODO : would ReferencedSymbol.Locations be a better way of accessing MethodDeclarationSyntaxes ? //INamedTypeSymbol programClass = compilation.GetTypeByMetadataName ( `` DotNetDiagrams.Program '' ) ; //IMethodSymbol barMethod = programClass.GetMembers ( `` Bar '' ) .First ( s = > s.Kind == SymbolKind.Method ) as IMethodSymbol ; //IMethodSymbol fooMethod = programClass.GetMembers ( `` Foo '' ) .First ( s = > s.Kind == SymbolKind.Method ) as IMethodSymbol ; //ITypeSymbol fooSymbol = fooMethod.ContainingType ; //ITypeSymbol barSymbol = barMethod.ContainingType ; //Debug.Assert ( barMethod ! = null ) ; //Debug.Assert ( fooMethod ! = null ) ; //List < ReferencedSymbol > barReferencedSymbols = SymbolFinder.FindReferencesAsync ( barMethod , solution ) .Result.ToList ( ) ; //List < ReferencedSymbol > fooReferencedSymbols = SymbolFinder.FindReferencesAsync ( fooMethod , solution ) .Result.ToList ( ) ; //Debug.Assert ( barReferencedSymbols.First ( ) .Locations.Count ( ) == 1 ) ; //Debug.Assert ( fooReferencedSymbols.First ( ) .Locations.Count ( ) == 0 ) ; # endregion Console.ReadKey ( ) ; } } class DiagramGenerator { private Solution _solution ; public DiagramGenerator ( string solutionPath , MSBuildWorkspace workspace ) { _solution = workspace.OpenSolutionAsync ( solutionPath ) .Result ; } public async void ProcessSolution ( ) { foreach ( Project project in _solution.Projects ) { Compilation compilation = await project.GetCompilationAsync ( ) ; ProcessCompilation ( compilation ) ; } } private async void ProcessCompilation ( Compilation compilation ) { var trees = compilation.SyntaxTrees ; foreach ( var tree in trees ) { var root = await tree.GetRootAsync ( ) ; var classes = root.DescendantNodes ( ) .OfType < ClassDeclarationSyntax > ( ) ; foreach ( var @ class in classes ) { ProcessClass ( @ class , compilation , tree , root ) ; } } } private void ProcessClass ( ClassDeclarationSyntax @ class , Compilation compilation , SyntaxTree tree , SyntaxNode root ) { var methods = @ class.DescendantNodes ( ) .OfType < MethodDeclarationSyntax > ( ) ; foreach ( var method in methods ) { var model = compilation.GetSemanticModel ( tree ) ; // Get MethodSymbol corresponding to method var methodSymbol = model.GetDeclaredSymbol ( method ) ; // Get all InvocationExpressionSyntax in the above code . var allInvocations = root.DescendantNodes ( ) .OfType < InvocationExpressionSyntax > ( ) ; // Use GetSymbolInfo ( ) to find invocations of target method var matchingInvocations = allInvocations.Where ( i = > model.GetSymbolInfo ( i ) .Symbol.Equals ( methodSymbol ) ) ; ProcessMethod ( matchingInvocations , method , @ class ) ; } var delegates = @ class.DescendantNodes ( ) .OfType < DelegateDeclarationSyntax > ( ) ; foreach ( var @ delegate in delegates ) { var model = compilation.GetSemanticModel ( tree ) ; // Get MethodSymbol corresponding to method var methodSymbol = model.GetDeclaredSymbol ( @ delegate ) ; // Get all InvocationExpressionSyntax in the above code . var allInvocations = tree.GetRoot ( ) .DescendantNodes ( ) .OfType < InvocationExpressionSyntax > ( ) ; // Use GetSymbolInfo ( ) to find invocations of target method var matchingInvocations = allInvocations.Where ( i = > model.GetSymbolInfo ( i ) .Symbol.Equals ( methodSymbol ) ) ; ProcessDelegates ( matchingInvocations , @ delegate , @ class ) ; } } private void ProcessMethod ( IEnumerable < InvocationExpressionSyntax > matchingInvocations , MethodDeclarationSyntax methodDeclarationSyntax , ClassDeclarationSyntax classDeclarationSyntax ) { foreach ( var invocation in matchingInvocations ) { MethodDeclarationSyntax actingMethodDeclarationSyntax = null ; if ( SyntaxNodeHelper.TryGetParentSyntax ( invocation , out actingMethodDeclarationSyntax ) ) { var r = methodDeclarationSyntax ; var m = actingMethodDeclarationSyntax ; PrintCallerInfo ( invocation , classDeclarationSyntax , m.Identifier.ToFullString ( ) , r.ReturnType.ToFullString ( ) , r.Identifier.ToFullString ( ) , r.ParameterList.ToFullString ( ) , r.TypeParameterList ! = null ? r.TypeParameterList.ToFullString ( ) : String.Empty ) ; } } } private void ProcessDelegates ( IEnumerable < InvocationExpressionSyntax > matchingInvocations , DelegateDeclarationSyntax delegateDeclarationSyntax , ClassDeclarationSyntax classDeclarationSyntax ) { foreach ( var invocation in matchingInvocations ) { DelegateDeclarationSyntax actingMethodDeclarationSyntax = null ; if ( SyntaxNodeHelper.TryGetParentSyntax ( invocation , out actingMethodDeclarationSyntax ) ) { var r = delegateDeclarationSyntax ; var m = actingMethodDeclarationSyntax ; PrintCallerInfo ( invocation , classDeclarationSyntax , m.Identifier.ToFullString ( ) , r.ReturnType.ToFullString ( ) , r.Identifier.ToFullString ( ) , r.ParameterList.ToFullString ( ) , r.TypeParameterList ! = null ? r.TypeParameterList.ToFullString ( ) : String.Empty ) ; } } } private void PrintCallerInfo ( InvocationExpressionSyntax invocation , ClassDeclarationSyntax classBeingCalled , string callingMethodName , string returnType , string calledMethodName , string calledMethodArguments , string calledMethodTypeParameters = null ) { ClassDeclarationSyntax parentClassDeclarationSyntax = null ; if ( ! SyntaxNodeHelper.TryGetParentSyntax ( invocation , out parentClassDeclarationSyntax ) ) { throw new Exception ( ) ; } calledMethodTypeParameters = calledMethodTypeParameters ? ? String.Empty ; var actedUpon = classBeingCalled.Identifier.ValueText ; var actor = parentClassDeclarationSyntax.Identifier.ValueText ; var callInfo = callingMethodName + `` = > '' + calledMethodName + calledMethodTypeParameters + calledMethodArguments ; var returnCallInfo = returnType ; string info = BuildCallInfo ( actor , actedUpon , callInfo , returnCallInfo ) ; Console.Write ( info ) ; } private string BuildCallInfo ( string actor , string actedUpon , string callInfo , string returnInfo ) { const string calls = `` - > '' ; const string returns = `` -- > '' ; const string descriptionSeparator = `` : `` ; string callingInfo = actor + calls + actedUpon + descriptionSeparator + callInfo ; string returningInfo = actedUpon + returns + actor + descriptionSeparator + `` returns `` + returnInfo ; callingInfo = callingInfo.RemoveNewLines ( true ) ; returningInfo = returningInfo.RemoveNewLines ( true ) ; string result = callingInfo + Environment.NewLine ; result += returningInfo + Environment.NewLine ; return result ; } } static class SyntaxNodeHelper { public static bool TryGetParentSyntax < T > ( SyntaxNode syntaxNode , out T result ) where T : SyntaxNode { // set defaults result = null ; if ( syntaxNode == null ) { return false ; } try { syntaxNode = syntaxNode.Parent ; if ( syntaxNode == null ) { return false ; } if ( syntaxNode.GetType ( ) == typeof ( T ) ) { result = syntaxNode as T ; return true ; } return TryGetParentSyntax < T > ( syntaxNode , out result ) ; } catch { return false ; } } } public static class StringEx { public static string RemoveNewLines ( this string stringWithNewLines , bool cleanWhitespace = false ) { string stringWithoutNewLines = null ; List < char > splitElementList = Environment.NewLine.ToCharArray ( ) .ToList ( ) ; if ( cleanWhitespace ) { splitElementList.AddRange ( `` `` .ToCharArray ( ) .ToList ( ) ) ; } char [ ] splitElements = splitElementList.ToArray ( ) ; var stringElements = stringWithNewLines.Split ( splitElements , StringSplitOptions.RemoveEmptyEntries ) ; if ( stringElements.Any ( ) ) { stringWithoutNewLines = stringElements.Aggregate ( stringWithoutNewLines , ( current , element ) = > current + ( current == null ? element : `` `` + element ) ) ; } return stringWithoutNewLines ? ? stringWithNewLines ; } } }","How to access invocations through extension methods , methods in static classes and methods with ref/out parameters with Roslyn" "C_sharp : We have a new app we are trying to submit to the app store ( using TestFlight for pre-release beta testing ) but are getting an Invalid binary message due to the reference of UIWebView : TMS-90809 : Deprecated API Usage - New apps that use UIWebView are no longer accepted . Instead , use WKWebView for improved security and reliability.We 've followed the guide provide by Xamarin here : https : //docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview ? tabs=macos # uiwebview-deprecation-and-app-store-rejection-itms-90809We have : Upgraded Xamarin Forms to 4.6 or higher - 4.6.0.706Ensured Xamarin.iOS 13.10.0.17 or higher - 13.16.0.13Remove references to UIWebView ( none in the first place ) Ensured IOS build is set to `` Link Framework SDKs Only '' ( already was ) Added the required mtouch argument : `` -- optimize=experimental-xforms-product-type '' Updated all build configs ( release/iphone , release/simulator , debug/iphone , debug/simulator ) I 've also deleted my packages , bin , and object folders to ensure I get a full build , yet continue to get this response when uploading.EDIT : I added the warning flag to my MTOUCH to see where it 's used as well , and I do now see a warning , so it 's there ... somewhere.Warning code added : -- warn-on-type-ref=UIKit.UIWebViewBuild warning : How can I go about finding which package is utilizing UIWebView without haphazardly updating them all and hoping that does the trick ( without other unintended consequences ) ? EDIT # 2 : I got GREP search working as recommended below - here are my resultsLooks to me like HockeyApp may be one of my culprits . I 've already updated the package , but I do know HockeyApp 's been migrated to AppCenter , so perhaps this code is no longer maintained . Also see a reference SQLite , which is one set of packages I ca n't get updated without breaking other parts of my app.EDIT # 3We 've removed HockeyApp but still have the two reference warnings . I 've removed SQLIte PCL and re-added it to the most recent version but still see the reference to the storage.ide file , which I think is just a local database file I can ignore . It looks like all that 's left is Xamarin.Forms references , but all of this should be dealt with via my mtouch arguments : < MtouchExtraArgs > -- optimize=experimental-xforms-product-type -- warn-on-type-ref=UIKit.UIWebView < /MtouchExtraArgCa n't figure out what I 'm missing ... grep -r 'UIWebView ' .Binary file ./.vs/NorthernLights/xs/sqlite3/storage.ide matches./iOS/NorthernLights.iOS.csproj : < MtouchExtraArgs > -- optimize=experimental-xforms-product-type -- warn-on-type-ref=UIKit.UIWebView < /MtouchExtraArgs > Binary file ./packages/Xamarin.Forms.4.6.0.726/buildTransitive/XCODE10/Xamarin.Forms.Platform.iOS.dll matchesBinary file ./packages/Xamarin.Forms.4.6.0.726/buildTransitive/XCODE11/Xamarin.Forms.Platform.iOS.dll matchesBinary file ./packages/Xamarin.Forms.4.6.0.726/build/XCODE10/Xamarin.Forms.Platform.iOS.dll matchesBinary file ./packages/Xamarin.Forms.4.6.0.726/build/XCODE11/Xamarin.Forms.Platform.iOS.dll matchesBinary file ./packages/HockeySDK.Xamarin.5.2.0/lib/Xamarin.iOS10/HockeySDK.iOSBindings.dll matches",Xamarin iOS app being rejected for UIWebView after following guide "C_sharp : I 'm trying to write a DLL in Delphi to allow my C # app to access an Advantage database ( using VS2013 and not been able to access the data directly ) .My issue is after I make the call , the array in C # is full of null values.The Delphi DLL code : This appears to be working . I 've used ShowMessage to show what the information going in looks like and what it looks like after.The C # Code : This code executes , no errors of any kind , but when I iterate through projectItems each one returns TItem = record Id : Int32 ; Description : PWideChar ; end ; function GetNumElements ( const ATableName : PWideChar ) : Integer ; stdcall ; var recordCount : Integer ; begin ... // code to get the number of records from ATableName Result : = recordCount ; end ; procedure GetTableData ( const ATableName : PWideChar ; const AIdField : PWideChar ; const ADataField : PWideChar ; result : array of TItem ) ; stdcall ; begin ... // ATableName , AIdField , and ADataField are used to query the specific table , then I loop through the records and add each one to result array index : = -1 ; while not Query.Eof do begin Inc ( index ) ; result [ index ] .Id : = Query.FieldByName ( AIdField ) .AsInteger ; result [ index ] .Description : = PWideChar ( Query.FieldByName ( ADataField ) .AsString ) ; Query.Next ; end ; ... // cleanup stuff ( freeing created objects , etc ) end ; [ StructLayoutAttribute ( LayoutKind.Explicit ) ] // also tried LayoutKind.Sequential without FieldOffsetpublic struct TItem { [ FieldOffset ( 0 ) ] public Int32 Id ; [ MarshalAs ( UnmanagedType.LPWStr ) , FieldOffset ( sizeof ( Int32 ) ) ] public string Description ; } public static extern void GetTableData ( [ MarshalAs ( UnmanagedType.LPWStr ) ] string tableName , [ MarshalAs ( UnmanagedType.LPWStr ) ] string idField , [ MarshalAs ( UnmanagedType.LPWStr ) ] string dataField , [ MarshalAs ( UnmanagedType.LPArray ) ] TItem [ ] items , int high ) ; public void GetListItems ( ) { int numProjects = GetNumElements ( `` Project '' ) ; TItems [ ] projectItems = new TItem [ numProjects ] ; GetTableData ( `` Project '' , `` ProjectId '' , `` ProjectName '' , projectItems , numProjects ) ; } Id = 0Description = null",Retrieve record array from Delphi DLL with C # "C_sharp : I have some code like this , I do n't know what type is until runtime.And I need a list defined as : I 've triedBut it does not work well because I need to pass this list to XmlSerializer.Serialize method . It only output a correct result when this list is defined exactly Listfor example : When I pass in List < String > list = new List < String > ( ) It outputWhen I pass in IList list = new List < String > ( ) It will outputwhich is not what I want.How can I define a List when I do n't know what type is at compile time ? Type type ; List < type > var listType = typeof ( List < > ) .MakeGenericType ( new [ ] { type } ) ; IList list = Activator.CreateInstance ( listType ) ) ; < ArrayOfString > ... < /ArrayOfString > < ArrayOfAnyType > ... < /ArrayOfAnyType >",How do I create List < type > for runtime type ? "C_sharp : I have encountered some weird/unexpected behaviour in which Guid.ToString ( ) in a Linq expression returns a different result than Guid.ToString ( ) in a foreach loop.What the method is doing : The method in question is simply taking an object and then creates a new view-model from the original object . The company I work for has decided that Guid 's will not be allowed on view-models , due to one of our older JSON serializers having an bug in which Guid 's were not serialized correctly.The problem/unexpected result : While debugging/testing my method I found that the Linq expression I created was returning a strange result . When converting my Guid to its string representation , the result was being automatically capitalised . I did n't believe that it was the Linq expression at first but once I had converted the logic into a foreach loop I got a lower-cased string representation of my Guid.Example code : Please note that the property types for lookupList ( ID1 , ID2 , ID3 ) are all of type Guid and the properties on NewClass are all of type string.Linq expression : Returns : Foreach loop : Returns : The question : Why is this happening and is this expected behaviour ? I would expect both the Linq expression and the foreach loop to return the same result when .ToString ( ) is applied to my Guid but somehow it is not . I have also checked that there are no .ToString ( ) overrides in either class . Thank you in advance.Update : The lookupList has been handled by a .ToList ( ) before it hits my method . LookupList is of type List < t > where t is a custom business entity which has additional properties that the database does not have . Apologies , I did not make this clear in my original question . List < NewClass > returnList = lookupList.Select ( i = > new NewClass { Property1 = i.ID1.ToString ( ) , Property2 = i.ID2.ToString ( ) , Property3 = i.ID3.ToString ( ) , ... .. } ) .ToList ( ) ; { Property1=7081C549-64D6-458E-A693-0D2C9C47D183 Property2=06DD6A59-D339-4E15-89EA-48803DBA271E Property3=9A876EDD-3B79-C27E-1680-E0820A0CD6EC } var returnList = new List < NewClass > ( ) ; foreach ( var item in lookupList ) { returnList.Add ( new NewClass { Property1 = item.ID1.ToString ( ) , Property2 = item.ID2.ToString ( ) , Property3 = item.ID3.ToString ( ) , ... .. } ) ; } { Property1=7081c549-64d6-458e-a693-0d2c9c47d183 Property2=06dd6a59-d339-4e15-89ea-48803dba271e Property3=9a876edd-3b79-c27e-1680-e0820a0cd6ec }",Why is Guid.ToString returning capitalised string in Linq ? "C_sharp : Say I have a type T : And I have a predefined ordered sequence of identifiers : I now need to order an IObservable < T > which produces the following sequence of objects : So that the resulting IObservable produces hello.I do n't want to use ToArray , as I want to receive objects as soon as they arrive and not wait until everything is observed.More specifically , I would like to receive them like this : What would be the proper reactive way to do this ? The best I could come up with is this : EDIT : Schlomo raised some very valid issues with my code , which is why I marked his answer as correct . I made some modifications to his to code for it to be usable : Generic identifier and object typeIteration instead of recursion to prevent potential stackoverflow on very large observablesConvert the anonymous type to a real class for readabilityWherever possible , lookup a value in a dictionary only once and store as variable instead of looking it up multiple timesFixed typeThis gives me the following code : However , this code still has a couple of problems : Constant copying of the state ( mainly the ImmutableDictionary ) , which can be very expensive . Possible solution : maintain a separate state per observer , instead of per item received.When one or more of the elements in identifierSequence are not present in the source observable a problem appears . This currently blocks the ordered observable and it will never finish . Possible solutions : Timeout , throw exception when source observable is completed , return all available items when source observable is completed , ... When the source observable contains more elements than identifierSequence , we get a memory leak . Items that are in the source observable , but not in identifierSequence currently get added to the dictionary , but will not be deleted before the source observable completes . This is a potential memory leak . Possible solutions : check whether the item is in identifierSequence before adding it to the dictionary , bypass code and immediately output the item , ... MY SOLUTION : class T { public int identifier ; //Arbitrary but unique for each character ( Guids in real-life ) public char character ; //In real life not a char , but I chose char here for easy demo purposes } int [ ] identifierSequence = new int [ ] { 9 , 3 , 4 , 4 , 7 } ; { identifier : 3 , character ' e ' } , { identifier : 9 , character ' h ' } , { identifier : 4 , character ' l ' } , { identifier : 4 , character ' l ' } , { identifier : 7 , character ' o ' } Input : e h l l oOutput : he l l o Dictionary < int , T > buffer = new Dictionary < int , T > ( ) ; int curIndex = 0 ; inputObserable.SelectMany ( item = > { buffer [ item.identifier ] = item ; IEnumerable < ReportTemplate > GetReadyElements ( ) { while ( true ) { int nextItemIdentifier = identifierSequence [ curIndex ] ; T nextItem ; if ( buffer.TryGetValue ( nextItemIdentifier , out nextItem ) ) { buffer.Remove ( nextItem.identifier ) ; curIndex++ ; yield return nextItem ; } else { break ; } } } return GetReadyElements ( ) ; } ) ; public static IObservable < T > OrderByIdentifierSequence < T , TId > ( this IObservable < T > source , IList < TId > identifierSequence , Func < T , TId > identifierFunc ) { var initialState = new OrderByIdentifierSequenceState < T , TId > ( 0 , ImmutableDictionary < TId , ImmutableList < T > > .Empty , Enumerable.Empty < T > ( ) ) ; return source.Scan ( initialState , ( oldState , item ) = > { //Function to be called upon receiving new item //If we can pattern match the first item , then it is moved into Output , and concatted continuously with the next possible item //Otherwise , if nothing is available yet , just return the input state OrderByIdentifierSequenceState < T , TId > GetOutput ( OrderByIdentifierSequenceState < T , TId > state ) { int index = state.Index ; ImmutableDictionary < TId , ImmutableList < T > > buffer = state.Buffer ; IList < T > output = new List < T > ( ) ; while ( index < identifierSequence.Count ) { TId key = identifierSequence [ index ] ; ImmutableList < T > nextValues ; if ( ! buffer.TryGetValue ( key , out nextValues ) || nextValues.IsEmpty ) { //No values available yet break ; } T toOutput = nextValues [ nextValues.Count - 1 ] ; output.Add ( toOutput ) ; buffer = buffer.SetItem ( key , nextValues.RemoveAt ( nextValues.Count - 1 ) ) ; index++ ; } return new OrderByIdentifierSequenceState < T , TId > ( index , buffer , output ) ; } //Before calling the recursive function , add the new item to the buffer TId itemIdentifier = identifierFunc ( item ) ; ImmutableList < T > valuesList ; if ( ! oldState.Buffer.TryGetValue ( itemIdentifier , out valuesList ) ) { valuesList = ImmutableList < T > .Empty ; } var remodifiedBuffer = oldState.Buffer.SetItem ( itemIdentifier , valuesList.Add ( item ) ) ; return GetOutput ( new OrderByIdentifierSequenceState < T , TId > ( oldState.Index , remodifiedBuffer , Enumerable.Empty < T > ( ) ) ) ; } ) // Use Dematerialize/Notifications to detect and emit end of stream . .SelectMany ( output = > { var notifications = output.Output .Select ( item = > Notification.CreateOnNext ( item ) ) .ToList ( ) ; if ( output.Index == identifierSequence.Count ) { notifications.Add ( Notification.CreateOnCompleted < T > ( ) ) ; } return notifications ; } ) .Dematerialize ( ) ; } class OrderByIdentifierSequenceState < T , TId > { //Index shows what T we 're waiting on public int Index { get ; } //Buffer holds T that have arrived that we are n't ready yet for public ImmutableDictionary < TId , ImmutableList < T > > Buffer { get ; } //Output holds T that can be safely emitted . public IEnumerable < T > Output { get ; } public OrderByIdentifierSequenceState ( int index , ImmutableDictionary < TId , ImmutableList < T > > buffer , IEnumerable < T > output ) { this.Index = index ; this.Buffer = buffer ; this.Output = output ; } } /// < summary > /// Takes the items from the source observable , and returns them in the order specified in identifierSequence . /// If an item is missing from the source observable , the returned obserable returns items up until the missing item and then blocks until the source observable is completed . /// All available items are then returned in order . Note that this means that while a correct order is guaranteed , there might be missing items in the result observable . /// If there are items in the source observable that are not in identifierSequence , these items will be ignored . /// < /summary > /// < typeparam name= '' T '' > The type that is produced by the source observable < /typeparam > /// < typeparam name= '' TId '' > The type of the identifiers used to uniquely identify a T < /typeparam > /// < param name= '' source '' > The source observable < /param > /// < param name= '' identifierSequence '' > A list of identifiers that defines the sequence in which the source observable is to be ordered < /param > /// < param name= '' identifierFunc '' > A function that takes a T and outputs its unique identifier < /param > /// < returns > An observable with the same elements as the source , but ordered by the sequence of items in identifierSequence < /returns > public static IObservable < T > OrderByIdentifierSequence < T , TId > ( this IObservable < T > source , IList < TId > identifierSequence , Func < T , TId > identifierFunc ) { if ( source == null ) { throw new ArgumentNullException ( nameof ( source ) ) ; } if ( identifierSequence == null ) { throw new ArgumentNullException ( nameof ( identifierSequence ) ) ; } if ( identifierFunc == null ) { throw new ArgumentNullException ( nameof ( identifierFunc ) ) ; } if ( identifierSequence.Count == 0 ) { return Observable.Empty < T > ( ) ; } HashSet < TId > identifiersInSequence = new HashSet < TId > ( identifierSequence ) ; return Observable.Create < T > ( observer = > { //current index of pending item in identifierSequence int index = 0 ; //buffer of items we have received but are not ready for yet Dictionary < TId , List < T > > buffer = new Dictionary < TId , List < T > > ( ) ; return source.Select ( item = > { //Function to be called upon receiving new item //We search for the current pending item in the buffer . If it is available , we yield return it and repeat . //If it is not available yet , stop . IEnumerable < T > GetAvailableOutput ( ) { while ( index < identifierSequence.Count ) { TId key = identifierSequence [ index ] ; List < T > nextValues ; if ( ! buffer.TryGetValue ( key , out nextValues ) || nextValues.Count == 0 ) { //No values available yet break ; } yield return nextValues [ nextValues.Count - 1 ] ; nextValues.RemoveAt ( nextValues.Count - 1 ) ; index++ ; } } //Get the identifier for this item TId itemIdentifier = identifierFunc ( item ) ; //If this item is not in identifiersInSequence , we ignore it . if ( ! identifiersInSequence.Contains ( itemIdentifier ) ) { return Enumerable.Empty < T > ( ) ; } //Add the new item to the buffer List < T > valuesList ; if ( ! buffer.TryGetValue ( itemIdentifier , out valuesList ) ) { valuesList = new List < T > ( ) ; buffer [ itemIdentifier ] = valuesList ; } valuesList.Add ( item ) ; //Return all available items return GetAvailableOutput ( ) ; } ) .Subscribe ( output = > { foreach ( T cur in output ) { observer.OnNext ( cur ) ; } if ( index == identifierSequence.Count ) { observer.OnCompleted ( ) ; } } , ( ex ) = > { observer.OnError ( ex ) ; } , ( ) = > { //When source observable is completed , return the remaining available items while ( index < identifierSequence.Count ) { TId key = identifierSequence [ index ] ; List < T > nextValues ; if ( ! buffer.TryGetValue ( key , out nextValues ) || nextValues.Count == 0 ) { //No values available index++ ; continue ; } observer.OnNext ( nextValues [ nextValues.Count - 1 ] ) ; nextValues.RemoveAt ( nextValues.Count - 1 ) ; index++ ; } //Mark observable as completed observer.OnCompleted ( ) ; } ) ; } ) ; }",Sort Observable by predefined order in Reactive Extensions "C_sharp : I 'm looking to use the IRepository pattern ( backed by NHibernate , if it matters ) in a small project . The domain is a simple one , intentionally so to allow me to focus on understanding the IRepository pattern . The lone domain class is Movie , with properties for Year , Genre , and Title . My intent would be to `` get '' movies whose properties match criteria of the aforementioned types.Convention seems to be to have a generic IRepository interface , similar to the following : With a base implementation : Then to have a domain-specific interface : With an implementation that also extends the base Repository class : I would need to add necessary implementation to the base class as well as the concrete one , using NHibernate , but I would like to know if I am on the right track with this setup.There seems to be a fair bit of overhead for just one domain class , though it would be less noticeable if there were multiple domain classes involved . Right now I 'm trying to keep it simple so I can pin down the concept . public interface IRepository < T > { T Get ( int id ) ; T [ ] GetAll ( ) ; void Add ( T item ) ; void Update ( T item ) ; void Delete ( T item ) ; } public abstract class Repository < T > : IRepository < T > { public T Get ( int id ) { ... } public T [ ] GetAll ( ) { ... } public void Add ( T item ) { ... } public void Update ( T item ) { ... } public void Delete ( T item ) { ... } } public interface IMovieRepository { Movie [ ] GetByGenre ( Genre genre ) ; Movie [ ] GetByYear ( int year ) ; Movie [ ] GetByTitle ( string title ) ; } public class MovieRepository : Repository < Movie > , IMovieRepository { public Movie [ ] GetByGenre ( Genre genre ) { ... } public Movie [ ] GetByYear ( int year ) { ... } public Movie [ ] GetByTitle ( string title ) { ... } }",Am I using IRepository correctly ? "C_sharp : I 'm opening directories over network using : But having 2 network paths : How come first one takes very fast to verify that the network PC does n't exist , while 2nd takes around two minutes ? If I 'm not wrong it 's 30 seconds in Windows environment to determine if network path is unreachable . Why does it take so long in this case and how to speed up the info that PC is off ? System.Diagnostics.Process.Start ( path ) ; // path = UNC network path \\This_PC_Does_Not_Exist\dir\\This_PC_Is_Turned_Off\dir",C # opening unavailable network path with Process.Start ( ) "C_sharp : Is there a way to add a handler to all clients created by the IHttpClientFactory ? I know you can do the following on named clients : But I do n't want to use named clients I just want to add a handler to all clients that are given back to me via : services.AddHttpClient ( `` named '' , c = > { c.BaseAddress = new Uri ( `` TODO '' ) ; c.DefaultRequestHeaders.Accept.Add ( new MediaTypeWithQualityHeaderValue ( `` application/json '' ) ) ; c.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true , NoStore = true , MaxAge = new TimeSpan ( 0 ) , MustRevalidate = true } ; } ) .ConfigurePrimaryHttpMessageHandler ( ( ) = > new HttpClientHandler { AllowAutoRedirect = false , AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip } ) ; clientFactory.CreateClient ( ) ;",adding a handler to all clients created via IHttpClientFactory ? "C_sharp : We are implementing a solution to query a temporal table.When enabling a temporal table on SQL server for any table , SQL will automatically add a second table with extra “ _History ” at the end of the table to track history . For example , if we have a “ student ” table , SQL server will add “ student_History ” table.To query the student history , all that we need is querying student table and add FOR SYSTEM_TIME AS OF '2015-09-01 T10:00:00.7230011 ' ; at the end of the statement.So instead of write : We will write : Is there any way to automatically append this statement at the end of the query ? It is like intercepting the query and applying query filter like a soft table , but now it is not filtered , it is just statement at the end of the statement . Select * from student Select * from student FOR SYSTEM_TIME AS OF '2015-09-01 T10:00:00.7230011 '",Querying Data in a System-Versioned Temporal Table in Entity Framework Core "C_sharp : Let 's say , I have following simplified type : How to express null coalescing operator using CodeDOM to generate C # code , is it possible at all ? Now I 'm using following workaround : Which is equal to model.Result.Value , but not model.Result ? ? 0MBetter workaroundCodeExpression equalent to model.Result.GetValueOrDefault ( 0M ) suitable for nullable value types public class Model { public decimal ? Result { get ; set ; } } new CodePropertyReferenceExpression ( new CodePropertyReferenceExpression ( modelArgument , `` Result '' ) , `` Value '' ) ) new CodeMethodInvokeExpression ( new CodeMethodReferenceExpression ( new CodePropertyReferenceExpression ( modelArgument , `` Result '' ) , `` GetValueOrDefault '' ) , new [ ] { new CodePrimitiveExpression ( 0m ) } ) ) ,",How to express null coalescing operator using CodeDOM ? "C_sharp : I have a Cloud Service running on Azure and i 'm trying to add Umbraco as a VirtualApplication to the WebRole : ServiceDefinition.csdef : It runs perfectly on my local machine on the emulator , however when i deploy the package to the Azure Cloud Service i cant access the Umbraco page , it returns the following error : Stack Trace : I have already tried to add a startup task to no avail : startup.bat : And also to add permissions on the OnStart event of the web role , as instructed here URL.It also did n't work.When i remote desktop directly into the instance , the folder E : \sitesroot\ does n't even exist . ... < Site name= '' Web '' > < VirtualApplication name= '' cms '' physicalDirectory= '' ../../../umbracocms '' / > ... Access to the path ' E : \sitesroot\1\config\applications.config ' is denied.Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : System.UnauthorizedAccessException : Access to the path ' E : \sitesroot\1\config\applications.config ' is denied . [ UnauthorizedAccessException : Access to the path ' E : \sitesroot\1\config\applications.config ' is denied . ] System.IO.__Error.WinIOError ( Int32 errorCode , String maybeFullPath ) +216 System.IO.FileStream.Init ( String path , FileMode mode , FileAccess access , Int32 rights , Boolean useRights , FileShare share , Int32 bufferSize , FileOptions options , SECURITY_ATTRIBUTES secAttrs , String msgPath , Boolean bFromProxy , Boolean useLongPath , Boolean checkHost ) +1430 System.IO.FileStream..ctor ( String path , FileMode mode , FileAccess access , FileShare share , Int32 bufferSize , FileOptions options , String msgPath , Boolean bFromProxy ) +205 System.IO.FileStream..ctor ( String path , FileMode mode , FileAccess access , FileShare share , Int32 bufferSize , Boolean useAsync ) +112 System.Xml.XmlWriterSettings.CreateWriter ( String outputFileName ) +7430688 System.Xml.Linq.XDocument.Save ( String fileName , SaveOptions options ) +189 Umbraco.Core.Services.SectionService.LoadXml ( Action ` 1 callback , Boolean saveAfterCallback ) +253 Umbraco.Core.EnumerableExtensions.ForEach ( IEnumerable ` 1 items , Action ` 1 action ) +148 Umbraco.Core.CoreBootManager.Complete ( Action ` 1 afterComplete ) +116 Umbraco.Web.WebBootManager.Complete ( Action ` 1 afterComplete ) +337 [ HttpException ( 0x80004005 ) : Access to the path ' E : \sitesroot\1\config\applications.config ' is denied . ] System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode ( HttpContext context , HttpApplication app ) +12582201 System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS ( IntPtr appContext , HttpContext context , MethodInfo [ ] handlers ) +175 System.Web.HttpApplication.InitSpecial ( HttpApplicationState state , MethodInfo [ ] handlers , IntPtr appContext , HttpContext context ) +304 System.Web.HttpApplicationFactory.GetSpecialApplicationInstance ( IntPtr appContext , HttpContext context ) +404 System.Web.Hosting.PipelineRuntime.InitializeApplication ( IntPtr appContext ) +475 [ HttpException ( 0x80004005 ) : Access to the path ' E : \sitesroot\1\config\applications.config ' is denied . ] System.Web.HttpRuntime.FirstRequestInit ( HttpContext context ) +12599232 System.Web.HttpRuntime.EnsureFirstRequestInit ( HttpContext context ) +159 System.Web.HttpRuntime.ProcessRequestNotificationPrivate ( IIS7WorkerRequest wr , HttpContext context ) +12438981 < Startup priority= '' 1 '' > < Task commandLine= '' startup.bat '' executionContext= '' elevated '' taskType= '' simple '' / > < /Startup > echo `` starting startup task '' > > log.txt % windir % \system32\Icacls.exe ..\* /T /grant `` Network Service '' : ( F ) > log.txt",Umbraco 7.0.2 on Azure Cloud Service - Access to the path ' E : \sitesroot\1\config\applications.config ' is denied "C_sharp : I like the shortcut in C # of lock ( myLock ) { /* do stuff */ } . Is there an equivalent for read/write locks ? ( Specifically ReaderWriterLockSlim . ) Right now , I use the following custom method , which I think works , but is kind of annoying because I have to pass in my action as an anonymous function , and I would prefer to use a standard locking mechanism if possible . void bool DoWithWriteLock ( ReaderWriterLockSlim RWLock , int TimeOut , Action Fn ) { bool holdingLock = false ; try { if ( RWLock.TryEnterWriteLock ( TimeOut ) ) { holdingLock = true ; Fn ( ) ; } } finally { if ( holdingLock ) { RWLock.ExitWriteLock ( ) ; } } return holdingLock ; }",Is there an equivalent of the lock { } statement for ReaderWriterLockSlim ? "C_sharp : Example code : When button 1 is clicked , the message `` called object [ ] '' is displayed . It seems that the overloaded method with object [ ] parameter is preferred in this example . Any ideas why ? I 'm just curious more than anything . ( Background : this behavior caused some unexpected results in Razor with dynamic viewsFormatting nullable decimal in RazorEngine ) . private void DoSomething ( object obj ) { MessageBox.Show ( `` called object '' ) ; } private void DoSomething ( params object [ ] obj ) { MessageBox.Show ( `` called object [ ] '' ) ; } private void button1_Click ( object sender , EventArgs e ) { decimal ? amount = null ; dynamic obj = amount ; DoSomething ( obj ) ; }",null dynamic variable and function overloading "C_sharp : Assuming that I have Base and Child1 , Child2 , Child3 classes , I have the following code : Note that at the commented line I do n't need these child2 , child3 variables since it does n't matter what type it has , if it is not child1.Resharper suggests me that unused variable can be safely removed . Here comes the interesting part . I can not do that : since it results into `` class name is not valid at this point '' syntax error.This usage seems the most appropriate for me . I can not do that : since it results into `` conflicting variable '' error . By the way , this statement would make sense if ProcessAnyOther method accepted more precise type ( base for Child2 and Child3 ) and I called it with nevermind argument instead of b . However , I can do that : And it does not even create `` _ '' variable . That 's exactly what Resharper suggests to do . My question is : what is this ? Where else can it be used ? How is this `` _ '' operator or language part called ? Is it a part of C # language specification ? Base b ; // value is acquiredswitch ( b ) { case Child1 child1 : ProcessChild1 ( child1 ) ; break ; case Child2 child2 : case Child3 child3 : ProcessAnyOther ( b ) ; // < -- break ; default : throw new ArgumentOutOfRangeException ( nameof ( b ) ) ; } case Child2 : case Child3 : case Child2 nevermind : case Child3 nevermind : case Child2 _ : case Child3 _ :",C # 7.0 type pattern matching usage without variable C_sharp : Several times I 've seen ReSharper generate code that looks like this : Does the ' @ ' in @ delegate give that variable any special semantic meaning ? Or is it just a convention I did n't encounter before ? delegate void myHandler ( int i ) ; myHandler myHandlerContainer ; ... foreach ( Delegate @ delegate in myHandlerContainer.GetInvocationList ( ) ) { ... },Does the @ prefix for delegates have any special meaning ? "C_sharp : Preface : In my application , I store raw WAV data in the database as byte [ ] . In my domain model there is a class PcmAudioStream that represents that raw WAV data . I created an implementation of NHibernate 's IUserType to convert between my class and byte [ ] .There are several classes that use the PcmAudioStream class , all of which are mapped to database tables . To avoid always loading all WAV data when retrieving a row from such a table , I created an implementation of Fluent NHibernate 's IUserTypeConvention that specifies that those properties should always be lazy loaded.All of this works like a charm.Question : Because the content of these PcmAudioStreams rarely ever changes , I want to put retrieved instances in the second level cache . Now , I know how to activate the second level cache for a complete class , but how do I achieve this only for a lazy loaded property ? The relevant part of my domain model looks like this : The mapping is simple ( note : that is not my mapping , I am using a convention , but it is equivalent ) : public class User : Entity { public virtual string FirstName { get ; set ; } public virtual string LastName { get ; set ; } public virtual PcmAudioStream FullNameRecording { get ; set ; } // ... } public class UserMap : ClassMap < User > { public UserMap ( ) { Id ( x = > x.Id ) ; Map ( x = > x.FirstName ) ; Map ( x = > x.LastName ) ; Map ( x = > x.FullNameRecording ) .CustomType < PcmAudioStreamAsByteArray > ( ) ; } }",How to activate the second level cache on a lazy loaded property with own user type ? "C_sharp : I am unit testing an ICustomerRepository interface used for retrieving objects of type Customer.As a unit test what value am I gaining by testing the ICustomerRepository in this manner ? Under what conditions would the below test fail ? For tests of this nature is it advisable to do tests that I know should fail ? i.e . look for id 4 when I know I 've only placed 5 in the repositoryI am probably missing something obvious but it seems the integration tests of the class that implements ICustomerRepository will be of more value.Test Base ClassICustomerRepository and IRepository [ TestClass ] public class CustomerTests : TestClassBase { private Customer SetUpCustomerForRepository ( ) { return new Customer ( ) { CustId = 5 , DifId = `` 55 '' , CustLookupName = `` The Dude '' , LoginList = new [ ] { new Login { LoginCustId = 5 , LoginName = `` tdude '' } , new Login { LoginCustId = 5 , LoginName = `` tdude2 '' } } } ; } [ TestMethod ] public void CanGetCustomerById ( ) { // arrange var customer = SetUpCustomerForRepository ( ) ; var repository = Stub < ICustomerRepository > ( ) ; // act repository.Stub ( rep = > rep.GetById ( 5 ) ) .Return ( customer ) ; // assert Assert.AreEqual ( customer , repository.GetById ( 5 ) ) ; } } public class TestClassBase { protected T Stub < T > ( ) where T : class { return MockRepository.GenerateStub < T > ( ) ; } } public interface ICustomerRepository : IRepository < Customer > { IList < Customer > FindCustomers ( string q ) ; Customer GetCustomerByDifID ( string difId ) ; Customer GetCustomerByLogin ( string loginName ) ; } public interface IRepository < T > { void Save ( T entity ) ; void Save ( List < T > entity ) ; bool Save ( T entity , out string message ) ; void Delete ( T entity ) ; T GetById ( int id ) ; ICollection < T > FindAll ( ) ; }",What is the purpose of unit testing an interface repository "C_sharp : Let 's say I have an object MyCharacter of the class Character , which has the following properties : Health , Mana , MoveSpeed . From a different method I get a string that contains these stats as follows : '' Health : 100 Mana : 100 MoveSpeed : 100 '' I now want to assign these stats to my object . My current attempt is this : The thing now is , that I know the order of the stats . It 's always Health , then Mana , then MoveSpeed . So I am looking for a way to simplify it , namely getting rid of this switch ( since the actual Character here has 18 stats and it 's not exactly good looking as it is ) . My idea would be going through the array and tell the program to assign the first number it finds to Health , the second to Mana and the third to MoveSpeed.Is anything like that even possible ? // stats is the string I showed abovevar statsArray = stats.Split ( ' ' ) ; for ( var i = 0 ; i < statsArray.Length ; i++ ) { switch ( statsArray [ i ] ) { default : break ; case `` Health : '' : MyCharacter.Health = statsArray [ i+1 ] ; break ; case `` Mana : '' : MyCharacter.Mana = statsArray [ i+1 ] ; break ; case `` MoveSpeed : '' : MyCharacter.MoveSpeed = statsArray [ i+1 ] ; break ; } }",Assign values to object in for loop "C_sharp : I 've designed a simple card game where two cards are displayed and the user has to bet on whether they will get a card that is in between the two cards displayed . If the user does n't want to bet , they just deal again . The user begins with £100.The game works fine in most aspects , but has a huge flaw . The user can bet more than they have in their balance . So , if the user has £100 , they bet £105 , and they win , they will have £205 in their balance . This is clearly bad ! And if they have £100 , they bet £105 and they lose , their balance stays the same . This is also pretty bad.So I thought a simple if-statement would sort this out : Why does n't this work ? I 'm pretty sure it 's something so simple , but I 'm pretty new to C # , so go easy on me ! if ( wager > balance ) { winLoseLabel.Text = `` You ca n't bet more than you have ! `` ; } switch ( betResult ) { case TIE : winloseLabel.Text = `` Tie . You still lose . HA ! `` ; myRules.Balance -= wager ; break ; case PLAYERWINS : winloseLabel.Text = `` You win . Woop-de-do.. '' ; myRules.Balance += wager ; break ; case DEALERWINS : winloseLabel.Text = `` You lose . Get over it . `` ; myRules.Balance -= wager ; break ; }",Why wo n't my simple if statement work ? "C_sharp : I was playing with unsafe code for a problem on Code Golf , and I found something I ca n't explain . This code : Crashes with an access violation ( Segfault ) , but this code : Throws a NullReferenceException . It appears to me that the first is performing a read and the second is performing a write . An exception tells me that something , somewhere in the CLR is intercepting the write and stopping it before the OS kills the process . Why does this happen on the write , but not on the read ? It does segfault on a write if I make the pointer value sufficiently large . Does that mean there is a block of memory that the CLR knows is reserved and will not even attempt to write to ? Why then , does it allow me to try and read from that block ? Am I completely misunderstanding something here ? Edit : Interestingly enough : System.Runtime.InteropServices.Marshal.WriteInt32 ( IntPtr.Zero , 0 ) ; Gives me an access violation , not a NullReference . unsafe { int i = * ( int* ) 0 ; } unsafe { * ( int* ) 0=0 ; }",Why does this unsafe code throw a NullReferenceException ? "C_sharp : I have an object with a property implemented like After changing the implementation to something like on deserialzation , this Property comes up empty.i have lots of serialized data from the old implementation , and would like to load them with the new implementationis there any way , to change the implentation to be compatible with older binary files ? EDIT : Some people might run into the same problem , so here 's my hackish solution : the autogenerated fields have a naming convention that is non-valid c # code : the quick and dirty fix for me was to create a private backing field called xMyFieldxK__BackingField in the source , and patching the serialized binarydata by replacing all occurences of < MyField > with xMyFieldx before deserialisation public String Bla { get ; set ; } private String _bla ; public String Bla { get { return _bla ; } set { _bla = value ; } } [ CompilerGenerated ] private string < MyField > k__BackingField ; [ CompilerGenerated ] public void set_MyField ( string value ) { this. < MyField > k__BackingField = value ; } [ CompilerGenerated ] public string get_MyField ( ) { return this. < MyField > k__BackingField ; }",Change auto implemented properties to normal and deserialization with BinaryFormatter "C_sharp : We 're using Dapper and EF in our shop , and Dapper proofed to be extremely helpful in debugging queries in SQL server when something went wrong . Instead of just submitting raw SQL , we created a thin decorator that also adds some context information ( the origin ) as an SQL comment , something likeThis allows our DBAs and developers to reacy very quickly and find the source of a problem if we have DB calls that are erroneous , or introduce performance hits ( we have hundreds of thousands of DB calls per day , so one bad query can cause quite some damage ) .We would also like to do this with EF . It does n't have to be an SQL comment , but some kind of hook in order to supply meta information that is submitted with the call . Any idea whether this is possible ? Thanks for your advicePhilipp /* Foo.Bar.GetOrders ( ) */ SELECT * FROM Order WHERE orderId > 123",Inject debug information into Entity Framework queries "C_sharp : I have a WPF Desktop application using Prism 4 , in my bootstrapper i have the following code : the above code is telling prism to load all the .dlls from `` [ my app root ] \Modules '' path and check them to see if any class has implemented IModule . What I want to do is to limit the loading process to only DLLs which have been signed with a specific sign key so that prevent any developer to inject it 's module in my application . please advice if I 'm following the wrong path for such issue . protected override IModuleCatalog CreateModuleCatalog ( ) { var filepath = Assembly.GetExecutingAssembly ( ) .Location ; var path = Path.GetDirectoryName ( filepath ) ; System.IO.Directory.SetCurrentDirectory ( path ) ; path = Path.Combine ( path , `` Modules '' ) ; var moduleCatalog = new DirectoryModuleCatalog ( ) { ModulePath = path } ; return moduleCatalog ; }",How to limit prism 4 to load only special signed modules ? "C_sharp : I am trying to create a list of tuples with properties and conditions for their validation . So I had this idea in mind : How can I pass expression of type ( FirstName == null ) as Func ? List < Tuple < string , string , Func < bool > > > properties = new List < Tuple < string , string , Func < bool > > > { Tuple.Create ( FirstName , `` User first name is required '' , ? ? ? ) , } ; ...","Passing a condition into Func < bool > of a Tuple < string , string , Func < bool > >" "C_sharp : I use C # language and I have a little question about List < Tuple < int , int > > . Assume that I created a List < Tuple < int , int > > and then inserted some entry to it like : ( 12,3 ) , ( 154,43 ) , ( 85,342 ) Now I want to search the List JUST by first item , i.e . just by item1 and I want to do this by binary search.something like this : and some output like this:12 32Now is there any solution ? List < Tuple < int , int > > tt = new List < Tuple < int , int > > ( ) ; tt.Add ( new Tuple < int , int > ( 12,32 ) ) ; tt.sort ( ) ; tt.binarysearch ( item1:12 ) ;","Binary search on List < Tuple < int , int > > in c #" "C_sharp : I 'm trying to implement authorization through Last.fm . I 'm submitting my arguments as a Dictionary to make the signing easier . This is the code I 'm using to sign my calls : I 've checked the output in the debugger , it 's exactly how it should be , however , I 'm still getting WebExceptions every time I try , meaning the API is returning `` Invalid Method Signature '' . This means it 's not accepting the signature SignCall is generating.Here 's my code I use to generate the URL in case it 'll help : And sample usage to get a SessionKey : EDIT : Oh , and the code references an MD5 function implemented like this : Also , here 's the API documentation : API - Last.fm , with this page detailing authorization . public static string SignCall ( Dictionary < string , string > args ) { IOrderedEnumerable < KeyValuePair < string , string > > sortedArgs = args.OrderBy ( arg = > arg.Key ) ; string signature = sortedArgs.Select ( pair = > pair.Key + pair.Value ) . Aggregate ( ( first , second ) = > first + second ) ; return MD5 ( signature + SecretKey ) ; } public static string GetSignedURI ( Dictionary < string , string > args , bool get ) { var stringBuilder = new StringBuilder ( ) ; if ( get ) stringBuilder.Append ( `` http : //ws.audioscrobbler.com/2.0/ ? `` ) ; foreach ( var kvp in args ) stringBuilder.AppendFormat ( `` { 0 } = { 1 } & '' , kvp.Key , kvp.Value ) ; stringBuilder.Append ( `` api_sig= '' +SignCall ( args ) ) ; return stringBuilder.ToString ( ) ; } var args = new Dictionary < string , string > { { `` method '' , `` auth.getSession '' } , { `` api_key '' , ApiKey } , { `` token '' , token } } ; string url = GetSignedURI ( args , true ) ; public static string MD5 ( string toHash ) { byte [ ] textBytes = Encoding.UTF8.GetBytes ( toHash ) ; var cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider ( ) ; byte [ ] hash = cryptHandler.ComputeHash ( textBytes ) ; return hash.Aggregate ( `` '' , ( current , a ) = > current + a.ToString ( `` x2 '' ) ) ; }",How do I sign requests reliably for the Last.fm api ? "C_sharp : I am trying to connect to my remote MySQL server , using the following code . Can you tell me what I am doing wrong as the replacement of database connection info with variables does n't seem to be working.As a PHP developer , I prefer to use the code above instead of the deliberate casting below : But as you can see in this image , I am getting a lot of red squiggles : http : //screencast.com/t/xlwoG9by using MySql.Data.MySqlClient ; string db_Server = `` 10.0.0.0 '' ; string db_Name = `` myDatabase '' ; string db_User = `` myUser '' ; string db_Pass = `` myPassword '' ; // Connection String MySqlConnection myConnection = new MySqlConnection ( `` server = { 0 } ; database = { 1 } ; uid = { 2 } ; pwd = { 3 } '' , db_server , db_Name , db_User , db_Pass ) ; MySqlConnection myConnection = new MySqlConnection ( `` server=10.0.0.0 ; database=myDatabase ; uid=myUser ; pwd=myPassword '' ) ;",What is wrong with this Database connection string ? C_sharp : After updating Windows 10 to creators update with .net 4.7 I have a critical issue on starting very simple code.Description : The process was terminated due to an unhandled exception.Exception Info : System.AccessViolationExceptionSeems the similar issue is https : //github.com/dotnet/coreclr/issues/10826Anyone knows how to avoid that ? class Program { private int ? m_bool ; private bool prop { get { return false ; } } void test ( ) { //nothing } private object Test ( ) { if ( prop ) { try { test ( ) ; } catch ( Exception ) { } m_bool = 1 ; } return null ; } static void Main ( string [ ] args ) { new Program ( ) .Test ( ) ; } },Windows 10 Creators update .net 4.7 System.AccessViolationException issue "C_sharp : My UWP app stores data in encrypted form in local SQLite database on the device . I use Windows.Security.Cryptography.DataProtection classes for static data and also data streams encryption/decryption ( Ref : https : //docs.microsoft.com/en-us/windows/uwp/security/cryptography ) I have provided OneDrive data backup facility with the idea that the user can backup entire database to OneDrive from one device and restore it in the app installed on another device . This may help the user use the app on multiple devices and also in case the user acquires a new device.I use `` LOCAL=user '' Descriptor for the DataProtectionProvider class ( Ref : https : //docs.microsoft.com/en-us/uwp/api/windows.security.cryptography.dataprotection.dataprotectionprovider ) I was hoping that if I login using my Microsoft Account on two different devices and I encrypt data on one device , then restore data on other then the data should get decrypted ; however this is not happening.I was unable to get any documentation as well ( apart from the references listed above ) . I searched SO as well for MS Support but no luck . Can somebody help me with this ? My requirement : Data encrypted on one ( Windows ) device should be decrypted in other ( Windows ) device ( when a user is logged in using same Microsoft Account on both the devices ) . [ UPDATE ] Here 's the code sample : The code is trivial ; however , the process of error reproduction is important and is as follows : I run the App on my Windows 10 Mobile ( OS build : 10.0.14393.1770 ) then Backup data on OneDrive . My mobile shows that I am using a Microsoft Account ( say NP3 @ msft.com ) at Settings -- > Accounts -- > Your Info.Now , I log-in to my Windows 10 Laptop ( OS build : 15063.674 version : 1703 with Fall Creators Update SDK only applied ) using NP3 @ msft.com account when I run the App and Restore the Backup from OneDrive.Now , when I try to access the data , I get the error in IBuffer buffUnprotected = await Provider.UnprotectAsync ( buffProtected ) ; line of the UnprotectTextAsync method . The error is : Please note that if I restore data backed-up on OneDrive from the same device ( Mobile or Laptop ) , then this code works fine . So Backup/Restore functionality is working correctly with no data modification . const BinaryStringEncoding encoding = BinaryStringEncoding.Utf8 ; const string strDescriptor = `` LOCAL=user '' ; public static async Task < string > ProtectTextAsync ( string strClearText ) { DataProtectionProvider Provider = new DataProtectionProvider ( strDescriptor ) ; IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary ( strClearText , encoding ) ; IBuffer buffProtected = await Provider.ProtectAsync ( buffMsg ) ; return CryptographicBuffer.EncodeToBase64String ( buffProtected ) ; } public static async Task < String > UnprotectTextAsync ( string strProtected ) { DataProtectionProvider Provider = new DataProtectionProvider ( ) ; IBuffer buffProtected = CryptographicBuffer.DecodeFromBase64String ( strProtected ) ; IBuffer buffUnprotected = await Provider.UnprotectAsync ( buffProtected ) ; String strClearText = CryptographicBuffer.ConvertBinaryToString ( encoding , buffUnprotected ) ; return strClearText ; } System.Exception : 'The specified data could not be decrypted . ( Excep_FromHResult 0x8009002C ) '",UWP - Cross Device Data Encryption "C_sharp : I 'm trying to get all the computer names which are in the active directory `` Standard '' group . The AD tree looks like this : I tried to get the computers using `` memberOf '' attribute ( I found the attributes on this page : http : //www.kouti.com/tables/userattributes.htm ) . So I have this code : After debugging this code because it did n't show any message boxes I found out that the `` memberOf '' attribute returns some strange strings . I used MessageBox.Show ( entry.Properties [ `` memberOf '' ] .Value.ToString ( ) ) ; to get the value of `` memberOf '' attribute . This is what I get : There are much more MsgBoxes but every box is like this.After looking in our active directory I could n't figure out the order the entries gets displayed . And I noticed that nothing like `` Computer '' ( see the image ) shows up.Conclusion : I just want to get the computers in bbad.lan > Computer > Standard but the results of my code confuse me so I 'm quite perplexed now.Suggestion appreciated : ) using ( var context = new PrincipalContext ( ContextType.Domain , `` bbad.lan '' ) ) { using ( var searcher = new PrincipalSearcher ( new UserPrincipal ( context ) ) ) { foreach ( var result in searcher.FindAll ( ) ) { DirectoryEntry entry = result.GetUnderlyingObject ( ) as DirectoryEntry ; if ( entry.Properties [ `` memberOf '' ] .Value == `` Computer '' ) { MessageBox.Show ( `` aaa : `` + entry.Properties [ `` Name '' ] .Value.ToString ( ) ) ; } } } } 1 . MsgBox : CN=Gäste , CN=Builtin , DC=bbad , DC=lan2 . MsgBox : System.Object [ ] etc .",Get active directory computers of specific group using `` memberOf '' attribute using C # "C_sharp : I am using RazorPages in ASP.NET Core v2.0 , and I was wondering if anyone knows how to force the AnchorTagHelper to use lowercase ? For example , in my .cshtml mark-up , I would have the following anchor tag using the asp-page tag helper : The output that I am looking forTo give it more context to why this is important to my web app , please imagine a long url like what you would see at stackoverflow.comAny help would be appreciated ! I have looked at these other references but no luck : https : //github.com/aspnet/Mvc/issues/6393How do you enforce lowercase routing in ASP.NET Core MVC 6 ? < a asp-page= '' /contact-us '' > Contact Us < /a > // i want this < a href= '' /contact-us '' > Contact Us < /a > // i get this < a href= '' /Contact-us '' > Contact Us < /a > https : //stackoverflow.com/questions/anchortaghelper-asp-page-to-use-lowercase -- VS -- https : //stackoverflow.com/Questions/Anchortaghelper-asp-page-to-use-lowercase",ASP.NET Core RazorPages to force AnchorTagHelper ( asp-page ) to use lowercase routes "C_sharp : I have a Windows Phone 7 application that has been published to the marketplace . I 'm using Sql CE with LinqToSql . When the app runs , it checks for the existence of a database from a connection string , and creates if it does n't exist.As I begin to plan new features , I foresee some changes to the database schema , whether it be adding a new column to an existing table , adding new tables , etc.How does one go about updating the already existing database ? Do I have to manually execute ALTER and CREATE table statements for my adjustments now that the database already exists ? using ( CheckbookDataContext db = new CheckbookDataContext ( DBConnectionString ) ) { if ( ! db.DatabaseExists ( ) ) { isNewLoad = true ; db.CreateDatabase ( ) ; } }",Update LinqtoSql database with new schema changes ? C_sharp : I am confused as to how to implement the following in my current foreach : so that post.Username will NOT show if @ post.anon is TRUE ( and so that it will say `` Anonymous '' ) Thanks in advance for any advice/help/suggestions . @ foreach ( var post in Model . `` table '' .Where ( w = > w.Private_ID == 1 ) .OrderBy ( o = > o.Date ) ) { < div class = '' post '' > < fieldset > < p class= '' post_details '' > At @ post.Post_Date By @ post.Username < /p > @ post.Post_Desc < /fieldset > < /div > },ASP.NET MVC3 C # - foreach "C_sharp : Let 's say I have the following list : Which has the following entries : SomeObject.FieldI would like to sort this list so that FruitBowl entries go at the bottom , and that subject to this , everything is alphabetic.In order words : SomeObject.Field var someList = new List < SomeObject > ( ) ; AppleOrangeFruitBowl_OutsideBananaGrapeFruitBowl_Inside AppleBananaGrapeOrangeFruitBowl_InsideFruitBowl_Outside",C # order list by two different things C_sharp : All the code examples always use base ( ) as followse.g . http : //msdn.microsoft.com/en-us/library/hfw7t1ce % 28v=vs.71 % 29.aspxwhereas as i discovered recentlyalso prints AQ - is it a new `` feature '' or is it bad form not to call base ( ) in derived class constructors and will add to my bad karma and cause problems later ? orcan calling base ( ) safely be ignored ? class A { public A ( ) { Console.Writeline ( `` A '' ) ; } } class B : A { public B ( ) : base ( ) { } } class A { public A ( ) { Console.Writeline ( `` A '' ) ; } } class B : A { public B ( ) { } },Is explicitly calling base ( ) in derived constructors optional ? "C_sharp : So , this is kind of an obtuse question , but let me see if I can lay it out relatively simply . Lets say I have the following interface : Which I then implement with : Only Entity Framework ca n't work with interfaces , so it pretty much completely ignores this navigation property . In order to get EF to recognize it , I need to change it to : Where Bar would be my implementation of IBar . Only , that fails to implement the interface , which wants IBar not Bar.Now , consider a slightly different scenario , where I 've just got a basic foreign key : Same issue , but here , I can solve it by adding : EF is happy because it has a concrete type and the interface is happy because it has an implementation with IBar . The problem is that I ca n't figure out how to apply the same logic with an ICollection < IBar > because ( ICollection < Bar > ) value raises an exception saying `` Can not implicitly convert type ICollection < Bar > to ICollection < IBar > '' .How should I properly make the cast ? UPDATESo , I was n't paying close enough attention to where the error was being generated . It was actually complaining about the get { return Bars ; } bit . I was able to get rid of the error by changing it to : That seems a little hokey to me though , like I 'm only masking the error and creating a little time bomb for myself . I 'd appreciate any thoughts or alternate solutions . public interface IFoo { ICollection < IBar > Bars { get ; set ; } } public class Foo : IFoo { public virtual ICollection < IBar > Bars { get ; set ; } } public virtual ICollection < Bar > Bars { get ; set ; } public interface IFoo { IBar Bar { get ; set ; } } public class Foo : IFoo { public virtual IBar Bar { get ; set ; } } public class Foo : IFoo { public virtual Bar Bar { get ; set ; } IBar IFoo.Bar { get { return Bar ; } set { Bar = ( Bar ) value ; } } } public class Foo : IFoo { public virtual ICollection < Bar > Bars { get ; set ; } ICollection < IBar > IFoo.Bars { get { return ( ICollection < IBar > ) Enumeration.Cast < IBar > ( Bars ) ; } set { Bars = ( ICollection < Bar > ) value ; } } }",Implementing an ICollection < ISomething > with a concrete type to satisfy Entity Framework "C_sharp : I have the following code . In the documentation I state that min and max must be on the [ 1-5 ] range , and max has to be greater or equal to min . Is the third Exception correctly constructed ? If not , how should I construct the Exception ? DoSomething ( int min , int max ) { if ( min < 1 || min > 5 ) throw new ArgumentOutOfRangeException ( `` min '' ) ; if ( max < 1 || max > 5 ) throw new ArgumentOutOfRangeException ( `` max '' ) ; if ( min > max ) throw new ArgumentOutOfRangeException ( `` min & max '' ) ; DoSomethingWithYourLife ( ) ; // = ) }",How to use ArgumentOutOfRangeException with multiple params ? "C_sharp : So my company comes from a completely C # .Net environment , so naturally we are looking at Mono for mobile development . We have a very extensive windows platform library which I was able to port most of it as an Android Class Library . The idea being that this Android Class Library will be our mobile platform library which can be reused in the future for MonoTouch ( Have n't tested , but read that MonoTouch project can reference Android Class Libraries as long as there is no Android specific code ) . Within the library though , there are plenty of logging statements , which for the windows environment just end up being trace statements ( wrapped in a custom helper class ) . We want to retain the logging statements and based on the current environment ( iOS or Android ) , just translate those into native logging.I was planning to use partial declarations for the logging in the mobile platform library and have the Android and iOS specific libraries contain the implementations for those partial logging methods . But that fell apart when I realized partials do not work between assemblies.So now I am not sure how to go about this . The only thing I can think of if having two separate iOS and Android platform libraries and linking the same files . ( Xamarin might have a logging class that does this but we still need to come up with a pattern for any other future abstractions ) Any advice is appreciated . We are still in the experimental/planning phase so there is a chance we might be overlooking something , please let us know if that is the case.Thanks.EditLets say I have the following simple static class.And I have hundreds of calls to this method within the mobile platform library . Now lets say I reference this library in my Android application , is there any way to override the implementation of TraceHelper.WriteLine ( ) without modifying the library itself ? UpdateWe ended up creating Android and iOS libraries that implemented the missing .NET functionality . Just wrap the native equivalent functionality , in the same .NET namespace and class . EX : public static class TraceHelper { public static void WriteLine ( string message ) { // Validation and preprocessing Trace.WriteLine ( message ) ; } } using Android.Util ; namespace System.Diagnostics { public static class Trace { # region Non-Public Data Members private const string Tag = `` Trace '' ; # endregion public static void WriteLine ( string message ) { Log.WriteLine ( LogPriority.Verbose , Tag , message ) ; } } }",Shared library for MonoDroid and MonoTouch "C_sharp : I have created a .net core class library package and uploaded it to nuget.orgIn the dependencies section is says that my project depends on .NetStandard 1.4 , that is NetStandard.Library higher than 1.6Why is there such a confuse mismatch in the version number ? Are n't .NetStandard and NetStandard.Library supposed to be the same thing ? Or are they different things ? here is my .csprojand the link to my project : https : //www.nuget.org/packages/currency/ < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < TargetFramework > netstandard1.4 < /TargetFramework > < PackageVersion > 2.0.1 < /PackageVersion > < AssemblyName > currency < /AssemblyName > < /PropertyGroup > < /Project >",why .netstandard 1.4 is NetStandard.Library 1.6 ? "C_sharp : Why does Visual Studio warn about this when using is on value types , but does n't when on reference types ? Lines 1 and 2 raise the warning , while lines 3 and 4 do n't . if ( 5 is object ) if ( new Point ( ) is object ) if ( `` 12345 '' is object ) if ( new StringBuilder ( ) is object )",The given expression is always of the provided type "C_sharp : I have producer / consumer pattern in my app implemented used TPL Dataflow . I have the big dataflow mesh with about 40 blocks in it . There are two main functional parts in the mesh : producer part and consumer part . Producer supposed to continuosly provide a lot of work for consumer while consumer handling incoming work slowly sometimes . I want to pause producer when consumer is busy with some specified amount of work items . Otherwise the app consumes a lot of memory / CPU and behaves unsustainable.I made demo app that demonstrates the issue : The app prints something like this : That means the producer keeps spinning and pushing messages to consumer . I want it to pause and wait until the consumer have finished current portion of work and then the producer should continue providing messages for consumer.My question is quote similar to other question but it was n't answered properly . I tried that solution and it does n't work here allowing producer to flood the consumer with messages . Also setting BoundedCapacity does n't work too.The only solution I guess so far is make my own block that will monitor target block queue and acts according to target block 's queue . But I hope it is kind of overkill for this issue . using System ; using System.Linq ; using System.Threading.Tasks ; using System.Threading.Tasks.Dataflow ; namespace DataflowTest { class Program { static void Main ( string [ ] args ) { var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 , EnsureOrdered = false } ; var boundedOptions = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 4 , EnsureOrdered = false , BoundedCapacity = 5 } ; var bufferBlock = new BufferBlock < int > ( boundedOptions ) ; var producerBlock = new TransformBlock < int , int > ( x = > x + 1 , options ) ; var broadcastBlock = new BroadcastBlock < int > ( x = > x , options ) ; var consumerBlock = new ActionBlock < int > ( async x = > { var delay = 1000 ; if ( x > 10 ) delay = 5000 ; await Task.Delay ( delay ) ; Console.WriteLine ( x ) ; } , boundedOptions ) ; producerBlock.LinkTo ( bufferBlock ) ; bufferBlock.LinkTo ( broadcastBlock ) ; broadcastBlock.LinkTo ( producerBlock ) ; broadcastBlock.LinkTo ( consumerBlock ) ; bufferBlock.Post ( 1 ) ; consumerBlock.Completion.Wait ( ) ; } } } 2134569055690536905469057438028438040142303438079",How to make fast producer paused when consumer is overwhelmed ? "C_sharp : I thought that `` bill '' + `` john '' + null == billjohn , but in this example of mine it seems to be evaluating to null : Am I missing something obvious here ? var clients = from client in taxPortalService.Client ( ) select new ClientViewModel { ResidentialAddressLine1 = client.RESADDRESSLINE1 , ResidentialAddressLine2 = client.RESADDRESSLINE2 , ResidentialAddressLine3 = client.RESADDRESSLINE3 , ResidentialAddressLine4 = client.RESADDRESSLINE4 , ResidentialPostalCode = client.RESPOSTCODE , ResidentialCountry = client.RESCOUNTRY , IAResidentialAddress = client.RESADDRESSLINE1 + `` , `` + client.RESADDRESSLINE2 + `` , `` + client.RESADDRESSLINE3 + `` , `` + client.RESADDRESSLINE4 + `` , `` + client.RESPOSTCODE + `` , `` + client.RESCOUNTRY } ;",Linq why does concatenating strings result in a null ? "C_sharp : I am executing the async Task in my window : The window is launched in separate thread : When the windows is closed , the thread is of course finished , which is just fine.Now - if that happens before the FetchData is finished , I get the memory leak.Appears that FetchData remains awaited forever and the Task.s_currentActiveTasks static field is retaining my window instance forever : Retention path System.Collections.Generic.Dictionary.entries - > System.Collections.Generic.Dictionary+Entry [ 37 ] at [ 17 ] .value - > System.Threading.Tasks.Task.m_continuationObject - > System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.m_action - > System.Action._target - > System.Runtime.CompilerServices.AsyncMethodBuilderCore+ContinuationWrapper.m_continuation - > System.Action._target - > System.Runtime.CompilerServices.AsyncMethodBuilderCore+ContinuationWrapper.m_continuation - > System.Action._target - > ... If I understand this correctly , if/when the FetchData completes , the continuation should continue on the window instance target and a thread , but that never happens since the thread is finished.Is there any solutions to this , how to avoid memory leak in this case ? private async Task LoadData ( ) { // Fetch data var data = await FetchData ( ) ; // Display data // ... } // Create and run new threadvar thread = new Thread ( ThreadMain ) ; thread.SetApartmentState ( ApartmentState.STA ) ; thread.IsBackground = true ; thread.CurrentCulture = Thread.CurrentThread.CurrentCulture ; thread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture ; thread.Start ( ) ; private static void ThreadMain ( ) { // Set synchronization context var dispatcher = Dispatcher.CurrentDispatcher ; SynchronizationContext.SetSynchronizationContext ( new DispatcherSynchronizationContext ( dispatcher ) ) ; // Show window var window = new MyWindow ( ) ; window.ShowDialog ( ) ; // Shutdown dispatcher.InvokeShutdown ( ) ; }",Task await and thread terminate are causing memory leak "C_sharp : This post is completely edited to provide a more solid example and simplified ask I 'm looking to have the results from Child changes be reflected in the Parent , particularly the field NumberOfChildrenWithDegrees . If you check both boxes with bindings of HasUniversityDegree and HasHighSchoolDegree then HasTwoDegrees in the Child View updates . What I would like is the number of Children with HasTwoDegrees be reflected in the Parent VM.I thought this would just be simple , but it turns out that it does n't work - checking two boxes changes nothing in the Parent View ( the < TextBlock Text= '' { Binding NumberOfChildrenWithDegrees , Mode=TwoWay , UpdateSourceTrigger=Explicit } '' / > area . How can I get this number change to happen real time ? I 've created a small sample for Windows Phone that can be plugged directly into a page called TestPage . Just place the XAML in the content grid and the code in the code-behind ( VB ) .XAML : Code-behind : < Grid x : Name= '' ContentPanel '' Background= '' { StaticResource PhoneChromeBrush } '' Grid.Row= '' 1 '' > < ListBox x : Name= '' parentLB '' Margin= '' 12,12,12,12 '' HorizontalContentAlignment= '' Stretch '' > < ListBox.ItemTemplate > < DataTemplate > < StackPanel Orientation= '' Vertical '' Margin= '' 0,12,0,0 '' > < StackPanel Orientation= '' Horizontal '' > < TextBlock Text= '' Parent Name : `` / > < TextBlock Text= '' { Binding Name } '' / > < /StackPanel > < StackPanel Orientation= '' Horizontal '' > < TextBlock Text= '' Number of Children with Degrees : `` / > < TextBlock Text= '' { Binding NumberOfChildrenWithDegrees , Mode=TwoWay , UpdateSourceTrigger=Explicit } '' / > < /StackPanel > < ListBox Margin= '' 12,0,0,0 '' x : Name= '' group2 '' ItemsSource= '' { Binding Children , Mode=TwoWay } '' > < ListBox.ItemTemplate > < DataTemplate > < StackPanel > < StackPanel Orientation= '' Horizontal '' > < TextBlock Text= '' Child Name : `` / > < TextBlock Text= '' { Binding Name } '' / > < /StackPanel > < CheckBox Content= '' Has High School Degree : '' IsChecked= '' { Binding HasHighSchoolDegree , Mode=TwoWay } '' / > < CheckBox Content= '' Has University Degree : `` IsChecked= '' { Binding HasUniversityDegree , Mode=TwoWay } '' / > < CheckBox Content= '' Has Two Degrees ? `` IsEnabled= '' False '' IsChecked= '' { Binding HasTwoDegrees } '' / > < /StackPanel > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > < /StackPanel > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > < /Grid > Imports System.Collections.ObjectModelImports System.ComponentModelPartial Public Class TestPage Inherits PhoneApplicationPage Public Sub New ( ) InitializeComponent ( ) parentLB.ItemsSource = Grandparent1.ParentGroups End Sub Public Function Grandparent1 ( ) As GrandParent Dim ParentGroups As New List ( Of Parent ) ParentGroups.Add ( Parent1 ) ParentGroups.Add ( Parent2 ) Dim gp As New GrandParent gp.ParentGroups = ParentGroups Return gp End Function Public Function Parent2 ( ) As Parent Dim p As New Parent With { .Name = `` Tom '' } Dim c1 As New Child With { .Name = `` Tammy '' } Dim c2 As New Child With { .Name = `` Timmy '' } Dim children As New List ( Of Child ) children.Add ( c1 ) children.Add ( c2 ) p.Children = children Return p End Function Public Function Parent1 ( ) As Parent Dim p As New Parent With { .Name = `` Carol '' } Dim c1 As New Child With { .Name = `` Carl '' } c1.HasHighSchoolDegree = True c1.HasUniversityDegree = True Dim c2 As New Child With { .Name = `` Karla '' } Dim children As New List ( Of Child ) children.Add ( c1 ) children.Add ( c2 ) p.Children = children Return p End FunctionEnd ClassPublic Class GrandParent Inherits BindableBase Public Property ParentGroups As List ( Of Parent ) End ClassPublic Class Parent Inherits BindableBase Public Property Name As String Private _children As List ( Of Child ) Public Property Children As List ( Of Child ) Get Return Me._children End Get Set ( value As List ( Of Child ) ) Me.SetProperty ( Me._children , value ) End Set End Property Private _numberOfChildrenWithDegrees As Integer Public Property NumberOfChildrenWithDegrees As Integer Get Return Children.Where ( Function ( f ) f.HasTwoDegrees ) .Count End Get Set ( value As Integer ) Me.SetProperty ( Me._numberOfChildrenWithDegrees , value ) End Set End PropertyEnd ClassPublic Class Child Inherits BindableBase Public Property Name As String Public ReadOnly Property HasTwoDegrees As Boolean Get Return HasHighSchoolDegree AndAlso HasUniversityDegree End Get End Property Private _hasUniversityDegree As Boolean Public Property HasUniversityDegree As Boolean Get Return Me._hasUniversityDegree End Get Set ( value As Boolean ) Me.SetProperty ( Me._hasUniversityDegree , value ) OnPropertyChanged ( `` HasTwoDegrees '' ) End Set End Property Private _hasHighSchoolDegree As Boolean Public Property HasHighSchoolDegree As Boolean Get Return Me._hasHighSchoolDegree End Get Set ( value As Boolean ) Me.SetProperty ( Me._hasHighSchoolDegree , value ) OnPropertyChanged ( `` HasTwoDegrees '' ) End Set End PropertyEnd ClassPublic MustInherit Class BindableBase Implements INotifyPropertyChanged Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Protected Function SetProperty ( Of T ) ( ByRef storage As T , value As T , Optional propertyName As String = Nothing ) As Boolean If Object.Equals ( storage , value ) Then Return False storage = value Me.OnPropertyChanged ( propertyName ) Return True End Function Protected Sub OnPropertyChanged ( Optional propertyName As String = Nothing ) RaiseEvent PropertyChanged ( Me , New PropertyChangedEventArgs ( propertyName ) ) End SubEnd Class",Aggregate data from child into parent for Binding "C_sharp : Say I have an array of strings : How do I use LINQ to extract the strings between the `` xx '' markers as groups ? Say by writing them to the console as : string [ ] strArray = { `` aa '' , `` bb '' , `` xx '' , `` cc '' , `` xx '' , `` dd '' , `` ee '' , `` ff '' , `` xx '' , '' xx '' , '' gg '' , '' xx '' } ; ccdd , ee , ffgg","Using C # , LINQ how to pick items between markers again and again ?" "C_sharp : I 'm trying to convert an open source library from .Net 4.0 to 3.5 and can not easily convert the following long multiplication code : As you can see the author did n't find a way to do this . BigInteger does not exist in .NET 3.5.How can I compute the high bits 64 bits of a 64*64 multiplication on .NET 3.5 ? /// < summary > /// Calculate the most significant 64 bits of the 128-bit product x * y , where x and y are 64-bit integers . /// < /summary > /// < returns > Returns the most significant 64 bits of the product x * y. < /returns > public static long mul64hi ( long x , long y ) { # if ! NET35 BigInteger product = BigInteger.Multiply ( x , y ) ; product = product > > 64 ; long l = ( long ) product ; return l ; # else throw new NotSupportedException ( ) ; //TODO ! # endif }",Computing the high bits of a multiplication in C # "C_sharp : From the .NET APIs catalog , I understand that the Microsoft.Win32.Registry class is declared in the .NET Standard + Platform Extensions 2.0 package in an assembly Microsoft.Win32.Registry , Version=4.1.1.0 , PublicKeyToken=b03f5f7f11d50a3a . I 've created a class library which targets .NET Standard 2.0 , and here 's a simple class : I 've created a .NET Framework 4.7.2 console application which references my above class library : When I run this on Windows , this throws a run-time exception : System.IO.FileNotFoundException : 'Could not load file or assembly 'Microsoft.Win32.Registry , Version=4.1.3.0 , Culture=neutral , PublicKeyToken=b03f5f7f11d50a3a ' or one of its dependencies . The system can not find the file specified . 'Based on what I 've read , having assembly load issues in this scenario is somewhat of a known issue . The prescribed work-around is to enable automatic binding redirects and make sure my .NET Framework application is using PackageReference rather than Project.Config . I have done this with my projects from which I shared the above code , but I 'm still getting the error . What confuses me most , though , is that the error is indicating the .NET Core / .NET Core + Platform Extensions assembly ( Version=4.1.3.0 , PublicKeyToken=b03f5f7f11d50a3a ) rather than the .NET Standard ( Version=4.1.1.0 , PublicKeyToken=b03f5f7f11d50a3a ) or .NET Framework ( Version=4.0.0.0 , PublicKeyToken=b77a5c561934e089 ) versions from the APIs catalog : This is further corroborated by the Microsoft.Win32.Registry.DLL that is in the output directory : Based on further reading , I can make a little progress by doing either of the following : Add < CopyLocalLockFileAssemblies > true < /CopyLocalLockFileAssemblies > to the .NET Standard class library proj file -- or -- Add the Microsoft.Win32.Registry NuGet package directly to my .NET Framework console application.Either of these results in loading some version of the assembly , but then I get some odd behavior : I get an NRE for the LocalMachine property , which should n't happen.So here are the questions:1 . ) Since my project is a .NET Framework application , why is it not using the Microsoft.Win32.Registry class in the .NET Framework API , specifically the mscorlib assembly that the same APIs catalog refers to ? 2 . ) Why is n't the `` work around '' in the GitHub post not working for me ? 3 . ) Why is it seemingly looking for the .NET Core / ... extensions version of the assembly ? 4 . ) Why when I explicitly export the NuGet Microsoft.Win32.Registry assembly in the .NET Standard class library or directly reference the package in the .NET Framework console application does it result in the strange behavior where Microsoft.Win32.Registry.LocalMachine is null , which should never be the case on a Windows machine ? public class NetStandardClass { public string GetHklmRegValue ( ) { var lmKey = Microsoft.Win32.Registry.LocalMachine ; var softwareKey = lmKey.OpenSubKey ( `` Software '' ) ; return `` value '' ; } } class Program { static void Main ( string [ ] args ) { string value = new ClassLibrary2.NetStandardClass ( ) .GetHklmRegValue ( ) ; } }","Why is my .NET framework app looking for the wrong version of the .NET core/standard platform extension assembly , and how do I fix it ?" "C_sharp : Maybe I 'm just being dumb but when and why would you use : in place of : What advantage does passing by ref bring to this these methods ? NUnit.Framework.Assert.That < T > ( ref T , NUnit.Framework.Constraints.IResolveConstraint , string , params object [ ] ) NUnit.Framework.Assert.That < T > ( ref T , NUnit.Framework.Constraints.IResolveConstraint , string ) NUnit.Framework.Assert.That < T > ( ref T , NUnit.Framework.Constraints.IResolveConstraint ) NUnit.Framework.Assert.That ( object , NUnit.Framework.Constraints.IResolveConstraint , string , params object [ ] ) NUnit.Framework.Assert.That ( object , NUnit.Framework.Constraints.IResolveConstraint , string ) NUnit.Framework.Assert.That ( object , NUnit.Framework.Constraints.IResolveConstraint )",Why does NUnit 's Assert.That ( .. ) have ref overloads ? "C_sharp : I want to write the equivalent Java code of a C # code.My C # code is as follows : Java equivalent of my code looks like this.Here the `` new ( ) '' syntax in class declaration forces derived classes to write a default constructer which makes possible to call `` new T ( ) '' from base class . In other words when i am wrting the base class i am sure that the derived class will have a default constructer , so that i can instantiate a derived class object from base class.My problem in Java is , I can not instantiate a derived class object from super class . I get `` Can not instantiate the type T '' error for `` new T ( ) '' call . Is there any C # similar way in Java or should I use something like prototype pattern and cloning ? public abstract class A < T > where T : A < T > , new ( ) { public static void Process ( ) { Process ( new T ( ) ) ; } public static void Process ( T t ) { // Do Something ... } } public class B : A < B > { } public class C : A < C > { } public abstract class A < T extends A < T > > { public static < T extends A < T > > void process ( ) { process ( new T ( ) ) ; // Error : Can not instantiate the type T } public static < T extends A < T > > void process ( T t ) { // Do Something ... } public class B extends A < B > { } public class C extends A < C > { } }",Java : Create an object whose type is a type parameter "C_sharp : I want to pass a value to the base class constructor . The problem which I am facing is that the value is stored in a private variable inside derived class . Is it possible to pass it ? or is it a good approach to do like this ? This is what I triedIt is showing An object reference is required for non-static field , method or propertyBase class class Filtering : Display { private int length = 10000 ; public Filtering ( ) : base ( length ) { } } abstract class Display { public Display ( int length ) { } }",Passing private variable to base class constructor "C_sharp : I 've got this code : I get these warnings : Add : CodeContracts : ensures unproven : this.Count > = Contract.OldValue ( this.Count ) Clear : CodeContracts : ensures unproven : this.Count == 0Contains : CodeContracts : ensures unproven : ! Contract.Result < bool > ( ) || this.Count > 0CopyTo : CodeContracts : requires unproven : arrayIndex + this.Count < = array.LengthHow do I fix these ? Is there some way to just suppress these ? public class MyCollection : ICollection < string > { private readonly ICollection < string > _inner = new Collection < string > ( ) ; public void Add ( string item ) { _inner.Add ( item ) ; } // < -- CodeContracts : ensures unproven : this.Count > = Contract.OldValue ( this.Count ) public void Clear ( ) { _inner.Clear ( ) ; } // < -- CodeContracts : ensures unproven : this.Count == 0 public bool Contains ( string item ) { return _inner.Contains ( item ) ; // < -- CodeContracts : ensures unproven : ! Contract.Result < bool > ( ) || this.Count > 0 } public void CopyTo ( string [ ] array , int arrayIndex ) { _inner.CopyTo ( array , arrayIndex ) ; // < -- CodeContracts : requires unproven : arrayIndex + this.Count < = array.Length } public IEnumerator < string > GetEnumerator ( ) { return _inner.GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } public bool Remove ( string item ) { return _inner.Remove ( item ) ; } public int Count { get { return _inner.Count ; } } public bool IsReadOnly { get { return _inner.IsReadOnly ; } } }",Code contracts warnings when implementing ICollection with backing collection "C_sharp : I am not sure about the title of the question , but here it is : -I have my code as : -This works perfectly well , now if I need to do the same for another class say Dog or CatWhat I am doing is : -Now , I want it to change it to a Generic class , something like this below : -But , I am not able to do it . Puzzled even how will I call this method ? Will this work ... This is the first time I am working with generics . HttpClient client = new HttpClient ( ) ; // Create a HttpClientclient.BaseAddress = new Uri ( `` http : //localhost:8081/api/Animals '' ) ; //Set the Base Address//eg : - methodToInvoke='GetAmimals'//e.g : - input='Animal ' classHttpResponseMessage response = client.GetAsync ( 'GetAllAnimals ' ) .Result ; // Blocking call ! if ( response.IsSuccessStatusCode ) { XmlSerializer serializer = new XmlSerializer ( typeof ( Animal ) ) ; //Animal is my Class ( e.g ) string data = response.Content.ReadAsStringAsync ( ) .Result ; using ( MemoryStream ms = new MemoryStream ( UTF8Encoding.UTF8.GetBytes ( data ) ) ) { var _response = ( Animal ) serializer.Deserialize ( ms ) ; return _response ; } } HttpClient client = new HttpClient ( ) ; // Create a HttpClient client.BaseAddress = new Uri ( `` http : //localhost:8081/api/Animals '' ) ; //Set the Base Address //eg : - methodToInvoke='GetAmimals ' //e.g : - input='Animal ' class HttpResponseMessage response = client.GetAsync ( 'GetAllDogs ' ) .Result ; // Blocking call ! if ( response.IsSuccessStatusCode ) { XmlSerializer serializer = new XmlSerializer ( typeof ( Dog ) ) ; //Animal is my Class ( e.g ) string data = response.Content.ReadAsStringAsync ( ) .Result ; using ( MemoryStream ms = new MemoryStream ( UTF8Encoding.UTF8.GetBytes ( data ) ) ) { var _response = ( Dog ) serializer.Deserialize ( ms ) ; return _response ; } } private T GetAPIData ( T input , string parameters , string methodToInvoke ) { try { HttpClient client = new HttpClient ( ) ; client.BaseAddress = new Uri ( `` http : //localhost:8081/api/Animals '' ) ; //eg : - methodToInvoke='GetAmimals ' //e.g : - input='Animal ' class HttpResponseMessage response = client.GetAsync ( methodToInvoke ) .Result ; // Blocking call ! if ( response.IsSuccessStatusCode ) { XmlSerializer serializer = new XmlSerializer ( typeof ( input ) ) ; string data = response.Content.ReadAsStringAsync ( ) .Result ; using ( MemoryStream ms = new MemoryStream ( UTF8Encoding.UTF8.GetBytes ( data ) ) ) { var _response = ( input ) serializer.Deserialize ( ms ) ; return _response ; } } } catch ( Exception ex ) { throw new Exception ( ex.Message ) ; } return ( T ) input ; } var testData = GetAPIData ( new Aminal ( ) , null , 'GetAmimals ' ) ;",Creating Reusable Method using generics "C_sharp : I have a strange behaviour when I try to use a C # program to copy local files to a Sharepoint Server using UNC paths provided by Sharepoint to access the file system . First of all , my user has all the privileges required to access that specific Sharepoint-folder.This is what my operation basically looks like : This fails with an error `` The network path was not found . `` As soon as I copy the path above and paste it into WIndows File Explorer ( not internet explorer , this is simply an UNC path ) , everything works.So my assumption is , that in the background , Windows explorer does a little bit more . But what ? I do not have to enter any credentials , the targetSharepointPath simply works in explorer , and as soon as this was entered once , it also works in my C # program . Until I restart my system , I have to repeat that step . Why , and how can I achieve that programatically ? I work with UNC paths on `` normal '' Windows servers a lot , and once the user has rights I do not need any additional authentication . string targetSharepointPath = @ '' \\team.mycompany.com @ SSL\DavWWWRoot\team\wmscompanydep\Software Releases\MyToolConfig '' System.IO.File.Copy ( sourcePath , targetSharepointPath , false ) ;",Copy file to Sharepoint-share fails unless user connects to Sharepoint server for the first time "C_sharp : I have created a C # WinForms application.On my computer the following works : but this does n't : On my client 's computers it 's reversed . This works : but this does n't : The error states : Did n't manage to find any information on the internet about this problem . The program uses .Net Framework 4 and is a x86 application . I run Windows 8 x64 , the client runs Windows 7 x64.Does anybody have a clue as to why this occurs ? Thanks . DateTime.ParseExact ( `` 13/05/2012 '' , `` dd/mm/yyyy '' , null ) DateTime.Parse ( `` 13/05/2012 '' ) DateTime.Parse ( `` 13/05/2012 '' ) DateTime.ParseExact ( `` 13/05/2012 '' , `` dd/mm/yyyy '' , null ) String was not recognized as a valid DateTime .",DateTime weird behaviour "C_sharp : May I rely on the fact a Task is always executed in one thread ? It can be any , but it should be the same for the whole body , as I need the thread 's Culture to be set properly.If I ca n't , is there a parameter or so to get this behaviour ? Cheers , Matthias Task bind = Task.Factory.StartNew ( ( ) = > { Thread.CurrentThread.CurrentCulture = culture ; // do some asp.net binding stuff with automatic // date formatting gridView.DataSource = table ; gridView.DataBind ( ) ; }",.NET Task executed in one Thread "C_sharp : I have just begun to explore the mono winforms environment and I can not work out how to start a program from within monodevelop without a console session being started.My simple program runs okay but when it exits a terminal session is always created & waiting for me to 'press any key ' . I guess I could arrange things so that the terminal window closes automatically , but I would rather the app just ran 'natively ' , is this possible or does the way mono & .net function work preclude it ? As shown in the examples at Zetcode , in 'Main ' the rest of the code is started with 'application.run ( new aFunction ( ) ) ; ' , I thought this might be the cause of the terminal session occurring but replacing it with : causes the program to not run at all ( or maybe just exit without doing anything ) .I am an experienced programmer but not familiar at all with C # or the mono/.net environment so 'stating the obvious ' may be all that is required in an answer . myNewClass n = new myNewClass ( ) ; n.aFunction ( ) ;",Mono & WInforms on OS X "C_sharp : I 'm wondering if someone has a creative solution to my problem . I have a repeater that is populated from my database and it is as follows : and it produces a table that looks like thisWhat I 've circled are rows with repeating Change Id 's that I 'd like to default to collapsed but can be clicked to be expanded ( as well as clicked again to be collapsed again ) .I 've begun to implement Jon P 's solution below , and I 'm almost done ! Just the Jquery onclick event.Below is my codebehind PreRender method.Update again : The only thing I have left to fix is the jquery , which expands and collapses the hidden/opened rows on the toggler lines . Below is the jquery and css as per Jon P 's help.Can someone help me out in this final stretch ? I feel like I 'm close . < asp : Repeater ID= '' ResultsTableRepeater '' runat= '' server '' OnPreRender= '' ResultsTableRepeater_PreRender '' > < HeaderTemplate > < table class= '' td-table-bordered '' style= '' font-size : small ; width : 90 % '' > < tr > < th > Change # < /th > < th > Change Title < /th > < th > Change Description < /th > < th > Clarity Id < /th > < th > Package Description < /th > < th > Package Name < /th > < th > Package Status < /th > < th > Assigned To < /th > < th > New Package < /th > < /tr > < /HeaderTemplate > < ItemTemplate > < asp : Literal runat= '' server '' Text= ' < % # Eval ( `` ChangeId '' ) % > ' ID= '' IdTag '' Visible= '' false '' > < /asp : Label > < tr id= '' tableRow '' class= '' '' data-changeId= ' < % # Eval ( `` ChangeId '' ) % > ' runat= '' server '' style= ' < % # ( Eval ( `` AssignedTo '' ) .ToString ( ) == `` 7 '' || Eval ( `` AssignedTo '' ) .ToString ( ) == `` 8 '' ) ? `` `` : `` font-weight : bold ; background-color : cornsilk '' % > ' > < td > < % # Eval ( `` ChangeId '' ) % > < /td > < td > < % # Eval ( `` ChangeTitle '' ) % > < /td > < td > < % # Eval ( `` ChangeDescription '' ) % > < /td > < td > < % # Eval ( `` ClarityId '' ) % > < /td > < td > < % # ( Eval ( `` PackageId '' ) .ToString ( ) == string.Empty ) ? `` '' : `` < a href=http : //dev.rlaninfrastructure.tdbank.ca/RCIViewForm ? ChangeId= '' + Eval ( `` ChangeId '' ) + `` & PackageId= '' + Eval ( `` PackageId '' ) + `` runat='server ' id='RCILink ' > '' % > < asp : Label ID= '' ExistingPackageLabel '' runat= '' server '' Text= ' < % # ( Eval ( `` PackageId '' ) .ToString ( ) == string.Empty ) ? `` No packages '' : Eval ( `` PackageDescription '' ) .ToString ( ) % > ' > < /asp : Label > < % # ( Eval ( `` PackageId '' ) .ToString ( ) == string.Empty ) ? `` '' : `` < /a > '' % > < /td > < td > < % # Eval ( `` PackageName '' ) % > < /td > < td > < asp : Label ID= '' LabRequestedLabel '' runat= '' server '' Text= ' < % # ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 1 '' ) ? `` Requested '' : ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 2 '' ) ? `` Built '' : ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 3 '' ) ? `` NFT '' : ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 4 '' ) ? `` Pilot '' : ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 5 '' ) ? `` Production '' : ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 6 '' ) ? `` Completed '' : ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 7 '' ) ? `` Cancelled '' : ( Eval ( `` PackageStatus '' ) .ToString ( ) == `` 8 '' ) ? `` Pending '' : `` '' % > ' > < /asp : Label > < /td > < td > < % # ( Eval ( `` EmployeeName '' ) .ToString ( ) == string.Empty ) ? `` '' : Eval ( `` EmployeeName '' ) % > < /td > < td > < % # `` < a href=http : //dev.rlaninfrastructure.tdbank.ca/RCIViewForm ? ChangeId= '' + Eval ( `` ChangeId '' ) + `` runat='server ' id='RCILink ' > '' % > < asp : Label ID= '' NewPackageLabel '' runat= '' server '' Text= '' Create New '' > < /asp : Label > < % # '' < /a > '' % > < /td > < /tr > < /ItemTemplate > < FooterTemplate > < /table > < /FooterTemplate > < /asp : Repeater > protected void ResultsTableRepeater_PreRender ( object sender , EventArgs e ) { int previousId = 0 ; int currentId = 0 ; int nextId = 0 ; for ( int item = 0 ; item < ResultsTableRepeater.Items.Count ; item++ ) { Literal idTag = ( Literal ) ResultsTableRepeater.Items [ item ] .FindControl ( `` IdTag '' ) ; Literal classTag = ( Literal ) ResultsTableRepeater.Items [ item ] .FindControl ( `` ClassTag '' ) ; HtmlTableRow tableRow = ( HtmlTableRow ) ResultsTableRepeater.Items [ item ] .FindControl ( `` tableRow '' ) ; if ( item ! = ResultsTableRepeater.Items.Count - 1 ) int.TryParse ( ( ( Literal ) ResultsTableRepeater.Items [ item + 1 ] .FindControl ( `` IdTag '' ) ) .Text.ToString ( ) , out nextId ) ; if ( int.TryParse ( idTag.Text , out currentId ) ) { if ( currentId == previousId ) { tableRow.Attributes [ `` class '' ] = `` hidden '' ; } else if ( currentId ! = previousId & & currentId == nextId ) { tableRow.Attributes [ `` class '' ] = `` toggler '' ; } } else nextId = 0 ; int.TryParse ( idTag.Text , out previousId ) ; } } $ ( `` .toggler '' ) .click ( function ( ) { var idClicked = $ ( this ) .data ( `` changeid '' ) ; //Toggle hidden on the sibling rows with the same data id $ ( this ) .nextAll ( `` [ data-changeId= ' '' + idClicked + '' ' ] '' ) .toggleClass ( `` hidden '' ) ; //Toggle opened status on clicked row $ ( this ) .toggleClass ( `` opened '' ) ; } ) ; .hidden { display : none ; } .toggler td : first-child : :after { content : '' + '' ; } .toggler.opened td : first-child : :after { content : '' - '' ; }",asp : repeater collapsing table rows - Updated "C_sharp : I am using DoubleAnimation for zooming and panning in and out of map . My map is an image with huge resolution ( 15,000 x 8,438 ) . The problem is that on first time the zoom animation is very faltering and not smooth , at second time it ` s getting better and so on . How can I make my animation smoother or make some cashing of the image or animation before performing it , or maybe using other form of animation ? My Code : namespace AnimationTest { public partial class MainWindow : Window { ScaleTransform transP ; TranslateTransform trans2P ; DoubleAnimation animP ; DoubleAnimation animYP ; DoubleAnimation animXP ; TransformGroup myTransformGroupP ; public MainWindow ( ) { InitializeComponent ( ) ; transP = new ScaleTransform ( ) ; trans2P = new TranslateTransform ( ) ; myTransformGroupP = new TransformGroup ( ) ; myTransformGroupP.Children.Add ( transP ) ; myTransformGroupP.Children.Add ( trans2P ) ; animP = new DoubleAnimation ( 1 , 20 , TimeSpan.FromMilliseconds ( 3000 ) ) ; animXP = new DoubleAnimation ( 0 , -14000 , TimeSpan.FromMilliseconds ( 3000 ) ) ; animYP = new DoubleAnimation ( 0 , -4000 , TimeSpan.FromMilliseconds ( 3000 ) ) ; } private void button1_Click ( object sender , RoutedEventArgs e ) { image1.RenderTransform = myTransformGroupP ; transP.BeginAnimation ( ScaleTransform.ScaleXProperty , animP ) ; transP.BeginAnimation ( ScaleTransform.ScaleYProperty , animP ) ; trans2P.BeginAnimation ( TranslateTransform.XProperty , animXP ) ; trans2P.BeginAnimation ( TranslateTransform.YProperty , animYP ) ; } } }",Non-smooth DoubleAnimation "C_sharp : How do I remove a specific string from WPF RichTextBox ( if the string exist ) ? To rephrase my question , what is the WPF equivalent of the following WinForm RichTextBox version : Thanks ! richTextBox1.Text = `` aaabbbccc '' ; richTextBox1.Text = richTextBox1.Text.Replace ( `` bbb '' , `` '' ) ;",How to remove a specific string from WPF RichTextBox ? "C_sharp : Currently I have the following code : As you can see the query is the same each time except for the publicationType condition . I tried to refactor this by creating a method that takes a Func e.g.and then calling this method likeBut when I do this I get the error : InvalidCastException : Unable to cast object of type 'NHibernate.Hql.Ast.HqlParameter ' to type 'NHibernate.Hql.Ast.HqlBooleanExpression'.Is there another way to do this ? switch ( publicationType ) { case PublicationType.Book : return Session.Query < Publication > ( ) .Where ( p = > p.PublicationType == PublicationType.Book ) .OrderByDescending ( p = > p.DateApproved ) .Take ( 10 ) .Select ( p = > new PublicationViewModel { ... } ) ; case PublicationType.Magazine : return Session.Query < Publication > ( ) .Where ( p = > p.PublicationType == PublicationType.Magazine ) .OrderByDescending ( p = > p.DateApproved ) .Take ( 10 ) .Select ( p = > new PublicationViewModel { ... } ) ; case PublicationType.Newspaper ... . } private IEnumerable < PublicationViewModel > GetPublicationItems ( Func < PublicationType , bool > > pubQuery ) { return Session.Query < Publication > ( ) .Where ( pubQuery ) .OrderByDescending ( p = > p.DateApproved ) .Take ( 10 ) .Select ( p = > new PublicationViewModel { ... } ) ; } private bool IsBook ( PublicationType publicationType ) { return publicationType == PublicationType.Book ; } GetPublicationItems ( IsBook ) ;",Is it possible to refactor this nHibernate Linq query ? "C_sharp : When performing a Select on an IEnumerable I believe it is good practice to check for null references , so I often have a Where before my Select like this : This gets more complicated when accessing sub-properties : To follow this pattern I need to do a lof of calls to Where . I would like to create an extension method on IEnumerable that perform such null-checks automatically depending on what is referenced in the Select . Like this : Can this be done ? Is it fx . possible to retrieve the selected properties from the selector parameter when creating an extension method such as this ? EDIT : I use C # 5.0 with .NET Framework 4.5 someEnumerable.Where ( x = > x ! = null ) .Select ( x = > x.SomeProperty ) ; someEnumerable.Where ( x = > x ! = null & & x.SomeProperty ! = null ) .Select ( x = > x.SomeProperty.SomeOtherProperty ) ; someEnumerable.SelectWithNullCheck ( x = > x.SomeProperty ) ; someEnumerable.SelectWithNullCheck ( x = > x.SomeProperty.SomeOtherProperty ) ; public static IEnumerable < TResult > SelectWithNullCheck < TSource , TResult > ( this IEnumerable < TSource > source , Func < TSource , TResult > selector ) { return source.Where ( THIS IS WHERE THE AUTOMATIC NULL-CHECKS HAPPEN ) .Select ( selector ) ; }",Linq : Extension method on IEnumerable to automatically do null-checks when performing selects "C_sharp : I am starting learning C # and XNA , and I want to display an animated sprite ( moved by my keyboard ) .I 've got this sprite file : To display only the part I need , I use this code : But my problem is that the rendered image is blurred after moving : I tried to fix this by changing the SamplerStates , but nothing changed . Does anyone have an idea to help me ? Rectangle cuttedSprite = new Rectangle ( this.W * ( int ) this.mCurSprite.X , this.H * ( int ) this.mCurSprite.Y , this.W , this.H ) ; spriteBatch.Draw ( this.mSpriteTexture , this.mPosition , cuttedSprite , Color.White ) ;",Sprite becomes blurred "C_sharp : When S and T are different , this works : But , In the first example , since T is inferred from return type of lambda expression , ca n't T in the second example too be inferred ? I suppose its doing it , but why is first T not known , when second T of Func < T , T > is known , after all T == T right ? Or is there an order for types being inferred in case of Funcs ? public static void Fun < S , T > ( Func < S , T > func ) { } Fun ( ( string s ) = > true ) ; //compiles , T is inferred from return type . public static void Fun < T > ( Func < T , T > func ) { } Fun ( t = > true ) ; //ca n't infer type .","T of Func < S , T > is inferred from output of lambda expression only when S and T are different ?" "C_sharp : I was looking at this wikipedia article , and could n't understand how the hell that was working . A little bit frustrated not being able to understand the code just by looking at it , i dedided to port the code to c # ( i 'm .net , sorry guys : ) ) . Just some minor modifications were needed ( inherits and extends , base for super , etc ) and run the app . To my surprise , i got the following output : Just curious , can any java dev tell me what 's different here and why the wikipedia example works ( if it does work as they say it does , of course ) . Cost : 1 Ingredient : CoffeeCost : 1 Ingredient : CoffeeCost : 1 Ingredient : CoffeeCost : 1 Ingredient : Coffee namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { Coffee sampleCoffee = new SimpleCoffee ( ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; sampleCoffee = new Milk ( sampleCoffee ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; sampleCoffee = new Sprinkles ( sampleCoffee ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; sampleCoffee = new Whip ( sampleCoffee ) ; Console.WriteLine ( `` Cost : `` + sampleCoffee.getCost ( ) + `` Ingredient : `` + sampleCoffee.getIngredient ( ) ) ; Console.ReadKey ( ) ; } } //The Coffee Interface defines the functionality of Coffee implemented by decoratorpublic interface Coffee { double getCost ( ) ; // returns the cost of coffee String getIngredient ( ) ; //returns the ingredients mixed with coffee } //implementation of simple coffee without any extra ingredientspublic class SimpleCoffee : Coffee { double cost ; String ingredient ; public SimpleCoffee ( ) { cost = 1 ; ingredient = `` Coffee '' ; } public double getCost ( ) { return cost ; } public String getIngredient ( ) { return ingredient ; } } //abstract decorator class - note that it implements coffee interfaceabstract public class CoffeeDecorator : Coffee { protected Coffee decoratedCoffee ; protected String ingredientSeparator ; public CoffeeDecorator ( Coffee decoratedCoffee ) { this.decoratedCoffee = decoratedCoffee ; ingredientSeparator = `` , `` ; } public CoffeeDecorator ( ) { } public double getCost ( ) //note it implements the getCost function defined in interface Coffee { return decoratedCoffee.getCost ( ) ; } public String getIngredient ( ) { return decoratedCoffee.getIngredient ( ) ; } } //Decorator Milk that mixes milk with coffee//note it extends CoffeeDecoratorpublic class Milk : CoffeeDecorator { double cost ; String ingredient ; public Milk ( Coffee decoratedCoffee ) : base ( decoratedCoffee ) { cost = 0.5 ; ingredient = `` Milk '' ; } public double getCost ( ) { return base.getCost ( ) + cost ; } public String getIngredient ( ) { return base.getIngredient ( ) + base.ingredientSeparator + ingredient ; } } //Decorator Whip that mixes whip with coffee//note it extends CoffeeDecoratorpublic class Whip : CoffeeDecorator { double cost ; String ingredient ; public Whip ( Coffee decoratedCoffee ) : base ( decoratedCoffee ) { cost = 0.7 ; ingredient = `` Whip '' ; } public double getCost ( ) { return base.getCost ( ) + cost ; } public String getIngredient ( ) { return base.getIngredient ( ) + base.ingredientSeparator + ingredient ; } } //Decorator Sprinkles that mixes sprinkles with coffee//note it extends CoffeeDecoratorpublic class Sprinkles : CoffeeDecorator { double cost ; String ingredient ; public Sprinkles ( Coffee decoratedCoffee ) : base ( decoratedCoffee ) { cost = 0.2 ; ingredient = `` Sprinkles '' ; } public double getCost ( ) { return base.getCost ( ) + cost ; } public String getIngredient ( ) { return base.getIngredient ( ) + base.ingredientSeparator + ingredient ; } } }",Decorator Pattern question C # / java "C_sharp : Imagine you want a Save & Close and a Cancel & Close button on your fancy WPF MVVM window ? How would you go about it ? MVVM dictates that you bind the button to an ICommand and inversion of control dictates that your View may know your ViewModel but not the other way around.Poking around the net I found a solution that has a ViewModel closing event to which the View subscribes to like this : But that is code-behind mixed in with my so far very well designed MVVM.Another problem would be showing a licensing problem message box upon showing the main window . Again I could use the Window.Loaded event like I did above , but that 's also breaking MVVM , is it not ? Is there a clean way or should one be pragmatical instead of pedantic in these cases ? private void OnLoaded ( Object sender , RoutedEventArgs e ) { IFilterViewModel viewModel = ( IFilterViewModel ) DataContext ; viewModel.Closing += OnViewModelClosing ; } private void OnViewModelClosing ( Object sender , EventArgs < Result > e ) { IFilterViewModel viewModel = ( IFilterViewModel ) DataContext ; viewModel.Closing -= OnViewModelClosing ; DialogResult = ( e.Value == Result.OK ) ? true : false ; Close ( ) ; }",MVVM : Is code-behind evil or just pragmatic ? "C_sharp : I encountered some unexpected compiler behaviour when calling overloaded method with different Action < T > variations.Let 's say I have this class Test and I 'm creating its instance in the CallTest constructor . When calling the Test constructor with either TestDecimal or TestLong as a parameter I 'm receiving the following error : The call is ambiguous between the following methods or properties : 'Test ( System.Action < long > ) ' and 'Test ( System.Action < decimal > ) 'My guess is there 's some implicit conversion going on between long and decimal , but does anyone have any other idea what could have I done wrong ? Is there any workaround ? public class Test { public Test ( Action < long > arg ) { } public Test ( Action < decimal > arg ) { } } public class CallTest { public CallTest ( ) { Test t = new Test ( TestDecimal ) ; } public void TestDecimal ( decimal arg ) { } public void TestLong ( long arg ) { } }",Ambiguous method call with Action < T > parameter overload "C_sharp : As part of a large automation process , we are calling a third-party API that does some work calling services on another machine . We discovered recently that every so often when the other machine is unavailable , the API call will spin away sometimes up to 40 minutes while attempting to connect to the remote server . The API we 're using does n't offer a way to specify a timeout and we do n't want our program waiting around for that long , so I thought threads would be a nice way to enforce the timeout . The resulting code looks something like : Basically , I want to let APICall ( ) run , but if it is still going after timeout has elapsed , assume it is going to fail , kill it and move on.Since I 'm new to threading in C # and on the .net runtime I thought I 'd ask two related questions : Is there a better/more appropriate mechanism in the .net libraries for what I 'm trying to do , and have I committed any threading gotchas in that bit of code ? Thread _thread = new Thread ( _caller.CallServices ( ) ) ; _thread.Start ( ) ; _thread.Join ( timeout ) ; if ( _thread.IsAlive ) { _thread.Abort ( ) ; throw new Exception ( `` Timed-out attempting to connect . `` ) ; }",A reasonable use of threading in C # ? "C_sharp : I 'm trying to understand I/O Completion Ports and specifically how they relate to using async-await for I/O . The infamous article There is No Thread talks about IOCPs being borrowed briefly after the I/O is complete . Because the whole point of the article is to show that when the fancy hardware-level I/O stuff is in-flight , there is no thread that is consumed by a loop like Is the I/O done yet ? No . Is the I/O done yet ? No . Is the I/O done yet ? No . ... But then I 'm looking at this article which says that a `` component is in charge of checking the completion port for queued elements '' and gives an example like which to me looks like there is some polling going on . I guess my questions boil down toIs it true to say that a .NET application has 2 types of thread pools -- ( 1 ) `` worker threads '' and ( 2 ) `` I/O threads '' ? If it 's true , is there a fixed number , specified in a configuration , like M worker threads and N I/O threads ? And what is usually the ratio of M to N ? When exactly are I/O threads used ? public class IOCompletionWorker { public unsafe void Start ( IntPtr completionPort ) { while ( true ) { uint bytesRead ; uint completionKey ; NativeOverlapped* nativeOverlapped ; var result = Interop.GetQueuedCompletionStatus ( completionPort , out bytesRead , out completionKey , & nativeOverlapped , uint.MaxValue ) ; var overlapped = Overlapped.Unpack ( nativeOverlapped ) ; if ( result ) { var asyncResult = ( ( FileReadAsyncResult ) overlapped.AsyncResult ) ; asyncResult.ReadCallback ( bytesRead , asyncResult.Buffer ) ; } else { ThreadLogger.Log ( Interop.GetLastError ( ) .ToString ( ) ) ; } Overlapped.Free ( nativeOverlapped ) ; } } } var completionPortThread = new Thread ( ( ) = > new IOCompletionWorker ( ) .Start ( completionPortHandle ) ) { IsBackground = true } ; completionPortThread.Start ( ) ;",Is an IOCP a thread that is running while the I/O is taking place or after ? "C_sharp : In which scenarios Will Range partitioning will be better choice than Chunk partitioning ? ( and vise verse ) I already know that Chunk partitioning : grabbing smal chunks of elements from the input to process , he starts with small chunks then , increases the chunk size.Range partitioning preallocates an equal number of elements to each worker Also , Why this code : ( finding prime numbers till 100000 ) Might perform poorly with range partitioning ? While this code : ( finding the sum of sqrt of the first million numbers ) Will be better a better choice to use with range partitioning ? IEnumerable < int > numbers = Enumerable.Range ( 3 , 100000-3 ) ; var parallelQuery = from n in numbers.AsParallel ( ) where Enumerable.Range ( 2 , ( int ) Math.Sqrt ( n ) ) .All ( i = > n % i > 0 ) select n ; ParallelEnumerable.Range ( 1 , 10000000 ) .Sum ( i = > Math.Sqrt ( i ) )",Plinq 's Range partitioning vs Chunk partitioning ? "C_sharp : I got a strange problem . My mdi child form has 2 close buttons and 2 maximized buttons . A screenshot of the problem : I create the mdi child like this : If I get rid of `` summaryForm.WindowState = FormWindowState.Maximized ; '' , the window style is correct . But I hope to make the mdi child form maximized when created . summaryForm.MdiParent = ContainerForm ; summaryForm.WindowState = FormWindowState.Maximized ; summaryForm.Show ( ) ;",Why I got extra close button on mdi child window ? "C_sharp : I have a property in my class that has a lot of logic in set accessor : How can I prevent other developers ( or even me ) from changing field instead of property inside of this class ? If somebody writes something like this : it will break the logic of my class ! private String text ; public String Text { get { return text ; } private set { // some actions with a value value = value.Replace ( ' a ' , ' b ' ) ; text = value ; } } public Test ( String text ) { this.text = text ; }",How to forbid the use of fields instead of properties ? "C_sharp : Say I 've got a domain model created from C # classes like this : Along with the model , I have defined repository interfaces classes for IoC.Now , I 'm trying to turn this POCO domain model into a set of Entity classes using LINQ mapping . ( This approch was recommended in a book I 'm reading on MVC . ) In the example above this was easy enough to do with a few attributes without impacting the 'plain oldness ' of the classes : The problem comes when I start to map associations , change modifications and such . It seems that I 'm quickly destroying the original concept of the domain model , and instead simply creating a set of LINQ-to-SQL classes . Am I missing something ? Are these classes still the correct place for business logic ? Will I still be able to and should I continue to load data into these classes from non-LINQ , non-DB sources ? Thanks public class MyClass { public string MyProperty { get ; set ; } } [ Table ] public class MyClass { [ Column ] public string MyProperty { get ; set ; } }",Corrupting POCO Domain Model when creating LINQ Entity Classes ? "C_sharp : I have no doubt this is as easy to do as possible , but I have a function creator library that creates lambda functions for me of the form : And I 'm looking to specify the out parameter more specifically - Basically , I 'm looking to be able to create something along the lines of : But , when I try this , I get back a null ( as an aside , if I return objFunc as a Func < T1 , object > it is not a null , so I know that 's not where my issue lay ) .How do I do this correctly ? Func < T1 , object > private Func < T1 , T2 > GetFunc < T1 , T2 > ( string expression ) { Func < T1 , object > objFunc = CreateFunction ( expression ) ) ; return objFunc as Func < T1 , T2 > ; }","C # Convert Func < T1 , object > to Func < T1 , T2 >" "C_sharp : I 'm using Microsoft.VisualStudio.TestTools.UnitTesting ; but the method I marked as [ TestInitialize ] is n't getting called before the test . I 've never used this particular testing framework before but in every other framework there is always a way of registering a Setup and TearDown method that will auto run before and after every single test . Is this not the case with the visual studio testing tools unit testing framework ? [ TestClass ] public class RepoTest { private const string TestConnectionString = @ '' Server=localhost\SQL2014EXPRESS64 ; Database=RepoTest ; Trusted_Connection=True ; '' ; private const string MasterConnectionString = @ '' Server=localhost\SQL2014EXPRESS64 ; Database=master ; Trusted_Connection=True ; '' ; [ TestInitialize ] private void Initialize ( ) { using ( var connection = new SqlConnection ( MasterConnectionString ) ) using ( var command = new SqlCommand ( Resources.Initialize , connection ) ) { command.ExecuteNonQuery ( ) ; } } [ TestCleanup ] private void Cleanup ( ) { using ( var connection = new SqlConnection ( MasterConnectionString ) ) using ( var command = new SqlCommand ( Resources.Cleanup , connection ) ) { command.ExecuteNonQuery ( ) ; } } [ TestMethod ] public void CreateARepo ( ) { var repo = new Repo ( TestConnectionString ) ; } }",why is n't TestInitialize getting called automatically ? "C_sharp : The following does not compile . It fails with this error : CS0191 A readonly field can not be assigned to ( except in a constructor or a variable initializer ) Technically are we not in the constructor still , since the visibility of the local function is limited , so I 'm wondering why this does not compile . public class A { private readonly int i ; public A ( ) { void SetI ( ) { i = 10 ; } SetI ( ) ; } }",Set readonly fields in a constructor local function c # "C_sharp : I need to group `` Document '' value from XML . Problem is because key value ( productType ) can be multiple.This is XML : And this is what I try : My code is working only if is there one productType element . How to change my code to work if there is multiple value of productType ? < Documents > < Document > < id > 1 < /id > < title > title1 < /title > < productTypes > < productType id= '' x1 '' > Capital Costs Analysis Forum - Brazil < /productType > < productType id= '' x3 '' > Environmental , Health and Safety & amp ; Sustainability < /productType > < /productTypes > < /Document > < Document > < id > 2 < /id > < title > title2 < /title > < productTypes > < productType id= '' x1 '' > Capital Costs Analysis Forum - Brazil < /productType > < /productTypes > < /Document > < Document > < id > 3 < /id > < title > title3 < /title > < productTypes > < productType id= '' x3 '' > Environmental , Health and Safety & amp ; Sustainability < /productType > < /productTypes > < /Document > < Document > < id > 4 < /id > < title > title4 < /title > < productTypes > < productType id= '' x2 '' > Defense , Risk & amp ; Security < /productType > < /productTypes > < /Document > var documents = from document in some.Descendants ( `` Document '' ) group document by ( string ) document .Element ( `` productTypes '' ) .Elements ( `` productType '' ) .First ( ) into docGroupselect docGroup ;",How to group XML data by multiple value "C_sharp : I am doing the exact same thing in two classes , and in one the compiler is allowing it just fine , but the other one is giving me an error . Why the double standard ? There 's 15 classes using this same pattern , but only one refuses to compile , saying the following error : 'AWWAInvoicingXML.AwwaTransmissionInfo ' does not implement interface member 'AWWAInvoicingXML.IXmlSerializable.fromXML ( System.Xml.XmlDocumentFragment ) ' . 'AWWAInvoicingXML.AwwaTransmissionInfo.fromXML ( System.Xml.XmlDocumentFragment ) ' is either static , not public , or has the wrong return type.Here is my source code ... if I comment out the AwwaTransmissionInfo class , the rest of the file compiles just fine , so I know it 's not one of those where the compiler is just dying after the first error . And I know , I know , there 's built-in stuff for what I 'm trying to do here , but just assume I actually know what I 'm doing and skipped the built-in serializers for a reason : ) public interface IXmlSerializable { //if this interface is implemented , the object can be serialized to XML string toXML ( ) ; IXmlSerializable fromXML ( XmlDocumentFragment inXml ) ; } public class AwwaTransmissionInfo : IXmlSerializable { public DateTime DateTime = DateTime.Now ; public int ItemCount ; public string toXML ( ) { throw new Exception ( `` The method or operation is not implemented . `` ) ; } public AwwaTransmissionInfo fromXML ( XmlDocumentFragment inXml ) { throw new Exception ( `` The method or operation is not implemented . `` ) ; } } public class CEmail { public string Email = `` '' ; public string toXML ( ) { throw new System.Exception ( `` The method or operation is not implemented . `` ) ; } public CEmail fromXML ( XmlDocumentFragment inXml ) { throw new System.Exception ( `` The method or operation is not implemented . `` ) ; } }",C # double standard ? "C_sharp : In the Framework we are building we need the following pattern : As you see , we create a lambda when calling the base constructor . Oddly , when trying to actually use the lambda it throws NullReferenceException ( Console Application ) , or some kind of ExecutionEngineExceptionexception ( Web app on IIS ) .I think the reason is that this pointer is not ready before calling base constructor , so the lambda is unable to capture this.Name at this stage . Should n't it throw an exception in `` capture time '' instead of `` execution time '' ? Is this behavior documented ? I can refactor the code in a different way , but I think it worths a comment . public class BaseRenderer { Func < string > renderer ; public BaseRenderer ( Func < string > renderer ) { this.renderer = renderer ; } public string Render ( ) { return renderer ( ) ; } } public class NameRenderer : BaseRenderer { public string Name { get ; set ; } public NameRenderer ( ) : base ( ( ) = > this.Name ) { } } public class Program { public static void Main ( ) { Console.WriteLine ( new NameRenderer ( ) { Name = `` Foo '' } .Render ( ) ) ; } }",Corner case in using lambdas expression in base constructor "C_sharp : I 'm curious to know whether a Lambda ( when used as delegate ) will create a new instance every time it is invoked , or whether the compiler will figure out a way to instantiate the delegate only once and pass in that instance.More specifically , I 'm wanting to create an API for an XNA game that I can use a lambda to pass in a custom call back . Since this will be called in the Update method ( which is called many times per second ) it would be pretty bad if it newed up an instance everytime to pass in the delegate . InputManager.GamePads.ButtonPressed ( Buttons.A , s = > s.MoveToScreen < NextScreen > ( ) ) ;",Does a lambda create a new instance everytime it is invoked ? "C_sharp : I expose an IQueryable method from my business layer for use in other layers . I would like to execute a function against each of the items in the enumeration , once the query has executed down-level . It seems like there should be an event that is raised after the query executes , so that I can then operate on the results from this common layer.Something like : I want the ForEachDelayed function to return the IQueryable without executing the query . The idea is , once the query is executed , the results are passed through this delegate.Is there something like this out there ? If not , is there an event like `` IQueryable.OnExecute '' that I can subscribe to ? Any help would be awesome -- thanks ! EDIT : I thought I had the answer with this : But now , I get the following error : Method 'AppendData ( User ) ' has no supported translation to SQL.I really need a delegate to run AFTER the query has executed . public IQueryable < User > Query ( ) { return _Repository.Query < User > ( ) .ForEachDelayed ( u= > AppendData ( u ) ) ; } var users = from u in _Repository.Query < User > ( ) select AppendData ( u ) ; return users ;",Is there any way to delay- execute a delegate against an IQueryable < T > after/during execution ? "C_sharp : I have a method wrapping some external API call which often returns null . When it does , I want to return a default value . The method looks like thisThe problem is that ( T ) value might throw an invalid cast exception . So I thought I would change it tobut this requires where T : struct , and I want to allow reference types as well.Then I tried adding an overload which would handle both.but I found you ca n't overload based on constraints.I realize I can have two methods with different names , one for nullable types and one for nonnullable types , but I 'd rather not do that.Is there a good way to check if I can cast to T without using as ? Or can I use as and have a single method which works for all types ? public static T GetValue < T > ( int input ) { object value = ExternalGetValue ( input ) ; return value ! = null ? ( T ) value : default ( T ) } var value = ExternalGetValue ( input ) as Nullable < T > ; public static T GetValue < T > ( int input ) where T : struct { ... } public static T GetValue < T > ( int input ) where T : class { ... }",How can I check if a value can be cast to a generic type ? C_sharp : The above gives valid==true because the constructor with default arg is NOT called and the object is created with the standard default val = 0.0.If the struct is a class the behaviour is valid==false which is what I would expect . I find this difference in behaviour and particularly the behaviour in the struct case suprising and unintuitive - what is going on ? What does the default arg on the stuct construct serve ? If its useless why let this compile ? Update : To clarify the focus here is not on what the behaviour is - but rather why does this compile without warning and behave unintuitively . I.e If the default arg is not applied because in the new Test ( ) case the constructor is not called then why let it compile ? public struct Test { public double Val ; public Test ( double val = double.NaN ) { Val = val ; } public bool IsValid { get { return ! double.IsNaN ( Val ) ; } } } Test myTest = new Test ( ) ; bool valid = myTest.IsValid ;,Unintuitive behaviour with struct initialization and default arguments "C_sharp : So would : be faster or slower to do than constructor chaining to get the values to carColor and carTopSpeed ? I understand on a desktop environment the performance will almost always be negligible , but : I would like to know for mobile game development where all the little things count in performance . Thanks in advance ! public Car ( string color = `` red '' , topSpeed = 180 ) { carColor = color ; carTopSpeed = topSpeed ; }",Are there performance penalties for named/optional parameters for constructors ? "C_sharp : I have an array of valid e-mail address domains . Given an e-mail address , I want to see if its domain is validIs there a way to check if email contains any of the values of validDomains without using a loop ? string [ ] validDomains = { `` @ test1.com '' , `` @ test2.com '' , `` @ test3.com '' } ; string email = `` test @ test1.com ''",How can I check if a string contains an array of values ? "C_sharp : Code : The server is a Microsoft SQL Server instance . The database table MyTable contains fields which are nullable . Therefore null is a valid value to search on when performing the query.From my reading , and also from testing code like this , doing something like what I did here does n't work properly because apparently you ca n't do an `` equals null '' comparison this way - you 're supposed to do `` IS NULL '' . It looks like you can correct this and make it work by setting ANSI_NULL to OFF ( as per https : //msdn.microsoft.com/en-us/library/ms188048.aspx ) but it also indicates this method is deprecated and should not be used . That article suggests you can use an OR operator to do something like WHERE Field1 = 25 OR Field1 IS NULL . The problem is , with a single call to this function , I want to check for either null and only null , or for the given constant value and nothing else . So far , it seems like I need to basically build the query piece by piece , string by string , to account for the possibility of NULL values . So I 'd need to do something like : Is this really how it needs to be done ? Is there a more efficient way to do this without repeating that if block and by using parameters rather than concatenating a query string together ? ( Notes : An empty string is converted to a NULL here for the example . In the scenario I 'm actually working with , empty strings are never used , but instead NULL is stored . The database is out of my control , so I ca n't just say `` change all your NULLs to empty strings '' . Same goes for the ints - if we pass , say , -1 into the function it should be testing for a null value . Bad practice ? Maybe , but the database itself is not in my control , only the code to access it is . ) private void DoSomethingWithDatabase ( string f1 , int f2 ) { SqlCommand myCommand = new SqlCommand ( `` SELECT Field1 , Field2 , Field3 FROM MyTable WHERE Field1 = @ F1 AND Field2 = @ F2 '' , this.myConn ) ; myCommand.Parameters.Add ( `` @ F1 '' , System.Data.SqlDbType.VarChar ) ; myCommand.Parameters.Add ( `` @ F2 '' , System.Data.SqlDbType.Int ) ; if ( f1 == `` '' ) myCommand.Parameters [ `` @ F1 '' ] .Value = DBNull.Value ; else myCommand.Parameters [ `` @ F1 '' ] .Value = f1 ; if ( f2 < 0 ) myCommand.Parameters [ `` @ F2 '' ] .Value = DBNull.Value ; else myCommand.Parameters [ `` @ F2 '' ] .Value = f2 ; // code to do stuff with the results here } string theQuery = `` SELECT Field1 , Field2 , Field3 FROM MyTable WHERE `` ; if ( f1 == `` '' ) theQuery += `` Field1 IS NULL `` ; else theQuery += `` Field1 = @ F1 `` ; // ... SqlCommand myCommand = new SqlCommand ( theQuery , this.myConn ) ; if ( f1 == `` '' ) { myCommand.Parameters.Add ( `` @ F1 '' , System.Data.SqlDbType.VarChar ) ; myCommand.Parameters [ `` @ F1 '' ] .Value = f1 ; } // ...",.NET : How to deal with possible null values in an SQL query ? "C_sharp : I am working on a smooth terrain generation algorithm in C # and using XNA to display the data.I am making it so it creates a new point halfway between each point per iteration , at a random height between the two . This works OK , and I have set it so that on the second iteration it chooses a random point like in slide two , rather than trying to make a new point between points that are on the same axis.What is happening is that the loop is using the same random value from the previous iteration : http : //i.stack.imgur.com/UmWr7.pngThis is not ideal obviously , as it is not a proper random generation.If I use a Thread.Sleep ( 20 ) after each point generation it works correctly : http : //i.stack.imgur.com/KziOg.pngI do n't want to have to use the Sleep workaround if possible as it is very slow , and I would like to use this in real-time . I 'm pretty sure this has something to do with the C # garbage collector.Here is my Get Point CodeIs the garbage collection a part of the issue ? Any suggestions or solutions on solving this ? ? Random r = new Random ( ) ; int x = ( p1.X + p2.X ) / 2 ; int y ; if ( ! initial ) y = r.Next ( Math.Min ( p1.Y , p2.Y ) , Math.Max ( p1.Y , p2.Y ) ) ; else y = r.Next ( Math.Min ( p1.Y , p2.Y ) - Game1.screenHeight / 2 , Math.Max ( p1.Y , p2.Y ) + Game1.screenHeight / 2 ) ; return new Point ( x , y ) ;",Random object not disposing in C # "C_sharp : I have a bit of a unique problem . I am registering a dll as an assembly inside of a SQL Server database that takes in an SQLXml variable , along with two strings , and serializes the data into JSON format . For reference , here is the method call : I would use Newtonsoft.Json or Jayrock for this application if this was any other type of app . Normally I would follow the answer given here and do something similar to : However , since I am using SQLClr , there are certain rules of the road . One of which is that .Load ( ) and any other inherited method ca n't be used . I think the .Net framework said it best : System.InvalidOperationException : Can not load dynamically generated serialization assembly . In some hosting environments assembly load functionality is restricted , consider using pre-generated serializer . Please see inner exception for more information . -- - > System.IO.FileLoadException : LoadFrom ( ) , LoadFile ( ) , Load ( byte [ ] ) and LoadModule ( ) have been disabled by the host.I am not fluent in SqlClr by any means , but if I am understanding this blog correctly , this is caused by SqlCLR 's rules not allowing .Load ( ) and inherited methods without being signed for and having a strong name . My DLL and the 3rd party DLLs I 'm using do not have a strong name nor can I rebuild and sign them myself . So , this leaves me stuck with attempting to complete this task without using load ( Unless someone knows another way this can be done ) My only solution I could come up with is a very ugly while loop that is n't working properly , I have been getting a `` Jayrock.Json.JsonException : A JSON member value inside a JSON object must be preceded by its member name '' exception . Here is the while loop I wrote ( not my best code , I know ) : My question is , since I ca n't use .load ( ) and my while loop is a mess to debug , what would be the best approach here ? The other approach commonly discussed is deserialization into an Object with matching variables but I have a rather large XML coming out of SQL Server . My loop is an attempt at dynamic programming since there are ~200 fields that are being pulled to make this XML.Note : I am using Jayrock and working in .Net Framework 2.0 . I can not change the framework version at this time . [ SqlProcedure ] public static void Receipt ( SqlString initiatorPassword , SqlString initiatorId , SqlXml XMLOut , out SqlString strMessge ) XmlReader r = ( XmlReader ) XmlOut.CreateReader ( ) ; XmlDocument doc = new XmlDocument ( ) ; doc.load ( r ) ; int lastdepth = -1 ; Boolean objend = true ; Boolean wt = false ; //Write Member/Object statements for the header omittedJsonWriter w = new JsonTextWriter ( ) while ( m.Read ( ) ) { if ( ( lastdepth == -1 ) & & ( m.IsStartElement ( ) ) ) { //Checking for root element lastdepth = 0 ; } if ( ( m.IsStartElement ( ) ) & & ( lastdepth ! = -1 ) ) { //Checking for Start element ( < html > ) w.WriteMember ( m.Name ) ; if ( objend ) { //Check if element is new Parent Node , if so , write start object w.WriteStartObject ( ) ; objend = false ; } } if ( m.NodeType == XmlNodeType.Text ) { //Writes text here . NOTE : m.Depth > lastdepth here ! ! ! ! ! ! ! w.WriteString ( m.Value ) ; wt = true ; } if ( m.NodeType == XmlNodeType.Whitespace ) //If whitespace , keep on truckin { m.Skip ( ) ; } if ( ( m.NodeType == XmlNodeType.EndElement ) & & ( wt == false ) & & ( lastdepth > m.Depth ) ) { //End element that ends a series of `` Child '' nodes w.WriteEndObject ( ) ; objend = true ; } if ( ( m.NodeType == XmlNodeType.EndElement ) & & ( wt == true ) ) //Standard end of an el { wt = false ; } lastdepth = m.Depth ; } w.WriteEndObject ( ) ; jout = w.ToString ( ) ; }",Deserializing XML into JSON without using XmlDocument.Loadxml ( ) function "C_sharp : I will be working with approximately 320,000,000 data points for a high-resolution waveform . Each data point will require 2 floats ( XY coordinate ) for a total of 8 bytes.In order to have this memory allocated all at once , I was planning on using a struct such as the following : Since a struct is a value type , I am assuming that it consumes only the amount of memory necessary for each variable , as well as some small , fixed amount used by the CLR ( Common Language Runtime ) .Is there a way I can compute how much memory a struct will use during runtime of my application ? That is , granted I know the following : How many variables are in the struct.How many bytes are used for each variable.How many instances of the struct will be alive at a given point in time . public struct Point { public float X ; //4-bytes public float Y ; //4-bytes . }","In C # , how much memory does a struct require ?" "C_sharp : BackgroundThis question got me thinking about something . Lately , since I 've been looking at linq pad 's IL functionality , I 've been comparing the IL code of two approaches to the same problem to `` determine '' which is best.Using the question linked to above , about converting an array , I generated the IL code for the two answers : produced : and the other answer : produced : Looking at this , all I can tell is that the latter optiontakes 1 extra lineuses linq when the 1st answer does n't creates the Int 's differently via IL_0039.QuestionsFor this specific example , are my assumptions correct ? In general , how should I go about comparing two solutions via IL code ? In general , does a solution with fewer IL LOC mean that it will be faster or use less memory ? As the title says , Can I compare IL code to determine which technique is faster or better ? FWIW , I do n't do this often , just every once in a rare while when some discussion comes up amongst developers at work . Someone will say `` oh this is more efficient '' and we 'll throw it into linqpad to check out the IL code . Also FWIW , I almost always abide by the getting it working before getting it efficient/fast approach . Just so people do n't think I 'm constantly comparing IL code of what I 'm developing : ) var arr = new string [ ] { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } ; var result = Array.ConvertAll ( arr , s = > Int32.Parse ( s ) ) ; IL_0001 : ldc.i4.4 IL_0002 : newarr System.StringIL_0007 : stloc.2 IL_0008 : ldloc.2 IL_0009 : ldc.i4.0 IL_000A : ldstr `` 1 '' IL_000F : stelem.ref IL_0010 : ldloc.2 IL_0011 : ldc.i4.1 IL_0012 : ldstr `` 2 '' IL_0017 : stelem.ref IL_0018 : ldloc.2 IL_0019 : ldc.i4.2 IL_001A : ldstr `` 3 '' IL_001F : stelem.ref IL_0020 : ldloc.2 IL_0021 : ldc.i4.3 IL_0022 : ldstr `` 4 '' IL_0027 : stelem.ref IL_0028 : ldloc.2 IL_0029 : stloc.0 IL_002A : ldloc.0 IL_002B : ldsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate1IL_0030 : brtrue.s IL_0045IL_0032 : ldnull IL_0033 : ldftn b__0IL_0039 : newobj System.Converter < System.String , System.Int32 > ..ctorIL_003E : stsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate1IL_0043 : br.s IL_0045IL_0045 : ldsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate1IL_004A : call System.Array.ConvertAllIL_004F : stloc.1 b__0 : IL_0000 : ldarg.0 IL_0001 : call System.Int32.ParseIL_0006 : stloc.0 IL_0007 : br.s IL_0009IL_0009 : ldloc.0 IL_000A : ret var arr = new string [ ] { `` 1 '' , `` 2 '' , `` 3 '' , `` 4 '' } ; var result = arr.Select ( s = > int.Parse ( s ) ) .ToArray ( ) ; IL_0001 : ldc.i4.4 IL_0002 : newarr System.StringIL_0007 : stloc.2 IL_0008 : ldloc.2 IL_0009 : ldc.i4.0 IL_000A : ldstr `` 1 '' IL_000F : stelem.ref IL_0010 : ldloc.2 IL_0011 : ldc.i4.1 IL_0012 : ldstr `` 2 '' IL_0017 : stelem.ref IL_0018 : ldloc.2 IL_0019 : ldc.i4.2 IL_001A : ldstr `` 3 '' IL_001F : stelem.ref IL_0020 : ldloc.2 IL_0021 : ldc.i4.3 IL_0022 : ldstr `` 4 '' IL_0027 : stelem.ref IL_0028 : ldloc.2 IL_0029 : stloc.0 IL_002A : ldloc.0 IL_002B : ldsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate1IL_0030 : brtrue.s IL_0045IL_0032 : ldnull IL_0033 : ldftn b__0IL_0039 : newobj System.Func < System.String , System.Int32 > ..ctorIL_003E : stsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate1IL_0043 : br.s IL_0045IL_0045 : ldsfld UserQuery.CS $ < > 9__CachedAnonymousMethodDelegate1IL_004A : call System.Linq.Enumerable.SelectIL_004F : call System.Linq.Enumerable.ToArrayIL_0054 : stloc.1 b__0 : IL_0000 : ldarg.0 IL_0001 : call System.Int32.ParseIL_0006 : stloc.0 IL_0007 : br.s IL_0009IL_0009 : ldloc.0 IL_000A : ret",Can I compare IL code to determine which technique is faster or better ? "C_sharp : I have the following method in my BaseApiController class : I 'm using SingleResult for OData request ( because $ expand for single entity not works if I not create SingleResult ) . But now I have problem with UnitTests of this method on concrete controller ( e.g . AddressApiController ) . I always get NULL in result : I checked and debug GetById ( ) and find out that repository.Table.Where ( t = > t.ID == id ) ) return proper value , but after SingleResult.Create I 'm getting NULL . How can I solve this problem ? How can I read content from SingleResult or using something else ? public virtual HttpResponseMessage GetById ( int id ) { var entity = repository.GetById ( id ) ; if ( entity == null ) { var message = string.Format ( `` No { 0 } with ID = { 1 } '' , GenericTypeName , id ) ; return ErrorMsg ( HttpStatusCode.NotFound , message ) ; } return Request.CreateResponse ( HttpStatusCode.OK , SingleResult.Create ( repository.Table.Where ( t = > t.ID == id ) ) ) ; } [ TestMethod ] public void Get_By_Id ( ) { //Arrange var moq = CreateMockRepository ( ) ; var controller = new AddressApiController ( moq ) ; controller.Request = new HttpRequestMessage ( ) controller.Request.SetConfiguration ( new HttpConfiguration ( ) ) // Action HttpResponseMessage response = controller.GetById ( 1 ) ; var result = response.Content.ReadAsAsync < T > ( ) .Result ; // Accert Assert.IsNotNull ( result ) ; }",SingleResult and UnitTesting "C_sharp : First of all I 'm ashamed of myself for not being able to grasp the essence of MVVM patern after such a long struggle , and I ca n't help but to ask.I searched and searched about MVVM but the layers that has been ( seems to ) clear to me is only the View and ViewModel layer.So here is what I have been grasping until now with some little example , FYI I 'm using MySQL queries to fetch my data : ModelIt 's unclear to me what to do here . I have this class of Employee.cs : My question : Should I do the queries to fetch data from MySQL database in EmployeeModel class ? I read about this answer that Data Access layer is a different thing than MVVM 's Model , plus I can use a repository to request a list of Employees from my Data Access layer.Based on that answer then it should be like : Employee.cs [ Object properties definition ] , EmployeeDataAccess.cs [ Responsible to fetching Employee ( s ) data from MySQL ] EmployeeRepository.cs [ Called by EmployeeModel to get Employee data from DA ] EmployeeModel.cs [ Where I handle business logic like validation etc and use INotifyPropertyChanged on pretty much same properties as Employee.cs ] EmployeeViewModel.cs [ EmployeeView 's data context ] EmployeeView.cs [ XAML ] All of that for one page of Employee list , am I doing something wrong ? Sorry for the long question , if I said something wrong I would be more than glad to fix it.I 'm really clueless at the moment , so any fresh perspective is greatly appreciated . class Employee { public string Id { get ; set ; } public string Name { get ; set ; } public string Gender { get ; set ; } }",MVVM Roles for each layer "C_sharp : I need to retrieve the name of a single view inside a views\something folder ( comes from request ) within MVC 4.0 and I 'm not sure of how best to do it . My code works but it has a 'hacky ' feel to it and I was hoping someone could be simplified.My code looks like : Is there a more elegant way to achieve this ? private FileInfo GetNameOfViewToServe ( ) { var LeftPartOfUri = Request.Url.GetLeftPart ( UriPartial.Authority ) ; var folder = Request.Url.AbsoluteUri.Replace ( LeftPartOfFolderUri , string.Empty ) ; var directory = new DirectoryInfo ( Server.MapPath ( @ '' ~\Views\ '' + folder ) ) ; return directory.GetFiles ( ) .First ( ) ; }",Get file inside views folder in ASP.Net MVC 4.0 "C_sharp : I have this JSON : -Which I 'm deserialising using this object : -The SearchResponse itself is interpreted fine ( yay ! ) but the Search Result child object is incorrect - it looks just like the top level SearchResponse.Here 's what the following log lines give me : -This log output : -Anyone have an idea how to fix it ? Thanks in advance . { `` snippet-format '' : '' raw '' , '' total '' :1 , '' start '' :1 , '' page-length '' :200 , '' results '' : [ { `` index '' :1 , '' uri '' : '' /myproject/info.xml '' , '' path '' : '' fn : doc ( \ '' /myproject/info.xml\ '' ) '' , '' score '' :0 , '' confidence '' :0 , '' fitness '' :0 , '' content '' : '' < root xmlns : xs=\ '' http : //www.w3.org/2001/XMLSchema\ '' xmlns=\ '' \ '' xmlns : search=\ '' http : //marklogic.com/appservices/search\ '' > < content > Adams Project file < /content > < /root > '' } ] , '' facets '' : { `` lastmodified '' : { `` type '' : '' xs : dateTime '' , '' facetValues '' : [ ] } } , '' metrics '' : { `` query-resolution-time '' : '' PT0.002559S '' , '' facet-resolution-time '' : '' PT0.00111S '' , '' snippet-resolution-time '' : '' PT0.000043S '' , '' total-time '' : '' PT0.0039S '' } } public class SearchResponse : MarkLogicObject { // response fields public string SnippetFormat { get ; set ; } public int Total { get ; set ; } public int Start { get ; set ; } public int PageLength { get ; set ; } public SearchResult [ ] Results { get ; set ; } public string Warning { get ; set ; } public override string ToString ( ) { return `` SnippetFormat : `` + SnippetFormat + `` , Total : `` + Total + `` , Start : `` + Start + `` , Warning : `` + Warning ; } public static SearchResponse ParseJson ( string json ) { var map = JsonObject.Parse ( json ) ; return new SearchResponse { Total = int.Parse ( map [ `` total '' ] ) , Start = int.Parse ( map [ `` start '' ] ) , PageLength = int.Parse ( map [ `` page-length '' ] ) , SnippetFormat = map [ `` snippet-format '' ] , Warning = map [ `` warning '' ] , Results = map [ `` results '' ] .FromJson < SearchResult [ ] > ( ) // why does n't this deserialise properly ? It creates a SearchResponse object mirroring this one instead . } ; } } // Sub elements of SearchResponsepublic class SearchResult { public string Uri { get ; set ; } public long Index { get ; set ; } public string Path { get ; set ; } public double Score { get ; set ; } public double Fitness { get ; set ; } public double Confidence { get ; set ; } public string Content { get ; set ; } // JSON or XML content ( probably XML , no matter what ? format=json says ) public override string ToString ( ) { return string.Format ( `` [ SearchResult : Uri= { 0 } , Index= { 1 } , Path= { 2 } , Score= { 3 } , Fitness= { 4 } , Confidence= { 5 } , Content= { 6 } ] '' , Uri , Index , Path , Score , Fitness , Confidence , Content ) ; } } HttpWebResponse webResponse = restClient.Get < HttpWebResponse > ( completePath ( `` /v1/search '' , qp ) ) ; using ( var stream = webResponse.GetResponseStream ( ) ) using ( var sr = new StreamReader ( stream ) ) { var text = sr.ReadToEnd ( ) ; log.log ( `` response text : `` + text ) ; result = text.FromJson < SearchResponse > ( ) ; } log.log ( `` RESULT : `` + result.ToString ( ) ) ; for ( int i = 0 ; i < result.Results.Length ; i++ ) { log.log ( `` Result `` + i + `` : `` + result.Results [ i ] .ToString ( ) ) ; } 19:30:24 | SparkleMLLogger | RESULT : SnippetFormat : raw , Total : 1 , Start : 1 , Warning : 19:30:24 | SparkleMLLogger | Result : SnippetFormat : raw , Total : 1 , Start : 1 , Warning :",Incorrect array deserialisation in ServiceStack.Text "C_sharp : I ran across a compilation issue today that baffled me . Consider these two container classes.The former defines DoStuff ( T item ) and the latter overloads it with DoStuff < Tother > ( IEnumerable < Tother > ) specifically to get around the absence of covariance/contravariance of C # ( until 4 I hear ) .This codehits a rather strange compilation error . Note the absence of < char > from the method call . The type 'char ' can not be used as type parameter 'Tother ' in the generic type or method 'Container.DoStuff ( System.Collections.Generic.IEnumerable ) ' . There is no boxing conversion from 'char ' to 'string'.Essentially , the compiler is trying to jam my call to DoStuff ( string ) into Container.DoStuff < char > ( IEnumerable < char > ) because string implements IEnumerable < char > , rather than use BaseContainer.DoStuff ( string ) .The only way I 've found to make this compile is to add DoStuff ( T ) to the derived classWhy is the compiler trying to jam a string as IEnumerable < char > when 1 ) it knows it ca n't ( given the presence of a compilation error ) and 2 ) it has a method in the base class that compiles fine ? Am I misunderstanding something about generics or virtual method stuff in C # ? Is there another fix other than adding a new DoStuff ( T item ) to Container ? public class BaseContainer < T > : IEnumerable < T > { public void DoStuff ( T item ) { throw new NotImplementedException ( ) ; } public IEnumerator < T > GetEnumerator ( ) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ( ) { } } public class Container < T > : BaseContainer < T > { public void DoStuff ( IEnumerable < T > collection ) { } public void DoStuff < Tother > ( IEnumerable < Tother > collection ) where Tother : T { } } Container < string > c = new Container < string > ( ) ; c.DoStuff ( `` Hello World '' ) ; public class Container < T > : BaseContainer < T > { public new void DoStuff ( T item ) { base.DoStuff ( item ) ; } public void DoStuff ( IEnumerable < T > collection ) { } public void DoStuff < Tother > ( IEnumerable < Tother > collection ) where Tother : T { } }","Generics , inheritance , and failed method resolution of C # compiler" "C_sharp : If one loops through an XmlNodeList like thiseverything works as expected - foo is clearly of type XmlNode and the VS.NET IDE shows methods and fields.On the other hand is not compiling because here foo is of type object . Type inference sort of works but infers object.Apparently , the elements of XmlNodeList are not of one defined type , but assigning them to XmlNode instead of var does something implicitly ( casting or unboxing ) . First question : what 's the mechanism behind that ? Second ( related ) question : how to find the types one can use in this kind of loop ? Does the VS.NET IDE help ? foreach ( XmlNode foo in xmlNodeList ) { string baa = foo.Attributes [ `` baa '' ] .Value ; } foreach ( var foo in xmlNodeList ) { string baa = foo.Attributes [ `` baa '' ] .Value ; }",Why does var infer type object and not XmlNode in XmlNodeList loop ? "C_sharp : I decided to try out LINQ for the first time to try and solve this question.The results of my first foray into the wonderful world of LINQ looked like this : I 'd like to know how I can improve the above solution to this contrived little example . I 'm not too interested in whether I 've used the best validation method , or how I could localise `` Press Enter '' or anything like that ; I 'm just interested in using this example to learn a little more about LINQ . using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ConsoleApplication2 { class Program { static void Main ( string [ ] args ) { List < string > list = new List < string > ( ) { `` fred-064528-NEEDED1 '' , `` xxxx '' , `` frederic-84728957-NEEDED2 '' , `` sam-028-NEEDED3 '' , `` -- -- - '' , `` another-test '' } ; var result = from s in list where ( from c in s where c == '- ' select c ) .Count ( ) == 2 select s.Substring ( s.LastIndexOf ( `` - '' ) + 1 ) ; foreach ( string s in result ) Console.WriteLine ( s ) ; Console.WriteLine ( `` Press Enter '' ) ; Console.ReadLine ( ) ; } } }",Pimp my LINQ : a learning exercise based upon another post "C_sharp : We 're modelling a complicated system based around a complicated entity relationship in Dynamics CRM 4.0Due to the nature of development we 've had to implement a repository style pattern and have lots of different providers that relate to each other.What I really want to do is to profile their constructors and various lazy getters , but I want to model this at the top level possible.The problem is , of course , Scope - If I wrap the constructor in a using block , it 's not available to anything else . If I extend the using block so that everything that references the object I 'm profiling comes into scope , then the profiler is n't just profiling the constructor - it 's timing everything else.Similarly , there 's a level of nesting , If I nest the usings correctly , then the code becomes unreadable.I 've had a look at Profiler.Inline but that does n't serve my purposes.What I 'd really like to do is this : Does that make sense ? Hopefully I 'm overlooking something in Mini Profiler , but I 'd welcome any suggestions ! I would like to remodel the code a bit , but there is no time for that and whilst it looks odd , we actually have a pretty good cyclomatic complexity . ref = Profiler.StartStep ( `` Creating CRM Model '' ) ; //Do horrible CRM workvar myNewHorribleObject = CRM.ModelHorribleStuff ( ... ) ; Profiler.StopStep ( ref ) ; ref = Profiler.StartStep ( `` How long does it take to get X '' ) ; var data = Repository.GetSomething ( myNewHorribleObject.SomeId ) ; Profiler.StopStep ( ref ) ; ref = Profiler.StartStep ( `` How long does it take to get Y '' ) ; var newData = Repository.GetSomethingElse ( myNewHorribleObject.ContextId ) ; Profiler.StopStep ( ref ) ;",Stepping MVC Mini Profiler without nested usings "C_sharp : Can you create a delegate of an instance method without specifying the instance at creation time ? In other words , can you create a `` static '' delegate that takes as it 's first parameter the instance the method should be called on ? For example , how can I construct the following delegate using reflection ? I 'm aware of the fact that I can use methodInfo.Invoke , but this is slower , and does not check for type-correctness until it is called.When you have the MethodInfo of a particular static method , it is possible to construct a delegate using Delegate.CreateDelegate ( delegateType , methodInfo ) , and all parameters of the static method remain free.As Jon Skeet pointed out , you can simply apply the same to make an open delegate of an instance method if the method is non-virtual on a reference type . Deciding which method to call on a virtual method is tricky , so that 's no so trivial , and value-types look like they do n't work at all.For value types , CreateDelegate exhibits really weird behavior : Calling CreateDelegate with null as the target object throws a binding exception if the instance method belonged to a value type ( this works for reference types ) .Some follow-up years later : The incorrectly-bound target that caused func42 ( CultureInfo.InvariantCulture ) ; to return `` -201040128 '' instead of `` 42 '' in my example was memory corruption that could have allowed remote code execution ( cve-2010-1898 ) ; this was fixed in 2010 in the ms10-060 security update . Current frameworks correctly print 42 ! That does n't make answering this question any easier , but explains the particularly weird behavior in the example . Func < int , string > = i= > i.ToString ( ) ; var func37 = ( Func < CultureInfo , string > ) ( 37.ToString ) ; var toStringMethod = typeof ( int ) .GetMethod ( `` ToString '' , BindingFlags.Instance | BindingFlags.Public , null , new Type [ ] { typeof ( CultureInfo ) } , null ) ; var func42 = ( Func < CultureInfo , string > ) Delegate.CreateDelegate ( typeof ( Func < CultureInfo , string > ) , 42 , toStringMethod , true ) ; Console.WriteLine ( object.ReferenceEquals ( func37.Method , func42.Method ) ) ; //trueConsole.WriteLine ( func37.Target ) ; //37Console.WriteLine ( func42.Target ) ; //42Console.WriteLine ( func37 ( CultureInfo.InvariantCulture ) ) ; //37Console.WriteLine ( func42 ( CultureInfo.InvariantCulture ) ) ; //-201040128 ... WTF ?",`` Uncurrying '' an instance method in .NET "C_sharp : I was using LinqPad to test out some Enum functions and I did n't get integers like I expected when I used .Dump ( ) . Why did the ToList ( ) solve the problem ? void Main ( ) { Enum.GetValues ( typeof ( Options ) ) .Cast < int > ( ) .Dump ( ) ; Enum.GetValues ( typeof ( Options ) ) .Cast < int > ( ) .ToList ( ) .Dump ( ) ; } public enum Options { Equal , LessThan , GreaterThan }",Why does LINQPad dump enum integer values as strings ? "C_sharp : I 'm trying to add my first EF Core 2 migration . I had EF6 migrations running for the solution , but now I 've migrated to EF Core 2 and .Net Core 2.0 . When I run this command : I get this exception : I 'm running the command from the package manager console in Visual Studio 2017 v15.3 on Windows 10 . I get the same message when trying to run it from the windows command line . The startup project as well as the default project is set to a class library that contains the database context class . This is the .csproj project file for the project : Any idea on what I 'm doing wrong or how I can troubleshoot the issue ? dotnet ef migrations add InitialMigration System.IO.FileNotFoundException : Could not load file or assembly 'netstandard , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=cc7b13ffcd2ddd51 ' . The system can not find the file specified.File name : 'netstandard , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=cc7b13ffcd2ddd51 ' at System.Reflection.RuntimeAssembly.GetType ( RuntimeAssembly assembly , String name , Boolean throwOnError , Boolean ignoreCase , ObjectHandleOnStack type , ObjectHandleOnStack keepAlive ) at System.Reflection.RuntimeAssembly.GetType ( String name , Boolean throwOnError , Boolean ignoreCase ) at Microsoft.EntityFrameworkCore.Tools.ReflectionOperationExecutor..ctor ( String assembly , String startupAssembly , String projectDir , String contentRootPath , String dataDirectory , String rootNamespace , String environment ) at Microsoft.EntityFrameworkCore.Tools.Commands.ProjectCommandBase.CreateExecutor ( ) at Microsoft.EntityFrameworkCore.Tools.Commands.MigrationsListCommand.Execute ( ) at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute ( String [ ] args ) at Microsoft.EntityFrameworkCore.Tools.Program.Main ( String [ ] args ) Could not load file or assembly 'netstandard , Version=2.0.0.0 , Culture=neutral , PublicKeyToken=cc7b13ffcd2ddd51 ' . The system can not find the file specified . < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < TargetFramework > netcoreapp2.0 < /TargetFramework > < /PropertyGroup > < ItemGroup > < PackageReference Include= '' Analytics '' Version= '' 3.0.0 '' / > < PackageReference Include= '' AWSSDK.Core '' Version= '' 3.3.17.6 '' / > < PackageReference Include= '' AWSSDK.S3 '' Version= '' 3.3.10.2 '' / > < PackageReference Include= '' CoreCompat.System.Drawing.v2 '' Version= '' 5.2.0-preview1-r131 '' / > < PackageReference Include= '' HtmlAgilityPack '' Version= '' 1.5.1 '' / > < PackageReference Include= '' ImageProcessor '' Version= '' 2.5.4 '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.SqlServer '' Version= '' 2.0.0 '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.SqlServer.Design '' Version= '' 2.0.0-preview1-final '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.Tools '' Version= '' 2.0.0 '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.Tools.DotNet '' Version= '' 2.0.0 '' / > < PackageReference Include= '' Newtonsoft.Json '' Version= '' 10.0.3 '' / > < PackageReference Include= '' NLog.Extensions.Logging '' Version= '' 1.0.0-rtm-beta5 '' / > < PackageReference Include= '' QRCoder '' Version= '' 1.2.9 '' / > < PackageReference Include= '' System.Configuration.ConfigurationManager '' Version= '' 4.4.0 '' / > < PackageReference Include= '' WindowsAzure.Storage '' Version= '' 8.4.0 '' / > < /ItemGroup > < ItemGroup > < DotNetCliToolReference Include= '' Microsoft.EntityFrameworkCore.Tools.DotNet '' Version= '' 1.0.0 '' / > < /ItemGroup > < /Project >",Trying to get ef core migrations to work on project migrated to .net core 2 "C_sharp : ( Note : This sample code requires C # 7.2 or later , and the Nuget System.Memory package . ) Let 's suppose we have a readonly struct as follows : Now let 's put it into an array : So far so good . You can not write code to modify array [ 0 ] .Value directly.Now suppose we do this : So now we 've modified the Value component of the readonly struct in the array.Is this behaviour correct ? public readonly struct Test { public Test ( int value ) { Value = value ; } public int Value { get ; } } var array = new Test [ ] { new Test ( 1 ) } ; Console.WriteLine ( array [ 0 ] .Value ) ; // Prints 1 array.AsSpan ( ) .AsBytes ( ) [ 3 ] = 1 ; Console.WriteLine ( array [ 0 ] .Value ) ; // Prints 16777217",Are readonly structs supposed to be immutable when in an array ? "C_sharp : I am trying to bind my kendo multiselect to a property in a model using mvc 5 however all i get is a list of undefined elements . The list is correct at the controller level and looking at the source code the list is correct there but I can not visualize the list.What is also puzzling is that there are more undefined elements in the list then items the actual list in the model.Can anyone explain what is going on or show me how to go about debugging and fixing the issues I am having.Model : Controller : View : On a slightly separate note why does my standard validation using the model always return true ? ? Thank you for any help and advice on these issues.EDITSource code [ Required ] public SelectList hierarchy { get ; set ; } public virtual IEnumerable < SelectListItem > Hierarchy { get { var hierarchies = new List < Company > ( ) ; hierarchies = RoleCompanyHelper.GetHierachies ( ) ; var hierarchiesList = new List < SelectListItem > ( ) ; foreach ( var hierarchy in hierarchies ) { hierarchiesList.Add ( new SelectListItem { Value = hierarchy.CompanyID.ToString ( ) , Text = hierarchy.CompanyName } ) ; } return new SelectList ( hierarchiesList , `` Value '' , `` Text '' ) ; } } public ActionResult Index ( ) { var vm = new AXCurrentRolesViewModel ( ) ; return View ( vm ) ; } @ model TelerikMvcApp1.Models.AXCurrentRolesViewModel @ ( Html.Kendo ( ) .MultiSelect ( ) .Name ( `` addRoleCompany_hierarchy '' ) .BindTo ( new SelectList ( `` Value '' , `` Text '' ) ) .Value ( Model.hierarchy ) .DataTextField ( `` HierarchyName '' ) .DataValueField ( `` HierarchyID '' ) .Placeholder ( `` Select Hierarchy ... '' ) .Filter ( FilterType.StartsWith ) .AutoBind ( false ) ) < select id= '' addRoleCompany_hierarchy '' multiple= '' multiple '' name= '' addRoleCompany_hierarchy '' > < /select > < script > jQuery ( function ( ) { jQuery ( `` # addRoleCompany_hierarchy '' ) .kendoMultiSelect ( { `` dataSource '' : [ { `` Text '' : '' All Companies Inc IFRS \u0026 Consol '' , '' Value '' : '' 55 '' } , { `` Text '' : '' All Posting Companies ( exc POC \u0026 Investments ) '' , '' Value '' : '' 56 '' } , { `` Text '' : '' BUUK Group Structure '' , '' Value '' : '' 57 '' } , { `` Text '' : '' Cardiff Entities '' , '' Value '' : '' 58 '' } , { `` Text '' : '' Department '' , '' Value '' : '' 59 '' } , { `` Text '' : '' GTC/GPL/ENC/IPL/QPL/EAM '' , '' Value '' : '' 60 '' } , { `` Text '' : '' GTC/GUC/CUL '' , '' Value '' : '' 61 '' } , { `` Text '' : '' GTCConsoleAndOperationalCompanies '' , '' Value '' : '' 62 '' } , { `` Text '' : '' GTCOperationalCompanies '' , '' Value '' : '' 63 '' } , { `` Text '' : '' Inexus Companies '' , '' Value '' : '' 64 '' } , { `` Text '' : '' Investment Companies Only '' , '' Value '' : '' 65 '' } , { `` Text '' : '' PIL/POL '' , '' Value '' : '' 66 '' } ] , '' dataTextField '' : '' HierarchyName '' , '' filter '' : '' startswith '' , '' autoBind '' : fal se , `` dataValueField '' : '' HierarchyID '' , '' placeholder '' : '' Select Hierarchy ... '' } ) ; } ) ; < /script >",Using an MVC model to populate and validate a kendo multiselect ? "C_sharp : I 'm trying to use Visual Studio 2012 to create a Windows Forms application that can place the caret at the current position within a owner-drawn string . However , I 've been unable to find a way to accurately calculate that position.I 've done this successfully before in C++ . I 've tried numerous methods in C # but have not yet been able to position the caret accurately . Originally , I tried using .NET classes to determine the correct position , but then I tried accessing the Windows API directly . In some cases , I came close , but after some time I still can not place the caret accurately.I 've created a small test program and posted key parts below . I 've also posted the entire project here.The exact font used is not important to me ; however , my application assumes a mono-spaced font . Any help is appreciated.Form1.csThis is my main form.Windows.csHere are my Windows API declarations.EditThe code I 've posted has an issue that makes it even more inaccurate . This is a result of trying many different approaches , some more accurate than this . What I 'm looking for is a fix that makes it `` fully accurate '' , as it is in my MFC Hex Editor Control in C++ . public partial class Form1 : Form { private string TestString ; private int AveCharWidth ; private int Position ; public Form1 ( ) { InitializeComponent ( ) ; TestString = `` 123456789012345678901234567890123456789012345678901234567890 '' ; AveCharWidth = GetFontWidth ( ) ; Position = 0 ; } private void Form1_Load ( object sender , EventArgs e ) { Font = new Font ( FontFamily.GenericMonospace , 12 , FontStyle.Regular , GraphicsUnit.Pixel ) ; } protected override void OnGotFocus ( EventArgs e ) { Windows.CreateCaret ( Handle , ( IntPtr ) 0 , 2 , ( int ) Font.Height ) ; Windows.ShowCaret ( Handle ) ; UpdateCaretPosition ( ) ; base.OnGotFocus ( e ) ; } protected void UpdateCaretPosition ( ) { Windows.SetCaretPos ( Padding.Left + ( Position * AveCharWidth ) , Padding.Top ) ; } protected override void OnLostFocus ( EventArgs e ) { Windows.HideCaret ( Handle ) ; Windows.DestroyCaret ( ) ; base.OnLostFocus ( e ) ; } protected override void OnPaint ( PaintEventArgs e ) { e.Graphics.DrawString ( TestString , Font , SystemBrushes.WindowText , new PointF ( Padding.Left , Padding.Top ) ) ; } protected override bool IsInputKey ( Keys keyData ) { switch ( keyData ) { case Keys.Right : case Keys.Left : return true ; } return base.IsInputKey ( keyData ) ; } protected override void OnKeyDown ( KeyEventArgs e ) { switch ( e.KeyCode ) { case Keys.Left : Position = Math.Max ( Position - 1 , 0 ) ; UpdateCaretPosition ( ) ; break ; case Keys.Right : Position = Math.Min ( Position + 1 , TestString.Length ) ; UpdateCaretPosition ( ) ; break ; } base.OnKeyDown ( e ) ; } protected int GetFontWidth ( ) { int AverageCharWidth = 0 ; using ( var graphics = this.CreateGraphics ( ) ) { try { Windows.TEXTMETRIC tm ; var hdc = graphics.GetHdc ( ) ; IntPtr hFont = this.Font.ToHfont ( ) ; IntPtr hOldFont = Windows.SelectObject ( hdc , hFont ) ; var a = Windows.GetTextMetrics ( hdc , out tm ) ; var b = Windows.SelectObject ( hdc , hOldFont ) ; var c = Windows.DeleteObject ( hFont ) ; AverageCharWidth = tm.tmAveCharWidth ; } catch { } finally { graphics.ReleaseHdc ( ) ; } } return AverageCharWidth ; } } public static class Windows { [ Serializable , StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Auto ) ] public struct TEXTMETRIC { public int tmHeight ; public int tmAscent ; public int tmDescent ; public int tmInternalLeading ; public int tmExternalLeading ; public int tmAveCharWidth ; public int tmMaxCharWidth ; public int tmWeight ; public int tmOverhang ; public int tmDigitizedAspectX ; public int tmDigitizedAspectY ; public short tmFirstChar ; public short tmLastChar ; public short tmDefaultChar ; public short tmBreakChar ; public byte tmItalic ; public byte tmUnderlined ; public byte tmStruckOut ; public byte tmPitchAndFamily ; public byte tmCharSet ; } [ DllImport ( `` user32.dll '' ) ] public static extern bool CreateCaret ( IntPtr hWnd , IntPtr hBitmap , int nWidth , int nHeight ) ; [ DllImport ( `` User32.dll '' ) ] public static extern bool SetCaretPos ( int x , int y ) ; [ DllImport ( `` User32.dll '' ) ] public static extern bool DestroyCaret ( ) ; [ DllImport ( `` User32.dll '' ) ] public static extern bool ShowCaret ( IntPtr hWnd ) ; [ DllImport ( `` User32.dll '' ) ] public static extern bool HideCaret ( IntPtr hWnd ) ; [ DllImport ( `` gdi32.dll '' , CharSet = CharSet.Auto ) ] public static extern bool GetTextMetrics ( IntPtr hdc , out TEXTMETRIC lptm ) ; [ DllImport ( `` gdi32.dll '' ) ] public static extern IntPtr SelectObject ( IntPtr hdc , IntPtr hgdiobj ) ; [ DllImport ( `` GDI32.dll '' ) ] public static extern bool DeleteObject ( IntPtr hObject ) ; }",Unable to Calculate Position within Owner-Draw Text "C_sharp : I want to see how the method that is inside mscorlib.dll ( System.String ) works.I decompiled the mscorlib.dll with dotPeek and inside the method there is a call to ReplaceInternal method which I can not find it I have search for this method even on the open source .NET Core from GIT but no luck.Please explain where is this method and what is inside ? public String Replace ( String oldValue , String newValue ) ; string s = ReplaceInternal ( oldValue , newValue ) ;",decompile .NET Replace method ( v4.6.1 ) "C_sharp : Here are the steps to reproduce . The below program copies 10,000 rows from one SQL table to another using .Net Core console app and EF Core . The program inserts records in 100 batches , and ( this is important ! ) it creates a new instance of DbContext for each insert.1 ) Create SQL Server database , and the `` Froms '' and `` Tos '' tables:2 ) Populate the `` Froms '' table:3 ) Create .Net Core console app project with the name TestForEachAsync . Change version of C # to 7.1 or later ( required for async Main ) . Add Microsoft.EntityFrameworkCore.SqlServer nuget package.4 ) Create classes : Database entitiesDbContextMain5 ) Run the app - you get an exception The connection does not support MultipleActiveResultSets . Looks like multiple operations are being started on insertContext , though I do not see why.6 ) I found two ways to fix the issue : Replace the await froms.ForEachAsync ( ... ) loop with `` normal '' loop foreach ( var f in froms ) { ... } , orInside the async loop , replace await saveChangesTask ; with saveChangesTask.Wait ( ) ; But can someone explain please why the original code does not work as I expect ? Note : if you run the app multiple times , do not forget to truncate the `` Tos '' table before each run . create table Froms ( Id int identity ( 1 , 1 ) not null , Guid [ uniqueidentifier ] not null , constraint [ PK_Froms ] primary key clustered ( Id asc ) ) gocreate table Tos ( Id int not null , Guid [ uniqueidentifier ] not null , constraint [ PK_Tos ] primary key clustered ( Id asc ) ) go set nocount ondeclare @ i int = 0while @ i < 10000begin insert Froms ( Guid ) values ( newid ( ) ) set @ i += 1endgo using System ; namespace TestForEachAsync { public class From { public int Id { get ; set ; } public Guid Guid { get ; set ; } } } using System ; namespace TestForEachAsync { public class To { public int Id { get ; set ; } public Guid Guid { get ; set ; } } } using Microsoft.EntityFrameworkCore ; namespace TestForEachAsync { public class Context : DbContext { public DbSet < From > Froms { get ; set ; } public DbSet < To > Tos { get ; set ; } protected override void OnConfiguring ( DbContextOptionsBuilder optionsBuilder ) { optionsBuilder.UseSqlServer ( `` YOUR_CONNECTION_STRING '' ) ; } } } using System ; using System.Linq ; using System.Threading.Tasks ; using Microsoft.EntityFrameworkCore ; namespace TestForEachAsync { internal class Program { private static async Task Main ( string [ ] args ) { //Get the `` froms '' var selectContext = new Context ( ) ; var froms = selectContext.Froms.Select ( f = > new { f.Id , f.Guid } ) ; int count = 0 ; Task < int > saveChangesTask = null ; Context insertContext = new Context ( ) ; Context prevInsertContext = null ; //Iterate through `` froms '' await froms.ForEachAsync ( async f = > { //Add instace of `` to '' to the context var to = new To { Id = f.Id , Guid = f.Guid } ; await insertContext.Tos.AddAsync ( to ) ; count++ ; //If another 100 of `` to '' s has been added to the context ... if ( count % 100 == 0 ) { //Wait for the previous 100 `` to '' s to finish saving to the database if ( saveChangesTask ! = null ) { await saveChangesTask ; } //Start saving the next 100 `` to '' s saveChangesTask = insertContext.SaveChangesAsync ( ) ; //Dispose of the context that was used to save previous 100 `` to '' s prevInsertContext ? .Dispose ( ) ; //Reassign the context used to save the current 100 `` to '' s to a `` prev '' variable , //and set context variable to the new Context instance . prevInsertContext = insertContext ; insertContext = new Context ( ) ; } } ) ; //Wait for second last 100 `` to '' s to finish saving to the database if ( saveChangesTask ! = null ) { await saveChangesTask ; } //Save the last 100 `` to '' s to the database await insertContext.SaveChangesAsync ( ) ; insertContext.Dispose ( ) ; Console.WriteLine ( `` Done '' ) ; Console.ReadKey ( ) ; } } }",Unexpected behaviour with Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ForEachAsync < T > ( ) "C_sharp : I have an interface ( which is used by repositories ) that has this member : This allows the caller to specify an entity type ( T ) and the type of it 's Id field ( TId ) . The implementor of this interface would then find the entities of type T and use the id parameter to filter them according to their id ( which is defined on IEntity < TId > ) .Currently I 'm calling it like this : Ideally I 'd like to do this : I 've read the answers for this question : Partial generic type inference possible in C # ? I understand I ca n't get the syntax I want , but can get close . I ca n't quite get it setup right in my case though because of my generic parameter constraints.Here 's what I have so far : The compilation error I get is : The type 'T ' can not be used as type parameter 'T ' in the generic type or method 'PartsLegislation.Repository.IDataContext.FindById < T , TId > ( TId ) ' . There is no implicit reference conversion from 'T ' to 'PartsLegislation.Repository.IEntity < TId > '.I understand what it 's saying because the T in my wrapper class is only constrained to be a reference type , but the FindById function wants it to be IEntity < TId > , but I ca n't do that as the TId is in the method ( otherwise I 'm back at square one ) .How can I get around this issue ( or ca n't I ) ? T FindById < T , TId > ( TId id ) where T : class , IEntity < TId > where TId : IEquatable < TId > ; int id = 123 ; var myApproval = PartsDC.FindById < Approval , int > ( id ) ; int id = 123 ; var myApproval = PartsDC.FindById < Approval > ( id ) ; public class FindIdWrapper < T > where T : class { public readonly IDataContext InvokeOn ; public FindIdWrapper ( IDataContext invokeOn ) { InvokeOn = invokeOn ; } T ById < TId > ( TId id ) where TId : IEquatable < TId > { return InvokeOn.FindById < T , TId > ( id ) ; } } public static class DataContextExtensions { public static FindIdWrapper < T > Find < T > ( this IDataContext dataContext ) where T : class , IEntity { return new FindIdWrapper < T > ( dataContext ) ; } }",Working around lack of partial generic type inference with constraints "C_sharp : I understand that you can configure C # enum flags in this way : And once this is configured , you can represent a set of enumberations like so : Then you can make checks against this set , such as : Or print their values , like so : Which would print : However , can I go in reverse order ? For instance , if I know that Can I then ask MyEnum what set of its value/types would equal 3 ? Then , I can create an extension method ( GetSet ) to execute like this : Returning either a MyEnum set or a set of values , i.e . { 1 , 2 } . Please advise.EDIT : I was able to finally figure it out . Posted my answer below . [ Flags ] public enum MyEnum { Unknown = 0 , Type1 = 1 , Type2 = 2 , Type3 = 4 , Type4 = 8 , Type5 = 16 } MyEnum enumerationSet = MyEnum.Type1 | MyEnum.Type2 if ( enumerationSet.HasFlag ( MyEnum.Type1 ) ) { // Do something } Console.WriteLine ( `` { 0 } '' , enumerationSet ) ; Type1 , Type2 MyEnum.Type1 | MyEnum.Type2 == 3 List < MyEnum > myEnumSetList = MyEnum.GetSet ( 3 )",Using C # Enum Flags To Return A Set Of Values Based On Their Bit-Wise OR'ed Values C_sharp : Given this code : I 'm getting a compiler warning CS1723 on T inside the see cref XML element : XML comment has cref attribute 'T ' that refers to a type parameterMS Docs is completely useless in this case . Why should I care about this warning ? What is the reason for it ? /// < summary > /// Implementations represent a configuration with a specific data /// type < see cref= '' T '' / > that can be used by this application./// < /summary > internal interface IConfiguration < T > { },What is compiler warning CS1723 `` XML comment has cref attribute 'T ' that refers to a type parameter '' all about ? "C_sharp : Using binary formatting for 1st time in .net C # Code from MSDN is like this : Just wondering should I store an IFormatter in a field in my class and use it over and over again or should I do as above and instantiate a new one every time I save/load something ? I noticed it is not IDisposable . IFormatter formatter = new BinaryFormatter ( ) ; Stream stream = new FileStream ( `` MyFile.lvl '' , FileMode.Create , FileAccess.Write , FileShare.None ) ; formatter.Serialize ( stream , Globals.CurrentLevel ) ; stream.Close ( ) ;","Binary serialization , IFormatter : use a new one each time or store one in a field ?" "C_sharp : Update 1 : I 've written both a MFC-C++ implementation and an old-school Win32 app and recorded a video demonstrating how bad the issue really is : https : //www.youtube.com/watch ? v=f0CQhQ3GgAMSince the old-school Win32 app is not exhibiting this issue , this leads me to believe that C # and MFC both use the same rendering API that must cause this issue ( basically discharging my suspicion that the problem might be at the OS / graphics driver level ) .Original post : While having to display some REST data inside a ListView , I encountered a very peculiar problem : For certain inputs , the ListView rendering would literally slow to a crawl while scrolling horizontally . On my system and with the typical subclassed ListView with `` OptimizedDoubleBuffer '' , having a mere 6 items in a ListView will slow down rendering during scrolling to the point that i can see the headers `` swimming '' , i.e . the rendering of the items and headers during the scrolling mismatches.For a regular non-subclassed ListView with 10 items , I can literally see each item being drawn separately while scrolling ( the repainting takes around 1-2s ) .Here 's example code ( and yes , I am aware that these look like bear and butterfly emotes ; this issue was found from user-provided data , after all ) : Can someone explain what the issue is , and how to resolve it ? using System ; using System.Windows.Forms ; namespace SlowLVRendering { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; this.Load += new System.EventHandler ( this.Form1_Load ) ; } private void Form1_Load ( object sender , EventArgs e ) { const string slow = `` ヽ ( ´。㉨° ) ノ Ƹ̴Ӂ̴Ʒ~ ღ ( ヽ ( ´。㉨° ) ノ ༼ つ´º㉨º ༽つ ) ( 」゚ペ ) 」ヽ ( ´。㉨° ) ノ Ƹ̴Ӂ̴Ʒ~ ღ ( ヽ ( ´。㉨° ) ノ ༼ つ´º㉨º ༽つ ) ( 」゚ペ ) 」 '' ; ListView lv = new ListView ( ) ; lv.Dock = DockStyle.Fill ; lv.View= View.Details ; for ( int i = 0 ; i < 2 ; i++ ) lv.Columns.Add ( `` Title `` +i , 500 ) ; for ( int i = 0 ; i < 10 ; i++ ) { var lvi = lv.Items.Add ( slow ) ; lvi.SubItems.Add ( slow ) ; } Controls.Add ( lv ) ; } } }",Why is ListView rendering so slow for certain characters ? "C_sharp : I was trying to get some Lists sorted using OrderBy within a foreach loop , but for some reason they were n't maintaining their sort order outside of the loop . Here 's some simplified code and comments to highlight what was happening : However , when I instead assign result like this : then the return value has the Children sorted properly in each of the Parents.What is the behavior of List < T > vs an IEnumerable < T > in a foreach loop ? There seems to be some sort of difference since turning result into a List fixed the problems with sorting in the foreach loop . It feels like the first code snippet creates an iterator that makes a copy of each element when you do the iteration with foreach ( and thus my changes get applied to the copy but not the original object in result ) , while using ToList ( ) made the enumerator give a pointer instead . What 's going on here ? public class Parent { // Other properties ... public IList < Child > Children { get ; set ; } } public IEnumerable < Parent > DoStuff ( ) { var result = DoOtherStuff ( ) // Returns IEnumerable < Parent > .OrderByDescending ( SomePredicate ) .ThenBy ( AnotherPredicate ) ; // This sorting works as expected in the return value . foreach ( Parent parent in result ) { parent.Children = parent.Children.OrderBy ( YetAnotherPredicate ) .ToList ( ) ; // When I look at parent.Children here in the debugger , it 's sorted properly . } return result ; // When I look at the return value , the Children are not sorted . } var result = DoOtherStuff ( ) .OrderByDescending ( SomePredicate ) .ThenBy ( AnotherPredicate ) .ToList ( ) ; // < -- Added ToList here",List < T > vs IEnumerable < T > in foreach "C_sharp : I am passing some data ( 1-2MB ) between a php app and a c # program . The info needs to be encrypted and I was using a Rijndael encryption , but encryption was very slow . I am trying to switch to openssl_seal on the php side and have that working fine : PHP CODEBut I am having issues trying to decrypt on the c # end.C # CodeWhere DecryptSSL is being called with an ascii string containing the response from the php page.I never get the original string , '123 ' in this case , returned from the decrypt function . What else am I missing ? < ! -- language : lang-php -- > str = 123 ; $ fp = fopen ( `` /home/prod/publickey.pem '' , `` r '' ) ; $ cert = fread ( $ fp , 8192 ) ; fclose ( $ fp ) ; $ pk1 = openssl_get_publickey ( $ cert ) ; openssl_seal ( $ str , $ sealed , $ ekeys , array ( $ pk1 ) ) ; openssl_free_key ( $ pk1 ) ; $ sealed = base64_encode ( $ sealed ) ; $ Xevk = base64_encode ( $ ekeys [ 0 ] ) ; echo $ Xevk . `` \n\n\n '' . $ sealed ; < ! -- language : c # -- > public static string DecryptSSL ( string str ) { string [ ] strs = System.Text.RegularExpressions.Regex.Split ( str , `` \n\n\n '' ) ; X509Certificate2 myCert2 = null ; RSACryptoServiceProvider rsa = null ; try { myCert2 = new X509Certificate2 ( Properties.Resources.mycertkey , `` '' ) ; rsa = ( RSACryptoServiceProvider ) myCert2.PrivateKey ; } catch ( Exception e ) { Console.WriteLine ( e.Message ) ; } byte [ ] xkey = rsa.Decrypt ( Convert.FromBase64String ( strs [ 0 ] ) , false ) ; byte [ ] content = Convert.FromBase64String ( strs [ 1 ] ) ; EncDec.RC4 ( ref content , xkey ) ; return System.Convert.ToBase64String ( content ) ; } public static void RC4 ( ref Byte [ ] bytes , Byte [ ] key ) { Byte [ ] s = new Byte [ 256 ] ; Byte [ ] k = new Byte [ 256 ] ; Byte temp ; int i , j ; for ( i = 0 ; i < 256 ; i++ ) { s [ i ] = ( Byte ) i ; k [ i ] = key [ i % key.GetLength ( 0 ) ] ; } j = 0 ; for ( i = 0 ; i < 256 ; i++ ) { j = ( j + s [ i ] + k [ i ] ) % 256 ; temp = s [ i ] ; s [ i ] = s [ j ] ; s [ j ] = temp ; } i = j = 0 ; for ( int x = 0 ; x < bytes.GetLength ( 0 ) ; x++ ) { i = ( i + 1 ) % 256 ; j = ( j + s [ i ] ) % 256 ; temp = s [ i ] ; s [ i ] = s [ j ] ; s [ j ] = temp ; int t = ( s [ i ] + s [ j ] ) % 256 ; bytes [ x ] ^= s [ t ] ; } }",php data encrypted with openssl_seal . How to decode in c # ? "C_sharp : Is there any way to get sizeof ( ) a generic type ? e.g.As said in the example , the above is not possible , but is there a way to make it work ? Tried doing public unsafe int but it did n't change anything . Really do n't want to do something like public int GetSize < T > ( ) { return sizeof ( T ) ; //this wont work because T is n't assigned but is there a way to do this } public int GetSize < T > ( ) { if ( typeof ( T ) == typeof ( byte ) || typeof ( T ) == typeof ( sbyte ) ) { return 1 ; } else if ( typeof ( T ) == typeof ( short ) || typeof ( T ) == typeof ( ushort ) || typeof ( T ) == typeof ( char ) ) { return 2 ; } //and so on . }",Can you determine the size of a generic type ? "C_sharp : I can not find a specific example of this , so am posting the question . Any help appreciated.I have two large generic lists , both with over 300K items.I am looping through the first list to pull back information and generate a new item for a new list on the fly , but I need to search within the second list and return a value , based on THREE matching criteria , if found to add to the list , however as you can imagine , doing this 300k * 300k times is taking time.Is there any way I can do this more efficiently ? My code : var reportList = new List < StocksHeldInCustody > ( ) ; foreach ( var correctDepotHolding in correctDepotHoldings ) { var reportLine = new StocksHeldInCustody ( ) ; reportLine.ClientNo = correctDepotHolding.ClientNo ; reportLine.Value = correctDepotHolding.ValueOfStock ; reportLine.Depot = correctDepotHolding.Depot ; reportLine.SEDOL = correctDepotHolding.StockCode ; reportLine.Units = correctDepotHolding.QuantityHeld ; reportLine.Custodian = `` Unknown '' ; reportLine.StockName = correctDepotHolding.StockR1.Trim ( ) + `` `` + correctDepotHolding.StockR2.Trim ( ) ; //Get custodian info foreach ( var ccHolding in ccHoldList ) { if ( correctDepotHolding.ClientNo ! = ccHolding.ClientNo ) continue ; if ( correctDepotHolding.Depot ! = ccHolding.Depot ) continue ; if ( correctDepotHolding.StockCode ! = ccHolding.StockCode ) continue ; if ( correctDepotHolding.QuantityHeld ! = ccHolding.QuantityHeld ) continue ; reportLine.Custodian = ccHolding.Custodian ; break ; } reportList.Add ( reportLine ) ; }",Comparing two large generic lists "C_sharp : I defined a class : Then I do this because I will save JSONed sampleA and JSONed sampleB to Azure table , to present a full sample object . In other code , sometime only need name , sometime only need price , so I only need to pull data that needed each time . Of course in real code , the structure of the sample is much much more complex.My question is : , is there any easy method that can do : and sampleC should contain : public class Sample { public string name { get ; set ; } public int price { get ; set } } Sample sampleA = new Sample ( ) ; sampleA.name = `` test '' ; Sample sampleB = new Sample ( ) ; sampleB.price = 100 ; Sample sampleC = sampleA + sampleB ; sampleC.name = `` test '' ; sampleC.price = 100 ;",How to combine a Partial Class Object in C # ? "C_sharp : I have a production application ( IIS8 , MVC5 , nHibernate DAL ) and I 'm noticing high CPU usage as of late . Cycling the app pool fixes it but after doing some diagnostics and memory dumps from the server to analyze the issue , I noticed a consistent pattern of multiple threads trying to enumerate the same collection . The most common point is where the app checks the roles of the user . I suspect this might be more do to the fact that this code is ran for every request to verify permissions , so it 's more likely to be the collection it gets stuck on ? My CurrentUser object there is a simple interface containing the details of the user , injected from a dependency resolver . I have verified that the UserId is present and valid , it 's all pretty straight forward . When I took a look at the dumps of when these two requests were hung , I got a warning that multiple threads were enumerating a collection . When I checked the two threads in the dump , I saw practically identical stack traces . ( I 've renamed some of the namespace details in the stack trace but it 's otherwise unaltered ) . The userId ( and resulting profile ) in both requests are the same , so it appears it 's due to two separate threads trying to load the same object from the database at practically the same time.The stack trace is below , but I 'm not sure where to go from here in order to fix this.I 'm currently opening my database transaction in an ActionFilter that opens the transaction when OnActionExecuting ( ) happens , and then commit/rollback the transaction when OnActionExecuted ( ) happens.I 'm using StructureMap ( v2.6.4.1 ) for my dependency injection , and the relevant lines for my data persistence is as follows.UPDATE : I 'm still dealing with this and would love some tips on if this is a problem with nhibernate , or how I have it configured ? I had the app lockup to the point where we had to reboot to server today because of 19 separate threads trying to enumerate the same collection.It is mentioned below that it 's likely a problem with lifetime scoping of the SecurityService , which I agree is a possibility . Currently I have the services being provided through dependency injection via Structuremap ( last version of 2.6 released , have n't updated to 3.x yet ) . The details of which I 've details briefly below for what I hope is succinct but still relevant.My dependency resolver setup ... .nHibernate is configured with an internal context of WebSessionContextISessionFactory is SingletonISession is HybridHttpOrThreadLocalScopedISecurityService and the IRepository are both both left t the default of TransientThe roles are cached and if are not found then the system makes the call to the GetRoles method on the security service , I think I might have an issue with it calling GetRoles more often than it needs to , but that 's outside of the scope of the multiple concurrent enumeration problem I 'm having now.UPDATE : So I 'm baffled , I got the same issue today for a call to GetReference . 18 separate threads stuck enumerating the same collection , but this one was internal to nHibernate.There was more after the call to GetReference but it 's not really related to the problem from what I can tell ? public IList < Role > GetRoles ( string username ) { var login = GetLoginForUser ( username ) ; return ! login.Groups.Any ( ) ? new List < Role > ( ) : login.Groups.SelectMany ( x = > x.Roles ) .OrderBy ( x = > x.DisplayName ) .ToList ( ) ; } System.Collections.Generic.Dictionary ` 2 [ [ System.__Canon , mscorlib ] , [ System.Nullable ` 1 [ [ System.Int32 , mscorlib ] ] , mscorlib ] ] .FindEntry ( System.__Canon ) +129 System.Collections.Generic.Dictionary ` 2 [ [ System.__Canon , mscorlib ] , [ System.Nullable ` 1 [ [ System.Int32 , mscorlib ] ] , mscorlib ] ] .TryGetValue ( System.__Canon , System.Nullable ` 1 < Int32 > ByRef ) +12 NHibernate.AdoNet.ColumnNameCache.GetIndexForColumnName ( System.String , NHibernate.AdoNet.ResultSetWrapper ) +25 NHibernate.AdoNet.ColumnNameCache.GetIndexForColumnName ( System.String , NHibernate.AdoNet.ResultSetWrapper ) +25 NHibernate.AdoNet.ResultSetWrapper.GetOrdinal ( System.String ) +e NHibernate.AdoNet.ResultSetWrapper.GetOrdinal ( System.String ) +e NHibernate.Type.NullableType.NullSafeGet ( System.Data.IDataReader , System.String ) +29 NHibernate.Type.NullableType.NullSafeGet ( System.Data.IDataReader , System.String [ ] , NHibernate.Engine.ISessionImplementor , System.Object ) +16 NHibernate.Type.NullableType.NullSafeGet ( System.Data.IDataReader , System.String [ ] , NHibernate.Engine.ISessionImplementor , System.Object ) +16 NHibernate.Persister.Collection.AbstractCollectionPersister.ReadKey ( System.Data.IDataReader , System.String [ ] , NHibernate.Engine.ISessionImplementor ) +14 NHibernate.Persister.Collection.AbstractCollectionPersister.ReadKey ( System.Data.IDataReader , System.String [ ] , NHibernate.Engine.ISessionImplementor ) +14 NHibernate.Loader.Loader.ReadCollectionElement ( System.Object , System.Object , NHibernate.Persister.Collection.ICollectionPersister , NHibernate.Loader.ICollectionAliases , System.Data.IDataReader , NHibernate.Engine.ISessionImplementor ) +34 NHibernate.Loader.Loader.ReadCollectionElement ( System.Object , System.Object , NHibernate.Persister.Collection.ICollectionPersister , NHibernate.Loader.ICollectionAliases , System.Data.IDataReader , NHibernate.Engine.ISessionImplementor ) +34 NHibernate.Loader.Loader.ReadCollectionElements ( System.Object [ ] , System.Data.IDataReader , NHibernate.Engine.ISessionImplementor ) +d2 NHibernate.Loader.Loader.ReadCollectionElements ( System.Object [ ] , System.Data.IDataReader , NHibernate.Engine.ISessionImplementor ) +d2 NHibernate.Loader.Loader.GetRowFromResultSet ( System.Data.IDataReader , NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , NHibernate.LockMode [ ] , NHibernate.Engine.EntityKey , System.Collections.IList , NHibernate.Engine.EntityKey [ ] , Bo+ab NHibernate.Loader.Loader.GetRowFromResultSet ( System.Data.IDataReader , NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , NHibernate.LockMode [ ] , NHibernate.Engine.EntityKey , System.Collections.IList , NHibernate.Engine.EntityKey [ ] , Bo+ab NHibernate.Loader.Loader.DoQuery ( NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , Boolean ) +1e7 NHibernate.Loader.Loader.DoQuery ( NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , Boolean ) +1e7 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections ( NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , Boolean ) +7f NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections ( NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , Boolean ) +7f NHibernate.Loader.Loader.LoadCollection ( NHibernate.Engine.ISessionImplementor , System.Object , NHibernate.Type.IType ) +de NHibernate.Loader.Loader.LoadCollection ( NHibernate.Engine.ISessionImplementor , System.Object , NHibernate.Type.IType ) +de NHibernate.Loader.Collection.CollectionLoader.Initialize ( System.Object , NHibernate.Engine.ISessionImplementor ) +1c NHibernate.Loader.Collection.CollectionLoader.Initialize ( System.Object , NHibernate.Engine.ISessionImplementor ) +1c NHibernate.Persister.Collection.AbstractCollectionPersister.Initialize ( System.Object , NHibernate.Engine.ISessionImplementor ) +1e NHibernate.Persister.Collection.AbstractCollectionPersister.Initialize ( System.Object , NHibernate.Engine.ISessionImplementor ) +1e NHibernate.Event.Default.DefaultInitializeCollectionEventListener.OnInitializeCollection ( NHibernate.Event.InitializeCollectionEvent ) +16d NHibernate.Impl.SessionImpl.InitializeCollection ( NHibernate.Collection.IPersistentCollection , Boolean ) +1fa NHibernate.Collection.AbstractPersistentCollection.Initialize ( Boolean ) +2f NHibernate.Collection.AbstractPersistentCollection.Read ( ) +d NHibernate.Collection.Generic.PersistentGenericBag ` 1 [ [ System.__Canon , mscorlib ] ] .System.Collections.Generic.IEnumerable < T > .GetEnumerator ( ) +11 System_Core_ni ! System.Linq.Enumerable+ < SelectManyIterator > d__14 ` 2 [ [ System.__Canon , mscorlib ] , [ System.__Canon , mscorlib ] ] .MoveNext ( ) +10c System_Core_ni ! System.Linq.Buffer ` 1 [ [ System.__Canon , mscorlib ] ] ..ctor ( System.Collections.Generic.IEnumerable ` 1 < System.__Canon > ) +d9 System_Core_ni ! System.Linq.OrderedEnumerable ` 1+ < GetEnumerator > d__0 [ [ System.__Canon , mscorlib ] ] .MoveNext ( ) +6f System_Core_ni ! System.Linq.OrderedEnumerable ` 1+ < GetEnumerator > d__0 [ [ System.__Canon , mscorlib ] ] .MoveNext ( ) +6f mscorlib_ni ! System.Collections.Generic.List ` 1 [ [ System.__Canon , mscorlib ] ] ..ctor ( System.Collections.Generic.IEnumerable ` 1 < System.__Canon > ) +17e System_Core_ni ! System.Linq.Enumerable.ToList [ [ System.__Canon , mscorlib ] ] ( System.Collections.Generic.IEnumerable ` 1 < System.__Canon > ) +3b Company.ApplicationServices.SecurityService.GetRoles ( System.String ) +ef var cfg = Fluently.Configure ( ) .Database ( MsSqlConfiguration.MsSql2008.ConnectionString ( c = > c.FromConnectionStringWithKey ( `` DatabaseConnectionString '' ) ) .CurrentSessionContext < WebSessionContext > ( ) // ... etc etc ... . .Cache ( c = > c.ProviderClass < NHibernate.Caches.SysCache2.SysCacheProvider > ( ) .UseQueryCache ( ) .UseSecondLevelCache ( ) .UseMinimalPuts ( ) ) ; For < NHibernate.Cfg.Configuration > ( ) .Singleton ( ) .Use ( cfg ) ; For < NHibernate.ISessionFactory > ( ) .Singleton ( ) .Use ( ctx = > { try { var config = ctx.GetInstance < NHibernate.Cfg.Configuration > ( ) ; return config.BuildSessionFactory ( ) ; } catch ( SqlException ex ) { ctx.GetInstance < IExceptionLogger > ( ) .Error ( ex ) ; throw ; } } ) ; For < NHibernate.ISession > ( ) .HybridHttpOrThreadLocalScoped ( ) .Use ( ctx = > ctx.GetInstance < NHibernate.ISessionFactory > ( ) .OpenSession ( ) ) ; public class SecurityService : ISecurityService { private readonly IRepository < Login > loginRepository ; public IList < Role > GetCurrentUserRoles ( ) { var login = GetLoginForCurrentUser ( ) ; return GetRoles ( login.Name ) ; } public Login GetLoginForCurrentUser ( ) { //Some logic to derive the current UserId { guid } via some resources injected into this service class . return loginRepository.GetReference ( loginId ) ; } } public class NHibernateRepository < T > : IRepository < T > where T : class { protected ISession Session { get ; set ; } public NHibernateRepository ( ISession session ) { Session = session ; } public T GetReference ( object id ) { return Session.Get < T > ( id ) ; } // Other methods typical of a repository class , nothing special } For < ISecurityService > ( ) .Use < SecurityService > ( ) ; For ( typeof ( IRepository < > ) ) .Use ( typeof ( NHibernateRepository < > ) ) ; //And then the ISession is commented above . System.Collections.Generic.Dictionary ` 2 [ [ System.__Canon , mscorlib ] , [ System.Nullable ` 1 [ [ System.Int32 , mscorlib ] ] , mscorlib ] ] .FindEntry ( System.__Canon ) +129 System.Collections.Generic.Dictionary ` 2 [ [ System.__Canon , mscorlib ] , [ System.Nullable ` 1 [ [ System.Int32 , mscorlib ] ] , mscorlib ] ] .TryGetValue ( System.__Canon , System.Nullable ` 1 ByRef ) +12 NHibernate.AdoNet.ColumnNameCache.GetIndexForColumnName ( System.String , NHibernate.AdoNet.ResultSetWrapper ) +25 NHibernate.AdoNet.ResultSetWrapper.GetOrdinal ( System.String ) +e NHibernate.Type.NullableType.NullSafeGet ( System.Data.IDataReader , System.String ) +29 NHibernate.Type.NullableType.NullSafeGet ( System.Data.IDataReader , System.String [ ] , NHibernate.Engine.ISessionImplementor , System.Object ) +16 NHibernate.Type.AbstractType.Hydrate ( System.Data.IDataReader , System.String [ ] , NHibernate.Engine.ISessionImplementor , System.Object ) +14 NHibernate.Persister.Entity.AbstractEntityPersister.Hydrate ( System.Data.IDataReader , System.Object , System.Object , NHibernate.Persister.Entity.ILoadable , System.String [ ] [ ] , Boolean , NHibernate.Engine.ISessionImplementor ) +3ce NHibernate.Loader.Loader.LoadFromResultSet ( System.Data.IDataReader , Int32 , System.Object , System.String , NHibernate.Engine.EntityKey , System.String , NHibernate.LockMode , NHibernate.Persister.Entity.ILoadable , NHibernate.Engine.ISessionImplementor ) +118 NHibernate.Loader.Loader.InstanceNotYetLoaded ( System.Data.IDataReader , Int32 , NHibernate.Persister.Entity.ILoadable , NHibernate.Engine.EntityKey , NHibernate.LockMode , System.String , NHibernate.Engine.EntityKey , System.Object , System.Collections.IList , NHi+8c NHibernate.Loader.Loader.GetRow ( System.Data.IDataReader , NHibernate.Persister.Entity.ILoadable [ ] , NHibernate.Engine.EntityKey [ ] , System.Object , NHibernate.Engine.EntityKey , NHibernate.LockMode [ ] , System.Collections.IList , NHibernate.Engine.ISessionImpleme+129 NHibernate.Loader.Loader.GetRowFromResultSet ( System.Data.IDataReader , NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , NHibernate.LockMode [ ] , NHibernate.Engine.EntityKey , System.Collections.IList , NHibernate.Engine.EntityKey [ ] , Bo+97 NHibernate.Loader.Loader.DoQuery ( NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , Boolean ) +1e7 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections ( NHibernate.Engine.ISessionImplementor , NHibernate.Engine.QueryParameters , Boolean ) +7f NHibernate.Loader.Loader.LoadEntity ( NHibernate.Engine.ISessionImplementor , System.Object , NHibernate.Type.IType , System.Object , System.String , System.Object , NHibernate.Persister.Entity.IEntityPersister ) +f3 NHibernate.Loader.Entity.AbstractEntityLoader.Load ( NHibernate.Engine.ISessionImplementor , System.Object , System.Object , System.Object ) +22 NHibernate.Loader.Entity.AbstractEntityLoader.Load ( System.Object , System.Object , NHibernate.Engine.ISessionImplementor ) +12 NHibernate.Persister.Entity.AbstractEntityPersister.Load ( System.Object , System.Object , NHibernate.LockMode , NHibernate.Engine.ISessionImplementor ) +69 NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource ( NHibernate.Event.LoadEvent , NHibernate.Persister.Entity.IEntityPersister , NHibernate.Engine.EntityKey , NHibernate.Event.LoadType ) +84 NHibernate.Event.Default.DefaultLoadEventListener.DoLoad ( NHibernate.Event.LoadEvent , NHibernate.Persister.Entity.IEntityPersister , NHibernate.Engine.EntityKey , NHibernate.Event.LoadType ) +1d7 NHibernate.Event.Default.DefaultLoadEventListener.Load ( NHibernate.Event.LoadEvent , NHibernate.Persister.Entity.IEntityPersister , NHibernate.Engine.EntityKey , NHibernate.Event.LoadType ) +5e NHibernate.Event.Default.DefaultLoadEventListener.ReturnNarrowedProxy ( NHibernate.Event.LoadEvent , NHibernate.Persister.Entity.IEntityPersister , NHibernate.Engine.EntityKey , NHibernate.Event.LoadType , NHibernate.Engine.IPersistenceContext , System.Object ) +73 NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad ( NHibernate.Event.LoadEvent , NHibernate.Persister.Entity.IEntityPersister , NHibernate.Engine.EntityKey , NHibernate.Event.LoadType ) +cb NHibernate.Event.Default.DefaultLoadEventListener.OnLoad ( NHibernate.Event.LoadEvent , NHibernate.Event.LoadType ) +120 NHibernate.Impl.SessionImpl.FireLoad ( NHibernate.Event.LoadEvent , NHibernate.Event.LoadType ) +140 NHibernate.Impl.SessionImpl.Get ( System.String , System.Object ) +148 NHibernate.Impl.SessionImpl.Get ( System.Type , System.Object ) +121 NHibernate.Impl.SessionImpl.Get [ [ System.__Canon , mscorlib ] ] ( System.Object ) +143 Intellitive.Data.Repositories.NHibernateRepository ` 1 [ [ System.__Canon , mscorlib ] ] .GetReference ( System.Object ) +38",nHibernate enumerating the same collection on multiple threads "C_sharp : i am currently writing a web service client in delphi 7 ( service itself is in c # ) . everything seems to be working just fine . when i run a fiddler to look how does the xml going from my client app looks like i noticed that is looks different when i write the `` same '' client app in c # . Below are two xml ` sone that goes from a Delphi 7 appone that goes from c # appi am not fluent in xml so i did some research and to this moment i am able to tell thatUTF-8 is the default for documents without encoding information - ref . here - that means no difference hereXML Namespaces provide a method to avoid element name conflicts - ref . here - namespaces are different ( s : and SOAP-ENV : ) but there are specified , and as far as i am concerned should not make the difference eitherbut what about the schema - not sure about that . There are some extra attributes in the Envelope or datatypes in SomeID and SomeStatus tags . But that came from service wsdl ( i quess ? ! ) . Final questions : Why the app written in c # ( vs2012 ) does not add all the extra schemainformation to the xml . Does it really matter if the xml has them ornot ? can anyone tell if these can be considered as the same ? < ? xml version= '' 1.0 '' ? > < SOAP-ENV : Envelope xmlns : SOAP-ENV= '' http : //schemas.xmlsoap.org/soap/envelope/ '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : SOAP-ENC= '' http : //schemas.xmlsoap.org/soap/encoding/ '' > < SOAP-ENV : Body SOAP-ENV : encodingStyle= '' http : //schemas.xmlsoap.org/soap/encoding/ '' xmlns : NS2= '' http : //tempuri.org/ '' > < NS1 : SomeTagName xmlns : NS1= '' http : //tempuri.org/ '' > < SomeID xsi : type= '' xsd : int '' > 12345 < /SomeID > < SomeStatus xsi : type= '' NS2 : SomeStatusType '' > SOME_OK_STATUS < /SomeStatus > < /NS1 : SomeTagName > < /SOAP-ENV : Body > < /SOAP-ENV : Envelope > < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < s : Envelope xmlns : s= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < s : Body > < SomeTagName xmlns= '' http : //tempuri.org/ '' > < SomeID > 12345 < /SomeID > < SomeStatus > SOME_OK_STATUS < /SomeStatus > < /SomeTagName > < /s : Body > < /s : Envelope >",are these two XML ` s the same ? "C_sharp : I wanted to read the data from SqlDatabase but I 'm getting the IndexOutOfRangeException , here is the screenShot of my table : So here I have a function that gets the data from database and stores it into List of Lesson class , and i 'm getting the exception in the lessons.Add ( ) : And here my lessonClass : public List < Lesson > GetLessonsFromDay ( string Day ) { command.CommandText = `` SELECT * FROM [ Scadule ] WHERE [ day ] = ' '' + Day + `` ' '' ; con.Open ( ) ; SqlDataReader sdr = command.ExecuteReader ( ) ; List < Lesson > lessons = new List < Lesson > ( ) ; while ( sdr.Read ( ) ) { lessons.Add ( new Lesson ( Day , ( int ) sdr [ `` [ num ] '' ] , ( string ) sdr [ `` [ time ] '' ] , ( string ) sdr [ `` [ class ] '' ] , ( string ) sdr [ `` [ where ] '' ] ) ) ; } con.Close ( ) ; return lessons ; } public class Lesson { public Lesson ( string Day , int Num , string Time , string Class , string Where ) { this.Day = Day ; this.Num = Num ; this.Time = Time ; this.Class = Class ; this.Where = Where ; } public string Day { get ; set ; } public int Num { get ; set ; } public string Time { get ; set ; } public string Class { get ; set ; } public string Where { get ; set ; } }",Index out of range exception - C # "C_sharp : I 'm implementing a 64-bit fixed-point signed 31.32 numeric type in C # , based on long . So far so good for addition and substraction . Multiplication however has an annoying case I 'm trying to solve.My current algorithm consist of splitting each operand into its most and least significant 32 bits , performing 4 multiplications into 4 longs and adding the relevant bits of these longs . Here it is in code : This works in the general case but fails in a number of scenarios . Namely , the result is off by 1.0 ( decimal value ) , often for extremely small or large values of the operands . Here are some results from my unit tests ( FromRaw ( ) is a method that builds a Fix64 directly from a long value , without shifting it ) : I 'm trying to work out the logic of this on paper but I 'm a bit stuck . How can I fix this ? public static Fix64 operator * ( Fix64 x , Fix64 y ) { var xl = x.m_rawValue ; // underlying long of x var yl = y.m_rawValue ; // underlying long of y var xlow = xl & 0x00000000FFFFFFFF ; // take the 32 lowest bits of x var xhigh = xl > > 32 ; // take the 32 highest bits of x var ylow = yl & 0x00000000FFFFFFFF ; // take the 32 lowest bits of y var yhigh = yl > > 32 ; // take the 32 highest bits of y // perform multiplications var lowlow = xlow * ylow ; var lowhigh = xlow * yhigh ; var highlow = xhigh * ylow ; var highhigh = xhigh * yhigh ; // take the highest bits of lowlow and the lowest of highhigh var loResult = lowlow > > 32 ; var midResult1 = lowhigh ; var midResult2 = highlow ; var hiResult = highhigh < < 32 ; // add everything together and build result var finalResult = loResult + midResult1 + midResult2 + hiResult ; return new Fix64 ( finalResult ) ; // this constructor just copies the parameter into m_rawValue } Failed for FromRaw ( -1 ) * FromRaw ( -1 ) : expected 0 but got -1Failed for FromRaw ( -4 ) * FromRaw ( 6791302811978701836 ) : expected -1.4726290525868535041809082031 but got -2,4726290525868535041809082031Failed for FromRaw ( 2265950765 ) * FromRaw ( 17179869183 ) : expected 2.1103311001788824796676635742 but got 1,1103311001788824796676635742",64-bit fixed-point multiplication error "C_sharp : Other than readability , what is the difference between the following linq queries and when and why would I use one over the other : andUpdate : Dang , sorry introduced some bugs when trying to simplify my problem IEnumerable < T > items = listOfItems.Where ( d = > d is T ) .Cast < T > ( ) ; IEnumerable < T > items = listOfItems.OfType < T > ( ) ;",Difference between OfType < > ( ) and checking type in Where ( ) extension "C_sharp : Is there a way to prevent Visual Studio ( 2010 ) `` Format document '' menu to format the switch-case statements as the following : When I write my code like : And then hit `` Format document '' , Visual Studio adds break lines : I have looked into the Formatting section of VS Options , but I ca n't find anything relevant . ( I do not have ReSharper installed ) switch ( value ) { case `` 1 '' : mode = Mode.One ; break ; case `` 2 '' : mode = Mode.Two ; break ; } switch ( value ) { case `` 1 '' : mode = Mode.One ; break ; case `` 2 '' : mode = Mode.Two ; break ; }",Prevent Visual Studio to add break lines in switch-case statements "C_sharp : I 'm trying to learn about SynchronizationContext and friends.If I set a custom synchronization context at the start of e.g . a console app.Under what conditions will the current synchronization context flow with my async operations ? Are there differences between Task and others , e.g . Delegate.BeginInvoke ? If I execute stuff on the thread pool , am I forced to assign a synchronization context to that specific thread that is currently executing my work ? void Main ( ) { SynchronizationContext.SetSynchronizationContext ( new FooContext ( ) ) ; Action a = ( ) = > { var current = SynchronizationContext.Current ; //current is null here } ; a.BeginInvoke ( null , null ) ; ... sleep","SynchronizationContext , when does it flow and when does it not ?" "C_sharp : Consider the following code : On the one hand , a disposable object should dispose of it 's resources ; I get that , but on the other hand , the object did n't create and does n't own this resource , it was provided - > calling code should take responsibility for it ... no ? I ca n't think of any other situations like this , but is it a consistent pattern in the framework for any class receiving disposable objects to dispose of them on its own dispose ? using ( var ms = new MemoryStream ( ) ) { using ( var writer = BinaryWriter ( ms ) ) { writer.Write ( /*something*/ ) ; writer.Flush ( ) ; } Assert.That ( ms.Length > 0 ) ; // Throws ObjectDisposedException }",Why does a stream dispose when its writer is disposed ? "C_sharp : What is the difference between the evaluation of == and Equals in C # ? For Ex , butEdited : if ( x==x++ ) //Always returns true if ( x.Equals ( x++ ) ) //Always returns false int x=0 ; int y=0 ; if ( x.Equals ( y++ ) ) // Returns True",== vs Equals in C # "C_sharp : I will preface this with I 'm actively searching for the solution to this problem but figured I might short cut some research and development time if someone here on stack has already figured this out . ( I have found nothing online so here goes ) We have a case in an application framework we are building where we need the capability to take in a set of Predicates ( List < Expression < Func < T , bool > > > ) and parse it in a search framework.Right now we have the capability to filter in this way being that : The reason we need to do this is for scale-ability of filterable objects . However for a quick search this is not possible given the built in capabilities of EF . What I need to be able to do is : Object A ( lets pretend it 's a race car ) and we want to search make , model , team , and driver in a quick search box . So if I enter `` Earnhardt '' , it would search all race car entity properties being make , model , team , and driver . I would end up with all the DEI cars as well as Dale Jr . I would like to use the same approach so we can configure a searchable entity and reflect the search configuration on application start . I would ideally like to make some way of having the query look similar to this : I realize I can do : However this will not work for the approach we want to take to solve this problem . Ideally an admin for one of our client sites would be able to go in and configure an additional search term with a single click to be included in any and all quick searches for that entity type like we can currently pull off with Filters which use the standard .Where ( ... ) `` and '' chaining logic . //Assume predicates is passed as a method argument.// of List < Expression < Func < T , bool > > > //Assume user is passed in as a method argument.//Assume FilterToUserAccess is a custom extension method that restricts the dataset// to access restrictions.var query = _dbContext.Set < EntityType > ( ) .FilterToUserAccess ( user ) ; foreach ( var p in predicates ) { query = query.Where ( p ) ; } return p.ToList ( ) ; //Assume predicates is passed as a method argument.// of List < Expression < Func < T , bool > > > //Assume user is passed in as a method argument.//Assume FilterToUserAccess is a custom extension method that restricts the dataset// to access restrictions.var query = _dbContext.Set < EntityType > ( ) .FilterToUserAccess ( user ) ; foreach ( var p in predicates ) { query = query.Or ( p ) ; } return p.ToList ( ) ; _dbContext.Set < EntityType > ( ) .Where ( predicate1 || predicate2 || predicate3 )",Chaining OR conditions in EF 5.0 "C_sharp : In Entity Framework 6 Code First , is there a way to force all DateTime properties to be modeled as DateTime2 ? I know that I can do on each individual DateTime property , but I 'm wondering if there 's a way to set it as a default for all DateTime properties . .HasColumnType ( `` datetime2 '' )",Is it possible to force all DateTime properties to be modeled as DateTime2 ? "C_sharp : I 'm trying to parse a JSON response that includes something I 'm not quite familiar with , nor have I seen in the wild that often . Inside one of the JSON objects , there is a dynamically named JSON object . In this example , there is a JSON object inside `` bugs '' named `` 12345 '' which correlates to a bug number.What I 'm curious about is : What would be the most effective way to parse a dynamically-named JSON object like this ? Given some JSON Utility tools like http : //jsonutils.com/http : //json2csharp.com/They will take a JSON response like the one above and morph it into classes like the following respectfully : jsonutilsjson2charpThe problem about this is that it generates a class with a dynamic name . Thus subsequent queries with other identifiers to this API would result in a failure because the name does not match up nor would a generated [ JsonProperty ( `` '' ) ] as it would contain the dynamic class name as per the generated examples above.Although the JSON is valid , this seems to be a limitation with JSON that is formatted this way . Unfortunately I do not have any control on this JSON API , so I 'm curious what the best way to approach this problem would be ? { `` bugs '' : { `` 12345 '' : { `` comments '' : [ { `` id '' : 1 , `` text '' : `` Description 1 '' } , { `` id '' : 2 , `` text '' : `` Description 2 '' } ] } } } public class Comment { public int id { get ; set ; } public string text { get ; set ; } } public class 12345 { public IList < Comment > comments { get ; set ; } } public class Bugs { public 12345 12345 { get ; set ; } } public class Root { public Bugs bugs { get ; set ; } } public class Comment { public int id { get ; set ; } public string text { get ; set ; } } public class __invalid_type__12345 { public List < Comment > comments { get ; set ; } } public class Bugs { public __invalid_type__12345 __invalid_name__12345 { get ; set ; } } public class RootObject { public Bugs bugs { get ; set ; } }",What is the most effective way to parse JSON objects that are dynamically named ? "C_sharp : Successfully using the Mantis SOAP API ( aka `` MantisConnect '' ) from C # , I can successfully read an issue and also get the download_url field.When trying to download the attachment by something like this : it `` downloads '' a HTML page with the login screen instead of the binary attachment content.So my question is : How can I programmatically download an attachment for an issue in Mantis ? using ( var request = new WebClient ( ) ) { request.Credentials = new NetworkCredential ( `` username '' , `` password '' ) ; return request.DownloadData ( mantisAtt.download_url ) ; }",Programmatically download an attachment via Mantis SOAP API ? "C_sharp : What is the nicest way to get this functionality in C # ? I want to define a strongly-typed tuple on the fly ( for use in a local function ) , save a bunch of them in a list , do some processing and return a result , never to touch the list again.I do n't actually care about the strong typing , but a List of vars does n't work . Do I want a list of objects ? Is that the closest I can get ? Defining structs or classes for temporary data structures seems verbose and pedantic to me . List < struct { string , string , double } > L = new List < struct { string , string , double } > ; L.Add ( { `` hi '' , `` mom '' , 5.0 } ) ;",Representing Typed N-tuples in C # "C_sharp : I 'm building an API with WebAPI that will accept authentication information over SSL via HTTPS from the web browser client . The web browser uses forms authentication and requires HTTPS so it can securely sent username/password to the API endpoint . My API uses Websecurity.Login ( ) and Websecurity.Logout ( ) to handle authentication for the web client . How would this get handled in a WP8 application / Universal app built with WinJS ? Can I do the same thing - send login / registration credentials over HTTPS and use Websecurity to handle forms auth ? Here 's how my WebAPI is currently set up for auth : Is this approach compatible with WP8 or other native mobile app development authentication ? public HttpResponseMessage LogIn ( LoginModel model ) { if ( ModelState.IsValid ) { if ( User.Identity.IsAuthenticated ) { return Request.CreateResponse ( HttpStatusCode.Conflict , `` already logged in . `` ) ; } if ( WebSecurity.Login ( model.UserName , model.Password , persistCookie : model.RememberMe ) ) { FormsAuthentication.SetAuthCookie ( model.UserName , model.RememberMe ) ; return Request.CreateResponse ( HttpStatusCode.OK , `` logged in successfully '' ) ; } else { return new HttpResponseMessage ( HttpStatusCode.Unauthorized ) ; } } // If we got this far , something failed return new HttpResponseMessage ( HttpStatusCode.InternalServerError ) ; } public HttpResponseMessage LogOut ( ) { if ( User.Identity.IsAuthenticated ) { WebSecurity.Logout ( ) ; return Request.CreateResponse ( HttpStatusCode.OK , `` logged out successfully . `` ) ; } return Request.CreateResponse ( HttpStatusCode.Conflict , `` already done . `` ) ; }",Windows phone 8 development & WebAPI - authenticating via forms auth ? "C_sharp : Could some one please explain , What happens when a reference type is defined inside the value type . I write the following code : Which outputs : I 'm curious to know , after calling the method Test ( ObjVal , ObjValRef ) , how the values of ReferenceType is changed to 50 which resides inside the ValueType whose value is not changed ? namespace ClassInsideStruct { class ClassInsideStruct { static void Main ( string [ ] args ) { ValueType ObjVal = new ValueType ( 10 ) ; ObjVal.Display ( ) ; ValueType.ReferenceType ObjValRef = new ValueType.ReferenceType ( 10 ) ; ObjValRef.Display ( ) ; Test ( ObjVal , ObjValRef ) ; ObjVal.Display ( ) ; ObjValRef.Display ( ) ; Console.ReadKey ( ) ; } private static void Test ( ValueType v , ValueType.ReferenceType r ) { v.SValue = 50 ; r.RValue = 50 ; } } struct ValueType { int StructNum ; ReferenceType ObjRef ; public ValueType ( int i ) { StructNum = i ; ObjRef = new ReferenceType ( i ) ; } public int SValue { get { return StructNum ; } set { StructNum = value ; ObjRef.RValue = value ; } } public void Display ( ) { Console.WriteLine ( `` ValueType : `` + StructNum ) ; Console.Write ( `` ReferenceType Inside ValueType Instance : `` ) ; ObjRef.Display ( ) ; } public class ReferenceType { int ClassNum ; public ReferenceType ( int i ) { ClassNum = i ; } public void Display ( ) { Console.WriteLine ( `` Reference Type : `` + ClassNum ) ; } public int RValue { get { return ClassNum ; } set { ClassNum = value ; } } } } } ValueType : 10ReferenceType Inside ValueType Instance : Reference Type : 10Reference Type : 10ValueType : 10ReferenceType Inside ValueType Instance : Reference Type : 50Reference Type : 50",Class Inside Structure "C_sharp : I write simply code : And : I get a windows with textbox ( `` Text '' ) and checkbox . When i focus on textbox and press CtrlA checkbox toggle state , because TextBox.TextChanged raised and textBox1_TextChanged executed.But , i can ` t understand why TextChanged event raised on CtrlA ? using System.Windows.Forms ; namespace Test01 { partial class Form1 { /// < summary > /// Required designer variable . /// < /summary > private System.ComponentModel.IContainer components = null ; /// < summary > /// Clean up any resources being used . /// < /summary > /// < param name= '' disposing '' > true if managed resources should be disposed ; otherwise , false. < /param > protected override void Dispose ( bool disposing ) { if ( disposing & & ( components ! = null ) ) { components.Dispose ( ) ; } base.Dispose ( disposing ) ; } # region Windows Form Designer generated code /// < summary > /// Required method for Designer support - do not modify /// the contents of this method with the code editor . /// < /summary > private void InitializeComponent ( ) { this.textBox1 = new System.Windows.Forms.TextBox ( ) ; this.checkBox1 = new System.Windows.Forms.CheckBox ( ) ; this.SuspendLayout ( ) ; // // textBox1 // this.textBox1.Location = new System.Drawing.Point ( 33 , 32 ) ; this.textBox1.Name = `` textBox1 '' ; this.textBox1.Size = new System.Drawing.Size ( 186 , 20 ) ; this.textBox1.TabIndex = 0 ; this.textBox1.Text = `` Text '' ; this.textBox1.TextChanged += new System.EventHandler ( this.textBox1_TextChanged ) ; // // checkBox1 // this.checkBox1.AutoSize = true ; this.checkBox1.Location = new System.Drawing.Point ( 38 , 65 ) ; this.checkBox1.Name = `` checkBox1 '' ; this.checkBox1.Size = new System.Drawing.Size ( 80 , 17 ) ; this.checkBox1.TabIndex = 1 ; this.checkBox1.Text = `` checkBox1 '' ; this.checkBox1.UseVisualStyleBackColor = true ; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF ( 6F , 13F ) ; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font ; this.ClientSize = new System.Drawing.Size ( 234 , 86 ) ; this.Controls.Add ( this.checkBox1 ) ; this.Controls.Add ( this.textBox1 ) ; this.Name = `` Form1 '' ; this.Text = `` Form1 '' ; this.ResumeLayout ( false ) ; this.PerformLayout ( ) ; } void textBox1_TextChanged ( object sender , System.EventArgs e ) { if ( this.checkBox1.Checked ) this.checkBox1.CheckState = CheckState.Unchecked ; else this.checkBox1.CheckState = CheckState.Checked ; } # endregion private System.Windows.Forms.TextBox textBox1 ; private System.Windows.Forms.CheckBox checkBox1 ; } } namespace Test01 { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } } }",TextBox.TextChanged and `` CTRL-a '' "C_sharp : I have an application running on nHibernate v4.0.4.4000 - it is running in production on three seperate webservers . For ID-generation , I 'm using the default HiLo implementation ( unique id across tables ) .Sometimes , it generates duplicate Id 's when saving new entities with the following stack-trace : And the following message : The SessionFactory is set to use SnapshotIsolation , the DB is set at compability level 2008 ( 100 ) As far as I can tell , the updating of the hilo value is running in a transaction separate from the `` normal '' transactions ( I 've tried causing an exception - the hilo value is not rolled back ( which makes sense ) ) .According to the NHibernate profiler , the SQL run against the server for hilo values is : What am I missing ? Should n't the HiLo guard against duplicates ? EDIT : The duplicate IDs are not happening only on one table , but in the tables with very frequent inserts and deletions . The above code was the simplest among the suspects and is extremely simple - it only .Get ( ) a parent to check it is there and then creates and calls .Save ( ) on the new entity along with an audit trail row ( which uses the PostInsert eventlistener in nHibernate ) .EDIT2 : Id-Mapping for the above type ( used across all entities ) : The weird part is that ( due to @ Dexions comment ) when I check both the audit trail and the table - nothing has been persisted . The code used to persist is as follows : at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch ( IDbCommand ps ) at NHibernate.AdoNet.AbstractBatcher.ExecuteBatchWithTiming ( IDbCommand ps ) at NHibernate.AdoNet.AbstractBatcher.ExecuteBatch ( ) at NHibernate.AdoNet.AbstractBatcher.PrepareCommand ( CommandType type , SqlString sql , SqlType [ ] parameterTypes ) at NHibernate.AdoNet.AbstractBatcher.PrepareBatchCommand ( CommandType type , SqlString sql , SqlType [ ] parameterTypes ) at NHibernate.Persister.Entity.AbstractEntityPersister.Insert ( Object id , Object [ ] fields , Boolean [ ] notNull , Int32 j , SqlCommandInfo sql , Object obj , ISessionImplementor session ) at NHibernate.Persister.Entity.AbstractEntityPersister.Insert ( Object id , Object [ ] fields , Object obj , ISessionImplementor session ) at NHibernate.Action.EntityInsertAction.Execute ( ) at NHibernate.Engine.ActionQueue.Execute ( IExecutable executable ) at NHibernate.Engine.ActionQueue.ExecuteActions ( IList list ) at NHibernate.Engine.ActionQueue.ExecuteActions ( ) at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions ( IEventSource session ) at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush ( FlushEvent event ) at NHibernate.Impl.SessionImpl.Flush ( ) at Xena.Database.Main.Listeners.Strategies.CreateEntityAuditTrailStrategy.Execute ( Object criteria ) in K : \Projects\Xena\WorkDir\src\Xena.Database.Main\Listeners\Strategies\CreateEntityAuditTrailStrategy.cs : line 41at Xena.Domain.Rules.Strategies.StrategyExtensions.Execute [ TCriteria ] ( IEnumerable ` 1 strategies , TCriteria criteria ) in K : \Projects\Xena\WorkDir\src\Xena.Domain\Rules\Strategies\RelayStrategy.cs : line 55at NHibernate.Action.EntityInsertAction.PostInsert ( ) at NHibernate.Action.EntityInsertAction.Execute ( ) at NHibernate.Engine.ActionQueue.Execute ( IExecutable executable ) at NHibernate.Engine.ActionQueue.ExecuteActions ( IList list ) at NHibernate.Engine.ActionQueue.ExecuteActions ( ) at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions ( IEventSource session ) at NHibernate.Event.Default.DefaultAutoFlushEventListener.OnAutoFlush ( AutoFlushEvent event ) at NHibernate.Impl.SessionImpl.AutoFlushIfRequired ( ISet ` 1 querySpaces ) at NHibernate.Impl.SessionImpl.List ( CriteriaImpl criteria , IList results ) at NHibernate.Impl.CriteriaImpl.List ( IList results ) at NHibernate.Impl.CriteriaImpl.UniqueResult [ T ] ( ) at Xena.Web.EntityUpdaters.LedgerPostPreviewUpdater.TryCreateNewFiscalEntity ( ISession session , FiscalSetup fiscalSetup , LedgerPostPreview & entity , IEnumerable ` 1 & errors ) in K : \Projects\Xena\WorkDir\src\Xena.Web\EntityUpdaters\LedgerPostPreviewUpdater.cs : line 52at Xena.Web.SecurityContext. < > c__DisplayClass8_0 ` 1. < TrySaveUpdate > b__0 ( ISession session , TEntity & entity , IEnumerable ` 1 & errors ) in K : \Projects\Xena\WorkDir\src\Xena.Web\SecurityContext.cs : line 235at Xena.Web.SecurityContext. < > c__DisplayClass41_0 ` 1. < TrySave > b__0 ( ITransaction tx ) in K : \Projects\Xena\WorkDir\src\Xena.Web\SecurityContext.cs : line 815at Xena.Web.SecurityContext.TryWrapInTransaction [ T ] ( Func ` 2 action , T & result , IEnumerable ` 1 & errors , Boolean alwaysCommit ) in K : \Projects\Xena\WorkDir\src\Xena.Web\SecurityContext.cs : line 804at Xena.Web.SecurityContext.TrySave [ TEntity ] ( IEntityUpdater ` 1 entityUpdater , EntityCreate ` 1 create ) in K : \Projects\Xena\WorkDir\src\Xena.Web\SecurityContext.cs : line 812at Xena.Web.SecurityContext.TrySaveUpdate [ TEntity ] ( IFiscalEntityUpdater ` 1 entityUpdater ) in K : \Projects\Xena\WorkDir\src\Xena.Web\SecurityContext.cs : line 236at Xena.Web.Api.XenaFiscalApiController.WrapSave [ TEntity , TDto ] ( IFiscalEntityUpdater ` 1 updater , Func ` 2 get , Action ` 2 postGet ) in K : \Projects\Xena\WorkDir\src\Xena.Web\Api\Abstract\XenaFiscalApiController.cs : line 35at Xena.Web.Api.ApiLedgerPostPreviewController.Post ( LedgerPostPreviewDto ledgerPostPreview ) in K : \Projects\Xena\WorkDir\src\Xena.Web\Api\ApiLedgerPostPreviewController.cs : line 79at lambda_method ( Closure , Object , Object [ ] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor. < > c__DisplayClass10. < GetExecutor > b__9 ( Object instance , Object [ ] methodParameters ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync ( HttpControllerContext controllerContext , IDictionary ` 2 arguments , CancellationToken cancellationToken ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Web.Http.Controllers.ApiControllerActionInvoker. < InvokeActionAsyncCore > d__0.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter ` 1.GetResult ( ) at System.Web.Http.Controllers.ActionFilterResult. < ExecuteAsync > d__2.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Web.Http.Filters.AuthorizationFilterAttribute. < ExecuteAuthorizationFilterAsyncCore > d__2.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter ` 1.GetResult ( ) at System.Web.Http.Dispatcher.HttpControllerDispatcher. < SendAsync > d__1.MoveNext ( ) Message=Violation of PRIMARY KEY constraint 'PK_LedgerPostPreview ' . Can not insert duplicate key in object 'dbo.LedgerPostPreview ' . The duplicate key value is ( 94873244 ) .The statement has been terminated . Reading high value : select next_hifrom hibernate_unique_key with ( updlock , rowlock ) Updating high value : update hibernate_unique_keyset next_hi = 5978 /* @ p0 */where next_hi = 5977 /* @ p1 - next_hi */ public static void MapId < TMapping , TType > ( this TMapping mapping ) where TMapping : ClassMapping < TType > where TType : class , IHasId { mapping.Id ( m = > m.Id , m = > m.Generator ( Generators.HighLow , g = > g.Params ( new { max_lo = 100 } ) ) ) ; } using ( var tx = Session.BeginTransaction ( ) ) { try { var voucherPreview = Session.Get < VoucherPreview > ( voucherPreviewId ) ; //Parent var postPreview = //Factory create with the voucherPreview ; var index = Session.QueryOver < LedgerPostPreview > ( ) .Where ( lpp = > lpp.VoucherPreview == voucherPreview ) .SelectList ( l = > l.SelectMax ( lpp = > lpp.Index ) ) .SingleOrDefault < int > ( ) + 1 postPreview.Index = index ; // Set a few other properties and check validity Session.SaveOrUpdate ( postPreview ) ; } catch ( Exception ex ) { //Errorhandling leading to the above stacktrace } }",NHibernate HiLo generator generates duplicate Id 's "C_sharp : suppose I have this query : How many times does Numbers is enumerated when running the foreach ? how can I test it ( I mean , writing a code which tells me the number of iterations ) int [ ] Numbers= new int [ 5 ] { 5,2,3,4,5 } ; var query = from a in Numbers where a== Numbers.Max ( n = > n ) //notice MAX he should also get his value somehow select a ; foreach ( var element in query ) Console.WriteLine ( element ) ;",LINQ query and sub-query enumeration count in C # ? "C_sharp : I looking for help on how to make use of yield keyword to return IEnumberable in parallel blocks or Task block . Below is the pseudo codeI want to convert above code to parallel block like belowbut compiler throws error that Yield can not be used in Parallel blocks or anonymous delegate . I tried with Task block also , yield is not allowed in task anonymous delegateAny one suggest me simple and best way to have yield to return collection of data in parallel blocks or task . I read that RX 2.0 or TPL are good to use in the above scenario . I have a doubt whether to make use of RX or TPL library for asynchronous return of yield of values . Can any one suggest me which is better either Rx or TPL.If i use of Rx , is it necessary to create subscribe and convert parallel block AsObservable . public IEnumerable < List < T > > ReadFile ( ) { foreach ( string filepath in lstOfFiles ) { var stream = new FileStream ( filepath , FileMode.Open , FileAccess.Read ) ; foreach ( var item in ReadStream ( stream ) ) yield return item ; //where item is of type List < string > } } lstOfFiles.AsParallel ( ) .ForAll ( filepath = > { var stream = new FileStream ( filepath , FileMode.Open , FileAccess.Read ) ; foreach ( var item in ReadStream ( Stream ) ) yield return item ; } ) ;",how to use yield to return the collection of Item in parallel block or Task "C_sharp : Let 's say my solution has 2 projects : The first called `` MainProject '' ( A .NETStandard 2.0 project ) .The second called `` MainProjectTests '' ( A NUnit test project ) with some unit tests for each class into `` MainProject '' .The first project ( MainProject ) has a NuGet dependency called `` dependencyX '' . Obviously , the project `` MainProjectTests '' has a reference to `` MainProject '' .So when the test runner runs a test of `` MainProjectTests '' that calls methods from `` MainProject '' using `` dependencyX '' I 'm getting a System.IO.FileNotFoundException exception : System.IO.FileNotFoundException : Could not load file or assembly 'dependencyX , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null ' or one of its dependencies.Why am I getting this exception ? When I add `` dependencyX '' to `` MainProjectTests '' all works fine , but it seems to me not a good practice ... How to solve it ? I 'm using Visual Studio for Mac Community 7.2 preview ( 7.2 build 583 ) Thanks for the help.EDIT : Tried putting the options : in the NUnit project , but getting the same result . < RestoreProjectStyle > PackageReference < /RestoreProjectStyle > < AutoGenerateBindingRedirects > true < /AutoGenerateBindingRedirects >","Dependencies not flowing between dependent projects , causing System.IO.FileNotFoundException" "C_sharp : I have a .NET project written in C # that has a dependency with the CoolProp library ( available here https : //github.com/CoolProp/CoolProp ) . It calls the CoolProp functions using PInvoke.Unluckily I have to run this program in a linux environment ( precisely the AWS lambda env https : //docs.aws.amazon.com/en_us/lambda/latest/dg/current-supported-versions.html ) .For now , I want to execute it with .NET core ( command dotnet run ) on my PC with Ubuntu OS but I get always the following error : Unhandled Exception : System.DllNotFoundException : Unable to load shared library 'libCoolProp.so ' or one of its dependencies . In order to help diagnose loading problems , consider setting the LD_DEBUG environment variable : liblibCoolProp.so.so : can not open shared object file : No such file or directory at Test1.Program.PropsSI ( String Output , String Name1 , Double Prop1 , String Name2 , Double Prop2 , String Ref ) at Test1.Program.Main ( String [ ] args ) in /home/user/Desktop/TestDllInUbuntu/Test1/Program.cs : line 23The test program is : The Program.cs is in the same folder of libCoolProp.so.Notes : The same program in Windows 10 compiled and executed with .Net Core with its libCoolProp.dll works . The same program in Ubuntu 18 compiled and executed with Mono Runtime works.How to solve the compatibility issue between CoolProp lib and .Net Core runtime ? using System ; using System.Runtime.InteropServices ; namespace Test1 { class Program { [ DllImport ( `` libCoolProp.so '' ) ] private static extern double PropsSI ( string Output , string Name1 , double Prop1 , string Name2 , double Prop2 , string Ref ) ; static void Main ( string [ ] args ) { double propsRes = PropsSI ( `` H '' , `` T '' , 300.0 , `` Q '' , 0.0 , `` R410A '' ) ; Console.WriteLine ( propsRes ) ; } } }",Exception : System.DllNotFoundException - Invoke CoolProp ( Native C++ library ) functions with .NET Core 2.1 "C_sharp : Let 's start with a very simple piece of code : The result is 4xtrue . Now , let 's change a type of a variable d to decimal ? : This time the result will be True , True , False , True . The explanation of this situation is quite easy . Equals method is implemented as follows for Nullable < T > type : If this has a value and other parameter is not null then Decimal.Equals ( object value ) will be called . Decimal.Equals ( object value ) method works in this way , that if value parameter is not decimal then the result will be always false.It seems to me that the current implementation is not intuitive and I wonder why Nullable < T > does n't provide developers with generic version of Equals method e.g . : Was it done on purpose or is it an omission ? Comment 1 : A brief comment to be clear . I suggested that Nullable < T > should have two Equals methods i.e . : public override bool Equals ( object other ) and public bool Equals ( T other ) decimal d = 2 ; Console.WriteLine ( `` d == 2 = { 0 } '' , d == 2 ) ; Console.WriteLine ( `` d == ( decimal ) 2 = { 0 } '' , d == ( decimal ) 2 ) ; Console.WriteLine ( `` d.Equals ( 2 ) = { 0 } '' , d.Equals ( 2 ) ) ; Console.WriteLine ( `` d.Equals ( ( decimal ) 2 ) = { 0 } '' , d.Equals ( ( decimal ) 2 ) ) ; decimal ? d = 2 ; public override bool Equals ( object other ) { if ( ! this.HasValue ) { return ( other == null ) ; } if ( other == null ) { return false ; } return this.value.Equals ( other ) ; } public bool Equals ( T other ) { if ( ! this.HasValue ) return false ; return this.value.Equals ( other ) ; }",Why there is no Nullable < T > .Equals ( T value ) method ? C_sharp : I read the Loading Related Entities post by the Entity Framework team and got a bit confused by the last paragraph : Sometimes it is useful to know how many entities are related to another entity in the database without actually incurring the cost of loading all those entities . The Query method with the LINQ Count method can be used to do this . For example : Why do the Query + Count method needed here ? Ca n't we simple use the LINQ 's COUNT method instead ? Will that trigger the lazy loading and all the collection will be loaded to the memory and just than I 'll get my desired scalar value ? using ( var context = new BloggingContext ( ) ) { var blog = context.Blogs.Find ( 1 ) ; // Count how many posts the blog has var postCount = context.Entry ( blog ) .Collection ( b = > b.Posts ) .Query ( ) .Count ( ) ; } var blog = context.Blogs.Find ( 1 ) ; var postCount = blog.Posts.Count ( ) ;,Does LINQ with a scalar result trigger the lazy loading "C_sharp : In order to debug an issue in my code , I have declared the following two strings , assuming they would be equivalent : I discovered they are not . Great , this is the source of my issue . However , I 'm checking things in the immediate window ( on the line following the declarations ) and do n't understand what is happening . Here is the output : huh ? Why are n't they equal ? edit : I need to use 'thumbprint ' as the base . It 's a user entered string . I 'm just using 'newPrint ' as a temporary variable to hold the trimmed/uppered value . print is the expected outcome . String print = `` 8A9B485ECDC56B6E0FD023D6994A57EEC49B0717 '' ; String newPrint = thumbprint.Trim ( ) .Replace ( `` `` , `` '' ) .ToUpper ( ) ; print '' 8A9B485ECDC56B6E0FD023D6994A57EEC49B0717 '' newPrint '' ‎8A9B485ECDC56B6E0FD023D6994A57EEC49B0717 '' String.Compare ( print , newPrint ) ; 0print == newPrintfalseprint.Equals ( newPrint ) false",String Equality - What is going on here ? "C_sharp : If I have a context menu , is it possible to join it to another menu ? So you get : Let 's take an example of a notepad-like program . There is repetition in the menus in that there is a standard set of tools that appear in both the edit menu and the edit controls context menu ( the Cut , Copy , Paste , Select All ... ) .I 'd like to have a menu called ClipboardTools , which will appear in both the Edit and control context menus , without needing to create the items more than once . Of course in this case the repetition is n't that bad , but I have to deal with larger menus that appear in 3-4 different menus , and ideally not as sub menus . Menu 1 Item 1 Menu 1 Item 2 Menu 1 Item N -- -- -- -- - Menu 2 Item 1 Menu 2 Item 2 Menu 2 Item N",Join context menus "C_sharp : I am sending a post request to an api with c # webrequest and httpClient but always i get an error message from the api which says you posted invalid data in the header , but the point is when i send same data with chrome extension advanced rest client it works fine and i compared both request there is nothing different i have attached both request and my code , can anybody help to figure out what is the problem , this is the request from rest client app : and here is the request from c # and here is my c # code string item = `` < ? xml version=\ '' 1.0\ '' encoding=\ '' UTF - 8\ '' ? > '' + `` < request > '' + `` < Username > admin < /Username > '' + `` < Password > '' + password + `` < /Password > '' + `` < password_type > 4 < /password_type > '' + `` < /request > `` ; var request = ( HttpWebRequest ) WebRequest.Create ( `` http : //192.168.8.1/api/user/login '' ) ; request.Method = `` POST '' ; request.Headers [ `` _RequestVerificationToken '' ] = Token ; request.Headers [ `` Cookie '' ] = Sess ; byte [ ] bytes = Encoding.UTF8.GetBytes ( item ) ; request.ContentType = `` application/xml ; charset=UTF-8 '' ; request.ContentLength = bytes.Length ; Stream streamreq = request.GetRequestStream ( ) ; streamreq.Write ( bytes , 0 , bytes.Length ) ; streamreq.Close ( ) ; using ( HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ) using ( StreamReader reader = new StreamReader ( response.GetResponseStream ( ) ) ) { var result = reader.ReadToEnd ( ) ; }","Send Web request working with rest client app , but not working with c #" "C_sharp : I 'm using the great .NET library AutoPoco for creating test and Seed Data.In my model I have 2 date properties , StartDate and EndDate.I want the EndDate to be 3 hours after the start Date.I 've created a custom Data source for autopoco below that returns a random Datetime between a min and max dateBut in AutoPoco 's configuration how can i get my EndDate to be say , 3 hours after the autogenerated start Date ? Here 's the autopoco config class DefaultRandomDateSource : DatasourceBase < DateTime > { private DateTime _MaxDate { get ; set ; } private DateTime _MinDate { get ; set ; } private Random _random { get ; set ; } public DefaultRandomDateSource ( DateTime MaxDate , DateTime MinDate ) { _MaxDate = MaxDate ; _MinDate = MinDate ; } public override DateTime Next ( IGenerationSession session ) { var tspan = _MaxDate - _MinDate ; var rndSpan = new TimeSpan ( 0 , _random.Next ( 0 , ( int ) tspan.TotalMinutes ) , 0 ) ; return _MinDate + rndSpan ; } } IGenerationSessionFactory factory = AutoPocoContainer.Configure ( x = > { x.Conventions ( c = > { c.UseDefaultConventions ( ) ; } ) ; x.AddFromAssemblyContainingType < Meeting > ( ) ; x.Include < Meeting > ( ) .Setup ( ( c = > c.CreatedBy ) ) .Use < FirstNameSource > ( ) .Setup ( c = > c.StartDate ) .Use < DefaultRandomDateSource > ( DateTime.Parse ( `` 21/05/2011 '' ) , DateTime.Parse ( `` 21/05/2012 '' ) ) ; } ) ;",Generating a value dependent on another value with AutoPoco "C_sharp : I got an error today while trying to do some formatting to existing code . Originally , the code had the using directives declared outside the namespace : When I tried to insert the using directive inside the statement ( to comply with StyleCop 's rules ) , I got an error at the aliasing directive , and I had to fully qualify it : I wonder what difference there is between the two cases ? Does the location of the ( import-style ) using directive matter ? using System.Collections.Generic ; namespace MyNamespace { using IntPair = KeyValuePair < int , int > ; } namespace MyNamespace { using System.Collections.Generic ; //using IntPair = KeyValuePair < int , int > ; // Error ! using IntPair = System.Collections.Generic.KeyValuePair < int , int > ; // works }",Does the location of the ` using ` directive make a difference in C # ? "C_sharp : I have a deeply-nested object model , where some classes might look a bit like this : I 'd like to create my top-level object as a test fixture , but I want all the TBase instances ( such as in the instances collection above ) to be instances of TDerived rather than TBase.I thought I could do this quite simply using something like : ... but that does n't work , because the lambda expression in Customize is wrong . I 'm guessing there 's a way to do this , but AutoFixture seems to lack documentation , other than as a stream-of-consciousness on the developer 's blog.Can anyone point me in the right direction ? class TBase { ... } class TDerived : TBase { ... } class Container { ICollection < TBase > instances ; ... } class TopLevel { Container container1 ; Container container2 ; ... } var fixture = new Fixture ( ) ; fixture.Customize < TBase > ( c = > c.Create < TDerived > ( ) ) ; var model = this.fixture.Create < TopLevel > ( ) ;",How can I tell AutoFixture to always create TDerived when it instantiates a TBase ? "C_sharp : Given this simple model : And this simple query : ( userID is an int ) The following query is generated : Why is this AND NOT NULL criterion added ? The database does n't allow for nulls in that field , and an int ca n't be null in .netThis happens all over my queries . It 's pretty annoying , but is it impacting performance ? How can I get rid of it ? This is on a database-first model . public partial class UserColumnGrid { public int UserColumnGridID { get ; set ; } public int UserID { get ; set ; } public int ColumnGridID { get ; set ; } public int ColumnWidth { get ; set ; } public bool IsVisible { get ; set ; } public virtual ColumnGrid ColumnGrid { get ; set ; } public virtual User User { get ; set ; } } dbContext.UserColumnGrid.Where ( ucg = > ucg.UserID == userID ) .ToList ( ) ; SELECT [ Extent1 ] . [ UserColumnGridID ] AS [ UserColumnGridID ] , [ Extent1 ] . [ UserID ] AS [ UserID ] , [ Extent1 ] . [ ColumnGridID ] AS [ ColumnGridID ] , [ Extent1 ] . [ ColumnWidth ] AS [ ColumnWidth ] , [ Extent1 ] . [ IsVisible ] AS [ IsVisible ] FROM [ dbo ] . [ UserColumnGrid ] AS [ Extent1 ] WHERE ( [ Extent1 ] . [ UserID ] = 1 /* @ p__linq__0 */ ) AND ( 1 /* @ p__linq__0 */ IS NOT NULL )",Why does Entity Framework add unnecessary ( AND [ param ] IS NOT NULL ) in WHERE clause ? "C_sharp : I have this example code : The console output baffles me : Putting in fake processing 1.Fake processing finished 1.Putting in fake processing 2.Putting in fake processing 3.Fake processing finished 3.Fake processing finished 2.I am trying to chain the tasks so they execute one after another , what am I doing wrong ? And I ca n't use await , this is just example code , in reality I am queueing incoming tasks ( some asynchronous , some not ) and want to execute them in the same order they came in but with no parallelism , ContinueWith seemed better than creating a ConcurrentQueue and handling everythning myself , but it just does n't work ... static void Main ( string [ ] args ) { var t1 = Task.Run ( async ( ) = > { Console.WriteLine ( `` Putting in fake processing 1 . `` ) ; await Task.Delay ( 300 ) ; Console.WriteLine ( `` Fake processing finished 1 . `` ) ; } ) ; var t2 = t1.ContinueWith ( async ( c ) = > { Console.WriteLine ( `` Putting in fake processing 2 . `` ) ; await Task.Delay ( 200 ) ; Console.WriteLine ( `` Fake processing finished 2 . `` ) ; } ) ; var t3 = t2.ContinueWith ( async ( c ) = > { Console.WriteLine ( `` Putting in fake processing 3 . `` ) ; await Task.Delay ( 100 ) ; Console.WriteLine ( `` Fake processing finished 3 . `` ) ; } ) ; Console.ReadLine ( ) ; }",ContinueWith chaining not working as expected "C_sharp : I am trying to enable automatic ( no user prompt ) submission of hockey app crash reports on Xamarin.Forms ( Android and iOS ) : I have this for Android in MainActivity.cs : where CustomCrashListener is : This is n't sending any crash reports and HockeyApp with Xamarin documentation is thin . I am also trying to get this work on iOS . var customCrashListener = new CustomCrashListener ( ) ; CrashManager.Register ( this , `` appId '' , customCrashListener ) ; class CustomCrashListener : CrashManagerListener { public bool ShouldAutoUploadCrashes ( ) { return true ; } }",Xamarin.Forms + HockeyApp - auto submit crash reports "C_sharp : While digging in my company codebase i found something that astounds me : pairs of functions that differ only in optional parameters , here 's one example : what I find very strange , is that the compiler is happy with them.What is the explanation for this ? Am I missing something ? public static List < AvailableDay > Find ( string mailboxCalendarId , string [ ] typeTrameCles , DateTime dateMin , bool hasPhNonUrgent , bool hasPhUrgence , bool hasPhUrgenceDuJour ) public static List < AvailableDay > Find ( string mailboxCalendarId , string [ ] typeTrameCles , DateTime dateMin , bool hasPhNonUrgent , bool hasPhUrgence , bool hasPhUrgenceDuJour , int maxDaysResultCout = 1 )",Two methods that differ only in optional parameters "C_sharp : How can I get the type of the inner-most elements of a multidimensional array ? I 'd like to get the innermost element type regardless of the number of dimensions of the array ( Rank ) . var qq = new int [ 2,3 ] { { 1,2,3 } , { 1,2,4 } } ; var t = qq.GetType ( ) .ToString ( ) ; //is `` System.Int32 [ , ] '' var t2 = ? ? ; // should be `` System.Int32 ''",C # Get the type of a multidimensional array "C_sharp : If I declare a class as internal , why does the IL show it as private ? internal class Thing.class private auto ansi beforefieldinit Thing.Thing extends [ mscorlib ] System.Object","When I declare a class as internal , why does the IL show it as private ?" C_sharp : I have a database table which could contain many records and I 'd like to count the current total in the table . I was going to do a simple : Until I realized the return type for Count is int . What if the table is to hold more values than can be represented in 32 bits ? How can I count them ? Should I be counting them in a different way when we 're talking about that kind of scale ? DataContext.Table.Count ( c = > c.condition ) ;,LINQ and the Count extension method "C_sharp : i want to convert : toin c # .any elegant ways of doing this ? HECHT , WILLIAM Hecht , William","string conversion , first character upper of each word" "C_sharp : I am trying to create a graph that will show the progress of a workout . Every five button clicks a tick should be added to the graph . This is a example of how it should look.For demonstration purposes I am using a button click , In production the clicks will be every twenty revolutions of a wheel.Thanks in advance private int counter = 0 ; private void button1_Click ( object sender , EventArgs e ) { counter++ ; // code will go here }",Increase bar chart values with button clicks "C_sharp : I 'm writing some explicit operators to convert database model types to my domain model . Like so ( simplified example ) : However it 's possible that the roleEntity parameter is null . Most of times in the .net framework an explicit cast of a null instance results in an exception . Like so : But if the explicit operator would be adjusted , the above would function as expected : Question : Is it logical to create such explicit operators ? public static explicit operator DomainModel.Role ( Role roleEntity ) { DomainModel.Role role = new DomainModel.Role { RoleId = roleEntity.RoleId , Name = roleEntity.Name } ; return role ; } user.Role = ( DomainModel.Role ) _userRepository.GetRole ( user ) ; // Would normally results in a NullReferenceException public static explicit operator DomainModel.Role ( Role roleEntity ) { DomainModel.Role role = roleEntity == null ? null : new DomainModel.Role { RoleId = roleEntity.RoleId , Name = roleEntity.Name } ; return role ; }",Should explicit operators return null in c # ? "C_sharp : I have got a pipeline of tasks which basically is a variation of chain of responsibility pattern.A task in my pipeline looks as below..and my processor looks likeand my concrete implementation looks like this : ..and my tasks look like this : T could be different instances , but bound by a generic contract . One of the tasks are about mapping the incoming object into a completely different object and forwarding that instance from there onwards.Now as you would see , I 'm executing all the tasks in the pipeline , I would like to modify this to the following : Input for the Execute method for the next task should be from the previously executed task . If the CanExecute fails for a task then the pipeline should stop processing the tasks.Can you please help me in getting this . Also would you expect the code to be structured differently for this purpose ? internal interface IPTask < T > { bool CanExecute ( T instance ) ; T Process ( T instance ) ; } internal interface IProcessor < T > { T Execute ( T instance ) ; } public class Processor < T > : IProcessor < T > { private readonly ITasks < T > tasks ; public Processor ( ITasks < T > tasks ) { this.tasks= tasks ; } public T Execute ( T instance ) { var taskstoExecute = tasks.GetTasks ( ) .Where ( task = > task.CanExecute ( instance ) ) ; taskstoExecute.ToList ( ) .ForEach ( task= > task.Process ( instance ) ) ; return T ; } } internal interface ITasks < T > { IEnumerable < IPTask < T > > GetTasks ( ) ; }",Executing Chain of Responsibility variation "C_sharp : I am printing plain text in WPF by using a FlowDocument , FlowDocumentPaginator and PrintDialog . My approach is based on this article and is implemented as follows : This works good for printing stuff with narrow width . But when I try to print a long string , it all gets stuffed in a small area : I checked dimensions in the print dialog 's PrintTicket and in the paginator , and they seem to be okay : So , what is causing this problem and how can I fix it ? var printDialog = new PrintDialog ( ) ; if ( printDialog.ShowDialog ( ) == true ) { var flowDocument = new FlowDocument ( ) ; var paragraph = new Paragraph ( ) ; paragraph.FontFamily = new FontFamily ( `` Courier New '' ) ; paragraph.FontSize = 10 ; paragraph.Margin = new Thickness ( 0 ) ; paragraph.Inlines.Add ( new Run ( this.textToPrint ) ) ; flowDocument.FontSize = 10 ; flowDocument.Blocks.Add ( paragraph ) ; var paginator = ( ( IDocumentPaginatorSource ) flowDocument ) .DocumentPaginator ; printDialog.PrintDocument ( paginator , `` Chit '' ) ; }",WPF FlowDocument printing only to small area "C_sharp : Why does this declaration+assignment cause an error : while this does not : In is intuitive that the first statement should cause an error but not immediately clear why the second one is not.Furthermore , how could I tell if the SystemEvents.SessionEnding event has been actually unsubscribed after the call to handler ( null , null ) ? The GetInvocationList only works with delegates . // Use of unassigned local variable 'handler'.SessionEndingEventHandler handler = ( sender , e ) = > { isShuttingDown = true ; SystemEvents.SessionEnding -= handler ; } ; SessionEndingEventHandler handler = null ; handler = ( sender , e ) = > { isShuttingDown = true ; SystemEvents.SessionEnding -= handler ; } ; SystemEvents.SessionEnding += handler ; handler ( null , null ) ;",Use of unassigned local variable when creating an anonymous function closing on itself "C_sharp : I have a folder with a large amount of files inside of it . I want to be able to render each of my files as a button . And when I click on the button something will happen . As you can see there 's nothing crazy in the code . I have a panel on a form and I 've set auto scroll on the panel to true and auto size to false . This causes the form to maintain size and the buttons ( some of them anyway ) to get rendered off the form and I can scroll down to them.All good so far.If I have 100 or 200 file everything is ok , if I have 1932 files it takes about 10 seconds to render all the buttons.I 've read the follow question Super slow C # custom control and I understand that the approach I 'm using might not be the best to use here . And now the question at last : how does windows explorer handle this ? If I open this folder in Windows explorer it opens instantly.What type of control is windows explorer using ? Or is it doing it in a completly different way to me.Thanks private void Form1_Load ( object sender , EventArgs e ) { int x = 10 ; int y = 10 ; /// Process the list of files found in the directory . string [ ] fileEntries = Directory.GetFiles ( @ '' c : \lotsofDocs '' ) ; foreach ( string fileName in fileEntries ) { // do something with fileName Button newbotton = new Button ( ) ; newbotton.AutoSize = true ; newbotton.Text = fileName ; panel1.Controls.Add ( newbotton ) ; newbotton.Location = new Point ( x , y ) ; x += 150 ; if ( x == 760 ) { y += 50 ; x = 10 ; } }",how do I make my application as fast as windows explorer for rendering files "C_sharp : I have an interface called ICatalog as shown below where each ICatalog has a name and a method that will return items based on a Predicate < Item > function.A specific implementation of a catalog may be linked to catalogs in various format such as XML , or a SQL database.With an XML catalog I end up deserializing the entire XML file into memory , so testing each item with the predicate function does does not add a whole lot more overhead as it 's already in memory.Yet with the SQL implementation I 'd rather not retrieve the entire contents of the database into memory , and then filter the items with the predicate function . Instead I 'd want to find a way to somehow pass the predicate to the SQL server , or somehow convert it to a SQL query.This seems like a problem that can be solved with Linq , but I 'm pretty new to it . Should my interface return IQueryable instead ? I 'm not concerned right now with how to actually implement a SQL version of my ICatalog . I just want to make sure my interface will allow for it in the future . public interface ICatalog { string Name { get ; } IEnumerable < Item > GetItems ( Predicate < Item > predicate ) ; }",Linq based generic alternate to Predicate < T > ? "C_sharp : In C # , I open a file with FileShare.Delete . This allows me to open the file without restricting other processes from deleting it . For example : My questions are : What happens if the file is deleted by a different process after we created the stream , but before we read it ? Does the operating system keep a copy of the file until the stream\handle is closed ? Can I rely on reading the deleted file without getting any errors , or the wrong content ? using ( FileStream fs = new FileStream ( @ '' C : \temp\1.txt '' , FileMode.Open , FileAccess.Read , FileShare.ReadWrite | FileShare.Delete ) ) { int len = ( int ) fs.Length ; byte [ ] array = new byte [ len ] ; int bytesRead = fs.Read ( array , 0 , len ) ; }",What happens to a filestream when the file is deleted by a different process ? "C_sharp : I read through Jon Skeet 's article about beforefieldinit and I stumbled upon a question . He mentions that the type initializer can be invoked at any time before the first reference to a static field is called.This is my test code : The output is : But without the marked line , so without the invocation of the static field x1 , the output is : So the invocation of objects that are flagged with beforefieldinit affects the invocation of their type initializers ? Or does this belong to the strange effect of beforefieldinit he mentioned ? So , beforefieldinit can make the invocation of the type initializer even lazier or more eager . class Test1 { public static string x1 = EchoAndReturn1 ( `` Init x1 '' ) ; public static string EchoAndReturn1 ( string s ) { Console.WriteLine ( s ) ; return s ; } } class Programm { public static void Main ( ) { Console.WriteLine ( `` Starting Main '' ) ; Test1.EchoAndReturn1 ( `` Echo 1 '' ) ; Console.WriteLine ( `` After echo '' ) ; string y = Test1.x1 ; //marked line } } Init x1Starting MainEcho 1After echo Starting MainInit x1Echo 1After echo",C # BeforeFieldInit Jon Skeet explanation confusion "C_sharp : I have an AccountGroup which is a self-referencing entity . A leaf AccountGroup can contain 1 or more Accounts . Both entities have Balance property . Each AccountGroup has a Balance which is either a sum of Balances in sub-groups or sum of Balances of all Accounts ( in case of leaf group ) .In order to build a tree listing of all AccountGroups and Accounts I have to traverse this object graph recursively , which causes a lot ( I mean a lot ! ! ! ) of calls to DB ... Is there any way to improve upon this in such way that # of DB calls is reduced ? ThanksHere is the trimmed down codeAccount ( belongs to only 1 AccountGroup ) AccountGroup ( has 0 or many AccountGroups , has 1 or more Accounts if it is a leaf ) Calling Code public class Account { public int Id { get ; set ; } public int GroupId { get ; set ; } public string Name { get ; set ; } public decimal Balance { get ; set ; } public string AccountType { get ; set ; } public virtual AccountGroup Group { get ; set ; } } public class AccountGroup { public AccountGroup ( ) { Accounts = new HashSet < Account > ( ) ; Groups = new HashSet < AccountGroup > ( ) ; } public int Id { get ; set ; } public bool IsRoot { get { return Parent == null ; } } public bool IsLeaf { get { return ! Groups.Any ( ) ; } } public decimal Balance { get { return IsLeaf ? Accounts.Sum ( a = > a.Balance ) : Groups.Sum ( g = > g.Balance ) ; } } // if leaf group , get sum of all account balances , otherwise get sum of all subgroups public int ? ParentId { get ; set ; } public string Name { get ; set ; } public string Description { get ; set ; } public virtual ISet < Account > Accounts { get ; private set ; } public virtual ISet < AccountGroup > Groups { get ; private set ; } public virtual AccountGroup Parent { get ; set ; } } // start processing root groups ( ones without parent ) foreach ( var rootGroup in db.AccountGroups.Include ( g= > g.Groups ) .Where ( g = > g.ParentId == null ) ) { TraverseAccountGroup ( rootGroup , 0 ) ; } // recursive methodprivate static void TraverseAccountGroup ( AccountGroup accountGroup , int level ) { // // process account group // Console.WriteLine ( `` { 0 } { 1 } ( { 2 } ) '' , String.Empty.PadRight ( level * 2 , ' . ' ) , accountGroup.Name , level ) ; // // if subgroups exist , process recursivelly // if ( accountGroup.Groups.Any ( ) ) { foreach ( var subGroup in accountGroup.Groups ) { TraverseAccountGroup ( subGroup , level + 1 ) ; } } // // otherwise , process accounts belonging to leaf subgroup // else { foreach ( var account in accountGroup.Accounts ) { Console.WriteLine ( `` ACCOUNT [ { 0 } ] '' , account.Name ) ; } } }","EF Code First improving performance for self referencing , one to many relationships" "C_sharp : Why double dispatch via `` dynamic overload '' based on argument type is n't natively supported by C # ? I see this would require dynamic dispatching but since virtual method calls are also dispatched dynamically this would not be that strange to the language . So why this feature is not part of C # ? What would be most elegant solution to implement this functionality using Reflection ( maybe there are some libraries ) ? UPDATE indeed , because Method in this example is n't virtual and takes only one argument this would be still single dispatch but `` cardinality '' of dispatch is n't that important in this question as long as it 's > 0 . class Program { static void Main ( string [ ] args ) { var objs = new object [ ] { new Class1 ( ) , new Class2 ( ) } ; foreach ( var item in objs ) { Method ( item ) ; } } static void Method ( Class1 obj ) { } static void Method ( Class2 obj ) { } } class Class1 { } class Class2 { }",Single/double dispatch via `` dynamic overload '' in C # C_sharp : Suppose this is my condition and it is now using the ternary operator . Could someone suggest some other method other than If User.UserRoleID == 9 ? false : true,Is there any way to avoid use of Ternary Operator ? "C_sharp : In the following example , what happens to the process if it is still running once the code leaves the using statement ? using ( var p = new Process ( ) ) { p.StartInfo.FileName = `` c : \\temp\\SomeConsoleApp.exe '' ; p.Start ( ) ; }",What happens to a Process in a using statement without WaitForExit ( ) ? "C_sharp : I have a very basic asp.net MVC 6 app with basic routing , and I have a custom ErrorController to route errors to certain views.I am expecting however that when the user types in an URL that does not exist , an exception is thrown ( and I can handle it ) . However , no exception is thrown when I type in some random URL , I just get a blank page . I 'm pretty sure this worked in similarly in MVC < 6.The error handling itself works fine if I just throw an exception in a controller.Startup.cs ( partially ) public void Configure ( IApplicationEnvironment appEnv , IApplicationBuilder app , IHostingEnvironment env ) { if ( env.IsDevelopment ( ) ) { app.UseBrowserLink ( ) ; app.UseDeveloperExceptionPage ( ) ; } else { app.UseExceptionHandler ( HandleException ) ; } app.UseStaticFiles ( ) ; app.UseMvc ( routes = > MapRoutes ( routes , appEnv ) ) ; } private static void MapRoutes ( IRouteBuilder routes , IApplicationEnvironment env ) { routes.MapRoute ( name : `` default '' , template : `` { controller } / { action } / { id ? } '' , defaults : new { controller = `` main '' , action = `` index '' } ) ; } private static void HandleException ( IApplicationBuilder errorApp ) { # pragma warning disable CS1998 // Async method lacks 'await ' operators and will run synchronously errorApp.Run ( async context = > HandleErrorContext ( context ) ) ; # pragma warning restore CS1998 // Async method lacks 'await ' operators and will run synchronously } private static void HandleErrorContext ( HttpContext context ) { var error = context.Features.Get < IExceptionHandlerFeature > ( ) ; var exception = error.Error ; if ( exception == null ) { context.Response.Redirect ( `` ../error/external '' ) ; } else if ( exception is ExpirationException ) { context.Response.Redirect ( `` ../error/expired '' ) ; } else if ( exception is HttpException ) { var httpException = exception as HttpException ; int code = httpException.GetHttpCode ( ) ; context.Response.Redirect ( `` ../error/external ? code= '' + code ) ; } else { context.Response.Redirect ( `` ../error/external '' ) ; } }",MVC 6 no exception thrown for undefined routes "C_sharp : I am moving an existing ( and working ) ASP.NET web site to Azure web site . One of the bits of functionality on the site is signing an XML document . The code to get the key is : The last line is throwing a CryptographicException , with the message `` The system can not find the file specified '' .I have not put a key or container into Azure - my understanding is that the ServiceProvider would create one.I have reviewed this article , but did not get any clues.Clearly I am missing something fundamental . // retrieve a key from the key safe - this will create it if it does not exist yetSystem.Security.Cryptography.CspParameters csp = new CspParameters ( ) ; csp.KeyContainerName = `` MyKeyName '' ; System.Security.Cryptography.RSACryptoServiceProvider key = new RSACryptoServiceProvider ( csp ) ;",Using RSACryptoServiceProvider on Azure web site results in file not found error C_sharp : when multiplying a set of int 's and converting the result to a long I get a different answer as opposed to when I multiply a set of doubles and convert the result to a long . eg : Can anyone tell me why this happens ? Thank you int a = 5 ; int b = 5 ; int c = 7 ; int d = 6 ; int ee = 6 ; int f = 8 ; int g = 9 ; int h = 6 ; int i = 6 ; int j = 4 ; int k = 8 ; int l = 9 ; int m = 5 ; long x = a * b * c * d * ee * f * g * h * i * j * k * l * m ; double aa = 5 ; double ab = 5 ; double ac = 7 ; double ad = 6 ; double aee = 6 ; double af = 8 ; double ag = 9 ; double ah = 6 ; double ai = 6 ; double aj = 4 ; double ak = 8 ; double al = 9 ; double am = 5 ; long y = ( long ) ( aa * ab * ac * ad * aee * af * ag * ah * ai * aj * ak * al * am ) ;,Multiplication in C # error C_sharp : Supposing I have a class MyType : Given the following code : Which of these variable assignments would be the most efficient ? Is performance of GetType ( ) or typeof ( ) concerning enough that it would be beneficial to save off the type in a static field ? sealed class MyType { static Type typeReference = typeof ( MyType ) ; // ... } var instance = new MyType ( ) ; var type1 = instance.GetType ( ) ; var type2 = typeof ( MyType ) ; var type3 = typeReference ;,Which is more efficient : myType.GetType ( ) or typeof ( MyType ) ? "C_sharp : This does not work : System.NullReferenceException : Object reference not set to an instance of an object.This works : Both compile fine in VS2010 . public class A { private string _a_string ; public string AString { get { return _a_string ; } set { _a_string = value ; } } } public class B { private string _b_string ; private A _a ; public A A { get { return _a ; } set { _a = value ; } } public string BString { get { return _b_string ; } set { _b_string = value ; } } } B _b = new B { A = { AString = `` aString '' } , BString = `` bString '' } ; B _b = new B { A = new A { AString = `` aString '' } , BString = `` bString '' } ;",Why does this C # assignment throw an exception ? "C_sharp : For my own implementation of an Equals ( ) method , I want to check a bunch of internal fields . I do it like this : I would assume , that this compares the values , including null , for equality not the object address ( as a reference euqality compare operation would ) because : It is said so for `` predefined value types '' in this MSDN doc here.I assume Nullable < int > is such a `` predefined value type '' because of it is in the System Namespace according to this MSDN doc.Am I right to assume that the VALUES are compared here ? Note : Unit tests showed `` Yes '' , but I wanted to be reassured by others with this question , just in case I missed something . ... _myNullableInt == obj._myNullableInt & & _myString == obj._myString & & ...",Is Nullable < int > a `` Predefined value type '' - Or how does Equals ( ) and == work here ? "C_sharp : A query for a grid in an Entity Framework-backed .NET web application I 'm working on was giving a 500 error ( The cast to value type 'System.Int32 ' failed because the materialized value is null . Either the result type 's generic parameter or the query must use a nullable type . ) when the grid row object happened to have zero child items in a particular one-to-many relationship . The null was coming back on an unrelated integer property . Bafflingly , reversing the order of the two independent Let statements in the Linq expression made the error go away.That is , if there is only one Widget ( ID : 1 , CreatedOn : some datetime ) , which has no Bars and one Foo ( fValue : 96 ) orgives { WidgetID : 1 , fValue : 96 } as expected , butcomes back with { WidgetID : 1 , fValue : NULL } which of course crashes because Foo.fValue is an integer.All three expressions generate slightly different SQL queries under Entity Framework , which I would expect - the failing expression contains the clausewhich I believe is the culprit ( 0 Bars crossed with 1 Foo = 0 results ) . So I understand the `` how '' of the error ; what gets me is that I have no idea why the order of the LETs or whether I OrderBy with a Linq method call vs a Linq expression should make a difference.Here 's the reduced table schema / data if you want to experiment yourself : Can you explain why those 3 expressions are n't logically equivalent in Entity Framework ? from w in Widgets.OrderBy ( w = > w.CreatedOn ) let foo = w.Foos.FirstOrDefault ( ) let bar = w.Bars.FirstOrDefault ( ) select new { w.WidgetID , foo.fValue } from w in Widgetslet bar = w.Bars.FirstOrDefault ( ) let foo = w.Foos.FirstOrDefault ( ) orderby w.CreatedOnselect new { w.WidgetID , foo.fValue } from w in Widgets.OrderBy ( w = > w.CreatedOn ) let bar = w.Bars.FirstOrDefault ( ) let foo = w.Foos.FirstOrDefault ( ) select new { w.WidgetID , foo.fValue } ... ( SELECT TOP ( 1 ) [ Extent7 ] . [ fValue ] AS [ fValue ] FROM ( SELECT TOP ( 1 ) [ Extent6 ] . [ BarID ] AS [ BarID ] FROM [ dbo ] . [ Bars ] AS [ Extent6 ] WHERE [ Extent1 ] . [ WidgetID ] = [ Extent6 ] . [ bWidgetID ] ) AS [ Limit5 ] CROSS JOIN [ dbo ] . [ Foos ] AS [ Extent7 ] WHERE [ Extent1 ] . [ WidgetID ] = [ Extent7 ] . [ fWidgetID ] ) AS [ C1 ] ... create table Widgets ( WidgetID int not null primary key , CreatedOn datetime not null ) insert Widgets values ( 1 , '1995-02-03 ' ) create table Foos ( FooID int not null primary key , fWidgetID int not null references Widgets ( WidgetID ) , fValue int not null ) insert Foos values ( 7 , 1 , 96 ) create table Bars ( BarID int not null primary key , bWidgetID int not null references Widgets ( WidgetID ) , bValue int not null )",Why does the order of LET statements matter in this Entity Framework query ? "C_sharp : In my Messages controller , I want to check whether a certain dialog is on the stack for the incoming message prior to dispatching it to a dialog , so that I can suppress certain conditional behavior . I tried resolving IDialogStack as per this answer , like so : Here 's the modules being registered in my Global.asax : However , I get the following Exception : { `` An error occurred during the activation of a particular registration . See the inner exception for details . Registration : Activator = IDialogTask ( DelegateActivator ) , Services = [ Microsoft.Bot.Builder.Dialogs.Internals.IDialogStack , Microsoft.Bot.Builder.Dialogs.Internals.IDialogTask ] , Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime , Sharing = Shared , Ownership = OwnedByLifetimeScope -- - > Object reference not set to an instance of an object . ( See inner exception for details . ) '' With inner Exception : '' Object reference not set to an instance of an object . '' '' at Autofac.Core.Resolving.InstanceLookup.Activate ( IEnumerable1 parameters ) \r\n at Autofac.Core.Resolving.InstanceLookup. < Execute > b__5_0 ( ) \r\n at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare ( Guid id , Func1 creator ) \r\n at Autofac.Core.Resolving.InstanceLookup.Execute ( ) \r\n at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance ( ISharingLifetimeScope currentOperationScope , IComponentRegistration registration , IEnumerable1 parameters ) \r\n at Autofac.Core.Resolving.ResolveOperation.Execute ( IComponentRegistration registration , IEnumerable1 parameters ) \r\n at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent ( IComponentRegistration registration , IEnumerable1 parameters ) \r\n at Autofac.ResolutionExtensions.TryResolveService ( IComponentContext context , Service service , IEnumerable1 parameters , Object & instance ) \r\n at Autofac.ResolutionExtensions.ResolveService ( IComponentContext context , Service service , IEnumerable1 parameters ) \r\n at Autofac.ResolutionExtensions.Resolve [ TService ] ( IComponentContext context , IEnumerable1 parameters ) \r\n at Autofac.ResolutionExtensions.Resolve [ TService ] ( IComponentContext context ) \r\n at Progressive.CQBot.Controllers.MessagesController.d__0.MoveNext ( ) in D : \Source\Repos\QUO_Cognitive_Quoting\Src\CQBot\Controllers\MessagesController.cs : line 33 '' Is the advice in the linked answer deprecated ? Is there some module registration I 'm missing ? I would appreciate any direction ! public async Task < HttpResponseMessage > Post ( [ FromBody ] Activity incomingMessage ) { try { if ( incomingMessage.Type == ActivityTypes.Message ) { using ( var scope = DialogModule.BeginLifetimeScope ( Conversation.Container , activity ) ) { var stack = scope.Resolve < IDialogStack > ( ) ; } ... private void RegisterBotModules ( ) { var builder = new ContainerBuilder ( ) ; builder.RegisterModule ( new DialogModule ( ) ) ; builder.RegisterModule ( new ReflectionSurrogateModule ( ) ) ; builder.RegisterModule ( new DialogModule_MakeRoot ( ) ) ; builder.RegisterModule < GlobalMessageHandler > ( ) ; builder.RegisterModule ( new AzureModule ( Assembly.GetExecutingAssembly ( ) ) ) ; var store = new TableBotDataStore ( /*connection string*/ ) ; builder.Register ( c = > store ) .Keyed < IBotDataStore < BotData > > ( AzureModule.Key_DataStore ) .AsSelf ( ) .SingleInstance ( ) ; builder.Register ( c = > new CachingBotDataStore ( store , CachingBotDataStoreConsistencyPolicy.ETagBasedConsistency ) ) .As < IBotDataStore < BotData > > ( ) .AsSelf ( ) .InstancePerLifetimeScope ( ) ; builder.Update ( Conversation.Container ) ; var config = GlobalConfiguration.Configuration ; config.DependencyResolver = new AutofacWebApiDependencyResolver ( Conversation.Container ) ; }",How can I resolve the current dialog stack in my Bot Framework MessagesController ? "C_sharp : Is there any relationship between the open types List < > and IEnumerable < > ? Example : Is there any method to check the relationship between two open type , or the relationship only exist on closed type ? var type1 = typeof ( List < > ) ; var type2 = typeof ( IEnumerable < > ) ; //return falsetype2.IsAssignableFrom ( type1 ) ;",Relation between List < > and IEnumerable < > open type "C_sharp : According to NHProf , the use of implicit transactions is discouraged : http : //nhprof.com/Learn/Alerts/DoNotUseImplicitTransactionsHowever , NHibernate LINQ returns an IQueryable < > when reading objects from the database , and this is lazily evaluated . I have this method in a repository : The issue here is that the method will commit the transaction before data is evaluated . Is there a way to use the repository pattern and keep the IQueryable < > in an explicit transaction ? Or is it acceptable for read operations to use implicit transactions ? public IQueryable < T > GetAll < T > ( ) { using ( var transaction = _session.BeginTransaction ( ) ) { var data = _session.Linq < T > ( ) ; transaction.Commit ( ) ; return data ; } }",How do I keep an IQueryable < > within a transaction using the repository pattern ? "C_sharp : I ca n't find an answer to the following question : it 's clear , but the following is n't clear object o = 10 ; // Boxint i = ( int ) o ; // Unbox bool isInt = o is int ; // Is the unbox here or not ?",Does the IS operator unbox value type or not ? "C_sharp : I am trying to make a screenshot to the window of a process in Windows 7 64 bit , the problem is that I always get error in the following line : Saying `` invalid parameters '' , I made a throw to see the errors and width and height are always 0.Before in 32 bits it worked well , but now in 64 bits it does not work anymore.The code : How do I fix this error ? var bmp = new Bitmap ( width , height , PixelFormat.Format32bppArgb ) ; public void CaptureApplication ( ) { string procName = `` firefox '' ; var proc = Process.GetProcessesByName ( procName ) [ 0 ] ; var rect = new User32.Rect ( ) ; User32.GetWindowRect ( proc.MainWindowHandle , ref rect ) ; int width = rect.right - rect.left ; int height = rect.bottom - rect.top ; var bmp = new Bitmap ( width , height , PixelFormat.Format32bppArgb ) ; Graphics graphics = Graphics.FromImage ( bmp ) ; graphics.CopyFromScreen ( rect.left , rect.top , 0 , 0 , new Size ( width , height ) , CopyPixelOperation.SourceCopy ) ; bmp.Save ( `` c : \\tmp\\test.png '' , ImageFormat.Png ) ; } private class User32 { [ StructLayout ( LayoutKind.Sequential ) ] public struct Rect { public int left ; public int top ; public int right ; public int bottom ; } [ DllImport ( `` user32.dll '' ) ] public static extern IntPtr GetWindowRect ( IntPtr hWnd , ref Rect rect ) ; }",Take screenshot in process window "C_sharp : My class implements IEnumerable < T > twice . How can I get LINQ to work without casting hashtable every time ? I wrote my own covariant hashtable implementation that also inherits from .NET 's IDictionary < TKey , TValue > . Ultimately , it implements IEnumerable < T > twice with different types for T. I implemented the primary enumerable interface implicitly , and the other one explicitly . Something like this ( pseudocode ) : When I foreach the hash table , it takes as expected the primary enumerable : Now I want it to do the same thing in LINQ , but it flings compiler errors at me because it does not know which interface to pick for the extension methods : Error 1 : Could not find an implementation of the query pattern for source type 'HashTable ' . 'Select ' not found . Consider explicitly specifying the type of the range variable ' x ' . Error 2 : 'HashTable ' does not contain a definition for 'Select ' and no extension method 'Select ' accepting a first argument of type 'HashTable ' could be found ( are you missing a using directive or an assembly reference ? ) Maybe there 's some interface or inheritance trick I do n't know about ? For those who asked , here is the full tree of interfaces : Now you can see why I could n't make KeyValuePair < TKey , TValue > and IAssociation < TKey , TValue > the same . class HashTable < TKey , TValue > : ... IEnumerable < out IAssociation < out TKey , out TValue > > , IEnumerable < out KeyValuePair < TKey , TValue > > { // Primary : public IEnumerator < IAssociation < TKey , TValue > > GetEnumerator ( ) ; // Secondary : IEnumerator < KeyValuePair < TKey , TValue > > IEnumerable < KeyValuePair < TKey , TValue > > .GetEnumerator ( ) ; } using System ; using System.Collections.Generic ; using System.Linq ; var hashtable = new HashTable < string , int > ( ) ; foreach ( var kv in hashtable ) { // kv is IAssociation < string , int > } var xs1 = from x in hashtable // < -- 1 select x ; var xs2 = hashtable.Select ( x = > x ) ; // < -- 2 using SCG = System.Collections.Generic ; public class HashTable < TKey , TValue > : IKeyedCollection < TKey , TValue > , SCG.IDictionary < TKey , TValue > public interface IKeyedCollection < out TKey , out TValue > : ICollection < IAssociation < TKey , TValue > > public interface ICollection < out T > : SCG.IEnumerable < T > public interface IAssociation < out TKey , out TValue > // .NET Framework : public interface IDictionary < TKey , TValue > : ICollection < KeyValuePair < TKey , TValue > > public interface ICollection < T > : IEnumerable < T >",LINQ gets confused when implementing IEnumerable < T > twice "C_sharp : Is there a way to enter debug mode when a certain condition is met ? For example let 's say I would want to enter debug mode on the line on which i == 1 becomes true : I know it is possible to set conditional breakpoints like : But of course I could n't use that since I would have to add a conditional breakpoint for each line in the code where the condition value might get changed and that would get very messy in a real application.So , is there a way to globally set the condition i == 1 so that the debugger will break on the line on which the condition is met ? Thanks for your help ! using System ; namespace ConditionalDebug { public class Program { public static void Main ( string [ ] args ) { var r = new Random ( ) ; var i = r.Next ( 2 ) ; i += r.Next ( 2 ) ; i += r.Next ( 2 ) ; i += r.Next ( 2 ) ; i += r.Next ( 2 ) ; i = 1 ; Console.WriteLine ( i ) ; } } }",How to enter debug mode when a condition is met ? "C_sharp : I have a very simple DateTime object that is set to the date 01-01-0001 . I am supplied a value to add to this DateTime , in days . I am seeing an unexpected offset in my results though , of two days . Let 's pretend I print out the results of the AddDays ( ) call , like so : With the value seen above ( 735768.0 ) I expect an output of `` 6/18/2015 12:00:00 AM '' . However , instead I get `` 6/20/2015 12:00:00 AM '' . When I go to the following website and calculate the duration in days between 01-01-0001 -- > 06/18/2015 I get a value of 735,768 days , as expected : http : //www.timeanddate.com/date/durationresult.html ? m1=01 & d1=01 & y1=0001 & m2=06 & d2=18 & y2=2015Am I doing something wrong , or is there something going on under the hood that I am not aware of ? In case you are wondering , the 735,768 represents the first time value of the data that I am working with . The data is expected to start at 06/18/2015 00:00:00.Edit : I should note I merely provided that particular website as an example of a conflicting source . Other websites , including the government weather agency I get the data from all give me 06-18-2015 . This does n't mean C # is wrong . I am more so curious as to where this offset came from , and why . DateTime myDateTime = DateTime.Parse ( `` 01-01-0001 00:00:00 '' ) ; Console.WriteLine ( myDateTime.AddDays ( 735768.0 ) ) ;",C # DateTime AddDays Unexpected Offset "C_sharp : Is there any way to store data in the table kind of this : Inside SettingsModel column , which is defined in Linq-to-Sql like this : And also with DataContext option turned to the : With the class SettingsModel defined like this : This way ? ... You see , the code above doesnt work correctly , it is throwing exception which says that it can not convert string to MainTableSetting which means that either it can not save all the serialized data or that plus can not deserialize it back.I need some advices how to point this Linq-to-Sql to actually do serialization ( and vice versa ) when I access the database . namespace ElQueue.DataClasses { [ DataContract ] public sealed class SettingsModel { [ DataMember ( IsRequired = true ) ] public int [ ] VideoMediaData { get ; set ; } } } using ( SomeDataContext dataContext = new SomeDataContext ( ) ) { SettingsModel m = new SettingsModel ( ) ; m.VideoMediaData = new int [ ] { 1 , 2 , 3 } ; dataContext.MainTableSettings.InsertOnSubmit ( new MainTableSetting ( ) { SettingsModel = m } ) ; dataContext.SubmitChanges ( ) ; } using ( SomeDataContext dataContext = new SomeDataContext ( ) ) { var r = dataContext.MainTableSettings.Single ( ) ; }",Automatic serialization with Linq to Sql "C_sharp : I am migrating an application from ASP.NET Web Forms to ASP.NET MVC 3 . One of the central and critical pieces is currently locked away in its own directory . I have restricted unauthorized user from accessing this directory by using the following in my web.config file : My question is , how do I implement this same type of security in ASP.NET MVC 3 ? I have a hunch that it involves setting attributes on my Controller classes . However , the AuthorizeAttribute looks like it only accepts a list of user names and not an auth status ( please correct me if I 'm wrong ) . I looked at the sample ASP.NET internet application and I did n't see anything special being configured in it.Can someone please point me in the correct direction on this ? Thanks ! < location path= '' home '' allowOverride= '' false '' > < system.web > < authorization > < deny users= '' ? `` / > < allow users= '' * '' / > < /authorization > < /system.web > < /location >",Custom authorization in ASP.NET MVC 3 "C_sharp : I see this in many projects that demonstrate the use of CAEmitterLayer , but how does it translate to MonoTouch aka Xamarin.iOS ? I know I can use UIView.Layer.AddSubLayer ( ) but there seems to be performance impact . + ( Class ) layerClass { //configure the UIView to have emitter layer return [ CAEmitterLayer class ] ; }",How to implement + ( Class ) layerClass in Xamarin.iOS ? "C_sharp : While running some test code in OpenCL ( using Cloo C # ) , I started getting these OutOfResource errors from OpenCL and sometimes Unity just crashes entirely before I get an exception . I am basically re-calling a kernel function over and over with varying number of global/local work items to check timing . I leave the arguments the same and call the kernel starting with 2x2x2 global and 2x2x2 local and iterating uperwards checking only valid sizes . It works fine occasionally , but most of the time it completes about 30 or 40 Execute ( ) calls and then crashes on the next Execute ( ) call . Note : Execute refers to the OpenCL.dll on the computer . The stack trace Unity returns is NULL I assume because of the native code.Anyone have any idea what could be causing this ? Note : This version of Cloo is Cloo-Unity from GitHub and I am using it in Unity . The equivalent OpenCL function being called when I get the error is clEnqueueNDRangeKernel ( ) , but it is called Execute ( ) in Cloo.Code Sample : //Setup inputs one time ... foreach ( var input in p_inputs ) { inputs.Add ( input.Function , input ) ; profiles.Add ( input.Function , new RunProfile ( input.Function , input.Weight ) ) ; input.Input.Prepare ( package [ input.Function ] ) ; } //Profile ... DateTime start ; int g_state = 0 ; int l_state = 0 ; long [ ] g = new long [ 3 ] { 2 , 2 , 2 } ; long [ ] l = new long [ 3 ] { 2 , 2 , 2 } ; while ( g [ 0 ] * g [ 1 ] * g [ 2 ] < Device.MaxWorkGroupSize ) { l [ 0 ] = 2 ; l [ 1 ] = 2 ; l [ 2 ] = 2 ; l_state = 0 ; //Reset locals bool proceed = true ; while ( proceed ) { proceed = ( l [ 0 ] ! = g [ 0 ] || l [ 1 ] ! = g [ 1 ] || l [ 2 ] ! = g [ 2 ] ) ; if ( CLUtilities.ValidateExecutionParameters ( Device , g , l ) ) { Debug.Log ( `` Profiling Start : `` + g.ToEnumeratedString ( ) + `` / `` + l.ToEnumeratedString ( ) ) ; foreach ( var profile in profiles ) { start = DateTime.Now ; //Exception here when on ( g=6x4x4 , l=6x4x4 ) package.Execute ( package [ profile.Key ] , g , l ) ; package.Commands.Flush ( ) ; package.Commands.Finish ( ) ; float time = ( float ) ( DateTime.Now - start ) .TotalMilliseconds ; profile.Value.AddRun ( g , l , time ) ; } Debug.Log ( `` Profiling Ending : `` + g.ToEnumeratedString ( ) + `` / `` + l.ToEnumeratedString ( ) ) ; } l [ l_state ] += 2 ; l_state = ( l_state == 2 ) ? 0 : l_state + 1 ; } g [ g_state ] += 2 ; g_state = ( g_state == 2 ) ? 0 : g_state + 1 ; }",OpenCL Cloo : Out of Resources Error "C_sharp : Been using C # for about five years and only now did it strike me about the class visibility of custom exceptions . It 's perfectly legal to write internal or even private nested exceptions like so : So when you go about throwing these exceptions in your DLLs , only the ( minority of ) people doing decent ( non pokemon ) exception handling get their apps crashed.So my question is , what 's the purpose of such a pattern ? Or why is this even legal ? internal class WhyDoThis : Exception { } public class Foo { private class WhyWhyWhy : Exception { } }",Exception Class Visibility ? "C_sharp : Given an object , I would like to create a mock that implements the interface of the object and mocks one method , but forwards the rest of the methods to the real object , not the base class.For example : So , in the example I want to mock just ISqlUtil.SpecialMethodToBeMocked and forward the rest of methods/properties to the existing instance sqlUtil.Is it possible in Moq.NET ? EDIT 1It should work for generic methods as well . ISqlUtil sqlUtil = GetTheRealSqlUtilObjectSomehow ( ... ) ; var mock = new Mock < ISqlUtil > ( ) ; mock.Setup ( o = > o.SpecialMethodToBeMocked ( ... ) ) .Returns < ... > ( ... ) // Here I would like to delegate the rest of the methods to the real sqlUtil object . How ?",How to forward to another object when using .NET Moq ? "C_sharp : Anyone ever had problems with SlideInEffect and TurnstileFeatherEffect from windows phone toolkit ? I am trying to make SlideInEffect work on LongListSelector and LongListMultiSelector with no luck so far.Also the TurnstileFeatherEffect does not work when the page is loading but it does work when navigating away from them . Same applies to all pages ( panorama / pivot / normal pages ) .Take for example this code on a normal page : Also note that I changed RootFrameto new TransitionFrame ( ) . < phone : PhoneApplicationPage x : Class= '' SamplePage.Pages.About '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : phone= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone '' xmlns : shell= '' clr-namespace : Microsoft.Phone.Shell ; assembly=Microsoft.Phone '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' FontFamily= '' { StaticResource PhoneFontFamilyNormal } '' FontSize= '' { StaticResource PhoneFontSizeNormal } '' Foreground= '' { StaticResource PhoneForegroundBrush } '' SupportedOrientations= '' Portrait '' Orientation= '' Portrait '' mc : Ignorable= '' d '' d : DesignHeight= '' 768 '' d : DesignWidth= '' 480 '' xmlns : toolkit= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone.Controls.Toolkit '' shell : SystemTray.IsVisible= '' True '' > < ! -- Transitions -- > < toolkit : TransitionService.NavigationInTransition > < toolkit : NavigationInTransition > < toolkit : NavigationInTransition.Backward > < toolkit : TurnstileFeatherTransition Mode= '' BackwardIn '' / > < /toolkit : NavigationInTransition.Backward > < toolkit : NavigationInTransition.Forward > < toolkit : TurnstileFeatherTransition Mode= '' ForwardIn '' / > < /toolkit : NavigationInTransition.Forward > < /toolkit : NavigationInTransition > < /toolkit : TransitionService.NavigationInTransition > < toolkit : TransitionService.NavigationOutTransition > < toolkit : NavigationOutTransition > < toolkit : NavigationOutTransition.Backward > < toolkit : TurnstileFeatherTransition Mode= '' BackwardOut '' / > < /toolkit : NavigationOutTransition.Backward > < toolkit : NavigationOutTransition.Forward > < toolkit : TurnstileFeatherTransition Mode= '' ForwardOut '' / > < /toolkit : NavigationOutTransition.Forward > < /toolkit : NavigationOutTransition > < /toolkit : TransitionService.NavigationOutTransition > < ! -- LayoutRoot is the root grid where all page content is placed -- > < Grid x : Name= '' LayoutRoot '' Background= '' White '' > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < ! -- TitlePanel contains the name of the application and page title -- > < StackPanel Grid.Row= '' 0 '' Margin= '' 12,17,0,20 '' > < TextBlock Text= '' ABOUT '' Style= '' { StaticResource PhoneTextNormalStyle } '' Foreground= '' # 404041 '' FontWeight= '' Bold '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 0 '' / > < /StackPanel > < Grid x : Name= '' ContentPanel '' Grid.Row= '' 1 '' Margin= '' 24,0,0,0 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' > < Grid > < Image Height= '' 100 '' Source= '' /Assets/Images/logo.png '' Margin= '' -5,0,0,0 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Top '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 1 '' / > < StackPanel Margin= '' 0,90,0,0 '' > < StackPanel Margin= '' 0,0,0,0 '' Orientation= '' Horizontal '' HorizontalAlignment= '' Left '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 2 '' > < Image Height= '' 76 '' Width= '' 76 '' Margin= '' -16,0 , -20,0 '' Source= '' /Assets/AppBar/appbar.shield.png '' / > < HyperlinkButton Foreground= '' # FF474747 '' NavigateUri= '' http : //sample.com/ '' TargetName= '' _anything '' Content= '' Privacy Policy '' / > < /StackPanel > < StackPanel toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 3 '' Margin= '' 0 , -20,0,0 '' Orientation= '' Horizontal '' HorizontalAlignment= '' Left '' > < Image Height= '' 76 '' Width= '' 76 '' Margin= '' -16,0 , -20,0 '' Source= '' /Assets/AppBar/appbar.email.png '' / > < HyperlinkButton Foreground= '' # FF474747 '' NavigateUri= '' http : //sample.com/ '' TargetName= '' _anything '' Content= '' Send Feedback '' / > < /StackPanel > < /StackPanel > < ScrollViewer Margin= '' 0,210,0,0 '' > < Grid > < StackPanel Margin= '' 2,0,12,0 '' > < ! -- HEADER -- > < TextBlock TextWrapping= '' Wrap '' Text= '' Version '' FontWeight= '' Bold '' FontSize= '' 30 '' Foreground= '' # FF363636 '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 4 '' / > < ! -- BODY -- > < RichTextBox TextWrapping= '' Wrap '' Margin= '' -10,0,0,0 '' TextAlignment= '' Justify '' FontSize= '' 24 '' Foreground= '' # FF363636 '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 5 '' > < Paragraph > < Run Text= '' 0.0.1 '' / > < /Paragraph > < /RichTextBox > < ! -- HEADER -- > < TextBlock TextWrapping= '' Wrap '' Text= '' Description '' FontWeight= '' Bold '' FontSize= '' 30 '' Foreground= '' # FF363636 '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 6 '' / > < ! -- BODY -- > < RichTextBox TextWrapping= '' Wrap '' Margin= '' -10,0,0,0 '' TextAlignment= '' Justify '' FontSize= '' 24 '' Foreground= '' # FF363636 '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 7 '' > < Paragraph > < Run Text= '' Lorem Ipsum is simply dummy text of the printing and typesetting industry . Lorem Ipsum has been the industry 's standard dummy text ever since the 1500s , when an unknown printer took a galley of type and scrambled it to make a type specimen book . It has survived not only five centuries , but also the leap into electronic typesetting , remaining essentially unchanged . `` / > < /Paragraph > < /RichTextBox > < ! -- HEADER -- > < TextBlock TextWrapping= '' Wrap '' Text= '' Developed by '' FontWeight= '' Bold '' FontSize= '' 30 '' Foreground= '' # FF363636 '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 8 '' / > < ! -- BODY -- > < Grid HorizontalAlignment= '' Left '' Width= '' 440 '' toolkit : TurnstileFeatherEffect.FeatheringIndex= '' 9 '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' Auto '' / > < ColumnDefinition Width= '' Auto '' / > < /Grid.ColumnDefinitions > < Image Grid.Column= '' 0 '' HorizontalAlignment= '' Left '' Source= '' /Assets/Images/logo.png '' > < /Image > < Image Grid.Column= '' 1 '' Margin= '' 5,0,0,0 '' HorizontalAlignment= '' Left '' Source= '' /Assets/Images/logo.png '' > < /Image > < /Grid > < /StackPanel > < /Grid > < /ScrollViewer > < /Grid > < /Grid > < /Grid > < /phone : PhoneApplicationPage >",SlideInEffect and TurnstileFeatherEffect not working "C_sharp : I want all the positive integer values after the last negative value.Below is list of Integer values : I tryedExpected Output List < int > lst = new List < int > ( ) ; lst.Add ( 1 ) ; lst.Add ( 3 ) ; lst.Add ( 5 ) ; lst.Add ( -3 ) ; lst.Add ( 4 ) ; lst.Add ( -4 ) ; lst.Add ( 5 ) ; lst.Add ( 6 ) ; lst.Skip ( lst.Max ( 0 , lst.Count - 1 ) ) .ToList ( ) ; Last positive values after last negative value : in example list last negative value is -4and last positive values are 5 , 6 , So I want 5 and 6 from given list",How to get positive values after last negative value in a list ? "C_sharp : I am trying to make a UWP app using the RIOT API for League of Legends.When I go to their website to generate the JSON I get something like this : When I select this JSON and copy it into a new class using the special paste method in Visual Studio 2015 I get these classes with these properties : I created a new class called LOLFacade for connecting to the RiotAPI : This is the button event handler method : I hard coded the regionName and the user for testing purposes . This works with my username : `` gigaxel '' .When I try another username for example like `` xenon94 '' I get an exception : When I change the property name in Rootobject from gigaxel to xenon94 like this : When I recompile my code it works for the username xenon94 but it does n't work for my username `` gigaxel '' .I want it to work for any given username . { `` gigaxel '' : { `` id '' : 36588106 , `` name '' : `` Gigaxel '' , `` profileIconId '' : 713 , `` revisionDate '' : 1451577643000 , `` summonerLevel '' : 30 } } public class Rootobject { public Gigaxel gigaxel { get ; set ; } } public class Gigaxel { public int id { get ; set ; } public string name { get ; set ; } public int profileIconId { get ; set ; } public long revisionDate { get ; set ; } public int summonerLevel { get ; set ; } } public class LOLFacade { private const string APIKey = `` secret : D '' ; public async static Task < Rootobject > ConnectToRiot ( string user , string regionName ) { var http = new HttpClient ( ) ; string riotURL = String.Format ( `` https : // { 0 } .api.pvp.net/api/lol/ { 0 } /v1.4/summoner/by-name/ { 1 } ? api_key= { 2 } '' , regionName , user , APIKey ) ; var response = await http.GetAsync ( riotURL ) ; var result = await response.Content.ReadAsStringAsync ( ) ; return JsonConvert.DeserializeObject < Rootobject > ( result ) ; } } Rootobject root = new Rootobject { gigaxel = new Gigaxel ( ) } ; root = await LOLFacade.ConnectToRiot ( `` gigaxel '' , '' EUNE '' ) ; string name = root.gigaxel.name ; int level = root.gigaxel.summonerLevel ; InfoTextBlock.Text = name + `` is level `` + level ; Object reference not set to an instance of an object . public class Rootobject { public Gigaxel xenon94 { get ; set ; } }",Deserialize json into c # classes "C_sharp : I was using ReSharper plugin on VS2010 and i was generating an interface method.ReSharper put an @ on the parameter name . WHat is that used for ? Whats the difference forThanks ! int Count ( Func < ContratoList , bool > @ where ) ; int Count ( Func < ContratoList , bool > where ) ;",C # @ modifier for methods parameters "C_sharp : When I was writing some I/O routine in C++ , I would usually make it as generic as possible , by operating on the interfaces from < iostream > .For example : How should the same be done in C # ? I suspect I could write my routines based on the System.IO.TextReader or System.IO.TextWriter , but I 'm not sure.Obviously I 'm seeking for a same base class in C # , which is as generic as std : :istream or std : :ostream and which can be extended in many ways ( for example , as boost : :iostreams extends the std : : streams ) . void someRoutine ( std : :istream & stream ) { ... }",C # - stream question C_sharp : I was wondering what is the best/correct way of writing asynchronous code that is composed of two ( or more ) async and dependent ( the first have to finish to execute second ) operations.Example with async/await : Example with Continuation : await RunFirstOperationAsync ( ) ; await RunSecondOperationAsync ( ) ; await RunFirstOperationAsync ( ) .ContinueWith ( t = > RunSecondOperationAsync ( ) ) ;,Sequential await VS Continuation await "C_sharp : I just gave an answer to a quite simple question by using an extension method . But after writing it down i remembered that you ca n't unsubscribe a lambda from an event handler.So far no big problem . But how does all this behave within an extension method ? ? Below is my code snipped again . So can anyone enlighten me , if this will lead to myriads of timers hanging around in memory if you call this extension method multiple times ? I would say no , cause the scope of the timer is limited within this function . So after leaving it no one else has a reference to this object . I 'm just a little unsure , cause we 're here within a static function in a static class.UpdateJust to clarify i used System.Windows.Forms.Timer . So from your answers it seems , that especially using this timer class just was the right choice cause it does anything the way as i would expect it in this case . If you try another timer class in this case you can run into trouble as Matthew found out.Also i found a way by using WeakReferences if my objects are staying alive or not.Update 2After a little sleep and a little more thinking , i also made another change to my tester ( answer below ) i just added a GC.Collect ( ) after the last line and set the duration to 10000 . After starting the BlinkText ( ) several times i hitted all the time my button2 to get the current state and to force a garbage collection . And as it seems all the timers will be destroyed after calling the Stop ( ) method . So also a garbage collection while my BlinkText is already left and the timer is running does n't lead to any problems.So after all your good responses and a little more testing i can happily say that it just does what it should without leaving timers in the memory nor throwing away the timers before they done their work . public static class LabelExtensions { public static Label BlinkText ( this Label label , int duration ) { System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer ( ) ; timer.Interval = duration ; timer.Tick += ( sender , e ) = > { timer.Stop ( ) ; label.Font = new Font ( label.Font , label.Font.Style ^ FontStyle.Bold ) ; } ; label.Font = new Font ( label.Font , label.Font.Style | FontStyle.Bold ) ; timer.Start ( ) ; return label ; } }",Lambdas within Extension methods : Possible memory leak ? "C_sharp : I am programming a stocks/production program for a school project ( bike factory ) and I have to round some numbers up such as the bikes that have to be produced ( due to fallout it are doubles ) .If I use the following code : I get as an answer 110 , but that 's not right , it should be 109 ( 9 % of 100 ) . Although it seems to work with values below 9 % .What am I doing wrong ? double test = Math.Ceiling ( 100 * 1.09 ) ; label75.Text = Convert.ToString ( test ) ;",Rounding up c # giving wrong answer "C_sharp : Can someone tell me what I 'm doing wrong with the following Linq query ? I 'm trying to find the directory with the highest aphanumerical value.EDIT : The above code does not compile , the error that the compiler generates is : DirectoryInfo [ ] diList = currentDirectory.GetDirectories ( ) ; var dirs = from eachDir in diList orderby eachDir.FullName descending select eachDir ; MessageBox.Show ( dirs [ 0 ] .FullName ) ; Can not apply indexing with [ ] to an expression of type 'System.Linq.IOrderedEnumerable < System.IO.DirectoryInfo >",Check Directories in C # using Linq "C_sharp : I never liked implicit operators ( prefer extension methods ) because it is hard to see visually when that cast/conversion happens in the code . Imagine if you have example like below : Above implicit operator helps you to cast/convert deal in Xml format into Deal Object . Usually when you right click on a method , you can use `` Find Usages '' ( or Alt+F7 ) on it , which is quite helpful , is there anything similar for implicit operators ? I think that 's another reason to use the Extensions methods where possible . public static implicit operator Deal ( string dealAsXml ) { //convert the xml into Deal object }",How To Get `` Find Usages '' working with implicit operator methods ? "C_sharp : I am working on a Web Forms project that loads the results of Sql queries into DataTables.These DataTables are passed up to the front-end where we bind them to a Repeater web control.This works great . However , now we 'd like to bind to our own custom classes instead of a DataTable . Unfortunately , what I thought was the obvious answer did n't work ( implementing IDictionary < string , object > on our class ) . What do we need to have Eval bind to Datum without creating a concrete property for every binding ? Clearly DataRow does n't have to concretely implement every property we bind . So , somehow it seems that Eval is able to look up the property values by name on DataRow.Here is the custom classHere is where the DataSource is set in the aspx.cs fileAnd here is the binding in the aspx fileUsing the above example we get an error saying that the property in question does n't exist , which is true , but it does n't exist on DataRow either . How can I make it bind like System.Data.DataRow ? public class Datum : IDictionary < string , object > { private Dictionary < string , object > _entries ; public Datum ( ) { _entries = new Dictionary < string , object > ( ) ; } public object this [ string s ] { get { return this._entries [ s ] ; } } ... } rptTags.DataSource = new [ ] { new Datum { { `` Count '' , 1 } } , new Datum { { `` Count '' , 2 } } ; < asp : Repeater ID= '' rptTags '' runat= '' server '' > < ItemTemplate > < % # ( int ) Eval ( `` Count '' ) > < /ItemTemplate > < /asp : Repeater >",Dynamic Binding to Custom Business Object at Runtime "C_sharp : I have an image in different assembly : ( .NET Standard 1.4 ) ResourcesAssembly/Common/Images/CompanyLogo.png - mandatory requirementBuild Action : Content - mandatory requirementCopy to output directory : Copy if newer ( I checked after a compilation - the required image is presented in output directory where my exe is located - for example , Debug/Common/Images/CompanyLogo.png . So there should be no problem to get it from there . ) I want to paste it in my app 's assembly ( WPF ) inside a window . I try 2 variants.1.Image in interface is visible at runtime . But VS 's XAML designer does n't show the image at design time and says it is an error : Could not find a part of the path ' C : \Program Files ( x86 ) \Microsoft Visual Studio\2017\Community\Common7\IDE\Common\Images\CompanyLogo.png'.2.Image is not visible at runtime , but at design time all are OK.Visual studio 2017 Community Edition 15.4.4.So the first variant seems suitable for me , but that strange error - why it tries to find the image in Visual Studio folder ? `` siteoforigin '' option relates to the application exe , not to the Visual Studio exe , is n't it ? UPDATETried the second variant with build action as `` Embedded resource '' ( ResourcesAssembly is a .NET Standard 1.4 project ) . Even cleaned and rebuilt the solution . Result is the same as in the second variant : image is not visible at runtime , but at design time it is visible . < Image Source= '' pack : //siteoforigin : , , ,/Common/Images/CompanyLogo.png '' / > < Image Source= '' pack : //application : , , ,/ResourcesAssembly ; component/Common/Images/CompanyLogo.png '' / >",C # - Loading image from different assembly "C_sharp : If I have a format string that utilizes the same place holder multiple times , like : does person.GetFullName ( ) get evaluated twice , or is the compiler smart enough to know these are the same value , and should be evaluated once ? emailBody = $ '' Good morning { person.GetFullName ( ) } , blah blah blah , { person.GetFullName ( ) } would you like to play a game ? `` ;",Does string interpolation evaluate duplicated usage ? C_sharp : If I have a class with a ctor set up for multi-injection like this : And bindings set up like this : Then I would expect Shogun to be constructed with both weapons injected ? But this is n't the case - it only gets the Dagger.If I add a further binding like this : Then Shogun gets the Dagger and the Shuriken . WhenInjectedInto < T > ( ) looks like it should only be constraining the binding it is applied to and not affecting other bindings . I find this behaviour very misleading.Can someone explain what is happening here ? public Shogun ( IEnumerable < IWeapon > allWeapons ) { this.allWeapons = allWeapons ; } Bind < IWeapon > ( ) .To < Sword > ( ) ; Bind < IWeapon > ( ) .To < Dagger > ( ) .WhenInjectedInto < Shogun > ( ) ; Bind < IWeapon > ( ) .To < Sword > ( ) ; Bind < IWeapon > ( ) .To < Dagger > ( ) .WhenInjectedInto < Shogun > ( ) ; Bind < IWeapon > ( ) .To < Shuriken > ( ) .WhenInjectedInto < Shogun > ( ) ;,Ninject multi-injection is not as greedy as I would have thought ! How come ? "C_sharp : I just read Eric Lippert 's `` Arrays considered somewhat harmful '' article . He tells his readers that they `` probably should not return an array as the value of a public method or property , '' with the following reasoning ( slightly paraphrased ) : Now the caller can take that array and replace the contents of it with whatever they please . The sensible thing to return is IList < > . You can build yourself a nice read-only collection object once , and then just pass out references to it as much as you want.In essence , An array is a collection of variables . The caller doesn ’ t want variables , but it ’ ll take them if that ’ s the only way to get the values . But neither the callee nor the caller wants those variables to ever vary.In an attempt to understand what he meant by variables vs. values , I built demo class that has Array and IList < > fields , and methods that return references to both . Here it is on C # Pad.If I understand correctly , the GetArr ( ) method is Lippert 's bad practice , and GetList ( ) is his sensible practice . Here is a demo of the bad caller mutability behavior of GetArr ( ) : But I do n't understand his distinction - the IList < > reference has the same caller mutation problem : Obviously , I trust that Eric Lippert knows what he 's talking about , so where have I misinterpreted him ? In what way is a returned IList < > reference safer than an Array reference ? class A { private readonly int [ ] arr = new [ ] { 10 , 20 , 30 , 40 , 50 } ; private readonly List < int > list = new List < int > ( new [ ] { 10 , 20 , 30 , 40 , 50 } ) ; public int [ ] GetArr ( ) { return arr ; } public IList < int > GetList ( ) { return list ; } } var a = new A ( ) ; var arr1 = a.GetArr ( ) ; var arr2 = a.GetArr ( ) ; Console.WriteLine ( `` arr1 [ 2 ] : `` + arr1 [ 2 ] .ToString ( ) ) ; // > arr1 [ 2 ] : 30Console.WriteLine ( `` arr2 [ 2 ] : `` + arr2 [ 2 ] .ToString ( ) ) ; // > arr2 [ 2 ] : 30// ONE CALLER MUTATESarr1 [ 2 ] = 99 ; // BOTH CALLERS AFFECTEDConsole.WriteLine ( `` arr1 [ 2 ] : `` + arr1 [ 2 ] .ToString ( ) ) ; // > arr1 [ 2 ] : 99Console.WriteLine ( `` arr2 [ 2 ] : `` + arr2 [ 2 ] .ToString ( ) ) ; // > arr2 [ 2 ] : 99 var a = new A ( ) ; var list1 = a.GetList ( ) ; var list2 = a.GetList ( ) ; Console.WriteLine ( `` list1 [ 2 ] : `` + list1 [ 2 ] .ToString ( ) ) ; // > list1 [ 2 ] : 30Console.WriteLine ( `` list2 [ 2 ] : `` + list2 [ 2 ] .ToString ( ) ) ; // > list2 [ 2 ] : 30// ONE CALLER MUTATESlist1 [ 2 ] = 99 ; // BOTH CALLERS AFFECTEDConsole.WriteLine ( `` list1 [ 2 ] : `` + list1 [ 2 ] .ToString ( ) ) ; // > list1 [ 2 ] : 99Console.WriteLine ( `` list2 [ 2 ] : `` + list2 [ 2 ] .ToString ( ) ) ; // > list2 [ 2 ] : 99",What is the difference between returning an Array and an IList < > ? ( RE : Eric Lippert 's harmful arrays ) "C_sharp : I am trying to parse an HTML response for a couple of values and then insert them into SQL . I am able to get both values but , because the code is wrapped in a foreach statement , I get them twice . Here is my HTML responseHere is my code : name shows the servicename and value shows the class serviceOK but it repeats itself again because of the first foreach.My results look like this : Is there a way to , first , match the values up , and two , only have them show once ? < div align= '' CENTER '' class='dataTitle ' > Host State Breakdowns : < /div > < p align='center ' > < a href='trends.cgi ? host=hostname & includesoftstates=no & assumeinitialstates=yes & initialassumedhoststate=0 & backtrack=4 ' > < img src='trends.cgi ? createimage & host=hostname & includesoftstates=no & initialassumedhoststate=0 & backtrack=4 ' border= '' 1 '' alt='Host State Trends ' title='Host State Trends ' width='500 ' height='20 ' > < /a > < br > < /p > < div align= '' CENTER '' > < table border= '' 0 '' class='data ' > < tr > < th class='data ' > State < /th > < th class='data ' > Type / Reason < /th > < th class='data ' > Time < /th > < th class='data ' > % Total Time < /th > < th class='data ' > % Known Time < /th > < /tr > < tr class='dataEven ' > < td class='hostUP ' rowspan= '' 3 '' > UP < /td > < td class='dataEven ' > Unscheduled < /td > < td class='dataEven ' > 0d 10h 5m 19s < /td > < td class='dataEven ' > 100.000 % < /td > < td class='dataEven ' > 100.000 % < /td > < /tr > < tr class='dataEven ' > < td class='dataEven ' > Scheduled < /td > < td class='dataEven ' > 0d 0h 0m 0s < /td > < td class='dataEven ' > 0.000 % < /td > < td class='dataEven ' > 0.000 % < /td > < /tr > < tr class='hostUNREACHABLE ' > < td class='hostUNREACHABLE ' > Total < /td > < td class='hostUNREACHABLE ' > 0d 0h 0m 0s < /td > < td class='hostUNREACHABLE ' > 0.000 % < /td > < td class='hostUNREACHABLE ' > 0.000 % < /td > < /tr > < tr class='dataOdd ' > < td class='dataOdd ' rowspan= '' 3 '' > Undetermined < /td > < td class='dataOdd ' > Nagios Not Running < /td > < td class='dataOdd ' > 0d 0h 0m 0s < /td > < td class='dataOdd ' > 0.000 % < /td > < td class='dataOdd ' > < /td > < /tr > < tr class='dataOdd ' > < td class='dataOdd ' > Insufficient Data < /td > < td class='dataOdd ' > 0d 0h 0m 0s < /td > < td class='dataOdd ' > 0.000 % < /td > < td class='dataOdd ' > < /td > < /tr > < tr class='dataOdd ' > < td class='dataOdd ' > Total < /td > < td class='dataOdd ' > 0d 0h 0m 0s < /td > < td class='dataOdd ' > 0.000 % < /td > < td class='dataOdd ' > < /td > < /tr > < tr > < td colspan= '' 3 '' > < /td > < /tr > < tr class='dataEven ' > < td class='dataEven ' > All < /td > < td class='dataEven ' > Total < /td > < td class='dataEven ' > 0d 10h 5m 19s < /td > < td class='dataEven ' > 100.000 % < /td > < td class='dataEven ' > 100.000 % < /td > < /tr > < /table > < /div > < br > < br > < div align= '' CENTER '' class='dataTitle ' > State Breakdowns For Host Services : < /div > < div align= '' CENTER '' > < table border= '' 0 '' class='data ' > < tr > < th class='data ' > Service < /th > < th class='data ' > % Time OK < /th > < th class='data ' > % Time Warning < /th > < th class='data ' > % Time Unknown < /th > < th class='data ' > % Time Critical < /th > < th class='data ' > % Time Undetermined < /th > < /tr > < tr class='dataOdd ' > < td class='dataOdd ' > < a href='avail.cgi ? host=hostname & service=servicename & t1=1478498400 & t2=1478534719 & backtrack=4 & assumestateretention=yes & assumeinitialstates=yes & assumestatesduringnotrunning=yes & initialassumedhoststate=0 & initialassumedservicestate=0 & show_log_entries & showscheduleddowntime=yes & rpttimeperiod=24x7 ' > servicename < /a > < /td > < td class='serviceOK ' > 100.000 % ( 100.000 % ) < /td > < td class='serviceWARNING ' > 0.000 % ( 0.000 % ) < /td > < td class='serviceUNKNOWN ' > 0.000 % ( 0.000 % ) < /td > < td class='serviceCRITICAL ' > 0.000 % ( 0.000 % ) < /td > < td class='dataOdd ' > 0.000 % < /td > < /tr > < tr class='dataEven ' > < td class='dataEven ' > < a href='avail.cgi ? host=hostname & service=servicename2 & t1=1478498400 & t2=1478534719 & backtrack=4 & assumestateretention=yes & assumeinitialstates=yes & assumestatesduringnotrunning=yes & initialassumedhoststate=0 & initialassumedservicestate=0 & show_log_entries & showscheduleddowntime=yes & rpttimeperiod=24x7 ' > servicename2 < /a > < /td > < td class='serviceOK ' > 100.000 % ( 100.000 % ) < /td > < td class='serviceWARNING ' > 0.000 % ( 0.000 % ) < /td > < td class='serviceUNKNOWN ' > 0.000 % ( 0.000 % ) < /td > < td class='serviceCRITICAL ' > 0.000 % ( 0.000 % ) < /td > < td class='dataEven ' > 0.000 % < /td > < /tr > < /table > < /div > var response = ( HttpWebResponse ) request.GetResponse ( ) ; var stream = response.GetResponseStream ( ) ; HtmlDocument doc = new HtmlDocument ( ) ; doc.Load ( stream ) ; foreach ( HtmlNode node in doc.DocumentNode.SelectNodes ( `` //table [ @ class ] '' ) ) { foreach ( HtmlNode node2 in node.SelectNodes ( `` //td [ @ class = 'serviceOK ' ] '' ) ) { var value = node2.InnerText ; } foreach ( HtmlNode node3 in node.SelectNodes ( `` //a [ contains ( @ href , 'avail.cgi ' ) ] '' ) ) { var name = node3.InnerText ; } } 100.000 % ( 100.000 % ) 100.000 % ( 100.000 % ) servicenameservicename2100.000 % ( 100.000 % ) 100.000 % ( 100.000 % ) servicenameservicename2",Get HTML values from web response "C_sharp : So here is what I would like to be able to do.ororEssentially , I would like is for CatchLog ( ) to basically wrap the execution of the query in a try catch , and Debug.WriteLine ( ) the Exception and then throw it . Any ideas on how I could implement something like this ? var a = Item.CatchLog ( ) .Where ( x= > x.Property== '' value '' ) .Take ( 10 ) ; var a = Item.CatchLog ( ) .FirstOrDefault ( x= > x.Property== '' value '' ) ; var a = Item.CatchLog ( ) .Any ( x= > x.Property== '' value '' ) ;",Wrap a Linq query in a try/catch block using a method declaration "C_sharp : I came across IAsyncEnumerable while I am testing C # 8.0 features . I found remarkable examples from Anthony Chu ( https : //anthonychu.ca/post/async-streams-dotnet-core-3-iasyncenumerable/ ) . It is async stream and replacement for Task < IEnumerable < T > > I am wondering if this can be applied to read text files like below usage that read file line by line.I really want to know how to apply async with IAsyncEnumerable < string > ( ) to the above foreach loop so that it streams while reading.How do I implement iterator so that I can use yield return to read line by line ? // Data Access Layer.public async IAsyncEnumerable < Product > GetAllProducts ( ) { Container container = cosmosClient.GetContainer ( DatabaseId , ContainerId ) ; var iterator = container.GetItemQueryIterator < Product > ( `` SELECT * FROM c '' ) ; while ( iterator.HasMoreResults ) { foreach ( var product in await iterator.ReadNextAsync ( ) ) { yield return product ; } } } // Usageawait foreach ( var product in productsRepository.GetAllProducts ( ) ) { Console.WriteLine ( product ) ; } foreach ( var line in File.ReadLines ( `` Filename '' ) ) { // ... process line . }",Read text file with IAsyncEnumerable "C_sharp : I want to convert a dynamic object to json string . It worked perfect when I used Newtonsoft.Json at past . when I upgraded .net core to 3.0 and used System.Text.Json instead , it was bad.See the code : If I want to persist using System.Text.Json to convert the dynamic object because I hear that it is faster then other json converts , how could I do ? using System ; using System.Collections.Generic ; using System.Dynamic ; namespace ConsoleApp { class Program { static void Main ( string [ ] args ) { dynamic product = new ExpandoObject ( ) ; product.ProductName = `` Elbow Grease '' ; product.Enabled = true ; product.Price = 4.90m ; product.StockCount = 9000 ; product.StockValue = 44100 ; product.Tags = new string [ ] { `` Real '' , `` OnSale '' } ; // Will output : { `` ProductName '' : '' Elbow Grease '' , '' Enabled '' : true , '' Price '' :4.90 , // `` StockCount '' :9000 , '' StockValue '' :44100 , '' Tags '' : [ `` Real '' , '' OnSale '' ] } var json1 = Newtonsoft.Json.JsonConvert.SerializeObject ( product ) ; Console.WriteLine ( json1 ) ; // Both will throw exception : System.InvalidCastException : “ Unable to // cast object of type ' < GetExpandoEnumerator > d__51 ' to type // 'System.Collections.IDictionaryEnumerator'. ” var json2 = System.Text.Json.JsonSerializer.Serialize ( product ) ; Console.WriteLine ( json2 ) ; var json3 = System.Text.Json.JsonSerializer.Serialize < IDictionary < string , object > > ( product as IDictionary < string , object > ) ; Console.WriteLine ( json3 ) ; Console.ReadKey ( ) ; } } }",Throw exception when converting dynamic object to json with System.Text.Json.Serialization "C_sharp : I need to parse an url like the followingAt the moment i 'm using a switch on subaction to see what actually needs to be done . EG : This works , but i 'd rather have seperate actions for each event , directly accessed from the route . If possible I would like to combine the action and subaction in the routemap to access the right action./controller/action/ would call action ( ) /controller/action/subaction would call action_subaction ( ) /controller/action/subaction/id would call action_subaction ( id ) Is that possible directly from the routemap ? /controller/action/subaction/id public ActionResult Members ( string subaction , long id=0 ) { switch ( subaction ) { case `` Details '' : var member = _payment.GetMember ( id ) ; return View ( `` Members_details '' , member ) ; default : var members = _payment.GetMembers ( ) .ToList ( ) ; return View ( `` Members_list '' , members ) ; } }",.NET MVC Routing - bind 2 routeMap parameters C_sharp : I realize the title needs to be read more than once for understanding ... : ) I implemented a custom attribute that i apply to methods in my classes.all methods i apply the attribute to have the same signature and thus i defined a delegate for them : I have a struct that accepts that delegate as a parameterIs it possible to get from reflection a method that has the custom attribute and pass it to the struct into the 'method ' member ? I know you can invoke it but i think reflection wo n't give me the actual method from my class that i can cast to the TestMethod delegate . public delegate void TestMethod ( ) ; struct TestMetaData { TestMethod method ; string testName ; },How can I pass a method acquired by reflection in C # to a method that accepts the method as a delegate ? "C_sharp : I 'm downloading a blob from blob storage that is 1GB in size.If I use MS Azure storage explorer it takes under 10 minutes ( I have a 20 megabits down line ) .However when I use code : ( I 've also tried to use an in memory stream ) it takes over an hour to download 250MB ( At which point I killed it ) . I 've done this test multiple times and it happens consistently . I also monitored the network traffic . Via Storage Exlorer the network traffic downward is around 20MegabitsVia code the network traffic downward is around 1MegabitEDIT : I 'm still using an old version of Azure Storage Explorer ( 1.4.1 ) . But I can confirm new versions are also giving the same results . await blobRef.DownloadToFileAsync ( `` D : \\temp\\data.mdf '' , FileMode.Create ) ;",Blob Code download much slower than MS Azure Storage Explorer "C_sharp : SituationI am trying to run a command-line tool , DISM.exe , programmatically . When I run it manually it works , but when I try to spawn it with the following : Then my result comes out as : Error : 11You can not service a running 64-bit operating system with a 32-bit version of DISM.Please use the version of DISM that corresponds to your computer 's architecture.ProblemI 'm actually already aware of what causes this : my project is set up to compile for an x86 platform . ( See this question for example , although none of the answers mention this ) . However , unfortunately it is a requirement at the moment that we continue targeting this platform , I am not able to fix this by switching to Any CPU.So my question is how to programmatically spawn a process in a way which is independent of the platform of its parent- i.e . keep my project targeting x86 , but start a process which will target the correct platform for the machine it is on . var systemPath = Environment.GetFolderPath ( Environment.SpecialFolder.System ) ; var dism = new Process ( ) ; dism.StartInfo.FileName = Path.Combine ( systemPath , `` Dism.exe '' ) ; dism.StartInfo.Arguments = `` /Online /Get-Features /Format : Table '' ; dism.StartInfo.Verb = `` runas '' ; dism.StartInfo.UseShellExecute = false ; dism.StartInfo.RedirectStandardOutput = true ; dism.Start ( ) ; var result = dism.StandardOutput.ReadToEnd ( ) ; dism.WaitForExit ( ) ;",Programmatically start a process independent of platform "C_sharp : My coworker and I are debugging an issue in a WCF service he 's working on where a string 's length is n't being evaluated correctly . He is running this method to unit test a method in his WCF service : We tried to step into the .NET source code to see what value string.IsNullOrEmpty was receiving , but the IDE printed this message when we attempted to evaluate the variable : ' Can not obtain value of local or argument 'value ' as it is not available at this instruction pointer , possibly because it has been optimized away . ' ( None of the projects involved have optimizations enabled ) . So , we decided to try explicitly setting the value of the variable inside the method itself , immediately before the length check -- but that did n't help.We 're really pulling our hair out on this one . Has anyone else experienced behavior like this ? Any tips on debugging it ? Here 's the MSIL for the AppActiveDirectoryDomain object , where the behavior is occuring : And the MSIL for the string.IsNullOrEmpty call : Edit : Here is a screenshot of the variable in the 'Watch ' window at the moment the ArgumentNullException is thrown : http : //imgur.com/xQm4J.pngAlso , a second screenshot showing the exception being thrown when checking the length of the string , after explicitly declaring it 5 lines above : http : //imgur.com/lSrk9.pngUpdate # 3 : We tried changing the name of the local variable and it passes the null check and the length check , but fails when we call string.IsNullOrEmpty . See this screenshot : http : //imgur.com/Z57AA.png.Responses : We do n't use any tools that would modify the MSIL . We 've performed a cleanup , and also manually deleted all files from the build directories , and forced a rebuild ... same outcome.The following statement evaluates as true and enters the if block : if ( string.IsNullOrEmpty ( `` AOD '' ) ) { /* */ } .The constructor is called like so : try { using ( AppActiveDirectoryDomain domain = new AppActiveDirectoryDomain ( AppName , DomainName ) ) { } } This is immediately within the WCF service method itself ; AppName and DomainName are parameters to the call . Even bypassing these parameters and using new strings , we still get the errors . // Unit test methodpublic void RemoveAppGroupTest ( ) { string addGroup = `` TestGroup '' ; string status = string.Empty ; string message = string.Empty ; appActiveDirectoryServicesClient.RemoveAppGroup ( `` AOD '' , addGroup , ref status , ref message ) ; } // Inside the WCF service [ OperationBehavior ( Impersonation = ImpersonationOption.Required ) ] public void RemoveAppGroup ( string AppName , string GroupName , ref string Status , ref string Message ) { string accessOnDemandDomain = `` MyDomain '' ; RemoveAppGroupFromDomain ( AppName , accessOnDemandDomain , GroupName , ref Status , ref Message ) ; } public AppActiveDirectoryDomain ( string AppName , string DomainName ) { if ( string.IsNullOrEmpty ( AppName ) ) { throw new ArgumentNullException ( `` AppName '' , `` You must specify an application name '' ) ; } } // Lets try this again.public AppActiveDirectoryDomain ( string AppName , string DomainName ) { // Explicitly set the value for testing purposes . AppName = `` AOD '' ; if ( AppName == null ) { throw new ArgumentNullException ( `` AppName '' , `` You must specify an application name '' ) ; } if ( AppName.Length == 0 ) { // This exception gets thrown , even though it obviously is n't a zero length string . throw new ArgumentNullException ( `` AppName '' , `` You must specify an application name '' ) ; } } .method public hidebysig specialname rtspecialname instance void .ctor ( string AppName , string DomainName ) cil managed { .maxstack 5.locals init ( [ 0 ] class [ System ] System.Net.NetworkCredential ldapCredentials , [ 1 ] string [ ] creds , [ 2 ] string userName , [ 3 ] class [ mscorlib ] System.ArgumentNullException exc , [ 4 ] class [ System.DirectoryServices ] System.DirectoryServices.ActiveDirectory.DirectoryContext directoryContext , [ 5 ] class [ System.DirectoryServices ] System.DirectoryServices.ActiveDirectory.Domain domain , [ 6 ] class [ System.DirectoryServices.Protocols ] System.DirectoryServices.Protocols.LdapException V_6 , [ 7 ] class [ mscorlib ] System.Exception V_7 , [ 8 ] bool CS $ 4 $ 0000 , [ 9 ] char [ ] CS $ 0 $ 0001 , [ 10 ] string [ ] CS $ 0 $ 0002 ) L_0000 : ldarg.0 L_0001 : ldsfld string [ mscorlib ] System.String : :EmptyL_0006 : stfld string MyNamespace.MyClass.AppActiveDirectoryDomain : :appOUL_000b : ldarg.0 L_000c : call instance void [ mscorlib ] System.Object : :.ctor ( ) L_0011 : nop L_0012 : nop L_0013 : ldstr `` AOD '' L_0018 : call bool [ mscorlib ] System.String : :IsNullOrEmpty ( string ) L_001d : ldc.i4.0 L_001e : ceq L_0020 : stloc.s CS $ 4 $ 0000L_0022 : ldloc.s CS $ 4 $ 0000L_0024 : brtrue.s L_0037L_0026 : nop L_0027 : ldstr `` AppName '' L_002c : ldstr `` You must specify an application name '' L_0031 : newobj instance void [ mscorlib ] System.ArgumentNullException : :.ctor ( string , string ) L_0036 : throw .method public hidebysig static bool IsNullOrEmpty ( string 'value ' ) cil managed { .maxstack 8 L_0000 : ldarg.0 L_0001 : brfalse.s L_000d L_0003 : ldarg.0 L_0004 : callvirt instance int32 System.String : :get_Length ( ) L_0009 : ldc.i4.0 L_000a : ceq L_000c : ret L_000d : ldc.i4.1 L_000e : ret }",String Length Evaluating Incorrectly C_sharp : I 'll often have objects with properties that use the following pattern : Is there a name for this method ? private decimal ? _blah ; private decimal Blah { get { if ( _blah == null ) _blah = InitBlah ( ) ; return _blah.Value ; } },What is this C # pattern for property initialization ? "C_sharp : I have created an interface that my DbContext class implements , this enables me to create a fake db context for unit testing . This works well for all my LINQ queries so far but one , where I get the following exception : Executing the LINQ query through the interface throws the above exception , however when executing the exact same query directly on my DBContext the query works 100 % . Here is the interface and related demo code definitions : Each member potentially belongs to a single primary team , and optionally many secondary teams . The following demo code throws the exception : If I change the first line to : then the query executes perfectly.So my questions are : Why does it work through DemoContext and not IDemoContext ? How do I change IDemoContext so this query does work through the interface ? Unable to create a constant value of type 'DemoApp.Member ' . Only primitive types ( 'such as Int32 , String , and Guid ' ) are supported in this context . interface IDemoContext : IDisposable { IDbSet < Member > Members { get ; set ; } IDbSet < Team > Teams { get ; set ; } } public partial class DemoContext : DbContext , IDemoContext { public DemoContext ( ) : base ( `` name=DemoContext '' ) { } public IDbSet < Member > Members { get ; set ; } public IDbSet < Team > Teams { get ; set ; } } public partial class Member { public Member ( ) { this.SecondaryTeams = new HashSet < Team > ( ) ; } public int ID { get ; set ; } public string Name { get ; set ; } public int ? PrimaryTeamID { get ; set ; } public virtual Team PrimaryTeam { get ; set ; } public virtual ICollection < Team > SecondaryTeams { get ; set ; } } public partial class Team { public Team ( ) { this.PrimaryMembers = new HashSet < Member > ( ) ; this.SecondaryMembers = new HashSet < Member > ( ) ; } public int ID { get ; set ; } public string Name { get ; set ; } public virtual ICollection < Member > PrimaryMembers { get ; set ; } public virtual ICollection < Member > SecondaryMembers { get ; set ; } } using ( IDemoContext dbi = new DemoContext ( ) ) { var members = ( from member in dbi.Members select new { Name = member.Name , Team = member.PrimaryTeam.Name , SecondaryTeams = from secondaryTeam in member.SecondaryTeams join primaryMember in dbi.Members on secondaryTeam.ID equals primaryMember.PrimaryTeamID into secondaryTeamMembers select new { Name = secondaryTeam.Name , Count = secondaryTeamMembers.Count ( ) } } ) .ToList ( ) ; } using ( DemoContext dbi = new DemoContext ( ) )",DbContext throws exception on query when accessed through interface "C_sharp : Although BindingList < T > and ObservableCollection < T > provide mechanisms to detect list changes , they do n't support mechanisms to detect/intercept changes before they happen.I 'm writing a couple of interfaces to support this , but I want to canvas your opinion.Option 1 : Lists raise events for each type of actionHere , consumers might write code like this : Option 2 : Lists raise a single event , and the action is determined from the event argsHere , consumers might write code like this : Background : I 'm writing a set of general purpose interfaces/classes that represent the core components of DDD , and I 'm making the source code available ( hence the need to create friendly interfaces ) .This question is about making the interface as cohesive as possible , so that consumers can derive and implement their own collections without losing the core semantics.PS : Please do n't suggest using AddXYZ ( ) and RemoveXYZ ( ) methods for each list , because I 've already discounted that idea.PPS : I must include developers using .NET 2.0 : ) Related question . public class Order : Entity { public Order ( ) { this.OrderItems = new List < OrderItem > ( ) ; this.OrderItems.InsertingItem += new ListChangingEventHandler < OrderItem > ( OrderItems_InsertingItem ) ; this.OrderItems.SettingItem += new ListChangingEventHandler < OrderItem > ( OrderItems_SettingItem ) ; this.OrderItems.RemovingItem += new ListChangingEventHandler < OrderItem > ( OrderItems_RemovingItem ) ; } virtual public List < OrderItem > OrderItems { get ; internal set ; } void OrderItems_InsertingItem ( object sender , IOperationEventArgs < OrderItem > e ) { if ( ! validationPasses ) { e.Cancel = true ; return ; } e.Item.Parent = this ; } void OrderItems_SettingItem ( object sender , IOperationEventArgs < OrderItem > e ) { if ( ! validationPasses ) { e.Cancel = true ; return ; } e.Item.Parent = this ; } void OrderItems_RemovingItem ( object sender , IOperationEventArgs < OrderItem > e ) { if ( ! validationPasses ) { e.Cancel = true ; return ; } e.Item.Parent = null ; } } public class Order : Entity { public Order ( ) { this.OrderItems = new List < OrderItem > ( ) ; this.OrderItems.ListChanging += new ListChangingEventHandler < OrderItem > ( OrderItems_ListChanging ) ; } virtual public List < OrderItem > OrderItems { get ; internal set ; } void OrderItems_ListChanging ( object sender , IOperationEventArgs < OrderItem > e ) { switch ( e.Action ) { case ListChangingType.Inserting : case ListChangingType.Setting : if ( validationPasses ) { e.Item.Parent = this ; } else { e.Cancel = true ; } break ; case ListChangingType.Removing : if ( validationPasses ) { e.Item.Parent = null ; } else { e.Cancel = true ; } break ; } } }",Opinion wanted : Intercepting changes to lists/collections C_sharp : Need to create a summary/indice For this I have tags < Document-Title > My Title < /Document-Title > How I get these tags using HTML agility pack ? I have tried this : But titles is null HtmlDocument html = new HtmlDocument ( ) ; html.Load ( new StringReader ( Document.Content ) ) ; //Is the < html > I 'm load in database var titles = html.DocumentNode.SelectNodes ( `` //Document-Title '' ) ;,How get a custom tag with html agility pack ? "C_sharp : I have a problem with an validation error that only appears on Windows Azure , but not on the local Azure Emulator . In my model I have a class with an attribute `` Start '' and a DisplayFormat for the German date format : On my local machine , everything is fine , but when I try to save the field on a Windows Azure instance I get this validation message : The value '22.08.2011 ' is not valid for Beginn.Both ( local and cloud ) using the same database ( Azure SQL ) . So , I 'm confused . Any idea how to fix this ? [ Required ] [ DisplayFormat ( DataFormatString = `` { 0 : dd.MM.yyyy } '' , ApplyFormatInEditMode = true ) ] [ Display ( Name = `` Beginn '' ) ] public DateTime Start { get ; set ; }","Validation problem with Windows Azure , EF and MVC3" "C_sharp : I reviewed the answers to this question and see that invalid characters can cause issues that throw this error . My question is a tad different in that I 'm using RestSharp to make an API call as follows : The full stack trace of the exception is as follows : When I run this code , I do note that an HTTP 404 is thrown in the content section of the stack trace . I think this means that I have an incorrect baseURl but am not sure and would like to know if this is the case or if my code has other issues ? UPDATE : After researching this issue further , I think the error is being thrown because I 'm not serializing my model objects into JSON before sending the RestRequest.Do I need to serialize all of my objects before making the request ? Update 2 : Thanks to a second set of eyes , I corrected the URL . Now , when I run my application , the following error is thrown : private static T Execute < T > ( IRestRequest request , string baseUrl ) where T : class , new ( ) { var client = new RestClient ( baseUrl ) ; var response = client.Execute < T > ( request ) ; if ( response.ErrorException ! = null ) { Console.WriteLine ( `` Error : Exception : { 0 } , Headers : { 1 } , Content : { 2 } , Status Code : { 3 } '' , response.ErrorException , response.Headers , response.Content , response.StatusCode ) ; } return response.Data ; } public static ProPayResponse MerchantSignUpForProPay ( ) { var baseUrl = `` https : //xmltestapi.propay.com/ProPayAPI '' ; var request = BuildMerchantTestData ( ) ; var restRequest = CreateRestRequest ( `` SignUp '' , Method.PUT ) ; restRequest.AddJsonBody ( request ) ; return Execute < ProPayResponse > ( restRequest , baseUrl ) ; } private static async Task < RestRequest > CreateRestRequest ( string resource , Method method ) { var credentials = GetCredentials ( ) ; var restRequest = new RestRequest { Resource = resource , Method = method , RequestFormat = DataFormat.Json , } ; restRequest.AddHeader ( `` accept '' , `` application/json '' ) ; restRequest.AddHeader ( `` Authorization '' , credentials ) ; return restRequest ; } private static string GetCredentials ( ) { var termId = `` myterm '' ; // put affiliate term id here , if you have it var certString = `` mycertString '' ; // put affiliate cert string here var encodedCredentials = Convert.ToBase64String ( Encoding.Default.GetBytes ( certString + `` : '' + termId ) ) ; var credentials = $ '' Basic { encodedCredentials } '' ; return credentials ; } Error : Exception : System.Xml.XmlException : '= ' is an unexpected token . The expected token is ' ; ' . Line 26 , position 43. at System.Xml.XmlTextReaderImpl.Throw ( Exception e ) at System.Xml.XmlTextReaderImpl.Throw ( String res , String [ ] args ) at System.Xml.XmlTextReaderImpl.ThrowUnexpectedToken ( String expectedToken1 , String expectedToken2 ) at System.Xml.XmlTextReaderImpl.HandleEntityReference ( Boolean isInAttributeValue , EntityExpandType expandType , Int32 & charRefEndPos ) at System.Xml.XmlTextReaderImpl.ParseText ( Int32 & startPos , Int32 & endPos , Int32 & outOrChars ) at System.Xml.XmlTextReaderImpl.FinishPartialValue ( ) at System.Xml.XmlTextReaderImpl.get_Value ( ) at System.Xml.Linq.XContainer.ContentReader.ReadContentFrom ( XContainer rootContainer , XmlReader r ) at System.Xml.Linq.XContainer.ReadContentFrom ( XmlReader r ) at System.Xml.Linq.XContainer.ReadContentFrom ( XmlReader r , LoadOptions o ) at System.Xml.Linq.XDocument.Load ( XmlReader reader , LoadOptions options ) at System.Xml.Linq.XDocument.Parse ( String text , LoadOptions options ) at RestSharp.Deserializers.XmlDeserializer.Deserialize [ T ] ( IRestResponse response ) at RestSharp.RestClient.Deserialize [ T ] ( IRestRequest request , IRestResponse raw ) , Headers : System.Collections.Generic.List ` 1 [ RestSharp.Parameter ] , Content : Error : Exception : System.Xml.XmlException : Data at the root level is invalid . Line 1 , position 1.at System.Xml.XmlTextReaderImpl.Throw ( Exception e ) at System.Xml.XmlTextReaderImpl.Throw ( String res , String arg ) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace ( ) at System.Xml.XmlTextReaderImpl.ParseDocumentContent ( ) at System.Xml.XmlTextReaderImpl.Read ( ) at System.Xml.Linq.XDocument.Load ( XmlReader reader , LoadOptions options ) at System.Xml.Linq.XDocument.Parse ( String text , LoadOptions options ) at RestSharp.Deserializers.XmlDeserializer.Deserialize [ T ] ( IRestResponse response ) at RestSharp.RestClient.Deserialize [ T ] ( IRestRequest request , IRestResponse raw ) , Message : Data at the root level is invalid . Line 1 , position 1. , Headers : System.Collections.Generic.List ` 1 [ RestSharp.Parameter ] , Content : ? < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? >",RestSharp Methods Throw System.Xml.XMlException `` = '' is an unexpected token . The expected token is ' ; ' "C_sharp : I have class foo which is extending DynamicObject class.This class also contains a property of Dictionary type.When I am trying to serialize it using Newton.Soft Json converter . I am getting `` { } '' as blank object.Following is my code : Now I mentioned , while serializing it I am getting blank object.Follwing is the code for serialization : Please let me know if I am missing somthing ? public class Foo : DynamicObject { /// < summary > /// Gets or sets the properties . /// < /summary > /// < value > The properties. < /value > public Dictionary < string , object > Properties { get ; set ; } = new Dictionary < string , object > ( ) ; /// < summary > /// Gets the count . /// < /summary > /// < value > The count. < /value > public int Count = > Properties.Keys.Count ; } public static void Main ( ) { Foo foo= new Foo ( ) ; foo.Properties = new Dictionary < string , object > ( ) { { `` SomeId '' , 123 } , { `` DataType '' , '' UnKnonw '' } , { `` SomeOtherId '' , 456 } , { `` EmpName '' , `` Pranay Deep '' } , { `` EmpId '' , `` 789 '' } , { `` RandomProperty '' , `` 576Wow_Omg '' } } ; //Now serializing.. string jsonFoo = JsonConvert.SerializeObject ( foo ) ; //Here jsonFoo = `` { } '' .. why ? Foo foo2= JsonConvert.DeserializeObject < Foo > ( jsonFoo ) ; }",Ca n't Serialize a class extending DynamicObject into JSON string . "C_sharp : I have a handler for the CollectionChanged event of an ObservableCollection < T > object , and can not figure out how to use the NotifyCollectionChangedEventArgs to retrieve the item contained within the IList for the event.New items added to the collection are in the NewItems property , an IList object . Intellisense wo n't let me access .Item [ Index ] ( which I should be able to according to the docs ) nor can I cast the NewItems list to a local variable ( according to debug the NewItems list is a System.Collections.ArrayList.ReadOnlyList which does n't seem to exist as an accessible class in MSDN . ) What am I doing wrong ? Example : This example is keeping things as generic as possible and still fails . private void ThisCollectionChanged ( object sender , NotifyCollectionChangedEventArgs e ) { Item I = e.NewItems._________ ; // < < < < < can not access any property to get the item var j = e.NewItems ; //System.Collections.ArrayList.ReadOnlyList , see if you can find in the MSDN docs . IList I1 = ( IList ) e.NewItems ; //Cast fails . IList < Item > = ( IList < Item > ) e.NewItems.________ ; // < < < < < < < Ca n't make this cast without an IList.Item [ Index ] accessor . var i = j [ 0 ] ; //null var ioption = j.Item [ 0 ] ; //no such accessor string s = ( string ) i ; //null }",NotifyCollectionChangedEventArgs Item Inaccessible "C_sharp : Is there ever a reason to use Type parameters over generics , ie : It seems to me that generics are far more useful in that they provide generic constraints and with C # 4.0 , contravarience and covarience , as well as probably some other features I do n't know about . It would seem to me that the generic form has all the pluses , and no negatives that the first does n't also share . So , are there any cases where you 'd use the first instead ? // this ... void Foo ( Type T ) ; // ... over this.void Foo < T > ( ) ;",Type parameters vs. generics "C_sharp : I am writing a code-generator that will need to output some miniscule portions of VB.NET code , and since this is a code generator that will add user-provider code , I 'd like to try to avoid type name conflicts with types or names in the user-provided code.In C # , I can prefix types with global : : to make sure they 're matched from the global type namespace hierarchy , rather than some local name , but is there a similar system for VB.NET ? ie . this : global : :System.String",Is there something like `` global : : '' for VB.NET ? "C_sharp : i have a dll , built with mingw one of the header files contains this : I use this dll in another c++ app , built using Visual C++ ( 2008SP1 ) , not managed , but plain c++ ( simply include the header , and call the function ) But now I have to use it in a C # applicationThe problem is that i ca n't figure out how exactly ( i 'm new in .net programming ) this is what i 've triedWhen i call the function , nothing happens ( the mydll.dll file is located in the bin folder of the c # app , and it gives me no errors or warnings whatsoever ) extern `` C '' { int get_mac_address ( char * mac ) ; //the function returns a mac address in the char * mac } public class Hwdinfo { [ DllImport ( `` mydll.dll '' ) ] public static extern void get_mac_address ( string s ) ; }",using C function in C # "C_sharp : I have a C # 4.0 parser . It accepts 'dynamic ' as a keyword as a type . My parser trips overstatements found in working C # 3.0 programs of the form of : So , it dynamic really a keyword ? Or can it still be used as an arbitrary identifier name ? ( If so , why is n't 'int ' treated the same way ) ? Is there a reference spec somewhere that states whether dynamic is keyword ? The latest ECMA C # 4 specification does n't even mention 'dynamic ' , and the best I can find at the MS site is a `` preliminary specification '' which says its a keyword but I suspect that 's just sloppy writing . dynamic = < exp > ;",C # 'dynamic ' keyword ... is it really a RESERVED keyword or just a identifier that means something special when used as type ? "C_sharp : I use interfaces for decoupling my code . I am curious , is the usage of explicit interface implementation meant for hiding functionality ? Example : What is the benefit and specific use case of making this available only explicitly via the interface ? public class MyClass : IInterface { void IInterface.NoneWillCall ( int ragh ) { } }",Is the use of explicit interface implementation meant for hiding functionality ? "C_sharp : I played a bit around with the Kinect v2 and C # and tried to get a 512x424 pixel-sized image array that contains depth data aswell as the regarding color information ( RGBA ) . Therefore I used the MultiSourceFrameReader class to receive a MultiSourceFrame from which I got the ColorFrame and DepthFrame . With the methods ColorFrame.CopyConvertedFrameDataToArray ( ) and DepthFrame.CopyFrameDataToArray ( ) I received the arrays that hold color and depth information : Now I would have to map the color-quadruples that live within the ColorFrame-data-array cFrameData to each of the entries of the DepthFrame-data-array dFrameData but that 's where I 'm stuck . Output should be an array that is 4 times ( RGBA/BGRA ) the size of the dFrameData array and contains the color information to each pixel of the depth-frame : Does anyone have any suggestions ? I also took a look at the Kinect-SDK 's CoordinateMappingBasics example but they did it vice versa for the 1920x1080 pixel-sized image which I already got to work.EditI recognized that I should be able to get the mapped color information by using the ColorSpacePoint-struct which contains the X and Y coordinates to the specific color pixel . Therefore I set up the points like ... . and tried to access the color information like .. .. but I 'm still getting the wrong colors . Mostly white ones . // Contains 4*1920*1080 entries of color-info : BGRA|BGRA|BGRA..byte [ ] cFrameData = new byte [ 4 * cWidth * cHeight ] ; cFrame.CopyConvertedFrameDataToArray ( cFrameData , ColorImageFormat.Bgra ) ; // Has 512*424 entries with depth informationushort [ ] dFrameData = new ushort [ dWidth* dHeight ] ; dFrame.CopyFrameDataToArray ( dFrameData ) ; // Create the array that contains the color information for every depth-pixelbyte [ ] dColors = new byte [ 4 * dFrameData.Length ] ; for ( int i = 0 , j = 0 ; i < cFrameData.Length ; ++i ) { // The mapped color index . -- - > I 'm stuck here : int colIx = ? ; dColors [ j ] = cFrameData [ colIx ] ; // B dColors [ j + 1 ] = cFrameData [ colIx + 1 ] ; // G dColors [ j + 2 ] = cFrameData [ colIx + 2 ] ; // R dColors [ j + 3 ] = cFrameData [ colIx + 3 ] ; // A j += 4 ; } // Lookup table for color-point informationColorSpacePoint [ ] cSpacePoints = new ColorSpacePoint [ dWidth * dHeight ] ; this.kinectSensor.CoordinateMapper.MapDepthFrameToColorSpace ( dFrameData , cSpacePoints ) ; int x = ( int ) ( cSpacePoints [ i ] .X + 0.5f ) ; int y = ( int ) ( cSpacePoints [ i ] .Y + 0.5f ) ; int ix = x * cWidth + y ; byte r = cFrameData [ ix + 2 ] ; byte g = cFrameData [ ix + 1 ] ; byte b = cFrameData [ ix ] ; byte a = cFrameData [ ix + 3 ] ;",C # and Kinect v2 : Get RGB values that fit to depth-pixel "C_sharp : It seems to me there is really no guarantee that a non-nullable variable wo n't ever have null . Imagine I have a class that has one property that is not nullable : Now that might seem like it 's now can not be null . But if we reference this class with another library that does not use nullable context , nothing stops it from sending null in there.Is that correct or there are some runtime checks as well perhaps that ensure this ? public class Foo { public Foo ( string test ) { Test = test ; } public string Test { get ; set ; } }",Can a non-nullable reference type in C # 8 be null in runtime ? "C_sharp : Im currently developing an Air hockey game in Unity3d . The issue I 'm having is that when the player attempts to hit the puck too quickly , the player ends up going through the puck and therefore there is no collision . The game works perfectly as expected if the player stays still and the puck hits the player or if the player hits the puck at a slow pace.The player has a rigidbody using continuous collision detection using a capsule collider . The puck also has rigidbody with continuous dynamic collision detection and a mesh collider with convex.I tried setting the fixed timestep to 0.01 but that did n't have an effect . Here is the script for the player movement : and here is the code for the puck when it collides with the player : Any help would be much appreciated . Thanks . void ObjectFollowCursor ( ) { Ray ray = Camera.main.ScreenPointToRay ( Input.mousePosition ) ; Vector3 point = ray.origin + ( ray.direction * distance ) ; Vector3 temp = point ; temp.y = 0.2f ; // limits player on y axis cursorObject.position = temp ; } // If puck hits playerif ( collision.gameObject.tag == `` Player '' ) { Vector3 forceVec = this.GetComponent < Rigidbody > ( ) .velocity.normalized * hitForce ; rb.AddForce ( forceVec , ForceMode.Impulse ) ; Debug.Log ( `` Player Hit '' ) ; }",Air hockey game - Player bat goes through puck if moved too fast "C_sharp : Background : Let 's assume I 've got the following class : As you can see , it provides an implicit type conversion operator for T → Wrapped < T > . Ultimately , I would like to be able to use this class as follows : Problem : However , the type conversion in the above using clause fails . While I can assign a new X ( ) directly to wrappedIX , I am not allowed to assign anything of type IX to it . The compiler will complain with the following error : Compiler error CS0266 : Can not implicitly convert type 'IX ' to 'Wrapped < IX > ' . An explicit onversion exists ( are you missing a cast ? ) I do n't understand this . What 's the problem here ? class Wrapped < T > : IDisposable { public Wrapped ( T obj ) { /* ... */ } public static implicit operator Wrapped < T > ( T obj ) { return new Wrapped < T > ( obj ) ; } public void Dispose ( ) { /* ... */ } } interface IX { /* ... */ } class X : IX { /* ... */ } ... IX plainIX = new X ( ) ; using ( Wrapped < IX > wrappedIX = plainIX ) { /* ... */ }",Why does this implicit type conversion in C # fail ? "C_sharp : I thought I could make use of the new c # 6 operator nameof to build a dictionary of key/values implicitly from a params array.As an example , consider the following method call : I am not sure there will be an implementation of Test that will be able to imply the name of the elements , from the params array . Is there a way to do this using just nameof , without reflection ? string myName = `` John '' , myAge = `` 33 '' , myAddress = `` Melbourne '' ; Test ( myName , myAge , myAddress ) ; private static void Test ( params string [ ] values ) { List < string > keyValueList = new List < string > ( ) ; //for ( int i = 0 ; i < values.Length ; i++ ) foreach ( var p in values ) { // '' Key '' is always `` p '' , obviously Console.WriteLine ( $ '' Key : { nameof ( p ) } , Value : { p } '' ) ; } }",Is it possible to imply the name of the parameters of a params array using the nameof operator ? "C_sharp : How can I do it ? List < int > _lstNeedToOrder = new List < int > ( ) ; _lstNeedToOrder.AddRange ( new int [ ] { 1 , 5 , 6 , 8 } ) ; //I need to sort this based on the below list.List < int > _lstOrdered = new List < int > ( ) ; //to order by this list_lstOrdered.AddRange ( new int [ ] { 13 , 5 , 11 , 1 , 4 , 9 , 2 , 7 , 12 , 10 , 3 , 8 , 6 } ) ; order will be -- > _lstNeedToOrder = 5,1,8,6",LINQ method to sort a list based on a bigger list "C_sharp : In the code below : I am able to assign my `` listOfCI1 '' to an IEnumerable < I1 > ( due to covariance ) But why am I not able to assign it to an IList < I1 > ? For that matter , I can not even do the following : Should n't covariance allow me to assign a derived type to a base type ? interface I1 { } class CI1 : I1 { } List < CI1 > listOfCI1 = new List < CI1 > ( ) ; IEnumerable < I1 > enumerableOfI1 = listOfCI1 ; //this worksIList < I1 > listofI1 = listOfCI1 ; //this does not List < I1 > listOfI12 = listOfCI1 ;",Question about C # covariance "C_sharp : I need an easy way to iterate over multiple collections without actually merging them , and I could n't find anything built into .NET that looks like it does that . It feels like this should be a somewhat common situation . I do n't want to reinvent the wheel . Is there anything built in that does something like this : public class MultiCollectionEnumerable < T > : IEnumerable < T > { private MultiCollectionEnumerator < T > enumerator ; public MultiCollectionEnumerable ( params IEnumerable < T > [ ] collections ) { enumerator = new MultiCollectionEnumerator < T > ( collections ) ; } public IEnumerator < T > GetEnumerator ( ) { enumerator.Reset ( ) ; return enumerator ; } IEnumerator IEnumerable.GetEnumerator ( ) { enumerator.Reset ( ) ; return enumerator ; } private class MultiCollectionEnumerator < T > : IEnumerator < T > { private IEnumerable < T > [ ] collections ; private int currentIndex ; private IEnumerator < T > currentEnumerator ; public MultiCollectionEnumerator ( IEnumerable < T > [ ] collections ) { this.collections = collections ; this.currentIndex = -1 ; } public T Current { get { if ( currentEnumerator ! = null ) return currentEnumerator.Current ; else return default ( T ) ; } } public void Dispose ( ) { if ( currentEnumerator ! = null ) currentEnumerator.Dispose ( ) ; } object IEnumerator.Current { get { return Current ; } } public bool MoveNext ( ) { if ( currentIndex > = collections.Length ) return false ; if ( currentIndex < 0 ) { currentIndex = 0 ; if ( collections.Length > 0 ) currentEnumerator = collections [ 0 ] .GetEnumerator ( ) ; else return false ; } while ( ! currentEnumerator.MoveNext ( ) ) { currentEnumerator.Dispose ( ) ; currentEnumerator = null ; currentIndex++ ; if ( currentIndex > = collections.Length ) return false ; currentEnumerator = collections [ currentIndex ] .GetEnumerator ( ) ; } return true ; } public void Reset ( ) { if ( currentEnumerator ! = null ) { currentEnumerator.Dispose ( ) ; currentEnumerator = null ; } this.currentIndex = -1 ; } } }",Does .NET have a built in IEnumerable for multiple collections ? "C_sharp : Is there a shorthand way to denullify a string in C # ? It would be the equivalent of ( if ' x ' is a string ) : I guess I 'm hoping there 's some operator that would work something like : Wishful thinking , huh ? The closest I 've got so far is an extension method on the string class : which allows me to do : Any improvements on that , anyone ? string y = x == null ? `` '' : x ; string y = # x ; public static string ToNotNull ( this string value ) { return value == null ? `` '' : value ; } string y = x.ToNotNull ( ) ;",Is there a shorthand way to denullify a string in C # ? "C_sharp : I apologize for asking something that is probably too basic for C # folks . I 'm mostly doing my coding in C++.So if I want to write an assignment constructor for my class , how do I do that ? I have this so far , but it does n't seem to compile : public class MyClass { public string s1 ; public string s2 ; public int v1 ; public MyClass ( ) { s1 = `` '' ; s2 = `` '' ; v1 = 0 ; } public MyClass ( MyClass s ) { this = s ; //Error on this line } } MyClass a = new MyClass ( ) ; MyClass b = new MyClass ( a ) ;",C # copy constructor "C_sharp : The context is an aspnetcore 2.1 website hosted in a Docker container on port HTTP , along with the use of an Nginx reverse proxy exposing HTTPS 443 only.The website is accessed from the outside on HTTPS , it redirects to an STS website on HTTPS , which redirects to the /signin-wsfed on HTTPS.However , the response location from the /signin-wsfed is HTTP.Here is the request : and the response : HTTP being inacessible from the outside , this provokes an error.How does the Microsoft.AspNetCore.Authentication.WsFederation determine the response location , considering that every parameter in earlier requests ( wtrealm , wreply , ... ) are HTTPS ? POST https : //core-mydocker. # # # # /signin-wsfed HTTP/1.1Accept : image/gif , image/jpeg , image/pjpeg , application/x-ms-application , application/xaml+xml , application/x-ms-xbap , */*Referer : https : //sts-mydocker. # # # # /Pages/Email/Default.aspx ? wtrealm=https % 3a % 2f % 2fcore-mydocker. # # # # % 2f & wa=wsignin1.0 & wreply=https % 3a % 2f % 2fcore-mydocker. # # # # % 2fsignin-wsfed & wctx= # # # # # Accept-Language : fr-FR , fr ; q=0.8 , en-GB ; q=0.6 , en ; q=0.4 , ja ; q=0.2User-Agent : Mozilla/5.0 ( compatible ; MSIE 9.0 ; Windows NT 6.2 ; WOW64 ; Trident/7.0 ) Content-Type : application/x-www-form-urlencodedAccept-Encoding : gzip , deflateHost : core-mydocker. # # # # Content-Length : 10612Connection : Keep-AliveCache-Control : no-cache HTTP/1.1 302 FoundServer : nginx/1.12.2Date : Thu , 21 Feb 2019 09:39:34 GMTContent-Length : 0Connection : keep-aliveCache-Control : no-cachePragma : no-cacheExpires : Thu , 01 Jan 1970 00:00:00 GMTLocation : http : //core-mydocker. # # # # /AuthenticateSet-Cookie : .AspNetCore.Correlation.WsFederation. # # # # # # = ; expires=Thu , 01 Jan 1970 00:00:00 GMT ; path=/ ; HTTPOnly ; Securesignin-wsfed ; httponlySet-Cookie : FedAuth= # # # # # # # =/ ; HTTPOnly ; Secure ; httponlyAccess-Control-Allow-Credentials : trueAccess-Control-Allow-Origin : https : //mydocker. # # # #",AspNetCore.WsFederation get signin-wsfed redirect to HTTP when original request is HTTPS "C_sharp : I want to pin a generically-typed array and get a pointer to its memory : But trying to compile the above code produces this compiler error : The answers to these questions confirm that there 's no way to declare a generic T* pointer . But is there a way to pin a generic T [ ] array and get an IntPtr to the pinned memory ? ( Such a pointer still has use because it could be passed to native code or cast to a pointer of known type . ) T [ ] arr = ... ; fixed ( T* ptr = arr ) { // Use ptr here . } Can not take the address of , get the size of , or declare a pointer to a managed type",How can I pin ( and get an IntPtr to ) a generic T [ ] array ? "C_sharp : I wonder how I can store orderby expressions in a list . This is what I wanted to write : Then : which works for p.Name , but does not work for p.Id ( list [ 1 ] ) as it drops follwing exception An unhandled exception of type 'System.NotSupportedException ' occurred in EntityFramework.SqlServer.dll Additional information : Unable to cast the type 'System.Int32 ' to type 'System.Object ' . LINQ to Entities only supports casting EDM primitive or enumeration types.What type of list do I have to use ? List < Expression < Func < Products , Object > > > list = new List < Expression < Func < Products , Object > > > ( ) { p = > p.Name , p = > p.Id } ; var expr = list [ 0 ] ; myProducts.OrderBy ( expr ) ;",Linq : Queryable.OrderBy ( ) using a collection of Expressions "C_sharp : Consider following program : On deletion of repository folder I get an UnauthorizedAccessException - access to one of internal git files is denied . Is there anything else I should dispose of in order to delete the folder ? var path = Path.Combine ( Path.GetTempPath ( ) , Path.GetFileNameWithoutExtension ( Path.GetRandomFileName ( ) ) ) ; Directory.CreateDirectory ( path ) ; var testFile = Path.Combine ( path , `` test.txt '' ) ; File.WriteAllText ( testFile , `` Test file '' ) ; var source = Repository.Init ( path ) ; using ( var repository = new Repository ( source ) ) { repository.Index.Add ( `` test.txt '' ) ; } Directory.Delete ( path , true ) ;",Deletion of git repository "C_sharp : I wrote a very simple WCF project in Visual Studio : IBookStore : BookStoreImpl : My WebConfig file is : I have also created the database , attached it to the project with the .mdf file , compiled and run the project and I can see the timer running in the right corner of the screen after I run the project . Then I open my browser , type into the address box : http : //localhost:8080/bookservice/GetBooksList and press enter and I get an error page instead . Does n't look like my requests ever get to the server in the first place . Can anyone please help me understand why ? Here 's the error : EDIT : I noticed that if I set a breakpoint somewhere and run , I see the following error in the `` WCF Test Client '' window that pops up : '' Error : Can not obtain Metadata from http : //localhost:59250/BookStoreImpl.svc If this is a Windows ( R ) Communication Foundation service to which you have access , please check that you have enabled metadata publishing at the specified address . For help enabling metadata publishing , please refer to the MSDN documentation at http : //go.microsoft.com/fwlink/ ? LinkId=65455.WS-Metadata Exchange Error URI : http : //localhost:59250/BookStoreImpl.svc Metadata contains a reference that can not be resolved : 'http : //localhost:59250/BookStoreImpl.svc ' . The requested service , 'http : //localhost:59250/BookStoreImpl.svc ' could not be activated . See the server 's diagnostic trace logs for more information.HTTP GET Error URI : http : //localhost:59250/BookStoreImpl.svc There was an error downloading 'http : //localhost:59250/BookStoreImpl.svc ' . The request failed with the error message : -- No protocol binding matches the given address 'http : //localhost:8080/bookservice/ ' . Protocol bindings are configured at the Site level in IIS or WAS configuration . body { font-family : '' Verdana '' ; font-weight : normal ; font-size : .7em ; color : black ; } p { font-family : '' Verdana '' ; font-weight : normal ; color : black ; margin-top : -5px } b { font-family : '' Verdana '' ; font-weight : bold ; color : black ; margin-top : -5px } H1 { font-family : '' Verdana '' ; font-weight : normal ; font-size:18pt ; color : red } H2 { font-family : '' Verdana '' ; font-weight : normal ; font-size:14pt ; color : maroon } pre { font-family : '' Consolas '' , '' Lucida Console '' , Monospace ; font-size:11pt ; margin:0 ; padding:0.5em ; line-height:14pt } .marker { font-weight : bold ; color : black ; text-decoration : none ; } .version { color : gray ; } .error { margin-bottom : 10px ; } .expandable { text-decoration : underline ; font-weight : bold ; color : navy ; cursor : hand ; } @ media screen and ( max-width : 639px ) { pre { width : 440px ; overflow : auto ; white-space : pre-wrap ; word-wrap : break-word ; } } @ media screen and ( max-width : 479px ) { pre { width : 280px ; } } Server Error in '/ ' Application . No protocol binding matches the given address 'http : //localhost:8080/bookservice/ ' . Protocol bindings are configured at the Site level in IIS or WAS configuration . Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : System.InvalidOperationException : No protocol binding matches the given address 'http : //localhost:8080/bookservice/ ' . Protocol bindings are configured at the Site level in IIS or WAS configuration . Source Error : An unhandled exception was generated during the execution of the current web request . Information regarding the origin and location of the exception can be identified using the exception stack trace below . Stack Trace : [ InvalidOperationException : No protocol binding matches the given address 'http : //localhost:8080/bookservice/ ' . Protocol bindings are configured at the Site level in IIS or WAS configuration . ] System.ServiceModel.Activation.HostedAspNetEnvironment.GetBaseUri ( String transportScheme , Uri listenUri ) +109963 System.ServiceModel.Channels.TransportChannelListener.OnOpening ( ) +13058405 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +265 System.ServiceModel.Channels.DatagramChannelDemuxer2.OnOuterListenerOpen ( ChannelDemuxerFilter filter , IChannelListener listener , TimeSpan timeout ) +445 System.ServiceModel.Channels.SingletonChannelListener3.OnOpen ( TimeSpan timeout ) +78 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) +61 [ InvalidOperationException : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' SecurityNegotiationContract '' ' is unable to open its IChannelListener . ] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) +134 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.ServiceHostBase.OnOpen ( TimeSpan timeout ) +136 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Security.NegotiationTokenAuthenticator1.OnOpen ( TimeSpan timeout ) +137 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) +21 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open ( TimeSpan timeout ) +23 System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen ( TimeSpan timeout ) +513 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) +21 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open ( TimeSpan timeout ) +86 System.ServiceModel.Channels.SecurityChannelListener1.OnOpen ( TimeSpan timeout ) +240 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) +61 [ InvalidOperationException : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' IssueAndRenewSession '' ' is unable to open its IChannelListener . ] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) +134 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.ServiceHostBase.OnOpen ( TimeSpan timeout ) +136 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen ( TimeSpan timeout ) +129 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) +21 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open ( TimeSpan timeout ) +23 System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen ( TimeSpan timeout ) +759 System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) +21 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open ( TimeSpan timeout ) +130 System.ServiceModel.Channels.SecurityChannelListener1.OnOpen ( TimeSpan timeout ) +240 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) +61 [ InvalidOperationException : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' IBookStore '' ' is unable to open its IChannelListener . ] System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) +134 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.ServiceHostBase.OnOpen ( TimeSpan timeout ) +136 System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) +308 System.ServiceModel.HostingManager.ActivateService ( ServiceActivationInfo serviceActivationInfo , EventTraceActivity eventTraceActivity ) +110 System.ServiceModel.HostingManager.EnsureServiceAvailable ( String normalizedVirtualPath , EventTraceActivity eventTraceActivity ) +641 [ ServiceActivationException : The service '/BookStoreImpl.svc ' can not be activated due to an exception during compilation . The exception message is : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' IBookStore '' ' is unable to open its IChannelListener.. ] System.Runtime.AsyncResult.End ( IAsyncResult result ) +481507 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End ( IAsyncResult result ) +174 System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest ( IAsyncResult ar ) +351314 System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion ( IAsyncResult ar ) +9791593 < /pre > < /code > < /td > < /tr > < /table > < br > < hr width=100 % size=1 color=silver > < b > Version Information : < /b > ÿMicrosoft .NET Framework Version:4.0.30319 ; ASP.NET Version:4.6.1586.0 < /font > < /body > < /html > < ! -- [ InvalidOperationException ] : No protocol binding matches the given address 'http : //localhost:8080/bookservice/ ' . Protocol bindings are configured at the Site level in IIS or WAS configuration . at System.ServiceModel.Activation.HostedAspNetEnvironment.GetBaseUri ( String transportScheme , Uri listenUri ) at System.ServiceModel.Channels.TransportChannelListener.OnOpening ( ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Channels.DatagramChannelDemuxer2.OnOuterListenerOpen ( ChannelDemuxerFilter filter , IChannelListener listener , TimeSpan timeout ) at System.ServiceModel.Channels.SingletonChannelListener3.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) [ InvalidOperationException ] : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' SecurityNegotiationContract '' ' is unable to open its IChannelListener . at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.ServiceHostBase.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Security.NegotiationTokenAuthenticator1.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open ( TimeSpan timeout ) at System.ServiceModel.Security.SymmetricSecurityProtocolFactory.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open ( TimeSpan timeout ) at System.ServiceModel.Channels.SecurityChannelListener1.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) [ InvalidOperationException ] : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' IssueAndRenewSession '' ' is unable to open its IChannelListener . at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.ServiceHostBase.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Security.SecuritySessionSecurityTokenAuthenticator.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Security.CommunicationObjectSecurityTokenAuthenticator.Open ( TimeSpan timeout ) at System.ServiceModel.Security.SecuritySessionServerSettings.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Security.SecurityListenerSettingsLifetimeManager.Open ( TimeSpan timeout ) at System.ServiceModel.Channels.SecurityChannelListener1.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) [ InvalidOperationException ] : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' IBookStore '' ' is unable to open its IChannelListener . at System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.ServiceHostBase.OnOpen ( TimeSpan timeout ) at System.ServiceModel.Channels.CommunicationObject.Open ( TimeSpan timeout ) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService ( ServiceActivationInfo serviceActivationInfo , EventTraceActivity eventTraceActivity ) at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable ( String normalizedVirtualPath , EventTraceActivity eventTraceActivity ) [ ServiceActivationException ] : The service '/BookStoreImpl.svc ' can not be activated due to an exception during compilation . The exception message is : The ChannelDispatcher at 'http : //localhost:8080/bookservice/ ' with contract ( s ) ' '' IBookStore '' ' is unable to open its IChannelListener.. at System.Runtime.AsyncResult.End [ TAsyncResult ] ( IAsyncResult result ) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End ( IAsyncResult result ) at System.ServiceModel.Activation.ServiceHttpModule.EndProcessRequest ( IAsyncResult ar ) at System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion ( IAsyncResult ar ) -- > -- . '' using System.Collections.Generic ; using System.Runtime.Serialization ; using System.ServiceModel ; using System.ServiceModel.Web ; namespace BookStore { [ ServiceContract ] public interface IBookStore { [ OperationContract ] [ WebGet ] List < Book > GetBooksList ( ) ; [ OperationContract ] [ WebGet ( UriTemplate = `` GetBook/ { id } '' ) ] // The value of UriTemplate defines the name that the // client should use to turn to the function Book GetBookById ( int id ) ; [ OperationContract ] [ WebInvoke ( UriTemplate = `` AddBook/ { name } '' , Method = `` PUT '' ) ] void AddBook ( string name ) ; [ OperationContract ] [ WebInvoke ( UriTemplate = `` UpdateBook/ { id } / { name } '' , Method = `` POST '' ) ] void UpdateBook ( int id , string name ) ; [ OperationContract ] [ WebInvoke ( UriTemplate = `` DeleteBook/ { id } '' , Method = `` DELETE '' ) ] void DeleteBook ( int id ) ; } [ DataContract ] public class Book { int id ; string name ; [ DataMember ] public int ID { get { return id ; } set { id = value ; } } [ DataMember ] public string Name { get { return name ; } set { name = value ; } } } } using System.Collections.Generic ; using System.ServiceModel ; using System.ServiceModel.Activation ; namespace BookStore { [ AspNetCompatibilityRequirements ( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed ) ] [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.Single ) ] public class BookStoreImpl : IBookStore { public void AddBook ( string name ) { using ( var db = new BookStoreContext ( ) ) { Book book = new BookStore.Book { Name = name } ; db.Books.Add ( book ) ; db.SaveChanges ( ) ; } } public void DeleteBook ( int id ) { try { using ( var db = new BookStoreContext ( ) ) { Book book = db.Books.Find ( id ) ; db.Books.Remove ( book ) ; db.SaveChanges ( ) ; } } catch { throw new FaultException ( `` Something went wrong '' ) ; } } public Book GetBookById ( int id ) { using ( var db = new BookStoreContext ( ) ) { return db.Books.Find ( id ) ; } } public List < Book > GetBooksList ( ) { List < Book > allBooks = new List < Book > ( ) ; try { using ( var db = new BookStoreContext ( ) ) { IEnumerator < Book > booksEnum = db.Books.GetEnumerator ( ) ; booksEnum.Reset ( ) ; while ( booksEnum.MoveNext ( ) ) { allBooks.Add ( booksEnum.Current ) ; } } } catch { throw new FaultException ( `` Something went wrong '' ) ; } return allBooks ; } public void UpdateBook ( int id , string name ) { try { using ( var db = new BookStoreContext ( ) ) { Book book = db.Books.Find ( id ) ; book.Name = name ; db.SaveChanges ( ) ; } } catch { throw new FaultException ( `` Something went wrong '' ) ; } } } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < ! -- For more information on Entity Framework configuration , visit http : //go.microsoft.com/fwlink/ ? LinkID=237468 -- > < section name= '' entityFramework '' type= '' System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection , EntityFramework , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' requirePermission= '' false '' / > < /configSections > < appSettings > < add key= '' aspnet : UseTaskFriendlySynchronizationContext '' value= '' true '' / > < /appSettings > < system.web > < compilation debug= '' true '' targetFramework= '' 4.5.2 '' / > < httpRuntime targetFramework= '' 4.5.2 '' / > < httpModules > < add name= '' ApplicationInsightsWebTracking '' type= '' Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule , Microsoft.AI.Web '' / > < /httpModules > < /system.web > < system.serviceModel > < behaviors > < serviceBehaviors > < behavior name= '' MyServiceBehavior '' > < serviceMetadata httpGetEnabled= '' true '' / > < serviceDebug includeExceptionDetailInFaults= '' true '' / > < /behavior > < /serviceBehaviors > < endpointBehaviors > < behavior name= '' WebBehavior '' > < webHttp / > < /behavior > < /endpointBehaviors > < /behaviors > < services > < service behaviorConfiguration= '' MyServiceBehavior '' name= '' BookStore.BookStoreImpl '' > < endpoint address= '' http : //localhost:8080/bookservice/ '' binding= '' wsHttpBinding '' contract= '' BookStore.IBookStore '' / > < endpoint address= '' '' behaviorConfiguration= '' WebBehavior '' binding= '' webHttpBinding '' contract= '' BookStore.IBookStore '' > < /endpoint > < endpoint address= '' mex '' binding= '' mexHttpBinding '' contract= '' IMetadataExchange '' / > < /service > < /services > < /system.serviceModel > < ! -- < system.serviceModel > < services > < service name= '' BookStore.BookStoreImpl '' > < endpoint address= '' http : //localhost:8080/bookservice '' behaviorConfiguration= '' restfulBehavior '' binding= '' webHttpBinding '' bindingConfiguration= '' '' contract= '' BookStore.IBookStore '' / > < host > < baseAddresses > < add baseAddress= '' http : //localhost:8080/bookservice '' / > < /baseAddresses > < /host > < /service > < /services > < behaviors > < serviceBehaviors > < behavior > < serviceMetadata httpGetEnabled= '' true '' httpsGetEnabled= '' true '' / > < serviceDebug includeExceptionDetailInFaults= '' false '' / > < /behavior > < /serviceBehaviors > < endpointBehaviors > < behavior name= '' restfulBehavior '' > < webHttp / > < /behavior > < /endpointBehaviors > < /behaviors > < protocolMapping > < add binding= '' basicHttpsBinding '' scheme= '' https '' / > < /protocolMapping > < serviceHostingEnvironment aspNetCompatibilityEnabled= '' true '' multipleSiteBindingsEnabled= '' true '' / > < /system.serviceModel > -- > < system.webServer > < modules runAllManagedModulesForAllRequests= '' true '' > < remove name= '' ApplicationInsightsWebTracking '' / > < add name= '' ApplicationInsightsWebTracking '' type= '' Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule , Microsoft.AI.Web '' preCondition= '' managedHandler '' / > < /modules > < ! -- To browse web app root directory during debugging , set the value below to true . Set to false before deployment to avoid disclosing web app folder information . -- > < directoryBrowse enabled= '' true '' / > < validation validateIntegratedModeConfiguration= '' false '' / > < /system.webServer > < entityFramework > < defaultConnectionFactory type= '' System.Data.Entity.Infrastructure.LocalDbConnectionFactory , EntityFramework '' > < parameters > < parameter value= '' mssqllocaldb '' / > < /parameters > < /defaultConnectionFactory > < providers > < provider invariantName= '' System.Data.SqlClient '' type= '' System.Data.Entity.SqlServer.SqlProviderServices , EntityFramework.SqlServer '' / > < /providers > < /entityFramework > < /configuration >",Accessing WCF service via HTTP "C_sharp : I have a two tables are state and namelist.State namelistI want the the result table asI want the above result with using linq queryI tried below code but that returns error as ( Unable to create a constant value of type 'xxx ' . Only primitive types or enumeration types are supported in this context . ) Anyone know how to solve this issue ? -- -- -- -- -- -- id | state -- -- -- -- -- -- 1 |xxx2 |yyy -- -- -- -- -- -- -- -id|Name |stateid -- -- -- -- -- -- -- 1|aaa |12|abb |13|ccc |24|dds |2 -- -- -- -- -- -- -- -- -- state |count -- -- -- -- -- -- -- -- -- -xxx | 2yyy | 2 var count= ( from n in bc.db.state select new { states = n.state , count = ( from c in bc.db.namelist where c.stateid == n.id select n ) .Count ( ) } ) ;",Unable to create a constant value of type 'xxx ' . Only primitive types or enumeration types are supported in this context "C_sharp : Can I create anonymous implementations of an interface , in a way similar to the way Something on the lines of The situations where I see them to be useful are for specifying method parameters which are interface types , and where creating a class type is too much code.For example , consider like this : how would this be achieved if in the above code , the method Cleanup had an interface as a parameter , without writing a class definition ? ( I think Java allows expressions like new Interface ( ) ... ) delegate ( ) { // type impl here , but not implementing any interface } new IInterface ( ) { // interface methods impl here } public void RunTest ( ) { Cleanup ( delegate ( ) { return `` hello from anonymous type '' ; } ) ; } private void Cleanup ( GetString obj ) { Console.WriteLine ( `` str from delegate `` + obj ( ) ) ; } delegate string GetString ( ) ;",Anonymous types based in Interface "C_sharp : I 'm trying to convert a string to a double value but it 's not returning me what I expect ... That piece of code is returning 200.0 ( instead of 20.0 ) as a double value . Any idea why ? double dbl ; Double.TryParse ( `` 20.0 '' , out dbl ) ;",Converting a string to a double "C_sharp : In a cake build script there is a very neat way of documenting the tasks using the .Description ( ) extension on the Task . These descriptions are displayed when calling the build script with the -showdescription argument.I have several custom arguments in my build script that I 'd like to document somehow . Currently I added a task that outputs a description text similar to the manual page style for the available arguments that looks something like this : This works fine but is a lot of work , especially if the text should be properly formatted so it 's readable in the command line.So when I call ./build.ps1 -Target MyDocTaskI get a nice result : Is there another way or a best practice to add documentation for arguments so it can be displayed in the command line similar to the tasks descriptions ? Edit : Alternatively , can I find all available parameters in my build script to loop over them and generate such a description instead of writing it manually for each parameter ? var nextLineDescription = `` \n\t\t\t\t\t '' ; // for formatting Console.WriteLine ( `` ARGUMENTS '' ) ; Console.WriteLine ( `` '' ) ; Console.WriteLine ( `` \t -- someparameter= < number > \t\t '' + `` Description of the parameter '' + nextLineDescription + `` that can span multiple lines '' + nextLineDescription + `` and defaults to 5.\n '' ) ; ARGUMENTS -- someparameter=number Description of the parameter that can span multiple lines and defaults to 5 -- nextParameter Next description ...",How can cake build arguments be documented ? "C_sharp : This works : This crashes : This article suggests that the return attribute is essentially like calling Marshal.PtrToStringAnsi , so what 's the deal ? As Daniel pointed out , it 's probably crashing because the marshaller is attempting to free the memory . The article also states , N.B . : Note that the unmanaged side must not use the “ new ” keyword or the “ malloc ( ) ” C function to allocate memory . The Interop Marshaler will not be able to free the memory in these situations . This is because the “ new ” keyword is compiler dependent and the “ malloc ” function is C-library dependent.I 've tried freeing the char pointer with Marshal.FreeHGlobal , Marshal.FreeCoTaskMem and Marshal.FreeBSTR -- they all crash . There are n't any other ways of freeing the memory AFAIK , so I 'm guessing the memory was allocated via new or malloc ( ) . So what now , I 'm hooped ? I have a permanent memory leak in my program ? I checked the source . The string is created via static char errmsg [ SDL_ERRBUFIZE ] . My C is rusty , but I guess it 's declared as static so that it does n't get freed when it goes out of function scope . I do n't remember where static arrays live in memory-land though ; is there some way of freeing them ? Edit : Wait ... it 's static . That means each time there 's a new error it will overwrite the old error message , hence why SDL_GetError ( ) only returns the most recent error message . Ergo , I do n't have to worry about freeing it.As such , if all the return : MarshalAs ... options attempt to free the memory , then the only solution is my current one . This is optimal after all . [ DllImport ( `` SDL2.dll '' , CallingConvention = CallingConvention.Cdecl , EntryPoint = `` SDL_GetError '' ) ] private static extern IntPtr SDL_GetError ( ) ; public static string GetError ( ) { return Marshal.PtrToStringAnsi ( SDL_GetError ( ) ) ; } [ DllImport ( `` SDL2.dll '' , CallingConvention = CallingConvention.Cdecl , EntryPoint = `` SDL_GetError '' ) ] [ return : MarshalAs ( UnmanagedType.LPStr ) ] public static extern string GetError ( ) ;",How to marshal to ANSI string via attribute ? "C_sharp : I 've been searching for actual working code where an overloaded false operator actually gets executed.This question ( What 's the false operator in C # good for ? ) is somewhat the same , but the accepted answer links to an url which is returning a 404 error . I 've also looked at How does operator overloading of true and false work ? and some other questions.What I 've found in almost all answers is that false only gets executed when you use a short circuited and like x & & y . This is evaluated as T.false ( x ) ? x : T. & ( x , y ) .Ok , so I have the following code . The struct contains an int and considers itself true if the int is greater than zero . : Now I would hope the following program will execute and use the overloaded false operator.However , it does not even compile . It says it can not apply operator ' & & ' to operands of type 'MyStruct ' and 'MyStruct'.I know I can implement an overload of the & operator . So let 's do that . The & must return a MyStruct , so I can not make it return a bool.Now the code does compile . Its output is 1 and -1 . So the result of b1 & & b2 is not the same as that of b2 & & b1.If I debug the code , I see that b1 & & b2 first executes the false operator on b1 , which returns false . Then it performs the & operator on b1 and b2 , which performs a bitwise and on 1 and -1 , resulting in 1 . So it indeed is first checking if b1 is false.The second expression , b2 & & b1 first executes the false operator on b2 , which returns true . Combined with the fact I 'm using short circuiting , it does n't do anything with b1 and just prints out the value of b2.So yes , the false operator is executed when you use short circuiting . However , it does not execute the true or false operator on the second argument , but instead executes the overloaded & operator on the operands.When can this ever be useful ? Or how can I make my type so that it can check if the two variables both are true ? public struct MyStruct { private int _i ; public MyStruct ( int i ) { _i = i ; } public static bool operator true ( MyStruct ms ) { return ms._i > 0 ; } public static bool operator false ( MyStruct ms ) { return ms._i < = 0 ; } public override string ToString ( ) { return this._i.ToString ( ) ; } } class Program { private static void Main ( ) { MyStruct b1 = new MyStruct ( 1 ) ; // to be considered true MyStruct b2 = new MyStruct ( -1 ) ; // to be considered false Console.WriteLine ( b1 & & b2 ) ; Console.WriteLine ( b2 & & b1 ) ; } } public static MyStruct operator & ( MyStruct lhs , MyStruct rhs ) { return new MyStruct ( lhs._i & rhs._i ) ; }",When does overloaded false operator ever gets executed and what is it good for ? "C_sharp : I wrote this simple program : Is there any option to make the displayed values print only once ? For example , if there are three occurrences - the message displays three times . Is it possible to make it display once when there are more occurrences though ? class Program { static void Main ( string [ ] args ) { Console.Write ( `` Number of elements in the array : `` ) ; int numberOfElements = int.Parse ( Console.ReadLine ( ) ) ; int [ ] array = new int [ numberOfElements ] ; for ( int i = 0 ; i < numberOfElements ; i++ ) { Console.Write ( $ '' Element no { i+1 } : `` ) ; array [ i ] = int.Parse ( Console.ReadLine ( ) ) ; } for ( int i = 0 ; i < array.Length ; i++ ) { int count = 0 ; for ( int j = 0 ; j < array.Length ; j++ ) { if ( array [ i ] == array [ j ] ) { count++ ; } } Console.WriteLine ( $ '' { array [ i ] } appears `` + count + `` times '' ) ; } } } }",C # : how to detect repeating values in an array and process them in such a way that each repeating value is only processed once ? "C_sharp : For Data Explorer I would like to add support for a Batch separator . So for example if users type in : I would like to return the three result sets . Its clear that I need some sort of parser here , my hope is that this is a solved problem and I can just plug it in . ( writing a full T-SQL parser is not something I would like to do ) What component / demo code could achieve splitting this batch into its 3 parts ? select 'GO ' go select 1 as go Go select 100",How do I accurately handle a batch separator for SQL from C # "C_sharp : I am not sure if there 's a better way to do this . maybe someone help ? I want to cast an object of type JObject to a class in a factory . Class itself should be decided based on on another parameter . But I can only think of Serializing the object to a string an serializing back into a specific class . There has to be a better way ? https : //dotnetfiddle.net/3Qwq6V using Newtonsoft.Json ; using Newtonsoft.Json.Serialization ; using System ; namespace Test { public class Input { public int TypeId { get ; set ; } public object ObjectDefinesInput ; } public class VoiceInput { public string Language ; } public class TextInput { public string Encoding ; } public interface IResponse { void Respond ( ) ; } public class VoiceResponse : IResponse { private VoiceInput input { get ; set ; } public VoiceResponse ( VoiceInput input ) { this.input = input ; } public void Respond ( ) { // use information on VoiceInput to do something Console.WriteLine ( `` ( In `` + this.input.Language + '' ) : beep buup boop . `` ) ; } } public class TextResponse : IResponse { private TextInput input { get ; set ; } public TextResponse ( TextInput input ) { this.input = input ; } public void Respond ( ) { Console.WriteLine ( `` I am a text handler . Using `` + this.input.Encoding + '' . `` ) ; } } public static class ResponseFactory { public static IResponse CreateResponseHandler ( Input input ) { // -- -- -- -- -- -- -- -- - ISSUE HERE -- -- -- -- -- -- -- -- -- -- -- -- -- -- -// // I 'm using JsonConvert to serialize an < object > to a string , and then string jsonObjectDefinesInput = JsonConvert.SerializeObject ( input.ObjectDefinesInput , new JsonSerializerSettings { Formatting = Formatting.Indented , ContractResolver = new CamelCasePropertyNamesContractResolver ( ) } ) ; switch ( input.TypeId ) { case 1 : // ( VoiceInput ) input.ObjectDefinesInput throws exception // input.ObjectDefinesInput as VoiceInput returns null VoiceInput voiceInput = JsonConvert.DeserializeObject < VoiceInput > ( jsonObjectDefinesInput ) ; return new VoiceResponse ( voiceInput ) ; default : TextInput textInput = JsonConvert.DeserializeObject < TextInput > ( jsonObjectDefinesInput ) ; return new TextResponse ( textInput ) ; } } } public class Program { public static void Main ( string [ ] args ) { string jsonData1 = `` { \ '' typeId\ '' : 1 , \ '' ObjectDefinesInput\ '' : { \ '' Language\ '' : \ '' Robot\ '' } } '' ; string jsonData2 = `` { \ '' typeId\ '' : 2 , \ '' ObjectDefinesInput\ '' : { \ '' Encoding\ '' : \ '' UTF-8\ '' } } '' ; Input someInpput1 = JsonConvert.DeserializeObject < Input > ( jsonData1 ) ; Input someInpput2 = JsonConvert.DeserializeObject < Input > ( jsonData2 ) ; IResponse testResponse1 = ResponseFactory.CreateResponseHandler ( someInpput1 ) ; IResponse testResponse2 = ResponseFactory.CreateResponseHandler ( someInpput2 ) ; testResponse1.Respond ( ) ; testResponse2.Respond ( ) ; Console.ReadLine ( ) ; } } }",Is there a better way to cast an JObject to any implementation of an interface ? "C_sharp : So I am working through my first WPF project and I am liking what I see so far . There was more of learning curve than what I anticipated , but nevertheless WPF is pretty cool . However , I am struggling a little bit with the data binding concepts . One specific question I have is how do I make my data binding declarations refactor safe ? Consider this example.So what if I rename the FooProperty on my data object to something else ? The data binding will be invalid and I will not get a compile error since the binding was declared via text only . Is there a way to make the binding a little more refactor safe ? public class MyDataObject { public string FooProperty { get ; set ; } } void Bind ( ) { var gridView = myListView.View as GridView ; gridView.Columns.Clear ( ) ; gridView.Columns.Add ( new GridViewColumn ( ) { Header = `` FooHeader '' , DisplayMember = new Binding ( `` FooProperty '' ) } ) ; List < MyDataObject > source = GetData ( ) ; myListView.ItemsSource = source ; }",How do I make WPF data bindings refactor safe ? "C_sharp : In C # , if a class has all the correct methods/signatures for an Interface , but does n't explicitly implement it like : Can the class still be cast as that interface ? class foo : IDoo { }",C # and Interfaces - Explicit vs . Implicit "C_sharp : I need to use inheritance with EF4 and the TPH model created from DB.I created a new projet to test simples classes.There is my class model : There is my table in SQL SERVER 2008 : I added a condition in my EDMX on the Discriminator field to differentiate the Scooter , Car , Motorbike and Bike entities.MotorizedVehicle and Vehicle are Abstract.But when I compile , this error appears : Error 3032 : Problem in mapping fragments starting at lines 78 , 85 : EntityTypes EF4InheritanceModel.Scooter , EF4InheritanceModel.Motorbike , EF4InheritanceModel.Car , EF4InheritanceModel.Bike are being mapped to the same rows in table Vehicle . Mapping conditions can be used to distinguish the rows that these types are mapped to.Edit : To Ladislav : I try it and error change to become it for all of my entities : Error 3034 : Problem in mapping fragments starting at lines 72 , 86 : An entity is mapped to > different rows within the same table . Ensure these two mapping fragments do not map two > groups of entities with overlapping keys to two distinct groups of rows.To Henk ( with Ladislay suggestion ) : There are all of mappings details : What 's wrong ? Thanks VEHICLE ID : int PK Owner : varchar ( 50 ) Consumption : float FirstCirculationDate : date Type : varchar ( 50 ) Discriminator : varchar ( 10 )",EF4 and multiple abstract levels "C_sharp : I have a application with the following Layout . In the Shared Views Folder I have , _Layout.cshtml , _SideNav.cshtml and _CurrentUser.cshtml.In the _Layout.cshtml I have : In the _SideNav.cshtml I have : In the _CurrentUser.cshtml I have : We use FormsAuthentication to authenticate a user . We are not using the standard Identity authentication which ships with ASP.Net MVC 5 because we are using a LDAP Server.We use the username in the cookie so that we can easily get information from the LDAP server.Problem : @ User.Identity.Name returns that username . But I need to display the full name of the user . I have access to the full name when we authenticate . but not sure how to use it.How can I pass the FullName value from the AccountController to the _CurrentUser.cshtml partial view ? Kind of like a Global Container like @ User.Identity with more attributes that can be set . @ { Html.RenderPartialIf ( `` _SideNav '' , Request.IsAuthenticated ) ; } @ { Html.RenderPartial ( `` _CurrentUser '' ) ; } < div class= '' login-info '' > < span > < a href= '' javascript : void ( 0 ) ; '' id= '' show-shortcut '' data-action= '' toggleShortcut '' > < img src= '' ~/content/img/avatars/sunny.png '' alt= '' me '' class= '' online '' / > < span > @ User.Identity.Name < /span > < i class= '' fa fa-angle-down '' > < /i > < /a > < /span > < /div > FormsAuthentication.SetAuthCookie ( username , isPersistent ) ; ... ..HttpContext.Current.User = new GenericPrincipal ( new GenericIdentity ( username , `` Forms '' ) , roles ) ;",MVC 5 Global User Account Object "C_sharp : Please , now that I 've re-written the question , and before it suffers from further fast-gun answers or premature closure by eager editors let me point out that this is not a duplicate of this question . I know how to remove duplicates from an array.This question is about removing sequences from an array , not duplicates in the strict sense.Consider this sequence of elements in an array ; In this example I want to obtain the following ... Notice that duplicate elements are retained but that sequences of the same element have been reduced to a single instance of that element.Further , notice that when two lines repeat they should be reduced to one set ( of two lines ) ... .reduces to ... I 'm coding in C # but algorithms in any language appreciated . [ 0 ] a [ 1 ] a [ 2 ] b [ 3 ] c [ 4 ] c [ 5 ] a [ 6 ] c [ 7 ] d [ 8 ] c [ 9 ] d [ 0 ] a [ 1 ] b [ 2 ] c [ 3 ] a [ 4 ] c [ 5 ] d [ 0 ] c [ 1 ] d [ 2 ] c [ 3 ] d [ 0 ] c [ 1 ] d",Best way to reduce sequences in an array of strings "C_sharp : Is an atomic read guaranteed when you mix Interlocked operations with lock ( ) ( and other higher-level locks ) ? I am interested in general behaviour when mixing locking mechanisms like this , and any differences between Int32 and Int64 . private Int64 count ; private object _myLock ; public Int64 Count { get { lock ( _myLock ) { return count ; } } } public void Increment { Interlocked.Increment ( ref count ) ; }",Can Interlocked class safely be mixed with lock ( ) ? C_sharp : Example : A variable `` s '' is defined in a lambda and another variable `` s '' as a local variable within the same method . Visual Studio tells me `` A conflicting variable is defined below '' when I hover over the first `` s '' . Why are these conflicting ; the `` s '' in the lambda is not available outside of its enclosing brackets surely ? myObject.Stub ( s = > s.MyMethod ( null ) ) .IgnoreArguments ( ) .Return ( `` bleh '' ) ; var s = `` s '' ;,Lambda variable scope "C_sharp : I 'm currently trying to convert anto an Currently the watch shows me that my expression holds I 'd like to simplify this toCurrently I only succeed at adding a convert , resulting in : But since the underlying type IS a bool , I should be able to scratch the converts entirely , right ? I 'm familiar with expression visitors etc , but still ca n't figure out how to remove the convert.Edit : this accepted answer to this question Generic unboxing of Expression < Func < T , object > > to Expression < Func < T , TResult > > ( that could be a possible duplicate ) does n't work for me ... as the expression gets translated by EF , you can see it does Convert ( Convert ( ) ) instead of just removing the first convert ... , this results in `` Unable to cast the type 'System.Boolean ' to type 'System.Object ' . LINQ to Entities only supports casting EDM primitive or enumeration types . '' Expression < Func < T , object > > Expression < Func < T , bool > > Expression < Func < T , object > > myExpression = model= > Convert ( model.IsAnAirplane ) Expression < Func < T , bool > > myExpression = model= > model.IsAnAirplane Expression < Func < T , bool > > myExpression = model= > Convert ( Convert ( model.IsAnAirplane ) )",Removing an unneeded boxing convert from a c # expression C_sharp : I have a class with this constructor : and I want to use this class with a new ( ) constraint but I get this error : 'Currency ' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T ' in the generic type or method ... If I split the constructor everything works fine : why do I need to split the constructor ? public Currency ( Guid ? vcurrencyUI = null ) : base ( vcurrencyUI ) { } public Currency ( Guid ? vcurrencyUI ) : base ( vcurrencyUI ) { } public Currency ( ) : base ( ) { },Constructor with optional parameter violates new ( ) constraint "C_sharp : In the scenario where a WCF service returns a DataContract with an enum member that has an invalid value ( an int not present in the Enum type ) the thrown exception on the client side is The underlying connection was closed : The connection was closed unexpectedly.Strangely enough this exception is triggered because the DataContractSerializer can not serialize at the serverside of the connection . I would rather have something more usefull thrown at me and more important earlier , at runtime on the serverside but maybe a compiler warning ... WCF Service ContractService implementationClientTo have the actual exception thrown I had to disbale 'enable just my code ' in the debug options VS2010 and in the Exceptions dialog enable Thrown for 'Common language Runtime exceptions'With that settings the valuable exception is : SerializationException Enum value '42 ' is invalid for type 'WcfService1.Rating ' and can not be serialized . Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attributeThis comes at the cost that the debugger gets very noisy about all other kinds of thrown exceptions that AFAIK can be ignored.What can I try to have this exception thrown without the noise ? Is there something I can tweak or add in the WCF pipeline ? One possible solution to fail early with the cost of rework is adding an extra Assert in the setter of the enum member : An alternative I tried was adding a Contract in the hope a warning could be produced . I could n't find any thing better than basically a copy of the Debug.Assert.Is there an option to have the compiler emit this check for me or is there an alternative I 'm not aware of ? ( I also tried to compile with the check for arithmetic overflow/underflow enabled without expecting it to be succeful ) CodeContracts does emit a warning , ( you have to enble Implicit Enum write obligations ) though that does not really help The actual value may not be in the range defined for this enum valueThis behavior is in a VS2010/.Net 4.0 context . [ ServiceContract ] public interface IDtoService { [ OperationContract ] MyDto GetData ( int value ) ; } public enum Rating { None = 0 , NotSet = 1 , Somevalue = 34 } [ DataContract ] public class MyDto { Rating _rate ; [ DataMember ] public Rating Rating { get { return _rate ; } set { _rate = value ; } } } public class DtoService : IDtoService { public MyDto GetData ( int value ) { var dto = new MyDto { Rating = ( Rating ) 42 } ; // not in ENUM ! return dto ; } } var cl = new DtoServiceClient.DtoServiceClient ( ) ; var tada = cl.GetData ( 1 ) ; // connection closed exception Debug.Assert ( Enum.IsDefined ( typeof ( Rating ) , value ) , '' value is not valid for this enum '' ) ; System.Diagnostics.Contracts.Contract.Assert ( Enum.IsDefined ( typeof ( Rating ) , value ) ) ;",Fail early or clearly throw when an enum can not be serialized "C_sharp : I have ReSharper naming rules set up such that all property names must be PascalCase . However there are times when I have to use a different naming style to work with serialization . For example , backbone.js expects objects to have an Id named 'id ' . I 'd prefer to have my objects match the expectations of serializers rather than use fancy serialization attributes to change the way things are named . Is there a way to mark my DTO classes as such so resharper does n't complain about them ? What about a conventions-based approach , like `` Exempt any class whose name ends with 'Dto ' or is in a namespace called 'Dto ' ? Additionally , I 'd rather not use the special //disable rule XX comment blocks . I find them really distracting public class PersonDto { public int id { get ; set ; } //i want resharper to accept this as a valid name , // but only in this context . public string Name { get ; set ; } public string _CID { get ; set ; } //some external api is sending me data named like this }",Ignore ReSharper naming rules for DTOs "C_sharp : I know how to use properties and I understand that they implicitly call underlying get and set accessors , depending on whether we are writing to or reading from a property . What code ( a.b ) .i = 100 ; essentially does is that first property ’ s get accessor returns a reference to an object _b , and once we have this reference , we are able to access _b ’ s members and change their values . Thus , in our example , having read only property only prevents outside code from changing the value of a reference variable _b , but it doesn ’ t prevent outside code from accessing _b ’ s members . So it seems that property can only detect whether we are trying to read from or write to a variable ( in our case variable _b ) located on the stack , while it ’ s not able to detect whether we ’ re trying to also write to members of an object to which the variable on the stack ( assuming this variable is of reference type ) points to.a ) But doesn ’ t that defeat the whole purpose of having read-only properties ? Wouldn ’ t it be more effective if properties had the ability to also detect whether we ’ re trying to access members of an object returned by get accessor ( assuming backing field is of a reference type ) ? thank you static void Main ( string [ ] args ) { A a = new A ( ) ; ( a.b ) .i = 100 ; } class A { private B _b = new B ( ) ; public B b { get { return _b ; } } } class B { public int i ; }",Does n't this defeat the whole purpose of having read-only properties ? "C_sharp : I 'm writing some debug code at work , and I 'm wondering if what I 'm doing might hurt performance or not.Let 's get to the code : I know that the Debug class uses the Conditional attribute to avoid compilation in release mode ( or whenever DEBUG is undefined ) , but would this end up as a futile/empty iteration when compiled in release mode or would it be optimized by the compiler ? foreach ( var item in aCollection ) Debug.WriteLine ( item.Name ) ;",Does the C # compiler optimize foreach blocks when its contents have the Conditional attribute ? "C_sharp : I 'm trying to get a list of string ordered such that the longest are on either end of the list and the shortest are in the middle . For example : would get sorted as : EDIT : To clarify , I was specifically looking for a LINQ implementation to achieve the desired results because I was n't sure how/if it was possible to do using LINQ . ABBCCCDDDDEEEEEFFFFFF FFFFFFDDDDBBACCCEEEEE",LINQ non-linear order by string length "C_sharp : I 'm currently consuming a legacy WCF service that does not conform to the naming standards from the app in development . Now when developing against a REST service , where I create the models on my own it is really easy to rename a property like so : But with the WCF service it generates the model , and I do n't want to edit a generated file as all my changes would be lost when someone/-thing triggers the code generation again . So how could I achieve the same goal when consuming a WCF service ? [ DataContract ] public class SomeModel { [ DataMember ( Name = `` id '' ) ] public string Id { get ; set ; } // ... }",Rename property names from WCF service generated model "C_sharp : I 'm having difficulties working with some legacy enums that have multiple zero values . Whenever I call ToString on one of the non-zero values , all but the first zero value is included.Is there any way to isolate the non-zero value name without resorting to string manipulation or reflection ? EditI understand that having multiple items with the same value is not recommended however the enum in question is defined in a legacy assembly that I ca n't change . In fact , there are 12 public enums in mscorlib v4 that break this recommendation , as determined by the following simple LINQ query : //all of the following output `` Nada , Zilch , One '' Console.WriteLine ( TestEnum.One ) ; Console.WriteLine ( Convert.ToString ( TestEnum.One ) ) ; Console.WriteLine ( TypeDescriptor.GetConverter ( typeof ( TestEnum ) ) .ConvertToString ( TestEnum.One ) ) ; [ Flags ] enum TestEnum { Zero = 0 , Nada = 0 , Zilch = 0 , One = 1 } var types = typeof ( void ) .Assembly.GetTypes ( ) .Where ( type = > type.IsEnum & & type.IsPublic & & Enum.GetValues ( type ) .Cast < object > ( ) .GroupBy ( value = > value ) .Any ( grp = > grp.Count ( ) > 1 ) ) .ToList ( ) ;",Getting item names from enums with multiple zero values "C_sharp : I have been working on a windows form application based in c # and I am in need of some assistance . I am trying to recreate the window flicker that most windows applications have when a form loses focus to a parent form . Best way I can explain this is open up calculator open the help window and try to click the calculator , the help window then without falling behind the calculator flickers losing and gaining the shadowing around the edges.I have managed to regain the focus on the child window when the parent is clicked but this creates a odd flickering effect as the parent window is momentarily brought in front of the child window . I am only guessing but that effect I am looking for appears to be that the calculator is never brought in front of the help window and then the help window is simply activated and deactivated a few times.I tried doing some searches and I have seen a few topics relating to this but none of the solutions quite match . I am fairly new to making windows form applications so there are still a things I do n't understand so be patient with me if I do n't understand something at first.Thank you in advanceAn elaboration on the calculator example:1 ) open up calculator from windows accessories2 ) in the toolbar go to the help tab and open the about calculator option3 ) click on the calculator window4 ) the about calculator window will then flicker while never falling behind the calculatorThe only progress I have made towards this is The open variable is something I use to keep track of if open forms and is made true when I show another form . private void MainForm_Activated ( object sender , EventArgs e ) { if ( Open == true ) { //blink active window _addForm.Activate ( ) ; //makes window active } }",Window Flicker on loss of focus ? "C_sharp : I want it to behave such as you clicked somewhere on application . ( which collapses all menus , drop downs , etc ) Actually , I 'm trying to get around the interoperability related focus issue you get when you are hosting Windows Forms controls in a WPF application using WindowsFormsHost : If a WPF menu/popup by DevExpress is open and you click on a Windows Forms control , the menu/popup does n't get dismissed automatically.Now I have a lot of Windows Forms controls in the WindowsFormsHost and also a lot of DevExpress controls in the WPF area . To get around this easily , I have added a message filter to hook all clicks in application and then I see if the clicked control was a Windows Forms control . Then I need to do something to make all WPF menus , etc . by DevExpress dismissed if they were open.GlobalMouseHandler : GlobalMouseHandler globalClick = new GlobalMouseHandler ( ) ; System.Windows.Forms.Application.AddMessageFilter ( globalClick ) ; public class GlobalMouseHandler : System.Windows.Forms.IMessageFilter { private const int WM_LBUTTONDOWN = 0x201 ; private const int WM_RBUTTONDOWN = 0x204 ; public bool PreFilterMessage ( ref System.Windows.Forms.Message m ) { if ( m.Msg == WM_LBUTTONDOWN || m.Msg == WM_RBUTTONDOWN ) { var c = System.Windows.Forms.Control.FromHandle ( m.HWnd ) ; if ( c ! = null ) // TODO : CLOSE ALL WPF MENUS ETC // Did n't work : MainWindow.Instance.ARandomControl.Focus ( ) ; } return false ; } }","How to dismiss all WPF menus , popups , etc . by DevExpress programmatically to get around WindowsFormsHost related issue ?" "C_sharp : I 'm trying to distribute Values over a specific number of Value Holders based on a Start and End value.If the number of Value Holders is equal to the difference of the Start and End Values , it will just be a simple iteration : If the number of Value Holders is less than the difference of the Start and End Values , we need to skip some numbers . The goal is to try to distribute the values as evenly as possible.NOTE : Leaning on either right/left is not important : ) If the number of Value Holders is more than the difference of the Start and End Values , we will be repeating some numbers.How can I implement this in C # ? Start Value : 1End Value : 10Value Holders : 10|Expected Result : 1 2 3 4 5 6 7 8 9 10 Start Value : 1End Value : 10Value Holders : 5|Expected Result : 1 3 5 8 10 or 1 3 6 8 10Start Value : 1End Value : 10Value Holders : 3|Expected Result : 1 5 10 or 1 6 10 Start Value : 1End Value : 10Value Holders : 15|Expected Result : 1 2 3 4 4 5 5 6 6 7 7 8 8 9 10 ( or something similar )",Distribute Values Based on a Start and End Value and Number of Value Holders "C_sharp : I need to keep track of the selected item on a ListBox to update/disable other controls according to the currently selected value.This is the code to reproduce the issue : My form has a list box listBox1 and three buttons : addButton , removeButton and logSelectionButton.If you press addButton ( starting with an empty list ) , then removeButton and finally addButton again , neither SelectedValueChanged nor SelectedIndexChanged will fire at the last addButton press , even though if you press logSelectionButton before and after the last addButton press , you 'll see that the values of both SelectedIndex and SelectedValue have changed from -1 to 0 and from null to `` Item 1 '' respectively , and that `` Item 1 '' looks selected on the list box . This would cause any other controls I need to update according to the selected item to stay disabled until the user manually selects an item on the list box , even though the first item is already selected.I ca n't think of any workaround . Perhaps also subscribing to my BindingList 's ListChanged event to see whether the list is empty or not , but then I do n't know if the items in the list box will be updated before or after my event handler fires , which will cause other problems . public partial class Form1 : Form { private readonly BindingList < string > List = new BindingList < string > ( ) ; public Form1 ( ) { InitializeComponent ( ) ; listBox1.DataSource = List ; listBox1.SelectedValueChanged += ( s , e ) = > System.Diagnostics.Debug.WriteLine ( `` VALUE '' ) ; listBox1.SelectedIndexChanged += ( s , e ) = > System.Diagnostics.Debug.WriteLine ( `` INDEX '' ) ; addButton.Click += ( s , e ) = > List.Add ( `` Item `` + ( List.Count + 1 ) ) ; removeButton.Click += ( s , e ) = > List.RemoveAt ( List.Count - 1 ) ; logSelectionButton.Click += ( s , e ) = > { System.Diagnostics.Debug.WriteLine ( `` Selected Index : `` + listBox1.SelectedIndex ) ; System.Diagnostics.Debug.WriteLine ( `` Selected Value : `` + listBox1.SelectedValue ) ; } ; } }",ListBox SelectedValueChanged/SelectedIndexChanged not firing when data source changes "C_sharp : weird one . ( Probably not weird , at all ) I have 3 objects , Employee , Rota and Department.Not complicated , at all really . Rota can have an Employee and/or a Department assigned to it , all of this is configured using Fluent . All of my associations are correct ( the schema is perfect ) , however I have a weird oddity.When I do a myContext.Departments.FirstOrDefault ( ) and have a look at the SQL Generated , there is a LEFT OUTER JOIN on Employee & Rota . Why is this there ? I do n't want it to do this . Maybe my Fluent mappings are incorrect ? I 've tried all sorts , but ca n't seem to figure it out . I would understand it if I want a Rota object , that would join on the Department . But not the other way around ! If I do myContext.Departments.AsNoTracking ( ) .FirstOrDefault ( ) it does n't do the LEFT OUTER JOIN's.Any ideas guys ? Cheers , D public class Employee { public int Id { get ; set ; } public String Name { get ; set ; } public virtual Department Department { get ; set ; } } internal class EmployeeMapping : EntityTypeConfiguration < Employee > { public EmployeeMapping ( ) { HasKey ( a = > a.Id ) ; Property ( a = > a.Id ) .HasColumnName ( `` UserId '' ) ; HasRequired < Department > ( a = > a.Department ) .WithOptional ( ) .Map ( a = > a.MapKey ( `` DepartmentId '' ) ) ; } } public class Department { public int Id { get ; set ; } public String Name { get ; set ; } } internal class DepartmentMapping : EntityTypeConfiguration < Department > { public DepartmentMapping ( ) { HasKey ( a = > a.Id ) ; Property ( a = > a.Id ) .HasColumnName ( `` DepartmentId '' ) ; } } public class Rota { public int Id { get ; set ; } public virtual Employee Employee { get ; set ; } public virtual Department Department { get ; set ; } } internal class RotaMapping : EntityTypeConfiguration < Rota > { public RotaMapping ( ) { HasKey ( a = > a.Id ) ; Property ( a = > a.Id ) .HasColumnName ( `` RotaId '' ) ; HasOptional < Employee > ( a = > a.Employee ) .WithOptionalDependent ( ) .Map ( a = > a.MapKey ( `` EmployeeId '' ) ) ; HasOptional < Department > ( a = > a.Department ) .WithOptionalDependent ( ) .Map ( a = > a.MapKey ( `` DepartmentId '' ) ) ; } }",Why the Left Outer join ? "C_sharp : What I have : This enables classes that are using IRepository to be easily testable and IoC containers friendly . However someone using this class has to call CreateConnection before calling any methods that are getting something from database , otherwise exception will be thrown . This itself is kind of good - we dont want to have long lasting connections in application . So using this class I do it like this.Unfortunetelly this is not very good solution because people using this class ( including even me ! ) often forget to call _repository.CreateConnection ( ) before calling methods to get something from database.To resolve this I was looking at Mark Seemann blog post SUT Double where he implements Repository pattern in correct way . Unfortunately he makes Repository implement IDisposable , which means I can not simply inject it by IoC and DI to classes and use it after , because after just one usage it will be disposed . He uses it once per request and he uses ASP.NET WebApi capabilities to dispose it after request processing is done . This is something I can not do because I have my classes instances which use Repository working all the time.What is the best possible solution here ? Should I use some kind of factory that will give me IDisposable IRepository ? Will it be easily testable then ? public interface IRepository { IDisposable CreateConnection ( ) ; User GetUser ( ) ; //other methods , doesnt matter } public class Repository { private SqlConnection _connection ; IDisposable CreateConnection ( ) { _connection = new SqlConnection ( ) ; _connection.Open ( ) ; return _connection ; } User GetUser ( ) { //using _connection gets User from Database //assumes _connection is not null and open } //other methods , doesnt matter } using ( _repository.CreateConnection ( ) ) { var user = _repository.GetUser ( ) ; //do something with user }","Repository pattern - make it testable , DI and IoC friendly and IDisposable" "C_sharp : EDITSee edit note at the bottom of the question for additional detail.Original questionI have a CacheWrapper class which creates and holds onto an instance of the .NET MemoryCache class internally.MemoryCache hooks itself into AppDomain events , so it will never be garbage-collected unless it is explicitly disposed . You can verify this with the following code : Because of the behavior , I believe that my MemoryCache instance should be treated as an unmanaged resource . In other words , I should ensure that it is disposed in the finalizer of CacheWrapper ( CacheWrapper is itself Disposable follows the standard Dispose ( bool ) pattern ) .However , I am finding that this causes issues when my code runs as part of an ASP.NET app . When the application domain is unloaded , the finalizer runs on my CacheWrapper class . This in turn attempts to dispose the MemoryCache instance . This is where I run into issues . It seems that Dispose attempts to load some configuration information from IIS , which fails ( presumably because I 'm in the midst of unloading the app domain , but I 'm not sure . Here 's the stack dump I have : Is there any known solution to this ? Am I correct in thinking that I do need to dispose the MemoryCache in the finalizer ? EDITThis article validates Dan Bryant 's answer and discusses many of the interesting details . In particular , he covers the case of StreamWriter , which faces a similar scenario to mine because it wants to flush it 's buffers upon disposal . Here 's what the article says : Generally speaking , finalizers may not access managed objects . However , support for shutdown logic is necessary for reasonably-complex software . The Windows.Forms namespace handles this with Application.Exit , which initiates an orderly shutdown . When designing library components , it is helpful to have a way of supporting shutdown logic integrated with the existing logically-similar IDisposable ( this avoids having to define an IShutdownable interface without any built-in language support ) . This is usually done by supporting orderly shutdown when IDisposable.Dispose is invoked , and an abortive shutdown when it is not . It would be even better if the finalizer could be used to do an orderly shutdown whenever possible . Microsoft came up against this problem , too . The StreamWriter class owns a Stream object ; StreamWriter.Close will flush its buffers and then call Stream.Close . However , if a StreamWriter was not closed , its finalizer can not flush its buffers . Microsoft `` solved '' this problem by not giving StreamWriter a finalizer , hoping that programmers will notice the missing data and deduce their error . This is a perfect example of the need for shutdown logic.All that said , I think that it should be possible to implement `` managed finalization '' using WeakReference . Basically , have your class register a WeakReference to itself and a finalize action with some queue when the object is created . The queue is then monitored by a background thread or timer which calls the appropriate action when it 's paired WeakReference gets collected . Of course , you 'd have to be careful that your finalize action does n't inadvertantly hold onto the class itself , thus preventing collection altogether ! Func < bool , WeakReference > create = disposed = > { var cache = new MemoryCache ( `` my cache '' ) ; if ( disposed ) { cache.Dispose ( ) ; } return new WeakReference ( cache ) ; } ; // with false , we loop forever . With true , we exitvar weakCache = create ( false ) ; while ( weakCache.IsAlive ) { `` Still waiting ... '' .Dump ( ) ; Thread.Sleep ( 1000 ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; } '' Cleaned up ! `` .Dump ( ) ; MANAGED_STACK : SP IP Function 000000298835E6D0 0000000000000001 System_Web ! System.Web.Hosting.UnsafeIISMethods.MgdGetSiteNameFromId ( IntPtr , UInt32 , IntPtr ByRef , Int32 ByRef ) +0x2 000000298835E7B0 000007F7C56C7F2F System_Web ! System.Web.Configuration.ProcessHostConfigUtils.GetSiteNameFromId ( UInt32 ) +0x7f 000000298835E810 000007F7C56DCB68 System_Web ! System.Web.Configuration.ProcessHostMapPath.MapPathCaching ( System.String , System.Web.VirtualPath ) +0x2a8 000000298835E8C0 000007F7C5B9FD52 System_Web ! System.Web.Hosting.HostingEnvironment.MapPathActual ( System.Web.VirtualPath , Boolean ) +0x142 000000298835E940 000007F7C5B9FABB System_Web ! System.Web.CachedPathData.GetPhysicalPath ( System.Web.VirtualPath ) +0x2b 000000298835E9A0 000007F7C5B99E9E System_Web ! System.Web.CachedPathData.GetConfigPathData ( System.String ) +0x2ce 000000298835EB00 000007F7C5B99E19 System_Web ! System.Web.CachedPathData.GetConfigPathData ( System.String ) +0x249 000000298835EC60 000007F7C5BB008D System_Web ! System.Web.Configuration.HttpConfigurationSystem.GetApplicationSection ( System.String ) +0x1d 000000298835EC90 000007F7C5BAFDD6 System_Configuration ! System.Configuration.ConfigurationManager.GetSection ( System.String ) +0x56 000000298835ECC0 000007F7C63A11AE System_Runtime_Caching ! Unknown+0x3e 000000298835ED20 000007F7C63A1115 System_Runtime_Caching ! Unknown+0x75 000000298835ED60 000007F7C639C3C5 System_Runtime_Caching ! Unknown+0xe5 000000298835EDD0 000007F7C7628D86 System_Runtime_Caching ! Unknown+0x86 // my code here",Disposing MemoryCache in Finalizer throws AccessViolationException "C_sharp : We have an enum : When I try : Strangely , frozenLetter == A.Letter and anotherLetter both equal A , so the Letters type has been frozen , but to the first constant in the enum rather than the one specified.Is there a way to freeze an enum to the constant I wish ? enum Letters { A , B , C , D , E } var frozenLetter = fixture.Freeze ( Letters.D ) ; var letter = fixture.Create < Letters > ( ) ; var anotherLetter = fixture.Create < Letters > ( ) ;",Freeze enum value in AutoFixture "C_sharp : I 'm trying to finish a quick `` demonstration of learning '' program by morning for Mothers Day . I 've created a textbox for my mom to enter my birthday and a label to display the number of years , months , days , and seconds I 've been alive when she clicks a button.The following is the part of my code where I am stuck : As I commented in the code , I get a blue squiggly under TimeSpan in the last line ; but I do n't understand why . What am I doing wrong ? I 'm just a student : so I 've got the concept but am not used to datetime formats and need a little help . private void button1_Click ( object sender , EventArgs e ) { DateTime sonsBirthday = DateTime.Parse ( txtSonsBirthday.Text ) .Date ; DateTime now = DateTime.Now ; TimeSpan timeSpan = now - sonsBirthday ; timeSpan = Convert.TimeSpan ( lblTimeAlive ) ; // blue squiggly under TimeSpan here",Calculate # of Years Alive in C # WinForm "C_sharp : Task Parallel Library uses Event Tracing for Windows ( ETW ) for logging . Apparently , there is a bug related to logging , in either TPL or ETW , surfacing under Windows Phone or Windows Store .NET Runtime . The original issue is described here.A possible workaround would be to disable the TPL 's ETW EventSource . How do I disable it from within a Universal Windows app , if I really want to ? Reflection works for a Desktop app , but not for a WP/WinRT app . EventCommand.Disable is not recognized as a valid command for EventSource.SendCommand ( although it 's used internally in ETW ) . Here 's the code to play with ( as a console app ) : For a Universal app , MyEventListener can just be instantiated as part of Application : using System ; using System.Threading.Tasks ; using System.Diagnostics.Tracing ; using System.Reflection ; namespace ConsoleApplication { class Program { internal class MyEventListener : EventListener { protected override void OnEventSourceCreated ( EventSource eventSource ) { Console.WriteLine ( eventSource ) ; base.OnEventSourceCreated ( eventSource ) ; if ( eventSource.Name == `` System.Threading.Tasks.TplEventSource '' ) { Console.WriteLine ( `` enabled : `` + eventSource.IsEnabled ( ) ) ; // trying to disable with EventCommand.Disable : Invalid command try { System.Diagnostics.Tracing.EventSource.SendCommand ( eventSource , EventCommand.Disable , new System.Collections.Generic.Dictionary < string , string > ( ) ) ; Console.WriteLine ( `` enabled : `` + eventSource.IsEnabled ( ) ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message ) ; } // reflection : does n't work for Windows Phone/Store apps try { var ti = typeof ( EventSource ) .GetTypeInfo ( ) ; var f = ti.GetDeclaredField ( `` m_eventSourceEnabled '' ) ; f.SetValue ( eventSource , false ) ; Console.WriteLine ( `` enabled : `` + eventSource.IsEnabled ( ) ) ; } catch ( Exception ex ) { Console.WriteLine ( ex.Message ) ; } } } protected override void OnEventWritten ( EventWrittenEventArgs eventData ) { Console.WriteLine ( eventData ) ; } } static MyEventListener listener = new MyEventListener ( ) ; static void Main ( string [ ] args ) { Task.Delay ( 1000 ) .Wait ( ) ; Console.ReadLine ( ) ; } } } public sealed partial class App : Application { static MyEventListener listener = new MyEventListener ( ) ; }",How to disable Task Parallel Library 's ETW EventSource in a Universal App ? "C_sharp : I have a table and I want to clone the last line of it after the Add New link is pressed . It works completely fine when I have only TextBoxes in my rows but it does n't when there 's a dropdown . Please help me to modify the jquery code.Here 's the code of the table : And here 's the code that needs some improvement : I tried to modify this line whith changing input to select , but it didnt help var suffix = $ trNew.find ( ' : input : first ' ) .attr ( 'name ' ) .match ( /\d+/ ) ; < div > < a href= '' # '' id= '' addNew '' > Add New < /a > < /div > < table id= '' dataTable '' > < tr > < th > Item < /th > < th > Cost < /th > < th > < /th > < /tr > @ if ( Model ! = null & & Model.Count > 0 ) { int j = 0 ; foreach ( var i in Model ) { < tr > < td > @ Html.DropDownListFor ( a = > a [ j ] .fk_purchase_id , ( SelectList ) ViewBag.fk_purchase_id , null , htmlAttributes : new { @ class = `` form-control '' } ) < /td > < td > @ Html.TextBoxFor ( a = > a [ j ] .cost , htmlAttributes : new { @ class = `` form-control '' } ) < /td > < td > @ if ( j > 0 ) { < a href= '' # '' class= '' remove '' > Remove < /a > } < /td > < /tr > j++ ; } } < /table > < script > $ ( function ( ) { //1 . Add new row $ ( `` # addNew '' ) .click ( function ( e ) { e.preventDefault ( ) ; var $ tableBody = $ ( `` # dataTable '' ) ; var $ trLast = $ tableBody.find ( `` tr : last '' ) ; var $ trNew = $ trLast.clone ( ) ; alert ( $ trNew.html ) ; var suffix = $ trNew.find ( ' : input : first ' ) .attr ( 'name ' ) .match ( /\d+/ ) ; $ trNew.find ( `` td : last '' ) .html ( ' < a href= '' # '' class= '' remove '' > Remove < /a > ' ) ; $ .each ( $ trNew.find ( ' : input ' ) , function ( i , val ) { // Replaced Name var oldN = $ ( this ) .attr ( 'name ' ) ; var newN = oldN.replace ( ' [ ' + suffix + ' ] ' , ' [ ' + ( parseInt ( suffix ) + 1 ) + ' ] ' ) ; $ ( this ) .attr ( 'name ' , newN ) ; //Replaced value var type = $ ( this ) .attr ( 'type ' ) ; if ( type.toLowerCase ( ) == `` text '' ) { $ ( this ) .attr ( 'value ' , `` ) ; } } ) ; $ trLast.after ( $ trNew ) ; } ) ; } ) ; < /script >",How to copy table row with dropdownlist in with jQuery "C_sharp : I 'm struggling to figure out how to use visual studio to debug async code sanely , since it 's not breaking where I want it to . For example , in this code : How can I get Visual Studio to automatically break where the exception is thrown and not at the top of my program ? Or equivalently , without restarting the process , can I jump to that context and see the values of those locals ? I understand the root problem is that the exceptions are technically being handled by the behind the scenes async code , so VS does n't see them as being unhandled . Surely no one else likes this behavior though , and there 's a way to tell VS that exceptions that bubble up to an async call are n't really caught ... I 've tried turning `` just my code '' , `` break when this exception is thrown '' , etc. , on and off , but nothing helps.I am not looking for a solution that includes editing my code or manually adding breakpoints . Similarly , handing certain exceptions in special ways is also not a real solution . Not all the exceptions I want to break on are from my own code ; often it will come from a missing key in a dictionary , or something like that . Unexpected exceptions happen all the time when developing code , and I want to see that program state easily without manually placing breakpoints and/or try/catch code , rerunning the program , manually advancing the program until I happen to get to the function . And , that 's all under the assumption I can even get it to trigger again , when I do n't know anything about why it happened in the first place . And then do that for every exception that ever might occur during development.On top of all that , if you 're looking at the AggregateException that does come back , there is n't even a nice way to figure out where that exception comes from . You 've got to `` view details '' , then expand the exception , expand the inner exception , hover over the stack trace , remember the file and line number , close the details , go to the right place manually , and now put manual breakpoints and go debug manually . Why ca n't the system use this stack trace to do the right thing ? I 'm putting all these details in because I have read 20 other SO posts about similar topics . They do n't put all these details in , and people seem to go off happily , so I 'm confused what I 'm doing wrong . None of this happens when developing non-async code . Are all of the steps I 'm doing above necessary ? What is the best practice to make writing async code as pleasant as writing non-async code in terms of examining exception context ? using System ; using System.Threading.Tasks ; namespace TestNS { class Program { static void Main ( string [ ] args ) { Foo ( ) .Wait ( ) ; // sadly , it breaks here } static async Task Foo ( ) { var foo = 42 ; if ( foo == 42 ) { throw new Exception ( ) ; // want it to break here } } } }",debugging async C # in visual studio ; breaking on exceptions as expected "C_sharp : is it possible to initialize a static class on app start up `` automatically '' ? By automatically I mean without the need of referencing a property.The reason I want to be able to do this for is that I 'd like to automatically theme an app on start up.Here 's a short snippet : I know I can ( and that 's how it is at the moment ) go with original getter/setter and callin constructor of App ( it 's WPF project ) and it 'll do the job , however , at least from my point of view ( correct me if I 'm mistaken please ) it 'd make more sense for the default theme to apply without the need of explicitly stating it . static class Settings { private static Theme _defaultTheme ; public static Theme DefaultTheme { get { return _defaultTheme ; } private set { _defaultTheme = value ; ThemeManager.SetTheme ( value ) ; } } static Settings ( ) { DefaultTheme = Themes.SomeTheme ; } } ThemeManager.SetTheme ( Settings.DefaultTheme ) ;",Initialize static class implicitly "C_sharp : EDIT : So after a brief contact with the Assimp dev , I was pointed towards the import process . As I took over the code from someone else , I did not think looking that part : FlipUVs does exactly what it says , it flips on the y axis so the origin is now top left corner . So now I am able to get the model with proper UV but still mirrored mesh . Setting the parent object with scale x = -1 flips it back to normal and makes it look fine but I guess this is not meant to be . So I keep looking.See the picture , there are two crane models . The one on the left is loaded at runtime via serialization and reconstruction while the right one is the original one simply dragged to the scene.Serialization happens with Assimp library.The floor happens to be created first and seems to get the right uv map . While the other items get wrong uv map . Though I am printing the values of the uv maps and they seem to match the original one as they should.This is how to serialize , this is Mesh class from Assimp , not the Unity Mesh class , the app serializing is Windows application built in UWP : And this is the invert process : MeshData is just a temporary container with the deserialized values from the fbx.Then , meshes are created : I do n't see any reason in the code that should result in this kind of behaviour , I 'd say it would totally screw the mesh if the values were wrong.I can see that the fbx files I have are using quad instead of triangle for the indexing . Could it be that Assimp does not go to well with this ? using ( var importer = new AssimpContext ( ) ) { scene = importer.ImportFile ( file , PostProcessSteps.Triangulate | PostProcessSteps.FlipUVs | PostProcessSteps.JoinIdenticalVertices ) ; } private static void SerializeMeshes ( BinaryWriter writer , IEnumerable < Mesh > meshes ) { foreach ( Mesh mesh in meshes ) { ICollection < int > triangles = MeshLoadTriangles ( mesh ) ; MeshSerializeHeader ( writer , mesh.Name , mesh.VertexCount , triangles.Count , mesh.MaterialIndex ) ; MeshSerializeVertices ( writer , mesh.Vertices ) ; MeshSerializeUVCoordinate ( writer , mesh.TextureCoordinateChannels ) ; MeshSerializeTriangleIndices ( writer , triangles ) ; } } private static void MeshSerializeUVCoordinate ( BinaryWriter writer , List < Vector3D > [ ] textureCoordinateChannels ) { // get first channel and serialize to writer . Discard z channel // This is Vector3D since happening outside Unity List < Vector3D > list = textureCoordinateChannels [ 0 ] ; foreach ( Vector3D v in list ) { float x = v.X ; float y = v.Y ; writer.Write ( x ) ; writer.Write ( y ) ; } } private static void MeshSerializeVertices ( BinaryWriter writer , IEnumerable < Vector3D > vertices ) { foreach ( Vector3D vertex in vertices ) { Vector3D temp = vertex ; writer.Write ( temp.X ) ; writer.Write ( temp.Y ) ; writer.Write ( temp.Z ) ; } } private static void MeshSerializeTriangleIndices ( BinaryWriter writer , IEnumerable < int > triangleIndices ) { foreach ( int index in triangleIndices ) { writer.Write ( index ) ; } } private static void DeserializeMeshes ( BinaryReader reader , SceneGraph scene ) { MeshData [ ] meshes = new MeshData [ scene.meshCount ] ; for ( int i = 0 ; i < scene.meshCount ; i++ ) { meshes [ i ] = new MeshData ( ) ; MeshReadHeader ( reader , meshes [ i ] ) ; MeshReadVertices ( reader , meshes [ i ] ) ; MeshReadUVCoordinate ( reader , meshes [ i ] ) ; MeshReadTriangleIndices ( reader , meshes [ i ] ) ; } scene.meshes = meshes as IEnumerable < MeshData > ; } private static void MeshReadUVCoordinate ( BinaryReader reader , MeshData meshData ) { bool hasUv = reader.ReadBoolean ( ) ; if ( hasUv == false ) { return ; } Vector2 [ ] uvs = new Vector2 [ meshData.vertexCount ] ; for ( int i = 0 ; i < uvs.Length ; i++ ) { uvs [ i ] = new Vector2 ( ) ; uvs [ i ] .x = reader.ReadSingle ( ) ; uvs [ i ] .y = reader.ReadSingle ( ) ; } meshData.uvs = uvs ; } private static void MeshReadHeader ( BinaryReader reader , MeshData meshData ) { meshData.name = reader.ReadString ( ) ; meshData.vertexCount = reader.ReadInt32 ( ) ; meshData.triangleCount = reader.ReadInt32 ( ) ; meshData.materialIndex = reader.ReadInt32 ( ) ; } private static void MeshReadVertices ( BinaryReader reader , MeshData meshData ) { Vector3 [ ] vertices = new Vector3 [ meshData.vertexCount ] ; for ( int i = 0 ; i < vertices.Length ; i++ ) { vertices [ i ] = new Vector3 ( ) ; vertices [ i ] .x = reader.ReadSingle ( ) ; vertices [ i ] .y = reader.ReadSingle ( ) ; vertices [ i ] .z = reader.ReadSingle ( ) ; } meshData.vertices = vertices ; } private static void MeshReadTriangleIndices ( BinaryReader reader , MeshData meshData ) { int [ ] triangleIndices = new int [ meshData.triangleCount ] ; for ( int i = 0 ; i < triangleIndices.Length ; i++ ) { triangleIndices [ i ] = reader.ReadInt32 ( ) ; } meshData.triangles = triangleIndices ; } private static Mesh [ ] CreateMeshes ( SceneGraph scene ) { Mesh [ ] meshes = new Mesh [ scene.meshCount ] ; int index = 0 ; foreach ( MeshData meshData in scene.meshes ) { meshes [ index ] = new Mesh ( ) ; Vector3 [ ] vec = meshData.vertices ; meshes [ index ] .vertices = vec ; meshes [ index ] .triangles = meshData.triangles ; meshes [ index ] .uv = meshData.uvs ; meshes [ index ] .normals = meshData.normals ; meshes [ index ] .RecalculateNormals ( ) ; index++ ; } return meshes ; }",Mirrored mesh and wrong UV map runtime export "C_sharp : I understand the point of `` using '' is to guarantee that the Dispose method of the object will be called . But how should an exception within a `` using '' statement be handled ? If there is an exception , I need to wrap my `` using '' statement in a try catch . For example : Lets say there is an exception created in the creation of the object inside the using parameterOr an Exception within the using scopeIt seems like if I already need to handle an exception with a try catch , that maybe I should just handle the disposing of the object as well . In this case the `` using '' statement does n't seem to help me out at all . How do I properly handle an exception with `` using '' statement ? Is there a better approach to this that I 'm missing ? Could the `` using '' keyword syntax be a little more sugary ... It sure would be nice to have this : try { // Exception in using parameter using ( SqlConnection connection = new SqlConnection ( `` LippertTheLeopard '' ) ) { connection.Open ( ) ; } } catch ( Exception ex ) { } using ( SqlConnection connection = new SqlConnection ( ) ) { try { connection.Open ( ) ; } catch ( Exception ex ) { } } SqlConnection connection2 = null ; try { connection2 = new SqlConnection ( `` z '' ) ; connection2.Open ( ) ; } catch ( Exception ex ) { } finally { IDisposable disp = connection2 as IDisposable ; if ( disp ! = null ) { disp.Dispose ( ) ; } } using ( SqlConnection connection = new SqlConnection ( ) ) { connection.Open ( ) ; } catch ( Exception ex ) { // What went wrong ? Well at least connection is Disposed }",Why does n't 'using ' have a catch block ? "C_sharp : My issue is the following . I have received a WSDL to implement in my .NET 4.7.1 ASP.NET application so another company can call an operation from that WSDL that we implement . They require a few specific settings for the WCF service.SOAP 1.1WS-Security 1.0 WS-Addressing 1.0 ( 2005-08 ) HTTPS ( With x509 certs ) They require that we install a specific certificate and that we can validate their certificate with ours and in turn they will validate ours as well because they have our public key . I believe I should use Custom Binding - > Security - > MutualCertificate for this . I have specified the service and client certificate that should be used . ( Please notice that the WSDL implementation does not require WCF , they say consumers are free to implement it in any language . I chose to use WCF and they have a bit of documentation about it , so I think it should be supported . ) When I import their WSDL directly in SOAP UI , it says it uses SOAP 1.1 . The SOAP 1.1 namespace is visible in the WSDL . When I import my service 's WSDL ( Which in turns implements the interface generated by their WSDL ) , It uses SOAP 1.2 . This is a mismatch and very annoying.I have found this post : https : //stackoverflow.com/a/22255554/3013479 and I tried to remove HttpSoap12 and add HttpSoap . I have set the MessageVersion to Soap11WSAddressing10 so it should use SOAP1.1.. But it does not work.When i use BasicHTTPBinding without any configuration to that binding , it does use SOAP 1.1This is my binding : I believe I need a custom binding because in one of their documents they mention some properties from a custom binding . I am not sure though ! Also , this binding generates an AssymetricBinding and I believe no other default binding does this.Does anyone have any tips ? Do you guys need knowledge of the WSDL ? In theory , I am not able/allowed to adjust the WSDL because then maybe the service cant connect to us anymore . If I do need to adjust the WSDL , please tell me why so I can communicate this with the company . < customBinding > < binding > < textMessageEncoding writeEncoding= '' utf-8 '' messageVersion= '' Soap11WSAddressing10 '' / > < security authenticationMode= '' MutualCertificate '' enableUnsecuredResponse= '' false '' messageProtectionOrder= '' EncryptBeforeSign '' includeTimestamp= '' true '' defaultAlgorithmSuite= '' TripleDesRsa15 '' allowSerializedSigningTokenOnReply= '' false '' messageSecurityVersion= '' WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 '' / > < httpsTransport requireClientCertificate= '' true '' / > < /binding > < /customBinding >",WCF is using SOAP 1.2 even though MessageVersion is Soap11WSAddressing10 "C_sharp : Say I have a C # method like thisHere method creates a thread which access the local variable created in method.By the time it access this variable the method has finished and thus a local variable i should not exist . But the code runs without any trouble . As per my understanding local variable do not exist after the method block finishes.I am not able to get this . public void MyMethod ( ) { int i = 0 ; var thread = new Thread ( ( ) = > { Thread.Sleep ( 100 ) ; if ( i == 0 ) { Console.WriteLine ( `` Value not changed and is { 0 } '' , i ) ; } else { Console.WriteLine ( `` Value changed to { 0 } . `` , i ) ; } } ) ; thread.Start ( ) ; i = 1 ; }",How thread can access local variable even after the method has finished ? "C_sharp : ( Sorry for might be a trivial question , I 'm coming from Java & Maven , and still have n't wrapped my mind around C # dependencies ) I want to use log4net in all my projects . Since I do n't want to add the dll to all the projects , I 've created a `` Globals '' project , add a reference to log4net.dll in it , and referenced from all the other projects to the `` Globals '' project . However , I ca n't seem to access the log4net classes from any other project . Does n't seems to work either . What am I doing wrong ? using Globals.log4net ;",C # solutions : using one `` Globals '' project for external dll 's ? "C_sharp : I am using RavenDB in In-Memory mode for unit testing . My queries are backed by static indexes . I am not using WaitForNonStaleResults ( ) API ( nor do I want to ) .Typical workflow for a test is : Initialise RavenDB in In-Memory modeIntegrate indexes using IndexCreation.CreateIndexes ( Assembly , IDocumentStore ) Insert test data ( for verifying query behaviour ) Run queryVerify query outputI have noticed steps 1-3 happen so quickly , that static indexes do n't have time to get updated before step 4 - therefore the indexes are stale.I have created a quick work-around for this . After step 3 , I execute : This feels cumbersome . What I would like to know is : Is it normal for indexes to be stale when running RavenDB in In-Memory mode ? Is there a better way to avoid stale indexes during testing ? while ( documentStore.DocumentDatabase.Statistics.StaleIndexes.Length ! = 0 ) Thread.Sleep ( 10 ) ;",How should stale indexes be handled during testing ? "C_sharp : I have an old guard class - it constisted or static methods , typical of a utilty class.However , recently I 've started to use NLog - so my guards can now log as well as throw . The thing is with NLog that each calling class ( where the guard resides ) creates its own logger , so instead of a method like this : I have a method with a signature like this : Now all my methods contain the two same parameters relating to the logger , so I 've almost decided that dependency injection would be a better approach , passing the logger into the constructor , and obj into the method.The question I have is based on my inexperience - my new class wo n't be static , but should I leave the methods inside as static ? public static void NotNull < T > ( T obj , string param ) { if ( obj.Equals ( null ) ) throw new ArgumentNullException ( param ) ; } public static void NotNull < T > ( T obj , string param , Logger logger , LogLevel logLevel ) { }","Static methods inside class instance - good , bad or depends ?" "C_sharp : Hard question to phrase , but if I have : in some cases I want to get a Bunny object without any json , because the json string is null , so I do n't care what T is.In this case , can I create an overload or something to ignore T completely , or can I call GetBunny < null > or GetBunny < object > ? I 'm wondering what the correct way to solve this might be . public class BunnyManager { public Bunny < T > GetBunny < T > ( string someJson ) { return new Bunny < T > ( someJson ) ; } } public class Bunny < T > { T parsedJson { get ; set ; } public Bunny < T > ( string someJson ) { if ( ! string.IsNullOrEmpty ( someJson ) ) parsedJson = ConvertJsonStringToObject < T > ( someJson ) ; } }",Is it possible to structure a generic method so T is optional ? "C_sharp : For some reason when I 'm running my ASP.NET Core API using HttpSys on a windows server ( through service fabric ) the routing does n't work whereas locally everything works . The thing is that the middleware works fine , so I know that the request is being processed but it 's never able to hit any controller , it just defaults to my app.run ( `` Some 404 response '' ) 404 middleware . Some of my code : Startup.csProgram.cs : So the setup is almost similar apart from the UrlPrefixes . The fact that I can both through a gateway and on the windows server call https : //somehost/BasePathOfAPI/ and get the message We 're running ! displayed in the browser tells me that the API is up and running but it 's simply not able to hit any of the controllers if I try . One example of a controller : Now , the url I 'm using to try and get to the above controller is : Which returns in a 404 message : not found , however if I locally run : It works fine.Not sure where I 'm going wrong , maybe something with the UrlPrefixes but should I then be able to get to the middleware if that 's incorrect ? Maybe something with the routing , but then why does it work locally ? public void ConfigureServices ( IServiceCollection services ) { # region IOC //ommitted # endregion services.AddAutoMapper ( typeof ( SomeModel ) ) ; services.AddCors ( c = > { c.AddPolicy ( `` AllowOrigin '' , options = > options.AllowAnyOrigin ( ) .AllowAnyHeader ( ) .AllowAnyMethod ( ) ) ; } ) ; services.AddDbContext < SomeContext > ( options = > options.UseSqlServer ( _configuration.GetConnectionString ( `` Dev '' ) ) ) ; services.AddMvc ( ) .AddFluentValidation ( ) ; } public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; IdentityModelEventSource.ShowPII = true ; } //Eliminating that auth is the problem //app.UseAuthentication ( ) ; if ( env.IsProduction ( ) ) { app.UseHsts ( ) ; app.UseHttpsRedirection ( ) ; } app.UseCors ( `` AllowOrigin '' ) ; app.UseMvcWithDefaultRoute ( ) ; //tried this instead of below . No luck //app.UseMvc ( ) ; app.Use ( ( context , next ) = > { if ( context.Request.Path.Value == `` '' || context.Request.Path.Value == `` / '' ) { context.Response.ContentType = `` text/plain '' ; return context.Response.WriteAsync ( `` We 're running ! `` ) ; } return next.Invoke ( ) ; } ) ; app.Run ( context = > { context.Response.StatusCode = 404 ; context.Response.ContentType = `` application/json '' ; return context.Response.WriteAsync ( `` { \ '' message\ '' : \ '' Not found\ '' } '' ) ; } ) ; } } public static void Main ( string [ ] args ) { using ( var scope = host.Services.CreateScope ( ) ) { var services = scope.ServiceProvider ; try { var context = services.GetRequiredService < SomeContext > ( ) ; DbInitializer.Initialize ( context ) ; } catch ( Exception ex ) { logger.Error ( ex , `` An error occured while seeding the database '' ) ; } } host.Run ( ) ; } public static IWebHost CreateWebHostBuilder ( string [ ] args ) { IHostingEnvironment env = null ; var builder = WebHost.CreateDefaultBuilder ( args ) .UseStartup < Startup > ( ) .ConfigureAppConfiguration ( ( hostingContext , config ) = > { env = hostingContext.HostingEnvironment ; } ) .UseHttpSys ( options = > { if ( ! env.IsDevelopment ( ) ) { options.UrlPrefixes.Add ( `` https : //*:30010/BasePathOfAPI/ '' ) ; } else { options.UrlPrefixes.Add ( `` http : //localhost:5000/BasePathOfAPI/ '' ) ; } } ) .ConfigureLogging ( b = > { b.AddApplicationInsights ( `` id here '' ) ; } ) .UseNLog ( ) .Build ( ) ; return builder ; } [ Route ( `` api/ { someNumber : int } /Home '' ) ] [ ApiController ] public class HomeController : ControllerBase { //ctor and props ommitted [ HttpGet ( `` GetSomeData '' ) [ ProducesResponseType ( StatusCodes.200OK ) ] public async Task < IActionResult > GetSomeData ( ) { //implemenetation } } https : //somehost/BasePathOfAPI/api/1234/Home/GetSomeData http : //localhost:5000/BasePathOfAPI/api/1234/Home/GetSomeData",ASP.NET Core ( HttpSys ) Routing works locally but not when deployed "C_sharp : I 'm trying to use await/async in order to make some synchronous code asynchronous . For example , this works and unblocks the UI thread : But this does n't , and will hang the UI thread : I 'm trying to understand why this is the case . I was under the impression that var task = DoRequestAsync ( ) will create a new thread and run everything in the method asynchronously , but that appears to not be the case.I can use this to make it work : But this seems a bit hacky and I 'm not sure if it 's the right solution to this issue . Does anybody know how I can just run a bunch of synchronous code in an asynchronous way using Tasks and async/await ? private async void button1_Click ( object sender , EventArgs e ) { var task = DoRequestAsync ( ) ; textBox1.Text = `` starting async task '' ; var text = await task ; textBox1.Text = text ; } private async Task < string > DoRequestAsync ( ) { try { var client = new HttpClient ( ) ; client.Timeout = new TimeSpan ( 0 , 0 , 0 , 5 ) ; await client.GetAsync ( `` http : //123.123.123.123 '' ) ; // force a timeout exception } catch ( Exception e ) { } return `` done ! `` ; } private async void button1_Click ( object sender , EventArgs e ) { var task = DoRequestAsync ( ) ; textBox1.Text = `` starting async task '' ; var text = await task ; textBox1.Text = text ; } private async Task < string > DoRequestAsync ( ) { try { var request = WebRequest.Create ( `` http : //123.123.123.123 '' ) ; request.Timeout = 5000 ; request.GetResponse ( ) ; // force a timeout exception } catch ( Exception e ) { } return `` done ! `` ; } await Task.Run ( ( ) = > { var request = WebRequest.Create ( `` http : //123.123.123.123 '' ) ; request.Timeout = 5000 ; request.GetResponse ( ) ; } ) ;",How do I use await/async with synchronous code ? "C_sharp : I have a program that uses System.DirectoryServices.AccountManagement.PrincipalContext to verify that the information a user entered in a setup screen is a valid user on the domain ( the computer itself is not on the domain ) and do some operations on the users of the domain . The issue is I do not want the user to need to enter his or her password every time they run the program so I want to save it , but I do not feel comfortable storing the password as plain-text in their app.config file . PrincipalContext needs a plain-text password so I can not do a salted hash as everyone recommends for password storing.This is what I didWas this the right thing to do or is there a better way ? EDIT -- Here is a updated version based on everyone 's suggestions const byte [ ] mySalt = //It 's a secret to everybody . [ global : :System.Configuration.UserScopedSettingAttribute ( ) ] public global : :System.Net.NetworkCredential ServerLogin { get { var tmp = ( ( global : :System.Net.NetworkCredential ) ( this [ `` ServerLogin '' ] ) ) ; if ( tmp ! = null ) tmp.Password = new System.Text.ASCIIEncoding ( ) .GetString ( ProtectedData.Unprotect ( Convert.FromBase64String ( tmp.Password ) , mySalt , DataProtectionScope.CurrentUser ) ) ; return tmp ; } set { var tmp = value ; tmp.Password = Convert.ToBase64String ( ProtectedData.Protect ( new System.Text.ASCIIEncoding ( ) .GetBytes ( tmp.Password ) , mySalt , DataProtectionScope.CurrentUser ) ) ; this [ `` ServerLogin '' ] = value ; } } private MD5 md5 = MD5.Create ( ) ; [ global : :System.Configuration.UserScopedSettingAttribute ( ) ] public global : :System.Net.NetworkCredential ServerLogin { get { var tmp = ( ( global : :System.Net.NetworkCredential ) ( this [ `` ServerLogin '' ] ) ) ; if ( tmp ! = null ) tmp.Password = System.Text.Encoding.UTF8.GetString ( ProtectedData.Unprotect ( Convert.FromBase64String ( tmp.Password ) , md5.ComputeHash ( System.Text.Encoding.UTF8.GetBytes ( tmp.UserName.ToUpper ( ) ) ) , DataProtectionScope.CurrentUser ) ) ; return tmp ; } set { var tmp = value ; tmp.Password = Convert.ToBase64String ( ProtectedData.Protect ( System.Text.Encoding.UTF8.GetBytes ( tmp.Password ) , md5.ComputeHash ( System.Text.Encoding.UTF8.GetBytes ( tmp.UserName.ToUpper ( ) ) ) , DataProtectionScope.CurrentUser ) ) ; this [ `` ServerLogin '' ] = tmp ; } }",What to do when you can not save a password as a hash "C_sharp : I 'm trying to get a count of parents with no children plus parents children . As I write this I realize it is better explained with code.. So , here it goes : With these example types : And this data : I am trying to get a count of 3 back.Thank you in advance for your help.-Jessy HouleADDED AFTER : I was truly impressed with all the great ( and quick ) answers . For others coming to this question , looking for a few options , here is a Unit Test with a few of the working examples from below.Again , thank you all for your help ! public class Customer { public int Id { get ; set ; } public string Name { get ; set ; } public List < Order > Orders { get ; set ; } } public class Order { public int Id { get ; set ; } public string Description { get ; set ; } } var customers = new List < Customer > { new Customer { Id = 2 , Name = `` Jane Doe '' } , new Customer { Id = 1 , Name = `` John Doe '' , Orders = new List < Order > { new Order { Id = 342 , Description = `` Ordered a ball '' } , new Order { Id = 345 , Description = `` Ordered a bat '' } } } } ; // I 'm trying to get a count of customer orders added with customers with no orders// In the above data , I would expect a count of 3 as detailed below//// CId Name OId// -- -- -- -- -- -- -- -- // 2 Jane Doe// 1 John Doe 342// 1 John Doe 345int customerAndOrdersCount = { linq call here } ; // equals 3 [ TestMethod ] public void TestSolutions ( ) { var customers = GetCustomers ( ) ; // data from above var count1 = customers.Select ( customer = > customer.Orders ) .Sum ( orders = > ( orders ! = null ) ? orders.Count ( ) : 1 ) ; var count2 = ( from c in customers from o in ( c.Orders ? ? Enumerable.Empty < Order > ( ) ) .DefaultIfEmpty ( ) select c ) .Count ( ) ; var count3 = customers.Sum ( c = > c.Orders == null ? 1 : c.Orders.Count ( ) ) ; var count4 = customers.Sum ( c = > c.Orders==null ? 1 : Math.Max ( 1 , c.Orders.Count ( ) ) ) ; Assert.AreEqual ( 3 , count1 ) ; Assert.AreEqual ( 3 , count2 ) ; Assert.AreEqual ( 3 , count3 ) ; Assert.AreEqual ( 3 , count4 ) ; }",Count of flattened parent child association in LINQ "C_sharp : I have a table with image as varbinary ( max ) and with another data ( with another types ) which are more compact . I want to update another data but not image . In cycle ( i.e . all records ) with filter to choose records to update . I find various solutions but all of them use fetching the whole record ( s ) into context or attaching existing record ( i.e . fetched or created sometime before ) to context . Saying `` fetched or created sometime before '' I mean the whole record with all fields are presented - not cutted off image or another `` unnecessary '' fields.Is there a way to update records without fetching any unnecessary data ( varbinary image for example ) but through EF ? Maybe just fetching whatever lightweight POCO object without all the fields but only with those I need ? Or this class of tasks lays outside the EF 's assignment and I have to use plain SQL ? Well , just simple example : DB table : EF 's POCOI want to update the description without fetching the whole weed ( especially the image field ) , and for weeds whose names start with `` A '' , for example . create table Weed ( Id int identity ( 1,1 ) not null , Name nvarchar ( 100 ) not null , Description nvarchar ( max ) null , Image varbinary ( max ) null ) public partial class Weed { public Weed ( ) { } public int Id { get ; set ; } public string Name { get ; set ; } public string Description { get ; set ; } public byte [ ] Image { get ; set ; } }",Record with big data field - update without fetching ? C_sharp : Possible Duplicate : What is the “ ? ? ” operator for ? I have recently come across the ? ? operator in C # . What does this operator do and when would someone use it ? Example : string name = nameVariable ? ? string.Empty ;,What does the ? ? operator do ? "C_sharp : I already knew that setting a field is much slower than setting a local variable , but it also appears that setting a field with a local variable is much slower than setting a local variable with a field . Why is this ? In either case the address of the field is used.The benchmark results with 10e+6 iterations are : public class Test { public int A = 0 ; public int B = 4 ; public void Method1 ( ) // Set local with field { int a = A ; for ( int i = 0 ; i < 100 ; i++ ) { a += B ; } A = a ; } public void Method2 ( ) // Set field with local { int b = B ; for ( int i = 0 ; i < 100 ; i++ ) { A += b ; } } } Method1 : 28.1321 msMethod2 : 162.4528 ms",Why is setting a field many times slower than getting a field ? "C_sharp : Consider the following code which attempts to get a DateTime that 's equivalent to the local time `` midnight yesterday '' : Will this always result in a DateTime with a time component of 00:00:00 -- regardless of any corner cases such as leap days , leap seconds , or what the local time zone is ? More generally : Does calling DateTime.AddDays , passing a whole number as a parameter , always result in a DateTime being returned that has the exact same time component as the original Datetime ? The MSDN documentation for DateTime.AddDays does not address this specific question . DateTime midnightYesterday = DateTime.Today.AddDays ( -1.0d ) ;",Does calling DateTime.AddDays with a whole number always leave the time unchanged ? "C_sharp : I 'm working on an IEqualityComparer which is supposed to compare arrays of primitive types really fast . My plan is to obtain pointers to the arrays and memcmp them . Like this : The fixed statement does not allow me to pin either Array or T [ ] .There error messages are : Now , I do n't actually care how I make this work ( I 'm not committed to this exact approach ) . How can I memcmp two T [ ] where I know that T is a primitive/blittable type ? I really want to avoid switching on the type and creating a specialized ( and duplicated ) code version for each interesting type . Any kind of reflection solution is not workable due to performance constraints ( and yes I really need the performance here - no premature optimization warnings apply as it is customary on Stack Overflow ) . public unsafe override bool Equals ( T [ ] x , T [ ] y ) { if ( ReferenceEquals ( x , y ) ) return true ; if ( x == null || y == null ) return false ; if ( x.Length ! = y.Length ) return false ; var xArray = ( Array ) x ; var yArray = ( Array ) y ; fixed ( void* xPtr = xArray ) //compiler error 1 fixed ( T* yPtr = y ) //compiler error 2 { return memcmp ( xPtr , yPtr , x.Length * this.elementSize ) ; } } 1 . Can not implicitly convert type 'System.Array ' to 'void* ' 2 . Can not take the address of , get the size of , or declare a pointer to a managed type ( 'T ' )",How to use fixed with a variable of type Array or T [ ] ? "C_sharp : I 'm using a Command Handler pattern and binding with ninject.extensions.Conventions , which is working great when my actual IQueryHandler < , > interface implementation matches a single concrete type . Here is what I 'm using : But I 've come across a scenario where I need to override the default concrete type at runtime based on a custom route value . The following works without issues : The problem with the above is that I would need to write this code for every single one of my IQueryHandler < , > generic types . In addition , for each decorator I 'd like to apply globally ( like the top sample ) , I would have to modify each binding and add it , doubling or tripling the code.What I 'm hoping to accomplish is use something like the following . I 've implemented a class/interface to return the custom Route data value . This runs , but it throws an exception because at runtime the HttpContext.Current is null . I 'm thinking because it 's not resolving per request at runtime.Is there any way to use `` ToMethod '' or a Factory/Provider mechanism to move the logic for matching the runtime specific value and return the concrete type based on a naming convention ? Or any other ideas to accomplish this ? UPDATE : I 'm using the following pattern for DB access : https : //www.cuttingedge.it/blogs/steven/pivot/entry.php ? id=92So I have an implementation of IQueryHandler < , > for each type of query to my DB.My exact issue is I have different schemas for certain tables across clients , so I have to override the implementation for certain clients based on the Route Config in the url.The other place I 'm interested in using it would be to override a particular query implementation to pull from a different datastore : API or NoSQL.UPDATE 2Final update . So I took the code below and modified to move from naming scheme to Attribute based , as I do n't want each IQueryable to be named `` QueryHandler '' for each different default type.Changed this : To this : And added the following attribute that I 'm using to decorate my IQueryHandlersUsed like this : Then just had to do the same thing for my `` default '' to get by Attribute instead of Name . kernel.Bind ( x = > x .FromThisAssembly ( ) .SelectAllClasses ( ) .InheritedFrom ( typeof ( IQueryHandler < , > ) ) .BindSingleInterface ( ) .Configure ( b = > b.WhenInjectedInto ( typeof ( ValidationHandlerDecorator < , > ) ) .InRequestScope ( ) ) ) ; kernel.Bind ( typeof ( IQueryHandler < , > ) ) .To ( typeof ( PerformanceHandlerDecorator < , > ) ) .InRequestScope ( ) ; kernel.Bind < IQueryHandler < query1 , result1 > > ( ) .ToMethod ( context = > HttpContext.Current.Request.RequestContext.RouteData.Values [ `` type '' ] .ToString ( ) .ToLower ( ) == `` api '' ? ( IQueryHandler < query1 , result1 > ) new apiHandler ( ) : ( IQueryHandler < query1 , result1 > ) new defaultHandler ( ) ) kernel.Bind < IMyContext > ( ) .To < MyContext > ( ) .InRequestScope ( ) ; kernel.Bind ( x = > x.FromThisAssembly ( ) .SelectAllClasses ( ) .InheritedFrom ( typeof ( IQueryHandler < , > ) ) .StartingWith ( kernel.Get < IMyContext > ( ) .customRouteValue ) // this is n't valid ... .BindSingleInterface ( ) .Configure ( b = > b.InRequestScope ( ) ) ) ; IQueryHandler < GetDocInfo , DocInfo > IQueryHandler < GetFileInfo , FileInfo > IQueryHandler < GetOrderInfo , OrderInfo > IQueryHandler < GetMessageInfo , MessageInfo > public class defaultschemaGetMessageQueryHandler : IQueryHandler < GetMessageInfo , MessageInfo > public class client1schemaGetMessageQueryHandler : IQueryHandler < GetMessageInfo , MessageInfo > public class client2schemaGetMessageQueryHandler : IQueryHandler < GetMessageInfo , MessageInfo > string route = serviceType.Name.Substring ( 0 , indexOfSuffix ) ; string route = System.ComponentModel.TypeDescriptor .GetAttributes ( serviceType ) .OfType < QueryImplementation > ( ) .Single ( ) .Id ; [ System.AttributeUsage ( System.AttributeTargets.Class | System.AttributeTargets.Struct ) ] public class QueryImplementation : System.Attribute { public string Id { get { return id ; } } private string id ; public QueryImplementation ( string id ) { this.id = id ; } } [ QueryImplementation ( `` Custom '' ) ] public class CustomDocQueryHandler : IQueryHandler < GetDocInfo , DocInfo >",Ninject Convention Based binding to be resolved at runtime "C_sharp : I 've just replaced this piece of code : with this one : Now the code looks better ( to me ) but I 'm wondering what 's really happening here . I 'm concerned about performance in this case , and it 'd be bad news if applying this filter would mean that some kind of compiler magic would take place.Are the two pieces of code doing basically the 'same ' thing ? Are temporary containers created to do the filtering then passing them to my foreach ? Any help on the subject will be pretty much appreciated . Thanks . foreach ( var source in m_sources ) { if ( ! source.IsExhausted ) { ... . } } foreach ( var source in m_sources.Where ( src = > ! src.IsExhausted ) ) { ... }",What is the LINQ to objects 'where ' clause doing behind the scenes ? "C_sharp : I have some classes that represent database tables , to load the rows of each table on a DataGridView , I 've a List < > function that inside a loop gets all rows from that table.And for other tables , some other functions : list_rows_table2 , list_rows_table3 ... My question is : How do I create a only List < > function , where I can dynamically specify the type of List < > returned , or how to convert , for example a List < object > to List < myClass > before returning . public List < class_Table1 > list_rows_table1 ( ) { // class_Table1 contains each column of table as public property List < class_Table1 > myList = new List < class_Table1 > ( ) ; // sp_List_Rows : stored procedure that lists data // from Table1 with some conditions or filters Connection cnx = new Connection ; Command cmd = new Command ( sp_List_Rows , cnx ) ; cnx.Open ; IDataReader dr = cmd.ExecuteReader ( ) ; while ( dr.Read ( ) ) { class_Table1 ct = new class_Table1 ( ) ; ct.ID = Convert.ToInt32 ( dr [ ID_table1 ] ) ; ct.Name = dr [ name_table1 ] .ToString ( ) ; // ... all others wanted columns follow here myList.Add ( ct ) ; } dr.Close ( ) ; cnx.Close ( ) ; // myList contains all wanted rows ; from a Form fills a dataGridView return myList ( ) ; }",How to dynamically specify type of List < > function ? "C_sharp : I am trying to group a list of DTOs which contain alternate family pairs to group them in the following format to minimize duplication.Here is the DTO structure which I have currently which has duplicate rows as you can see which can be grouped together based on reverse relation also.into something like this : Code which I am trying : Program.csRelationDTO.csRelations.cs + -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -- -- -+| PersonId | RelativeId | Relation |+ -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -- -- -+| 1 | 2 | `` Son '' || 2 | 1 | `` Father '' || 1 | 3 | `` Mother '' || 3 | 1 | `` Son '' || 2 | 3 | `` Husband '' || 3 | 2 | `` Wife '' |+ -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -- -- -+ + -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -+| PersonId | RelativeId | Relation | ReverseRelation |+ -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -+| 1 | 2 | `` Son '' | `` Father '' || 1 | 3 | `` Mother '' | `` Son '' || 2 | 3 | `` Husband '' | `` Wife '' |+ -- -- -- -- -- + -- -- -- -- -- -- + -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -+ class Program { static void Main ( string [ ] args ) { List < RelationDTO > relationDTOList = new List < RelationDTO > { new RelationDTO { PersonId = 1 , RelativeId = 2 , Relation = `` Son '' } , new RelationDTO { PersonId = 2 , RelativeId = 1 , Relation = `` Father '' } , new RelationDTO { PersonId = 1 , RelativeId = 3 , Relation = `` Mother '' } , new RelationDTO { PersonId = 3 , RelativeId = 1 , Relation = `` Son '' } , new RelationDTO { PersonId = 2 , RelativeId = 3 , Relation = `` Husband '' } , new RelationDTO { PersonId = 3 , RelativeId = 2 , Relation = `` Wife '' } , } ; var grp = relationDTOList.GroupBy ( x = > new { x.PersonId } ) .ToList ( ) ; } } public class RelationDTO { public int PersonId { get ; set ; } public int RelativeId { get ; set ; } public string Relation { get ; set ; } } public class Relations { public int PersonId { get ; set ; } public int RelativeId { get ; set ; } public string Relation { get ; set ; } public string ReverseRelation { get ; set ; } }",Group alternate pairs using LINQ "C_sharp : I have the following C # code that does not behave as I would like.The requirement is that anything that implements any IEnumerable < T > uses the second method that prints `` 2 '' , but anything else uses the first method that prints `` 1 '' .A naive demonstration is below . ICollection < int > , IList < int > , List < int > and int [ ] all implement IEnumerable < T > but `` 1 '' is printed instead of `` 2 '' I 've tried changing the definition tobut this requires explicit type parameters to use , which is unacceptable : Has anyone got an ideas on how to achieve this in C # at compile time ? Any ideas are appreciated . Maybe contra/covariant delegates could work ? I 've tried wrangling with the C # compiler but have got nowhere . using System ; using System.Collections.Generic ; using System.Linq.Expressions ; namespace Test { public class Program { public static void Main ( ) { var parent = new Parent < Class > ( ) ; // OK : TProperty == int . Prints `` 1 '' parent.Map ( c = > c.IntValue ) ; // OK : TProperty == int . Prints `` 2 '' parent.Map ( c = > c.IEnumerableIntValue ) ; // Wrong : TProperty == ICollection < int > . Prints `` 1 '' parent.Map ( c = > c.ICollectionIntValue ) ; // Wrong : TProperty == List < int > . Prints `` 1 '' parent.Map ( c = > c.ListIntValue ) ; // Wrong : TProperty == int [ ] . Prints `` 1 '' parent.Map ( c = > c.ArrayIntValue ) ; } public class Class { public int IntValue { get ; set ; } public IEnumerable < int > IEnumerableIntValue { get ; set ; } public ICollection < int > ICollectionIntValue { get ; set ; } public List < int > ListIntValue { get ; set ; } public int [ ] ArrayIntValue { get ; set ; } } } public class Parent < T > { public void Map < TProperty > ( Expression < Func < T , TProperty > > expression ) { Console.WriteLine ( `` 1 '' ) ; } public void Map < TProperty > ( Expression < Func < T , IEnumerable < TProperty > > > expression ) { Console.WriteLine ( `` 2 '' ) ; } } } public void Map < TEnumerable , TElement > ( Expression < Func < T , TEnumerable > > expression ) where TEnumerable : IEnumerable < TElement > { Console.WriteLine ( `` 2 '' ) ; } parent.Map < int [ ] , int > ( c = > c.ArrayIntValue ) ;",Generic type parameter to match anything that is IEnumerable < T > "C_sharp : I want to know what exactly happens inside when we declare a variable , like this : While debugging , I noticed for both values that it was showing null only . But when using ref tr without initializing null it will give error while the second line doesn't.Please help me to know about it in depth string tr ; string tr = null ;",Difference between string str and string str=null "C_sharp : I 'm developing an application which will have these classes : And I will have 20+ more classes , which will derive from Trigger or Action , so in the end , I will have one Shortcut class , 15 Action-derived classes and 5 Trigger-derived classes.My question is , which ORM will best suit this application ? EF , NH , SubSonic , or maybe something else ( Linq2SQL ) ? I will be periodically releasing new application versions , adding more triggers and actions ( or changing current triggers/actions ) , so I will have to update database schema as well . I do n't know if EF or NH provides any good methods to easily update the schema . Or if they do , is there any tutorial how to do that ? I 've already found this article about NH schema updating , quoting : Fortunately NHibernate provides us the possibility to update an existing schema , that is NHibernate creates an update script which can the be applied to the database.I 've never found how to actually generate the update script , so I ca n't tell NH to update the schema . Maybe I 've misread something , I just did n't found it.Note : If you suggest EF , will be EF 1.0 suitable as well ? I would rather use some older .NET than 4.0.Note 2 : The ORM framework should be free for commercial usage.Note 3 : I will also use code obfuscation , randomly renaming all symbols etc ... so to ORM should support this . class Shortcut { public string Name { get ; } public IList < Trigger > Triggers { get ; } public IList < Action > Actions { get ; } } class Trigger { public string Name { get ; } } class Action { public string Name { get ; } }",Which ORM to use ? "C_sharp : I asked a question regarding returning a Disposable ( IDisposable ) object from a function , but I thought that I would muddle the discussion if I raised this question there.I created some sample code : I coded it this way deliberately , because then I call : Using the debugger , I notice that the Dispose method never executes , even though we 've already instantiated a Disposable object . If I correctly understand the purpose of Dispose , if this class actually had opened handles and the like , then we would not close them as soon as we had finished with them.I ask this question because this behavior aligns with what I would expect , but in the answers to the related question , people seemed to indicate that using would take care of everything.If using still somehow takes care of all of this , could someone explain what I 'm missing ? But , if this code could indeed cause resource leak , how would you suggest I code GetDisposable ( with the condition that I must instantiate the IDisposable object and run code which could throw an exception prior to the return statement ) ? class UsingTest { public class Disposable : IDisposable { public void Dispose ( ) { var i = 0 ; i++ ; } } public static Disposable GetDisposable ( bool error ) { var obj = new Disposable ( ) ; if ( error ) throw new Exception ( `` Error ! `` ) ; return obj ; } } using ( var tmp = UsingTest.GetDisposable ( true ) ) { }",I do n't quite understand the workings of using/Disposable objects "C_sharp : I 'm trying to create a geotiff ( elevation DEM data ) file by using Libtiff.Net.The problem is that I have never succeeded to add the following two tags : To add the tag , I wrote the code as follows : According to the description for the `` SetField '' method , the method returns `` true '' if the tag value was set successfully.However , in my case , the method never returns when trying to add the above 2 tags . ( Other tags can be added without any problem . ) I already confirmed that the created geotiff does not contain the geographic information , by using other GIS softwares , such as ArcGIS.Am I missing something or did something wrong ? Any hints or answers will be appreciated ! For your convenience , the code I write so far is the following : TiffTag.GEOTIFF_MODELTIEPOINTTAGTiffTag.GEOTIFF_MODELPIXELSCALETA tiff.SetField ( TiffTag.GEOTIFF_MODELTIEPOINTTAG , 0.0 , 0.0 , 0.0 , leftTopX , leftTopY , 0.0 ) ; tiff.SetField ( TiffTag.GEOTIFF_MODELPIXELSCALETAG , pixelScaleX , pixelScaleY , 0.0 ) ; public void WriteTiff ( ) { using ( var tiff = Tiff.Open ( `` C : \\test\\newCreated.tif '' , `` w '' ) ) { if ( tiff == null ) return ; int width = 100 ; int height = 100 ; int byteDepth = 4 ; int tileSize = 64 ; //Geo info to add double leftTopX = 10000 ; double leftTopY = 15000 ; double pixelScaleX = 1 ; double pixelScaleY = 1 ; //Set the basic tags tiff.SetField ( TiffTag.IMAGEWIDTH , width ) ; tiff.SetField ( TiffTag.IMAGELENGTH , height ) ; tiff.SetField ( TiffTag.SAMPLESPERPIXEL , 1 ) ; tiff.SetField ( TiffTag.BITSPERSAMPLE , 8 * byteDepth ) ; tiff.SetField ( TiffTag.ORIENTATION , Orientation.TOPLEFT ) ; tiff.SetField ( TiffTag.ROWSPERSTRIP , height ) ; tiff.SetField ( TiffTag.XRESOLUTION , 88 ) ; tiff.SetField ( TiffTag.YRESOLUTION , 88 ) ; tiff.SetField ( TiffTag.RESOLUTIONUNIT , ResUnit.INCH ) ; tiff.SetField ( TiffTag.PLANARCONFIG , PlanarConfig.CONTIG ) ; tiff.SetField ( TiffTag.PHOTOMETRIC , Photometric.MINISBLACK ) ; tiff.SetField ( TiffTag.COMPRESSION , Compression.NONE ) ; tiff.SetField ( TiffTag.FILLORDER , FillOrder.MSB2LSB ) ; tiff.SetField ( TiffTag.SOFTWARE , `` MyLib '' ) ; tiff.SetField ( TiffTag.SAMPLEFORMAT , SampleFormat.IEEEFP ) ; //Set the size of the tile tiff.SetField ( TiffTag.TILEWIDTH , tileSize ) ; tiff.SetField ( TiffTag.TILELENGTH , tileSize ) ; //set the geographics info //The following two lines never succeeded ... . tiff.SetField ( TiffTag.GEOTIFF_MODELTIEPOINTTAG , 0.0 , 0.0 , 0.0 , leftTopX , leftTopY , 0.0 ) ; tiff.SetField ( TiffTag.GEOTIFF_MODELPIXELSCALETAG , pixelScaleX , pixelScaleY , 0.0 ) ; //Write the tile data here // ... ... .. // } }","Create Geotiff using `` LibTiff.Net '' , and add geographic information" "C_sharp : It seems to me that some properties of the F # option type are not visible from C # projects . By inspecting the types , I can see more or less the reason , but I do n't really understand what exactly is going on , why these choices have been made or how best to circumvent the issue.Here 's some snippets demonstrating the issue . I have a VS2015 solution containing two projects , a C # project and a F # project . In the F # project , I have a class defined as follows : Furthermore , in F # I can write something like this : So it would appear that the option type has a property named IsNone . Now , in the C # project , I have a reference to the .dll compiled from the F # project . This allows me to write e.g.The variable optionType is an FSharpOption < int > . As I noted above , when I use option types in F # projects , I usually have access to for example the IsSome and IsNone properties . However , when I try to write something like optionType.IsNone , I get the CS1546 error `` Property , indexer or event ... is not supported by the language '' . In concordance with this , Intellisense does not detect the property : Now , when inspecting the FSharpOption type , I can see that the IsNone and IsSome `` properties '' appear as static methods : On the other hand , when I inspect the type from F # , I see the following instead : Here , the `` existence '' of the properties IsSome and IsNone is evident . Hovering the cursor over these properties , VS2015 gives me the following note : `` The containing type can use 'null ' as a representation value for its nullary union case . This member will be compiled as a static member . '' This is the reason why the properties are n't available except as static methods ( as noted by lukegv and Fyodor Soikin ) .So , the situation appears to be the following : The compiled FSharpOption type does not have any IsNone and IsSome properties . Something is going on behind the scenes in F # to enable functionality emulating these properties.I know that I can get around this by using the OptionModule in Microsoft.FSharp.Core . However , it seems that this functionality is a conscious choice by the architects of the F # core library . What are the reasons for the choice ? And is using OptionModule the right solution , or is there a better way to use the FSharpOption < T > type from C # ? type Foo ( ) = member this.Bar ( ) = Some ( 1 ) let option = ( new Foo ( ) ) .Bar ( ) let result = if option.IsNone then `` Is none '' else `` Is some '' var optionType = new Foo ( ) .Bar ( ) ;",Why are some properties ( e.g . IsSome and IsNone ) for FSharpOption not visible from C # ? "C_sharp : I see some colleague code where he chooses to not await the database call and just return the Task . E.g.as _userManager.SaveToDatabaseAsync is async , I would have implemented this wayThe calling method of this method always await it : Is there any benefit to not make the inner method async and just return the Task , letting the caller await it ? I thought we had to write Async all the way down ... public Task < UpdateResult > AddActivityAsync ( ClaimsPrincipal principal , Activity activity ) { return _userManager.SaveToDatabaseAsync ( principal , activity ) ; } public async Task < UpdateResult > AddActivityAsync ( ClaimsPrincipal principal , Activity activity ) { return await _userManager.SaveToDatabaseAsync ( principal , activity ) ; } await _profile.AddActivityAsync ( ... , ... )",Return a Task instead of awaiting the inner method call "C_sharp : Pretty new to dependency injection and I 'm trying to figure out if this is an anti pattern.Let 's say I have 3 assemblies : Foo.Users needs an object that is built within Foo.Payment , and Foo.Payment also needs stuff from Foo.Users . This creates some sort of circular dependency.I have defined an interface in Foo.Shared that proxies the Dependency Injection framework I 'm using ( in this case NInject ) .In the container application , I have an implementation of this interface : The configuration looks like this : This allows me to instantiate a new object of Foo.Payment.SomeType from inside Foo.Users without needing a direct reference : This makes it unclear what the exact dependencies of the UserAccounts class are in this instance , which makes me think it 's not a good practice.How else can I accomplish this ? Any thoughts ? Foo.Shared - this has all the interfacesFoo.Users - references Foo.SharedFoo.Payment - references Foo.Shared public interface IDependencyResolver { T Get < T > ( ) ; } public class DependencyResolver : IDependencyResolver { private readonly IKernel _kernel ; public DependencyResolver ( IKernel kernel ) { _kernel = kernel ; } public T Get < T > ( ) { return _kernel.Get < T > ( ) ; } } public class MyModule : StandardModule { public override void Load ( ) { Bind < IDependencyResolver > ( ) .To < DependencyResolver > ( ) .WithArgument ( `` kernel '' , Kernel ) ; Bind < Foo.Shared.ISomeType > ( ) .To < Foo.Payment.SomeType > ( ) ; // < - binding to different assembly ... } } public class UserAccounts : IUserAccounts { private ISomeType _someType ; public UserAccounts ( IDependencyResolver dependencyResolver ) { _someType = dependencyResolver.Get < ISomeType > ( ) ; // < - this essentially creates a new instance of Foo.Payment.SomeType } }",Injecting the Dependency Injector using Dependency Injection "C_sharp : I have the following C structureI now have a bunch of files created in C with thousands of those structures . I need to read them using C # and speed is an issue.I have done the following in C # And then I read the data from the file usingThis works perfectly and I can retrieve the data just fine from the files.I 've read that I can speedup things if instead of using GCHandle.Alloc/Marshal.PtrToStructure I use C++/CLI or C # unsafe code . I found some examples but they only refer to structures without fixed sized arrays.My question is , for my particular case , is there a faster way of doing things with C++/CLI or C # unsafe code ? EDITAdditional performance info ( I 've used ANTS Performance Profiler 7.4 ) :66 % of my CPU time is used by calls to Marshal.PtrToStructure.Regarding I/O , only 6 out of 105ms are used to read from the file . struct MyStruct { char chArray [ 96 ] ; __int64 offset ; unsigned count ; } [ StructLayout ( LayoutKind.Sequential , CharSet = CharSet.Ansi , Size = 108 ) ] public struct PreIndexStruct { [ MarshalAs ( UnmanagedType.ByValTStr , SizeConst = 96 ) ] public string Key ; public long Offset ; public int Count ; } using ( BinaryReader br = new BinaryReader ( new FileStream ( pathToFile , FileMode.Open , FileAccess.Read , FileShare.Read , bufferSize ) ) ) { long length = br.BaseStream.Length ; long position = 0 ; byte [ ] buff = new byte [ structSize ] ; GCHandle buffHandle = GCHandle.Alloc ( buff , GCHandleType.Pinned ) ; while ( position < length ) { br.Read ( buff , 0 , structSize ) ; PreIndexStruct pis = ( PreIndexStruct ) Marshal.PtrToStructure ( buffHandle.AddrOfPinnedObject ( ) , typeof ( PreIndexStruct ) ) ; structures.Add ( pis ) ; position += structSize ; } buffHandle.Free ( ) ; }",Fast read C structure when it contains char array "C_sharp : I 'm a perl programmer doing a bit of C # . Facing an odd issue with Regex.Replace in regard to the zero-or-more assertion , *.Say I wanted to replace zero or more letters with a single letter . In perl , I could do this : But if I try and do the same in C # , like this : The docs do say `` The * character is not recognized as a metacharacter within a replacement pattern '' Why ? And is there any work around if you want a bit of your regex to slurp up some left over string which may not be there ( like `` .* ? '' on the end ) ( this is a silly example , but you get the point ) my $ s = `` A '' ; $ s =~ s/\w*/B/ ; print $ s ; $ s now = `` B '' string s = Regex.Replace ( `` A '' , @ '' \w* '' , `` B '' ) ; s now = `` BB ''",C # Regex Replace and * "C_sharp : Recently I 've been using git stash many times and I 've been thinking that it is really slow , even on a new repository with a single file . I 've read this question about git stash slowness and this other one and tried every answer to these questions but nothing actually works . For example I 've done the following steps to reproduce it : git inittouch file.txtvim file.txt ( edit the file adding 2 lines ) git add .git commit -m `` Initial commit '' vim file.txt ( edit it again adding 1 line ) time git stashOutput:8 seconds for stashing a single line is so much time . Now a test using libgit2sharp : This code takes 74ms to stash the same change.If Libgit2 is that fast then it should be possible to speed up git stash command . How can I achieve this ? Actually using windows 10 64bit and git 2.11 64bits . Other git commands ( like status , add , commit , etc . ) work fine.UPDATE : I 've updated to git 2.13 and now it 's 14,53s for git stash ... UPDATE 2 : I 've updated to git 2.15 and trying the same test time git stash returns real 0m6,553s . Still really slow ... $ time git stashSaved working directory and index state WIP on master : b9454ed Initial commitHEAD is now at b9454ed Initial commit real 0m8.042suser 0m0.000ssys 0m0.046s static void Main ( string [ ] args ) { Repository repo=new Repository ( @ '' C : \Users\UserTest\TestGitRepo '' ) ; repo.Stashes.Add ( new Signature ( `` test '' , `` test @ test.com '' , new DateTimeOffset ( DateTime.Now ) ) , `` Stash on master '' ) ; }",Git stash on windows extremly slow compared to Libgit2 "C_sharp : I 'm working for a Fortune 100 company and I 'm thrown into being tasked with security moving from SHA1 to SHA-2 . This is not my area of expertise , but as I study cryptography I am questioning the outdated information etc ... SHA-2 is obviously needed over SHA-1 but when the security team KNOWS that the hashing of password + salt is using SHA , with GPU being so ridiculously fast at cracking billions of hashes - I do not get why for passwords i 'm not being told to use bcrypt or another equivalent that is slow , WHY ? I 'm shown a powerpoint slide in which i 'm told to create my salt 60,000 times . I searched all over the internet and I 'm not seeing any such advise or examples . Why ? I 'm using C # I suppose that I 'm not told to create a salt over and over , but to create the hash over and over.Would this logic be appropriate ? How do I make this hashing to work properly ? Update found the powerpoint slideUpdate with Code - Problem with implementation on verification of the hashProblem is when I use the check on the code I 'm trying if ( resultHash.Equals ( hassPassword ) ) and it does not match ... /// NEW Question figured that I would go ahead and create a new question , thanks everyone in advance.Verification of Hashing password is not working string SaltAndPwd = string.Concat ( plainTextPassword , salt ) ; SHA256 sha2 = SHA256Managed.Create ( ) ; byte [ ] buff = sha2.ComputeHash ( Encoding.Unicode.GetBytes ( SaltAndPwd ) ) ; string plainTextPassword = `` aF7Cvs+QzZKM=4 ! `` ; string salt = `` o9kc5FvhWQU== '' ; SHA256 sha2 = SHA256Managed.Create ( ) ; for ( var i = 0 ; i < = 60000 ; i++ ) { byte [ ] buff = sha2.ComputeHash ( Encoding.Unicode.GetBytes ( SaltAndPwd ) ) ; } public string BuildVerify ( ) { string password = `` '' ; string salt = `` '' ; byte [ ] result ; using ( var sha256 = SHA256.Create ( ) ) { password = `` hovercraft '' ; // step 1 : you can use RNGCryptoServiceProvider for something worth using var passwordHashing = new PasswordHashing ( ) ; salt = passwordHashing.CreateRandomSalt ( ) ; // step 2 string hash = Convert.ToBase64String ( sha256.ComputeHash ( Encoding.UTF8.GetBytes ( salt + password ) ) ) ; // step 3 result = sha256.ComputeHash ( Encoding.UTF8.GetBytes ( salt + hash ) ) ; // step 4 for ( int i = 0 ; i < 60000 ; i++ ) { result = sha256.ComputeHash ( Encoding.UTF8.GetBytes ( salt + Convert.ToBase64String ( result ) ) ) ; } } // TESTING VERIFY this works .. string SaltAndPwd = string.Concat ( password , salt ) ; SHA256 sha2 = SHA256Managed.Create ( ) ; byte [ ] buff = sha2.ComputeHash ( Encoding.Unicode.GetBytes ( SaltAndPwd ) ) ; string resultHash = Convert.ToBase64String ( buff ) ; string hassPassword = Convert.ToBase64String ( result ) ; if ( resultHash.Equals ( hassPassword ) ) { // perfect } return `` '' ; } public class PasswordHashing { public string CreateRandomSalt ( ) { string password = `` '' ; password = HashPassword.CreateSalt ( 8 ) + `` = '' ; password = password.Replace ( `` / '' , `` c '' ) ; return password ; } } public static string CreateSalt ( int size ) { RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ( ) ; byte [ ] buff = new byte [ size ] ; rng.GetBytes ( buff ) ; return Convert.ToBase64String ( buff ) ; }","Password Hashing - Why salt 60,000 times" "C_sharp : I 've been digging into IL recently , and I noticed some odd behavior of the C # compiler . The following method is a very simple and verifiable application , it will immediately exit with exit code 1 : When I compile this with Visual Studio Community 2015 , the following IL code is generated ( comments added ) : If I were to handwrite this method , seemingly the same result could be achieved with the following IL : Are there underlying reasons that I 'm not aware of that make this the expected behaviour ? Or is just that the assembled IL object code further optimized down the line , so the C # compiler does not have to worry about optimization ? static int Main ( string [ ] args ) { return 1 ; } .method private hidebysig static int32 Main ( string [ ] args ) cil managed { .entrypoint .maxstack 1 .locals init ( [ 0 ] int32 V_0 ) // Local variable init IL_0000 : nop // Do nothing IL_0001 : ldc.i4.1 // Push ' 1 ' to stack IL_0002 : stloc.0 // Pop stack to local variable 0 IL_0003 : br.s IL_0005 // Jump to next instruction IL_0005 : ldloc.0 // Load local variable 0 onto stack IL_0006 : ret // Return } .method static int32 Main ( ) { .entrypoint ldc.i4.1 // Push ' 1 ' to stack ret // Return }",Why does this very simple C # method produce such illogical CIL code ? "C_sharp : Simplified from this question and got rid of possible affect from LinqPad ( no offsensive ) , a simple console application like this : The `` false '' results from the operator ceq in CIL of the code above ( visit the original question for details ) . So my questions are : ( 1 ) Why == is translating to ceq instead of call Delegate Equals ? Here I do n't care about the ( un ) wrapping between Delegate and Action . At the very last , when evaluating a == b , a is of type Action while b is a Delegate . From the spec : 7.3.4 Binary operator overload resolution An operation of the form x op y , where op is an overloadable binary operator , x is an expression of type X , and y is an expression of type Y , is processed as follows : • The set of candidate user-defined operators provided by X and Y for the operation operator op ( x , y ) is determined . The set consists of the union of the candidate operators provided by X and the candidate operators provided by Y , each determined using the rules of §7.3.5 . If X and Y are the same type , or if X and Y are derived from a common base type , then shared candidate operators only occur in the combined set once . • If the set of candidate user-defined operators is not empty , then this becomes the set of candidate operators for the operation . Otherwise , the predefined binary operator op implementations , including their lifted forms , become the set of candidate operators for the operation . The predefined implementations of a given operator are specified in the description of the operator ( §7.8 through §7.12 ) . • The overload resolution rules of §7.5.3 are applied to the set of candidate operators to select the best operator with respect to the argument list ( x , y ) , and this operator becomes the result of the overload resolution process . If overload resolution fails to select a single best operator , a binding-time error occurs . 7.3.5 Candidate user-defined operators Given a type T and an operation operator op ( A ) , where op is an overloadable operator and A is an argument list , the set of candidate user-defined operators provided by T for operator op ( A ) is determined as follows : • Determine the type T0 . If T is a nullable type , T0 is its underlying type , otherwise T0 is equal to T. • For all operator op declarations in T0 and all lifted forms of such operators , if at least one operator is applicable ( §7.5.3.1 ) with respect to the argument list A , then the set of candidate operators consists of all such applicable operators in T0 . • Otherwise , if T0 is object , the set of candidate operators is empty . • Otherwise , the set of candidate operators provided by T0 is the set of candidate operators provided by the direct base class of T0 , or the effective base class of T0 if T0 is a type parameter.From the spec , a and b have a same base class Delegate , obviously the operator rule == defined in Delegate should be applied here ( the operator == invokes Delegate.Equals essentially ) . But now it looks like the candidate list of user-defined operators is empty and at last Object == is applied . ( 2 ) Should ( Does ) the FCL code obey the C # language spec ? If no , my first question is meaningless because something is specially treated . And then we can answer all of these questions using `` oh , it 's a special treatment in FCL , they can do something we ca n't . The spec is for outside programmers , do n't be silly '' . public class Program { static void M ( ) { } static void Main ( string [ ] args ) { Action a = new Action ( M ) ; Delegate b = new Action ( M ) ; Console.WriteLine ( a == b ) ; //got False here Console.Read ( ) ; } }",Implicit method group conversion gotcha ( Part 2 ) "C_sharp : I 'm executing a Remove ( ) using Entity Framework . When I try to run SaveChanges ( ) , I 'm told that I ca n't insert NULL into a column that does n't allow it . This is strange to me , since I 'm not doing any INSERT , and I checked each of the 30 existing entries to find that it should n't be trying to save the table with null in that column.Here is the code in question : var user = db.AspNetUsers.FirstOrDefault ( u = > u.Id == userId ) ; if ( user ! = null ) { var itemsToRemove = user.ItemXrefs.Where ( i = > ! itemIDs.Contains ( i.ItemID ) ) .ToList ( ) ; foreach ( var xref in itemsToRemove ) { user.ItemXrefs.Remove ( xref ) ; } db.SaveChanges ( ) ; // ... }",Can not INSERT NULL into Column on Remove "C_sharp : Consider the following code example : Using the code : My problem is on the code : The question is : The output should be 15 or 55 ? ! According to the .NET Team : Decision : Made 2017-04-11 : Runs I2.M , which is the unambiguously most specific override at runtime.I 'm not sure here beacuse of the keyword 'new ' on the overridden interface ? what should be the correct behaviour ? In case you need to compile it from source , you can download the source code from : https : //github.com/alugili/Default-Interface-Methods-CSharp-8 public interface IPlayer { int Attack ( int amount ) ; } public interface IPowerPlayer : IPlayer { int IPlayer.Attack ( int amount ) { return amount + 50 ; } } public interface ILimitedPlayer : IPlayer { new int Attack ( int amount ) { return amount + 10 ; } } public class Player : IPowerPlayer , ILimitedPlayer { } IPlayer player = new Player ( ) ; Console.WriteLine ( player.Attack ( 5 ) ) ; // Output 55 , -- > im not sure from this output . I can compile the code but not execute it ! IPowerPlayer powerPlayer = new Player ( ) ; Console.WriteLine ( powerPlayer.Attack ( 5 ) ) ; // Output 55ILimitedPlayer limitedPlayer = new Player ( ) ; Console.WriteLine ( limitedPlayer.Attack ( 5 ) ) ; // Output 15 Console.WriteLine ( player.Attack ( 5 ) ) ; // Output 55",Default Interface Methods in C # 8 "C_sharp : Is there any way of making a composite attribute in C # to provide equivalent metadata at compile time ? E.g , change : To : [ ClassInterface ( ClassInterfaceType.AutoDual ) ] [ ProgId ( `` MyProgId '' ) ] [ MyMefExport ( `` MyProgId '' ) ] public class MyClass { } [ MyCompositeAttribute ( `` MyProgId '' ) ] public class MyClass { }",Composite Attribute "C_sharp : I 'm very new to Swift language , I have a C # Background.and I 'm wondering if there is an equivalent code for C # using statement in swift Language using ( var a = new MyClass ( ) ) { //Code Here }",C # using Statement equivalent in Swift "C_sharp : I am trying to implement my own messaging system for a Unity game . I have a basic version working - a very simplified example of this is as follows : This all works fine . What I would like to do now is implement some `` magic '' to allow the message handler to be called with the actual derived type , like this : This would mean that the message handling code across thousands of scripts will not need to bother casting the Message object to the correct derived type - it will already be of that type . It would be far more convenient . I feel like this could be possible to achieve somehow using generics , delegates , expression trees , covariance and/or contravariance , but I 'm just not getting it ! I 've been trying a lot of different things , and feel like I am getting close , but I just ca n't get there . These are the two partial solutions that I 've been able to come up with : Partial solution 1 works fine , but it uses reflection , which is n't really an option considering the performance - this is a game , and the messaging system will be used a lot . Partial solution 2 works , but only as long as the T generic parameter is available . The messaging system will also have a queue of Message objects that it will process , and T will not be available there.Is there any way to achieve this ? I would greatly appreciate any help that anyone could offer ! One final thing to note is that I am using Unity , which uses Mono - .NET 4 is not an option , and as far as I know this rules out using `` dynamic '' . // Messaging class : private Dictionary < Type , List < Func < Message , bool > > > listeners ; // Set up by some other code.public void AddListener < T > ( Func < Message , bool > listener ) where T : Message { this.listeners [ typeof ( T ) ] .Add ( listener ) ; } public void SendMessage < T > ( T message ) where T : Message { foreach ( Func < Message , bool > listener in this.listeners [ typeof ( T ) ] ) { listener ( message ) ; } } // Some other class : private void Start ( ) { messaging.AddListener < MyMessage > ( this.MessageHandler ) ; // Subscribe to messages of a certain type . } private bool MessageHandler ( Message message ) { // We receive the message as the Message base type ... MyMessage message2 = ( MyMessage ) message ; // ... so we have to cast it to MyMessage . // Handle the message . } private bool MessageHandler ( MyMessage message ) { // Handle the message . } // Messaging class : private Dictionary < Type , List < Delegate > > listeners ; // Delegate instead of Func < Message , bool > .public void AddListener < T > ( Func < T , bool > listener ) where T : Message { // Func < T , bool > instead of Func < Message , bool > . this.listeners [ typeof ( T ) ] .Add ( listener ) ; } public void SendMessage < T > ( T message ) where T : Message { foreach ( Delegate listener in this.listeners [ typeof ( T ) ] ) { listener.Method.Invoke ( method.Target , new object [ ] { message } ) ; // Partial solution 1 . ( ( Func < T , bool > ) listener ) ( message ) ; // Partial solution 2 . } }",How to dynamically invoke delegates with known parameter base type ? "C_sharp : As documented on this MSDN article , vstest.consolecan filter tests to run by traits . For example , a sample vstest.console command might look as follows : Actually , the whole article says that multiple traits will be provided using the following syntax : My issue is when you provide more than a trait , tests are filtered using a logical or and official documentation says nothing about how to filter tests that match all given traits . `` C : \Program Files ( x86 ) \Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe '' `` C : \mytest.dll '' /TestCaseFilter : '' TestCategory=traitA|TestCategory=traitB|traitN '' /logger : trx < Expression > is of the format < property > = < value > [ | < Expression > ] .",Can vstest.console filter tests by all matched traits ? "C_sharp : I have following Json-based configuration file : As serialization framework I use Newtonsoft . To serialize this config into objects I have implemented following classes : In a class I try to serialize a specific configuration section into these class structures using IConfigurationSection.Get ( ) . But when I debug the code , I always get an `` empty '' variable serializedConfiguration which is not null , but all properties are null . If I use or change the naming of the properties in the json file to exactly match the property names in the classes like this : it it works fine . Do you have any idea , why setting PropertyName on JsonProperty does not seem to have any effect ? { `` PostProcessing '' : { `` ValidationHandlerConfiguration '' : { `` MinimumTrustLevel '' : 80 , `` MinimumMatchingTrustLevel '' : 75 } , `` MatchingCharacterRemovals '' : [ `` - '' , `` '' '' , `` : '' ] } , `` Processing '' : { `` OrderSelection '' : { `` SelectionDaysInterval '' : 30 , `` SelectionDaysMaximum '' : 365 } } } [ JsonObject ( MemberSerialization.OptIn ) ] public class RecognitionConfiguration { [ JsonProperty ( PropertyName = `` PostProcessing '' , Required = Required.Always ) ] public PostRecognitionConfiguration PostRecognitionConfiguration { get ; set ; } [ JsonProperty ( PropertyName = `` Processing '' , Required = Required.Always ) ] public ProcessRecognitionConfiguration ProcessRecognitionConfiguration { get ; set ; } } [ JsonObject ( MemberSerialization.OptIn ) ] public class PostRecognitionConfiguration { [ JsonProperty ( Required = Required.Always ) ] public ValidationHandlerConfiguration ValidationHandlerConfiguration { get ; set ; } [ JsonProperty ] public List < string > MatchingCharacterRemovals { get ; set ; } } [ JsonObject ( MemberSerialization.OptIn ) ] public class ProcessRecognitionConfiguration { [ JsonProperty ( PropertyName = `` OrderSelection '' , Required = Required.Always ) ] public OrderSelectionConfiguration OrderSelectionConfiguration { get ; set ; } } var serializedConfiguration = this.ConfigurationSection.Get < RecognitionConfiguration > ( ) ; this.ConfigurationSection.GetSection ( `` Processing '' ) .Get < ProcessRecognitionConfiguration > ( ) { `` ProcessRecognitionConfiguration '' : { `` OrderSelectionConfiguration '' : { `` SelectionDaysInterval '' : 30 , `` SelectionDaysMaximum '' : 365 } } }",Fail to serialize IConfigurationSection from Json "C_sharp : I 've got some timers that measure the time to execute code . It 's allowed ( even better ) if the predicted time changes according to more data ( every loop there is more data so prediction should be more accurate ) . I would like to give user a predicted time of finish ( both time like 15 minutes , and 10:56 ) . DateTime startTimeFunctionTotal = DateTime.Now ; for ( int i = 0 ; i < array.Count ; i++ ) { DateTime startTimeFunction = DateTime.Now ; //some code here DateTime stopTimeFunction = DateTime.Now ; TimeSpan durationTimeFunction = stopTimeFunction - startTimeFunction ; } DateTime stopTimeFunctionTotal = DateTime.Now ; TimeSpan durationTimeFunctionTotal = stopTimeFunctionTotal - startTimeFunctionTotal ;",How to estimate end time of method in WinForms to properly inform user about predicted time of finish ? "C_sharp : I am developing a desktop application in WPF , that contains different types of shapes ( like circle , radius circle , diameter circle ) . Now I need to resize shapes on demand so I used .Net adorner which provides the flexibility to drag and resize the shapes . The exact issue is that I want to resize two elements at same time ( i.e *When I resize the circle , the radius Line should also resize with respect to the radius start and end points ) . Note I have n't tried anything ( I have not done any development yet , so I have not code ) .Updated Trial of your code . This is a Diameter Circle So when I am drag it it will drag only the ellipse public class SimpleCircleAdorner : Adorner { // Be sure to call the base class constructor . public SimpleCircleAdorner ( UIElement adornedElement , Panel ownerPanel ) : base ( adornedElement ) { _ownerPanel = ownerPanel ; } protected override void OnMouseEnter ( MouseEventArgs e ) { Point point = Mouse.GetPosition ( AdornedElement ) ; _currentPosition = getMousePosition ( point ) ; switch ( _currentPosition ) { case MousePosition.BR : case MousePosition.TL : Cursor = Cursors.SizeNWSE ; break ; case MousePosition.BL : case MousePosition.TR : Cursor = Cursors.SizeNESW ; break ; } } protected override void OnMouseLeave ( MouseEventArgs e ) { AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer ( AdornedElement ) ; if ( adornerLayer ! = null ) { Adorner [ ] adorners = adornerLayer.GetAdorners ( AdornedElement ) ; if ( adorners ! = null ) { foreach ( Adorner adorner in adorners ) { adornerLayer.Remove ( adorner ) ; } } } } MousePosition _currentPosition ; Panel _ownerPanel ; bool _isDraging = false ; Point _startPosition ; protected override void OnPreviewMouseLeftButtonDown ( MouseButtonEventArgs e ) { if ( Mouse.Capture ( this ) ) { _isDraging = true ; _startPosition = Mouse.GetPosition ( _ownerPanel ) ; } } protected override void OnPreviewMouseMove ( MouseEventArgs e ) { if ( _isDraging ) { Point newPosition = Mouse.GetPosition ( _ownerPanel ) ; double diffX = ( newPosition.X - _startPosition.X ) ; double diffY = ( newPosition.Y - _startPosition.Y ) ; // we should decide whether to change Width and Height or to change Canvas.Left and Canvas.Right if ( Math.Abs ( diffX ) > = 1 || Math.Abs ( diffY ) > = 1 ) { switch ( _currentPosition ) { case MousePosition.TL : case MousePosition.BL : foreach ( FrameworkElement ui in _ownerPanel.Children ) { if ( ui.GetType ( ) == typeof ( Ellipse ) || ui.GetType ( ) == typeof ( Line ) ) { Canvas.SetLeft ( ui , Math.Max ( 0 , Canvas.GetLeft ( ui ) + diffX ) ) ; ui.Width = Math.Max ( 0 , ui.Width - diffX ) ; } } _ownerPanel.InvalidateArrange ( ) ; break ; case MousePosition.BR : case MousePosition.TR : foreach ( FrameworkElement ui in _ownerPanel.Children ) { if ( ui.GetType ( ) == typeof ( Ellipse ) || ui.GetType ( ) == typeof ( Line ) ) { ui.Width = Math.Max ( 0 , ui.Width + diffX ) ; } } break ; } switch ( _currentPosition ) { case MousePosition.TL : case MousePosition.TR : foreach ( FrameworkElement ui in _ownerPanel.Children ) { if ( ui.GetType ( ) == typeof ( Ellipse ) || ui.GetType ( ) == typeof ( Line ) ) { Canvas.SetTop ( ui , Math.Max ( 0 , Canvas.GetTop ( ui ) + diffY ) ) ; } } foreach ( FrameworkElement ui in _ownerPanel.Children ) { if ( ui.GetType ( ) == typeof ( Ellipse ) || ui.GetType ( ) == typeof ( Line ) ) { ui.Height = Math.Max ( 0 , ui.Height - diffY ) ; } } break ; case MousePosition.BL : case MousePosition.BR : foreach ( FrameworkElement ui in _ownerPanel.Children ) { if ( ui.GetType ( ) == typeof ( Ellipse ) || ui.GetType ( ) == typeof ( Line ) ) { ui.Height = Math.Max ( 0 , ui.Height + diffY ) ; } } break ; } } _startPosition = newPosition ; } } protected override void OnPreviewMouseLeftButtonUp ( MouseButtonEventArgs e ) { } protected override void OnPreviewMouseRightButtonUp ( MouseButtonEventArgs e ) { if ( _isDraging ) { Mouse.Capture ( null ) ; _isDraging = false ; } } MousePosition getMousePosition ( Point point ) // point relative to element { double h2 = ActualHeight / 2 ; double w2 = ActualWidth / 2 ; if ( point.X < w2 & & point.Y < h2 ) return MousePosition.TL ; else if ( point.X > w2 & & point.Y > h2 ) return MousePosition.BR ; else if ( point.X > w2 & & point.Y < h2 ) return MousePosition.TR ; else return MousePosition.BL ; } enum MousePosition { TL , TR , BL , BR } double _renderRadius = 5.0 ; protected override void OnRender ( DrawingContext drawingContext ) { Rect adornedElementRect = new Rect ( this.AdornedElement.DesiredSize ) ; SolidColorBrush renderBrush = new SolidColorBrush ( Colors.Black ) ; renderBrush.Opacity = 0.3 ; Pen renderPen = new Pen ( new SolidColorBrush ( Colors.Black ) , 1.5 ) ; drawingContext.DrawEllipse ( renderBrush , renderPen , adornedElementRect.TopLeft , _renderRadius , _renderRadius ) ; drawingContext.DrawEllipse ( renderBrush , renderPen , adornedElementRect.TopRight , _renderRadius , _renderRadius ) ; drawingContext.DrawEllipse ( renderBrush , renderPen , adornedElementRect.BottomLeft , _renderRadius , _renderRadius ) ; drawingContext.DrawEllipse ( renderBrush , renderPen , adornedElementRect.BottomRight , _renderRadius , _renderRadius ) ; } }",Resize more than one different shape at same time using .net adorner "C_sharp : I 'm writing an add-in for another piece of software through its API . The classes returned by the API can only be access through the native software and the API . So I am writing my own stand alone POCO/DTO objects which map to the API classes . I 'm working on a feature which will read in a native file , and return a collection of these POCO objects which I can stole elsewhere . Currently I 'm using JSON.NET to serialize these classes to JSON if that matters.For example I might have a DTO like this..and a method like this to read the native `` Persons '' into my DTO objectsI have unit tests setup with a test file , however I keep running into unexpected problems when running my export on other files . Sometimes native objects will have unexpected values , or there will be flat out bugs in the API which throw exceptions when there is no reason to.Currently when something `` exceptional '' happens I just log the exception and the export fails . But I 've decided that I 'd rather export what I can , and record the errors somewhere . The easiest option would be to just log and swallow the exceptions and return what I can , however then there would be no way for my calling code to know when there was a problem.One option I 'm considering is returning a dictionary of errors as a separate out parameter . The key would identify the property which could not be read , and the value would contain the details of the exception/error.Alternatively I was also considering just storing the errors in the return object itself . This inflates the size of my object , but has the added benefit of storing the errors directly with my objects . So later if someone 's export generates an error , I do n't have to worry about tracking down the correct log file on their computer.How is this typically handled ? Is there another option for reporting the errors along with the return values that I 'm not considering ? public class MyPersonDTO { public string Name { get ; set ; } public string Age { get ; set ; } public string Address { get ; set ; } } public static class MyDocReader { public static IList < MyPersonDTO > GetPersons ( NativeDocument doc ) { //Code to read Persons from doc and return MyPersonDTOs } } public static class MyDocReader { public static IList < MyPersonDTO > persons GetPersons ( NativeDocument doc , out IDictionary < string , string > errors ) { //Code to read persons from doc } } public class MyPersonDTO { public string Name { get ; set ; } public string Age { get ; set ; } public string Address { get ; set ; } public IDictionary < string , string > Errors { get ; set ; } }",Design pattern for including errors with return values C_sharp : it looks like that I am not able to expose via COM a class to an unmanaged client if one of the property of the class has type DateTime .Example : Only if I comment out the Date property on both the interface and implementation will the .tlh file contain a the Test structure ( obviously without the Date ) .Any idea ? Is there a way to represent a date that is visible via COM ? Do I really need to pass the Date as a string and then parse it ? Thank you for your time ! [ ComVisible ( true ) ] public interface ITest { string Name { get ; } DateTime Date { get ; } } [ Serializable ] [ ComVisible ( true ) ] public class Test : ITest { public string Name { get ; private set ; } public DateTime Date { get ; private set ; } },Is it possible to expose a DateTime field through COM ? "C_sharp : Let 's say I have an XML file such as this : How can I read this file and execute a code snippet depending on the element ? for example , if the `` name '' element says `` level7a '' , execute code snippet X . If the name element says level7B , execute code snippet Y.I can provide such code snippets if t makes answering the question easier . Thanks for the help ! < root > < level1 name= '' level1A '' > < level2 name= '' level2A '' > < level3 name= '' level3A '' > < level4 name= '' level4A '' > < level5 name= '' level5A '' > < level6 name= '' level6A '' > < level7 name= '' level7A '' > < level8 name= '' level8A '' > < /level8 > < /level7 > < /level6 > < /level5 > < /level4 > < /level3 > < /level2 > < /level1 > < level1 name= '' level1B '' > < level2 name= '' level2B '' > < level3 name= '' level3B '' > < level4 name= '' level4B '' > < level5 name= '' level5B '' > < level6 name= '' level6B '' > < level7 name= '' level7B '' > < level8 name= '' level8B '' > < /level8 > < /level7 > < /level6 > < /level5 > < /level4 > < /level3 > < /level2 > < /level1 > < /root >",Reading XML and performing an action depending on the attribute "C_sharp : You may consider this a bug report , however I 'm curious if I am terribly wrong here , or if there is an explanation from Eric or someone else at Microsoft.UpdateThis is now posted as a bug on Microsoft Connect.DescriptionConsider the following class : Here , A.B is a write-only but otherwise fine property.Now , imagine we assign it inside of expression : This code makes C # compiler ( both 3.5.30729.4926 and 4.0.30319.1 ) spit outInternal Compiler Error ( 0xc0000005 at address 013E213F ) : likely culprit is 'BIND'.and crash.However , merely replacing object initializer syntax ( { } ) with a constructor ( ( ) ) compiles just fine.Full code for reproduction : ( And yes , I did hit it working on a real project . ) class A { public object B { set { } } } Expression < Func < A > > expr = ( ) = > new A { B = new object { } } ; using System ; using System.Linq.Expressions ; class Test { public static void Main ( ) { Expression < Func < A > > expr = ( ) = > new A { B = new object { } } ; } } class A { public object B { set { } } }",C # compiler bug ? Object initializer syntax used for write-only property in Expression makes csc crash "C_sharp : I 'm running a timer like this : It will trigger an event every 3rd second . The event is not very heavy I think , it is reading text from a file , comparing text length to the text in a textbox and will replace the text in the box if it has more characters.But how resource heavy is the timer ? And is it a bad idea to read text from a file every 3rd second ( the file is a log file in plain text ) . private void InitializeTimer ( ) { Timer myTimer = new Timer ( ) ; myTimer.Interval = 3000 ; myTimer.Enabled = true ; myTimer.Tick += new EventHandler ( TimerEventProcessor ) ; myTimer.Start ( ) ; }",How resource heavy is a Timer ? "C_sharp : I am writing a component that involves Actions and came upon a requirement to find a way to identify using reflection cases when the Action.Target object is a closure that the compiler have generated . I am doing an experiment to try and find a way , the purpose of this little experiment is to develop a predicate that takes an Action and returns a bool that tells if the action target is an instance of such closure class.In my test case , I have the following methods that create 4 different types of actions : The following table shows the properties of each action : As you see , LambaAction and ClosureAction are quite similar in terms of defnition , they both use lambda , but the closure one has a local function variable that is being used inside the lambda , and therefore the compiler is forced into generating a closure class . Its clear that the second row , the one that presents ClosureAction , is the only one that has a target that is a closure type . The static one does not have a target at all , and the other two use the calling class ( Called ActionReferences ) as target . The next table presents a comparison of the target reflection type properties : So we can see that what 's unique about the closure case is that the target type is not a type info but rather a nested type . It 's also the only one that is private nested , sealed and has a name that contains the string + < > c__DisplayClass . Now while I think that these characteristics are conclusive for any normal usage case , I would prefer to define a predicate that I can rely on . I do n't like to base this mechanism on compilers naming conventions or properties that are not unique because technically , the user may create a private nested sealed class with the same naming convention ... it 's not likely , but it 's not 100 % clean solution.So finally - the question is this : Is there a clean cut way to write a predicate the identifies actions that are actually compiler generated closures ? Thanks private void _createClosure ( int i ) { ClosureAction = new Action ( ( ) = > { var j = i ; var k = somenum ; } ) ; } private void _createLambda ( ) { LambdaAction = new Action ( ( ) = > { this._instanceAction ( ) ; } ) ; } private void _createInstance ( ) { InstanceAction = new Action ( _instanceAction ) ; } private void _createStatic ( ) { StaticAction = new Action ( _staticAction ) ; } private int somenum ; private void _instanceAction ( ) { somenum++ ; } private static void _staticAction ( ) { }",How to identify a lambda closure with reflection "C_sharp : So I 've been playing around with the latest release of the WCF Web API and decided I wanted to dive into implementing Ninject with it.Based off what I 've read I need to implement the interface IResourceFactory which demands the following methods : So I chicken scratched the following out : and wired it up withAmazingly , this seems to work . The first resource method I created to serve out a list of states/provinces generates output with HTTP 200 OK.So , to the question . Is there a cleaner way of writing this factory ? I really fuddled through it and it just does n't feel right . I feel like I 'm missing something obvious staring me in the face . The hack I made in the new Resolve method feels especially dirty so I figured I 'd tap into those more experienced to tighten this up . Has anyone else implemented Ninject with the WCF Web API and implemented a cleaner solution ? Thanks for any input ! public object GetInstance ( System.Type serviceType , System.ServiceModel.InstanceContext instanceContext , System.Net.Http.HttpRequestMessage request ) ; public void ReleaseInstance ( System.ServiceModel.InstanceContext instanceContext , object service ) ; public class NinjectResourceFactory : IResourceFactory { private readonly IKernel _kernel ; public NinjectResourceFactory ( ) { var modules = new INinjectModule [ ] { new ServiceDIModule ( ) , //Service Layer Module new RepositoryDIModule ( ) , //Repo Layer Module new DataServiceDIModule ( ) } ; _kernel = new StandardKernel ( modules ) ; } # region IResourceFactory Members public object GetInstance ( Type serviceType , InstanceContext instanceContext , HttpRequestMessage request ) { return Resolve ( serviceType ) ; } public void ReleaseInstance ( InstanceContext instanceContext , object service ) { throw new NotImplementedException ( ) ; } # endregion private object Resolve ( Type type ) { return _kernel.Get ( type ) ; } //private T Resolve < T > ( ) // { // return _kernel.Get < T > ( ) ; // } //private T Resolve < T > ( string name ) // { // return _kernel.Get < T > ( metaData = > metaData.Has ( name ) ) ; // return _kernel.Get < T > ( ) .Equals ( With.Parameters . // ContextVariable ( `` name '' , name ) ) ; // } } var configuration = HttpHostConfiguration.Create ( ) .SetResourceFactory ( new NinjectResourceFactory ( ) ) ; RouteTable.Routes.MapServiceRoute < StateProvinceResource > ( `` States '' , configuration ) ;",Setting up Ninject with the new WCF Web API "C_sharp : I have a problem in getting some data out from Cassandra using c # and FluentCassandra.In my Cassandra keyspace i have the following super column family definition : What i would like to do is run a query on this supercolumnfamily similar to the following in sql : Following one tutorial i found i can get some data out of Cassandra with the following command : but this is equivalent in sql `` timestamp '' > `` 2011-01-01 00:00:00.000 '' and so far i can not figure out how to retrieve data from a range of values.Any hints or help will be appreciated : ) Thanks in advance , Nicola < ColumnFamily Name= '' MySCFName '' ColumnType= '' Super '' CompareWith= '' TimeUUIDType '' CompareSubcolumnsWith= '' AsciiType '' / > select `` something '' from MyTable where `` timestamp '' between `` 2011-01-01 00:00:00.000 '' and `` 2011-03-01 00:00:00.000 '' family.Get ( `` 238028210009775 '' ) .Fetch ( DateTime.Parse ( `` 2011-01-01 00:00:00.000 '' ) ) .FirstOrDefault ( ) ;",FluentCassandra range selection problem "C_sharp : For example , this is from .NET Framework source file UnsafeNativeMethods.cs : and this is from PInvoke.Net : Which is the correct/best signature for this function ? ( only one of them has [ return : MarshalAs ( UnmanagedType.Bool ) ] , or [ In , Out ] ref , etc . ) I 've noticed that in .NET Framework source files many/most signatures have ExactSpelling=true , CharSet=CharSet.Auto , but on PInvoke they do n't . Is this required ? [ DllImport ( ExternDll.User32 , ExactSpelling=true , CharSet=CharSet.Auto ) ] public static extern bool GetWindowRect ( HandleRef hWnd , [ In , Out ] ref NativeMethods.RECT rect ) ; [ DllImport ( `` user32.dll '' ) ] [ return : MarshalAs ( UnmanagedType.Bool ) ] public static extern bool GetWindowRect ( HandleRef hwnd , out RECT lpRect ) ;","When calling Windows API functions from C # , which source for signatures to trust : .NET Framework source code or PInvoke ?" "C_sharp : In our product , we have things called `` services '' which are the basic means of communication between different parts of the product ( and especially between languages—an in-house language , C , Python and .NET ) .At present , code is like this ( Services.Execute utilising params object [ ] args ) : I 'd rather like to be able to write code like this and get the benefits of type checking and less verbose code : This can be achieved with a simple function , But this is rather verbose , and not quite so easy to manage when doing it for scores of services , as I intend to be doing.Seeing how extern and the DllImportAttribute work , I hope it should be possible to hook this up by some means like this : But I do n't know how to achieve this at all and ca n't seem to find any documentation for it ( extern seems to be a fairly vaguely defined matter ) . The closest I 've found is a somewhat related question , How to provide custom implementation for extern methods in .NET ? which did n't really answer my question and is somewhat different , anyway . The C # Language Specification ( especially , in version 4.0 , section 10.6.7 , External methods ) does n't help.So , I want to provide a custom implementation of external methods ; can this be achieved ? And if so , how ? myString = ( string ) Services.Execute ( `` service_name '' , arg1 , arg2 , ... ) ; myString = ServiceName ( arg1 , arg2 , ... ) ; public static string ServiceName ( int arg1 , Entity arg2 , ... ) { return ( string ) Services.Execute ( `` service_name '' , arg1 , arg2 , ... ) ; } [ ServiceImport ( `` service_name '' ) ] public static extern string ServiceName ( int arg1 , Entity arg2 , ... ) ;",How can I implement my own type of extern ? "C_sharp : This is very odd as I have used the Replace function for thousands of times . This is my code : and this is the variable d 's value when I trace : but it stuck when the value of d is : can anybody tell me why ? Its funny that even dashes are added programatically . while ( d.IndexOf ( `` -- '' ) ! = -1 ) d=d.Replace ( `` -- '' , `` - '' ) ; `` آدنیس , اسم دختر , girl name , آدونیس -- ‌-گلی-به-رنگ-زرد-و-قرمز-که-فقط-هنگام-تابش-خورشید-باز-می-شود '' `` آدنیس , اسم دختر , girl name , آدونیس-‌-گلی-به-رنگ-زرد-و-قرمز-که-فقط-هنگام-تابش-خورشید-باز-می-شود ''",String.Replace not working correctly C_sharp : This question is not about a method I can mark with [ System.Obsolete ] . The method I wan na ignore is in a dll I do n't have control over.I use a 3rd party library which contains an extension method for objects . This leads to confusion and may cause problems in the future . Is there any way to mark this extension method ( or all the extension methods from a certain dll ) as obsolete externally or prevent this extension method appearing in intellisense . The problematic method is : public static class ExtensionMethods { public static bool IsNumeric ( this object obj ) { if ( obj == null ) return false ; return obj.GetType ( ) .IsPrimitive || obj is double || ( obj is Decimal || obj is DateTime ) || obj is TimeSpan ; } },Making extension methods from a third party library obsolete C_sharp : When I update a NuGet package whose reference I 've set to beit removes this line from the project ( csproj ) file.What is the rationale behind this behavior and is there a way to control or work-around this ? < SpecificVersion > False < /SpecificVersion >,Why is the NuGet Package Manager removing SpecificVersion False from the project file "C_sharp : I 'm trying to implement JWT tokens but keep running into the following exception : IDX10640 : Algorithm is not supported : 'http : //www.w3.org/2001/04/xmldsig-more # hmac-sha256 ' when trying to write the token to compact json string.Any ideas on solving this ? Update 1 : The error above occurs with `` System.IdentityModel.Tokens.Jwt '' : `` 5.0.0-beta7-208241120 '' Update 2 : Updated code const string issuer = `` issuer '' ; const string audience = `` audience '' ; byte [ ] keyForHmacSha256 = new byte [ 32 ] ; new Random ( ) .NextBytes ( keyForHmacSha256 ) ; var claims = new List < Claim > { new Claim ( `` deviceId '' , `` 12 '' ) } ; var now = DateTime.UtcNow ; var expires = now.AddHours ( 1 ) ; var signingCredentials = new SigningCredentials ( new SymmetricSecurityKey ( keyForHmacSha256 ) , SecurityAlgorithms.HmacSha256Signature , SecurityAlgorithms.Sha256Digest ) ; var token = new JwtSecurityToken ( issuer , audience , claims , now , expires , signingCredentials ) ; return _tokenHandler.WriteToken ( token ) ;",DNX Core 5.0 JwtSecurityTokenHandler `` IDX10640 : Algorithm is not supported : 'http : //www.w3.org/2001/04/xmldsig-more # hmac-sha256 ' '' "C_sharp : I have SAP RPC OCX control that I 'd like to use.In C # 4 following code works fine : Following code does NOT work ( even though connection is NOT null ) Following error is thrown : '' Attempted to read or write protected memory . This is often an indication that other memory is corrupt . `` The most bizarre fact is this though : Last line is executed and throws the same exception ! ! ! Replace c2 with c1 works as expected ... I feel I am missing something trivial and yet I am at a complete loss ... Please help ? Additional info : Changing from : to : Makes no difference . c1 still works and c2 still does not.Additional info # 2 : Changing properties on FC itself also works in both cases . System.Type t = System.Type.GetTypeFromProgID ( `` SAP.Functions '' , true ) ; dynamic fc = System.Activator.CreateInstance ( t , false ) ; dynamic connection = fc.Connection ; connection.System = `` '' ; System.Type t = System.Type.GetTypeFromProgID ( `` SAP.Functions '' , true ) ; dynamic fc = System.Activator.CreateInstance ( t , false ) ; var connection = fc.Connection as SAPLogonCtrl.Connectionconnection.System = `` '' ; System.Type t = System.Type.GetTypeFromProgID ( `` SAP.Functions '' , true ) ; dynamic fc = System.Activator.CreateInstance ( t , false ) ; dynamic c1 = fc.Connection ; var c2 = fc.Connection as SAPLogonCtrl.Connection ; if ( c1 == c2 ) c2.System = `` '' ; dynamic fc = System.Activator.CreateInstance ( t , false ) ; var fc = System.Activator.CreateInstance ( t , false ) as SAPFunctionsOCX.SAPFunctions ;",Dynamic vs Typed produces strange results "C_sharp : Is it possible to use Moq to mock an unsafe interface ? For example I have ( MCVE ) : However I can not use an unsafe type as a type parameter and I get the error : Is it possible to setup mocks without using a type parameter to avoid this problem ? ( I know the obvious solution is to not use an unsafe interface , I am wondering if there is a solution that does work with unsafe interfaces . ) Edit/Update : it is possible to use a stub class , but I would like to avoid that if it is possible to use Moq as Moq provides considerably less verbose code . [ TestClass ] public class UnitTest1 { [ TestMethod ] public unsafe void TestMethod1 ( ) { Mock < IMyUnsafeInterface > mockDependency = new Mock < IMyUnsafeInterface > ( ) ; mockDependency.Setup ( i = > i.DoWork ( It.IsAny < int* > ( ) ) ) ; // error on this line systemUnderTest.Dependency = mockDependency.Object ; ... } } public unsafe interface IMyUnsafeInterface { void DoWork ( int* intPtr ) ; byte* MethodNotRelevantToThisTest1 ( byte* bytePtr ) ; ComplexObject MethodNotRelevantToThisTest2 ( ) ; ... } Error 1 The type 'int* ' may not be used as a type argument public unsafe class MyUnsafeClass : IMyUnsafeInterface { public void DoWork ( int* intPtr ) { // Do something } public byte* MethodNotRelevantToThisTest1 ( byte* bytePtr ) { throw new NotImplementedException ( ) ; } public ComplexObject MethodNotRelevantToThisTest2 ( ) { throw new NotImplementedException ( ) ; } ... }",Using Moq to mock a unsafe interface "C_sharp : I 'm struggling with some Generic constraint issues when trying to implement a library that allows inheritance and hoping someone can help . I 'm trying to build up a class library that has 3 flavours to it , each building on top of the other . To me it seemed like a perfect opportunity to use Generics as I ca n't quite do what I want through pure inheritance . The code 's below ( this should paste straight into VS ) with some explanation afterwards : The idea behind the code is that there are a set of base classes that expose properties using Generics . This allows me to have strongly typed collections for example.There are then 2 of the 3 stages build upon these , TSP and VRP in the example which have 4 concrete classes ( these are what the developer using the class library should be interacting with as the generic constraints just get a bit crazy ) - Element , Visit , Route and Solution.There are also some classes prefixed Generic for both TSP and VRP . These allow the inheritance that I want as it exposes the Generic Types . If I do n't use these ( say Concrete_VRPRoute inherits Concrete_TSPRoute ) then I have to keep casting the type of item returned by the Visits collection to get the Capacity property for example.I 'm fairly confident all the types line up correctly , but when I try to build I get the following errors and I really do n't know how to tackle them . Error 1 The type ' V ' can not be used as type parameter ' V ' in the generic type or method 'Test.Generic_Route ' . There is no implicit reference conversion from ' V ' to 'Test.Generic_Visit ' . Error 2 The type ' V ' can not be used as type parameter ' V ' in the generic type or method 'Test.Generic_Solution ' . There is no implicit reference conversion from ' V ' to 'Test.Generic_Visit ' . Error 3 The type ' R ' can not be used as type parameter ' R ' in the generic type or method 'Test.Generic_Solution ' . There is no implicit reference conversion from ' R ' to 'Test.Generic_Route ' Error 4 The type ' V ' can not be used as type parameter ' V ' in the generic type or method 'Test.Generic_TSPRoute ' . There is no implicit reference conversion from ' V ' to 'Test.Concrete_TSPVisit ' . Error 5 The type ' V ' can not be used as type parameter ' V ' in the generic type or method 'Test.Generic_TSPSolution ' . There is no implicit reference conversion from ' V ' to 'Test.Concrete_TSPVisit ' . Error 6 The type ' R ' can not be used as type parameter ' R ' in the generic type or method 'Test.Generic_TSPSolution ' . There is no implicit reference conversion from ' R ' to 'Test.Concrete_TSPRoute ' . Error 7 The type 'Test.Concrete_VRPVisit ' can not be used as type parameter ' V ' in the generic type or method 'Test.Generic_TSPSolution ' . There is no implicit reference conversion from 'Test.Concrete_VRPVisit ' to 'Test.Concrete_TSPVisit ' . Error 8 The type 'Test.Concrete_VRPRoute ' can not be used as type parameter ' R ' in the generic type or method 'Test.Generic_TSPSolution ' . There is no implicit reference conversion from 'Test.Concrete_VRPRoute ' to 'Test.Concrete_TSPRoute ' . 'Test.Concrete_TSPRoute ' . using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Test { # region Base Classes public class GenericElement { } /// < summary > Visit to a GenericElement < /summary > public class Generic_Visit < E > where E : GenericElement { public E Element { get ; set ; } } /// < summary > Collection of Visits < /summary > public class Generic_Route < V , E > where V : Generic_Visit < E > where E : GenericElement { public List < V > Visits { get ; set ; } public Double Distance { get ; set ; } } /// < summary > Collection of Routes < /summary > public class Generic_Solution < R , V , E > where R : Generic_Route < V , E > where V : Generic_Visit < E > where E : GenericElement { public List < R > Routes { get ; set ; } public Double Distance { get { return this.Routes.Select ( r = > r.Distance ) .Sum ( ) ; } } } # endregion # region TSP Classes public class Concrete_TSPNode : GenericElement { } public abstract class Generic_TSPVisit < E > : Generic_Visit < E > where E : Concrete_TSPNode { public Double Time { get ; set ; } } public abstract class Generic_TSPRoute < V , E > : Generic_Route < V , E > where V : Concrete_TSPVisit where E : Concrete_TSPNode { public Double Time { get { return this.Visits.Select ( v = > v.Time ) .Sum ( ) ; } } } public abstract class Generic_TSPSolution < R , V , E > : Generic_Solution < R , V , E > where R : Concrete_TSPRoute where V : Concrete_TSPVisit where E : Concrete_TSPNode { public Double Time { get { return this.Routes.Select ( r = > r.Time ) .Sum ( ) ; } } } public class Concrete_TSPVisit : Generic_TSPVisit < Concrete_TSPNode > { } public class Concrete_TSPRoute : Generic_TSPRoute < Concrete_TSPVisit , Concrete_TSPNode > { } public class Concrete_TSPSolution : Generic_TSPSolution < Concrete_TSPRoute , Concrete_TSPVisit , Concrete_TSPNode > { } # endregion # region VRP public class Concrete_VRPNode : Concrete_TSPNode { } public abstract class Generic_VRPVisit < E > : Generic_TSPVisit < E > where E : Concrete_VRPNode { public Double Capacity { get ; set ; } } public abstract class Generic_VRPRoute < V , E > : Generic_TSPRoute < V , E > where V : Concrete_VRPVisit where E : Concrete_VRPNode { public Double Capacity { get { return this.Visits.Select ( v = > v.Capacity ) .Sum ( ) ; } } } public abstract class G_VRPSolution < R , V , E > : Generic_TSPSolution < R , V , E > where R : Concrete_VRPRoute where V : Concrete_VRPVisit where E : Concrete_VRPNode { public Double Capacity { get { return this.Routes.Select ( r = > r.Capacity ) .Sum ( ) ; } } } public class Concrete_VRPVisit : Generic_VRPVisit < Concrete_VRPNode > { } public class Concrete_VRPRoute : Generic_VRPRoute < Concrete_VRPVisit , Concrete_VRPNode > { } public class Concrete_VRPSolution : Generic_TSPSolution < Concrete_VRPRoute , Concrete_VRPVisit , Concrete_VRPNode > { } # endregion }",How to use Inheritance when using Generic Constraints "C_sharp : I have C # strings which contain sentences . Sometimes these sentences are OK , sometimes they are just user generated random characters . What I would like to do is to trim words inside these sentences . For example given the following string : I would like to run this through a filter : And to get an output where every word can contain only up to 6 characters : Any ideas how this could be done with good performance ? Is there anything in .NET which could handle this automatically ? I 'm currently using the following code : Which in theory works , but it provides a bad output if the long word ends with a separator other than space . For example : This is sweeeeeeeeeeeeeeeet ! And something more.Ends up looking like this : This is sweeeeeeee And something more.Update : OK , the comments were so good that I realized that this may have too many `` what ifs '' . Perhaps it would be better if the separators are forgotten . Instead if a word gets trimmed , it could be shown with three dots . Here 's some examples with words trimmed to max 5 characters : Apocalypse now ! - > Apoca ... now ! Apocalypse ! - > Apoca ... ! Example ! - > ! Exam ... This is sweeeeeeeeeeeeeeeet ! And something more . - > This is sweee ... And somet ... more . var stringWithLongWords = `` Here 's a text with tooooooooooooo long words '' ; var trimmed = TrimLongWords ( stringWithLongWords , 6 ) ; `` Here 's a text with tooooo long words '' private static string TrimLongWords ( string original , int maxCount ) { return string.Join ( `` `` , original.Split ( ' ' ) .Select ( x = > x.Substring ( 0 , x.Length > maxCount ? maxCount : x.Length ) ) ) ; }",Trim too long words from sentences in C # ? "C_sharp : I 've been trying to make an IRC client for my Windows Phone 8.1 app , and I was lucky enough to find a really good tutorial . Unfortunately the tutorial was for WP 7 and as of WP 8.1 MS changed it to runtime apps , meaning SocketAsyncEvents is unavailable to me ( even though MSDN says it supports Windows Phone 8.1 ) .Digging around I found that the sockets were moved to Windows.Networking.Sockets , but yet none of them contained SocketAsyncEvents . I 'm pretty much unable to go any further from here , does anybody have an idea on how to convert said function to something that would work with WP 8.1 ? public void SendToServer ( string message ) { var asyncEvent = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint ( server , serverPort ) } ; var buffer = Encoding.UTF8.GetBytes ( message + Environment.NewLine ) ; asyncEvent.SetBuffer ( buffer , 0 , buffer.Length ) ; connection.SendAsync ( asyncEvent ) ; }",Windows Phone 8.1 IRC "C_sharp : Say I have the following models : I run the following in the package-manager : to generate some views and stuff ... but it appears that the scaffolder ignores any complex/non-scalar data types and consequently generates views that are of little use.I am wondering if it is possible to instruct the scaffolder to be a little more intelligent about things . Here 's what I would like to happen : scaffolder creates Editor/Display templates in the shared folderuses EditorFor to leverage these templatesAll the code to make this happen seems to be generated by the scaffolder , but is structured in a way that surprises me , with _CreateOrEdit.cshtml `` templates '' generated in the folder associated with the view . To me , this suggests that the scaffolder generates code that would not be ideally suited to a more recursive way of generating views for models.Are my expectations way off , or am I missing something ? public class Item { public int Id { get ; set ; } public ItemDescription ItemDescription { get ; set ; } } public class ItemDescription { public int Id { get ; set ; } public int Revision { get ; set ; } public string Test { get ; set ; } } Scaffold Controller Item",Scaffolding and Display/EditorTemplates "C_sharp : I 'm writing a small technical analysis library that consists of items that are not availabile in TA-lib . I 've started with an example I found on cTrader and matched it against the code found in the TradingView version.Here 's the Pine Script code from TradingView : Here 's my attempt to implement the indicator : IndicatorBase class and CandleSeries classMath HelpersThe problemThe output values appear to be within the expected range however my Fisher Transform cross-overs do not match up with what I am seeing on TradingView 's version of the indicator.QuestionHow do I properly implement the Fisher Transform indicator in C # ? I 'd like this to match TradingView 's Fisher Transform output.What I KnowI 've check my data against other indicators that I have personally written and indicators from TA-Lib and those indicators pass my unit tests . I 've also checked my data against the TradingView data candle by candle and found that my data matches as expected . So I do n't suspect my data is the issue.SpecificsCSV Data - NFLX 5 min aggPictured below is the above-shown Fisher Transform code applied to a TradingView chart . My goal is to match this output as close as possible.Fisher CyanTrigger MagentaExpected Outputs : Crossover completed at 15:30 ETApprox Fisher Value is 2.86Approx Trigger Value is 1.79Crossover completed at 10:45 ETApprox Fisher Value is -3.67Approx Trigger Value is -3.10My Actual Outputs : Crossover completed at 15:30 ETMy Fisher Value is 1.64My Trigger Value is 1.99Crossover completed at 10:45 ETMy Fisher Value is -1.63My Trigger Value is -2.00BountyTo make your life easier I 'm including a small console applicationcomplete with passing and failing unit tests . All unit tests areconducted against the same data set . The passing unit tests are from atested working Simple Moving Average indicator . The failing unittests are against the Fisher Transform indicator in question.Project Files ( updated 5/14 ) Help get my FisherTransform tests to pass and I 'll award the bounty.Just comment if you need any additional resources or information.Alternative Answers that I 'll considerSubmit your own working FisherTransform in C # Explain why my FisherTransform is actually working as expected len = input ( 9 , minval=1 , title= '' Length '' ) high_ = highest ( hl2 , len ) low_ = lowest ( hl2 , len ) round_ ( val ) = > val > .99 ? .999 : val < -.99 ? -.999 : valvalue = 0.0value : = round_ ( .66 * ( ( hl2 - low_ ) / max ( high_ - low_ , .001 ) - .5 ) + .67 * nz ( value [ 1 ] ) ) fish1 = 0.0fish1 : = .5 * log ( ( 1 + value ) / max ( 1 - value , .001 ) ) + .5 * nz ( fish1 [ 1 ] ) fish2 = fish1 [ 1 ] public class FisherTransform : IndicatorBase { public int Length = 9 ; public decimal [ ] Fish { get ; set ; } public decimal [ ] Trigger { get ; set ; } decimal _maxHigh ; decimal _minLow ; private decimal _value1 ; private decimal _lastValue1 ; public FisherTransform ( IEnumerable < Candle > candles , int length ) : base ( candles ) { Length = length ; RequiredCount = Length ; _lastValue1 = 1 ; } protected override void Initialize ( ) { Fish = new decimal [ Series.Length ] ; Trigger = new decimal [ Series.Length ] ; } public override void Compute ( int startIndex = 0 , int ? endIndex = null ) { if ( endIndex == null ) endIndex = Series.Length ; for ( int index = 0 ; index < endIndex ; index++ ) { if ( index == 1 ) { Fish [ index - 1 ] = 1 ; } _minLow = Series.Average.Lowest ( Length , index ) ; _maxHigh = Series.Average.Highest ( Length , index ) ; _value1 = Maths.Normalize ( 0.66m * ( ( Maths.Divide ( Series.Average [ index ] - _minLow , Math.Max ( _maxHigh - _minLow , 0.001m ) ) - 0.5m ) + 0.67m * _lastValue1 ) ) ; _lastValue1 = _value1 ; Fish [ index ] = 0.5m * Maths.Log ( Maths.Divide ( 1 + _value1 , Math.Max ( 1 - _value1 , .001m ) ) ) + 0.5m * Fish [ index - 1 ] ; Trigger [ index ] = Fish [ index - 1 ] ; } } }",How to correctly calculate Fisher Transform indicator "C_sharp : I 'm currently working on a Rest API using asp.net Web Api ( 5.0.0-rc1 ) . By now we do n't use any DI container , so it 's Poor Man 's DI . But the plan is to use one or another soon.In order to resolve our dependencies we use our own implementation of IHttpControllerActivator similar to how it is described in Mark Seemann 's blog.The problemAll our controllers use services in order to perform their actions . We 're also trying to reuse controllers for different roles . F.e . a controller that lists all users has the HttpGet attributeSo depending on the role in the uri ( could be f.e . admin or department ) we want to resolve the controller 's dependencies differently . This could mean , that we want to wrap a service with a decorator or we need to inject a some kind of strategy ` into the service depending on the role.Note : The conditional resolving of a dependency could be deep down in the dependency graph.The questionSince I 'm quite new to dependency injection I 'm really unsure what 's the standard way to resolve conditional dependencies . Is dependency injection meant to be conditional on a per request base or is the dependency graph rather fixed and we should use factories in this case ? F.e . a controller gets ISomeServiceFactory instead of a ISomeService and the factory itself gets the role injected.I also took a look at Castle Windsor 's Typed Factory Facility , but I 'm not sure if that would solve our problem . [ HttpGet ( `` api/role/ { role } /users '' ) ]",Conditional dependency resolving per request in ASP.NET Web Api 2 "C_sharp : I am working on a logic that decreases the value of an alphanumeric List < char > . For example , A10 becomes A9 , BBA becomes BAZ , 123 becomes 122 . And yes , if the value entered is the last one ( like A or 0 ) , then I should return -An additional overhead is that there is a List < char > variable which is maintained by the user . It has characters which are to be skipped . For example , if the list contains A in it , the value GHB should become GGZ and not GHA.The base of this logic is a very simple usage of decreasing the char but with these conditions , I am finding it very difficult.My project is in Silverlight , the language is C # . Following is my code that I have been trying to do in the 3 methods : I seriously need help for this . Please help me out crack through this . List < char > lstGetDecrName ( List < char > lstVal ) //entry point of the value that returns decreased value { List < char > lstTmp = lstVal ; subCheckEmpty ( ref lstTmp ) ; switch ( lstTmp.Count ) { case 0 : lstTmp.Add ( '- ' ) ; return lstTmp ; case 1 : if ( lstTmp [ 0 ] == '- ' ) { return lstTmp ; } break ; case 2 : if ( lstTmp [ 1 ] == ' 0 ' ) { if ( lstTmp [ 0 ] == ' 1 ' ) { lstTmp.Clear ( ) ; lstTmp.Add ( ' 9 ' ) ; return lstTmp ; } if ( lstTmp [ 0 ] == ' A ' ) { lstTmp.Clear ( ) ; lstTmp.Add ( '- ' ) ; return lstTmp ; } } if ( lstTmp [ 1 ] == ' A ' ) { if ( lstTmp [ 0 ] == ' A ' ) { lstTmp.Clear ( ) ; lstTmp.Add ( ' Z ' ) ; return lstTmp ; } } break ; } return lstGetDecrValue ( lstTmp , lstVal ) ; } List < char > lstGetDecrValue ( List < char > lstTmp , List < char > lstVal ) { List < char > lstValue = new List < char > ( ) ; switch ( lstTmp.Last ( ) ) { case ' A ' : lstValue = lstGetDecrTemp ( ' Z ' , lstTmp , lstVal ) ; break ; case ' a ' : lstValue = lstGetDecrTemp ( ' z ' , lstTmp , lstVal ) ; break ; case ' 0 ' : lstValue = lstGetDecrTemp ( ' 9 ' , lstTmp , lstVal ) ; break ; default : char tmp = ( char ) ( lstTmp.Last ( ) - 1 ) ; lstTmp.RemoveAt ( lstTmp.Count - 1 ) ; lstTmp.Add ( tmp ) ; lstValue = lstTmp ; break ; } return lstValue ; } List < char > lstGetDecrTemp ( char chrTemp , List < char > lstTmp , List < char > lstVal ) //shifting places eg unit to ten , etc . { if ( lstTmp.Count == 1 ) { lstTmp.Clear ( ) ; lstTmp.Add ( '- ' ) ; return lstTmp ; } lstTmp.RemoveAt ( lstTmp.Count - 1 ) ; lstVal = lstGetDecrName ( lstTmp ) ; lstVal.Insert ( lstVal.Count , chrTemp ) ; return lstVal ; }",Logic to decrease character values "C_sharp : See the following code snippet : The above cast will throw an invalid cast exception.Actually , IDictionary < TKey , TValue > also indirectly implements IEnumerable < out T > , because it also implements ICollection < T > . That is , the whole cast should be valid.In fact , for me it is even more strange that if I run the whole cast on a debugger watch slot , it works ! What 's going on ? ( IEnumerable < object > ) new Dictionary < string , string > ( )","Why does upcasting IDictionary < TKey , TValue > to IEnumerable < object > fail ?" "C_sharp : I 'm making my first baby steps with unit testing and have written ( among others ) these two methods : Is the NoException method really needed ? If an exception is going to be thrown it 'll be thrown in the CorrectCount method too.I 'm leaning towards keep it as 2 test cases ( maybe refactor the repeated code as another method ) because a test should only test for a single thing , but maybe my interpretation is wrong . [ TestCase ] public void InsertionSortedSet_AddValues_NoException ( ) { var test = new InsertionSortedSet < int > ( ) ; test.Add ( 5 ) ; test.Add ( 2 ) ; test.Add ( 7 ) ; test.Add ( 4 ) ; test.Add ( 9 ) ; } [ TestCase ] public void InsertionSortedSet_AddValues_CorrectCount ( ) { var test = new InsertionSortedSet < int > ( ) ; test.Add ( 5 ) ; test.Add ( 2 ) ; test.Add ( 7 ) ; test.Add ( 4 ) ; test.Add ( 9 ) ; Assert.IsTrue ( test.Count == 5 ) ; }",Should I test that methods do n't throw exceptions ? "C_sharp : I am trying to parse somewhat standard XML documents that use a schema called MARCXML from various sources.Here are the first few lines of an example XML file that needs to be handled ... and one without namespace prefixes ... Key point : in order to get the XPaths to resolve further along in the program I have to go through a regex routine to add the namespaces to the NameTable ( which does n't add them by default ) . This seems unnecessary to me.The XPath call looks something like this ... XmlNode leaderNode = xmlDoc.SelectSingleNode ( `` .// '' + LeaderNode , nsMgr ) ; Where LeaderNode is a configurable value and would equal `` marc : leader '' in the first example and `` leader '' in the second example . Is there a better , more efficient way to do this ? Note : suggestions for solving this using LINQ are welcome , but I would mainly like to know how to solve this using XmlDocument.EDIT : I took GrayWizardx 's advice and now have the following code ... Now there 's no more dependency on Regex ! < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' no '' ? > < marc : collection xmlns : marc= '' http : //www.loc.gov/MARC21/slim '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //www.loc.gov/MARC21/slim http : //www.loc.gov/standards/marcxml/schema/MARC21slim.xsd '' > < marc : record > < marc : leader > 00925njm 22002777a 4500 < /marc : leader > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' no '' ? > < collection xmlns= '' http : //www.loc.gov/MARC21/slim '' > < record > < leader > 01142cam 2200301 a 4500 < /leader > Regex xmlNamespace = new Regex ( `` xmlns : ( ? < PREFIX > [ ^= ] + ) =\ '' ( ? < URI > [ ^\ '' ] + ) \ '' '' , RegexOptions.Compiled ) ; XmlDocument xmlDoc = new XmlDocument ( ) ; xmlDoc.LoadXml ( xmlRecord ) ; XmlNamespaceManager nsMgr = new XmlNamespaceManager ( xmlDoc.NameTable ) ; MatchCollection namespaces = xmlNamespace.Matches ( xmlRecord ) ; foreach ( Match n in namespaces ) { nsMgr.AddNamespace ( n.Groups [ `` PREFIX '' ] .ToString ( ) , n.Groups [ `` URI '' ] .ToString ( ) ) ; } if ( LeaderNode.Contains ( `` : '' ) ) { string prefix = LeaderNode.Substring ( 0 , LeaderNode.IndexOf ( ' : ' ) ) ; XmlNode root = xmlDoc.FirstChild ; string nameSpace = root.GetNamespaceOfPrefix ( prefix ) ; nsMgr.AddNamespace ( prefix , nameSpace ) ; }",How to correctly parse an XML document with arbitrary namespaces "C_sharp : I have 2 overloaded C # functions like this : Basically one using OleCommand and the other SqlCommand for the return value of the function.But the ugly thing about this is that I have to cast the function pointer to the correct type even though i feel the compiler should be able to resolve it without problems : Is there any way tell the compiler to be smarter so that I do n't have to do the type casting ? Or did I do anything wrong ? EDIT : Added a bounty because I am really interested to learn . Thanks for any advice . private void _Insert ( Hashtable hash , string tablename , Func < string , object [ ] , SqlCommand > command ) private void _Insert ( Hashtable hash , string tablename , Func < string , object [ ] , OleCommand > command ) class RemoteDatabase { public SqlCommand GetCommand ( string query , object [ ] values ) ; } _Insert ( enquiry , `` Enquiry '' , ( Func < string , object [ ] , SqlCommand > ) ( _RemoteDatabase.GetCommand ) ) ;",C # function pointer in overloaded function "C_sharp : I am using System.Net.Http.HttpClient , It is showing some weird errors.Below is my code.Exception-The text associated with this error code could not be found.An error occurred in the secure channel support.My workarounds-hrresult- -2147012739 ( I think this WINNETI_SCHANNEL_ERROR ) below is the stacktrace- at System.Net.Http.HttpClientHandler.d__86.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Net.Http.HttpClient.d__58.MoveNext ( ) Steps I have taken to resolve the issue:1.Turned off Firewall.2.Given all available options in INTERNET OPTIONS ( SSL , TLS etc . ) 3.The link you have provided , I have already checked that.4.Tried Windows.Web.http instead of system.net.http5.Used Handlers and Certificates6.Checked capabilities-Internet ( Client ) , Internet ( Client and server ) , Private Networks ( Even I checked all of the capabilities and tried but same result ) 7.I have created a console application and pasted same codes , Worked like a charm.The only problem is , it is not working in uwp platform and specifically in my system ( It is working in my friend 's system ) .8.Tried all available option available in internet . public async static Task SearchYoutube ( string query , int count ) { try { string format = `` https : //www.googleapis.com/youtube/v3/search ? part=snippet & maxResults=20 & q=mere & key=XXXXXXXXXXXXXXX & pageToken= '' ; HttpClient client = new HttpClient ( ) ; // System.Net.ServicePointManager.EnableDnsRoundRobin = true ; var html = await client.GetStringAsync ( format ) ; string ht = html.ToString ( ) ; } catch ( Exception ex ) { //var resp = ex.Response as HttpWebResponse ; } }",httpclient issue in UWP "C_sharp : I am trying to get list of variants and for each of this variants get all subvariants list irrespective of where subvariants fall forparticular Test say 100.This is sample data : I have 3 subvariants for Variants 1 : I have 3 subvariants for Variants 2 : But notice in my output in am getting all Id as 0 for Variants 2 subvariants list in Variant1 CustomSubvariantList : Data Model : Query : Update : Based on comments this is the sample inputs and expected output : Case 1 : When subvariants name are different in all parent variantsVariants : SubVariants : Test Operation : Expected output : Case 2 : When Subvariants name are same in all parents variants : SubVariants : Expected Output : Id TestId SourceSubVariantId TargetSubVariantId DiffPerc114 100 66 67 100.00115 100 67 68 100.00116 100 70 71 99.99 Id=66 , Name=AbcId=68 , Name=PqrId=69 , Name=xyz Id=70 , Name=lmnId=71 , Name=xxxId=72 , Name=hhh public class Variants { public int Id { get ; set ; } public string Name { get ; set ; } public string Type { get ; set ; } public virtual ICollection < SubVariants > SubVariants { get ; set ; } } public class SubVariants { public int Id { get ; set ; } public int VariantId { get ; set ; } public string Name { get ; set ; } public virtual Variants Variants { get ; set ; } public virtual ICollection < TestOperation > TestOperation { get ; set ; } public virtual ICollection < TestOperation > TestOperation1 { get ; set ; } } public class TestOperation { public int Id { get ; set ; } public Nullable < int > TestId { get ; set ; } public int SourceSubVariantId { get ; set ; } public int TargetSubVariantId { get ; set ; } public decimal DiffPerc { get ; set ; } public virtual SubVariants SubVariants { get ; set ; } public virtual SubVariants SubVariants1 { get ; set ; } public virtual Test Test { get ; set ; } } int testId=100 ; var query = from v in context.Variants where v.Type == `` Add '' select new { ParentVariant = v.Name , Type = v.Method , CustomSubvariantList = ( from svName in context.SubVariants.Select ( sv = > sv.Name ) .Distinct ( ) join x in ( from sv in v.SubVariants from to in sv.TestOperation where to.TestId == testId orderby sv.Id select new { sv.Name , to.DiffPerc , SourceId = ( int ? ) to.SubVariants.Id , TargetID= ( int ? ) to.SubVariants1.Id } ) on svName equals x.Name into g from x in g.DefaultIfEmpty ( ) orderby x.SourceId select new { SourceId=x.SourceId ? ? 0 , TargetId=x.TargetID ? ? 0 , Name = svName , DiffPerc = x.DiffPerc } ) .ToList ( ) } ; Id Name Type CategoryId11 Variant1 Add 112 Variant2 Add 113 Variant3 Add 114 Variant4 Add 1 Id VariantId Name66 11 Abc67 11 PQR68 11 Xyz70 12 lmn71 12 xxx72 12 hhh Id TestId SourceSubVariantId TargetSubVariantId DiffPerc114 100 66 67 10.00115 100 67 68 20.00114 100 70 71 40.00115 100 71 72 50.00 Id VariantId Name66 11 Abc67 11 PQR68 11 Xyz70 12 Abc71 12 PQR72 12 Xyz",Getting inappropriate output with left join "C_sharp : Given an INamedTypeSymbol ( that comes from an referenced assembly , not source ) how can I find all types ( in both source and referenced assemblies ) that inherit from this type ? In my particular case , I 'm looking for all types that inherit from NUnit.Framework.TestAttribute . I can get access to the named type symbol as follows : I 've taken a look at SymbolFinder , Compilation and INamedTypeSymbol but I have n't had any luck.Edit : The FindDerivedClassesAsync method looks close to what I need . ( I 'm not 100 % sure that it finds derived classes in referenced assemblies ) . However it 's internal , so I 've opened an issue . var ws = MSBuildWorkspace.Create ( ) ; var soln = ws.OpenSolutionAsync ( @ '' C : \Users\ ... \SampleInheritanceStuff.sln '' ) .Result ; var proj = soln.Projects.Single ( ) ; var compilation = proj.GetCompilationAsync ( ) .Result ; string TEST_ATTRIBUTE_METADATA_NAME = `` NUnit.Framework.TestAttribute '' ; var testAttributeType = compilation.GetTypeByMetadataName ( TEST_ATTRIBUTE_METADATA_NAME ) ; //Now how do I find types that inherit from this type ?",Find types that inherit from given INamedTypeSymbol "C_sharp : I 've read this : Is it ok to await the same task from multiple threads - is await thread safe ? and I do n't feel clear about the answer , so here 's a specific use case.I have a method that performs some async network I/O . Multiple threads can hit this method at once , and I dont wa n't them all to invoke a network request , If a request is already in progress I want to block/await the 2nd+ threads , and have them all resume once the single IO operation has completed.How should I write the following pseudcode ? I 'm guessing each calling thread really needs to get its own Task , so each can get it 's own continuation , so instead of returning currentTask I should return a new Task which is completed by the `` inner '' Task from DoAsyncNetworkIO.Is there a clean way to do this , or do I have to hand roll it ? static object mutex = new object ( ) ; static Task currentTask ; async Task Fetch ( ) { lock ( mutex ) { if ( currentTask ! = null ) return currentTask ; } currentTask = DoAsyncNetworkIO ( ) ; await currentTask ; lock ( mutex ) { var task = currentTask ; currentTask = null ; return task ; } }",How to have mutliple threads await a single Task ? "C_sharp : I found a great way on how to do periodic work using the async/await pattern over here : https : //stackoverflow.com/a/14297203/899260Now what I 'd like to do is to create an extension method so that I can do Is that possible at all , and if , how would you do it ? EDIT : So far , I refactored the code from the URL above into an extension method , but I do n't know how to proceed from there someInstruction.DoPeriodic ( TimeSpan.FromSeconds ( 5 ) ) ; public static class ExtensionMethods { public static async Task < T > DoPeriodic < T > ( this Task < T > task , CancellationToken token , TimeSpan dueTime , TimeSpan interval ) { // Initial wait time before we begin the periodic loop . if ( dueTime > TimeSpan.Zero ) await Task.Delay ( dueTime , token ) ; // Repeat this loop until cancelled . while ( ! token.IsCancellationRequested ) { // Wait to repeat again . if ( interval > TimeSpan.Zero ) await Task.Delay ( interval , token ) ; } } }",Create an extension method to do periodic work "C_sharp : In my integration tests , I use a TestServer class to work towards a test server instance for my integration tests . In RC1 , I instanciated it using the following code : On RC2 , TestServer.CreateBuilder ( ) was removed . Therefore , I tried to create a new TestServer using the following code : The problem I 'm facing is that after RC2 , the runtime is unable to resolve dependencies for DI , so that it throws exceptions on the Configure method for the Startup class . The system does however start up if I start the actual server ( not the test project ) . The exception thrown is as following : I 'm currently using the following package for the test host : Microsoft.AspNetCore.TestHost '' : `` 1.0.0-rc2-final var server = new TestServer ( TestServer.CreateBuilder ( ) .UseStartup < Startup > ( ) ) ; var server = new TestServer ( new WebHostBuilder ( ) .UseStartup < Startup > ( ) ) ; System.Exception : Could not resolve a service of type 'ShikashiBot.IShikashiBotManager ' for the parameter 'botManager ' of method 'Configure ' on type 'ShikashiBot.Startup ' .",Integration tests broken after migrating to ASP.NET Core RC2 "C_sharp : I 'm trying to understand better how memory works in .NET , so I 'm playing with BenchmarkDotNet and diagnozers . I 've created a benchmark comparing class and struct performance by summing array items . I expected that summing value types will always be quicker . But for short arrays it 's not . Can anyone explain that ? The code : I have three arrays : Which I initialize with the same set of random values.Then a benchmarked method : Size is a benchmark parameter.Two other benchmark methods ( ValueTypeSum and ExtendedValueTypeSum ) are identical , except for I 'm summing on _valueTypeData or _extendedValueTypeData . Full code for the benchmark.Benchmark results : DefaultJob : .NET Framework 4.7.2 ( CLR 4.0.30319.42000 ) , 64bit RyuJIT-v4.7.3190.0Core : .NET Core 2.1.4 ( CoreCLR 4.6.26814.03 , CoreFX 4.6.26814.02 ) , 64bit RyuJITI 've run the benchmark with BranchMispredictions and CacheMisses hardware counters , but there are no cache misses nor branch mispredictions . I 've also checked the release IL code , and benchmark methods differ only by instructions that load reference or value type variables.For bigger array sizes summing value type array is always quicker ( e.g . because value types occupy less memory ) , but I do n't understand why it 's slower for shorter arrays . What do I miss here ? And why making the struct bigger ( see ExtendedValueType ) makes summing a bit faster ? -- -- UPDATE -- -- Inspired by a comment made by @ usr I 've re-run the benchmark with LegacyJit . I 've also added memory diagnoser as inspired by @ Silver Shroud ( yes , there are no heap allocations ) .Job=LegacyJitX64 Jit=LegacyJit Platform=X64Runtime=ClrWith legacy JIT results are as expected - but slower than earlier results ! . Which suggests RyuJit does some magical performance improvements , which do better on reference types. -- -- UPDATE 2 -- -- Thanks for great answers ! I 've learned a lot ! Below results of yet another benchmark . I 'm comparing the originally benchmarked methods , methods optimized , as suggested by @ usr and @ xoofx : and unrolled versions , as suggested by @ AndreyAkinshin , with above optimizations added : Full code here.Benchmark results : BenchmarkDotNet=v0.11.3 , OS=Windows 10.0.17134.345 ( 1803/April2018Update/Redstone4 ) Intel Core i5-6400 CPU 2.70GHz ( Skylake ) , 1 CPU , 4 logical and 4 physical coresFrequency=2648439 Hz , Resolution=377.5809 ns , Timer=TSCDefaultJob : .NET Framework 4.7.2 ( CLR 4.0.30319.42000 ) , 64bit RyuJIT-v4.7.3190.0 internal class ReferenceType { public int Value ; } internal struct ValueType { public int Value ; } internal struct ExtendedValueType { public int Value ; private double _otherData ; // this field is here just to make the object bigger } private ReferenceType [ ] _referenceTypeData ; private ValueType [ ] _valueTypeData ; private ExtendedValueType [ ] _extendedValueTypeData ; [ Benchmark ] public int ReferenceTypeSum ( ) { var sum = 0 ; for ( var i = 0 ; i < Size ; i++ ) { sum += _referenceTypeData [ i ] .Value ; } return sum ; } Method | Size | Mean | Error | StdDev | Ratio | RatioSD | -- -- -- -- -- -- -- -- -- -- - | -- -- - | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- : | -- -- -- -- : | ReferenceTypeSum | 100 | 75.76 ns | 1.2682 ns | 1.1863 ns | 1.00 | 0.00 | ValueTypeSum | 100 | 79.83 ns | 0.3866 ns | 0.3616 ns | 1.05 | 0.02 | ExtendedValueTypeSum | 100 | 78.70 ns | 0.8791 ns | 0.8223 ns | 1.04 | 0.01 | | | | | | | | ReferenceTypeSum | 500 | 354.78 ns | 3.9368 ns | 3.6825 ns | 1.00 | 0.00 | ValueTypeSum | 500 | 367.08 ns | 5.2446 ns | 4.9058 ns | 1.03 | 0.01 | ExtendedValueTypeSum | 500 | 346.18 ns | 2.1114 ns | 1.9750 ns | 0.98 | 0.01 | | | | | | | | ReferenceTypeSum | 1000 | 697.81 ns | 6.8859 ns | 6.1042 ns | 1.00 | 0.00 | ValueTypeSum | 1000 | 720.64 ns | 5.5592 ns | 5.2001 ns | 1.03 | 0.01 | ExtendedValueTypeSum | 1000 | 699.12 ns | 9.6796 ns | 9.0543 ns | 1.00 | 0.02 | Method | Size | Mean | Error | StdDev | Ratio | RatioSD | -- -- -- -- -- -- -- -- -- -- - | -- -- - | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- : | -- -- -- -- : | ReferenceTypeSum | 100 | 76.22 ns | 0.5232 ns | 0.4894 ns | 1.00 | 0.00 | ValueTypeSum | 100 | 80.69 ns | 0.9277 ns | 0.8678 ns | 1.06 | 0.01 | ExtendedValueTypeSum | 100 | 78.88 ns | 1.5693 ns | 1.4679 ns | 1.03 | 0.02 | | | | | | | | ReferenceTypeSum | 500 | 354.30 ns | 2.8682 ns | 2.5426 ns | 1.00 | 0.00 | ValueTypeSum | 500 | 372.72 ns | 4.2829 ns | 4.0063 ns | 1.05 | 0.01 | ExtendedValueTypeSum | 500 | 357.50 ns | 7.0070 ns | 6.5543 ns | 1.01 | 0.02 | | | | | | | | ReferenceTypeSum | 1000 | 696.75 ns | 4.7454 ns | 4.4388 ns | 1.00 | 0.00 | ValueTypeSum | 1000 | 697.95 ns | 2.2462 ns | 2.1011 ns | 1.00 | 0.01 | ExtendedValueTypeSum | 1000 | 687.75 ns | 2.3861 ns | 1.9925 ns | 0.99 | 0.01 | Method | Size | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op | -- -- -- -- -- -- -- -- -- -- - | -- -- - | -- -- -- -- -- - : | -- -- -- -- -- - : | -- -- -- -- -- - : | -- -- -- : | -- -- -- -- : | -- -- -- -- -- -- : | -- -- -- -- -- -- : | -- -- -- -- -- -- : | -- -- -- -- -- -- -- -- -- -- : | ReferenceTypeSum | 100 | 110.1 ns | 0.6836 ns | 0.6060 ns | 1.00 | 0.00 | - | - | - | - | ValueTypeSum | 100 | 109.5 ns | 0.4320 ns | 0.4041 ns | 0.99 | 0.00 | - | - | - | - | ExtendedValueTypeSum | 100 | 109.5 ns | 0.5438 ns | 0.4820 ns | 0.99 | 0.00 | - | - | - | - | | | | | | | | | | | | ReferenceTypeSum | 500 | 517.8 ns | 10.1271 ns | 10.8359 ns | 1.00 | 0.00 | - | - | - | - | ValueTypeSum | 500 | 511.9 ns | 7.8204 ns | 7.3152 ns | 0.99 | 0.03 | - | - | - | - | ExtendedValueTypeSum | 500 | 534.7 ns | 3.0168 ns | 2.8219 ns | 1.03 | 0.02 | - | - | - | - | | | | | | | | | | | | ReferenceTypeSum | 1000 | 1,058.3 ns | 8.8829 ns | 8.3091 ns | 1.00 | 0.00 | - | - | - | - | ValueTypeSum | 1000 | 1,048.4 ns | 8.6803 ns | 8.1196 ns | 0.99 | 0.01 | - | - | - | - | ExtendedValueTypeSum | 1000 | 1,057.5 ns | 5.9456 ns | 5.5615 ns | 1.00 | 0.01 | - | - | - | - | [ Benchmark ] public int ReferenceTypeOptimizedSum ( ) { var sum = 0 ; var array = _referenceTypeData ; for ( var i = 0 ; i < array.Length ; i++ ) { sum += array [ i ] .Value ; } return sum ; } [ Benchmark ] public int ReferenceTypeUnrolledSum ( ) { var sum = 0 ; var array = _referenceTypeData ; for ( var i = 0 ; i < array.Length ; i += 16 ) { sum += array [ i ] .Value ; sum += array [ i + 1 ] .Value ; sum += array [ i + 2 ] .Value ; sum += array [ i + 3 ] .Value ; sum += array [ i + 4 ] .Value ; sum += array [ i + 5 ] .Value ; sum += array [ i + 6 ] .Value ; sum += array [ i + 7 ] .Value ; sum += array [ i + 8 ] .Value ; sum += array [ i + 9 ] .Value ; sum += array [ i + 10 ] .Value ; sum += array [ i + 11 ] .Value ; sum += array [ i + 12 ] .Value ; sum += array [ i + 13 ] .Value ; sum += array [ i + 14 ] .Value ; sum += array [ i + 15 ] .Value ; } return sum ; } Method | Size | Mean | Error | StdDev | Ratio | RatioSD | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | -- -- - | -- -- -- -- - : | -- -- -- -- -- : | -- -- -- -- -- : | -- -- -- : | -- -- -- -- : | ReferenceTypeSum | 512 | 344.8 ns | 3.6473 ns | 3.4117 ns | 1.00 | 0.00 | ValueTypeSum | 512 | 361.2 ns | 3.8004 ns | 3.3690 ns | 1.05 | 0.02 | ExtendedValueTypeSum | 512 | 347.2 ns | 5.9686 ns | 5.5831 ns | 1.01 | 0.02 | ReferenceTypeOptimizedSum | 512 | 254.5 ns | 2.4427 ns | 2.2849 ns | 0.74 | 0.01 | ValueTypeOptimizedSum | 512 | 353.0 ns | 1.9201 ns | 1.7960 ns | 1.02 | 0.01 | ExtendedValueTypeOptimizedSum | 512 | 280.3 ns | 1.2423 ns | 1.0374 ns | 0.81 | 0.01 | ReferenceTypeUnrolledSum | 512 | 213.2 ns | 1.2483 ns | 1.1676 ns | 0.62 | 0.01 | ValueTypeUnrolledSum | 512 | 201.3 ns | 0.6720 ns | 0.6286 ns | 0.58 | 0.01 | ExtendedValueTypeUnrolledSum | 512 | 223.6 ns | 1.0210 ns | 0.9550 ns | 0.65 | 0.01 |",Why is summing an array of value types slower then summing an array of reference types ? "C_sharp : When you create a form or a user control , the WinForms designer generates a dispose method that looks like this : The problem with this code is that it can lead to incorrect behaviour if it is ever edited to dispose of additional objects . I have seen .designer.cs files with dispose methods that look like this : ... which is incorrect , as the disposal of _myDisposable and _myOtherDisposable should not depend on whether or not components is null.So , ignoring the argument about whether or not it is good practice to edit this designer generated code , and ignoring the fact that you can change it by editing the templates , my question is : Why does n't the designer generate code that looks more like this ? This code has the same end result , but is safer and less prone to errors during modification . protected override void Dispose ( bool disposing ) { if ( disposing & & ( components ! = null ) ) { components.Dispose ( ) ; } base.Dispose ( disposing ) ; } protected override void Dispose ( bool disposing ) { if ( disposing & & ( components ! = null ) ) { components.Dispose ( ) ; if ( _myDisposable ! = null ) _myDisposable.Dispose ( ) ; if ( _myOtherDisposable ! = null ) _myOtherDisposable.Dispose ( ) ; } base.Dispose ( disposing ) ; } protected override void Dispose ( bool disposing ) { if ( disposing ) { if ( components ! = null ) components.Dispose ( ) ; } base.Dispose ( disposing ) ; }",Why does the WinForms designer generate somewhat 'inconvenient ' code in its dispose method ? C_sharp : I have created an agent to read windows event using WMI . I ma using the agent from last 3 years to collect events . It is used in a SEIM product . The query looks likeI am able to get the events properly . But Now I want to read apploacker events 'Microsoft-Windows-AppLocker/EXE and DLL ' ( Application and Security Logs - > Microsoft - > Windows - > AppLocker - > Exe And DLL ) .I tried the below query but it returns zero record though I have 40+ records in it . I can see the record in event viewer.I have tried with `` wbemtest '' but no record with no error.I am not sure if this can be achieved by any other way using WMI . I know Powershell has a cmdlet and through which I am able to read 'Microsoft-Windows-AppLocker/EXE and DLL ' events . But I want to read it using WMI.Any pointers will be highly appreciated.Thanks in advance to all viewers . SELECT * FROM Win32_NTLogEvent where LogFile = 'System ' or logFile='Active Directory Web Services ' SELECT * FROM Win32_NTLogEvent where LogFile = 'Microsoft-Windows-AppLocker/EXE and DLL ',WMI query to Read 'Microsoft-Windows-AppLocker/EXE and DLL ' C # "C_sharp : I created a simple Web API app ( empty template from Visual Studio with Web API enabled ) , added a controller : Now we need to support file name extensions ( e.g . file.pdf ) in the path variable , so I modified the web.config : The problem now is that the HTTP status codes are inconsistents , depending on the URL segments provided after the prefix /api/test/ : The 500 error page is displayed in HTML and nothing is logged in the application logs , no exception thrown . I am using VS 2015 , with .NET framework 4.5.1 . [ RoutePrefix ( `` api/test '' ) ] public class TestController : ApiController { [ HttpGet ] [ Route ( @ '' resource/ { *path ? } '' ) ] public async Task < HttpResponseMessage > GetFolder ( string path = `` '' ) { return this.Request.CreateResponse ( HttpStatusCode.OK , new { Status = `` OK '' } ) ; } } < system.webServer > < handlers > < remove name= '' ExtensionlessUrlHandler-Integrated-4.0 '' / > < remove name= '' OPTIONSVerbHandler '' / > < remove name= '' TRACEVerbHandler '' / > < add name= '' ExtensionlessUrlHandler-Integrated-4.0 '' path= '' * . '' verb= '' * '' type= '' System.Web.Handlers.TransferRequestHandler '' preCondition= '' integratedMode , runtimeVersionv4.0 '' / > < ! -- API must handle all file names -- > < add name= '' ApiUrlHandler '' path= '' /api/test/* '' verb= '' GET , POST , PUT , DELETE , OPTIONS '' type= '' System.Web.Handlers.TransferRequestHandler '' preCondition= '' integratedMode , runtimeVersionv4.0 '' / > < /handlers > < /system.webServer > GET /api/test/resource = > HTTP 200 ( as expected ) GET /api/test/resource/foo = > HTTP 200 ( as expected ) GET /api/test/foo = > HTTP 404 ( as expected ) GET /api/test/foo/bar = > HTTP 500 ( expected : 404 )",ASP.NET Web API application returns HTTP 500 for non existant routes with TransferRequestHandler enabled "C_sharp : I 'm trying to set up a program that would create a task schedule in a remote server . The following code works fine for local machine however when I try it with the remote server , it throws up the following error . System.Runtime.InteropServices.COMException : 'The request is not supported . ( Exception from HRESULT : 0x80070032 ) ' I 've already tested the credentials , server name etc and they work just fine with the Remote Desktop Connection . I 'm using the Microsoft.Win32.TaskScheduler namespace . Any help with this is much appreciated . void SetupDailyTask ( ) { using ( TaskService ts = new TaskService ( `` servername.us.xxxxxdomain.com '' , @ '' domainname\username '' , '' domainname '' , '' password '' ) ) { //Task tsk = ts.GetTask ( `` DailyTask '' ) ; //if ( tsk ! = null ) { ts.RootFolder.DeleteTask ( `` DailyTask '' ) ; } //DateTime dt = DateTime.Now ; //TimeSpan tsp = new TimeSpan ( 12 , 44 , 0 ) ; //dt = dt.Date + tsp ; //ts.Execute ( `` notepad.exe '' ) .Once ( ) .Starting ( dt ) .AsTask ( `` DailyTask '' ) ; } }",C # Task Scheduler in Remote Machine "C_sharp : Is there any reason to prefer one of these methods of implementing a global exception handler in a Windows Forms application over the other ? First MethodSecond MethodDoes handling the ThreadException event give you something that the try / catch does n't ? static void Main ( string [ ] args ) { try { System.Windows.Forms.Application.Run ( mainform ) ; } catch ( Exception ex ) { // Log error and display error message } } static void Main ( string [ ] args ) { System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler ( Application_ThreadException ) ; System.Windows.Forms.Application.Run ( mainform ) ; } static void Application_ThreadException ( object sender , ThreadExceptionEventArgs e ) { // Log error and display error message }",Difference between handling Application.ThreadException and wrapping Application.Run in Try / Catch "C_sharp : I am experiencing problem in my application with OutOfMemoryException . My application can search for words within texts . When I start a long running process search to search about 2000 different texts for about 2175 different words the application will terminate at about 50 % through with a OutOfMemoryException ( after about 6 hours of processing ) I have been trying to find the memory leak . I have an object graph like : ( -- > are references ) a static global application object ( controller ) -- > an algorithm starter object -- > text mining starter object -- > text mining algorithm object ( this object performs the searching ) .The text mining starter object will start the text mining algorithm object 's run ( ) -method in a separate thread . To try to fix the issue I have edited the code so that the text mining starter object will split the texts to search into several groups and initialize one text mining algorithm object for each group of texts sequentially ( so when one text mining algorithm object is finished a new will be created to search the next group of texts ) . Here I set the previous text mining algorithm object to null . But this does not solve the issue.When I create a new text mining algorithm object I have to give it some parameters . These are taken from properties of the previous text mining algorithm object before I set that object to null . Will this prevent garbage collection of the text mining algorithm object ? Here is the code for the creation of new text mining algorithm objects by the text mining algorithm starter : Here is the start of the thread that is running the whole search process : Can something here prevent the previous text mining algorithm object from being garbage collected ? private void RunSeveralAlgorithmObjects ( ) { IEnumerable < ILexiconEntry > currentEntries = allLexiconEntries.GetGroup ( intCurrentAlgorithmObject , intNumberOfAlgorithmObjectsToUse ) ; algorithm.LexiconEntries = currentEntries ; algorithm.Run ( ) ; intCurrentAlgorithmObject++ ; for ( int i = 0 ; i < intNumberOfAlgorithmObjectsToUse - 1 ; i++ ) { algorithm = CreateNewAlgorithmObject ( ) ; AddAlgorithmListeners ( ) ; algorithm.Run ( ) ; intCurrentAlgorithmObject++ ; } } private TextMiningAlgorithm CreateNewAlgorithmObject ( ) { TextMiningAlgorithm newAlg = new TextMiningAlgorithm ( ) ; newAlg.SortedTermStruct = algorithm.SortedTermStruct ; newAlg.PreprocessedSynonyms = algorithm.PreprocessedSynonyms ; newAlg.DistanceMeasure = algorithm.DistanceMeasure ; newAlg.HitComparerMethod = algorithm.HitComparerMethod ; newAlg.LexiconEntries = allLexiconEntries.GetGroup ( intCurrentAlgorithmObject , intNumberOfAlgorithmObjectsToUse ) ; newAlg.MaxTermPercentageDeviation = algorithm.MaxTermPercentageDeviation ; newAlg.MaxWordPercentageDeviation = algorithm.MaxWordPercentageDeviation ; newAlg.MinWordsPercentageHit = algorithm.MinWordsPercentageHit ; newAlg.NumberOfThreads = algorithm.NumberOfThreads ; newAlg.PermutationType = algorithm.PermutationType ; newAlg.RemoveStopWords = algorithm.RemoveStopWords ; newAlg.RestrictPartialTextMatches = algorithm.RestrictPartialTextMatches ; newAlg.Soundex = algorithm.Soundex ; newAlg.Stemming = algorithm.Stemming ; newAlg.StopWords = algorithm.StopWords ; newAlg.Synonyms = algorithm.Synonyms ; newAlg.Terms = algorithm.Terms ; newAlg.UseSynonyms = algorithm.UseSynonyms ; algorithm = null ; return newAlg ; } // Run the algorithm in it 's own thread Thread algorithmThread = new Thread ( new ThreadStart ( RunSeveralAlgorithmObjects ) ) ; algorithmThread.Start ( ) ;",Question about Garbage collection C # .NET "C_sharp : In a C # application , I 'd like to determine whether another .NET application is a Console application or not.Can this be done using the reflection APIs ? EDIT : OK , it does n't look like I 'm going to get a good answer to this question because it does n't look like the framework exposes the functionality I want . I dug around in the PE/COFF spec and came up with this : /// < summary > /// Parses the PE header and determines whether the given assembly is a console application./// < /summary > /// < param name= '' assemblyPath '' > The path of the assembly to check. < /param > /// < returns > True if the given assembly is a console application ; false otherwise. < /returns > /// < remarks > The magic numbers in this method are extracted from the PE/COFF file/// format specification available from http : //www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx/// < /remarks > bool AssemblyUsesConsoleSubsystem ( string assemblyPath ) { using ( var s = new FileStream ( assemblyPath , FileMode.Open , FileAccess.Read ) ) { var rawPeSignatureOffset = new byte [ 4 ] ; s.Seek ( 0x3c , SeekOrigin.Begin ) ; s.Read ( rawPeSignatureOffset , 0 , 4 ) ; int peSignatureOffset = rawPeSignatureOffset [ 0 ] ; peSignatureOffset |= rawPeSignatureOffset [ 1 ] < < 8 ; peSignatureOffset |= rawPeSignatureOffset [ 2 ] < < 16 ; peSignatureOffset |= rawPeSignatureOffset [ 3 ] < < 24 ; var coffHeader = new byte [ 24 ] ; s.Seek ( peSignatureOffset , SeekOrigin.Begin ) ; s.Read ( coffHeader , 0 , 24 ) ; byte [ ] signature = { ( byte ) ' P ' , ( byte ) ' E ' , ( byte ) '\0 ' , ( byte ) '\0 ' } ; for ( int index = 0 ; index < 4 ; index++ ) { Assert.That ( coffHeader [ index ] , Is.EqualTo ( signature [ index ] ) , `` Attempted to check a non PE file for the console subsystem ! `` ) ; } var subsystemBytes = new byte [ 2 ] ; s.Seek ( 68 , SeekOrigin.Current ) ; s.Read ( subsystemBytes , 0 , 2 ) ; int subSystem = subsystemBytes [ 0 ] | subsystemBytes [ 1 ] < < 8 ; return subSystem == 3 ; /*IMAGE_SUBSYSTEM_WINDOWS_CUI*/ } }",How can I determine the subsystem used by a given .NET assembly ? "C_sharp : So I have this simple class that updates my labels , and it gets accessed by different threads and reports progress of my application . It works fine however when closing this app this code always throws an error about trying to access something that is disposed . Is this not the proper way to go about this ? Is there something I need to add to make sure it does n't try to perform updates on the UI while the app is closing ? private delegate void SetLabelTextDelegate ( string str1 , string str2 ) ; public void SetLabelText ( string str1 , string str2 ) { if ( this.label1.InvokeRequired || this.label2.InvokeRequired ) { this.Invoke ( new SetLabelTextDelegate ( SetLabelText ) , new object [ ] { str1 , str2 } ) ; return ; } this.label1.Text = ( str1 == string.Empty ) ? this.label1.Text : str1 ; this.label2.Text = ( str2 == string.Empty ) ? this.label2.Text : str2 ; }",Proper Way to Update UI on Different Thread "C_sharp : How can I construct a query against an custom IUserType field in NHibernate ? More specifically : I 'm working on a brownfield application . I have a field in the database called `` State '' which contains a char representing what state a given object is in.In my code I want this to be represented as an enum so I 've created an enum with a value for each state and created an IUserType that converts from the db 's char value to my enum and back for selects & updates.I want to construct a query that looks something like this : However , that query throws an exception : presumably because NHibernate does n't know how to do a select against the DB 's char field given a StateEnum type . session.CreateCriteria < MyType > ( ) .Add ( Expression.Eq ( `` State '' , StateEnum.Complete ) ) could not resolve property : State of : MyNamespace.MyType",Constructing query against IUserType in NHibernate "C_sharp : I have base abstract Goods class and inherited Book class . Should I write title , barCode , price that exist in the Goods class twice ? Can I replace this with less redundant construction ? abstract class Goods { public decimal weight ; string Title , BarCode ; double Price ; public Goods ( string title , string barCode , double price ) { Title = title ; BarCode = barCode ; Price = price ; } } abstract class Book : Goods { protected int NumPages ; public Book ( string title , string barCode , double price , int numPages ) : base ( title , barCode , price ) { NumPages = numPages ; weight = 1 ; } public override void display ( ) { base.display ( ) ; Console.WriteLine ( `` Page Numbers : { 0 } '' , NumPages ) ; } } public Book ( string title , string barCode , double price , int numPages ) : base ( title , barCode , price )",Abstract class fields redundancy C # "C_sharp : Update : This is the query from the debugger , which was retrieved from a string builder : If you remove the curly brackets and post it in Navigator , it works.Original : I have a problem when running my program . The query in sql navigator returns 192 rows but when I run the query on c # ( visual studio 2010 ) the query returns 0 rows.Below is my c # code : This is the query I am using in sql navigator ( which returns 192 rows ) : { SELECT * FROM FCR.V_REPORT WHERE DATE BETWEEN to_date ( '14/09/2001 ' , 'dd/mm/yyyy ' ) AND to_date ( '30/09/2011 ' , 'dd/mm/yyyy ' ) } public static DataTable GetReport ( string date1 , string date2 ) { DatabaseAdapter dba = DatabaseAdapter.GetInstance ( ) ; string SqlQuery = string.Format ( @ '' SELECT * FROM FCR.V_REPORT WHERE DATE BETWEEN to_date ( ' { 0 } ' , 'dd/mm/yyyy ' ) AND to_date ( ' { 1 } ' , 'dd/mm/yyyy ' ) '' , date1 , date2 ) ; OracleDataReader reader = dba.QueryDatabase ( SqlQuery ) ; DataTable dt = new DataTable ( ) ; dt.Load ( reader ) ; int temp = dt.Rows.Count ; return dt ; } SELECT * FROM FCR.V_REPORTWHERE DATE BETWEEN to_date ( '01/01/2001 ' , 'dd/mm/yyyy ' ) AND to_date ( '30/09/2011 ' , 'dd/mm/yyyy ' )","Query problem - rows are returned when query is run in sql navigator , but not in my c # program" "C_sharp : This code throws an exception System.InvalidOperationException : The entity type 'List < .. > ' was not found . Ensure that the entity type has been added to the model.However , if you add the type constraint where T : class no exception is thrown . Why is this ? I was under the impression C # type constraints did n't affect run time behavior like this . Both versions compile fine . private static void Update < T > ( DbContext context , ICollection < T > existing , ICollection < T > updated ) // where T : class { context.RemoveRange ( existing ) ; updated.ToList ( ) .ForEach ( existing.Add ) ; }",Entity Framework Core DbContext.RemoveRange and type constraints "C_sharp : I do have a list a Culture and a list of Translation : The current code IActionResult return : But i expect to add the Null values for the missing translation : { `` en-US '' , `` fr-FR '' , `` it-IT '' , `` es-ES '' } Can it be done with only Linq ? Or maybe i should do a loop in the dictionary et repopulate the vales ? public class Translation { public string key { get ; set ; } public string value { get ; set ; } public string cultureId { get ; set ; } } public async Task < IActionResult > ReactGetResources ( string module = `` shared '' ) { string [ ] Languages = { `` en-US '' , `` fr-FR '' , `` it-IT '' , `` es-ES '' } ; List < Translation > Translation = new List < Translation > ( ) ; Translation.Add ( new Translation { key = `` hello '' , value = `` Hello '' , cultureId = `` en-US '' } ) ; Translation.Add ( new Translation { key = `` hello '' , value = `` Bonjour '' , cultureId = `` fr-FR '' } ) ; Translation.Add ( new Translation { key = `` hello '' , value = `` Buongiorno '' , cultureId = `` it-IT '' } ) ; Translation.Add ( new Translation { key = `` goodbye '' , value = `` Good Bye '' , cultureId = `` en-US '' } ) ; Translation.Add ( new Translation { key = `` goodbye '' , value = `` Au revoir '' , cultureId = `` fr-FR '' } ) ; Translation.Add ( new Translation { key = `` goodbye '' , value = `` adiós '' , cultureId = `` es-ES '' } ) ; Dictionary < string , List < string > > query = Translation .OrderBy ( o = > o.cultureId ) .GroupBy ( o = > o.key ) .ToDictionary ( g = > g.Key , g = > g.Select ( x = > x.value ) .ToList ( ) ) ; return Json ( query ) ; } { `` hello '' : [ `` Hello '' , //en `` Bonjour '' , //fr `` Buongiorno '' //it ] , `` goodbye '' : [ `` Good Bye '' , //en `` Au revoir '' , //fr `` Adiós '' , //es ] } { `` hello '' : [ `` Hello '' , //en `` Bonjour '' , //en `` Buongiorno '' , //it null //es ] , `` goodbye '' : [ `` Good Bye '' , //en `` Au revoir '' , //fr null , //it `` Adiós '' //es ] }","Linq to Dictionary < string , List < string > > with Null values" "C_sharp : I have an object with two objects as properties ( User , PrimaryNode ) , both could potentially be null , see below : I 'm using Entity Framework 6 to populate the Item object and using chained includes to populate the PrimaryNode and User objects within it.When the first chained Include has a null object then the whole object returns as null , for example : If in the above example i.User is null then the item variable is null . Whats the best way of populating both the sub-objects in a way that if a sub-object is null then the parent object and the other sub-object will still be populated ? public class Item { [ Key ] public int ItemId { get ; set ; } public string ItemName { get ; set ; } public Node PrimaryNode { get ; set ; } public User User { get ; set ; } } using ( var db = new MyContext ( ) ) { var item = db.Items.Include ( i = > i.User ) .Include ( n = > n.PrimaryNode ) .FirstOrDefault ( i = > i.ItemId == id ) ; }",Entity Framework ObjectQuery.Include ( ) "C_sharp : Hello guys i am trying to create my own Task-Like types using the AsyncMethodBuilderAttribute for the .NetCore framework.So far in .Net Core my custom Type works and it can be awaited and i can return it as async [ MyTypeName ] < T > MyMethod ( ) instead of Task .However in .NetStandard 2.0 the attribute is not present and and i tried to implement it : I decorated my awaitable type with the attribute but it still does not let me use it : `` The return type of an async method must be void , Task , Task < T > '' So far i can use something like this in .Net Core and it works ! ! Attribute : Below are the implementation of the custom type and the async method builder.The awaiter is not important in this case but i can provide the source if needed . My Task-Like TypeThe custom AsyncMethodBuilder implementation : What else should i add for it to work in .Net Standard ? public async Task WrapperMethod ( ) { int result=await GetIntAsync ( ) ; } public async Errand < int > GetIntAsync ( ) { await Task.Delay ( 1000 ) ; return 3 ; } [ AttributeUsage ( AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate , Inherited = false , AllowMultiple = false ) ] public sealed class AsyncMethodBuilderAttribute : Attribute { // // Parameters : // builderType : public AsyncMethodBuilderAttribute ( Type builderType ) { this.BuilderType = builderType ; } // public Type BuilderType { get ; } } [ AsyncMethodBuilder ( typeof ( Builder ) ) ] public partial class Errand { private readonly Builder mbuilder ; public Errand ( ) { } internal Errand ( Builder methodBuilder ) = > this.mbuilder = methodBuilder ; private readonly HashSet < Awaiter > awaiters = new HashSet < Awaiter > ( ) ; protected bool isCompleted = false ; public Awaiter GetAwaiter ( ) { Awaiter result = new Awaiter ( this ) ; this.awaiters.Add ( result ) ; return result ; } } public partial class Builder { # region `` Compiler integration `` public static Builder Create ( ) { return new Builder ( ) ; } protected IAsyncStateMachine myStateMachine ; public void Start < TStateMachine > ( ref TStateMachine stateMachine ) where TStateMachine : IAsyncStateMachine { this.myStateMachine = stateMachine ; this.errand = new Errand ( this ) ; stateMachine.MoveNext ( ) ; } public void SetException ( Exception ex ) { } public void AwaitOnCompleted < TAwaiter , TStateMachine > ( ref TAwaiter awaiter , ref TStateMachine machine ) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { var foo = machine as IAsyncStateMachine ; awaiter.OnCompleted ( ( ) = > { foo.MoveNext ( ) ; } ) ; } public void AwaitUnsafeOnCompleted < TAwaiter , TStateMachine > ( ref TAwaiter awaiter , ref TStateMachine machine ) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { IAsyncStateMachine asyncMachine = machine as IAsyncStateMachine ; awaiter.OnCompleted ( ( ) = > asyncMachine.MoveNext ( ) ) ; } private Errand errand ; public Errand Task { get { return this.errand ; } } public void SetStateMachine ( IAsyncStateMachine stateMachine ) { } public void SetResult ( ) { } # endregion // internal void AddAwaiter ( Awaiter awaiter ) = > this.awaiters.Add ( awaiter ) ; }",Implementing async return Types on .NET Standard "C_sharp : I have an third party library that has the following API : What I want to do is call this method but using anonymous objects such as : Is it possible to take the second anonymous object and convert it to something like : So what I want is to convert the new { Id = id } to a function that takes TReport and returns bool ? Update < TReport > ( object updateOnly , Expression < Func < TReport , bool > > where ) Update ( new { Name = `` test '' } , new { Id = id } ) x = > x.Id == id .",Convert anonymous object to expression delegate "C_sharp : I 'm trying to improve the performance of my IoC container . We are using Unity and SimpleInjector and we have a class with this constructor : I also have another class with this constructor : I 'm seeing that the second one gets resolved in 1 millisecond , most of the time , whereas the first one takes on average 50-60 milliseconds . I 'm sure the reasoning for the slower one is because of the parameters , it has more parameters . But how can I improve the performance of this slower one ? Is it the fact that we are using Func < T > as parameters ? What can I change if it is causing the slowness ? public AuditFacade ( IIocContainer container , Func < IAuditManager > auditManagerFactory , Func < ValidatorFactory > validatorCreatorFactory , IUserContext userContext , Func < ITenantManager > tenantManagerFactory , Func < IMonitoringComponent > monitoringComponentFactory ) : base ( container , auditManagerFactory , GlobalContext.CurrentTenant , validatorCreatorFactory , userContext , tenantManagerFactory ) { _monitoringComponent = new Lazy < IMonitoringComponent > ( monitoringComponentFactory ) ; } public AuditTenantComponent ( Func < IAuditTenantRepository > auditTenantRepository ) { _auditTenantRepository = new Lazy < IAuditTenantRepository > ( auditTenantRepository ) ; }",Are Func < T > parameters in constructor slowing down my IoC resolving ? "C_sharp : What would be a better approach for an xml-based repository:1 ) Save changes to the underlying xml document on each call to the repository ... or2 ) Provide the end-user with a SaveChanges ( ) method ... My inclination leans towards option 1 , because providing a SaveChanges ( ) method does n't really seem like a repositories responsibility . However , I 'm second-guessing this decision for a couple of reasons : a ) In a multi-threaded environment , this gives the end-user an easy way to roll-back changes should a call to the repository fail , leaving objects in a partially-mutated state.b ) Option 2 provides a `` batch-like '' paradigm , which I can see as being more flexible for a variety of reasons . public class XmlRepository1 { private XDocument xDocument ; public void CrudOp ( ) { // Perform CRUD operation ... // Call Save ( ) xDocument.Save ( path ) ; } } public class XmlRepository2 { private XDocument xDocument ; public void CrudOp ( ) { // Perform CRUD operation ... // DO N'T call save } // Provide a SaveChanges ( ) method to the end-user ... public void SaveChanges ( ) { xDocument.Save ( path ) ; } }",XML Repository ; to Save ( ) or not to Save ( ) "C_sharp : Here 's the task : I need to lock based on a filename . There can be up to a million different filenames . ( This is used for large-scale disk-based caching ) .I want low memory usage and low lookup times , which means I need a GC 'd lock dictionary . ( Only in-use locks can be present in the dict ) .The callback action can take minutes to complete , so a global lock is unacceptable . High throughput is critical.I 've posted my current solution below , but I 'm unhappy with the complexity.EDIT : Please do not post solutions that are not 100 % correct . For example , a solution which permits a lock to be removed from the dictionary between the 'get lock object ' phase and the 'lock ' phase is NOT correct , whether or not it is an 'accepted ' design pattern or not.Is there a more elegant solution than this ? Thanks ! [ EDIT : I updated my code to use looping vs. recursion based on RobV 's suggestion ] [ EDIT : Updated the code again to allow 'timeouts ' and a simpler calling pattern . This will probably be the final code I use . Still the same basic algorithm as in the original post . ] [ EDIT : Updated code again to deal with exceptions inside callback without orphaning lock objects ] Usage example public delegate void LockCallback ( ) ; /// < summary > /// Provides locking based on a string key . /// Locks are local to the LockProvider instance./// The class handles disposing of unused locks . Generally used for /// coordinating writes to files ( of which there can be millions ) . /// Only keeps key/lock pairs in memory which are in use./// Thread-safe./// < /summary > public class LockProvider { /// < summary > /// The only objects in this collection should be for open files . /// < /summary > protected Dictionary < String , Object > locks = new Dictionary < string , object > ( StringComparer.Ordinal ) ; /// < summary > /// Synchronization object for modifications to the 'locks ' dictionary /// < /summary > protected object createLock = new object ( ) ; /// < summary > /// Attempts to execute the 'success ' callback inside a lock based on 'key ' . If successful , returns true . /// If the lock can not be acquired within 'timoutMs ' , returns false /// In a worst-case scenario , it could take up to twice as long as 'timeoutMs ' to return false . /// < /summary > /// < param name= '' key '' > < /param > /// < param name= '' success '' > < /param > /// < param name= '' failure '' > < /param > /// < param name= '' timeoutMs '' > < /param > public bool TryExecute ( string key , int timeoutMs , LockCallback success ) { //Record when we started . We do n't want an infinite loop . DateTime startedAt = DateTime.UtcNow ; // Tracks whether the lock acquired is still correct bool validLock = true ; // The lock corresponding to 'key ' object itemLock = null ; try { //We have to loop until we get a valid lock and it stays valid until we lock it . do { // 1 ) Creation/aquire phase lock ( createLock ) { // We have to lock on dictionary writes , since otherwise // two locks for the same file could be created and assigned // at the same time . ( i.e , between TryGetValue and the assignment ) if ( ! locks.TryGetValue ( key , out itemLock ) ) locks [ key ] = itemLock = new Object ( ) ; //make a new lock ! } // Loophole ( part 1 ) : // Right here - this is where another thread ( executing part 2 ) could remove 'itemLock ' // from the dictionary , and potentially , yet another thread could // insert a new value for 'itemLock ' into the dictionary ... etc , etc.. // 2 ) Execute phase if ( System.Threading.Monitor.TryEnter ( itemLock , timeoutMs ) ) { try { // May take minutes to acquire this lock . // Trying to detect an occurence of loophole above // Check that itemLock still exists and matches the dictionary lock ( createLock ) { object newLock = null ; validLock = locks.TryGetValue ( key , out newLock ) ; validLock = validLock & & newLock == itemLock ; } // Only run the callback if the lock is valid if ( validLock ) { success ( ) ; // Extremely long-running callback , perhaps throwing exceptions return true ; } } finally { System.Threading.Monitor.Exit ( itemLock ) ; //release lock } } else { validLock = false ; //So the finally clause does n't try to clean up the lock , someone else will do that . return false ; //Someone else had the lock , they can clean it up . } //Are we out of time , still having an invalid lock ? if ( ! validLock & & Math.Abs ( DateTime.UtcNow.Subtract ( startedAt ) .TotalMilliseconds ) > timeoutMs ) { //We failed to get a valid lock in time . return false ; } // If we had an invalid lock , we have to try everything over again . } while ( ! validLock ) ; } finally { if ( validLock ) { // Loophole ( part 2 ) . When loophole part 1 and 2 cross paths , // An lock object may be removed before being used , and be orphaned // 3 ) Cleanup phase - Attempt cleanup of lock objects so we do n't // have a *very* large and slow dictionary . lock ( createLock ) { // TryEnter ( ) fails instead of waiting . // A normal lock would cause a deadlock with phase 2 . // Specifying a timeout would add great and pointless overhead . // Whoever has the lock will clean it up also . if ( System.Threading.Monitor.TryEnter ( itemLock ) ) { try { // It succeeds , so no-one else is working on it // ( but may be preparing to , see loophole ) // Only remove the lock object if it // still exists in the dictionary as-is object existingLock = null ; if ( locks.TryGetValue ( key , out existingLock ) & & existingLock == itemLock ) locks.Remove ( key ) ; } finally { // Remove the lock System.Threading.Monitor.Exit ( itemLock ) ; } } } } } // Ideally the only objects in 'locks ' will be open operations now . return true ; } } LockProvider p = new LockProvider ( ) ; bool success = p.TryExecute ( `` filename '' ,1000 , delegate ( ) { //This code executes within the lock } ) ;",Better solution to multithreading riddle ? "C_sharp : What I need to do : Compile the SDL2 source into an .so file for x86 and ARM64 architectureReference this file in Xamarin.AndroidCall the SDL2 methods in my C # code.Things I 've learned so far : SDL2 requires a Java Activity or JNI bindings to invoke the native code.I can not proceed without somehow integrating SDL2 libs and a JNI to the Xamarin.Android project.I am incapable of solving this problem and my brain has fried in the process.Things I 've tried : Outdated GitHub projects : https : //github.com/0x0ade/SDL2Droid-CShttps : //github.com/fallahn/sdl2vsThis blog post that lets me create C++ code but not using Xamarinhttps : //trederia.blogspot.com/2017/03/building-sdl2-for-android-with-visual.htmlRunning SDL2 through Android Studio which works but does n't help me as I need to invoke my C # code.I do n't have extensive Xamarin knowledge so I 'm not sure how to do this , I can really use another pair of eyes right now . The SDL2Droid-CS GitHub project should theoretically work but I ca n't find a way to compile the SDL2 used in that project for the x86 emulator included in C # .I tried compiling my code using armeabiv7 libsdl2.so and then running it directly on my phone . Unfortunately Visual Studio was unable to debug this thus making it difficult for me to implement my code.Next I tried to debug the previously compiled app ( using SDL2Droid-CS ) through Android Studio and it gave me this error : The Min SDK was 19 so the error it gives is weird.I 'm assuming that SDL2 was not implemented properly which is leading to all these problems . The GitHub code has some holes and the person who uploaded it has n't been active . Resources : SDL2 Website : https : //www.libsdl.org/SDL2 Source : https : //www.libsdl.org/release/SDL2-2.0.8.zipSDL2Droid GitHub Project : https : //github.com/0x0ade/SDL2Droid-CSGitHub Project from blog : https : //github.com/fallahn/sdl2vsBlog that explains building SDL2 in Visual Studio 06-19 00:39:55.362 13143-13143/ ? I/zygote64 : Late-enabling -Xcheck : jni06-19 00:39:55.474 13143-13143/SDL2Droid_CS.SDL2Droid_CS W/ActivityThread : Application SDL2Droid_CS.SDL2Droid_CS can be debugged on port 8100 ... 06-19 00:39:55.514 13143-13143/ ? W/monodroid : Creating public update directory : ` /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ ` Using override path : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ Using override path : /storage/emulated/0/Android/data/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ Trying to load sgen from : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/libmonosgen-2.0.so Trying to load sgen from : /storage/emulated/0/Android/data/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/libmonosgen-2.0.so Trying to load sgen from : /storage/emulated/0/../legacy/Android/data/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/libmonosgen-2.0.so Trying to load sgen from : /data/app/SDL2Droid_CS.SDL2Droid_CS-wmPu9Ce48QdJhvYc6bPRiA==/lib/arm64/libmonosgen-2.0.so Trying to load sgen from : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__/links/libmonosgen-2.0.so06-19 00:39:55.515 13143-13143/ ? W/monodroid : Trying to load sgen from : /system/lib/libmonosgen-2.0.so06-19 00:39:55.515 13143-13143/ ? A/monodroid : can not find libmonosgen-2.0.so in override_dir : /data/user/0/SDL2Droid_CS.SDL2Droid_CS/files/.__override__ , app_libdir : /data/app/SDL2Droid_CS.SDL2Droid_CS-wmPu9Ce48QdJhvYc6bPRiA==/lib/arm64 nor in previously printed locations . Do you have a shared runtime build of your app with AndroidManifest.xml android : minSdkVersion < 10 while running on a 64-bit Android 5.0 target ? This combination is not supported . Please either set android : minSdkVersion > = 10 or use a build without the shared runtime ( like default Release configuration ) .",How to implement the SDL2 library into Xamarin.Android ? "C_sharp : I have a simple paged linq query against one entity : I expected it to generate SQL similar to : When I run the above query in SSMS , it returns quickly ( had to rebuild my indexes first ) .However , the generated SQL is different . It contains a nested query as shown below : The Widgets table is enormous and the inner query returns 100000s of records , causing a timeout.Is there anything I can do to change the generation ? Anything I am doing wrong ? UPDATEI finally managed to refactor my code to return the results relatively quickly : Note , the page > 0 logic is simply used to prevent an invalid parameter being used ; it does no optimization . In fact page > 1 , while valid , does not provide any noticeable optimization for the 1st page ; since the Where is not a slow operation . var data = ( from t in ctx.ObjectContext.Widgets where t.CampaignId == campaignId & & t.CalendarEventId == calendarEventId ( t.RecurringEventId IS NULL OR t.RecurringEventId = recurringEventId ) select t ) ; data = data.OrderBy ( t = > t.Id ) ; if ( page > 0 ) { data = data.Skip ( rows * ( page - 1 ) ) .Take ( rows ) ; } var l = data.ToList ( ) ; select top 50 * from Widgets w where CampaignId = xxx AND CalendarEventId = yyy AND ( RecurringEventId IS NULL OR RecurringEventId = zzz ) order by w.Id SELECT TOP ( 50 ) [ Project1 ] . [ Id ] AS [ Id ] , [ Project1 ] . [ CampaignId ] AS [ CampaignId ] < redacted > FROM ( SELECT [ Project1 ] . [ Id ] AS [ Id ] , [ Project1 ] . [ CampaignId ] AS [ CampaignId ] , < redacted > , row_number ( ) OVER ( ORDER BY [ Project1 ] . [ Id ] ASC ) AS [ row_number ] FROM ( SELECT [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ CampaignId ] AS [ CampaignId ] , < redacted > FROM [ dbo ] . [ Widgets ] AS [ Extent1 ] WHERE ( [ Extent1 ] . [ CampaignId ] = @ p__linq__0 ) AND ( [ Extent1 ] . [ CalendarEventId ] = @ p__linq__1 ) AND ( [ Extent1 ] . [ RecurringEventId ] = @ p__linq__2 OR [ Extent1 ] . [ RecurringEventId ] IS NULL ) ) AS [ Project1 ] ) AS [ Project1 ] WHERE [ Project1 ] . [ row_number ] > 0ORDER BY [ Project1 ] . [ Id ] ASC var data = ( from t in ctx.ObjectContext.Widgets where t.CampaignId == campaignId & & t.CalendarEventId == calendarEventId ( t.RecurringEventId IS NULL OR t.RecurringEventId = recurringEventId ) select t ) ) .AsEnumerable ( ) .Select ( ( item , index ) = > new { Index = index , Item = item } ) ; data = data.OrderBy ( t = > t.Index ) ; if ( page > 0 ) { data = data.Where ( t = > t.Index > = ( rows * ( page - 1 ) ) ) ; } data = data.Take ( rows ) ;",Entity Framework generates inefficient SQL for paged query "C_sharp : I would not believe this if I was n't seeing it with my own eyes.Results in a value of `` { 0 } test { 1 } '' for variable testResults in a value of `` Mark test 13 '' for variable testWhhhhahaaaaattt ? This is Xamarin by the way . I am very baffled here . Visual Studio 8.0.4 . I 've assigned the value of test to a UI element , logged it to LogCat , and viewed it with the debugger . They all agree on the odd value . string test = String.Format ( `` { 0 } test { 1 } '' , `` Mark '' , 13 ) ; string test = string.Format ( `` { 0 } test { 1 } '' , `` Mark '' , 13 ) ;","String.Format ( ) does n't work , but string.Format ( ) does" "C_sharp : How can I add Quick Access Item container default by RibbonLibrary if I have binded collection for it . Its throws Operation is not valid while ItemSource is in use while is I add Quick Access tool item from UI.Error while Add comment if not clear . < r : Ribbon Name= '' ribbon '' > < r : Ribbon.QuickAccessToolBar > < r : RibbonQuickAccessToolBar ItemsSource = '' { Binding QuickMenuItems , Mode=OneWay } '' > < r : RibbonQuickAccessToolBar.ItemTemplate > < DataTemplate > < StackPanel > < r : RibbonButton QuickAccessToolBarId= '' { Binding RibbonId } '' Label= '' { Binding Label } '' SmallImageSource= '' { Binding ImageUri } '' Command= '' { Binding Command } '' / > < /StackPanel > < /DataTemplate > < /r : RibbonQuickAccessToolBar.ItemTemplate > < /r : RibbonQuickAccessToolBar > < /r : Ribbon.QuickAccessToolBar > < r : RibbonTab Header= '' Home '' > < r : RibbonGroup x : Name= '' Clipboard '' ItemsSource = '' { Binding MenuItems , Mode=OneWay } '' > < r : RibbonGroup.ItemTemplate > < DataTemplate > < StackPanel > < r : RibbonButton QuickAccessToolBarId= '' { Binding RibbonId } '' Label= '' { Binding Label } '' SmallImageSource= '' { Binding ImageUri } '' Command= '' { Binding Command } '' / > < /StackPanel > < /DataTemplate > < /r : RibbonGroup.ItemTemplate > < /r : RibbonGroup > < /r : RibbonTab > < /r : Ribbon > ObservableCollection < RibbonItem > _MenuItems ; ObservableCollection < RibbonItem > _QuickMenuItems ; public ObservableCollection < RibbonItem > MenuItems { get { return _MenuItems ; } } public ObservableCollection < RibbonItem > QuickMenuItems { get { return _QuickMenuItems ; } } public class RibbonItem { public RibbonItem ( string label , string imageUri , ICommand command , string ribbonId ) { Label = label ; ImageUri = imageUri ; Command = command ; } public string Label { get ; private set ; } public string ImageUri { get ; private set ; } public ICommand Command { get ; private set ; } public string RibbonId { get ; private set ; } }",How to access Quick Access tool bar command ` Add to Quick Access Tool ` if source binding applicable "C_sharp : I 'd like to get full name of all connected microphones . I was googling to find out an answer but there was no answer that satisfies me.Let me show some examples:1.All of these getters shows : `` Device Audio USB '' or `` Device compatible with High Definition standard '' .2.The same answer : `` Device Audio USB '' or `` Device compatible with High Definition standard '' .I want to get the full name . I mean , something like : `` Sennheiser microphone USB '' . Is it even possible ? I found : Get the full name of a waveIn device but a link in it is broken and I do n't see any dsound.lib for c # ( to use DirectSoundCaptureEnumerate ) .Am I missing anything ? Or is there any other option ? ManagementObjectSearcher mo = new ManagementObjectSearcher ( `` select * from Win32_SoundDevice '' ) ; foreach ( ManagementObject soundDevice in mo.Get ( ) ) { MessageBox.Show ( soundDevice.GetPropertyValue ( `` Caption '' ) .ToString ( ) ) ; // or MessageBox.Show ( soundDevice.GetPropertyValue ( `` Description '' ) .ToString ( ) ) ; //or MessageBox.Show ( soundDevice.GetPropertyValue ( `` Manufacturer '' ) .ToString ( ) ) ; //or MessageBox.Show ( soundDevice.GetPropertyValue ( `` Name '' ) .ToString ( ) ) ; //or MessageBox.Show ( soundDevice.GetPropertyValue ( `` ProductName '' ) .ToString ( ) ) ; } WaveInCapabilities [ ] devices = GetAvailableDevices ( ) ; foreach ( device in devices ) { MessageBox.Show ( device.ProductName ) ; }",How to get full name of microphone in C # ? "C_sharp : Is this a valid way to use a Lambda as an EventHandler ? It seems to me that the handler has been correctly removed and that the garbage collector should clean this up . However , I have n't seen anyone else do it this way , so I thought I 'd better double check.Along the same lines , what 's the best tool ( preferably free ) to use to test whether this is in fact being garbage collected ? DispatcherTimer timer = new DispatcherTimer ( ) ; timer.Interval = TimeSpan.FromSeconds ( 10 ) ; EventHandler callback = null ; callback = ( s , e ) = > { timer.Stop ( ) ; timer.Tick -= callback ; } ; timer.Tick += callback ; timer.Start ( ) ;",Will this get Garbage Collected ? "C_sharp : i 'm trying to load text from database into many text fields every thing is Ok , but one field of them text lenght is more than the length of the text field so not all the text appear on the screen that is my ASP.net code and that is the code behind of it and that is what i get in the web page the orginal text is `` ECASTI ( Egyptian Center for the Advancement of Science , Technology , and Innovation ) `` can any one help ? ? ! ! ! < asp : TextBox ID= '' descriptiont '' runat= '' server '' Rows= '' 3 '' Width= '' 300px '' Height= '' 100px '' Wrap= '' true '' > descriptiont.Text = s.GetValue ( 1 ) .ToString ( ) ; descriptiont.Enabled = false ;",Text cut in text area in ASP.net page "C_sharp : In the launchSettings.json I have the following . It works and I can access Swagger and the rest of the page using https : //localhost:44300.When I alter `` sslPort '' : 44300 to e.g . `` sslPort '' : 44299 , I can still access the stuff by altering the URL accordingly.However , when I set the value to 5100 , I 've noticed that the contents are n't accessible anymore . In fact , it seems that the working range is rather limited and only concentrated around 44300.What is that about ? ! I 've turned off the firewall , just in case . In the config I 've tried adding the urls like this . No changes in the behavior.How can I force the app to run properly on the port of my choice ? Following docs for .NET Core 2.2 , I added the configuration of the redirection as follows . As feared , it had no effect on the issue.Noticing that the docs themselves suggest 5001 as an alternative port number , I 'm starting to suspect that the issue might be located entirely elsewhere . I ' v recreated the setup on a different machine and was able to reproduce the error . Still , both are computers configured by me , so it 'd be great if someone not-me'ish could confirm the behavior.I 've got a tip to use Nmap to check the port answers and apparently there 's something answering on the port 5100 . The same can be confirmed using TelNet . However , the Swagger as well as the calls using PostMan fail still ... { ... `` iisSettings '' : { `` windowsAuthentication '' : false , `` anonymousAuthentication '' : true , `` iisExpress '' : { `` applicationUrl '' : `` http : //localhost:52088 '' , `` sslPort '' : 44300 } } , ... } WebHost.CreateDefaultBuilder ( args ) //.UseUrls ( `` https : //localhost/5100 '' ) .UseStartup < Startup > ( ) ; services.AddHttpsRedirection ( _ = > { _.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect ; _.HttpsPort = 5100 ; } ) ;",What is limiting the port range for HTTPS in .NET Core 2.2 ? "C_sharp : It seems that in most cases the C # compiler could call Dispose ( ) automatically . Like most cases of the using pattern look like : Since foo is n't used ( that 's a very simple detection ) and since its not provided as argument to another method ( that 's a supposition that applies to many use cases and can be extended ) , the compiler could automatically and immediately call Dispose ( ) without the developper requiring to do it.This means that in most cases the using is pretty useless if the compiler does some smart job . IDisposable seem low level enough to me to be taken in account by a compiler.Now why is n't this done ? Would n't that improve the performances ( if the developpers are ... dirty ) . public void SomeMethod ( ) { ... using ( var foo = new Foo ( ) ) { ... } // Foo is n't use after here ( obviously ) . ... }",Why is 'using ' improving C # performances "C_sharp : I am new to entity framework . I wrote a simple code first database.how to change the physical location of database.mdf by class . let 's say i what to save my database in |DataDirectory|\App_Data\database.mdf . I am using windows forms.here is the DbContextand here is the configuration file app.configthanks for you time and please help . : ) class DatabaseContext : DbContext { public DatabaseContext ( ) : base ( `` database '' ) { } public DbSet < Login > Logins { get ; set ; } public DbSet < master > masters { get ; set ; } public DbSet < People > People { get ; set ; } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < ! -- For more information on Entity Framework configuration , visit http : //go.microsoft.com/fwlink/ ? LinkID=237468 -- > < section name= '' entityFramework '' type= '' System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection , EntityFramework , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' requirePermission= '' false '' / > < /configSections > < startup > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.5.2 '' / > < /startup > < entityFramework > < defaultConnectionFactory type= '' System.Data.Entity.Infrastructure.LocalDbConnectionFactory , EntityFramework '' > < parameters > < parameter value= '' mssqllocaldb '' / > < /parameters > < /defaultConnectionFactory > < providers > < provider invariantName= '' System.Data.SqlClient '' type= '' System.Data.Entity.SqlServer.SqlProviderServices , EntityFramework.SqlServer '' / > < /providers > < /entityFramework > < /configuration > ` < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < ! -- For more information on Entity Framework configuration , visit http : //go.microsoft.com/fwlink/ ? LinkID=237468 -- > < section name= '' entityFramework '' type= '' System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection , EntityFramework , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' requirePermission= '' false '' / > < /configSections > < startup > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.5.2 '' / > < /startup > < entityFramework > < defaultConnectionFactory type= '' System.Data.Entity.Infrastructure.LocalDbConnectionFactory , EntityFramework '' > < parameters > < parameter value= '' mssqllocaldb '' / > < /parameters > < /defaultConnectionFactory > < providers > < provider invariantName= '' System.Data.SqlClient '' type= '' System.Data.Entity.SqlServer.SqlProviderServices , EntityFramework.SqlServer '' / > < /providers > < /entityFramework > < /configuration > `",entity framework change database physical location by class C_sharp : The use case is some what like this : Now my question is Why is it not possible to use `` SomeClass ( As it is derived from object ) '' as a return type of Clone ( ) method if we consider the Funda 's of Covariance and Contravariance ? Can somebody explain me the reason behind this implementation of Microsoft ? ? ? ? public class SomeClass : ICloneable { // Some Code // Implementing interface method public object Clone ( ) { // Some Clonning Code } },Why the concept of `` Covariance '' and `` Contravariance '' are applicable while implementing the methods of an interface ? "C_sharp : I am getting the following error when trying to let user login using GOOGLEI have tried so many things and nothing worksI used the following code initiallyI also tried the followingNo luck at all , My Client ID for Web application is set up as followingI have no idea what i am doing wrong , Have anyone faced this issue and have a solution for thisHighly appreciatedCheers app.UseGoogleAuthentication ( clientId : `` APIKEY.apps.googleusercontent.com '' , clientSecret : `` SECRET-K '' ) ; app.UseGoogleAuthentication ( new GoogleOAuth2AuthenticationOptions ( ) { ClientId = `` APIKEY.apps.googleusercontent.com '' , ClientSecret = `` SECRET-K '' , CallbackPath = new PathString ( `` /signin-google '' ) } ) ;",Error : redirect_uri_mismatch ( ASP.NET MVC ) "C_sharp : C # 7.1 introduces a new feature called `` Default Literals '' that allows new default expressions.For Nullable < T > types , the default value is null , and with the usual usage this works as expected : However , when I try to use the new default literal as an optional argument ( parameter ) of a function , it 's not working as expected : To me , this behavior is unexpected and looks like a bug in the compiler.Can anybody confirm the bug , or explain this behavior ? // instead of writingFoo x = default ( Foo ) ; // we can just writeFoo x = default ; int ? x = default ( int ? ) ; // x is nullint ? x = default ; // x is null static void Foo ( int ? x = default ( int ? ) ) { // x is null } static void Foo ( int ? x = default ) { // x is 0 ! ! ! }",Using C # 7.1 default literal in nullable optional argument causes unexpected behavior "C_sharp : ContextI want my UserControl ( RepositoryContainer ) to be filled up with data when on XAML Designer.I created a file named RepositoryContainerDesignData.xaml ( it is in the same folder as the RepositoryContainer.xaml ) and set it as d : DataContext to the UserControl.But instead of displaying the data , XAML Designer displays the property name.Here 's a minimal example : Design Data ( RepositoryContainerDesignData.xaml ) User Control ( RepositoryContainer.xaml ) Code-behindExpected output : Output : Already tried : Set IsDesignTimeCreatable as true : Closing Visual Studio and deleting .vs folderRepositoryContainerDesignData.xaml Build Action is DesignDataEnvironment info : Windows 10 Pro x64Visual Studio Community 2015 ( Version 14.9.25431.01 Update 3 ) Microsoft .NET Framework 4.6.01586More info at a Pastebin RAW to keep post cleanAm I missing something ? PSIf I create a class ( e.g . public class RepositoryContainerData ) , create a property called Title and set an instance of this class as d : DataContext ( d : DataContext= '' { d : DesignInstance local : RepositoryContainerData , IsDesignTimeCreatable=True } '' ) it works as expected . < local : RepositoryContainer xmlns : local= '' clr-namespace : SystemSpecs.View.UserControls '' Title= '' My Repository Title '' / > < UserControl x : Class= '' SystemSpecs.View.UserControls.RepositoryContainer '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : local= '' clr-namespace : SystemSpecs.View.UserControls '' mc : Ignorable= '' d '' d : DesignHeight= '' 100 '' d : DesignWidth= '' 500 '' d : DataContext= '' { d : DesignData Source=RepositoryContainerDesignData.xaml } '' DataContext= '' { Binding RelativeSource= { RelativeSource Self } } '' > < Grid > < TextBlock Text= '' { Binding Path=Title } '' FontSize= '' 24 '' Foreground= '' White '' HorizontalAlignment= '' Center '' / > < /Grid > < /UserControl > using System.Windows.Controls ; namespace SystemSpecs.View.UserControls { public partial class RepositoryContainer : UserControl { public string Title { get ; set ; } public RepositoryContainer ( ) { InitializeComponent ( ) ; } } }",XAML Designer displays property name instead of Designer Data ( d : DataContext ) when Binding "C_sharp : Integrating a payment Checkout Stripe . Used JavaScript Stripe handler , to apply Stripe charge on the transaction.After charging the customer , it returns token . Using this token we can proceed for Actual payment . And here is the AJAX call to Payment functionality : Here is Web Method on my TEST server , which passes token to Stripe server : If I POST AJAX call on POSTMAN , it shows unexpected 's ' in JSON . What it means in general , and in this case specifically ? var StripeHelper = { payProceed : function ( token ) { try { var _ajax = new AjaxHelper ( `` /Services/Service.asmx/PaymentProceed '' ) ; _ajax.Data = `` { token : '' + JSON.stringify ( token ) + `` } '' ; _ajax.OnInit = function ( ) { PageHelper.loading ( true ) ; } ; _ajax.OnSuccess = function ( data ) { console.log ( data.d ) ; PageHelper.loading ( false ) ; window.location ( '/payment-success ' ) ; } ; _ajax.Init ( ) ; } catch ( e ) { PageHelper.loading ( false ) ; } } } [ WebMethod ( EnableSession = true ) ] public string PaymentProceed ( string token ) { Session [ `` PAYMENT_MODE '' ] = PaymentContants.PaymentVia.Stripe ; var myCharge = new StripeChargeCreateOptions ( ) ; myCharge.AmountInCents = 100 ; myCharge.Currency = `` USD '' ; myCharge.Description = `` Charge for property sign and postage '' ; myCharge.TokenId = token ; string key = `` sk_test_Uvk2cH***********Fvs '' ; //test key var chargeService = new StripeChargeService ( key ) ; StripeCharge stripeCharge = new StripeCharge ( ) ; //Error is coming for below line -- > stripeCharge = chargeService.Create ( myCharge ) ; //No token found return stripeCharge.Id ; }",unexpected 's ' in postman on sending Webmethod "C_sharp : I 'm currently using the Azure DocumentDB to store product data with prices . Nearly everything is working quite fine but now I have the issue that my decimals ( System.Decimal ) are being truncated when reading from DocumentDB.For example this price : will be truncated intoAs we are using a sync mechanism to find price changes , this will result into a price change as it is not the same price anymore . I have no idea how I can change the behavior of the DocumentDB . In worst case I would have to truncate my input prices to prevent this problem , but I would rather not.Thanks for help . Input Price : 25.1132356547854257645454 DocumentDB Price : 25.113235654785",Azure DocumentDB Decimal Truncation "C_sharp : I have a little problem that I thought was a no-brainer ... but alas ... I have some xml and all I want to do is to add the xml : space= '' preserve '' to the root element using c # .I tried this : The result of this is : I think this is equivalent toBut since xml : space is a special attribute , I am a bit in doubt.So : Are they identical ? Is there a way I can add this to the document in a `` clean '' way ? var rootElem = xDoc.Root ; // XDocumentrootElem.SetAttributeValue ( `` { xml } space '' , `` preserve '' ) ; < ProjectDetails xmlns= '' http : //site/ppm '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' p3 : space= '' preserve '' xmlns : p3= '' xml '' > < ProjectDetails xmlns= '' http : //site/ppm '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xml : space= '' preserve '' >",Adding xml : space to root element "C_sharp : I am trying to create a Color Picker similar to that of MS Paint.Unfortunately , I ca n't figure out the algorithm for saturation.Whenever I try to implement saturation , it simply will not saturate correctly.I have to be missing some understanding of the saturation effect in the algorithm.This is what my current algorithm creates.Anytime I try to perform a saturated effect going down on the Y axis , it just makes everything after the first line completely red or black . } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; using SFML ; using SFML.Graphics ; using SFML.Window ; namespace Source { public ColorWheel ( ) { for ( int y = 0 ; y < 255 ; y++ ) { for ( int z = 0 ; z < 6 ; z++ ) { for ( int x = 0 ; x < 255 ; x++ ) { uint ux = ( uint ) x ; uint uy = ( uint ) y ; uint uz = ( uint ) z ; ux = ux + ( uz * 255 ) ; image.SetPixel ( ux , uy , color ) ; //Red 255 - Green 0-254 if ( z == 0 ) { color.G += 1 ; } //Green 255 - Red 255-0 else if ( z == 1 ) { color.R -= 1 ; } //Green 255 - Blue 0-255 else if ( z == 2 ) { color.B += 1 ; } //Blue 255 - Green 255-0 else if ( z == 3 ) { color.G -= 1 ; } //Blue 255 - Red 0-255 else if ( z == 4 ) { color.R += 1 ; } //Red 255 - Blue 255-0 else if ( z == 5 ) { color.B -= 1 ; } Texture texture = new Texture ( image ) ; sprite.Texture = texture ; } public void Update ( double dt ) { } public void Render ( RenderWindow rWindow ) { rWindow.Draw ( sprite ) ; } }",What am I missing / doing wrong for my rainbow Color Picker to not saturate correctly ? "C_sharp : I have created a CompositeDataBoundControl that i can databind perfectly well.Now i want to do the same thing , but not for a list of objects , but for a single object . Reasons is that i want my colleagues to have the ability to simply use the < % # Eval ( `` X '' ) % > in their front end code . The problem is that the CompositeDataBoundControl has a method that i have to override , which only accepts a collection as a datasource Is there a way to do the same thing for a single object ? CreateChildControls ( System.Collections.IEnumerable dataSource , bool dataBinding )",asp.net CompositeDataBoundControl for a single object "C_sharp : IntroI 'm Developing a tool that can interpret and use API Blueprints.I created a new console app , added SnowCrash.NET nuget package and wrote this code : ProblemWhen I deployed my code ( copied the bin folder ) to a different computer than my development environment , I get a FileNotFoundException pointing to SnowCrash.dllhere is a snapshop from the error message : Could not load file or assembly 'snowcrashCLR.DLL ' or one of its dependencies . The specified module could not be found.Details : What I 've tried so farI used sysinternal procmon on both machines to compare and it looks like my dev machine ( which runs fine ) is loading this DLL : Load Image C : \Windows\Microsoft.NET\assembly\GAC_MSIL\Microsoft.VisualC.STLCLR\v4.0_2.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualC.STLCLR.dllMy computer , which the application works fine on , has these runtimes installedOn the computer that had the error ( did not work ) , I installed the same identical list of runtimes above , but that did not solve the problem or made it work.I installed visual studio on that computer , that did not work previously , and when I tried my application and it workedYour help is greatly appreciated if you have better knowledge or battle scars with a similar issue . static void Main ( string [ ] args ) { snowcrashCLR.Blueprint blueprint ; snowcrashCLR.Result result ; var path = args.Length > 1 ? args [ 1 ] : @ '' c : \ '' ; snowcrashCLR.SnowCrashCLR.parse ( path , out blueprint , out result ) ; if ( result ! = null ) { var warnings = result.GetWarningsCs ( ) ; foreach ( var warning in warnings ) { Console.WriteLine ( `` { 0 } : { 1 } '' , warning.code , warning.message ) ; } } } [ FileNotFoundException : Could not load file or assembly 'snowcrashCLR.DLL ' or one of its dependencies . The specified module could not be found . ] System.Reflection.RuntimeAssembly._nLoad ( AssemblyName fileName , String codeBase , Evidence assemblySecurity , RuntimeAssembly locationHint , StackCrawlMark & stackMark , IntPtr pPrivHostBinder , Boolean throwOnFileNotFound , Boolean forIntrospection , Boolean suppressSecurityChecks ) +0 System.Reflection.RuntimeAssembly.nLoad ( AssemblyName fileName , String codeBase , Evidence assemblySecurity , RuntimeAssembly locationHint , StackCrawlMark & stackMark , IntPtr pPrivHostBinder , Boolean throwOnFileNotFound , Boolean forIntrospection , Boolean suppressSecurityChecks ) +34 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName ( AssemblyName assemblyRef , Evidence assemblySecurity , RuntimeAssembly reqAssembly , StackCrawlMark & stackMark , IntPtr pPrivHostBinder , Boolean throwOnFileNotFound , Boolean forIntrospection , Boolean suppressSecurityChecks ) +152 System.Reflection.RuntimeAssembly.InternalLoad ( String assemblyString , Evidence assemblySecurity , StackCrawlMark & stackMark , IntPtr pPrivHostBinder , Boolean forIntrospection ) +77 System.Reflection.RuntimeAssembly.InternalLoad ( String assemblyString , Evidence assemblySecurity , StackCrawlMark & stackMark , Boolean forIntrospection ) +16 System.Reflection.Assembly.Load ( String assemblyString ) +28 MS Visual C++ 2005 Redist ( x64 ) MS Visual C++ 2008 Redist ( x64 ) 9.0.30729.4148MS Visual C++ 2008 Redist ( x64 ) 9.0.30729.6161MS Visual C++ 2008 Redist ( x86 ) 9.0.30729.4148MS Visual C++ 2008 Redist ( x86 ) 9.0.30729.6161MS Visual C++ 2010 x64 Redist - 10.0.40219MS Visual C++ 2013 x64 Redist - 12.0.30501MS Visual C++ 2013 x86 Redist - 12.0.30501",Can not use a C++/CLI DLL unless visual studio is installed "C_sharp : Looks like ExpressionTrees compiler should be near with the C # spec in many behaviors , but unlike C # there is no support for conversion from decimal to any enum-type : Other rarely used C # explicit conversions , like double - > enum-type exists and works as explained in C # specification , but not decimal - > enum-type . Is this a bug ? using System ; using System.Linq.Expressions ; class Program { static void Main ( ) { Func < decimal , ConsoleColor > converter1 = x = > ( ConsoleColor ) x ; ConsoleColor c1 = converter1 ( 7m ) ; // fine Expression < Func < decimal , ConsoleColor > > expr = x = > ( ConsoleColor ) x ; // System.InvalidOperationException was unhandled // No coercion operator is defined between types // 'System.Decimal ' and 'System.ConsoleColor ' . Func < decimal , ConsoleColor > converter2 = expr.Compile ( ) ; ConsoleColor c2 = converter2 ( 7m ) ; } }",Is this is an ExpressionTrees bug ? # 2 "C_sharp : I am trying to create a WCF application that will listen for requests from a suppliers system . The supplier has provided me with a WSDL so I need to create a service and expose its ' endpoint to them . I have used SvcUtil.exe to generate the C # classes , but it outputs rather odd-looking types.This is a snippet of the WSDL that has been given to me : The command I run is simplyI would expect that this creates a structure like this : So that when it is serialized I get something like : However , the output of SvcUtil.exe gives me the following : It 's seems to bunch up the Submit and the Incident objects into one , and also it prepends 'SubmitIncident ' onto each of the nested elements . So when serializing I get this : This causes problems with both the supplier ( my service does n't match their WSDL so they ca n't talk to me ) , and with onward processing I am doing in the application . Can anyone help me understand why this is happening , how to stop it , and get SvcUtil to output properly . < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < wsdl : definitions xmlns : soap= '' http : //schemas.xmlsoap.org/wsdl/soap/ '' xmlns : tm= '' http : //microsoft.com/wsdl/mime/textMatching/ '' xmlns : soapenc= '' http : //schemas.xmlsoap.org/soap/encoding/ '' xmlns : mime= '' http : //schemas.xmlsoap.org/wsdl/mime/ '' xmlns : s= '' http : //www.w3.org/2001/XMLSchema '' xmlns : soap12= '' http : //schemas.xmlsoap.org/wsdl/soap12/ '' xmlns : http= '' http : //schemas.xmlsoap.org/wsdl/http/ '' xmlns : wsdl= '' http : //schemas.xmlsoap.org/wsdl/ '' > < wsdl : types > < s : schema elementFormDefault= '' qualified '' > < s : element name= '' Submit '' > < s : complexType > < s : sequence > < s : element minOccurs= '' 0 '' maxOccurs= '' 1 '' name= '' Incident '' > < s : complexType > < s : sequence > < s : element minOccurs= '' 0 '' maxOccurs= '' 1 '' form= '' unqualified '' name= '' TransactionId '' type= '' s : string '' / > < s : element minOccurs= '' 0 '' maxOccurs= '' 1 '' form= '' unqualified '' name= '' TransactionType '' type= '' s : string '' / > < s : element minOccurs= '' 0 '' maxOccurs= '' 1 '' form= '' unqualified '' name= '' TransactionSubType '' type= '' s : string '' / > < s : element minOccurs= '' 0 '' maxOccurs= '' unbounded '' form= '' unqualified '' name= '' ConfigurationItem '' > < s : complexType > < s : sequence > < s : element minOccurs= '' 0 '' maxOccurs= '' 1 '' form= '' unqualified '' name= '' AssetTag '' type= '' s : string '' / > < s : element minOccurs= '' 0 '' maxOccurs= '' 1 '' form= '' unqualified '' name= '' Name '' type= '' s : string '' / > ... . svcutil.exe file_name.wsdl class Submit { ... } class Incident { ... } class ConfigurationItem { ... } < Submit > < Incident > < TransactionId > 12345 < /TransactionId > < TransactionType > 12345 < /TransactionType > < TransactionSubType > 12345 < /TransactionSubType > < ConfigurationItem > < AssetTag > xyz < /AssetTag > < Name > name < /Name > < /ConfigurationItem > < /Incident > < /Submit > class SubmitIncident { ... } class SubmitIncidentConfigurationItem { ... } < SubmitIncident > < TransactionId > ... < /TransactionId > < TransactionType > ... < /TransactionType > < TransactionSubType > ... < /TransactionSubType > < SubmitIncidentConfigurationItem > < AssetTag > ... < /AssetTag > < Name > ... < /Name > < /SubmitIncidentConfigurationItem > < /SubmitIncident >",WCF service + SvcUtil generating unexpected object structure "C_sharp : I defined a custom ExpandableObjectConverter for collections : And also have a proxy class called ExpandableObjectManager , which in essence does this : Using this method : Is it possible to add type descriptor in such a way that all generic List < T > will be expandable in the property grid ? For example , given a simple Employee class : I can do this ( and it works , but only for List < Employee > ) : I would like to cover all T , not just Employee , without having to write 1 line for each possible class . I tried this - did n't work : TL ; DR : Default view of a List when set as SelectedObject in the property grid : Expected results : Without having to add a type descriptor for List < Employee > , and instead having some generic handler for all List < T > . internal class ExpandableCollectionConverter : ExpandableObjectConverter { public override PropertyDescriptorCollection GetProperties ( ITypeDescriptorContext context , object value , Attribute [ ] attributes ) { //implementation that returns a list of property descriptors , //one for each item in `` value '' } } TypeDescriptor.AddAttributes ( type , new TypeConverterAttribute ( typeof ( ExpandableCollectionConverter ) ) ) ; public static class ExpandableObjectManager { public static void AddTypeDescriptor ( Type tItem ) { //eventually calls TypeDescriptor.AddAttributes } } class Employee { public string Name { get ; set ; } public string Title { get ; set ; } public DateTime DateOfBirth { get ; set ; } } ExpandableObjectManager.AddTypeDescriptor ( typeof ( List < Employee > ) ) ; ExpandableObjectManager.AddTypeDescriptor ( typeof ( List < > ) ) ;",Add type descriptors to all List < T > for a generic implementation of property grid expansion ? "C_sharp : I have some auto-generated data being exported into my Unity project . To help me out I want to assign a custom icon to these assets to clearly identify them . This is of course simply possible via the editor itself , but ideally I 'd like this to happen automatically on import . To this effect I have written an AssetPostProcessor which should take care of this for me . In the example below ( which applies to MonoScripts as an example but could apply to any kind of asset ) , all newly imported scripts will have the MyFancyIcon icon assigned to them . This update is both visible on the script assets themselves , as well as on the MonoBehaviours in the inspector . And it works just fine , except for one problem . The updates are n't saved when closing the project and reopening it . To the best of my knowledge , either the EditorUtility.SetDirty ( script ) ; call should take care of this , or at the very least the AssetDatabase.SaveAssets ( ) ; call . However , looking at the difference between manually assigning an icon ( which works ) and doing it programmatically , there is an icon field in the meta files associated with the assets which does get set when manually assigning an icon , but not in my scripted case . ( In the scripted case the meta files are n't even updated ) So what gives ? Do I have to do anything in particular when it 's ( apparently ) only meta data I 'm changing ? Is there anything simple I 'm overlooking ? using UnityEngine ; using UnityEditor ; using System.Reflection ; public class IconAssignmentPostProcessor : AssetPostprocessor { static void OnPostprocessAllAssets ( string [ ] importedAssets , string [ ] deletedAssets , string [ ] movedAssets , string [ ] movedFromAssetPaths ) { Texture2D icon = AssetDatabase.LoadAssetAtPath < Texture2D > ( `` Assets/Iconfolder/MyFancyIcon.png '' ) ; foreach ( string asset in importedAssets ) { MonoScript script = AssetDatabase.LoadAssetAtPath < MonoScript > ( asset ) ; if ( script ! = null ) { PropertyInfo inspectorModeInfo = typeof ( SerializedObject ) .GetProperty ( `` inspectorMode '' , BindingFlags.NonPublic | BindingFlags.Instance ) ; SerializedObject serializedObject = new SerializedObject ( script ) ; inspectorModeInfo.SetValue ( serializedObject , InspectorMode.Debug , null ) ; SerializedProperty iconProperty = serializedObject.FindProperty ( `` m_Icon '' ) ; iconProperty.objectReferenceValue = icon ; serializedObject.ApplyModifiedProperties ( ) ; serializedObject.Update ( ) ; EditorUtility.SetDirty ( script ) ; } } AssetDatabase.SaveAssets ( ) ; AssetDatabase.Refresh ( ) ; } }",Programmatically setting and saving the icon associated with an imported asset "C_sharp : There is a method that takes a list of base objects as a parameter.When I ` m calling that method , I want to pass list of derived objects.But I can not do that because collection of derived is not the same as collection of base objects.What is the best practice to handle this situation ? Now I 'm using my extension .ToBase ( ) where I create new collection , but I think there is nicer solution.Thanks . abstract class Base { } class MyClass : Base { } // ... void Method ( List < Base > list ) { } var derivedList = new List < MyClass > ( ) ; Method ( derivedList ) ;",Collections with generic objects "C_sharp : I 'm trying to make something in C # that requires calling into some unmanaged DLLs , a process which I know nothing about ! I found a `` Hello World '' tutorial that should be as simple as copying and pasting a couple lines of code from the bottom : This compiles and runs to completion without any errors , however nothing is printed by the time it gets to the ReadKey ( ) .Did I miss some important setup step ? The project builds for .NET 4.6.1 ( in case that matters for DLL versioning or something ) . using System ; using System.Runtime.InteropServices ; namespace PInvokeTest { class Program { [ DllImport ( `` msvcrt40.dll '' ) ] public static extern int printf ( string format , __arglist ) ; public static void Main ( ) { printf ( `` Hello % s ! \n '' , __arglist ( `` World '' ) ) ; Console.ReadKey ( ) ; } } }",`` Hello World '' via PInvoke "C_sharp : Let 's say I have a class as follows : Now , if I try to consume this in code , I use something like this : The reason that it 's 7 , is because overload resolution prefers [ IList < object > ] over [ IEnumerable < object > ] and [ object ] , and because [ string , int=default ] has preference over [ object ] .In my scenario , I 'd like to get the best matching overload using reflection . In other words : 'best ' is defined as ' c # overload resolution ' . E.g . : While the scenario I sketch has only 1 parameter , the solution I seek can have multiple parameters . Update 1 : Because I received a comment that this is too difficult for SO due to the difficulties of overload resolution implementation ( which I am well aware of ) , I feel inclined to send an update . To give my argument some power , this was my first attempt , which uses the default .NET binder that handles the overload resolution : This version already seems to do simple overload resolution correctly , but fails to work with optional parameters . Because .NET afaik works with type binding like I show here , I suppose that the solution could be implemented fairly easy . public class AcceptMethods { public int Accept ( string s , int k = 1 ) { return 1 ; } public int Accept ( object s ) { return 2 ; } public int Accept ( IEnumerable < object > s ) { return 7 ; } public int Accept ( IList < object > s ) { return 4 ; } } object [ ] list = new object [ ] { `` a '' , new object [ 0 ] , `` c '' , `` d '' } ; Assert.AreEqual ( 7 , list.Select ( ( a ) = > ( ( int ) new AcceptMethods ( ) .Accept ( ( dynamic ) a ) ) ) .Sum ( ) ) ; int sum = 0 ; foreach ( var item in list ) { var method = GetBestMatching ( typeof ( AcceptMethods ) .GetMethods ( ) , item.GetType ( ) ) ; sum += ( int ) method.Invoke ( myObject , new object [ ] { item } ) ; } Assert.AreEqual ( 7 , sum ) ; private MethodBase GetBestMatching ( IEnumerable < MethodInfo > methods , Type [ ] parameters ) { return Type.DefaultBinder.SelectMethod ( BindingFlags.Instance | BindingFlags.Public | BindingFlags.OptionalParamBinding | BindingFlags.InvokeMethod , methods.ToArray ( ) , parameters , null ) ; }",Get best matching overload from set of overloads "C_sharp : As part of our continuous integration efforts we 've created a custom deployment application for handling Entity Framework 6.0 Code First database migrations . We take our target DLLs and compare those against the currently deployed DLLs to determine the migration path whether that path be upwards or downwards . In order to ensure we 're loading the correct version of the data context 's DLL we 're listening on the AppDomain.CurrentDomain.AssemblyResolve ( see : Loading Dependent Assemblies Manually ) .This works fine when deploying a simple data context ( a single table seeded with a single row ) to a server running SQL Server 2012 ( running Windows Server 2012 ) , but the following error occurs when deploying the same simple data context to a server running SQL Server 2008 R2 ( running Windows Server 2008 Standard ) : Some logging output revealed that BuildAssemblyId is throwing the NullReferenceException because the args.RequestingAssembly that 's being passed in is null . The value in args.Name is the name of the DLL that contains our data context . This gets thrown between the creation of the context and the data seeding as the table is created , but empty.The application was initial running on each machine independently . We 've ruled out .NET Framework discrepancy by update each machine to .NET 4.5.1 . Also , we ran the deployment application on the same machine ; we used the machine that had SQL Server 2012 installed . Finally , both the deployment application and simple data context are referencing the same version of EntityFramework.EDITIt was suggested that the attribute on the table object could be the root of the problem.We removed the TableAttribute and while it still failed on SQL Server 2008 R2 the error became reproducible on SQL Server 2012 . using System ; using System.Collections.Concurrent ; using System.IO ; using System.Reflection ; using System.Security.Cryptography ; using System.Text ; public enum MigrationsSource { Target = 1 , Deployed= 2 } public class AssemblyLoader { private readonly ConcurrentDictionary < string , MigrationsSource > m_Sources = new ConcurrentDictionary < string , MigrationsSource > ( ) ; private string m_DeployedPath ; private string m_TargetPath ; public AssemblyLoader ( ) { AppDomain.CurrentDomain.AssemblyResolve += ResolveDependentAssembly ; } ~AssemblyLoader ( ) { AppDomain.CurrentDomain.AssemblyResolve -= ResolveDependentAssembly ; } private Assembly ResolveDependentAssembly ( object sender , ResolveEventArgs args ) { MigrationsSource source ; if ( m_Sources.TryGetValue ( BuildAssemblyId ( args.RequestingAssembly ) , out source ) ) { var assemblyName = new AssemblyName ( args.Name ) ; string targetPath = Path.Combine ( source == MigrationsSource.Deployed ? m_DeployedPath : m_TargetPath , string.Format ( `` { 0 } .dll '' , assemblyName.Name ) ) ; assemblyName.CodeBase = targetPath ; //We have to use LoadFile here , otherwise we wo n't load a differing //version , regardless of the codebase because only LoadFile //will actually load a *new* assembly if it 's at a different path //See : http : //msdn.microsoft.com/en-us/library/b61s44e8 ( v=vs.110 ) .aspx var dependentAssembly = Assembly.LoadFile ( assemblyName.CodeBase ) ; m_Sources.TryAdd ( BuildAssemblyId ( dependentAssembly ) , source ) ; return dependentAssembly ; } return null ; } private string BuildAssemblyId ( Assembly assembly ) { return Convert.ToBase64String ( HashAlgorithm.Create ( `` SHA1 '' ) .ComputeHash ( UTF8Encoding.UTF8.GetBytes ( string.Format ( `` { 0 } | { 1 } '' , assembly.FullName , assembly.Location ) ) ) ) ; } } Unhandled Exception : System.NullReferenceException : Object reference not set to an instance of an object . at EntityFramework.AssemblyLoader.BuildAssemblyId ( Assembly assembly ) in c : \EntityFramework\AssemblyLoader.cs : line 103 at EntityFramework.AssemblyLoader.ResolveDependentAssembly ( Object sender , ResolveEventArgs args ) in c : \EntityFramework\AssemblyLoader.cs : line 42 at System.AppDomain.OnAssemblyResolveEvent ( RuntimeAssembly assembly , String assemblyFullName ) at System.RuntimeTypeHandle.GetTypeByName ( String name , Boolean throwOnError , Boolean ignoreCase , Boolean reflectionOnly , StackCrawlMarkHandle stackMark , IntPtr pPrivHostBinder , Boolean loadTypeFromPartialName , ObjectHandleOnStack type ) at System.RuntimeTypeHandle.GetTypeByName ( String name , Boolean throwOnError , Boolean ignoreCase , Boolean reflectionOnly , StackCrawlMark & stackMark , IntPtr pPrivHostBinder , Boolean loadTypeFromPartialName ) at System.RuntimeType.GetType ( String typeName , Boolean throwOnError , Boolean ignoreCase , Boolean reflectionOnly , StackCrawlMark & stackMark ) at System.Type.GetType ( String typeName , Boolean throwOnError ) at System.Data.Entity.Infrastructure.DependencyResolution.ClrTypeAnnotationSerializer.Deserialize ( String name , String value ) at System.Data.Entity.Core.SchemaObjectModel.SchemaElement.CreateMetadataPropertyFromXmlAttribute ( String xmlNamespaceUri , String attributeName , String value ) at System.Data.Entity.Core.SchemaObjectModel.SchemaElement.AddOtherContent ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.SchemaElement.ParseAttribute ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.SchemaElement.Parse ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.Schema.HandleEntityTypeElement ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.Schema.HandleElement ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.SchemaElement.ParseElement ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.SchemaElement.Parse ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.Schema.HandleTopLevelSchemaElement ( XmlReader reader ) at System.Data.Entity.Core.SchemaObjectModel.Schema.InternalParse ( XmlReader sourceReader , String sourceLocation ) at System.Data.Entity.Core.SchemaObjectModel.Schema.Parse ( XmlReader sourceReader , String sourceLocation ) at System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate ( IEnumerable ` 1 xmlReaders , IEnumerable ` 1 sourceFilePaths , SchemaDataModelOption dataModel , AttributeValueNotification providerNotification , AttributeValueNotification providerManifestTokenNotification , ProviderManifestNeeded providerManifestNeeded , IList ` 1 & schemaCollection ) at System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate ( IEnumerable ` 1 xmlReaders , IEnumerable ` 1 sourceFilePaths , SchemaDataModelOption dataModel , DbProviderManifest providerManifest , IList ` 1 & schemaCollection ) at System.Data.Entity.Core.Metadata.Edm.EdmItemCollection.LoadItems ( IEnumerable ` 1 xmlReaders , IEnumerable ` 1 sourceFilePaths , SchemaDataModelOption dataModelOption , DbProviderManifest providerManifest , ItemCollection itemCollection , Boolean throwOnError ) at System.Data.Entity.Core.Metadata.Edm.EdmItemCollection.Init ( IEnumerable ` 1 xmlReaders , IEnumerable ` 1 filePaths , Boolean throwOnError ) at System.Data.Entity.Core.Metadata.Edm.EdmItemCollection..ctor ( IEnumerable ` 1 xmlReaders ) at System.Data.Entity.Utilities.XDocumentExtensions.GetStorageMappingItemCollection ( XDocument model , DbProviderInfo & providerInfo ) at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff ( XDocument sourceModel , XDocument targetModel , Lazy ` 1 modificationCommandTreeGenerator , MigrationSqlGenerator migrationSqlGenerator , String sourceModelVersion , String targetModelVersion ) at System.Data.Entity.Migrations.DbMigrator.IsModelOutOfDate ( XDocument model , DbMigration lastMigration ) at System.Data.Entity.Migrations.DbMigrator.Upgrade ( IEnumerable ` 1 pendingMigrations , String targetMigrationId , String lastMigrationId ) at System.Data.Entity.Migrations.DbMigrator.UpdateInternal ( String targetMigration ) at System.Data.Entity.Migrations.DbMigrator. < > c__DisplayClassc. < Update > b__b ( ) at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists ( Action mustSucceedToKeepDatabase ) at System.Data.Entity.Migrations.DbMigrator.Update ( String targetMigration ) at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase ( InternalContext internalContext , Func ` 3 createMigrator , ObjectContext objectContext ) at System.Data.Entity.Internal.InternalContext.CreateDatabase ( ObjectContext objectContext , DatabaseExistenceState existenceState ) at System.Data.Entity.Database.Create ( DatabaseExistenceState existenceState ) at System.Data.Entity.CreateDatabaseIfNotExists ` 1.InitializeDatabase ( TContext context ) at System.Data.Entity.Internal.InternalContext. < > c__DisplayClassf ` 1. < CreateInitializationAction > b__e ( ) at System.Data.Entity.Internal.InternalContext.PerformInitializationAction ( Action action ) at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization ( ) at System.Data.Entity.Internal.LazyInternalContext. < InitializeDatabase > b__4 ( InternalContext c ) at System.Data.Entity.Internal.RetryAction ` 1.PerformAction ( TInput input ) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction ( Action ` 1 action ) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase ( ) at EntityFramework.DbDeploymentManager.HandleDatabaseInitialization ( DatabaseEndpoint endpoint ) in c : \EntityFramework\DbDeploymentManager.cs : line 185 at EntityFramework.DbDeploymentManager.Deploy ( ) in c : \EntityFramework\DbDeploymentManager.cs : line 67 at EntityFramework.Deployer.Program.Main ( String [ ] args ) in c : \EntityFramework.Deployer\Program.cs : line 23 [ Table ( `` dbo.tblCustomer '' ) ] public class Customer { public Guid Id { get ; set ; } public string Name { get ; set ; } }",ResolveEventArgs.RequestingAssembly is null when AppDomain.CurrentDomain.AssemblyResolve is called "C_sharp : I have the following C # code : And here it 's IL code ( ILSpy ) : How can I get it with System.Reflection.Emit or better with the Mono.Cecil ? public static double f ( double x1 , double x2 = 1 ) { return x1 * x2 ; } .method public hidebysig static float64 f ( float64 x1 , [ opt ] float64 x2 ) cil managed { .param [ 2 ] = float64 ( 1 ) // Method begins at RVA 0x20c6 // Code size 4 ( 0x4 ) .maxstack 8 IL_0000 : ldarg.0 IL_0001 : ldarg.1 IL_0002 : mul IL_0003 : ret } // end of method A : :f",Emitting function with optional parameter "C_sharp : I got CS0079 compile error when I tried to run the code below : Error : CS0079 : The event MyClassE.Error can only appear on the left hand side of += or -=Searched around but could n't figure out how to resolve it.ADDED : if ( MyClass.Error ! = null ) or MyClass.Error ( null , null ) ; Get the same CS0079 error . CS0079 : The event MyClassE.Error can only appear on the left hand side of += or -=Can anyone help me on this ? public delegate void MyClassEHandler ( MyClassEParam param ) ; public class MyClassE { public static event MyClassEHandler Error { add { MyClassE.Error = ( MyClassEHandler ) Delegate.Combine ( MyClassE.Error , value ) ; } } }",C # CS0079 Event Handling Compile Error "C_sharp : I have two classes . First class is Parent , which has a list of objects ( Child ) . Each of the Child has the reference to his Parent class . Question is how to implement this reference through the constructor.The issue is that I have a code which parses some XML code and creates the list of Parent objects . Here is the example : Of course I can init the Parent property within Parent constructor , just remove the private from Parent setter and then go trhough all children and use this property . But I want to make it read-only . Something like this : public sealed class Child { public Child ( string id , string name , Parent parent ) { Id = id ; Name = name ; Parent = parent ; } public Parent ParentInstance { get ; private set ; } public string Id { get ; private set ; } public string Name { get ; private set ; } } public sealed class Parent { public Parent ( string id , string name , IEnumerable < Child > children ) { Id = id ; Name = name ; Children = children ; } public string Id { get ; private set ; } public string Name { get ; private set ; } public IEnumerable < Child > Children { get ; private set ; } } internal Parent ParseParent ( XElement parentXElement ) { return new Parent ( parentXElement.Attribute ( `` id '' ) .Value , parentXElement.Attribute ( `` name '' ) .Value , parentXElement.Descendants ( `` child '' ) .Select ( ParseChild ) ) ; } public Parent ( string id , string name , IEnumerable < Child > children ) { Id = id ; Name = name ; Children = children.ForEach ( c = > c.ParentInstance = this ) ; }",How properly initialize parent and child references between two classes through constructor "C_sharp : Just out of curiosity - consider the following example : My question is the following : is the value of the Foo field boxed because it resides on the heap ? Or is it in a special container object / memory section that encapsulates it just like an instance value type field is part of an object on the heap ? I would assume that it is not boxed but I do n't know for sure and I can not find any documentation on it.Thank you for your help . public class A { public static int Foo ; } public class Program { static void Main ( ) { // The following variable will be allocated on the // stack and will directly hold 42 because it is a // value type . int foo = 42 ; // The following field resides on the ( high frequency ) // heap , but is it boxed because of being a value type ? A.Foo = 42 ; } }",Is a static value type field boxed in the heap in C # ? "C_sharp : I 'm curious - sometimes I make changes in my code , recompile , then copy my exe or dll file over the old version and see Windows telling me that the date of the file changed , but the size stayed exactly the same . Why is that ? As an example , I tested with the following console application : This produced an exe file of 5120 bytes ( Visual Studio 2012 , Debug build ) . Then , I changed the code to this : The size of the exe is exactly the same.I look at the disassembly , which is showing a difference in the IL code , so it can not be that the difference is optimized away : First version : Second version : If the code is physically bigger , how can the files be exactly the same size ? Is this just some random chance ? It happens to me a lot ( when making small changes to the code ) ... using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ConsoleApplication4 { class Program { static void Main ( string [ ] args ) { int a = 1 ; int b = 2 ; Console.WriteLine ( a + b ) ; } } } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ConsoleApplication4 { class Program { static void Main ( string [ ] args ) { int a = 1 ; int b = 2 ; int c = 3 ; Console.WriteLine ( a + b + c ) ; } } } .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 15 ( 0xf ) .maxstack 2 .locals init ( int32 V_0 , int32 V_1 ) IL_0000 : nop IL_0001 : ldc.i4.1 IL_0002 : stloc.0 IL_0003 : ldc.i4.2 IL_0004 : stloc.1 IL_0005 : ldloc.0 IL_0006 : ldloc.1 IL_0007 : add IL_0008 : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_000d : nop IL_000e : ret } // end of method Program : :Main .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 19 ( 0x13 ) .maxstack 2 .locals init ( [ 0 ] int32 a , [ 1 ] int32 b , [ 2 ] int32 c ) IL_0000 : nop IL_0001 : ldc.i4.1 IL_0002 : stloc.0 IL_0003 : ldc.i4.2 IL_0004 : stloc.1 IL_0005 : ldc.i4.3 IL_0006 : stloc.2 IL_0007 : ldloc.0 IL_0008 : ldloc.1 IL_0009 : add IL_000a : ldloc.2 IL_000b : add IL_000c : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_0011 : nop IL_0012 : ret } // end of method Program : :Main",Why do n't small changes in code affect exe file size ? "C_sharp : I need to compare file system wildcard expressions to see whether their results would overlap , by only examining/comparing the expressions.For sake of example , we are building a utility that would sort files from one ( or more locations ) into a separate folders based on file system wildcard expressions . For example : *.txt goes into folder a , *.doc goes into folder b , and so on . The wildcard characters we would support would be * and ? I want to be able to determine from just analyzing the wildcard expressions , whether they would conflict/overlap.For example , if I have the following expressions : They would conflict ( overlap ) because the second expression *.y would include *.x.y results . ( ex . A.x.y would match both expressions ) I am approaching this by building a tree structure using the using all of the expressions , figuring that the very act of building a tree will fail if the expressions conflict.If I try to add the pattern b.x , the tree would be successful following the *.x path , and thereby say that the pattern already exists.Am I heading in the correct direction ? Or is there an known algorithm for attacking this ? *.x.y*.y For example : *.xa.ba.cb.dmight create a tree like +-*-.-x |start + -- + | +-b | | +-a-.-+-c | | +-b-.-d",Checking collision in filename search patterns with wildcards "C_sharp : I am trying to set clipboard data and invoke a paste to windows . My data is successfully set into the clipboard but when I perform awith an image in the clipboard , it does not paste the image . When text is in the clipboard , it does successfully paste the text.When I set the clipboard content to contain an image and then close my application and manually perform a CTRL+V , the image pastes successfully . Does anyone have any idea what I am doing wrong ? Is there another way to invoke a paste ? Many Thanks SendKeys.Send ( `` ^V '' ) ;",SendKeys.Send ( `` ^V '' ) ; does not paste an image but it does paste text "C_sharp : Is PLINQ guaranteed to return query results in the order of the original sequence being operated on , even if results are produced in parallel ? For instance : will the result always be `` aa , ba , ca , da , `` ? new List < String > ( ) { `` a '' , `` b '' , `` c '' , `` d '' } .asParallel ( ) .Select ( str = > str + `` a '' ) .asSequential ( ) .ToList ( ) .ForEach ( str = > Console.Write ( str + `` , `` ) ;",does PLINQ preserve the original order in a sequence ? "C_sharp : I chose to use mongodb as a storage for domain-centric data.I was searching for official mongodb providers to integrate them into ASP.NET MVC project to keep a single application database . There are no official providers and available ones do n't look mature/stable . So I decided to use simple membership as it is . How to get rid of Entity Framework-specific code , if possible , from the AccountController ? How would you manage user profiles having both SimpleMembership UserProfile and MongoDB User ? ExampleIn a separate assembly [ project-name ] .domain there are two classes : Will this be a solution if I add an UserProfileId to User ? public class Event { public DateTime ScheduledDate { get ; set ; } public String Name { get ; set ; } public Location Location { get ; set ; } } public class User { public String Name { get ; set ; } public List < Events > AssociatedEvents { get ; set ; } } public class User { public Int32 UserProfileId { get ; set ; } public String Name { get ; set ; } public List < Events > AssociatedEvents { get ; set ; } }","Managing user profiles with SimpleMembership/Sql Server CE , MongoDB" "C_sharp : I have a MongoDB database that has a collection called fooCollection . This collection has documents in it containing geospatial data in the way of a bounding polygon . I am using the C # MongoDB driver in my app . I noticed that it was not finding documents with certain spatial queries although it works with most of them . I emptied the collection except for one offending document and I tried to find it by executing queries directly . My document looks like this : I also have this index on that collection : The following query correctly returns this document : However , this query does not : If you plot those three geometries , I ca n't really see why one would work but not the other.Both lines lie entirely within the polygonThe working line is much longerThe working line has a bearing of between 0° and 90° , the other between 90° and 180°.Is anyone able to explain this behaviour ? EDIT : I have also tested the points individually instead of using the LineStrings . The only one that is a hit is [ 24.7698287 , -28.7353533 ] . I do need the LineStrings - the query should be a hit even if only the edge intersects the polygon and no points lie withinYou can see the geojson here or you can plot the three geometries yourself by pasting the following line into http : //geojson.io/ : { `` _id '' : UUID ( `` 12345678-62d9-4024-86dc-123456789012 '' ) , '' polygon '' : { `` type '' : `` Polygon '' , `` coordinates '' : [ [ [ 18.414846 , -33.9699577 ] , [ 18.414846 , -26.0991189 ] , [ 31.0330578 , -26.0991189 ] , [ 31.0330578 , -33.9699577 ] , [ 18.414846 , -33.9699577 ] ] ] } , '' foo '' : `` bar '' } [ 1 , { `` polygon '' : `` 2dsphere '' } , `` polygon_2dsphere '' , `` data.fooCollection '' , 3 ] db.getCollection ( 'fooCollection ' ) .find ( { `` polygon '' : { $ geoIntersects : { $ geometry : { type : `` LineString '' , coordinates : [ [ 24.7698287 , -28.7353533 ] , [ 28.0423 , -26.19793 ] ] } } } } ) db.getCollection ( 'fooCollection ' ) .find ( { `` polygon '' : { $ geoIntersects : { $ geometry : { type : `` LineString '' , coordinates : [ [ 27.7706902 , -26.1091189 ] , [ 28.0423 , -26.19793 ] ] } } } } ) { `` type '' : '' GeometryCollection '' , '' geometries '' : [ { `` type '' : '' Polygon '' , '' coordinates '' : [ [ [ 18.414846 , -33.9699577 ] , [ 18.414846 , -26.0991189 ] , [ 31.0330578 , -26.0991189 ] , [ 31.0330578 , -33.9699577 ] , [ 18.414846 , -33.9699577 ] ] ] } , { `` type '' : '' LineString '' , '' coordinates '' : [ [ 27.7706902 , -26.1091189 ] , [ 28.0423 , -26.19793 ] ] } , { `` type '' : '' LineString '' , '' coordinates '' : [ [ 24.7698287 , -28.7353533 ] , [ 28.0423 , -26.19793 ] ] } ] }","MongoDB $ geoIntersects not finding one fully-contained line in polygon , but finding another" "C_sharp : If I had the value : `` dog '' and the enumeration : how could I get 0 for the value `` dog '' from Animals ? EDIT : I am wondering if there is index like acces . More commonn : how can I get the integer for string value . public enum Animals { dog = 0 , cat = 1 , rat = 2 }",How to get the int for enum value in Enumeration "C_sharp : I 'm having a bit of trouble here , in our company we have a self rolled DA layer which uses self referencing generics . In Visual Studio 2010 , the IDE was perfectly happy with this , however 2012 seems to be having difficulty , even though when we build , it succeeds.Here is an example : The DataObject definition is as follows : I realise it is n't the simplest of definitions , but its legal , and it builds perfectly fine . However , this 'issue ' causes intellisense to fail , as well as the 'Go To Definition ' function , which needless to say is frustrating . I 've tried removing and re-adding the references , but the issue persists . VS2010 is perfectly happy and is what I have gone back to using , VS2012 is very nice and responsive but if this issue persists its a deal breaker . Anyone got any ideas ? Want to make a couple of things clear , this issue is an intermittent one ( which is a pain as its really hard to track the root cause ) .It breaks intellisense and 'go to definition ' everywhere , not just for the class with the error.I 'll have a go at building a example solution to submit to connect , but time is n't on my side lately . [ TypeDescriptionProvider ( typeof ( HyperTypeDescriptor.HyperTypeDescriptionProvider ) ) ] public class DataObject < T > : INotifyPropertyChanged , IDataErrorInfo , IEditableObject , IDataObject where T : DataObject < T > , new ( )",Visual Studio 2012 - Self Referencing Generics Parsing Errors "C_sharp : When I use < para > < /para > tag in documentation ( in form of < para / > as well ) in Visual Studio 2015 Community Edition , I 'm getting an extra blank line displayed in IntelliSense tooltip ( the one which appears when typing in member name ) .I 've tried many variants , including but not limited to listed in the following example : but still it appears , and it is infuriating . Please , if anyone knows how to get rid of it , help me.UPDATE ( image uploaded ) UPDATE 2 ( disambiguation with XML multiline comments in C # - what am I doing wrong ? ) The question is NOT about getting new lines in XML comments , which I know how to obtain . It is about getting rid of extra new lines while using < para / > tag . public interface IFooBar { /// < summary > foo < para > bar < /para > < para > baz < /para > < /summary > void Foo ( ) ; /// < summary > foo /// < para > bar < /para > /// < para > baz < /para > /// < /summary > void Bar ( ) ; /// < summary > foo < para / > bar < para / > baz < /summary > void Baz ( ) ; /// < summary > foo < para / > ///bar /// < para / > baz /// < /summary > void Qux ( ) ; }","Extra blank line displayed from < para > < /para > and < para / > in VS2015CE , ca n't get rid of it" "C_sharp : I have a part of code that operates on large arrays of double ( containing about 6000 elements at least ) and executes several hundred times ( usually 800 ) .When I use standard loop , like that : The memory usage rises for about 40MB ( from 40MB at the beggining of the loop , to the 80MB at the end ) .When I force to use the garbage collector to execute at every iteration , the memory usage stays at the level of 40MB ( the rise is unsignificant ) . But the execution time is 3 times longer ! ( it is crucial ) How can I force the C # to use the same area of memory instead of allocating new ones ? Note : I have the access to the code of someObject class , so if it would be needed , I can change it . double [ ] singleRow = new double [ 6000 ] ; int maxI = 800 ; for ( int i=0 ; i < maxI ; i++ ) { singleRow = someObject.producesOutput ( ) ; // ... // do something with singleRow// ... } double [ ] singleRow = new double [ 6000 ] ; int maxI = 800 ; for ( int i=0 ; i < maxI ; i++ ) { singleRow = someObject.producesOutput ( ) ; // ... // do something with singleRow// ... GC.Collect ( ) }",Memory leaks while using array of double "C_sharp : A static constructor is executed the first time you access a static member . Knowing this , I have several questions : Does this mean that every time I access a static method , the runtime must check if the static constructor has been called ? Does this incur a performance hit ? Do `` constructor-less '' static classes avoid this performance hit ? [ EDIT ] : I would like to clarify that I 'm NOT concerned with micro-optimization.I am asking this question because it is a design decision . If a static constructor incurs a performance hit , then I will design my code with that in mind , and will be more aware of the decisions that may affect performance . Here 's an example to illustrate my question . Would there be any benefit of taking the Independent method and putting it in a separate static class ? That way , it would not have to check if static Test had been initialized . [ Update See my answer below for a better , simpler example ] .Here 's the quote from the C # specification about the static constructor : The execution of a static constructor is triggered by the first of the following events to occur within an application domain : An instance of the class is created . Any of the static members of the class are referenced . static class Test { // Static constructor with dependent method : static int x ; static Test ( ) { x = 5 ; } static int Dependent ( ) { return x ; } // Static , independent method : static int Independent ( int y ) { return y+1 ; } }",Can a static constructor reduce the performance of accessing static methods ? "C_sharp : I have a static method : And I need to be able to invoke it using a Type parameter calls to which could be numerous , so my standard pattern is to create a thread-safe cache of delegates ( using ConcurrentDictionary in .Net 4 ) which dynamically invoke the Foo < T > method with the correct T. Without the caching , though , the code is this : This is not the first time I 've had to do this - and in the past I have use Expression trees to build and compile a proxy to invoke the target method - to ensure that return type conversion and boxing from int - > object ( for example ) is handled correctly.Update - example of Expression code that worksWhat 's slightly amusing is that I learned early on with expressions that an explicit Convert was required and accepted it - and in lieu of the answers here it does now make sense why the .Net framework does n't automatically stick the equivalent in.End updateHowever , this time I thought I 'd just use Delegate.CreateDelegate as it makes great play of the fact that ( from MSDN ) : Similarly , the return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate , because this guarantees that the return value of the method can be cast safely to the return type of the delegate.Now - if I pass typeof ( string ) to LateFoo method , everything is fine.If , however , I pass typeof ( int ) I get an ArgumentException on the CreateDelegate call , message : Error binding to target method . There is no inner exception or further information.So it would seem that , for method binding purposes , object is not considered more restrictive than int . Obviously , this must be to do with boxing being a different operation than a simple type conversion and value types not being treated as covariant to object in the .Net framework ; despite the actual type relationship at runtime.The C # compiler seems to agree with this ( just shortest way I can model the error , ignore what the code would do ) : Does not compile because the Foo method 'has the wrong return type ' - given the CreateDelegate problem , C # is simply following .Net 's lead.It seems to me that .Net is inconsistent in it 's treatment of covariance - either a value type is an object or it 's not ; & if it 's not it should not expose object as a base ( despite how much more difficult it would make our lives ) . Since it does expose object as a base ( or is it only the language that does that ? ) , then according to logic a value type should be covariant to object ( or whichever way around you 're supposed to say it ) making this delegate bind correctly . If that covariance can only be achieved via a boxing operation ; then the framework should take care of that.I dare say the answer here will be that CreateDelegate does n't say that it will treat a box operation in covariance because it only uses the word 'cast ' . I also expect there are whole treatises on the wider subject of value types and object covariance , and I 'm shouting about a long-defunct and settled subject . I think there 's something I either do n't understand or have missed , though - so please enlighten ! If this is unanswerable - I 'm happy to delete . public class Example { //for demonstration purposes - just returns default ( T ) public static T Foo < T > ( ) { return default ( T ) ; } } static object LateFoo ( Type t ) { //creates the delegate and invokes it in one go return ( Func < object > ) Delegate.CreateDelegate ( typeof ( Func < object > ) , typeof ( Example ) .GetMethod ( `` Foo '' , BindingFlags.Public | BindingFlags.Static ) . MakeGenericMethod ( t ) ) ( ) ; } static object LateFoo ( Type t ) { var method = typeof ( Example ) .GetMethod ( `` Foo '' , BindingFlags.Public | BindingFlags.Static ) .MakeGenericMethod ( t ) ; //in practise I cache the delegate , invoking it freshly built or from the cache return Expression.Lambda < Func < IField , object > > ( Expression.Convert ( Expression.Call ( method ) , typeof ( object ) ) ) .Compile ( ) ( ) ; } public static int Foo ( ) { Func < object > f = new Func < object > ( Foo ) ; return 0 ; }","Delegate.CreateDelegate wo n't box a return value - deliberate , or an ommission ?" C_sharp : Is there a reasonably simple way to get FxCop to check that all my assemblies declare a particular attribute value ? I want to make sure everyone has changed the default you get on creating a project : [ assembly : AssemblyCompany ( `` Microsoft '' ) ] // fail [ assembly : AssemblyCompany ( `` FooBar Inc. '' ) ] // pass,FxCop : custom rule for checking assembly info values "C_sharp : Consider the following code : When I compile and run a RELEASE x86 build of this on Windows 7 x64 using Visual Studio 2010 , I get the following timings ( running on Intel Core i7 ) That in itself is odd - why would loop3 ( ) be so much slower than the other loops ? Anyway , I then uncomment the indicated line ( the Console.WriteLine ( ) ) , and my timings become : Now loop2 ( ) is far slower , and loop3 ( ) far quicker . I find this most curious ... So I have two questions : Can anyone else reproduce this , andIf so , can anyone explain it ? [ EDIT ] I should add that I can verify these timings with a stopwatch , and I am running the test program from the command-line ( so we can rule out Visual Studio interfering with it ) .ADDENDUM : I modified the program as follows to exclude the possibility that the JITTER is optimizing out the loops : Now my results are as follows : builder.AppendLine ( ) commented out : builder.AppendLine ( ) not commented out : Note the difference in the loop2 ( ) timing when I do that . Does not compute ! using System ; using System.Diagnostics ; namespace Demo { class Program { static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; for ( int trial = 0 ; trial < 4 ; ++trial ) { sw.Restart ( ) ; loop1 ( ) ; Console.WriteLine ( `` loop1 ( ) took `` + sw.Elapsed ) ; sw.Restart ( ) ; loop2 ( ) ; Console.WriteLine ( `` loop2 ( ) took `` + sw.Elapsed ) ; sw.Restart ( ) ; loop3 ( ) ; Console.WriteLine ( `` loop3 ( ) took `` + sw.Elapsed ) ; // Console.WriteLine ( ) ; // < -- Uncomment this and the timings change a LOT ! } } static void loop1 ( ) { bool done = false ; for ( int i = 0 ; i < 100000 & & ! done ; ++i ) { for ( int j = 0 ; j < 100000 & & ! done ; ++j ) { for ( int k = 0 ; k < 2 ; ++k ) { if ( i == 9900 ) { done = true ; break ; } } } } } static void loop2 ( ) { for ( int i = 0 ; i < 100000 ; ++i ) { for ( int j = 0 ; j < 100000 ; ++j ) { for ( int k = 0 ; k < 2 ; ++k ) { if ( i == 9900 ) { goto exit ; } } } } exit : return ; } static void loop3 ( ) { for ( int i = 0 ; i < 100000 ; ++i ) { for ( int j = 0 ; j < 100000 ; ++j ) { for ( int k = 0 ; k < 2 ; ++k ) { if ( i == 9900 ) { k = 2 ; j = 100000 ; i = 100000 ; } } } } } } } loop1 ( ) took 00:00:01.7935267loop2 ( ) took 00:00:01.4747297loop3 ( ) took 00:00:05.6677592loop1 ( ) took 00:00:01.7654008loop2 ( ) took 00:00:01.4818888loop3 ( ) took 00:00:05.7656440loop1 ( ) took 00:00:01.7990239loop2 ( ) took 00:00:01.5019258loop3 ( ) took 00:00:05.7979425loop1 ( ) took 00:00:01.8356245loop2 ( ) took 00:00:01.5688070loop3 ( ) took 00:00:05.7238753 loop1 ( ) took 00:00:01.8229538loop2 ( ) took 00:00:07.8174210loop3 ( ) took 00:00:01.4879274loop1 ( ) took 00:00:01.7691919loop2 ( ) took 00:00:07.4781999loop3 ( ) took 00:00:01.4810248loop1 ( ) took 00:00:01.7749845loop2 ( ) took 00:00:07.5304738loop3 ( ) took 00:00:01.4634904loop1 ( ) took 00:00:01.7521282loop2 ( ) took 00:00:07.6325186loop3 ( ) took 00:00:01.4663219 using System ; using System.Diagnostics ; using System.Text ; namespace Demo { class Program { static void Main ( string [ ] args ) { Console.WriteLine ( test ( ) ) ; } static string test ( ) { Stopwatch sw = new Stopwatch ( ) ; int total = 0 ; StringBuilder builder = new StringBuilder ( ) ; for ( int trial = 0 ; trial < 2 ; ++trial ) { sw.Restart ( ) ; total += loop1 ( ) ; builder.AppendLine ( `` loop1 ( ) took `` + sw.Elapsed ) ; sw.Restart ( ) ; total += loop2 ( ) ; builder.AppendLine ( `` loop2 ( ) took `` + sw.Elapsed ) ; sw.Restart ( ) ; total += loop3 ( ) ; builder.AppendLine ( `` loop3 ( ) took `` + sw.Elapsed ) ; //builder.AppendLine ( ) ; // Uncommenting this line makes a big difference ! } builder.AppendLine ( total.ToString ( ) ) ; return builder.ToString ( ) ; } static int loop1 ( ) { bool done = false ; int total = 0 ; for ( int i = 0 ; i < 100000 & & ! done ; ++i ) { for ( int j = 0 ; j < 100000 & & ! done ; ++j ) { for ( int k = 0 ; k < 2 ; ++k ) { if ( i == 9900 ) { done = true ; break ; } ++total ; } } } return total ; } static int loop2 ( ) { int total = 0 ; for ( int i = 0 ; i < 100000 ; ++i ) { for ( int j = 0 ; j < 100000 ; ++j ) { for ( int k = 0 ; k < 2 ; ++k ) { if ( i == 9900 ) { goto exit ; } ++total ; } } } exit : return total ; } static int loop3 ( ) { int total = 0 ; for ( int i = 0 ; i < 100000 ; ++i ) { for ( int j = 0 ; j < 100000 ; ++j ) { for ( int k = 0 ; k < 2 ; ++k ) { if ( i == 9900 ) { k = 2 ; j = 100000 ; i = 100000 ; } else { ++total ; } } } } return total ; } } } loop1 ( ) took 00:00:06.6509471loop2 ( ) took 00:00:06.7322771loop3 ( ) took 00:00:01.5361389loop1 ( ) took 00:00:06.5746730loop2 ( ) took 00:00:06.7051531loop3 ( ) took 00:00:01.5027345-1004901888 loop1 ( ) took 00:00:06.9444200loop2 ( ) took 00:00:02.8960563loop3 ( ) took 00:00:01.4759535loop1 ( ) took 00:00:06.9036553loop2 ( ) took 00:00:03.1514154loop3 ( ) took 00:00:01.4764172-1004901888",Adding a single Console.WriteLine ( ) outside a loop changes a loop 's timings - why ? "C_sharp : I have a small test application that executes two threads simultaneously . One increments a static long _value , the other one decrements it . I 've ensured with ProcessThread.ProcessorAffinity that the threads are associated with different physical ( no HT ) cores to force intra processor communication and I have ensured that they overlap in execution time for a significant amount of time.Of course , the following does not lead to zero : So , the logical conclusion would be to : Which of course leads to zero.However , the following also leads to zero : Of course , the lock statement ensures that the reads and writes are not reordered because it employs a full fence . However , I can not find any information concerning synchronization of processor caches . If there would n't be any cache synchronization , I 'd think I should be seeing deviation from 0 after both threads were finished ? Can someone explain to me how lock/Monitor.Enter/Exit ensures that processor caches ( L1/L2 caches ) are synchronized ? for ( long i = 0 ; i < 10000000 ; i++ ) { _value += offset ; } for ( long i = 0 ; i < 10000000 ; i++ ) { Interlocked.Add ( ref _value , offset ) ; } for ( long i = 0 ; i < 10000000 ; i++ ) { lock ( _syncRoot ) { _value += offset ; } }",How does the lock statement ensure intra processor synchronization ? "C_sharp : I 've found some strange behavior . If SelectedItem is SettingsItem then can not deselect it from codeXAML : CS : And that is all . I do n't understand why code does n't work for Settings Item and how to deal with this problem . < NavigationView Name= '' nv '' > < NavigationView.MenuItems > < NavigationViewItem Content= '' dsadas '' / > < NavigationViewItem Content= '' dsadas '' / > < NavigationViewItem Content= '' dsadas '' / > < NavigationViewItem Content= '' dsadas '' / > < /NavigationView.MenuItems > < Button Click= '' Button_Click '' Content= '' de select '' / > < /NavigationView > private void Button_Click ( object sender , RoutedEventArgs e ) { nv.SelectedItem = null ; }",NavigationView - When selected settings item there is no way to unselect it from code "C_sharp : Just for knowledge purposes , how can I verify that n methods are executing in parallel ? Is there a test that can assure me that DoSomething is n't executed sequentially ( If Console.WriteLine is n't a good test , what could be a very simple test function ? ) Parallel.For ( 0 , 10 , i = > DoSomething ( i ) ) ; ... void DoSomething ( int par ) { Console.WriteLine ( $ '' Test : { par } '' ) ; }",How to verify that n methods are executing in parallel ? "C_sharp : Right now I am studying the common design patterns and for the most part I understand the purpose of the decorator pattern . But what I do n't get is , what is the purpose of wrapping an existing object in a decorator class ? Consider this scenario , since Progress is part of the observer pattern , I want to limit the amount of updates to its subscribers to prevent the UI thread from locking.So I have decorated the class to only update once every 50 milliseconds.Both classes accomplish the same thing , except I find the first version better because it allows me to use the base constructor for setting the delegate for progress updates . The base class already supports overriding the method , so what is the need for me wrap the object ? Are both classes example of the decorator pattern ? I would much rather use the first option but I rarely see examples in that manner . public class ProgressThrottle < T > : Progress < T > { private DateTime _time = DateTime.Now ; public ProgressThrottle ( Action < T > handler ) : base ( handler ) { } protected override void OnReport ( T value ) { if ( DateTime.Now.AddMilliseconds ( 50 ) < _time ) { base.OnReport ( value ) ; _time = DateTime.Now ; } } } public class ProgressThrottle2 < T > : IProgress < T > { private DateTime _time = DateTime.Now ; private readonly IProgress < T > _wrapper ; public ProgressThrottle2 ( IProgress < T > wrapper ) { _wrapper = wrapper ; } public void Report ( T value ) { if ( DateTime.Now.AddMilliseconds ( 50 ) < _time ) { _wrapper.Report ( value ) ; _time = DateTime.Now ; } }","Decorator Pattern , via inheritance or dependency injection ?" "C_sharp : I 'm learning LINQ using the 101 LINQ Samples in the MSDN page and I came across this code : The purpose of this function is to `` use TakeWhile to return elements starting from the beginning of the array until a number is hit that is less than its position in the array . `` How exactly the n and index know which parameter to take ? ( i.e . how does n know it will take 5 , 4 , 1 , 3 , 9 , 8 , 6 , 7 , 2 , 0 and how does index know it will do an increment of 0 , 1 , 2 , 3 ... ) ? int [ ] numbers = { 5 , 4 , 1 , 3 , 9 , 8 , 6 , 7 , 2 , 0 } ; var firstSmallNumbers = numbers.TakeWhile ( ( n , index ) = > n > = index ) ; foreach ( var n in firstSmallNumbers ) { Console.WriteLine ( n ) ; }",How do lambda parameters map in TakeWhile ? "C_sharp : I am trying to search a paragraph for certain text with Regex . I 'd like the realist to return X number of words before and after and add highlights around all the occurrences of the text with.For Example : Consider the following paragraph . The result should have at least 10 characters before and after with no words cut off . The search term is `` dog '' . The Dog is a pet animal . It is one of the most obedient animals . There are many kinds of dogs in the world . Some of the are very friendly while some of them a dangerous . Dogs are of different color like black , red , white and brown . Some old them have slippery shiny skin and some have rough skin . Dogs are carnivorous animals . They like eating meat . They have four legs , two ears and a tail . Dogs are trained to perform different tasks . They protect us from thieves b ) guarding our house . They are loving animals . A dog is called man 's best friend . They are used by the police to find hidden things . They are one of the most useful animals in the world . Doggonit ! The result I desire is an array with that looks like the following : The Dog is a pet animalmany kinds of dogs in the worlddangerous . Dogs are of different rough skin . Dogs are carnivorousand a tail . Dogs are trainedanimals . A dog is calledthe world . Doggonit ! What I 've Got : I 've search around and have found the following regex that has perfectly returned the results as desired but without adding extra formatting . I created several methods to facilitate each functionality : And I can call it like : I do n't know yet the result of , or how to deal with , multiple occurrences of the word within the 10 characters . ie : if a sentence had `` A dog is a dog of course ! '' . I guess I can deal with that later.Tests : Issues : The function I created allows the search to find the searchTerm as a whole word only or part of the word.What I was doing was a simple Replace ( word , `` < strong > '' + word `` < /strong > '' ) on the results when displaying them . This works great if I was searching for parts of the word . But when searching for whole words , if the result included the searchTerm as part of the word , that part of the word would highlight.For example : if I was searching for `` dog '' and the result was : `` All dogs go to dog heaven . '' The highlighting would come out as `` All dogs go to dog heaven . '' But I want `` All dogs go to dog heaven . `` Question : The question is how can I get the matched word wrapped with some HTML like < strong > or anything else I 'd want ? private List < List < string > > Search ( string text , string searchTerm , bool searchEntireWord ) { var result = new List < List < string > > ( ) ; var searchTerms = searchTerm.Split ( ' ' ) ; foreach ( var word in searchTerms ) { var searchResults = ExtractParagraph ( text , word , sizeOfResult , searchEntireWord ) ; result.Add ( searchResults ) ; if ( searchResults.Count > 0 ) { foreach ( var searchResult in searchResults ) { Response.Write ( `` < strong > Result : < /strong > `` + searchResult + `` < br > '' ) ; } } } return result ; } private List < string > ExtractParagraph ( string text , string searchTerm , sizeOfResult , bool searchEntireWord ) { var result = new List < string > ( ) ; searchTerm = searchEntireWord ? @ '' \b '' + searchTerm + @ '' \b '' : searchTerm ; //var expression = @ '' ( ( ^. { 0,30 } |\w* . { 30 } ) \b '' + searchTerm + @ '' \b ( . { 30 } \w*| . { 0,30 } $ ) ) '' ; var expression = @ '' ( ( ^ . { 0 , '' + sizeOfResult + @ '' } |\w* . { `` + sizeOfResult + @ '' } ) '' + searchTerm + @ '' ( . { `` + sizeOfResult + @ '' } \w*| . { 0 , '' + sizeOfResult + @ '' } $ ) ) '' ; var wordMatch = new Regex ( expression , RegexOptions.IgnoreCase | RegexOptions.Singleline ) ; foreach ( Match m in wordMatch.Matches ( text ) ) { result.Add ( m.Value ) ; } return result ; } var text = `` The Dog is a pet animal . It is one of ... '' ; var searchResults = Search ( text , `` dog '' , 10 ) ; if ( searchResults.Count > 0 ) { foreach ( var searchResult in searchResults ) { foreach ( var result in searchResult ) { Response.Write ( `` < strong > Result : < /strong > `` + result + `` < br > '' ) ; } } } var searchResults = Search ( text , `` dog '' , 0 , false ) ; // should include only the matched wordvar searchResults = Search ( text , `` dog '' , 1 , false ) ; // should include the matched word and only one word preceding and following the matched word ( if any ) var searchResults = Search ( text , `` dog '' , 10 , false ) ; // should include the matched word and up to 10 characters ( but not cutting off words in the middle ) preceding and following it ( if any ) var searchResults = Search ( text , `` dog '' , 50 , false ) ; // should include the matched word and up to 50 characters ( but not cutting off words in the middle ) preceding and following it ( if any )",Highlight Words from a Regex Match "C_sharp : The step following the establishment of a connection with an anonymous pipe requires the server calling DisposeLocalCopyOfClientHandle . MSDN explains : The DisposeLocalCopyOfClientHandle method should be called after the client handle has been passed to the client . If this method is not called , the AnonymousPipeServerStream object will not receive notice when the client disposes of its PipeStream object.Trying to understand why would n't the server be noticed when client is closed , I went on to look at DisposeLocalCopyOfClientHandle on reference source : This sentence confused me : once the child handle is inherited , the OS considers the parent and child 's handles to be different.Are n't the parent 's handle and the child 's handle ( i.e. , the server 's m_handle and the server 's m_clientHandle , which is passed to the child ) different from the first place ? does `` different '' here mean `` references different objects '' ( this is the way I understand it ) , or does it have other meaning ? // This method is an annoying one but it has to exist at least until we make passing handles between// processes first class . We need this because once the child handle is inherited , the OS considers// the parent and child 's handles to be different . Therefore , if a child closes its handle , our // Read/Write methods wo n't throw because the OS will think that there is still a child handle around// that can still Write/Read to/from the other end of the pipe.//// Ideally , we would want the Process class to close this handle after it has been inherited . See// the pipe spec future features section for more information.// // Right now , this is the best signal to set the anonymous pipe as connected ; if this is called , we// know the client has been passed the handle and so the connection is live . [ System.Security.SecurityCritical ] public void DisposeLocalCopyOfClientHandle ( ) { if ( m_clientHandle ! = null & & ! m_clientHandle.IsClosed ) { m_clientHandle.Dispose ( ) ; } }",The need to call DisposeLocalCopyOfClientHandle ( ) after establishing a connection "C_sharp : In a text to speech application by C # I use SpeechSynthesizer class , it has an event named SpeakProgress which is fired for every spoken word . But for some voices the parameter e.AudioPosition is not synchronized with the output audio stream , and the output wave file is played faster than what this position shows ( see this related question ) .Anyway , I am trying to find the exact information about the bit rate and other information related to the selected voice . As I have experienced if I can initialize the wave file with this information , the synchronizing problem will be resolved . However , if I ca n't find such information in the SupportedAudioFormat , I know no other way to find them . For example the `` Microsoft David Desktop '' voice provides no supported format in the VoiceInfo , but it seems it supports a PCM 16000 hz , 16 bit format.How can I find audio format of the selected voice of the SpeechSynthesizer var formats = CurVoice.VoiceInfo.SupportedAudioFormats ; if ( formats.Count > 0 ) { var format = formats [ 0 ] ; reader.SetOutputToWaveFile ( CurAudioFile , format ) ; } else { var format = // How can I find it , if the audio has n't provided it ? reader.SetOutputToWaveFile ( CurAudioFile , format ) ; }",How can I find the audio format of the selected voice of the SpeechSynthesizer "C_sharp : I have an ASP.NET MVC application that displays a list of items . In my view page I loop over the items and render each item with partial view , like so : In the item view , I wrap each item with a form that has a 'Delete ' button , like this : The items are rendered properly , the resulting page has a nice list of all the items with their proper names and IDs displayed . EDIT : The same happens with @ Hidden , apparently , contrary to what I wrote before.In addition , this only happens the second time the form is rendered ( that is , after one of the Delete buttons is clicked ) , the first time everything is working properly . My action methods looks like this : Why is this happening ? @ foreach ( var item in Model.items ) { < li > @ Html.Partial ( `` ItemView '' , item ) < /li > } @ using ( Html.BeginForm ( ... ) ) { @ Html.HiddenFor ( m= > m.Id ) < label > @ Model.Name ( @ Model.Id ) < /label > < input type= '' submit '' value= '' Delete '' / > } public ActionResult AllItems ( ) { var model = new AllItemsModel ( ) ; return PartialView ( model ) ; } public ActionResult Delete ( DeleteModel model ) { ... . Perform the delete ... return PartialView ( `` AllItems '' , new AllItemsModel ( ) ) ; }",Html.HiddenFor binding to wrong element "C_sharp : I was adapting a simple prime-number generation one-liner from Scala to C # ( mentioned in a comment on this blog by its author ) . I came up with the following : It works , returning the same results I 'd get from running the code referenced in the blog . In fact , it works fairly quickly . In LinqPad , it generated the 100,000th prime in about 1 second . Out of curiosity , I rewrote it without Enumerable.Range ( ) and Any ( ) : Intuitively , I 'd expect them to either run at the same speed , or even for the latter to run a little faster . In actuality , computing the same value ( 100,000th prime ) with the second method , takes 12 seconds - It 's a staggering difference.So what 's going on here ? There must be fundamentally something extra happening in the second approach that 's eating up CPU cycles , or some optimization going on the background of the Linq examples . Anybody know why ? int NextPrime ( int from ) { while ( true ) { n++ ; if ( ! Enumerable.Range ( 2 , ( int ) Math.Sqrt ( n ) - 1 ) .Any ( ( i ) = > n % i == 0 ) ) return n ; } } int NextPrimeB ( int from ) { while ( true ) { n++ ; bool hasFactor = false ; for ( int i = 2 ; i < = ( int ) Math.Sqrt ( n ) ; i++ ) { if ( n % i == 0 ) hasFactor = true ; } if ( ! hasFactor ) return n ; } }",Enumerable.Range ( ... ) .Any ( ... ) outperforms a basic loop : Why ? "C_sharp : My application throw the exception occasionally : Exception type : InvalidOperationException Exception message : Collection was modified ; enumeration operation may not execute.And here 's stacktraceAnd here 's my code : Anybody can help ? it 's so weird ! Exception type : InvalidOperationException Exception message : Collection was modified ; enumeration operation may not execute . at System.Reflection.RuntimeAssembly._nLoad ( AssemblyName fileName , String codeBase , Evidence assemblySecurity , RuntimeAssembly locationHint , StackCrawlMark & stackMark , IntPtr pPrivHostBinder , Boolean throwOnFileNotFound , Boolean forIntrospection , Boolean suppressSecurityChecks ) at System.Reflection.RuntimeAssembly.InternalGetSatelliteAssembly ( String name , CultureInfo culture , Version version , Boolean throwOnFileNotFound , StackCrawlMark & stackMark ) at System.Resources.ManifestBasedResourceGroveler.GetSatelliteAssembly ( CultureInfo lookForCulture , StackCrawlMark & stackMark ) at System.Resources.ManifestBasedResourceGroveler.GrovelForResourceSet ( CultureInfo culture , Dictionary ` 2 localResourceSets , Boolean tryParents , Boolean createIfNotExists , StackCrawlMark & stackMark ) at System.Resources.ResourceManager.InternalGetResourceSet ( CultureInfo requestedCulture , Boolean createIfNotExists , Boolean tryParents , StackCrawlMark & stackMark ) at System.Resources.ResourceManager.InternalGetResourceSet ( CultureInfo culture , Boolean createIfNotExists , Boolean tryParents ) at System.Resources.ResourceManager.GetString ( String name , CultureInfo culture ) public IList < Function > MapWithLanguage ( IList < Function > list ) { if ( list == null ) { return null ; } var currentResource = Type.GetType ( `` Fanex.Athena.Models.ViewModel.Menu , Fanex.Athena.Models '' ) ; ResourceManager rm = new ResourceManager ( currentResource ) ; var newList = new List < Function > ( ) ; foreach ( var func in list ) { newList.Add ( new Function { Name = rm.GetString ( `` Menu_ '' + func.FunctionId ) , } ) ; } return newList ; }",InvalidOperationException When calling ResourceManager.GetString "C_sharp : I try parse a byte array to struct but it doesnt work with Sequential . The values are wrong in the Sequential struct but it work correct with Explicit struct ? I need sequential the byte array have no fix length . The DwLength field is the size of Data field.ValuesMessageType 128 ( Sequential 128 ) DwLength 20 ( Sequential 33554432 ) Slot 0 ( Sequential 0 ) Seq 0 ( Sequential 0 ) Status 2 ( Sequential 59 ) Error 0 ( Sequential 143 ) ChainParameter 0 ( Sequential 128 ) Test Codestruct RdrToPcDataBlock Sequentialstruct RdrToPcDataBlock ExplicitGetStruct var bytes = new byte [ ] { 0x80 , 0x14 , 0x00 , 0x00 , 0x00 , 0x00 , 0x00 , 0x02 , 0x00 , 0x00 , 0x3B , 0x8F , 0x80 , 0x01 , 0x80 , 0x4F , 0x0C , 0xA0 , 0x00 , 0x00 , 0x03 , 0x06 , 0x03 , 0x00 , 0x03 , 0x00 , 0x00 , 0x00 , 0x00 , 0x68 } ; var result1 = GetStruct < RdrToPcDataBlock1 > ( bytes ) ; var result2 = GetStruct < RdrToPcDataBlock2 > ( bytes ) ; [ StructLayout ( LayoutKind.Sequential ) ] public struct RdrToPcDataBlock1 { public byte MessageType ; public int DwLength ; public byte Slot ; public byte Seq ; public byte Status ; public byte Error ; public byte ChainParameter ; [ MarshalAs ( UnmanagedType.ByValArray ) ] public byte [ ] Data ; } [ StructLayout ( LayoutKind.Explicit ) ] public struct RdrToPcDataBlock2 { [ FieldOffset ( 0 ) ] public byte MessageType ; [ FieldOffset ( 1 ) ] public int DwLength ; [ FieldOffset ( 5 ) ] public byte Slot ; [ FieldOffset ( 6 ) ] public byte Seq ; [ FieldOffset ( 7 ) ] public byte Status ; [ FieldOffset ( 8 ) ] public byte Error ; [ FieldOffset ( 9 ) ] public byte ChainParameter ; [ FieldOffset ( 10 ) ] public byte Data ; } public T GetStruct < T > ( byte [ ] bytes ) { try { var handle = GCHandle.Alloc ( bytes , GCHandleType.Pinned ) ; var item = ( T ) Marshal.PtrToStructure ( handle.AddrOfPinnedObject ( ) , typeof ( T ) ) ; handle.Free ( ) ; return item ; } catch { return default ( T ) ; } }",C # parse bytes to struct sequential "C_sharp : Given a list of objects i need to return a list consisting of the objects and the sum of a property of the objects for all objects in the list seen so far . More generally givenI would like to have the output ofWhat is the `` right '' functional way to do this ? I can do it in a standard iterative approach of course but I am looking for how this would be done in a functional , lazy way.Thanks var input = new int [ ] { 1,2,3 } // does not compile but did not want to include extra classes.var output = { ( 1,1 ) , ( 2,3 ) , ( 3,6 ) } ;",How to get list of intermediate sums in a functional way ? Using LINQ ? "C_sharp : So I 've installed Nginx , Node.js and C # ASP.NET Core 2.1 on my virtual server ( virtualbox ) and currently running on each separate port.Node.js running on localhost:3000..NET Core running on localhost:5000.But then I want to make custom URI on this kind of case . If a user accesses the root site ( only `` / '' ) , then it will go to the Node.js application . And if a user accesses the another page ( in this case if a user access `` /api '' ) then I want a user to go into .NET Core application.Now if I access the root site , it works properly . An example I visit 192.168.56.2 ( this is my virtual server IP ) , then the browser will open Node.js application . But if I access 192.168.56.2/api , it returns 404 error code.Here 's my /etc/nginx/sites-available/default configuration : On my C # code , after I was generated the code with running dotnet new webapp -o mywebsite , I 'm not changing anything except the Properties/launchSettings.json ( I remove the localhost:5001 into only localhost:5000 ) .Did I misconfigure on the Nginx ? Or should I change something in my C # code ? server { listen 80 default_server ; listen [ : : ] :80 default_server ; root /var/www/html ; # Add index.php to the list if you are using PHP index index.html index.htm ; root /var/www/html ; server_name _ ; # Front-end : Node.js location / { proxy_pass http : //localhost:3000 ; proxy_http_version 1.1 ; proxy_set_header Upgrade $ http_upgrade ; proxy_set_header Connection 'upgrade ' ; proxy_set_header Host $ host ; proxy_cache_bypass $ http_upgrade ; } # Back-end : C # ASP.NET Core 2.1 location /api/ { proxy_pass http : //localhost:5000 ; proxy_http_version 1.1 ; proxy_set_header Upgrade $ http_upgrade ; proxy_set_header Connection keep-alive ; proxy_cache_bypass $ http_upgrade ; proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for ; proxy_set_header X-Forwarded-Proto $ scheme ; } }",How to Run C # ASP.NET Core 2.1 and Node.js with Different Ports in Nginx ? "C_sharp : Although this is a university assignment ( homework ) I 've come to the best solution I could think of . I would achieve full marks with this code as it matches the question , however I was specially allowed to develop it in C # rather than everyone else using Java , kind of a `` yeh , show what c # can do '' challenge ; - ) The question was : Create a program to find the password of a SHA1 hash using a brute force technique , assuming passwords are 6 characters long and can only contain lower-case a-z and 0-9.I created a LINQ query and after I have the possible combinations I need to run them through SHA1 to get a hash and compare it to the provided password hash.I created this code : Now my real problem is that it solved easy passwords quickly ( `` aaaaaa '' is instant ) but obviously takes longer the further the password is away from `` aaaaaa '' .I would hope someone could provide some pointers on how to increase the performance . public static string BruteForceHash ( string hash ) { var results = from c0 in Enumerable.Range ( 0 , 36 ) from c1 in Enumerable.Range ( 0 , 36 ) from c2 in Enumerable.Range ( 0 , 36 ) from c3 in Enumerable.Range ( 0 , 36 ) from c4 in Enumerable.Range ( 0 , 36 ) from c5 in Enumerable.Range ( 0 , 36 ) select new string ( new [ ] { Characters [ c0 ] , Characters [ c1 ] , Characters [ c2 ] , Characters [ c3 ] , Characters [ c4 ] , Characters [ c5 ] , } ) ; string found = null ; Parallel.ForEach ( results , ( result , loopstate , a ) = > { string hashed = SHA1 ( result , Encoding.Default ) ; if ( hashed == hash ) { found = result ; loopstate.Break ( ) ; } } ) ; if ( found ! = null ) { return found ; } return `` Not found . `` ; }",Performance tuning C # permutations and SHA1 code C_sharp : I have this method signature : List < ITMData > Parse ( string [ ] lines ) ITMData has 35 properties.How would you effectively test such a parser ? Questions : Should I load the whole file ( May I use System.IO ) ? Should I put a line from the file into a string constant ? Should I test one or more linesShould I test each property of ITMData or should I test the whole object ? What about the naming of my test ? EDIT I changed the method signature to ITMData Parse ( string line ) .Test Code : EDIT 2I am still not sure if I should test only one property per class . In my opinion this allows me to give more information for the specification namely that when I parse a single line from index 59 to index 79 I get fldName . If I test all properties within one class I loss this information . Am I overspecifying my tests ? My Tests now looks like this : [ Subject ( typeof ( ITMFileParser ) ) ] public class When_parsing_from_index_59_to_79 { private const string Line = `` ... ... ... '' ; private static ITMFileParser _parser ; private static ITMData _data ; private Establish context = ( ) = > { _parser = new ITMFileParser ( ) ; } ; private Because of = ( ) = > { _data = _parser.Parse ( Line ) ; } ; private It should_get_fldName = ( ) = > _data.FldName.ShouldBeEqualIgnoringCase ( `` HUMMELDUMM '' ) ; } [ Subject ( typeof ( ITMFileParser ) ) ] public class When_parsing_single_line_from_ITM_file { const string Line = `` '' static ITMFileParser _parser ; static ITMData _data ; Establish context = ( ) = > { _parser = new ITMFileParser ( ) ; } ; private Because of = ( ) = > { _data = _parser.Parse ( Line ) ; } ; It should_get_fld ? ? ? = ( ) = > _data.Fld ? ? ? .ShouldEqual ( ? ? ? ) ; It should_get_fld ? ? ? = ( ) = > _data.Fld ? ? ? .ShouldEqual ( ? ? ? ) ; It should_get_fld ? ? ? = ( ) = > _data.Fld ? ? ? .ShouldEqual ( ? ? ? ) ; It should_get_fld ? ? ? = ( ) = > _data.Fld ? ? ? .ShouldEqual ( ? ? ? ) ; It should_get_fld ? ? ? = ( ) = > _data.Fld ? ? ? .ShouldEqual ( ? ? ? ) ; It should_get_fld ? ? ? = ( ) = > _data.Fld ? ? ? .ShouldEqual ( ? ? ? ) ; It should_get_fld ? ? ? = ( ) = > _data.Fld ? ? ? .ShouldEqual ( ? ? ? ) ; ... },How to effectively test a fixed length flat file parser using MSpec ? "C_sharp : My application needs to review all new application Event Log entries as they come in . What I would like to know is what happens if another Entry is written to the EventLog while a previous Entry is being handled ? The documentation for EventLog.EntryWritten Event provides an example of handling an entry written event which uses threading ( which is why I am asking the question ) . In this example they use System.Threading and call the WaitOne ( ) and Set ( ) methods on the AutoResetEvent class , however I 'm not sure precisely what this code is intended to achieve . The documentation states that - WaitOne ( ) `` blocks the current thread until the current WaitHandle receives a signal '' , and that Set ( ) `` sets the state of the event to signaled , allowing one or more waiting threads to proceed '' . I 'm not sure what the threading portion of this example is intended to demonstrate , and how this relates to how ( or if ) it needs to be applied in practice.It appears that WaitOne ( ) blocks the thread immediately after the entry has been written , until it has been handled , where it is then set to signalled ( using Set ( ) ) , before allowing the thread to proceed . Is this the one and only thread for the application ? Most importantly , when my application is not responsible for writing the the events which need to be read from the EventLog , how should this principle be applied ? ( If , indeed , it needs to be applied . ) What does happen if a new Entry is written while the application is inside the handler ? private void eventLog_Application_EntryWritten ( object sender , EntryWrittenEventArgs e ) { // Process e.Entry }",What happens if a new Entry is written to the Event Log while the application is inside the handler for a previous entry being written ? "C_sharp : By using include tag I am trying to put comments for my code in separate file `` docs.xml '' .But it does not work . I have been trying both C # and VB.NET projects . Here is my comments file : I have a class ABC with one single property Demo . before this property I write : or in VB.NET : However summary for ABC.Demo never appears in InteliSense / Object browser / another project ( if I reference my project ) .I have a strong feeling I am missing something here.P.S . I have tried following `` path [ @ name= ] '' pattern of XML file , but it does not help . < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < d > < summary > Demo summary < /summary > < /d > /// < include file= '' docs.xml '' path= '' d/* '' / > `` ' < include file= '' docs.xml '' path= '' d/* '' / >",Visual Studio XML external comments file does not work "C_sharp : In my project I have implemented custom routing constraints to allow for API versioning via a custom header variable ( api-version ) , similar to this sample project on Codeplex , although I modified the constraint to allow for a major.minor convention.This involves creating two separate controllers whose routes are differentiated via a FullVersionedRoute attribute : Sample1Controller.csSample2Controller.csFullVersionedRoute.csFullVersionConstraint.csThis works just fine , but the auto-generated help files ca n't differentiate between the actions in the two controllers as they look like the same route ( if you only pay attention to the url route , whic it does by default ) . As such , the action from Sample2Controller.cs overwrites the action from Sample1Controller.cs so only the Sample2 API is displayed on the help pages.Is there a way to configure the Web API Help Page package to recognize a Custom Constraint and recognize that there are two , separate APIs , and subsequently display them as separate API groups on Help Pages ? /// < summary > /// v1.0 Controller/// < /summary > public class Sample1Controller : ApiController { [ FullVersionedRoute ( `` api/test '' , `` 1.0 '' ) ] public IEnumerable < string > Get ( ) { return new [ ] { `` This is version 1.0 test ! '' } ; } } /// < summary > /// v2.0 Controller/// < /summary > public class Sample2Controller : ApiController { [ FullVersionedRoute ( `` api/test '' , `` 2.0 '' ) ] public IEnumerable < string > Get ( ) { return new [ ] { `` This is version 2.0 test ! '' } ; } } using System.Collections.Generic ; using System.Web.Http.Routing ; namespace HelperClasses.Versioning { /// < summary > /// Provides an attribute route that 's restricted to a specific version of the api . /// < /summary > internal class FullVersionedRoute : RouteFactoryAttribute { public FullVersionedRoute ( string template , string allowedVersion ) : base ( template ) { AllowedVersion = allowedVersion ; } public string AllowedVersion { get ; private set ; } public override IDictionary < string , object > Constraints { get { var constraints = new HttpRouteValueDictionary ( ) ; constraints.Add ( `` version '' , new FullVersionConstraint ( AllowedVersion ) ) ; return constraints ; } } } } using System.Collections.Generic ; using System.Linq ; using System.Net.Http ; using System.Web.Http.Routing ; namespace HelperClasses.Versioning { /// < summary > /// A Constraint implementation that matches an HTTP header against an expected version value . /// < /summary > internal class FullVersionConstraint : IHttpRouteConstraint { public const string VersionHeaderName = `` api-version '' ; private const string DefaultVersion = `` 1.0 '' ; public FullVersionConstraint ( string allowedVersion ) { AllowedVersion = allowedVersion ; } public string AllowedVersion { get ; private set ; } public bool Match ( HttpRequestMessage request , IHttpRoute route , string parameterName , IDictionary < string , object > values , HttpRouteDirection routeDirection ) { if ( routeDirection == HttpRouteDirection.UriResolution ) { var version = GetVersionHeader ( request ) ? ? DefaultVersion ; return ( version == AllowedVersion ) ; } return false ; } private string GetVersionHeader ( HttpRequestMessage request ) { IEnumerable < string > headerValues ; if ( request.Headers.TryGetValues ( VersionHeaderName , out headerValues ) ) { // enumerate the list once IEnumerable < string > headers = headerValues.ToList ( ) ; // if we find once instance of the target header variable , return it if ( headers.Count ( ) == 1 ) { return headers.First ( ) ; } } return null ; } } }",Getting Web API Help Pages to Work with Custom Routing Constraints "C_sharp : Considering the following example : Until recently , I was under the impression that , as long as FirstThread ( ) really did execute before SecondThread ( ) , this program could not output anything but 1.However , my understanding now is that : Volatile.Write ( ) emits a release fence . This means no preceding load or store ( in program order ) may happen after the assignment of 1 to sharedState.Volatile.Read ( ) emits an acquire fence . This means no subsequent load or store ( in program order ) may happen before the copying of sharedState to sharedStateSnapshot.Or , to put it another way : When sharedState is actually released to all processor cores , everything preceding that write will also be released , and , When the value in the address sharedStateSnapshot is acquired ; sharedState must have been already acquired.If my understanding is therefore correct , then there is nothing to prevent the acquisition of sharedState being 'stale ' , if the write in FirstThread ( ) has not already been released.If this is true , how can we actually ensure ( assuming the weakest processor memory model , such as ARM or Alpha ) , that the program will always print 1 ? ( Or have I made an error in my mental model somewhere ? ) private int sharedState = 0 ; private void FirstThread ( ) { Volatile.Write ( ref sharedState , 1 ) ; } private void SecondThread ( ) { int sharedStateSnapshot = Volatile.Read ( ref sharedState ) ; Console.WriteLine ( sharedStateSnapshot ) ; }",Volatile fields : How can I actually get the latest written value to a field ? C_sharp : I am trying to get Visual Studio 2015 ( 14.0 ) to use auto properties when implementing an interface using refactoring for C # .I.e . I want this ; as opposed to this ; I have accomplished this in past versions of Visual Studio by editing the code snippet file ( instructions here ) but I can not get this to work using Visual Studio 2015 . public object SomeProperty { get ; set ; } public object SomeProperty { get { throw new NotImplementedException ( ) ; } set { throw new NotImplementedException ( ) ; } },Refactoring `` Implement Interface '' using auto properties VS2015 "C_sharp : In an ASP.NET application ( C # ) we are using Postgres as backend and Npgsql as data provider . A couple of days ago we had a serious problem with loss of data . I investigated in code and found code like this : Someone insisted that Npgsql would handle exception by its own and would automatically rollback the transaction in case something went wrong during the transactions.In my opinion this is quite optimistic , and the code should be wrapped in a try and catch block and call a transaction rollback explicitly : Is that wrong ? Moreover , will a transaction rollback always work ? I read somewhere that it will only work if a Postgres exception is raised , say in case of malformed sql , but it will not work in case of other kind of exceptions . Can someone clarify this point too ? var transaction = connection.BeginTransaction ( ) ; //some crud operation here transaction.Commit ( ) var transaction = connection.BeginTransaction ( ) ; try { //some crud operation here transaction.Commit } catch ( Exception ex ) { transaction.Rollback ( ) ; }",How does Npgsql handle failed transactions ? "C_sharp : I have a problem with a C # program that includes the following : When running this code , childInstance becomes null.I tried below assignment with explicit cast , but ended with an exception : Child childInstance = ( Child ) Child.ParseFromA ( @ '' path/to/Afile '' ) ; Since I want to parse some types of files into Parent and Child instance , I want to keep the design that generates instances by static methods.How should I get a proper childInstance ? class Program { static void Main ( string [ ] args ) { Child childInstance = Child.ParseFromA ( @ '' path/to/Afile '' ) as Child ; } } class Parent { int property ; public static Parent ParseFromA ( string filename ) { Parent parent = new Parent ( ) ; // parse file and set property here ... return parent ; } } class Child : Parent { public void SomeAdditionalFunction ( ) { } }",How can I downcast an instance generated by static method ? "C_sharp : I am currently in the process of setting up push notifications for our app written in Unity ( C # ) . Code in draft below . ( In summary : I get a user 's current time at which he has logged in , and assign that time as the push notification time for its corresponding day of the week . If there are null times in other days of the week ( 0-6 ) , I assign this time to those as well ; otherwise , they are left alone as they have in that case been previously assigned the appropriate time for the day . ) Now , I set up the notification trigger for the day , hour , and minute of the next notification , and set `` Repeats '' to true . In documentation it states that the notification will be repeated every `` defined time period '' -- so therefore I assume , e.g. , if I have set Day to February 6 , and hour and minute to 12:34p that this will repeat every February 6th at 12:34p.What I would like is to have notifications repeat on a weekly basis . This was simple in Xcode because you could set a `` Weekday '' as opposed to a specific day , as is the case here . Is there any solution to making a notification repeat by day of the week ? private void IOSNotificationManager ( ) { // determine whether user has already allowed or disallowed notifications -- wo n't run again if user has already made decision StartCoroutine ( RequestAuthorization ( ) ) ; // Schedule daily notification for user based on time of play // iOS uses local time , while Android uses UTC DateTime userTime = DateTime.Now ; // Set a reminder for this specific day of the week ( 0 = Sunday , 6 = Saturday ) . // Note that this will overwrite any previous time set for this day . GameData.PushNotificationTimes [ ( int ) userTime.DayOfWeek ] = userTime ; // Schedule the week of push notifications for days that have n't already been scheduled for ( var i = 0 ; i < 7 ; i++ ) { if ( GameData.PushNotificationTimes [ i ] == null ) { // get the number of days after which the notification should occur int daysToNotification = ( i - ( int ) userTime.DayOfWeek + 7 ) % 7 ; DateTime nextDay = userTime.AddDays ( daysToNotification ) ; GameData.PushNotificationTimes [ i ] = nextDay ; } Debug.Log ( `` The push notification time scheduled for day `` + i + `` is `` + GameData.PushNotificationTimes [ i ] ) ; } for ( var i = 0 ; i < 7 ; i++ ) { DateTime pushNotificationTime = GameData.PushNotificationTimes [ i ] ; var calendarTrigger = new iOSNotificationCalendarTrigger ( ) { Day = pushNotificationTime.Day , Hour = pushNotificationTime.Hour , Minute = pushNotificationTime.Minute , // Indicate whether the notification is repeated every defined time period . // For instance if hour and minute fields are set the notification will be triggered every day at the specified hour and minute . Repeats = true } ; } }","How can I set a weekly repeat push notifications in Unity ( C # , currently targeting iOS ) ?" "C_sharp : I ’ m trying to automate linking the NetSuite purchase order to a NetSuite sale order and the following is the code I tried to accomplish this task . But I 'm getting error ( see at the bottom ) . Can you please check and let me know what I ’ m missing here ? Purchase Order Creation code : Code I 'm using to Update Purchase Order Number in Sales Order : But I get the follwoing Error : You do not have permissions to set a value for element createPOSpecified due to one of the following reasons : 1 ) The field is read-only ; 2 ) An associated feature is disabled ; 3 ) The field is available either when a record is created or updated , but not in both cases.Note : createPOSpecified is not displayed in the sales order screen in NetSuite . When I try to update a field in the sales order which exist in the form , then I am able to update it successfully but the field I am trying to update ( createPOSpecified ) is not available in this sales form . In this case how can I update this ? Also is this the better way of linking the purchase order with sales order ? Thanks , Hemant.Updated 25-May-2020 ( Responding to Anand Rajaram ) We are using the ADMINISTRATOR role for creating purchase order and linking that to sales order . A user with this role has been provided by our client and we don ’ t have permission to see fields that are displayed in the screen and have been restricted for EDIT . But we are able to edit most of the field displayed in the screen.createPOSpecified is not a custom field . It ’ s a property in the SALESORDETITEM class . It will not be displayed in any sales order form.If this is the proper code for creating purchase order and linking that to sales order , then I have few queries:3.1 When we create purchase order through NetSuite by clicking the dropship link in the sales order item grid , we are able to see Mark Shipped button . But when we create purchase order through code , it is displaying the Receive button and there was no changes in the purchase order status.This field is not displaying when we are creating purchase order through code . We have provided information for createdFrom property , but not sure why it is not displayingWe assume this is the field that helps to link with sales order . We have provided this information while creating item fulfillment and vendor bill and these are properly linked with sales order , but we are not sure why purchase order is not getting linked with sales order.Finally on the below comments which you have provided Which is basically having a custom transaction body field on Sales Order form , and once PO is created , update the newly created PO in Sales Order field.We don ’ t have any custom transaction body field in our sales order form for providing purchase order . But once purchase order is created through NetSuite , purchase order number will be displayed in the sales order item grid.So all this boils down to : what is that we have missed in the code and what is that we have to fix to display the `` Mark Shipped '' button , “ Created From '' label and linking Purchase Order to Sales Order.Thanks , Hemant . var createPurchaseOrder = new PurchaseOrder ( ) ; createPurchaseOrder.entity = new RecordRef ( ) { internalId = “ 653 ” //type = RecordType.purchaseOrder , //typeSpecified = true } ; RecordRef soRecordRef = new RecordRef ( ) ; soRecordRef.internalId = “ XXXXXXXX ” ; soRecordRef.type = RecordType.salesOrder ; soRecordRef.typeSpecified = true ; createPurchaseOrder.createdFrom = soRecordRef ; RecordRef depRecordRef = new RecordRef ( ) ; depRecordRef.internalId = “ 3 ” ; depRecordRef.name = “ eBay : eBay FNC ” ; depRecordRef.type = RecordType.department ; depRecordRef.typeSpecified = true ; createPurchaseOrder.department = depRecordRef ; PurchaseOrderItem [ ] Items = new PurchaseOrderItem [ 1 ] ; Items [ 0 ] = new PurchaseOrderItem ( ) ; RecordRef item = new RecordRef ( ) ; item.type = RecordType.nonInventoryPurchaseItem ; item.typeSpecified = true ; item.internalId = “ XXXXX ” ; Items [ 0 ] .item = item ; Items [ 0 ] .rate = “ 5 ” ; Items [ 0 ] .quantity = 1 ; Items [ 0 ] .quantitySpecified = true ; PurchaseOrderItemList purchaseOrderItemList = new PurchaseOrderItemList ( ) ; purchaseOrderItemList.item = Items ; createPurchaseOrder.itemList = purchaseOrderItemList ; WriteResponse response = Service.add ( createPurchaseOrder ) ; var updateSalesOrder = new SalesOrder ( ) ; updateSalesOrder.internalId = “ XXXXXXXX ” ; SalesOrderItem [ ] soItems = new SalesOrderItem [ 1 ] ; var soItem = new SalesOrderItem ( ) ; RecordRef roItem = new RecordRef ( ) ; roItem.type = RecordType.inventoryItem ; roItem.typeSpecified = true ; roItem.internalId = “ XXXXX ” ; soItem.item = roItem ; RecordRef prLevel = new RecordRef ( ) ; prLevel.type = RecordType.priceLevel ; prLevel.internalId = “ -1 ” ; prLevel.typeSpecified = true ; soItem.price = prLevel ; soItem.rate = “ 15 ” ; soItem.quantity = 1 ; soItem.quantitySpecified = true ; RecordRef poItem = new RecordRef ( ) ; poItem.type = RecordType.purchaseOrder ; poItem.typeSpecified = true ; poItem.internalId = purchaseOrder.internalId ; soItem.createdPo = poItem ; soItems [ 0 ] = soItem ; SalesOrderItemList salesOrderItemList = new SalesOrderItemList ( ) ; salesOrderItemList.item = soItems ; updateSalesOrder.itemList = salesOrderItemList ; response = Service.update ( updateSalesOrder ) ; if ( response.status.isSuccess ! = true ) throw new Exception ( response.status.statusDetail [ 0 ] .message ) ; 3.2 **createdFrom** field is displaying as below when we create purchase order through netsuite .",Netsuite : How to link Purchase Order to Sales Order "C_sharp : I consume a web service which returns me some dates as string , and I use DateTime.Parse to get the correspondente DateTime objects . It is working , but I 'm afraid my usage of DateTime.Parse may be vulnerable to bugs caused by different locale settings . The date returned is in the following format : The code I use to parse it : Is there some way ( such as passing a format provider , or using another method ) in which I guarantee that my parsing routine will work regardless of the machine locale settings ? 2014-04-24T00:00:00 DateTime d = DateTime.Parse ( strValue ) ;",How to correctly parse a DateTime in this format : `` 2013-04-29T00:00:00 '' "C_sharp : Say I have a byte array with 100,000 bytes in it . I want to convert each byte into its textual representation of itself . For example : The above code takes around 35 seconds to complete , is there some way I could cut that down to around 5 seconds ? byte [ ] b = new byte [ 55000 ] ; for ( int i = 0 ; i < b.Length ; i++ ) { Console.WriteLine ( ConvertToString ( b [ i ] ) ) ; }",Is there a faster way to loop through thousands of items ? "C_sharp : I 'm making a program in C # that receive sms and display to the user , and I 'm having a problem with the sort of the data . For example , if the user sort the table by ids , from the higher id to the lower so when a new sms arrives it gets on the top of the table , the new sms will get to the bottom of the table anyway.Here is a screenshotAs you can see , the id 125 is under the 0 instead of being on the top of the table ... Is there any code or event that I should use ? There is where I want to start that event : Thank you once more Edper for your help ! There is when I add the message in the program : And the AddTable method : If you want to now also the point of it , this is a program for show Messages in a screen , for example , in a disco , the users send messages from the mobile to a number connected by a model to a PC and the messages will show on it , actually I 'm testing it in a friends disco.Thank you again for the help ! Edit : Added a bounty of 50 reputation for who can help me fix the table . public void readSms ( ) { try { comm = AppData.getInstance ( ) .getComm ( ) ; DecodedShortMessage [ ] messages = comm.ReadMessages ( PhoneMessageStatus.All , `` SM '' ) ; foreach ( DecodedShortMessage message in messages ) { if ( AppData.getInstance ( ) .mensagens.Count ! = 0 ) { Message msg = new Message ( AppData.getInstance ( ) .messages.Last.Value.getId ( ) + 1 , ( ( SmsDeliverPdu ) ( message.Data ) ) .OriginatingAddress , message.Data.UserDataText , ( ( SmsDeliverPdu ) ( message.Data ) ) .SCTimestamp.ToDateTime ( ) , false ) ; AppData.getInstance ( ) .setMensagem ( msg ) ; } else { Message msg = new Message ( 0 , ( ( SmsDeliverPdu ( message.Data ) ) .OriginatingAddress , message.Data.UserDataText , ( ( SmsDeliverPdu ) ( message.Data ) ) .SCTimestamp.ToDateTime ( ) , false ) ; AppData.getInstance ( ) .setMensagem ( msg ) ; } } // I need to put the event of sorting here in case any message was been added } catch ( Exception ex ) { MessageBox.Show ( ex.Message ) ; } } public void preencherTabela ( int lastIndex ) { LinkedList < Message > messages = AppData.getInstance ( ) .getMessagessList ( ) ; { addTable ( messages.ElementAt ( i ) .getId ( ) , messages.ElementAt ( i ) .getChecked ( ) , messages.ElementAt ( i ) .getMsg ( ) , messages.ElementAt ( i ) .getNum ( ) , messages.ElementAt ( i ) .getDate ( ) ) ; } } private void addTable ( int p , bool p_2 , string p_3 , string p_4 , DateTime dateTime ) { this.dataGridView1.Invoke ( new MethodInvoker ( ( ) = > { this.dataGridView1.Rows.Add ( p , p_2 , p_3 , p_4 , dateTime ) ; } ) ) ; }",DataGridView auto re-sort "C_sharp : Summary Of Problem : I have a console app that , after copying many folders and files over to a new location , a local drive , it then deletes certain files/folders . One of these filetypes it deletes is .exe files . When trying to delete said files it gives me a denied access error . ( This also occurs while trying to delete other kinds of files and folders as well ) Other Notes : I saw several questions , such as Unable to delete .exe file through c # . However the process was never running on my local machine nor on the source it was copied from . I am both a local administrator and a domain administrator on our domain , and I had ownership over all folders and files in the directories I 'm working with . But it still denies me access when trying to delete the file from code . I am however able to delete such files/folders manually . ( click delete key ) Problem : As stated above I am looking for a way to get past this issue denying me access to delete these `` Illegal '' file types and delete them from my code.My Code : ( Updated ) Any help would be greatly appreciated . If this question has been directly answered elsewhere please feel free to mention it in the comment . As I stated above I have been looking through past question regarding this issue and have not found a solution as of yet . Otherwise thank you for your help . # region Delete_Illegal_Items public static void RemoveIllegalItems ( ) { Console.Clear ( ) ; DirectoryInfo Libraries = new DirectoryInfo ( Library.DestinationMain ) ; try { foreach ( var Lib in Libraries.GetDirectories ( ) ) { Console.WriteLine ( `` Working On { 0 } . `` , Lib.Name ) ; Parallel.Invoke ( ( ) = > { RemoveBadFiles ( Lib ) ; } , ( ) = > { DeleteEmptyFolders ( Lib ) ; } ) ; } } catch ( AggregateException e ) { Console.WriteLine ( `` There Was An Unusual Error During Initialization Of Library Correction : \n { 0 } '' , e.InnerException.ToString ( ) ) ; } } private static string [ ] BadFiles = { @ '' .hta '' , @ '' .exe '' , @ '' .lnk '' , @ '' .tmp '' , @ '' .config '' , @ '' .ashx '' , @ '' .hta . `` , @ '' .hta : : $ DATA '' , @ '' .zip '' , @ '' .asmx '' , @ '' .json '' , @ '' .soap '' , @ '' .svc '' , @ '' .xamlx '' , @ '' .msi '' , @ '' .ops '' , @ '' .pif '' , @ '' .shtm '' , @ '' .shtml '' , @ '' smt '' , @ '' .vb '' , @ '' .vbe '' , @ '' .vbs '' , @ '' .ds_store '' , @ '' .db '' , @ '' .ini '' , @ '' .tiff '' } ; private static void RemoveBadFiles ( DirectoryInfo directory ) { DirectoryInfo [ ] dirs = null ; FileInfo [ ] files = null ; if ( directory ! = null ) { files = directory.GetFiles ( ) ; } try { dirs = directory.GetDirectories ( ) ; } catch ( IOException ) { } catch ( Exception e ) { Console.WriteLine ( `` \nError During Enumeration Of Items To Delete : \n { 0 } '' , e.Message ) ; } if ( files ! = null ) { foreach ( var file in files ) { try { if ( file.IsReadOnly ) { file.IsReadOnly = false ; } if ( BadFiles.Contains ( Path.GetExtension ( file.FullName ) ) ) { File.Delete ( file.FullName ) ; } } catch ( Exception e ) { Console.WriteLine ( `` \nError During Removal Or Illegal Files : \n '' + e.Message ) ; } } } if ( dirs ! = null ) { foreach ( var dir in dirs ) { switch ( dir.Name ) { case `` .TemporaryItems '' : { try { Directory.Delete ( dir.FullName ) ; } catch { } break ; } case `` AI_RecycleBin '' : { try { Directory.Delete ( dir.FullName ) ; } catch { } break ; } case `` .ToRemove '' : { try { Directory.Delete ( dir.FullName ) ; } catch { } break ; } default : { break ; } } RemoveBadFiles ( dir ) ; } } } private static void DeleteEmptyFolders ( DirectoryInfo directory ) { Program Main = new Program ( ) ; try { DirectoryInfo [ ] dirs = directory.GetDirectories ( ) ; foreach ( var subDirectory in dirs ) { int sum = Library.CountLibrary ( subDirectory.FullName ) ; if ( sum == 0 ) { Directory.Delete ( subDirectory.FullName ) ; } DeleteEmptyFolders ( subDirectory ) ; } } catch { } } # endregion",Access Denied While Deleting .exe File "C_sharp : Apologies for the essay-like nature of this question . I have been struggling to get to grips with this and have tried to sum up my understanding of what is needed , with the specific questions I have.In this question relating to reading data from a European DTCO company card , I was given advice that involved following the algorithm in the screenshot below ( from Appendix 11 of this document ) but I 'm not clear how to perform the two highlighted steps.I see that Sign is a segment of the array containing the certificate but what does it mean to open it with the public key ? I can successfully perform the step before by reading CA_Certificate from the card and issuing a MANAGE SECURITY ENVIRONMENT APDU using CAR´ ( see first step of algorithm ) from it . But having selected the public key that way , what public key do I use in the open Sign step . The MSE selects one but I do n't have it ; I have only the European public key from ERCA , but is that the same key I have selected in the card ? I do n't have any private keys , but would I need them.In the step for checking that Hash ( C´ ) = H´ , how should I calculate the hash ? There seem to be so many different ways ( is formats the right word ? ) of doing encryption/decryption/hashing that I 'm quite confused.All I really need to be able to do to read the data I need is to authenticate using EXTERNAL AUTHENTICATE , immediately after a GET CHALLENGE that returns an 8 byte challenge . I presume I need to use that to calculate the cipher for the EXTERNAL AUTHENTICATE . I found the sample code below ( see full post ) and although it appears to be in some C-like scripting language ( I 'm using C # ) and for a different type of smartcard it seems quite similar to what I must use.Differences areThe additional P2 parameter indicating that MANAGE SECURITY ENVIRONMENT has been done , presumably with the CAR´ from Card_Certificate , which does n't work for me , though it does with the CAR´ from CA_Certificate.Lc of 0x80 instead of the 0x81 in the sample code.Any cipher I calculate to use here would have to be 128 bytes long while it 's unclear of the cipher length in the sample . //// Authenticate against CardOS card//var card = new Card ( _scsh3.reader ) ; var crypto = new Crypto ( ) ; var key = new Key ( ) ; key.setComponent ( Key.DES , new ByteString ( `` 01010101010101010101010101010101 '' , HEX ) ) ; // Get challengevar challenge = card.sendApdu ( 0x00 , 0x84 , 0x00 , 0x00 , 8 , [ 0x9000 ] ) ; // Crypto.DES_MAC_EMV is a CBC generated Retail-MACvar cipher = crypto.sign ( key , Crypto.DES_MAC_EMV , challenge ) ; card.sendApdu ( 0x00 , 0x82 , 0x00 , 0x81 , cipher ) ; print ( `` Card returns `` + card.SW.toString ( 16 ) + `` - `` + card.SWMSG ) ;",Need advice on cryptographic algorithm "C_sharp : Problem : I am trying to manually Validate some c # objects , and the Validator is ignoring string length related validations.Test Case : extending this example which uses the [ Required ] attribute , i also wanted to validate that strings were not too long , as follows.Expected result : an error : `` difficulty is too long . `` Actual result : 'is valid'other things tested : the validator is working , uncommenting the [ Required ] results in the message `` The Name field is required . '' using [ StringLength ] instead ( as noted at https : //stackoverflow.com/a/6802739/432976 ) made no difference . public class Recipe { // [ Required ] public string Name { get ; set ; } [ MaxLength ( 1 ) ] public string difficulty = `` a_string_that_is_too_long '' ; } public static void Main ( string [ ] args ) { var recipe = new Recipe ( ) ; var context = new ValidationContext ( recipe , serviceProvider : null , items : null ) ; var results = new List < ValidationResult > ( ) ; var isValid = Validator.TryValidateObject ( recipe , context , results ) ; if ( ! isValid ) { foreach ( var validationResult in results ) { Console.WriteLine ( validationResult.ErrorMessage ) ; } } else { Console.WriteLine ( `` is valid '' ) ; } }",Validator ignoring MaxLength attributes "C_sharp : I have the fallowing FluentNHibernate-Mapping : And this is the Property in the Entity for Discount : But the Schema ( for SQL-Server ) , which NHibernate is creating , contains now : Can someone help me , what is going wrong ? this.Map ( x = > x.Discount ) .Precision ( 8 ) .Scale ( 2 ) .Not.Nullable ( ) ; public virtual Decimal Discount { get ; set ; } Discount NUMERIC ( 19 , 0 ) not null ,",NHibernate is not respecting precision and scale for creating numeric-column ( for a decimal ) "C_sharp : I am wondering how a piece of locked code can slow down my code even though the code is never executed . Here is an example below : This code runs in ~1300ms on my machine . If we remove the lock block ( but keep its body ) , we get 750ms . Almost the double , even though the code is never run ! Of course this code does nothing . I noticed it while adding some lazy initialization in a class where the code checks if the object is initialized and if not initializes it . The problem is that the initialization is locked and slows down everything even after the first call.My questions are : Why is this happening ? How to avoid the slowdown public void Test_PerformanceUnit ( ) { Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; Random r = new Random ( ) ; for ( int i = 0 ; i < 10000 ; i++ ) { testRand ( r ) ; } sw.Stop ( ) ; Console.WriteLine ( sw.ElapsedTicks ) ; } public object testRand ( Random r ) { if ( r.Next ( 1 ) > 10 ) { lock ( this ) { return null ; } } return r ; }",How to avoid slowdown due to locked code ? "C_sharp : Not sure how else to explain this , so the title pretty much describes the problem.Random is not being re-initialised every part of the loop . It 's a static member of a class which I always call on from other classes.I am not using a custom seed.The initialisation code is : This ( I am aware this is not a great way - it 's rudimentary and temporary ) generates a tree.However my terrain often looks something like this , with many clustered trees : ☁☁☁☁☁☁☁☁☁☁Can anyone give insight into why this is happening ? Is there a better alternative than using the System.Security.Cryptography.Random class ? I 'd expect an average of 9 gap per tree , but it 's more like 7 and then 3 trees closely clustered together . public static Random random = new Random ( ) ; for ( int x = 0 ; x < 75 ; x++ ) { if ( main.random.Next ( 11 ) == 1 ) { tiles [ heightMap [ x ] - 1 ] [ x ] = 4 ; tiles [ heightMap [ x ] - 2 ] [ x ] = 4 ; tiles [ heightMap [ x ] - 3 ] [ x ] = 4 ; tiles [ heightMap [ x ] - 4 ] [ x ] = 4 ; tiles [ heightMap [ x ] - 5 ] [ x ] = 4 ; tiles [ heightMap [ x ] - 5 ] [ x - 1 ] = 5 ; tiles [ heightMap [ x ] - 6 ] [ x - 1 ] = 5 ; tiles [ heightMap [ x ] - 6 ] [ x ] = 5 ; tiles [ heightMap [ x ] - 5 ] [ x + 1 ] = 5 ; tiles [ heightMap [ x ] - 6 ] [ x + 1 ] = 5 ; } }","Why is System.Random giving ' 1 ' a lot of times in a row , then not for a while , then again ?" "C_sharp : I 'm trying to find all the methods that an interface grants me through reflection . I have a type array which I verify has only interfaces , from there I need to extract all the methods.Unfortunately , If I do something like typeof ( IList ) .GetMethods ( ) it only returns the methods on IList not those on ICollection , or IEnumerableI 've tried the following linq query but it does n't return the methods found on the outer interfaces . How can I fix my query ? If this was SQL I could do something like a recursive CTE with a union all , but I do n't think such a syntax exist in C # . Can anyone help here ? from outerInterfaces in interfacesfrom i in outerInterfaces.GetInterfaces ( ) from m in i.GetMethods ( ) select m",Get all methods on an Type [ ] of interfaces using LINQ ? "C_sharp : I 'm trying to fetch a Polygon data from MySQL into my C # application.I have exactly defined in one table the Polygon field where geodata holds.Proof : Returns : So the object in the table is fine and correctly defined.There is a source code in C # : http : //ideone.com/bn1urQAnd the main lines are ( 73-76 ) : I 've commented , but this is n't an obstacle to tell you about both operations : retrieving as BLOB with the next deserializationparsing the fetched string via MySqlGeometry.Parse ( System.String ) methodBLOB retrievingWell , I shall start with commented part of code , let 's imagine , that these lines are uncommented and there are n't lines 75 and 76 with string parsing.Also there is another correction , the SQL query which is sending to the MySQL server must look like : I 've just changed in SQL query the function AsWKT ( ) to the AsWKB ( ) ( from text to binary formatter at MySQL ) .So , the result of this query would be : At lines : You are able to see that I 'm fetching that BLOB object then converting it to the System.Byte [ ] array and only then I 'm trying to build the MySqlGeomerty , but it 's very pity and seems to be that MySQL libraries are identifying this object as a POINT , not a POLYGON.Proof : But ! ! ! I have exactly the POLYGON object in MySQL , by the next SQL query : Proof : That was about the BLOB object.Geometry parsing from System.StringNow ... Let 's imagine the original source with commented BLOB fetching.Let 's look at the lines : And shall change the SQL query in the C # app source code to the : Yes ... MySQL libraries for .NET are providing allegedly another style of geomerty bulding , from the System.String.But , when I 'm trying to parse the var polygon , which is retrieving correctly as you have seen above , I 'm getting the next error : Proof : All these do look like , that MySQL libraries do n't provide a full structures for the data binding from MySQL server . SELECT GeometryType ( GeomFromText ( AsWKT ( object ) ) ) as ` type ` FROM geo.data ; //var polygon = ( byte [ ] ) reader [ `` object '' ] ; //var obj = new MySqlGeometry ( MySqlDbType.Blob , polygon ) ; var polygon = reader [ `` object '' ] .ToString ( ) ; var obj = MySqlGeometry.Parse ( polygon ) ; SELECT AsWKB ( object ) as 'object ' FROM geo.data var polygon = ( byte [ ] ) reader [ `` object '' ] ; var obj = new MySqlGeometry ( MySqlDbType.Blob , polygon ) ; SELECT GeometryType ( GeomFromText ( AsWKT ( object ) ) ) as ` type ` , AsWKT ( object ) as ` data ` FROM geo.data var polygon = reader [ `` object '' ] .ToString ( ) ; var obj = MySqlGeometry.Parse ( polygon ) ; SELECT AsWKT ( object ) as 'object ' FROM geo.data System.FormatException : String does not contain a valid geometry value","MySql drivers for .NET does n't support Polygon struct , does it ?" "C_sharp : The JWT.IO website has a debugger for creating and validating JSON Web Token.When I copy and paste my secret string into the VERIFY SIGNATURE block , I can see that it generates a signature.I scroll down the page a little bit and found the .NET solution implemented by Microsoft . After downloading , I add my unit test to generate the signature manually.However , the signature generated by the JWT.IO website is slightly different from the one generated by my unit test.I notice that the JWT.IO signature string is URL encoding safe , but the unit test signature is not.How do I generate the same signature as the JWT.IO website does ? UPDATEThe accepted answer below pointed me to the class Base64UrlEncoder . I have modified my unit test to generate the exact same signature as JWT.IO web site does : Secrect string : `` THIS IS A SECRET STRING WHICH CAN BE SHARED BETWEEN THE SERVICES '' Unit test signature : `` B0d57pcHoDiTDE/98dyrMx9HoFKGLOcM094eYBgJqHo= '' JWT.IO signature : B0d57pcHoDiTDE_98dyrMx9HoFKGLOcM094eYBgJqHo",How to generate the same signature as the JWT.IO website does ? "C_sharp : I start a Process by Then I confirm it is running by : I get back true and find the process but the UserName is empty . Why is that ? I also found some code to get the Owner of the Process but when I use this the Owner is also empty . Please can you explain me why this is so ? Process app = new Process ( ) ; app.StartInfo.UseShellExecute = false ; app.StartInfo.FileName = path ; app.StartInfo.Domain = `` Domain '' ; app.StartInfo.UserName = `` userName '' ; string password = `` Password '' ; System.Security.SecureString ssPwd = new System.Security.SecureString ( ) ; for ( int x = 0 ; x < password.Length ; x++ ) { ssPwd.AppendChar ( password [ x ] ) ; } password = `` '' ; app.StartInfo.Password = ssPwd ; app.Start ( ) ; private bool IsRunning ( string name ) { Process [ ] processlist = Process.GetProcesses ( ) ; if ( Process.GetProcessesByName ( name ) .Length > 0 ) { string user = Process.GetProcessesByName ( name ) [ 0 ] .StartInfo.UserName ; log.Debug ( `` Process `` + name + `` is running by : `` + user ) ; return true ; } else { return false ; } } public string GetProcessOwner ( int processId ) { string query = `` SELECT * FROM Win32_Process WHERE ProcessID = `` + processId ; ManagementObjectSearcher searcher = new ManagementObjectSearcher ( query ) ; ManagementObjectCollection processList = searcher.Get ( ) ; foreach ( ManagementObject obj in processList ) { string [ ] argList = new string [ ] { string.Empty , string.Empty } ; int returnVal = Convert.ToInt32 ( obj.InvokeMethod ( `` GetOwner '' , argList ) ) ; if ( returnVal == 0 ) { // return DOMAIN\user return argList [ 1 ] + `` \\ '' + argList [ 0 ] ; } } return `` NO OWNER '' ; }",Process.StartInfo.Username is empty "C_sharp : I did some benchmarks with collection types implemented in the .NET Framework.From the Reference Source I know that List < T > uses an array to store contents . To avoid resizing the array with every insertion , the array length gets doubled every time the free space runs out.Now my benchmark would insert random long values into a List ( see the figure above for the size - time - graph ) . There are obvious `` lag spikes '' at lists sizes like 128 or 256 where the internal array has to be re-allocated . But at a size of 512 ( and 128 , though ? ) , there seems to be a really big lag and the time it takes to insert one item is durably increased.In my understanding , the graph should be strictly constant , except the occasions where the internal array needs to be reallocated . Are there any reasons for this behavior , perhaps related to the CLR or Windows memory management / memory fragmentation ? The benchmarks were executed as 64bit application on a Windows 10 / i7-3630QM machine ( source code as seen below ) . Because one single add operation would n't be measurable , I create 1000 lists and add one item each for every list size.EDIT : I double checked my results and yes , they are reproducible . I increased the number of collections tested from 1000 to 10000 , and the result is now much more smooth ( see image below ) . The spikes from resizing the internal array are now clearly visible . And yet the steps in the graph remain - this is a divergence with the expected O ( 1 ) complexity that an array insert should be if you ignore the resizing.I also tried to trigger a GC collection before each Add operation and the graph remained exactly the same.As for the concerns about the creation of delegate objects : All my delegates ( like ProfileAction ) are instance properties that remain assigned during one complete test cycle , in this case 10000 lists with 1000 add operations each . for ( int i = 1 ; i < = MaxCollectionSize ; i++ ) { // Reset time measurement TestContainer.ResetSnapshot ( ) ; // Enable time measurement TestContainer.BeginSnapshot ( ) ; // Execute one add operation on 1000 lists each ProfileAction.Invoke ( TestContainer ) ; TestContainer.EndSnapShot ( ) ; double elapsedMilliseconds = ( TestContainer.GetElapsedMilliSeconds ( ) / ( double ) Stopwatch.Frequency ) * 1000 ; // ... }",Does C # store arrays larger than 512 longs ( 4096 bytes ) differently ? "C_sharp : Windows service : Generating a set of FileWatcher objects from a list of directories to watch in a config file , have the following requirements : File processing can be time consuming - events must be handled on their own task threadsKeep handles to the event handler tasks to wait for completion in an OnStop ( ) event.Track the hashes of uploaded files ; do n't reprocess if not differentPersist the file hashes to allow OnStart ( ) to process files uploaded while the service was down.Never process a file more than once . ( Regarding # 3 , we do get events when there are no changes ... most notably because of the duplicate-event issue with FileWatchers ) To do these things , I have two dictionaries - one for the files uploaded , and one for the tasks themselves . Both objects are static , and I need to lock them when adding/removing/updating files and tasks . Simplified code : What 's the effect of requesting a lock on the FileSystemWatcher collection in the ContinueWith ( ) delegate when the delegate is defined within a lock on the same object ? I would expect it to be fine , that even if the task starts , completes , and enters the ContinueWith ( ) before ProcessModifiedDatafeed ( ) releases the lock , the task thread would simply be suspended until the creating thread has released the lock . But I want to make sure I 'm not stepping on any delayed execution landmines.Looking at the code , I may be able to release the lock sooner , avoiding the issue , but I 'm not certain yet ... need to review the full code to be sure.UPDATETo stem the rising `` this code is terrible '' comments , there are very good reasons why I catch the exceptions I do , and am catching so many of them . This is a Windows service with multi-threaded handlers , and it may not crash . Ever . Which it will do if any of those threads have an unhandled exception.Also , those exceptions are written to future bulletproofing . The example I 've given in comments below would be adding a factory for the handlers ... as the code is written today , there will never be a null task , but if the factory is not implemented correctly , the code could throw an exception . Yes , that should be caught in testing . However , I have junior developers on my team ... `` May . Not . Crash . '' ( also , it must shut down gracefully if there is an unhandled exception , allowing currently-running threads to complete - which we do with an unhandled exception handler set in main ( ) ) . We have enterprise-level monitors configured to send alerts when application errors appear on the event log – those exceptions will log and flag us . The approach was a deliberate and discussed decision.Each possible exception has each been carefully considered and chosen to fall into one of two categories - those that apply to a single datafeed and will not shut down the service ( the majority ) , and those that indicate clear programming or other errors that fundamentally render the code useless for all datafeeds . For example , we 've chosen to shut down the service down if we ca n't write to the event log , as that 's our primary mechanism for indicating datafeeds are not getting processed . The exceptions are caught locally , because the local context is the only place where the decision to continue can be made . Furthermore , allowing exceptions to bubble up to higher levels ( 1 ) violates the concept of abstraction , and ( 2 ) makes no sense in a worker thread.I 'm surprised at the number of people who argue against handling exceptions . If I had a dime for every try..catch ( Exception ) { do nothing } I see , you 'd get your change in nickels for the rest of eternity . I would argue to the death1 that if a call into the .NET framework or your own code throws an exception , you need to consider the scenario that would cause that exception to occur and explicitly decide how it should be handled . My code catches UnauthorizedExceptions in IO operations , because when I considered how that could happen , I realized that adding a new datafeed directory requires permissions to be granted to the service account ( it wo n't have them by default ) . I appreciate the constructive input ... just please do n't criticize simplified example code with a broad `` this sucks '' brush . The code does not suck - it is bulletproof , and necessarily so.1 I would only argue a really long time if Jon Skeet disagrees public sealed class TrackingFileSystemWatcher : FileSystemWatcher { private static readonly object fileWatcherDictionaryLock = new object ( ) ; private static readonly object runningTaskDictionaryLock = new object ( ) ; private readonly Dictionary < int , Task > runningTaskDictionary = new Dictionary < int , Task > ( 15 ) ; private readonly Dictionary < string , FileSystemWatcherProperties > fileWatcherDictionary = new Dictionary < string , FileSystemWatcherProperties > ( ) ; // Wired up elsewhere private void OnChanged ( object sender , FileSystemEventArgs eventArgs ) { this.ProcessModifiedDatafeed ( eventArgs ) ; } private void ProcessModifiedDatafeed ( FileSystemEventArgs eventArgs ) { lock ( TrackingFileSystemWatcher.fileWatcherDictionaryLock ) { // Read the file and generate hash here // Properties if the file has been processed before // ContainsNonNullKey is an extension method if ( this.fileWatcherDictionary.ContainsNonNullKey ( eventArgs.FullPath ) ) { try { fileProperties = this.fileWatcherDictionary [ eventArgs.FullPath ] ; } catch ( KeyNotFoundException keyNotFoundException ) { } catch ( ArgumentNullException argumentNullException ) { } } else { // Create a new properties object } fileProperties.ChangeType = eventArgs.ChangeType ; fileProperties.FileContentsHash = md5Hash ; fileProperties.LastEventTimestamp = DateTime.Now ; Task task ; try { task = new Task ( ( ) = > new DatafeedUploadHandler ( ) .UploadDatafeed ( this.legalOrg , datafeedFileData ) , TaskCreationOptions.LongRunning ) ; } catch { .. } // Only lock long enough to add the task to the dictionary lock ( TrackingFileSystemWatcher.runningTaskDictionaryLock ) { try { this.runningTaskDictionary.Add ( task.Id , task ) ; } catch { .. } } try { task.ContinueWith ( t = > { try { lock ( TrackingFileSystemWatcher.runningTaskDictionaryLock ) { this.runningTaskDictionary.Remove ( t.Id ) ; } // Will this lock burn me ? lock ( TrackingFileSystemWatcher.fileWatcherDictionaryLock ) { // Persist the file watcher properties to // disk for recovery at OnStart ( ) } } catch { .. } } ) ; task.Start ( ) ; } catch { .. } } } }","Nested lock in Task.ContinueWith - Safe , or playing with fire ?" "C_sharp : I have some code While debugging , I set a breakpoint on the b ( ) call . Then going to the immediate window , I 'd like to be able to execute code from a DLL that is in my project but is not yet loaded . Say I want a new Boo and call Foo ( ) . The code is in the namespace Baz in dll Spongle.dll.When I typeI get the error : The type or namespace name 'Baz ' is not valid in this scope.If I change my code such that my Boo is already loaded it works fine.Is it possible to load the dll from the immediate window during debug so I can call my code despite it being loaded ( yet ) ? . I could use the new Boo ( ) as a static initializer of my application main class , but then I have problems during unit testing as it wo n't necesarily involve the class with that static initializer . var aa = a ( ) ; b ( aa ) ; > > new Baz.Boo ( ) .Foo ( aa ) new Boo ( ) ; // dummy to ensure loadingvar aa = a ( ) ; b ( aa ) ;",How to load dll 's during debug in VS2013 "C_sharp : I have been working on a client - server project . The server side implemented on PHP . The client implemented on C # . The websocket is used for connection between them.So , here is the problem . Client will make a request . Json is in use for sending objects and validating against the schema . The request MUST HAVE it 's name and MAY contain args . Args are like associative array ( key = > value ) .Server will give a response . Response MAY contain args , objects , array of objects . For example , client sends a request like : For this , server will reply with an AuthSuccess or AuthFailed response like : If response is AuthSuccess , client will send a requst of who is online . Server must send an array of users . And so on . So the problem is , how to store those responses on a client side . I mean , the way of creating a new object for each response type is insane . They will be hundreds of request types , and each of them requires it 's own response . And any changing in structure of request will be very very hard ... Need some kind of pattern or trick . I know it 's kind of a noob way ... But if anyone has a better idea of implementing request/response structure , please tell it.Best regards ! { `` name '' : `` AuthenticationRequest '' , `` username '' : `` root '' , `` password '' : `` password '' , `` etc '' : `` etc '' } { `` name '' : `` AuthFailed '' , `` args '' : [ { `` reason '' : `` Reason text '' } ] }",Parsing ( many ) JSON different objects to C # classes . Is strongly typed better ? "C_sharp : Are LINQ expression trees proper trees , as in , graphs ( directed or not , wikipedia does not seem too agree ) without cycles ? What is the root of an expression tree from the following C # expression ? The expression tree looks like this , with `` - > '' denoting the name of the property of the node the other node is accessible through.When using ExpressionVisitor to visit the LambdaExpression , the ParameterExpression is visited twice . Is there a way to use the ExpressionVisitor to visit the LambdaExpression so that all the nodes are visited exactly once , and in a specific , well-known order ( pre-order , in-order , post-order etc . ) ? ( string s ) = > s.Length - > Parameters [ 0 ] Lambda -- -- -- -- -Parameter ( string s ) \ / \- > Body /- > Expression \ / Member ( Length )",Are LINQ expression trees proper trees ? "C_sharp : I have a base class which needs to process the names of the properties of derived classes ( explicit access ) . To do so , I created a method which takes a lambda expression as input : This allows me to call the method like so : The problem is that object is not restrictive at all . I can also call : How can I restrict the GetMemberName method so that it can only accept as input the members of the classes which derive from my base class ? Setting GetMemberName ( Expression < Func < MyBaseClass > > expression ) restricts access to an entire class . Setting GetMemberName ( Expression < Func < MyBaseClass , object > > expression ) restricts access to the current instance but still allows `` random '' objects to be passed.EDIT : The comment for derived.GetMemberName ( ( ) = > `` something '' ) ; was in the context of returning the property name , not the `` value '' of the lambda expression . The GetPropertyName method does not return anything , due to the fact that I 'm only analyzing MemberExpression or UnaryExpression . private string GetMemberName ( Expression < Func < object > > expression ) { //gets the property name ( MemberExpression or UnaryExpression ) //out of scope return propertyName ; } derived.GetMemberName ( ( ) = > derived.MyPropertyInt ) ; derived.GetMemberName ( ( ) = > derived.MyPropertyStr ) ; derived.GetMemberName ( ( ) = > `` something '' ) ; //does not `` return '' anything but compiles ( out of scope ) derived.GetMemberName ( ( ) = > anotherClass.RandomMember ) ; //not derived from `` base ''",Restrict lambda expression argument to the properties of a class "C_sharp : In C # .NET , why ca n't I access constants in a class with the 'this ' keyword ? Example : public class MyTest { public const string HI = `` Hello '' ; public void TestMethod ( ) { string filler ; filler = this.HI ; //Wo n't work . filler = HI //Works . } }",Why ca n't I use 'this . ' in C # to access my class constant ? "C_sharp : [ Note After Answer : I am actually querying in memory-objects and that 's why ToTraceString does n't work . I added this to save the reader potential time from reading my long post ] .I 'm using a ToTraceString command when trying to inspect how my LINQ queries end up looking . However , today my query got a bit complicated , involving a join and all of the sudden , I get this error when I try to Trace my String : Unable to cast object of type 'd__7a ` 1 [ EGSLanguageProviderShared.DTODataType ] ' to type 'System.Data.Objects.ObjectQuery'.My Query , and subsequent invocation of ToTraceString is as follows ( note that System.Data.Entity has to be referenced in order for this to work ) . Both objects I 'm querying ( langDTs and langInstructionsAVDTs ) are Entity Framework ( .Net 3.5 ) objects from the same database . My Where Clause ( == av.InstructionAVKey ) uses a simple Value Collection Class , nothing to see there.Any ideas on how I could see the LINQ translation of this Join ? : :- ) . I noticed that System.Data.Objects has more types of queries , but I ca n't get any of the ones which seem more relevant to this case , to work.LATER EDIT : As you recommended , I tried changing the IEnumerable to an IQueryable but that resulted in a type incompatibility compilation error : :- /.After doing an explicit cast , I got the same error , but at Runtime ( Unable to cast object of type ' < DistinctIterator > d__7a1 [ EGSLanguageProviderShared.DTODataType ] ' to type 'System.Linq.IQueryable1 [ EGSLanguageProviderShared.DTODataType ] '. ` ) Additional code : my objects langDTs and langInstructionsAVDTs are : So these objects are indeed queried immediately because they are Lists : :- ) . As for DTODataType and DTOInstructionActiveValueDataType , they are simple Value Collection Classes , just public Properties , that 's all . EVEN LATER EDITMight be of interest that at their root , the objects I 'm using are indeed declared as ObjectQuery back in the deepest layer ( Entity Framework ) : However , as I bring the data from over the Data Access Layer , I am converting them to Data Transfer Objects ( the DTO-prefixed classes you keep seeing ) , which are simple Value Collection Classes ( a property-by-property map of the Entity Objects which I use in order to keep the Data Model completely separated from the View and also to execute any data post-processing in the Presentation side ) . IEnumerable < DTODataType > dts = ( from langDT in langDTs join langIAVDT in langInstructionsAVDTs on langDT.DataTypeKey equals langIAVDT.DataTypeKey where langIAVDT.InstructionAVKey == av.InstructionAVKey select langDT ) .Distinct ( ) ; var sql = ( ( System.Data.Objects.ObjectQuery ) dts ) .ToTraceString ( ) ; List < DTOInstructionActiveValueDataType > langInstructionsAVDTs = CurrentLPInstructionManager.GetInstructionsActiveValuesDataTypes ( ( from avKey in langInstructionsAVs select avKey.InstructionAVKey ) .Distinct ( ) .ToArray ( ) ) ; List < DTODataType > langDTs = _LPDataTypeManager.GetDataTypes ( ( from dt in langInstructionsAVDTs orderby dt.DataTypeKey select dt.DataTypeKey ) .Distinct ( ) .ToArray ( ) ) ; public global : :System.Data.Objects.ObjectQuery < instructions > instructions",Trace LINQ when Joins are used "C_sharp : For a math package , I am trying to have classes for different types of matrices , like typical rectangular matrix , triangular matrix , diagonal matrix etc . The reason is naturally to save on efficient storage and efficient algorithm implementation for special matrices . But I would still like to have the flexibility of overloaded operators where C = A + B would take A and B as any type of matrix and return corresponding result ( the result can be downgraded to typical rectangular matrix if one of the operands is rectangular ) .I have thought of 2 possible ideas , both of which are messy : ( 1 ) An IMatrix interface , which would list all the methods that need to be implemented for each type of matrix , e.g. , transpose , inverse etc . the efficient implementation of which which is different for each type of matrix . Two problems here : ( a ) Operator overloads are static methods , so ca n't be listed in the interface , or even a base class implementing the interface . Operator overloads would have to be written in each class separately , and I ca n't possibly achieve C=A+B type operation ( as I mentioned above ) , without messy type checking and casting in the client code , that I really want to avoid . ( b ) I can not have both operands as interface when I define operator overloads : i.e . I can not do the following in , say , DiagonalMatrix class : ( 2 ) Can have one Matrix class with a matrix type variable stored in the class ( may be an Enum ) . Depending on the type , we can implement the data structure and algorithms . The operator overloading would then work seamlessly . One problems here : ( a ) The class would be huge with possible switch-case syntax for checking matrix type before launching specific algorithm . For each binary operators , I would have to have n^2 cases , n being the number of matrix type I want to implement . Might also be a maintenance nightmare.Looks like , without the operator overloading detail , I could have used Factory pattern or Visitor pattern , but not so with op overloads . What would be the best way to go for this problem ? Resources I have found so far : One related thread here.Explanation of a similar problem faced by the dev of another OS C # Numerics package.Edits:4/25/2011 : Added more resources I have found about this problem so far . public override IMatrix operator + ( IMAtrix lhsMatrix , IMatrix rhsMatrix ) { ... }",OOP design question on inheritance and operator overloading "C_sharp : Suppose I have a view typed to a collection , e.g . a List < ItemViewModel > : Foo and Bar are simply string properties.This generates HTML name attributes of the form [ i ] .Foo and [ i ] .Bar , which , of course , is correct and binds correctly when posted in a form.Now suppose , instead , that the above view is an editor template , which is rendered like so ( where Model.Items is a List < ItemViewModel > ) : All of a sudden , the names generated within the editor template are of the form - for example - Items. [ i ] .Foo . The default model binder ca n't bind this as it expects the form Items [ i ] .Foo.This works fine in the first scenario - where the view is not an editor template - and also works fine where the collection is a property , rather than the entire model : It only fails when the model itself is a collection and the view is an editor template.There are a few ways of working around this , none of which are ideal : Type the editor template to an individual instance of ItemViewModel - this is no good as the actual template in question contains additional markup for adding to/removing from the collection . I need to be able to work with the entire collection inside the template.Wrap the List < ItemViewModel > in another property ( e.g . by implementing ItemListViewModel ) and pass that to the template - this is not ideal , either , as this is an enterprise application that I would rather not clutter with superfluous wrapping view models.Generate the markup for the inner editor templates manually to produce the correct name - this is what I am currently doing but I would rather avoid it as I lose the flexibility of HtmlHelpers.So , the question : Why does NameFor ( and therefore EditorFor ) exhibit this behaviour in this particular scenario when it works fine for slight variations ( i.e . is it intentional and , if so , why ) ? Is there a simple way of working around this behaviour without any of the shortcomings of the above ? As requested , full code to reproduce : Models : Controller action : Index.cshtml : _ItemView.cshtml ( editor template ) : Name attributes for Foo and Bar inputs will be of the form Model . [ i ] .Property and will not bind back when posted to an action method with the signature ActionResult Index ( WrappingViewModel ) . Note that , as mentioned above , this works fine if you iterate over Items in the main view or if you get rid of WrappingViewModel , make the top-level model a List < ItemViewModel > and iterate over Model directly . It only fails for this specific scenario . @ model List < ItemViewModel > @ for ( int i = 0 ; i < Model.Count ; i++ ) { @ Html.EditorFor ( m = > m [ i ] .Foo ) @ Html.EditorFor ( m = > m [ i ] .Bar ) } @ model WrappingViewModel @ Html.EditorFor ( m = > m.Items ) @ Html.EditorFor ( m = > m.Items [ i ] .Foo ) public class WrappingViewModel { [ UIHint ( `` _ItemView '' ) ] public List < ItemViewModel > Items { get ; set ; } public WrappingViewModel ( ) { Items = new List < ItemViewModel > ( ) ; } } public class ItemViewModel { public string Foo { get ; set ; } public string Bar { get ; set ; } } public ActionResult Index ( ) { var model = new WrappingViewModel ( ) ; model.Items.Add ( new ItemViewModel { Foo = `` Foo1 '' , Bar = `` Bar1 '' } ) ; model.Items.Add ( new ItemViewModel { Foo = `` Foo2 '' , Bar = `` Bar2 '' } ) ; return View ( model ) ; } @ model WrappingViewModel @ using ( Html.BeginForm ( ) ) { @ Html.EditorFor ( m = > m.Items ) < input type= '' submit '' value= '' Submit '' / > } @ model List < ItemViewModel > @ for ( int i = 0 ; i < Model.Count ; i++ ) { @ Html.EditorFor ( m = > m [ i ] .Foo ) @ Html.EditorFor ( m = > m [ i ] .Bar ) }",NameFor generates incorrect name when iterating over collection in editor template "C_sharp : In writing the code that throws the exception I asked about here , I came to the end of my message , and paused at the punctuation . I realized that nearly every exception message I 've ever thrown probably has a ! somewhere.What tone do you take when writing exception messages ? When going through logs , do you find any certain style of message actually helps more than another ? throw new InvalidOperationException ( `` I 'm not configured correctly ! `` ) ; throw new ArgumentNullException ( `` You passed a null ! `` ) ; throw new StupidUserException ( `` You ca n't divide by 0 ! What the hell were you THINKING ? ? ? DUMMY ! ! ! ! ! `` ) ;",What style do you use for exception messages ? "C_sharp : Summary : Null is returned after casting the base class to the derived class . However , the base class object seems to be OK before the casting.Details : I am rewriting the older asp.net WebForms application to be able to extend it using MVC approach . As a part of the proces , I am converting the Web Site Project to the Web Application Project . In the case , the ProfileCommon class is not generated automatically . So , I have copied the autogenerated class definition from the older project and placed it as utils\ProfileCommon.cs . Content of the file is ( simplified to a single property that was also renamed from the Czech equivalent ) : The difference also is that I have removed the virtual from the GetProfile ( ) method and made it static . ( The ProfileBase does not have the GetProfile ( ) method ; so , it should be fine , right ? ) The code compiles fine . However , I can observe the following in the browser ( loosely translated , line numbers do not match with the example ) : When debugging , the ProfileBase.Create ( username ) returns the object , where the correct value for the Name property has the expected value ( debugger knows how to get the value ) . However , after the cast , the resulting object reference is null . ( I have to admit I am not very good in C # ; I came from C++ . ) I tried also to split the command to get the ProfileBase p = ProfileBase.Create ( username ) ; ( the object is not null ) , and only then to cast it to ProfileCommon q = p as ProfileCommon ; ( the q is null ) .Update : Strange . I have renamed my class to ProfileComm , cleaned the project , compiled from scratch . There is no ProfileCommon string in the directory ( nor in the sources , not in the binary files , the *.suo , the *.dll , the *.pdb , not in any other file ) . Even the filename was renamed to ProfileComm.cs not to have the ProfileCommon in the *.csproj . The source of the GetProfile ( ) was changed to : Now the details of the exception in the browser read ( translated from another language ) : System.InvalidCastException : Object of the type ProfileCommon can not be casted to the type proj_app.utils.ProfileComm.When debugging , the debugger shows that the type of the p is ProfileCommon : I have no idea from where the type name ProfileCommon slipped in . Could it be related do a version of the .NET framework ? What should I check ? Could the ProfileCommon class still be generated dynamically somehow ? using System ; using System.Web ; using System.Web.Profile ; namespace proj_app.utils { public class ProfileCommon : System.Web.Profile.ProfileBase { public virtual string Name { get { return ( ( string ) ( this.GetPropertyValue ( `` Name '' ) ) ) ; } set { this.SetPropertyValue ( `` Name '' , value ) ; } } public static ProfileCommon GetProfile ( string username ) { return ( ( ProfileCommon ) ( ProfileBase.Create ( username ) ) ) ; } } } The object of the ProfileCommon type can not be casted to proj_app.utils.ProfileCommon.Description : ... unhandled exception during the web request ... Details about the exception : The object of the ProfileCommon type can not be casted to proj_app.utils.ProfileCommon.Zdrojová chyba : Line 36 : public static ProfileCommon GetProfile ( string username ) Line 37 : { Line 38 : return ( ( ProfileCommon ) ( ProfileBase.Create ( username ) ) ) ; Line 39 : } Line 40 : } Source file : d : \__RizeniProjektu\aplikace\proj_app\utils\ProfileCommon.cs Line : 38Stack trace : [ InvalidCastException : Objekt typu ProfileCommon nelze přetypovat na typ proj_app.utils.ProfileCommon . ] proj_app.utils.ProfileCommon.GetProfile ( String username ) in d : \__RizeniProjektu\aplikace\proj_app\utils\ProfileCommon.cs:38 Users_seznam.Page_Load ( Object sender , EventArgs e ) in d : \__RizeniProjektu\aplikace\proj_app\Users\seznam.aspx.cs:29 System.Web.Util.CalliEventHandlerDelegateProxy.Callback ( Object sender , EventArgs e ) +51 System.Web.UI.Control.OnLoad ( EventArgs e ) +92 System.Web.UI.Control.LoadRecursive ( ) +54 System.Web.UI.Page.ProcessRequestMain ( Boolean includeStagesBeforeAsyncPoint , Boolean includeStagesAfterAsyncPoint ) +772 public class ProfileComm : System.Web.Profile.ProfileBase { ... public static ProfileComm GetProfile ( string username ) { object p = ProfileBase.Create ( username ) ; Type t = p.GetType ( ) ; string s = t.Name ; return ( ( ProfileComm ) ( p ) ) ; } }",ProfileCommon -- casting in run-time fails "C_sharp : I am trying to code an algorithm that solves a maze problem but I am facing some difficulty to apply it correctly . The algorithm runs over the walls instead of changing the direction after finding the valid point.Complete Code on GithubI do not understand clearly how to check for the previousPoint and then from that point check for the next valid move.Could someone help me giving me some tips on which direction I could go ? I tried to implement the answer given by Paul but could not really get anywhere from it and I am completely lost.That is what I got from your answer : When I run it I get a stack overflow error.When I am checking the possible points and calling the function recursively with I do n't really understand why I am checking the nextValidMove ( y-1 , x ) since it was already true at the begining of my if statement : I thought of checking the previousPoint together , like this : But I am getting a stackoverflow error . I have no clue how to get out of there anymore . class MapPathFinder { public bool [ , ] correctPath = new bool [ 12,12 ] ; public int [ , ] previousPoint = new int [ 12 , 12 ] ; public bool startPointFound = false ; public bool nextValidMove ( MapFile map , int y , int x ) { if ( ( y == map.width ) & & ( x == map.height ) ) { return false ; //Checks if at the edge and terminates the method } if ( ( map.Matrix [ y , x ] ) == 1 ) { return true ; // check if at a wall and terminate the method } if ( y ! = 0 ) { if ( nextValidMove ( map , y-1 , x ) ) { map.Matrix [ y , x ] = 9 ; //changes the color of the position correctPath [ y , x ] = true ; return correctPath [ y , x ] ; } if ( y ! = map.width - 1 ) //check if at the limit of the map { if ( nextValidMove ( map , y + 1 , x ) ) { map.Matrix [ y , x ] = 9 ; correctPath [ y , x ] = true ; return correctPath [ y , x ] ; } } if ( x ! = 0 ) { if ( nextValidMove ( map , y , x - 1 ) ) { map.Matrix [ y , x ] = 9 ; correctPath [ y , x ] = true ; return correctPath [ y , x ] ; } } if ( x ! = map.height - 1 ) { if ( nextValidMove ( map , y , x + 1 ) ) { map.Matrix [ y , x ] = 9 ; correctPath [ y , x ] = true ; return correctPath [ y , x ] ; } } } return false ; } public bool PathFinder ( MapFile map ) { for ( int y = 1 ; y < map.width ; y++ ) { for ( int x = 1 ; x < map.height ; x++ ) { var status = MapDisplay.DisplayMap ( map ) ; if ( status ) { nextValidMove ( map , x , y ) ; } } } return true ; } public bool nextValidMove ( MapFile map , int y , int x ) { if ( ( y == map.width ) || ( x == map.height ) ) return false ; if ( y < 0 || x < 0 ) return false ; if ( ( map.Matrix [ y , x ] ) == 1 ) return true ; // check if at a wall and terminate the method if ( map.Matrix [ y , x ] == 5 ) return map.end ; if ( y - 1 > = 0 & & map.Matrix [ y-1 , x ] == 2 & & ! nextValidMove ( map , y-1 , x ) ) { map.Matrix [ y , x ] = 9 ; previousPoint [ y , x ] = map.Matrix [ y , x ] ; return false ; } // Test the East wall ... if ( x + 1 < = map.width - 1 & & map.Matrix [ y + 1 , x ] == 2 & & ! nextValidMove ( map , y , x+1 ) ) { map.Matrix [ y , x ] = 9 ; previousPoint [ y , x ] = map.Matrix [ y , x ] ; return false ; } // Test the South wall ... if ( y + 1 < = map.height - 1 & & map.Matrix [ y , x + 1 ] == 2 & & ! nextValidMove ( map , y+1 , x ) ) { map.Matrix [ y , x ] = 9 ; previousPoint [ y , x ] = map.Matrix [ y , x ] ; return false ; } // Test the West wall ... if ( x - 1 > = 0 & & map.Matrix [ y , x - 1 ] == 2 & & ! nextValidMove ( map , y , x-1 ) ) { map.Matrix [ y , x ] = 9 ; previousPoint [ y , x ] = map.Matrix [ y , x ] ; return false ; } return false ; } ! nextValidMove ( map , y-1 , x ) if ( map.Matrix [ y-1 , x ] == 2 & & ! nextValidMove ( y-1 , x ) ) if ( nextValidMove ( map , y - 1 , x ) & & ! previousPoint [ y-1 , x ] )",How to check for the previous path searched on a maze C # "C_sharp : I have read that a variable should never do more than one thing . Overloading a variable to do more than one thing is bad . Because of that I end up writing code like this : ( With the customerFound variable ) But deep down inside , I sometimes want to write my code like this : ( Without the customerFound variable ) Does this secret desires make me an evil programmer ? ( i.e . is the second case really bad coding practice ? ) bool customerFound = false ; Customer foundCustomer = null ; if ( currentCustomer.IsLoaded ) { if ( customerIDToFind = currentCustomer.ID ) { foundCustomer = currentCustomer ; customerFound = true ; } } else { foreach ( Customer customer in allCustomers ) { if ( customerIDToFind = customer.ID ) { foundCustomer = customer ; customerFound = true ; } } } if ( customerFound ) { // Do something } Customer foundCustomer = null ; if ( currentCustomer.IsLoaded ) { if ( customerIDToFind = currentCustomer.ID ) { foundCustomer = currentCustomer ; } } else { foreach ( Customer customer in allCustomers ) { if ( customerIDToFind = customer.ID ) { foundCustomer = customer ; } } } if ( foundCustomer ! = null ) { // Do something }",Does checking against null for 'success ' count as `` Double use of variables '' ? "C_sharp : We 're creating an internal use Cake addin for our build scripts.We 're currently publishing it as pre-release to an internal feed , we 've previously consumed addins from NuGet with # addin [ id ] syntax like this : Is it possible to change the default feed or specify the feed in any way ? And is there a way to indicate that pre-release is allowed ? # addin `` Cake.FileHelpers ''",How do I fetch Cake Build prerelease addin from alternative source ? "C_sharp : Using Microsoft Message Analyzer , I can see that post data using the HttpClient is being sent in two tcp packets . One for the header , then one for the post data . This data could easily fit into one packet , however it is being split into two . I have explicitly turned on nagling and expect 100 continue off using the ServicePointManager , though , it does n't seem to help.5023 ( .Net ) shows 2 packets are sent to destination , 8170 ( Postman ) shows 1 packet being sent . Tests were done with the same payload.Below is some sample code used to generate the request in .netIs there a way to force the payload into a single packet ? Using .Net Framework 4.7related question here ServicePointManager.Expect100Continue = false ; ServicePointManager.UseNagleAlgorithm = true ; public void TestRequest ( ) { var uri = new Uri ( `` http : //www.webscantest.com/ '' ) ; ServicePointManager.Expect100Continue = false ; ServicePointManager.UseNagleAlgorithm = true ; var p = ServicePointManager.FindServicePoint ( uri ) ; p.Expect100Continue = false ; p.UseNagleAlgorithm = true ; HttpClient client = new HttpClient ( ) ; client.DefaultRequestHeaders.Add ( `` Connection '' , `` close '' ) ; var values = new Dictionary < string , string > { { `` thing1 '' , `` hello '' } , { `` thing2 '' , `` world '' } } ; var content = new FormUrlEncodedContent ( values ) ; var response = client.PostAsync ( `` http : //www.webscantest.com/ '' , content , CancellationToken.None ) .Result ; }",c # httpclient post force single packet "C_sharp : Is the use of implicit enum fields to represent numeric values a necessarily bad practice ? Here is a use case : I want an easy way to represent hex digits , and since C # enums are based on integers , they seem like a natural match . I do n't like a char or a string here , because I have to explicitly validate their values . The problem with enums is that digits [ 0-9 ] are not valid field identifiers ( with good reason ) . It occurred to me that I do n't need to declare the digits 0-9 , because they are implicitly present.So , my hex digit enum would look like : So , I could write Tuple < Hex , Hex > r = Tuple.Create ( Hex.F , ( Hex ) 1 ) ; , and r.Item1.ToString ( ) + r.Item2.ToString ( ) would give me `` F1 '' . Basically , my question is that if the ToString ( ) value of the numeric constant is what I want to name the enum field , why is it problematic to omit the declaration entirely ? An alternative representation as an enum could have the fields declared with some prefix , such as : The problem is that the above example would give me `` F_1 '' instead of `` F1 '' . Obviously , this is easy to fix . I 'm wondering if there are additional problems with the implicit approach that I am not considering . public enum Hex : int { A = 10 , B = 11 , C = 12 , D = 13 , E = 14 , F = 15 } public enum Hex : int { _0 = 0 , _1 = 1 , _2 = 2 , _3 = 3 , _4 = 4 , _5 = 5 , _6 = 6 , _7 = 7 , _8 = 8 , _9 = 9 , A = 10 , B = 11 , C = 12 , D = 13 , E = 14 , F = 15 }",Is the use of implicit enum fields to represent numeric values a bad practice ? "C_sharp : I have a query like this The where clause needs to be after fetch due to this bug . The problem is that thouse Fetch calls issue additional joins . In SQL query looks like the following : It does inner join to put a condition on CommunityId and does left outer join to do fetching.I 've found similar question , but my query has different execution plan with and without additional joins . Is it a bug in LINQ provider ? Maybe there is a workaround ? var orderedQueryable = this.participationRequests .Fetch ( x = > x.CommunityEvent ) .Fetch ( x = > x.CommunityMember ) .ThenFetch ( x = > x.User ) .Where ( x = > x.CommunityMember.Community.Id == communityId ) .OrderBy ( x = > x.CreateDate ) ; select *from ParticipationRequests participat0_ left outer join CommunityEvents communitye1_ on participat0_.CommunityEventId = communitye1_.Id left outer join CommunityMembers communitym2_ on participat0_.CommunityMemberId = communitym2_.Id left outer join Users user3_ on communitym2_.UserId = user3_.Id inner join CommunityMembers communitym4_ on participat0_.CommunityMemberId = communitym4_.Id inner join CommunityMembers communitym5_ on participat0_.CommunityMemberId = communitym5_.Id inner join Communities community6_ on communitym5_.CommunityId = community6_.Idwhere community6_.Id = 2002 /* @ p0 */order by participat0_.CreateDate asc",LINQ to Nhibernate duplicates joins "C_sharp : i am attempting to attach a Delegate to an invocation list of a different delegate . By that i am achieving a kind of Hook on existing events.I need to hook up something that runs after each event that is invoked.The following example works as long as the Delegate exposed by the type and the Action i pass in have the exact same signature . ( On1 and OnAll events are both declared with an Action delegate so it works ) .Code : How i hook up an Action with an existing delegate exposed by an event modifier.The Sample : The Problem : When the Delegate exposed with an event modifier in Tester does not have the same signature i get a well wanted and obvious exception which states ( in my words ) that Action ca n't be added to an invocation list of an Action < int > . makes sense . Just to be clear I 'm describing the following : What I 'm looking for is a way to create another Delegate of the same type as the EventHandlerType . In order to do that i need to create a method with the signature i of EventHandlerType which would internally invoke action . something like : public static class ReflectionExtensions { public static IEnumerable < EventInfo > GetEvents ( this object obj ) { var events = obj.GetType ( ) .GetEvents ( ) ; return events ; } public static void AddHandler ( this object obj , Action action ) { var events = obj.GetEvents ( ) ; foreach ( var @ event in events ) { @ event.AddEventHandler ( obj , action ) ; } } } public class Tester { public event Action On1 ; public event Action On2 ; public void RaiseOn1 ( ) { On1 ( ) ; } public void RaiseOn2 ( ) { On2 ( ) ; } } class Program { static void Main ( string [ ] args ) { var t = new Tester ( ) ; t.On1 += On1 ; t.On2 += On2 ; t.AddHandler ( OnAll ) ; t.RaiseOn1 ( ) ; t.RaiseOn2 ( ) ; } public void On1 ( ) { } public void On2 ( ) { } public void OnAll ( ) { } } public event Action < int > On1 ; public void On1 ( int i ) { } public static void AddHandler ( this object obj , Action action ) { var events = obj.GetEvents ( ) ; foreach ( var @ event in events ) { // method with the signeture of EventHandlerType which does action ( ) ; MethodInfo wrapperMethod = WrapAction ( @ event.EventHandlerType , action ) ; Delegate handler = Delegate.CreateDelegate ( @ event.EventHandlerType , action.Target , wrapperMethod ) ; @ event.AddEventHandler ( obj , handler ) ; } }",Reflection - Add a Delegate to another Delegate 's invocation list "C_sharp : I have the following code in ASP.Net Generic handler to download the file.it works fine with local path - like `` D : \Files\Sample.pdf '' or `` \localserver\Files\Sample.pdf '' .but it throws and access denied error while trying to access the Network file share like `` \anotherServer\Files\Sample.pdf '' .Does it related to double hopping ? If can I use spsecurity.runwithelevatedprivileges to fix this issue ? or what are the other options ? As per this article https : //weblogs.asp.net/owscott/iis-windows-authentication-and-the-double-hop-issue it seems to be a double hopping issue . How do I address this ? All I want is that end user should be able to download remote resources by using asp.net generic handler . // generate you file// set FilePath and FileName variablesstring stFile = FilePath + FileName ; try { response.Clear ( ) ; response.ContentType = `` application/pdf '' ; response.AppendHeader ( `` Content-Disposition '' , `` attachment ; filename= '' + FileName + `` ; '' ) ; response.TransmitFile ( stFile ) ; } catch ( Exception ex ) { // any error handling mechanism } finally { response.End ( ) ; }",Downloading a file from a Remote File share throws access denied "C_sharp : I am reading C # in Depth from Jon Skeet . Although I have understood the concept of CoVariance and ContraVariance , but I am unable to understand this line : Well , covariance is safe when SomeType only describes operations that return the type parameter—and contravariance is safe when SomeType only describes operations that accept the type parameter.Can someone please explain with an example for both , why both are type safe in one direction and not in the other direction ? Updated Question : I still did n't understand from the answers given . I will try to explain my concern using the same example from the book - C # In Depth.It explains using the following class hierarchy : COVARIANCE is : Trying to convert from IEnumerable < Circle > to IEnumerable < IShape > , but it is mentioned that this conversion is type safe only when we are performing while returning it from some method , and not type safe when we are passing it as an IN parameter.CONTRA VARIANCE is : Trying to convert from IEnumerable < IShape > to IEnumerable < Circle > , which is mentioned to be type safe only while performing it when sending it as an IN parameter . IEnumerable < IShape > GetShapes ( ) { IEnumerable < Circle > circles = GetEnumerableOfCircles ( ) ; return circles ; // Conversion from IEnumerable < Circle > to IEnumerable < IShape > - COVARIANCE } void SomeMethod ( ) { IEnumerable < Circle > circles = GetEnumerableOfCircles ( ) ; DoSomethingWithShapes ( circles ) ; // Conversion from IEnumerable < Circle > to IEnumerable < IShape > - COVARIANCE } void DoSomethingWithShapes ( IEnumerable < IShape > shapes ) // Why this COVARIANCE is type unsafe ? ? { // do something with Shapes } IEnumerable < Circle > GetShapes ( ) { IEnumerable < IShape > shapes = GetEnumerableOfIShapes ( ) ; return shapes ; // Conversion from IEnumerable < IShape > to IEnumerable < Circle > - Contra-Variance // Why this Contra-Variance is type unsafe ? ? } void SomeMethod ( ) { IEnumerable < IShape > shapes = GetEnumerableOfIShapes ( ) ; DoSomethingWithCircles ( shapes ) ; // Conversion from IEnumerable < IShape > to IEnumerable < Circle > - Contra-Variance } void DoSomethingWithCircles ( IEnumerable < Circle > circles ) { // do something with Circles }",Type safety in CoVariance and ContraVariance "C_sharp : In my application , _collection is a List from which I need to remove all User objects which do not match the criteria.However , the following code gets an invalid operation error in its second iteration since the _collection itself has been changed : I could create another List collection and copy them back and forth but then I have the issue of non-cloned reference types , etc.Is there a way to do the above more elegantly than copying _collection to another another List variable ? foreach ( User user in _collection ) { if ( ! user.IsApproved ( ) ) { _collection.Remove ( user ) ; } }",What is the easiest way to foreach through a List < T > removing unwanted objects ? "C_sharp : I have noticed an interesting behavior with float rounding / truncation by the C # compiler . Namely , when a float literal is beyond the guaranteed representable range ( 7 decimal digits ) , then a ) explicitly casting a float result to float ( a semantically unnecessary operation ) and b ) storing intermediate calculation results in a local variable both change the output . An example : The output is : In the JITted debug build on my computer , b is calculated as follows : whereas d is calculated asFinally , my question : why is the second line of the output different from the fourth ? Does that extra fmul make such a difference ? Also note that if the last ( already unrepresentable ) digit from the float f is removed or even reduced , everything `` falls in place '' . using System ; class Program { static void Main ( ) { float f = 2.0499999f ; var a = f * 100f ; var b = ( int ) ( f * 100f ) ; var c = ( int ) ( float ) ( f * 100f ) ; var d = ( int ) a ; var e = ( int ) ( float ) a ; Console.WriteLine ( a ) ; Console.WriteLine ( b ) ; Console.WriteLine ( c ) ; Console.WriteLine ( d ) ; Console.WriteLine ( e ) ; } } 205204205205205 var b = ( int ) ( f * 100f ) ; 0000005a fld dword ptr [ ebp-3Ch ] 0000005d fmul dword ptr ds : [ 035E1648h ] 00000063 fstp qword ptr [ ebp-5Ch ] 00000066 movsd xmm0 , mmword ptr [ ebp-5Ch ] 0000006b cvttsd2si eax , xmm0 0000006f mov dword ptr [ ebp-44h ] , eax var d = ( int ) a ; 00000096 fld dword ptr [ ebp-40h ] 00000099 fstp qword ptr [ ebp-5Ch ] 0000009c movsd xmm0 , mmword ptr [ ebp-5Ch ] 000000a1 cvttsd2si eax , xmm0 000000a5 mov dword ptr [ ebp-4Ch ] , eax",Strange compiler behavior with float literals vs float variables "C_sharp : Recently I discovered quite interesting behaviour of Moq library ( 4.5.21 ) in one of mine C # projects . Below is the class that I am trying to test.Below is my TestClass : I get following output : I 'd expect that I can Verify that the method was called Once each time with an object with different State . Any thoughts on what am I doing wrong ? Thank you ! public class Order { public string State { get ; set ; } } public interface IOrderService { Task UpdateOrderAsync ( Order order ) ; } public class Program { public async Task RunAsync ( IOrderService orderService ) { var order = new Order ( ) ; order.State = `` new '' ; await orderService.UpdateOrderAsync ( order ) ; order.State = `` open '' ; await orderService.UpdateOrderAsync ( order ) ; } } [ TestMethod ] public async Task TestMethod ( ) { var mock = new Mock < IOrderService > ( ) ; await new Program ( ) .RunAsync ( mock.Object ) ; mock.Verify ( x = > x.UpdateOrderAsync ( It.Is < Order > ( o = > o.State == `` new '' ) ) , Times.Once ) ; mock.Verify ( x = > x.UpdateOrderAsync ( It.Is < Order > ( o = > o.State == `` open '' ) ) , Times.Once ) ; } Moq.MockException : Expected invocation on the mock once , but was 0 times : x = > x.UpdateOrderAsync ( It.Is < Order > ( o = > o.State == `` new '' ) ) Configured setups : x = > x.UpdateOrderAsync ( It.Is < Order > ( o = > o.State == `` new '' ) ) , Times.Oncex = > x.UpdateOrderAsync ( It.Is < Order > ( o = > o.State == `` open '' ) ) , Times.OncePerformed invocations : IOrderService.UpdateOrderAsync ( Order < State : open > ) IOrderService.UpdateOrderAsync ( Order < State : open > )",Verify method calls using with different state of object using Moq "C_sharp : Working in a business environment , I do n't really get to code or use the good old console anymore . My work is repetitive and thus not really challenging.I decided to challenge myself by writing a snake game in a C # console ; and boy did it make my brain work . I never have to think this hard on a day-to-day basis , but I felt like my programming skills were n't getting any better.I have a problem though . The basic approach I took was to create a snake class and a food class . The snake class uses an array to store all coordinates and then a drawing class decides what coords to draw on-screen.The problem is that as you move the snake , the array fills up ( maxsize is 250 for performance ) , so when I reach the end of the array I want to copy the last few coords to a temp array , flush the original array and copy the temp coords back to the main array.The problem I have is copying x coords back to the original array . I decided to do it manually to test but this solution always makes my poor snake leave behind one of its segments on the screen when it should n't be there.How would I go about doing this programmatically ? I really do n't mind posting the whole game here if someone really wants to dig into the code . spoints [ 4 , 0 ] = stemp [ 249 , 0 ] ; spoints [ 4 , 1 ] = stemp [ 249 , 1 ] ; spoints [ 4 , 2 ] = stemp [ 249 , 2 ] ; spoints [ 3 , 0 ] = stemp [ 248 , 0 ] ; spoints [ 3 , 1 ] = stemp [ 248 , 1 ] ; spoints [ 3 , 2 ] = stemp [ 248 , 2 ] ; spoints [ 2 , 0 ] = stemp [ 247 , 0 ] ; spoints [ 2 , 1 ] = stemp [ 247 , 1 ] ; spoints [ 2 , 2 ] = stemp [ 247 , 2 ] ; spoints [ 1 , 0 ] = stemp [ 246 , 0 ] ; spoints [ 1 , 1 ] = stemp [ 246 , 1 ] ; spoints [ 1 , 2 ] = stemp [ 246 , 2 ] ; spoints [ 0 , 0 ] = stemp [ 245 , 0 ] ; spoints [ 0 , 1 ] = stemp [ 245 , 1 ] ; spoints [ 0 , 2 ] = stemp [ 245 , 2 ] ;",Array assignment Snake "C_sharp : Output 1 2 null 2Code class Program { static void Main ( String [ ] args ) { String s = null ; PrintLength ( s ) ; PrintLength ( s , s ) ; PrintLength ( null ) ; PrintLength ( null , null ) ; Console.ReadKey ( ) ; } private static void PrintLength ( params String [ ] items ) { Console.WriteLine ( items == null ? `` null '' : items.Length.ToString ( ) ) ; } }",Why does params behave like this ? C_sharp : Why do I see 0 instead of .73 ? int x = 73 ; int y = 100 ; double pct = x/y ;,How do you divide integers and get a double in C # ? "C_sharp : I believe the code is pretty self-explanatory . Why is n't the RegularExpression attribute being used by the Validator ? License.cs : LicenseTest.cs public class License { [ Required ] [ RegularExpression ( `` ( [ 0-9A-F ] { 4 } \\- ) { 4 } [ 0-9A-F ] { 4 } '' ) ] public string Code { get ; set ; } } [ TestMethod ] public void TestValidationOfCodeProperty ( ) { // These tests pass so I know the regex is not the issue Assert.IsTrue ( Regex.IsMatch ( `` ABCD-EF01-2345-6789-FFFF '' , `` ( [ 0-9A-F ] { 4 } \\- ) { 4 } [ 0-9A-F ] { 4 } '' ) ) ; Assert.IsFalse ( Regex.IsMatch ( `` abcd-ef01-2345-6789-ff00 '' , `` ( [ 0-9A-F ] { 4 } \\- ) { 4 } [ 0-9A-F ] { 4 } '' ) ) ; Assert.IsFalse ( Regex.IsMatch ( `` 3331313336323034313135302020202020212121 '' , `` ( [ 0-9A-F ] { 4 } \\- ) { 4 } [ 0-9A-F ] { 4 } '' ) ) ; // Setup Validator License lic = new License ( ) ; var ctx = new ValidationContext ( lic ) ; var results = new List < ValidationResult > ( ) ; // Passes - TryValidateObject returns false because the required field is empty lic.Code = `` '' ; Assert.IsFalse ( Validator.TryValidateObject ( lic , ctx , results ) ) ; // Passes - TryValidateObject returns true lic.Code = `` 10D0-4439-0002-9ED9-0743 '' ; Assert.IsTrue ( Validator.TryValidateObject ( lic , ctx , results ) ) ; // FAILS - TryValidateObject returns true lic.Code = `` 3331313336323034313135302020202020212121 '' ; Assert.IsFalse ( Validator.TryValidateObject ( lic , ctx , results ) ) ; }",The RegularExpression data annotation is not being recognized by the Validator "C_sharp : I have employee table with bigint primary key field in database and entity data model with database first approach . Employee class have this structureI write this basic query with Entity FrameworkIt Generate query as the following : As you can see there is unnecessary cast to bigint in query while both type of Emp_No and ids array are long , It causes bad execution times specially whenever ids array has many elements.How can I remove this redundant cast ? public partial class Employee { public long Emp_No { get ; set ; } public string Name { get ; set ; } public string Family { get ; set ; } ... } List < long > ids = new List < long > ( ) { 1,2,3,4,5,6 } database.Employees.Where ( q = > ids.Contain ( q.Emp_No ) ) .ToList ( ) ; SELECT [ Extent1 ] . [ Emp_No ] AS [ Emp_No ] , [ Extent1 ] . [ Name ] AS [ Name ] , [ Extent1 ] . [ Family ] AS [ Family ] , ... FROM [ dbo ] . [ Employee ] AS [ Extent1 ] WHERE [ Extent1 ] . [ Emp_No ] IN ( cast ( 0 as bigint ) , cast ( 1 as bigint ) , cast ( 2 as bigint ) , cast ( 3 as bigint ) , cast ( 4 as bigint ) , cast ( 5 as bigint ) , cast ( 6 as bigint ) )",Unnecessary conversion to bigint "C_sharp : I have an EF Core 2.2 application that is working fine . Then I introduce procedures and know I can do this : ... In myContextExample call to get data : This should be noted this works fine . However , when I go to create a new migration it generates a table . Fine no biggie , I will just state in the On Model Creating not to build that table.Nope , now when I call my procedure that was just working I get this : Can not create a DbSet for 'MyProcsDbSet ' because this type is not included in the model for the context.Is there a way to get a dbset for procedure returns and not have to forever suppress the want of ef core to create tables ? The ability of .NET Core EF code first always seems like it 's biggest drawback was with the custom objects and their creation and retrieval . public virtual DbSet < MyProcsDbSet > MyProcsDbSet { get ; set ; } using ( var context = myContext ( ) ) { var data = context.MyProcsDbSet.ExecuteSQL ( `` Myproc @ p0 '' , 1 ) ; } bldr.Ignore < MyProcsDbSet > ( ) ;",If I ignore a dbset used for a procedure I can not use EF Core to get that procedure "C_sharp : I have a list of strings and I want to convert it to some kind of grouped list , whereby the values would be grouped by their location in the list ( not normal grouping , but in a way , that the same items are in a group only if they are together ) . Consider the following example : Can this transformation be done with LINQ or should I write the algorithm usual way with loops ? LinkedList < string > myList = new LinkedList < string > ( ) ; myList.AddLast ( `` aaa '' ) ; myList.AddLast ( `` aaa '' ) ; myList.AddLast ( `` bbb '' ) ; myList.AddLast ( `` bbb '' ) ; myList.AddLast ( `` aaa '' ) ; myList.AddLast ( `` aaa '' ) ; myList.AddLast ( `` aaa '' ) ; LinkedList < MyTuple > groupedList = new LinkedList < MyTuple > ( ) ; groupedList.AddLast ( new MyTuple ( `` aaa '' , 2 ) ) ; groupedList.AddLast ( new MyTuple ( `` bbb '' , 2 ) ) ; groupedList.AddLast ( new MyTuple ( `` aaa '' , 3 ) ) ;",'Smart ' grouping with LINQ C_sharp : We all know that strings are immutable and StringBuilder is mutable . Right . Then why does its methods returns a StringBuilder object . Should they all not be void methods ? Why thisand not Any example explaining use of this would be great . public StringBuilder Append ( bool value ) public void Append ( bool value ),"If StringBuilder is mutable , then why do StringBuilder methods return a StringBuilder object ?" "C_sharp : I have a Xamarin Forms application which gives the user 3 theme options . I want to be able to change the Tabbar background , selected item and unselected item color with a button click . In iOS I was able to do this with a renderer like below : In Android , I know its possible to change these colors in styles.xml but that would only allow me to set the colors once . Also , I am using the ToolbarPlacement= '' Bottom '' to place my tab bar at the bottom of the screen . I wonder if its possible to be able to change the BarSelectedItemColor dynamically with a button click . protected override void OnElementChanged ( VisualElementChangedEventArgs e ) { base.OnElementChanged ( e ) ; if ( e.OldElement ! = null ) { Xamarin.Forms.Application.Current.PropertyChange -= Current_PropertyChanged ; return ; } Xamarin.Forms.Application.Current.PropertyChange += Current_PropertyChanged ; //subscribe to the App class ' built in property changed event UpdateTheme ( ) ; } void Current_PropertyChanged ( object sender , System.ComponentModel.PropertyChangedEventArgs e ) { UpdateTheme ( ) ; } android : TabbedPage.ToolbarPlacement= '' Bottom '' android : TabbedPage.BarSelectedItemColor= '' Red '' android : TabbedPage.IsSwipePagingEnabled= '' False ''",Is it possible to change the tabbar selected item color dynamically in Xamarin Forms Android ? "C_sharp : I came across the following in a code review : typeName originates from an AJAX request and is not validated . Does this pose any potential security issues ? For example , is it possible for unexpected code to be executed , or for the entire application to crash ( denial of service ) , as the result of loading arbitrary types from arbitrary assemblies ? ( I suppose some joker could attempt to exhaust available memory by loading every type from every assembly in the GAC . Anything worse ? ) Notes : This is an ASP.NET application running under Full Trust.The resulting type is only used as shown above . No attempt is made to instantiate the type . Type type = Type.GetType ( typeName ) ; if ( type == typeof ( SomeKnownType ) ) DoSomething ( ... ) ; // does not use type or typeName",Is it safe to call Type.GetType with an untrusted type name ? "C_sharp : I have a content security policy that causes Chrome to post a report , but the action that receives the report returns `` 415 Unsupported Media Type '' . I understand this is because the post has a Content-Type of `` application/csp-report '' . How do I add this as a allowed content type in Core 3.1 ( its basically just json ) .ActionCut down version of model // https : //anthonychu.ca/post/aspnet-core-csp/ [ HttpPost ] [ Consumes ( `` application/csp-report '' ) ] public IActionResult Report ( [ FromBody ] CspReportRequest request ) { return Ok ( ) ; } public class CspReportRequest { [ JsonProperty ( PropertyName = `` csp-report '' ) ] public CspReport CspReport { get ; set ; } } public class CspReport { [ JsonProperty ( PropertyName = `` document-uri '' ) ] public string DocumentUri { get ; set ; } }",`` 415 Unsupported Media Type '' for Content-Type `` application/csp-report '' in ASP.NET Core "C_sharp : I need to send a daily summary email to all users but I am unsure where exactly I should trigger it.I have made a class for sending the emails : Then in ConfigureServices ( ) I have registered service and hangfire : And in Configure ( ) addedNow I am stuck . Hang-fire docs say I need to do something like : I am not sure how to do this so that the class gets initiated with dependent services injected . How do I reference the SendAllSummaries ( ) method of instantiated service ? What is best way to do this ? public class SummaryEmailBusiness { private MyDbContext _db ; private IEmailSender _emailSender ; public SummaryEmailBusiness ( MyDbContext db , IEmailSender emailSender ) { _db = db ; _emailSender = emailSender ; } public void SendAllSummaries ( ) { foreach ( var user in _db.AspNetUsers ) { //send user a summary } } } services.AddHangfire ( config = > config.UseSqlServerStorage ( Configuration.GetConnectionString ( `` DefaultConnection '' ) ) ) ; services.AddTransient < SummaryEmailBusiness > ( ) ; app.UseHangfireDashboard ( ) ; app.UseHangfireServer ( ) ; RecurringJob.AddOrUpdate ( ( ) = > SendAllSummaries ( ) , Cron.Daily ) ;",Sending a daily summary email with hang-fire and ASP.NET Core "C_sharp : Basically , I have the following : The requirements are : All PropA items in the collection are unique ( no duplicates ) All PropB items in the collection are unique ( no duplicates ) Ca n't seem to figure out what to do here for my Contract.ForAll ( ... ) statement.Bonus : if I can combine the Contract.ForAll ( ... ) statements without ruining the code contracts ? public class MyClass { public MyClass ( ICollection < MyObject > coll ) { Contract.Requires ( coll ! = null ) ; Contract.Requires ( Contract.ForAll ( coll , obj = > obj ! = null ) ) ; Contract.Requires ( Contract.ForAll ( coll , obj = > ( ? ? ? ? ) ) ; //What goes here ? } } public class MyObject { public object PropA { get ; set ; } public object PropB { get ; set ; } }",C # Code Contracts -- How to ensure that a collection of items contains items with unique properties ? "C_sharp : We have a hardware system with some FPGA 's and an FTDI USB controller . The hardware streams data over USB bulk transfer to the PC at around 5MB/s and the software is tasked with staying in sync , checking the CRC and writing the data to file.The FTDI chip has a 'busy ' pin which goes high while its waiting for the PC to do its business . There is a limited amount of buffering in the FTDI and elsewhere on the hardware.The busy line is going high for longer than the hardware can buffer ( 50-100ms ) so we are losing data . To save us from having to re-design the hardware I have been asked to 'fix ' this issue ! I think my code is quick enough as we 've had it running up to 15MB/s , so that leaves an IO bottleneck somewhere . Are we just expecting too much from the PC/OS ? Here is my data entry point . Occasionally we get a dropped bit or byte . If the checksum does n't compute , I shift through until it does . byte [ ] data is nearly always 4k . void ftdi_OnData ( byte [ ] data ) { List < byte > buffer = new List < byte > ( data.Length ) ; int index = 0 ; while ( ( index + rawFile.Header.PacketLength + 1 ) < data.Length ) { if ( CheckSum.CRC16 ( data , index , rawFile.Header.PacketLength + 2 ) ) // < - packet length + 2 for 16bit checksum { buffer.AddRange ( data.SubArray < byte > ( index , rawFile.Header.PacketLength ) ) ; index += rawFile.Header.PacketLength + 2 ; // < - skip the two checksums , we dont want to save them ... } else { index++ ; // shift through } } rawFile.AddData ( buffer.ToArray ( ) , 0 , buffer.Count ) ; }",Fixing gaps in streamed USB data "C_sharp : When I want to use a colon `` : '' in my string switch case statement I get the error `` unterminated string literal '' , how can I fix this and why does it give the error ? Code : If fixed it by doing this but do n't find it a good solution : EDIT : MVC Razor syntax are used @ switch ( stringText ) { case `` aaaa : ggg '' : Do something ... break ; case `` bbbb : ggg '' : Do something else ... break ; } const string extra = `` : ggg '' ; @ switch ( stringText ) { case `` aaaa '' + extra : Do something ... break ; case `` bbbb '' + extra : Do something else ... break ; }",String switch in Razor markup with colon in case statement causes error `` unterminated string literal '' "C_sharp : There is no difference between these two lines , because the compiler , in the second line , understands that it is an array of type int.But why ca n't I do this with different types ? Why does n't the compiler convert my variable to type object ? EDIT : Thanks for all your answers . But I still wonder , what are the pros and cons to make all expressions that the compiler ca n't convert to type object ? ( Because I use var notation which means that it ca n't be any type . I understand like this . ) Why does n't the compiler find the nearest type of the array members by going up the inheritance tree ? var x = new int [ ] { 1 , 2 , 3 } ; //Fine , x is int [ ] var x = new [ ] { 1 , 2 , 3 } ; //Fine , x is int [ ] var x = new object [ ] { 1 , `` df '' , 5 } ; //Fine , x is object [ ] var x = new [ ] { 1 , `` df '' , 5 } ; //Error ! `` No best type found for implicity-typed-array ''",Why does n't the compiler convert var [ ] to object [ ] in c # ? C_sharp : Can anyone shed light on why GetFile ( ) is empty when I enumerate `` C : \Windows\System32\Tasks '' ? I have checked this : VS is running as AdminNo exception is thrownThere are files in rootI can copy files out ( via explorer ) to another folder and it works System.IO.Directory.GetFiles ( @ '' C : \Windows\System32\Tasks '' ) ;,System.IO.Directory.GetFiles Empty "C_sharp : I have a small website I implemented with AngularJS , C # and Entity Framework . The whole website is a Single Page Application and gets all of its data from one single C # web service.My question deals with the interface that the C # web service should expose . For once , the service can provide the Entities in a RESTful way , providing them directly or as DTOs . The other approach would be that the web service returns an object for exactly one use case so that the AngularJS Controller only needs to invoke the web service once and can work with the responded model directly.To clarify , please consider the following two snippets : AndWhile the first example exposes a RESTful interface and works with the resource metaphor , it has the huge drawback of only returning parts of the data . The second example returns an object tailored to the needs of the MVC controller , but can most likely only be used in one MVC controller . Also , a lot of mapping needs to be done for common fields in the second scenario.I found that I did both things from time to time in my webservice and want to get some feedback about it . I do not care too much for performance , altough multiple requests are of course problematic and once they slow down the application too much , they need refactoring . What is the best way to design the web service interface ? // The service returns DTOs , but has to be invoked multiple // times from the AngularJS controller public Order GetOrder ( int orderId ) ; public List < Ticket > GetTickets ( int orderId ) ; // The service returns the model directly public OrderOverview GetOrderAndTickets ( int orderId ) ;",AngularJS and Web Service Interaction Best Practices C_sharp : How to set the value of ISync.SyncTimestamp ? I tried casting the `` this . '' but it does n't work [ DataContract ] public class OrderSyncData : ISync { public OrderSyncData ( Order o ) { this.CurrentOrderStatus = o.DriverStatus ; this.StatusDescription = o.StatusDescription ; SyncTimestamp = o.SyncTimestamp ; ? ? ? ? } [ DataMember ] public string CurrentOrderStatus { get ; set ; } [ DataMember ] public string StatusDescription { get ; set ; } [ DataMember ] // I do n't think I need these any more public bool IsCanceled { get ; set ; } [ DataMember ] public bool IsResolved { get ; set ; } [ DataMember ] public bool IsPendingResponse { get ; set ; } DateTime ISync.SyncTimestamp { get ; set ; } },how to set value of property in constructor ( explicit interface implementation ) "C_sharp : If I do the following : Does the person that was in person [ 0 ] still exists in memory because it 's Sneezing delegate has a reference to the Person_Sneezing method or does it get collected by the GC ? public class Test { public static void Main ( ) { List < Person > persons = new List < Person > { new Person ( ) } ; persons [ 0 ] .Sneezing += new EventHandler ( Person_Sneezing ) ; persons = null ; } public static void Person_Sneezing ( object sender , EventArgs e ) { ( sender as Person ) .CoverFace ( ) ; } }",Does garbage collector clear objects subscribed to events ? "C_sharp : I used netsh for add my application to firewall as follows . Before I add it to the firewall , how to I know that the application has not been added to the firewall ? because I do not want add my application to the firewall repeatedly . ProcessStartInfo info = null ; try { using ( Process proc = new Process ( ) ) { string productAssembly = new Uri ( Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ) .CodeBase ) ) .LocalPath + `` \\ '' + this.ProductName + `` .exe '' ; string args = string.Format ( CultureInfo.InvariantCulture , `` advfirewall firewall add rule name=\ '' { 0 } \ '' dir=in action=allow program=\ '' { 1 } \ '' enable=yes '' , this.ProductName , productAssembly ) ; info = new ProcessStartInfo ( `` netsh '' , args ) ; proc.StartInfo = info ; proc.StartInfo.UseShellExecute = false ; proc.StartInfo.CreateNoWindow = true ; proc.StartInfo.RedirectStandardOutput = false ; proc.Start ( ) ; } } catch ( Exception ex ) { MessageBox.Show ( ex.Message ) ; }",How do I know my application has not been added to the firewall ? "C_sharp : I have a Sitecore 7 Controller Rendering . I need to vary the OutputCache by a custom method.The rendering is currently set to `` Cachable '' , `` VaryByData '' and `` VaryByParm '' in Sitecore.I 've added an output cache attribute to my action , and set a custom vary string : My Global.asax inherits from Sitecore.Web.Application , and I 've overridden GetVaryByCustomString as follows : I 'm never seeing the GetVaryByCustomString method fire , and the controller is behaving as though it did n't have an OutputCache attribute on it at all ... It 's as though it 's actually just doing the default `` Cachable '' , `` VaryByData '' , `` VaryByParm '' behaviour from Sitecore.Any clues ? [ OutputCache ( VaryByCustom = `` ThisIsATest '' , Duration = 60 ) ] public ActionResult Index ( ) { ... } public override string GetVaryByCustomString ( HttpContext context , string custom ) { if ( custom == `` ThisIsATest '' ) return `` some custom key '' ; return base.GetVaryByCustomString ( context , custom ) ; }",Can I use VaryByCustom with a Sitecore 7 Controller Rendering ? "C_sharp : Windows 8.1 comes with a feature called `` SlideToShutdown '' . I am trying to call that executable file programmatically . I tried Process.Start ( ) ; in C # , Shell ( ) in VB and ( void ) system ( ) ; in C. It says error as ' C : \Windows\System32\SlideToShutdown.exe ' is not recognized as an internal or external command , operable program or batch file . But in command prompt when I execute start C : \windows\system32\slidetoshutdown.exe it works perfectly.This is my C program ( named a.c ) to call itPlease help me . # include < stdlib.h > # include < stdio.h > int main ( ) { ( void ) system ( `` C : \\Windows\\System32\\SlideToShutDown.exe '' ) ; return ( 0 ) ; }",A specific exe file can not be called programmatically C_sharp : I have the following piece of example code : line 3 errors with an Overflow exception . However i want to achieve the same result like i would subtract 2 unsigned shorts in C and they over/underflow.What is the most proper way to achieve this ? UInt16 a = 0x3A ; UInt16 b = 0xFFDF ; UInt16 result = Convert.ToUInt16 ( a - b ) ;,c # uint to ushort overflow like in native C "C_sharp : I 'm working with drawing a long string to a bitmap ( talking more than a million characters ) , including multiline characters \r\n , written by a StringBuilder.My Text to Bitmap code is as follows : Normally , it works as expected -- but only when used for single characters . However , the issue lies when a multitude of characters are used . Simply put , extra lines appear both vertically and horizontally when drawn on to the image.This effect is demonstrated here , zoomed in 1:1 ( see the full Image ) : However , I can render this same text in Notepad++ with just the output of the string and it 's essentially as expected : I can view it in any other text viewer ; the result will be the same.So how , and why , is the program rendering the Bitmap with those 'extra ' lines ? public static Bitmap GetBitmap ( string input , Font inputFont , Color bmpForeground , Color bmpBackground ) { Image bmpText = new Bitmap ( 1 , 1 ) ; try { // Create a graphics object from the image . Graphics g = Graphics.FromImage ( bmpText ) ; // Measure the size of the text when applied to image . SizeF inputSize = g.MeasureString ( input , inputFont ) ; // Create a new bitmap with the size of the text . bmpText = new Bitmap ( ( int ) inputSize.Width , ( int ) inputSize.Height ) ; // Instantiate graphics object , again , since our bitmap // was modified . g = Graphics.FromImage ( bmpText ) ; // Draw a background to the image . g.FillRectangle ( new Pen ( bmpBackground ) .Brush , new Rectangle ( 0 , 0 , Convert.ToInt32 ( inputSize.Width ) , Convert.ToInt32 ( inputSize.Height ) ) ) ; // Draw the text to the image . g.DrawString ( input , inputFont , new Pen ( bmpForeground ) .Brush , new PointF ( 0 , 0 ) ) ; } catch { // Draw a blank image with background . Graphics.FromImage ( bmpText ) .FillRectangle ( new Pen ( bmpBackground ) .Brush , new Rectangle ( 0 , 0 , 1 , 1 ) ) ; } return ( Bitmap ) bmpText ; }",Drawing a Long String on to a Bitmap results in Drawing Issues "C_sharp : In my server side blazor project ( core 3 , preview6 ) I 'm trying to invoke javascript with an instance of my class . You can do this by injecting a IJSRuntime and calling InvokeAsync on it ( see here ) . Because I need to get rid of all the null properties ( the js library that should handle my object ( chartJs ) can not handle null values ) and because I have some custom serialization ( for enums that can have different datatypes ) , I hacked it to work with an ExpandoObject ( that was not my idea but it works ) . I first serialized my object with json.net so I could define NullValueHandling = NullValueHandling.Ignore and so all the custom converters got used . Then I used json.net again to parse it to an ExpandoObject . I of course did that because otherwise the values that are n't in the json would be null in the c # instance but this way they are n't present at all . This ExpandoObject which does n't have the null values and which has the correct enum values , is then used to invoke the javascript . This way there are no null values when it gets to the javascript engine.Since in preview6 json.net is n't used internally anymore and the new json serializer ( from System.Text.Json ) can not handle ExpandoObjects , I got a runtime error when I updated from preview5 to preview6 , saying that ExpandoObject is n't supported . No big deal , I made a function to convert an ExpandoObject to a Dictionary < string , object > which can be serialized without a problem.Read this question to see more about how I did this and to see some examples . This might be a good idea if you do n't quite understand what I did . Also it contains the json that I will add in here as well along with the c # model and other explanations.This works but I thought that maybe if I would be able to get back to json.net I could completely remove the ExpandoObject because firstly it would use the custom converters I wrote for my special enums and secondly I could specify NullValueHandling = NullValueHandling.Ignore globally ( ps . would this have sideeffects ? ) . I followed the ms docs on how to use json.net again and added this to the ConfigureServies method ( services.AddRazorPages ( ) was already there ) : Sadly it did not work and directly invoking js with the object led to the exact same json ( see below ) as before I added this . Then I tried using an ExpandoObject directly because I knew the new json serializer from .net ca n't handle that . As expected it threw an exception and the stacktrace shows no signs of json.net . This confirms that it 's not actually using json.net like I told it to . at System.Text.Json.Serialization.JsonClassInfo.GetElementType ( Type propertyType , Type parentType , MemberInfo memberInfo ) at System.Text.Json.Serialization.JsonClassInfo.CreateProperty ( Type declaredPropertyType , Type runtimePropertyType , PropertyInfo propertyInfo , Type parentClassType , JsonSerializerOptions options ) at System.Text.Json.Serialization.JsonClassInfo.AddProperty ( Type propertyType , PropertyInfo propertyInfo , Type classType , JsonSerializerOptions options ) at System.Text.Json.Serialization.JsonClassInfo..ctor ( Type type , JsonSerializerOptions options ) at System.Text.Json.Serialization.JsonSerializerOptions.GetOrAddClass ( Type classType ) at System.Text.Json.Serialization.JsonSerializer.GetRuntimeClassInfo ( Object value , JsonClassInfo & jsonClassInfo , JsonSerializerOptions options ) at System.Text.Json.Serialization.JsonSerializer.HandleEnumerable ( JsonClassInfo elementClassInfo , JsonSerializerOptions options , Utf8JsonWriter writer , WriteStack & state ) at System.Text.Json.Serialization.JsonSerializer.Write ( Utf8JsonWriter writer , Int32 flushThreshold , JsonSerializerOptions options , WriteStack & state ) at System.Text.Json.Serialization.JsonSerializer.WriteCore ( PooledByteBufferWriter output , Object value , Type type , JsonSerializerOptions options ) at System.Text.Json.Serialization.JsonSerializer.WriteCoreString ( Object value , Type type , JsonSerializerOptions options ) at System.Text.Json.Serialization.JsonSerializer.ToString [ TValue ] ( TValue value , JsonSerializerOptions options ) at Microsoft.JSInterop.JSRuntimeBase.InvokeAsync [ T ] ( String identifier , Object [ ] args ) at ChartJs.Blazor.ChartJS.ChartJsInterop.GetJsonRep ( IJSRuntime jSRuntime , Object obj ) I then also tried just changing the options from the normal serializer to see if that would change anything . I used this instead of AddNewtonsoftJson : Interestingly this still gave me the same result.I will add the json that got produced along with what should be produced . You can also find this in the CodeReview question I mentioned earlier . The following json is what I get : It stays the same whenI do n't specify anything in the ConfigureServices method.I specify to use Newtonsoft.Json through AddNewtonsoftJson . I specify the JsonOptions from .net through AddJsonOptions . This is what I should get . Notice all the null values are removed and the custom converter is used . I was only able to get this with my hacky solution that uses the ExpandoObject.So why is it still using System.Text.Json instead of Newtonsoft.Json even though I instructed it to ? What else do I have to add to make it use json.net ? services.AddRazorPages ( ) .AddNewtonsoftJson ( o = > { o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore ; o.SerializerSettings.ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy ( true , false ) } ; } ) ; services.AddRazorPages ( ) .AddJsonOptions ( o = > o.JsonSerializerOptions.IgnoreNullValues = true ) ; { `` options '' : { `` someInt '' : 2 , `` someString '' : null , `` axes '' : [ { `` someString '' : null } , { `` someString '' : `` axisString '' } ] } , `` data '' : { `` data '' : [ 1 , 2 , 3 , 4 , 5 ] , `` someString '' : `` asdf '' , `` someStringEnum '' : { } < -- this is one of those special enums with a custom converter } } { `` options '' : { `` someInt '' : 2 , `` axes '' : [ { } , { `` someString '' : `` axisString '' } ] } , `` data '' : { `` data '' : [ 1 , 2 , 3 , 4 , 5 ] , `` someString '' : `` asdf '' , `` someStringEnum '' : `` someTestThing '' < -- this is one of those special enums with a custom converter } }",IJSRuntime ignores custom json serializer in server side blazor project "C_sharp : Say we have an IEnumerable < T > stuff ; Is there a concise way to Take n elements and then another m elements after the first , without re-evaluating ? example code : What I was thinking was maybe this ( not working code ) Edit to add to the difficulty and to clarify the complexity of what I would like to accomplish : I want to continue the query after the Take , i.e . stuff.Take ( 10 ) ; stuff.Skip ( 10 ) .Take ( 20 ) ; // re-evaluates stuff var it = stuff.GetEnumerator ( ) ; it.Take ( 10 ) ; it.Take ( 20 ) ; it.Take ( 10 ) ; var cont = it.Select ( Mutate ) ; cont.Take ( 20 ) ; cont = cont.Where ( Filter ) ; cont.Take ( 5 ) ;",LINQ continue after Take C_sharp : Based on what i have read asp.net core have dropped the synchronization context . This means that the thread that executes codes after await call might not be the same one that executes codes before awaitSo is HttpContext still safe to use in async methods ? or is it possible to get a different context after the await call ? For example in a controller actioncould context1 be different from context2 ? and the recommended way to get the context in none controller method is by dependency injecting IHttpContextAccessor Is IHttpContextAccessor.HttpContext safe from async await pattern ? I.E . could context1 be different from context2 ? public async Task < IActionResult > Index ( ) { var context1 = HttpContext ; await Task.Delay ( 1000 ) ; var context2 = HttpContext ; ... . } public async void Foo ( IHttpContextAccessor accessor ) { var context1 = accessor.HttpContext ; await Task.Delay ( 1000 ) ; var context2 = accessor.HttpContext ; },is HttpContext async safe in asp.net core ? "C_sharp : I am creating a service using Microsoft ASP.NET Web API with the following requirements : Input must be in XML ( no json ) XML will follow a standard ( can not add custom element names/attributes to the input xml ) When encountering exceptions in deserialization ( i.e . data values in bad format ) they must be logged as warnings and parsing of the input xml must continue The XML will contain collections of elements in which the elements need to bedeserialized into types derived from a base typeRequirements 1 and 2 simply define my input . I started developing my solution by using the built-in System.Xml.Serialization.XmlSerializer class , but had to abandon it because it could not handle requirement # 3.Alternately , I found YAXLib which provided a very useful way to handle requirement # 3 . YAXLib also handles requirement # 4 , but only by utilizing custom attributes in the XML : Because of requirement # 2 , I can not use this approach . I need something like the System.Xml.Serialization.XmlElementAttribute so I can instruct the serializer in code , not in the data . Is there an existing solution out there that will handle all of these requirements ? Example : InputC # ClassesExpected OutputObjects in the Items collection of the DEALS class should be deserialized into their respective types : COLLATERALS and LOANS . Also , the first collateral with the value 'xyz ' will not get deserialized ( since the type is decimal ) but the remaining valid COLLATERAL items would get deserialized . The error parsing 'xyz ' to decimal should be logged somehow . < ListOfObjects > < Object yaxlib : realtype= '' System.Int32 '' > 7 < /Object > < Object yaxlib : realtype= '' System.Double '' > 3.14 < /Object > < Object yaxlib : realtype= '' System.String '' > Congrats < /Object > < Object yaxlib : realtype= '' System.StringSplitOptions '' > RemoveEmptyEntries < /Object > < /ListOfObjects > < DEALS > < DEAL > < COLLATERALS > < COLLATERAL > xyz < /COLLATERAL > < COLLATERAL > 1.2 < /COLLATERAL > < COLLATERAL > 4.5 < /COLLATERAL > < /COLLATERALS > < LOANS > < LOAN > < CLOSING_INFORMATION / > < /LOAN > < /LOANS > < /DEAL > < /DEALS > public class DEAL { [ System.Xml.Serialization.XmlElementAttribute ( `` COLLATERALS '' , typeof ( COLLATERALS ) ) ] [ System.Xml.Serialization.XmlElementAttribute ( `` LOANS '' , typeof ( LOANS ) ) ] [ YAXCollection ( YAXCollectionSerializationTypes.RecursiveWithNoContainingElement ) ] public object [ ] Items { get { return this.itemsField ; } set { this.itemsField = value ; } } // Remaining implementation details omitted.. } public class COLLATERALS { /* details omitted.. */ } public class LOANS { /* details omitted.. */ } public class COLLATERAL { [ System.Xml.Serialization.XmlTextAttribute ( ) ] public decimal Value { get ; set ; } }",XML Deserialization with Polymorphism and Exception Handling "C_sharp : The async keyword do cause the CIL to change ( even if there 's no await inside the method ) , but it is primarily to allow await to be present.But I did not expect the following to happen : This print : But if I change toIt prints : QuestionWhy do n't I see the delay ? The TCS is only resolved after three seconds . Meanwhile , the task is not resolved and should be awaited . static void Main ( string [ ] args ) { Task t = Go ( ) ; t.Wait ( ) ; } static async Task Go ( ) { Console.WriteLine ( 1 ) ; await AAA ( 3000 ) ; Console.WriteLine ( 2 ) ; } static Task < object > AAA ( int a ) // < -- - No ` async ` { TaskCompletionSource < object > tcs = new TaskCompletionSource < object > ( ) ; Task.Delay ( a ) .ContinueWith ( b = > tcs.SetResult ( null ) ) ; return tcs.Task ; } 1 ( wait ) 2 static Task < object > AAA ( int a ) static async Task < object > AAA ( int a ) 12 ( no wait )",Why does my TCS not await ? "C_sharp : Are there any best practices on returning different return types on overloaded methods ? For instance if I have a Load method in my DAL , I either want to load a single item or a bunch of items . I know that I could use a number of approaches : Load one objectLoad multiple objectsNow something I know I can do is to overload one method and have different return types . Like so : AndWhile it seems there 's nothing to stop me doing this , and it keeps things tidy from an API perspective , does this seem like a good idea ? I came across it last night and part of me thinks I should n't be doing this for the reason of wanting matching return types for overloaded method.I could also have the Load ( int id ) method return a collection that only holds one item . It seems to me that this violates the principle of least surprise though in that if you 're expecting one item returned , you should return that item , you should n't return a list containing a single item.So here are my conflicting thoughts surrounding these ideas : Overloaded methods should all return the same type . If methods do the same thing , do n't give them a bunch of different names , overload the same method name . It makes things simpler from an API user 's perspective , they do n't have to trawl through a bunch of different methods that all essentially do the same thing but with different parameters . Return the most obvious type for the method , i.e . if the user is likely to be expecting a collection of items , return a collection of items , if they are likely to be expecting a single item , return a single item.So the latter two thoughts kind of outweigh the first , but at the same time , the first thought seems like a programmatic best practice of sorts.Are there any best practices surrounding this practice ? I 'd be interested to hear others ' thoughts on the subject . MyBusinessObject LoadOne ( int id ) { } MyBusinessObject [ ] LoadMany ( params int [ ] ids ) { } MyBusinessObject Load ( int id ) { } MyBusinessObject [ ] Load ( params int [ ] ids ) { }",Should I use different return types on overloaded methods ? "C_sharp : The System.Threading.ConcurrentQueue.TryDequeue method threw an exception the other day that took me totally by surprise . Here 's the stack trace : At first I thought the problem was that TryDequeueCore called the Random constructor with a bad value . But further investigation reveals that TryDequeueCore calls the default constructor . It looks to me like the error is in the Random constructor : As the documentation for the System.Environment.TickCount property says : The value of this property is derived from the system timer and is stored as a 32-bit signed integer . Consequently , if the system runs continuously , TickCount will increment from zero to Int32.. : :.MaxValue for approximately 24.9 days , then jump to Int32.. : :.MinValue , which is a negative number , then increment back to zero during the next 24.9 days.So , if you call the Random constructor during that one-millisecond period ( after the system has been up for int.MaxValue milliseconds ) , it 's going to throw this exception.Does anybody have a workaround ? For my own code , I can make a CreateRandom method that gets the TickCount value and checks it for int.MinValue . But what to do about code that I have no control over ? I hope the RTL team fixes this in .NET 4.0.Update 2009/07/22 : The BCL Team responded to the bug and said that it has been resolved for the next release . System.OverflowException : Negating the minimum value of a twos complement number is invalid . at System.Math.AbsHelper ( Int32 value ) at System.Random..ctor ( Int32 Seed ) at System.Threading.Collections.ConcurrentQueue ` 1.TryDequeueCore ( T & result ) at System.Threading.Collections.ConcurrentQueue ` 1.TryDequeue ( T & result ) at MyProgram.ThreadProc ( ) in c : \MyProgram\Main.cs : line 118 at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) .method public hidebysig specialname rtspecialname instance void .ctor ( ) cil managed { // Code size 12 ( 0xc ) .maxstack 8 IL_0000 : ldarg.0 IL_0001 : call int32 System.Environment : :get_TickCount ( ) IL_0006 : call instance void System.Random : :.ctor ( int32 ) IL_000b : ret } // end of method Random : :.ctor",Bug in System.Random constructor ? "C_sharp : My program uses SHA-1 certificate for SSL connection . The SHA-2 certificate has been widely used now by some web services ( Gmail ) instead . This causes blocking incoming connection to SMTP servers during email notification setup.To send email I use SmtpClient like thisI ca n't send an email by using this code and I do n't want to allow `` less secure apps '' in my gmail account.How to implement or switch to SHA-2 certificate for email notifications ? using ( var smtpClient = new SmtpClient ( serverSettings.SmtpServerName , ( int ) serverSettings.SmtpPort ) ) { smtpClient.EnableSsl = serverSettings.SmtpUseSsl ; smtpClient.UseDefaultCredentials = false ; if ( ! string.IsNullOrEmpty ( serverSettings.UserName ) || ! string.IsNullOrEmpty ( serverSettings.EncryptedPassword ) ) { smtpClient.Credentials = new NetworkCredential ( serverSettings.UserName , serverSettings.EncryptedPassword ) ; } ... smtpClient.Send ( message ) ; }",How to switch between using SHA-2 instead of SHA-1 ? "C_sharp : So I have an almost 1:1 ratio of views to view models and things seem to be going well . If I understand their purpose correctly it seems that view models should `` Strip down '' Entity models so that only relevant properties are passed to the presentation layer Add additional information needed for presentation such as a list of state abbreviations or contact types when creating , say , an address.In trying to keep with those principles I 've sort of hit a bit of a wall with my Reports controller . Various reports that are generated for a customer require access to about 30 or so different properties . As such , my view model ends up looking very similar to my Entity model.Of course the easiest solution is to just pass the Entity model to the view so that I 'll have access to all properties , however I also need to be able to generate reports for blank or `` incomplete '' customers . This causes problems will null reference exceptions when trying to access navigation properties on my Entity models.So I can either use a null check on just about every field within the view , which does n't seem too appealing ... OR I could implement a view model to avoid the null reference exceptions . The problem is that I 'd end up with a view model that looked like this : Typing all those properties out is one of those things that just feels wrong . Am I missing a more elegant solution to this problem ? var customer = customersRepository.GetCustomer ( id ) ; var viewModel = new CustomersViewModel ( ) { FirstName = customer.FirstName , LastName = customer.LastName , Address = customer.MailingAddress.Address , City = customer.MailingAddress.City , // and on and on for about 30 different properties } ; return View ( viewModel ) ;",ASP.NET MVC : How do I handle a view model with many properties ? "C_sharp : In my Application_Start I configure Unity using the Unity-AutoRegistration tool : My UnityFactory class is static . Configure works as follows : It runs under IIS7 and all works fine when when it 's started.It stops working whenever the application pool has been recycled . The configuration somehow gets messed up , and it is not able to resolve my classes anymore . However , the static field configuration in the UnityFactory class still contains the configuration as was provided the first time . So the class itself has n't changed.The Application_Start method is not triggered after the application pool has been recycled , so the configuration is not applied again.If I set a breakpoint and manually apply the configuration again , it all works again.What is happening here ? Why is Unity forgetting about all my classes ? And is there an event I can subscribe to which allows me to know when the pool has been recycled ? UnityFactory.Configure ( config = > config .Include ( If.ImplementsITypeName , Then.Register ( ) ) .ExcludeSystemAssemblies ( ) ) ; public static void Configure ( Func < IAutoRegistration , IAutoRegistration > configuration ) { // Store the configuration to be able to apply it again when needed UnityFactory.configuration = configuration ; // Create new UnityContainer container = new UnityContainer ( ) ; // Apply configuration configuration ( container.ConfigureAutoRegistration ( ) ) .ApplyAutoRegistration ( ) ; }",Unity configuration missing after application pool restart "C_sharp : I have the code : I do n't know if anything like this is possible ? I want to do it in one line.This is what I have in mind : I know it 's stupid but I want something similar . The method that has player as a parameter is unique to the Enemy object . I have to parse to call it . foreach ( var o in objects ) { o.Update ( time ) ; if ( o is Portal ) { var a = ( Portal ) o ; a.Interact ( ref player , player.Interact ) ; } else if ( o is Enemy ) { var e = ( Enemy ) o ; e.Update ( time , player ) ; } } ( Enemy ) o = > Update ( time , player ) ;",Cast different objects and call a method in same line ? "C_sharp : Does anyone know what the CancellationToken does if you add it with a parameter in the for example https : //mongodb.github.io/mongo-csharp-driver/2.3/apidocs/html/M_MongoDB_Driver_IMongoCollectionExtensions_UpdateMany__1.htmIs it a rollback ? Or what does it do ? public static UpdateResult UpdateMany < TDocument > ( this IMongoCollection < TDocument > collection , Expression < Func < TDocument , bool > > filter , UpdateDefinition < TDocument > update , UpdateOptions options = null , CancellationToken cancellationToken = null )",MongoDB C # driver CancellationToken "C_sharp : I noticed a strange behavior while debugging an ASP.NET Web Application ( .NET 4.6.1 ) . Whenever an HTTP error occurs ( e.g . 404 or 403 ) the request get duplicated up to a total of 3 times.I have tested this singular issue using fiddler , and Intellitrace effectively shows me the three identical requests ( even if I send just a single request ) .I can see the effects of this issue because any Owin middleware in the pipeline is invoked three times . A simple middleware like this : Will print three consecutive `` HIT ! '' into the console.This happens only if the request generates an error , and not if the request is handled by a middleware ( e.g . not if the middleware responds with a 2XX status code ) .What 's going on ? I 'm running VS2015 and IIS Express 10 on Win10 . [ EDIT ] It may be related to my Web.config configuration ? I 'm adding an excerpt from it . app.Use ( async ( c , n ) = > { Debug.WriteLine ( `` HIT ! `` ) ; await n.Invoke ( ) ; } ) ; < system.web > < compilation debug= '' true '' targetFramework= '' 4.6.1 '' / > < httpRuntime targetFramework= '' 4.6.1 '' enableVersionHeader= '' false '' / > < /system.web > < system.webServer > < httpProtocol > < customHeaders > < clear / > < /customHeaders > < redirectHeaders > < clear / > < /redirectHeaders > < /httpProtocol > < security > < requestFiltering removeServerHeader= '' true '' / > < /security > < handlers > < remove name= '' ExtensionlessUrlHandler-Integrated-4.0 '' / > < remove name= '' OPTIONSVerbHandler '' / > < remove name= '' TRACEVerbHandler '' / > < add name= '' ExtensionlessUrlHandler-Integrated-4.0 '' path= '' * . '' verb= '' * '' type= '' System.Web.Handlers.TransferRequestHandler '' preCondition= '' integratedMode , runtimeVersionv4.0 '' / > < /handlers > < modules runAllManagedModulesForAllRequests= '' true '' / > < /system.webServer >",Duplicated requests when debugging ASP.NET on IIS Express "C_sharp : A few of my API endpoints have models that include enums . FluentValidation is being used to verify that the values sent across meet their respective requirements . To aid in usability and document generation , enums are allowed to be sent as strings rather than integers . Validation that the value sent across is in the correct range works fine if an invalid integer is sent , but serialization will fail if an invalid string is sent across.My desired outcome would be to simply deserialize the enum property to null when the string does not match any of the enum 's fields so that the model can be passed through to the validator to create a friendly message.How can I achieve this ? This is using net-core 3 preview 8 with the System.Text.Json API . public enum Foo { A = 1 , B = 2 } public class Bar { public Foo ? Foo { get ; set ; } } void Main ( ) { var options = new JsonSerializerOptions ( ) ; options.Converters.Add ( new JsonStringEnumConverter ( ) ) ; options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase ; var jsonString = `` { \ '' foo\ '' : \ '' C\ '' } '' ; var jsonSpan = ( ReadOnlySpan < byte > ) Encoding.UTF8.GetBytes ( jsonString ) ; try { var result = JsonSerializer.Deserialize < Bar > ( jsonSpan , options ) ; Console.WriteLine ( result.Foo == null ) ; } catch ( Exception ex ) { Console.WriteLine ( `` Serialization Failed '' ) ; } }",How can I get a null value instead of a serialization error when deserializing an enum by string conversion ? C_sharp : Given this entity model variable : The below code can not use from db varibale connection string DataBaseEntities db = new DataBaseEntities ( ) ; SqlBulkCopy sbc = new SqlBulkCopy ( db.Connection.ConnectionString ) ;,How to fetch entity model connection string ? C_sharp : Whenever I want to exercise a certain path of code that would otherwise only be reached under a difficult to reproduce condition like : I or it with a true value : Is there a more elegant approach ? if ( condition ) { code to be tested } if ( true || condition ) { code to be tested },Testing a difficult to reach code path "C_sharp : I wondering why my RabbitMQ RPC-Client always processed the dead messages after restart . _channel.QueueDeclare ( queue , false , false , false , null ) ; should disable buffers . If I overload the QueueDeclare inside the RPC-Client I ca n't connect to the server . Is something wrong here ? Any idea how to fix this problem ? RPC-ServerRPC-Client new Thread ( ( ) = > { var factory = new ConnectionFactory { HostName = _hostname } ; if ( _port > 0 ) factory.Port = _port ; _connection = factory.CreateConnection ( ) ; _channel = _connection.CreateModel ( ) ; _channel.QueueDeclare ( queue , false , false , false , null ) ; _channel.BasicQos ( 0 , 1 , false ) ; var consumer = new QueueingBasicConsumer ( _channel ) ; _channel.BasicConsume ( queue , false , consumer ) ; IsRunning = true ; while ( IsRunning ) { BasicDeliverEventArgs ea ; try { ea = consumer.Queue.Dequeue ( ) ; } catch ( Exception ex ) { IsRunning = false ; } var body = ea.Body ; var props = ea.BasicProperties ; var replyProps = _channel.CreateBasicProperties ( ) ; replyProps.CorrelationId = props.CorrelationId ; var xmlRequest = Encoding.UTF8.GetString ( body ) ; var messageRequest = XmlSerializer.DeserializeObject ( xmlRequest , typeof ( Message ) ) as Message ; var messageResponse = handler ( messageRequest ) ; _channel.BasicPublish ( `` '' , props.ReplyTo , replyProps , messageResponse ) ; _channel.BasicAck ( ea.DeliveryTag , false ) ; } } ) .Start ( ) ; public void Start ( ) { if ( IsRunning ) return ; var factory = new ConnectionFactory { HostName = _hostname , Endpoint = _port < = 0 ? new AmqpTcpEndpoint ( _endpoint ) : new AmqpTcpEndpoint ( _endpoint , _port ) } ; _connection = factory.CreateConnection ( ) ; _channel = _connection.CreateModel ( ) ; _replyQueueName = _channel.QueueDeclare ( ) ; // Do not connect any more _consumer = new QueueingBasicConsumer ( _channel ) ; _channel.BasicConsume ( _replyQueueName , true , _consumer ) ; IsRunning = true ; } public Message Call ( Message message ) { if ( ! IsRunning ) throw new Exception ( `` Connection is not open . `` ) ; var corrId = Guid.NewGuid ( ) .ToString ( ) .Replace ( `` - '' , `` '' ) ; var props = _channel.CreateBasicProperties ( ) ; props.ReplyTo = _replyQueueName ; props.CorrelationId = corrId ; if ( ! String.IsNullOrEmpty ( _application ) ) props.AppId = _application ; message.InitializeProperties ( _hostname , _nodeId , _uniqueId , props ) ; var messageBytes = Encoding.UTF8.GetBytes ( XmlSerializer.ConvertToString ( message ) ) ; _channel.BasicPublish ( `` '' , _queue , props , messageBytes ) ; try { while ( IsRunning ) { var ea = _consumer.Queue.Dequeue ( ) ; if ( ea.BasicProperties.CorrelationId == corrId ) { var xmlResponse = Encoding.UTF8.GetString ( ea.Body ) ; try { return XmlSerializer.DeserializeObject ( xmlResponse , typeof ( Message ) ) as Message ; } catch ( Exception ex ) { IsRunning = false ; return null ; } } } } catch ( EndOfStreamException ex ) { IsRunning = false ; return null ; } return null ; }","RabbitMQ durable queue does not work ( RPC-Server , RPC-Client )" "C_sharp : Recently , I was running into a problem which I 'm still breaking my head over . In an application , I registered a dispatcher exception handler . In the same application , a third-party-component ( DevExpress Grid Control ) causes an exception within the event handler for Control.LayoutUpdated . I expect , that the dispatcher exception handler is triggered once . But instead , I get a stack overflow . I produced a sample without the third party component and discovered , that it happens in every WPF application.Is there any way to prevent this behavior ? It happens with .NET framework 3.0 , 3.5 , 4.0 and 4.5 . I ca n't just wrap a try-catch around the LayoutUpdated event handler since it is in a third party component and I do n't think , a stack overflow should happen . using System ; using System.Windows ; using System.Windows.Controls ; using System.Windows.Threading ; namespace MyApplication { /* App.xaml < Application xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' x : Class= '' MyApplication.App '' Startup= '' OnStartup '' / > */ public partial class App { private void OnStartup ( object sender , StartupEventArgs e ) { DispatcherUnhandledException += OnDispatcherUnhandledException ; MainWindow = new MainWindow ( ) ; MainWindow.Show ( ) ; } private static void OnDispatcherUnhandledException ( object sender , DispatcherUnhandledExceptionEventArgs e ) { MessageBox.Show ( e.Exception.Message ) ; e.Handled = true ; } } public class MainWindow : Window { private readonly Control mControl ; public MainWindow ( ) { var grid = new Grid ( ) ; var button = new Button ( ) ; button.Content = `` Crash ! `` ; button.HorizontalAlignment = HorizontalAlignment.Center ; button.VerticalAlignment = VerticalAlignment.Center ; button.Click += OnButtonClick ; mControl = new Control ( ) ; grid.Children.Add ( mControl ) ; grid.Children.Add ( button ) ; Content = grid ; } private void OnButtonClick ( object sender , RoutedEventArgs e ) { mControl.LayoutUpdated += ThrowException ; mControl.UpdateLayout ( ) ; mControl.LayoutUpdated -= ThrowException ; } private void ThrowException ( object sender , EventArgs e ) { throw new NotSupportedException ( ) ; } } }",Stack overflow after an exception in Control.LayoutUpdated if DispatcherUnhandledException is registered "C_sharp : I 'm upgrading a site by creating a new ASP.Net Mvc 5 skeleton and then dropping in the content.Currently all seems to be working except for the strongly typed views . All Model property access fails and it 's evident that the nongeneric controller is used.Example : I get the error 'object ' does not contain a definition for 'Title ' and no extension method ... Going to Definition on Model takes me here : How come it chooses the wrong item ? The project was created as a MVC4 project and then upgraded to MVC5 using nuget before any code was added . < % @ Page Language= '' C # '' MasterPageFile= '' ~/Views/Shared/Site.Master '' Inherits= '' System.Web.Mvc.ViewPage < MySite.Models.MyViewModel > '' % > < asp : Content ID= '' Content1 '' ContentPlaceHolderID= '' MainContent '' runat= '' server '' > < h1 > < % = Model.Title % > < /h1 > < /asp : Content > namespace System.Web.Mvc { // Summary : // Represents the properties and methods that are needed to render a view as // a Web Forms page . [ FileLevelControlBuilder ( typeof ( ViewPageControlBuilder ) ) ] public class ViewPage : Page , IViewDataContainer { < snip > public object Model { get ; }",Mvc 5 ViewPage < T > becomes non generic ViewPage when compiled "C_sharp : Basically the word.txt contains 170000 English words . Is there a collection class in C # that is faster than array of string for the above query ? There will be no insert or delete , just search if a string starts with `` abe '' or `` abdi '' .Each word in the file is unique.EDIT 1 This search will be performed potentially millions of times in my application . Also I want to stick with LINQ for collection query because I might need to use aggregate function.EDIT 2 The words from the file are sorted already , the file will not change string [ ] words = System.IO.File.ReadAllLines ( `` word.txt '' ) ; var query = from word in words where word.Length > `` abe '' .Length & & word.StartsWith ( `` abe '' ) select word ; foreach ( var w in query.AsParallel ( ) ) { Console.WriteLine ( w ) ; }",What is the most efficient collection class in C # for string search "C_sharp : I 'm trying to extract information out of rc-files . In these files , `` -chars in strings are escaped by doubling them ( `` '' ) analog to c # verbatim strings . is ther a way to extract the string ? For example , if I have the following string `` this is a `` '' test '' '' '' I would like to obtain this is a `` '' test '' '' . It also must be non-greedy ( very important ) .I 've tried to use the following regular expression ; However the performance was awful.I ' v based it on the explanation here : http : //ad.hominem.org/log/2005/05/quoted_strings.phpHas anybody any idea to cope with this using a regular expression ? `` ( ? < text > [ ^ '' '' ] * ( `` '' ( .| '' '' | [ ^ '' ] ) * ) * ) ''",regular expression for c # verbatim like strings ( processing `` '' -like escapes ) "C_sharp : Perhaps my expectations are wrong . I am not an cryptography expert , I 'm just a simple user . I have exhaustively tried to make this work with no success so far.Background information : I 'm trying to port a Legacy Encryption from Delphi Encryption Compendium which is using Blowfish Engine ( TCipher_Blowfish_ ) with CTS operation mode ( cmCTS ) . The private key is hashed by RipeMD256 ( THash_RipeMD256 ) .Problems : The input plain text array of bytes needs to be the same size of CIPHER_BLOCK . As far as I can tell it shouldn't.From Wikipedia : In cryptography , ciphertext stealing ( CTS ) is a general method of using a block cipher mode of operation that allows for processing of messages that are not evenly divisible into blocks without resulting in any expansion of the ciphertext , at the cost of slightly increased complexity.The output is not the same as the old routine : I 'm using : Same IVSame PasswordSame input plain textThe legacy application is using ANSI String , the new one uses Unicode , so for every input string I 've called Encoding.ASCII.GetBytes ( `` plainText '' ) , Encoding.ASCII.GetBytes ( `` privatepassword '' ) .The private password bytes is then hashed by RipeMD256 , I 've checked the output bytes and they are the same.I can confirm the problem is specific in the Bouncy Clastle ( operation mode or missing configuration/step ) because I 've downloaded a second library Blowfish.cs and using an input of 8 bytes ( same size as the cipher block ) and using the Encrypt_CBC ( bytes [ ] ) with the same IV results in the same output as the legacy format.This is the sketch of the code i 'm using for both Blowfish.cs and Bouncy Castle : Delphi Encryption CompendiumBlofish.csI assume that CTS and CBC will always have the same result if the input is 8 bits length . Is this just lucky/coincidence or is fundamentally truth ? Bouncy CastleAs I said , I 'm comparing CBC with CTS based on the assumption that given a 8 bytes input , the output will be the same . I can not forward the implementation with Bouncy Castle if even with the same input the output is not the same.I Do n't Know : If the CTS Mode used in Delphi Encryption Compendium uses CBC along with CTS . I Could n't find documented anywhere.The difference between calling just DoFinal ( ) and ProcessBytes ( ) then DoFinal ( ) in Bouncy Castle , I imagine that is required when the input block is larger than engine block size , in this case they are the same size.If Delphi Encryption Compendium is correct/wrong or If Bouncy Castle is correct/wrong . I do n't have enough knowledge in cryptography to understand the implementation , otherwise I would n't ask a question here ( I need guidance ) . var IV : Array [ 0..7 ] of Byte ( 1,2,3,4,5,6,7,8 ) ; Key : String = '12345678 ' ; with TCipher_Blowfish.Create ( `` , nil ) dobegin try InitKey ( Key , @ IV ) ; //Key is auto hashed using RIPE256 here ; Result : = CodeString ( '12345678 ' , paEncode , -1 ) ; //Output bytes is later encoded as MIME64 here , the result is the hash . finally Free ; end ; end ; var hashOfPrivateKey = HashValue ( Encoding.ASCII.GetBytes ( `` 12345678 '' ) ) ; Blowfish b = new BlowFish ( hashOfPrivateKey ) ; b.IV = new byte [ 8 ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; var input = Encoding.ASCII.GetBytes ( `` 12345678 '' ) ; var output = b.Encrypt_CBC ( input ) ; IBufferedCipher inCipher = CipherUtilities.GetCipher ( `` BLOWFISH/CTS '' ) ; var hashOfPrivateKey = HashValue ( Encoding.ASCII.GetBytes ( `` 12345678 '' ) ) ; var key = new KeyParameter ( hashOfPrivateKey ) ; var IV = new byte [ 8 ] { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; var cipherParams = new ParametersWithIV ( key , IV ) ; inCipher.Init ( true , cipherParams ) ; var input = Encoding.ASCII.GetBytes ( `` 12345678 '' ) ; //try one : direct with DoFinalvar output = inCipher.DoFinal ( input ) ; // output bytes different from expectedinCipher.Reset ( ) ; //try two : ProcessBytes then DoFinalvar outBytes = new byte [ input.Length ] ; var res = inCipher.ProcessBytes ( input , 0 , input.Length , outBytes , 0 ) ; var r = inCipher.DoFinal ( outBytes , res ) ; // outBytes bytes different from expected",Bouncy Castle CTS Mode for Blowfish Engine not working as expected "C_sharp : We are using Rebus as a queue system with Sql server . We have several recipients for different types of messages . Each message can be handled by several workers of a certain type.One message should only be handled/processed by one worker ( the first one that pulls it ) . If a worker for some reason ca n't finish it , it postpones the message using the timeout service.If I have understood it correctly , it becomes a TimeoutRequest and put in the timeouts table . When it 's time to rerun , it becomes a TimeoutReply before it is reintroduced into the queue as the original message.The problem we are having is that when it becomes a TimeoutReply , all the workers pick it up and create the original message . One original message becomes several messages ( as many as there are workers ) when timed out . Our Rebus setup is the following : '' Server side '' : '' Worker side '' : Any help in solving the problem or to provide understanding is greatly appreciated ! var adapter = new BuiltinContainerAdapter ( ) ; Configure.With ( adapter ) .Logging ( l = > l.Log4Net ( ) ) .Transport ( t = > t.UseSqlServerInOneWayClientMode ( connectionString ) .EnsureTableIsCreated ( ) ) .CreateBus ( ) .Start ( ) ; return adapter ; _adapter = new BuiltinContainerAdapter ( ) ; Configure.With ( _adapter ) .Logging ( l = > l.Log4Net ( ) ) .Transport ( t = > t.UseSqlServer ( _connectionString , _inputQueue , `` error '' ) .EnsureTableIsCreated ( ) ) .Events ( x = > x.AfterMessage += ( ( bus , exception , message ) = > SendWorkerFinishedJob ( exception , message ) ) ) .Events ( x = > x.BeforeMessage += ( bus , message ) = > SignalWorkerStartedJob ( message ) ) .Behavior ( x = > x.SetMaxRetriesFor < Exception > ( 0 ) ) .Timeouts ( x = > x.StoreInSqlServer ( _connectionString , `` timeouts '' ) .EnsureTableIsCreated ( ) ) .CreateBus ( ) .Start ( numberOfWorkers ) ;",How can we avoid multiple Rebus messages when its has been timed out ? "C_sharp : I was implementing sync/async overloads when I came across this peculiar situation : When I have a regular lambda expression without parameters or a return value it goes to the Run overload with the Action parameter , which is predictable . But when that lambda has a while ( true ) in it it goes to the overload with the Func parameter.Output : action funcSo , how can that be ? Is there a reason for it ? public void Test ( ) { Run ( ( ) = > { var name = `` bar '' ; } ) ; Run ( ( ) = > { while ( true ) ; } ) ; } void Run ( Action action ) { Console.WriteLine ( `` action '' ) ; } void Run ( Func < Task > func ) // Same behavior with Func < T > of any type . { Console.WriteLine ( `` func '' ) ; }",Peculiar overload resolution with while ( true ) "C_sharp : I am working on open source community project Azure Media Services Upload and Play Videos in MVC since 2015 . I was not using any delivery encryption earlier , so I started working on AES.In all the source code/samples by Azure Media Services Team , i noticed test token was being generated just after uploading the content and this works well in my case too . But , how do I generate test token next time onward for playback ? What I understood is that , we need token each time player requests playback . Technically , player creates a request to key service provider and received updated token.So to get updated token , I tried couple of ways n not able to fix this , i see error `` A ContentKey ( Id = ' ... ' , Type = 'EnvelopeEncryption ' ) which contains the same type already links to this asset '' . This looks like a valid error message because key of type EnvelopeEncryption was already added and associated with asset after uploading content , and upon requesting again this pops-up.The code given below is copied from here.Above method calls media service key service provider.How do I fix this ? public ActionResult Index ( ) { var model = new List < VideoViewModel > ( ) ; var videos = db.Videos.OrderByDescending ( o = > o.Id ) .ToList ( ) ; foreach ( var video in videos ) { var viewModel = new VideoViewModel ( ) ; viewModel.Id = video.Id ; viewModel.EncodedAssetId = video.EncodedAssetId ; viewModel.IsEncrypted = video.IsEncrypted ; viewModel.LocatorUri = video.LocatorUri ; // If encrypted content , then get token to play if ( video.IsEncrypted ) { IAsset asset = GetAssetById ( video.EncodedAssetId ) ; IContentKey key = CreateEnvelopeTypeContentKey ( asset ) ; viewModel.Token = GenerateToken ( key ) ; } model.Add ( viewModel ) ; } return View ( model ) ; }",Azure Media Service - generate new AES encryption token for playback "C_sharp : I just found out about the Interlocked class and now I have some basic questions.From my understanding I should use Interlocked when manipulating numeric variables when multi-threading . If that statement is true , what about doing reads or just general using of the variables ? For example : Do I need to use an Interlocked statement there ? What about when I 'm initializing the variable : I need to make sure I understand this before implmenting it . if ( ( iCount % 100 ) == 0 ) Int32 iCount = 0 ;",interlocked - when do I use it ? "C_sharp : I have written an application in Visual Studio 2015 that uses C # 6.0 features and targets .NET 4.5.2 . When I build it using Microsoft Build Tools 2015 , which is what is done by our TeamCity server , the resulting bin folder also contains a copy of mscorlib.dll . The problem here is that the mscorlib.dll being copied is the .NET 4.6 DLL , which causes problems at runtime.I have replaced my call to string.Format ( ) with the new string interpolation syntax to work around the problem . That , however , shoves the underlying problem under the carpet instead of addressing it : Why is the .NET 4.6 DLL included in my build and how can I force the 4.5.2 DLL to be included in its place ? If you are interested in the runtime problem this caused for me , it caused my : To be interpreted as ( link -- which only exists in .NET 4.6 ) : Instead of ( link ) : string.Format ( CultureInfo.InvariantCulture , `` { 0 } = ' { 1 } ' '' , `` key '' , `` value '' ) System.String System.String.Format ( System.IFormatProvider , System.String , System.Object , System.Object ) System.String System.String.Format ( System.IFormatProvider , System.String , params System.Object [ ] )",Force Microsoft Build Tools 2015 to include mscorlib for the targeted version of the framework instead of 4.6 "C_sharp : I understand what boxing is . A value type is boxed to an object/reference type and is then stored on managed heap as an object . But I ca n't get thru unboxing.Unboxing converts your object/reference type back to the value typeAlright . But if I try to unbox a value type into another value type , for example , long in above example , it throws InvalidCastExceptionIt leaves me with an idea that may be runtime implicitly knows the actual TYPE of value type boxed inside `` box '' object . If I am right , I wonder where this type information is stored.EDIT : Since int is implicitly convertible to long . This is what confusing me . is perfectly fine because it has no boxing/unboxing involved . int i = 123 ; // A value typeobject box = i ; // Boxingint j = ( int ) box ; // Unboxing long d = ( long ) box ; int i = 123 ; long lng = i ;",How runtime knows the exact type of a boxed value type ? "C_sharp : Can AutoMapper be `` persuaded '' to temporarily suspend particular mappings ? To illustrate what am trying to accomplish , I will use an illustration . Suppose that I have a repository , StudentRepository , that uses LINQ to interacts with database objects ( tables ) like Students , Courses , Activities , Clubs etc . On the application side , there are matching domain objects Student , Course , Activity , Club . The Student class contains array members of type Course , Activity , and Club like : AutoMapper is configured to map the database objects to the domain objects where the mappings are defined in a static constructor of StudentRepository like : Is it possible to `` persuade '' AutoMapper to suspend the mappings within one function block ? For example : NOTE `` for some specific reasons '' : One reason one may want to take control away from AutoMapper would be this http : //codebetter.com/davidhayden/2007/08/06/linq-to-sql-query-tuning-appears-to-break-down-in-more-advanced-scenarios/ where in the case of a 1 : n associations , LINQ to SQL only supports joining-in one 1 : n association per query . AutoMapper would be inefficient here - making N calls to load Courses for N students returned , N more calls to load Activities for the same N students returned , and possibly N more calls to load Clubs for the same N students returned . public class Student { // ... more members public Course [ ] Courses { get ; set ; } public Activity [ ] Activities { get ; set ; } public Club [ ] Clubs { get ; set ; } // ... even more members } public class StudentRepository : IStudentRepository { static class StudentRepository { // ... other mappings Mapper.CreateMap < TableStudent , Student > ( ) .ForMember ( dest = > dest.Courses , opt = > opt.MapFrom ( src = > Mapper.Map < IEnumerable < Course > > ( src.TableCourses ) ) ) .ForMember ( dest = > dest.Activities , opt = > opt.MapFrom ( src = > Mapper.Map < IEnumerable < Activity > > ( src.TableActivities ) ) ) .ForMember ( dest = > dest.Clubs , opt = > opt.MapFrom ( src = > Mapper.Map < IEnumerable < Clubs > > ( src.TableClubs ) ) ) // where TableStudents , TableCourses , TableActivities , TableClubs are database entities // ... yet more mappings } } public Student [ ] GetStudents ( ) { DataContext dbContext = new StudentDBContext ( ) ; var query = dbContext.Students ; // = > SUSPEND CONFIGURATION MAPPINGS for Subjects , Activities and Clubs WHILE STILL making use of others // = > The idea here it to take personal charge of 'manually ' setting the particular members ( *for some specific reasons ) var students = Mapper.Map < Student > ( query ) ; // = > Still be able to use AutoMapper to map other members } public Student [ ] OtherStudentRepositoryMethods ( ) { // Other repository methods continue to make use of the mappings configured in the static constructor }",Can AutoMapper be `` persuaded '' to temporarily suspend particular mappings ? C_sharp : I have the following code : and I wonder if it is a good translation from F # ? ? public abstract class A ... public class B : A ... public class C : A ... void my_fct ( A x ) { if ( x is B ) { block_1 } else if ( x is C ) { block_2 } else { block_3 } } type a = B | Clet my_fct x = match x with | B - > ( block_1 ) | C - > ( block_2 ) | _ - > ( block_3 ),F # discriminated unions versus C # class hierarchies "C_sharp : How do I export to excel or pdf with all data already expanded ( Drill Down ) in the report viewer.Export to PDF for example , the data that are part of the drilldown not appear.Is there any way to configure it via C # ? Here 's a part of my code : I thank you very much ! byte [ ] bytes = report.ServerReport.Render ( `` PDF '' ) ; string fsFileName = `` C : \Reports\MyReport.pdf '' ; FileStream fs = new FileStream ( fsFileName , FileMode.Create ) ; fs.Write ( bytes , 0 , bytes.Length ) ; fs.Close ( ) ;",Export to PDF with expanded drilldown the report viewer by C # ? "C_sharp : Let 's say I have IEnumerable < int > property backed with List < int > field , so I can modify the collection from within the class , but it 's publicly exposed as read-only.But with code like that you can easily cast object retrieved from the property back to List < int > and modify it : Question is : what is the best ( best readable , easiest to write , without performance loss ) way to avoid that ? I can come up with at least 4 solutions , but non of them is perfect : foreach and yield return : - really annoying to write and to read . AsReadOnly ( ) : + will cause exception when someone tries to modify the returned collection+ does not create a copy of the entire collection.ToList ( ) + User can still modify retrieved collection , but it 's not the same collection we are modifying from within the class , so we should n't care . - creates a copy of entire collection what may cause problems when collection is big.Custom wrapper class.usage : + do n't need to clone the collection- when you use it as LINQ queries source some methods wo n't use ICollection.Count , because you do n't expose it.Is there any better way to do that ? public class Foo { private List < int > _bar = new List < int > ( ) ; public IEnumerable < int > Bar { get { return _bar ; } } } var foo = new Foo ( ) ; var bar = ( List < int > ) foo.Bar ; bar.Add ( 10 ) ; public IEnumerable < int > Bar { get { foreach ( var item in _bar ) yield return item ; } } public IEnumerable < int > Bar { get { return _bar.AsReadOnly ( ) ; } } public IEnumerable < int > Bar { get { return _bar.ToList ( ) ; } } public static class MyExtensions { private class MyEnumerable < T > : IEnumerable < T > { private ICollection < T > _source ; public MyEnumerable ( ICollection < T > source ) { _source = source ; } public IEnumerator < T > GetEnumerator ( ) { return _source.GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return ( ( IEnumerable ) _source ) .GetEnumerator ( ) ; } } public static IEnumerable < T > AsMyEnumerable < T > ( this ICollection < T > source ) { return new MyEnumerable < T > ( source ) ; } } public IEnumerable < int > Bar { get { return _bar.AsMyEnumerable ( ) ; } }",How can I safely return List < T > from method/property declared as IEnumerable < T > ? "C_sharp : I noticed this interesting use of the `` this '' keyword while viewing the disassembled code of Int32.GetHashCode ( ) in .NET Reflector : I always thought `` this '' is only used with reference types not value types . In the code above , will boxing be used every time you try to get the hash code of an int ? From the documentation of the `` this '' keyword in MSDN : - The this keyword refers to the current instance of the classRegards public override int GetHashCode ( ) { return this ; }",Can the `` this '' keyword be used with value types ? "C_sharp : Is it possible to write an Attribute that can track methods to detect if those methods are never called ? output : It is not strictly necessary to have it run at compile time , but it should work when the application is initialized ( better at compile time anyway ) .This tag will be putted to track methods on Audio Library , since audio is refactored very frequently and we usually search for audio methods with 0 references in code we want to mark these methods so we can detect quickly and remove unused audio assets.Basically each time we add a new sound effect , we may later no longer trigger it ( calling its method ) , and the audio file/playback code can remain in the application for a long time . [ Track ] void MyMethod ( ) { } warning : method `` MyMethod '' in `` MyClass '' has no references in code .",C # Attribute to detect unused methods "C_sharp : I 'm working on batch downloader but some URLs are not sending data correctly.For example , this page : http : //i.imgbox.com/absMQK6A.pngIn any internet browser , this page shows an image , but in my program , downloads strange data.I think this URL is fake or protected ( I do n't know HTML well . ) BTW , in IE , I can download that image normally with right click and save as image.so I want to emulate that behavior in my program.How can I do this ? Below is part of my program 's code.UserAgent is string that has informations of browser.such as IE , Firefox etc.Thanks . HttpWebRequest request = ( HttpWebRequest ) HttpWebRequest.Create ( DownloadAddress ) ; if ( Proxy ! = null ) { request.Proxy = Proxy ; } if ( ! string.IsNullOrWhiteSpace ( UserAgent ) ) { request.UserAgent = UserAgent ; } HttpWebResponse response = ( HttpWebResponse ) request.GetResponse ( ) ; Stream downloadHttpStream = response.GetResponseStream ( ) ; int read = downloadHttpStream.Read ( buffer , 0 , buffer.Length ) ; // output codes",C # Download Image from unknown format "C_sharp : I am implementing a custom IFormatter to serialize objects into a custom format that is required by our legacy systems.If I declare a C # auto property : And then in my custom serialize method I get the serialized fields via : How can I access the StringLength attribute that decorates the auto Property ? I am currently getting the property info by taking advantage of the < PropertyName > k_backingfield naming convention . I 'd rather not rely on this as it seems to be a specific detail of the C # compiler implementation . Is there a better way ? [ StringLength ( 15 ) ] public MyProperty { get ; set ; } MemberInfo [ ] members = FormatterServices.GetSerializableMembers ( graph.GetType ( ) , Context ) ;",Get PropertyInfo of a C # auto property given the backing field "C_sharp : I was looking for the .NET implementation of Atan2 in a reflector and found the following line : That is not surprising since it makes sense for most arithmetic functions to be implemented in native code . However , there was no DllImport call associated with this or other functions in System.Math.The core question is about how the function implemented in native code but I would also like to know which native Dll it resides in . Also , why is there no DllImport ? Is that because compilation strips it away ? public static extern double Atan2 ( double y , double x ) ;",How is Atan2 implemented in .NET ? "C_sharp : The Error message is : Ca n't convert lambda expression to dynamic type , because it is not a delegate type Any help , private void SimpleLambda ( ) { dynamic showMessage = x = > MessageBox.Show ( x ) ; showMessage ( `` Hello World ! `` ) ; }",lambda expression and Messagebox in C # C_sharp : I use the following code to enable myClass to use foreach . But I am rather new to programming and have some difficulty in understanding the following code . I described my problems in the comments . I would be grateful for providing some information . public class MyClass : IEnumerable < string > { //1 ) What is IEnumerator for ? // Whats the difference between IEnumerator and IEnumerable public IEnumerator < string > GetEnumerator ( ) { yield return `` first '' ; yield return `` second '' ; } //2 ) What is it for ? It just calls above method IEnumerator IEnumerable.GetEnumerator ( ) { return GetEnumerator ( ) ; } } //3 ) Lastly what benefits I have from implementing genetic interface //IEnumerable < string > instead of just IEnumerable,Question regarding IEnumerable and IEnumerator "C_sharp : Possible Duplicate : Why does modulus division ( % ) only work with integers ? This code does n't work in C and C++ but works in C # and Java : Also , division remainder is defined for reals in Python.What is the reason this operation is not defined for floats and doubles in C and C++ ? float x = 3.4f % 1.1f ; double x = 3.4 % 1.1 ;",Why is there no division remainder operation for floats/doubles in C and C++ ? "C_sharp : I am aware that this may on first glance look like a question you have seen before : Knowing when an external process ' window showsBut this is slightly different.I have an C # asp.net web application , for helping people create an installer for their programs . ( The developers here are mostly mechanical engineers scripting equations in some calculation tools , they are not software people , so we do n't want them spending time learning wix , debugging the installers , maintaing GUID 's between releases , and so on.. ) The serverside will be running the console application `` heat.exe '' ( a tool that is shipped with the wix tools ) , to harvest information on how to register dll 's etc. , if and only if they have a dll in their repository..I do it like this : I thought this worked..It passed tests , it 's been running for a while without problems , and then suddenly , a developer called , that the webtool I made , no longer produces wix xml for him..When I logged into the server , I found this dialog : and then clicked [ OK ] - the web application then continued , and produced the xml , and stuff worked..I have now found the dll that , makes heat throw this error . It does n't really need registering ( typical right ? ) . So I could probably just write a timeout thing , to kill heat.exe if it takes to long , and thus unlock the waiting script , ( and basicly fix the issue untill it happens again with a dll that actually needs registering ) But that is not really detecting the error , that is just detecting that stuff takes time ... On this error , I would like to continue the script , but present a warning to the user , that heat.exe failed to run on that particular file . But to do this I need my asp.net application to know that this error was invoked , and dispose it , so that the script can continue..how the * ? do I get information that this runtime error occurred , so I can handle it from the server script ? Have you tried using the -sreg command line option to heat ? I now have , and as a result , heat.exe no longer chrashes , but this is not a solution , as heat also avoids harvesting the registry information that I need for autoregistering the dll 's shipped with the code in question . public int runHeat ( string filePath , string outputFile , ref string response ) { response += `` run heat.exe to harvest file data '' + '\r ' + '\n ' ; string args = `` file `` + ' '' ' + filePath + ' '' ' + `` -srd -out '' + ' '' ' + outputFile + ' '' ' ; string command = Path.Combine ( WixBinariesPath , `` heat.exe '' ) ; string workPath = Path.GetDirectoryName ( filePath ) ; StringBuilder outputBuilder ; ProcessStartInfo processStartInfo ; Process process ; outputBuilder = new StringBuilder ( ) ; processStartInfo = new ProcessStartInfo ( ) ; processStartInfo.CreateNoWindow = true ; processStartInfo.RedirectStandardOutput = true ; processStartInfo.RedirectStandardInput = true ; processStartInfo.UseShellExecute = false ; processStartInfo.WorkingDirectory = workPath ; processStartInfo.Arguments = args ; processStartInfo.FileName = command ; processStartInfo.ErrorDialog = false ; //create the process handler process = new Process ( ) ; process.StartInfo = processStartInfo ; // enable raising events because Process does not raise events by default process.EnableRaisingEvents = true ; // attach the event handler for OutputDataReceived before starting the process process.OutputDataReceived += new DataReceivedEventHandler ( delegate ( object sender , DataReceivedEventArgs e ) { // append the new data to the data already read-in outputBuilder.AppendLine ( e.Data ) ; } ) ; // start the process // then begin asynchronously reading the output // then wait for the process to exit // then cancel asynchronously reading the output process.Start ( ) ; process.BeginOutputReadLine ( ) ; process.WaitForExit ( ) ; // use the output response += outputBuilder.ToString ( ) ; if ( process.ExitCode ! = 0 ) response += '\r ' + '\n ' + `` heat.exe exited with code : `` + process.ExitCode ; process.CancelOutputRead ( ) ; return process.ExitCode ; }","how to detect , and react when an External sub Process , invokes an error dialog" "C_sharp : Boxing converts a value type to an object type . Or as MSDN puts it , boxing is an `` operation to wrap the struct inside a reference type object on the managed heap . `` But if you try to drill into that by looking at the IL code , you only see the magic word `` box . `` Speculating , I guess that the runtime has some sort of generics-based secret class up its sleeve , like Box < T > with a public T Value property , and boxing an int would look like : Unboxing the int would be far cheaper : return box.Value ; Unfortunately , my performance-hungry server application does a fair bit of boxing , specifically of decimals . Worse , these boxes are short-lived , which makes me suspect I pay twice , once for instanciating the box and then again for garbage collecting the box after I 'm done with it.If I was alloacting this memory myself , I would consider the use of an object pool here . But since the actual object creation is hidden behind a magic word in the IL , what are my options ? My specific questions : Is there an existing mechanism for inducing the runtime to take boxes from a pool rather than instanciating them ? What is the type of the instance created during boxing ? Is it possible to manually take control of the boxing process , yet still be compatible with unboxing ? If that last question seems strange , what I mean is that I could create my own Box < T > or DecimalBox class , pool it , and box/unbox manually . But I do n't want to have to go and modify the various places in the code that consume the boxed value ( aka unbox it ) . int i = 5 ; Box < int > box = new Box < int > ; box.Value = 5 ;",C # - Is it possible to pool boxes ? "C_sharp : I need to run a method with a given parameter in a thread . I 've noticed that when I run it , the parameter is wrong . For the example given , I have an array int [ ] output with the numbers 1-7 . For each number , I create a thread with the method WriteInt ( i ) . I expect the output to be 1-7 in any order , but I consistently see some numbers missed and others duplicated . What is going on and what would the correct way be to start these threads ? ( The list is only there to join the threads afterwards ) Example output : class Program { static void Main ( string [ ] args ) { int [ ] output = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; List < Thread > runningThreads = new List < Thread > ( ) ; foreach ( int i in output ) { Thread thread = new Thread ( ( ) = > WriteInt ( i ) ) ; thread.Start ( ) ; runningThreads.Add ( thread ) ; } foreach ( Thread t in runningThreads ) { t.Join ( ) ; } } private static void WriteInt ( int i ) { Console.WriteLine ( i ) ; } } 334567",Threads receiving wrong parameters "C_sharp : The System.Xml parsing features had a few surprises for me in store , and I wonder how the following should be interpreted , or if this is `` up to the implementation '' : Version 1 : Version 2 : What should be the value of elem ? Or is it okay that this depends on the implementation that parses it , and should I just deal with that ? I expected ( at first ) that in both cases all whitespace between the start/end node and the first non-whitespace character would be ignored . This is not the case , but failing that , I would 've at least expected it to never be ignored , but this is also not the case . See full repro below for my expectations.To elaborate ... Two cases had me stumped when I tested them : XDocument.Parse will suddenly start to include the \n\t whitespace in example 2 , whereas it ignored it in example 1.XDocument.Load with new XmlReaderSettings { IgnoreWhitespace = true } will behave similarly.What gives ? Is this just the implementation being ( to my taste ) quirky , and/or is this specified behavior ? Here 's a full repro of my expectations ( fresh C # class library project with latest NUnit package from NuGet ) : < root > < elem > < ! [ CDATA [ MyValue ] ] > < /elem > < /root > < root > < elem > - < ! [ CDATA [ MyValue ] ] > - < /elem > < /root > [ TestFixture ] public class XmlTests { public static XDocument ParseDocument ( string input ) { return XDocument.Parse ( input ) ; } public static XDocument LoadDocument ( Stream stream ) { var xmlReader = XmlReader.Create ( stream , new XmlReaderSettings ( ) { IgnoreWhitespace = false } ) ; // Default return XDocument.Load ( xmlReader ) ; } public static XDocument LoadDocument_IgnoreWhitespace ( Stream stream ) { var xmlReader = XmlReader.Create ( stream , new XmlReaderSettings ( ) { IgnoreWhitespace = true } ) ; return XDocument.Load ( xmlReader ) ; } const string example1 = `` < root > < elem > \n\t < ! [ CDATA [ MyValue ] ] > \n < /elem > < /root > '' ; const string example2 = `` < root > < elem > \n\t- < ! [ CDATA [ MyValue ] ] > -\n < /elem > < /root > '' ; [ Test ] public void A_Parsing_Example1_WorksAsExpected ( ) { var doc = ParseDocument ( example1 ) ; var element = doc.Descendants ( `` elem '' ) .Single ( ) ; Assert.That ( element.Value , Is.EqualTo ( `` MyValue '' ) ) ; } [ Test ] public void B_Loading_Example1_WorksAsExpected ( ) { var doc = LoadDocument ( new MemoryStream ( Encoding.UTF8.GetBytes ( example1 ) ) ) ; var element = doc.Descendants ( `` elem '' ) .Single ( ) ; Assert.That ( element.Value , Is.EqualTo ( `` \n\tMyValue\n '' ) ) ; } [ Test ] public void C_LoadingWithIgnoreWhitespace_Example1_WorksAsExpected ( ) { var doc = LoadDocument_IgnoreWhitespace ( new MemoryStream ( Encoding.UTF8.GetBytes ( example1 ) ) ) ; var element = doc.Descendants ( `` elem '' ) .Single ( ) ; Assert.That ( element.Value , Is.EqualTo ( `` MyValue '' ) ) ; } [ Test ] public void D_Parsing_Example2_WorksAsExpected ( ) { var doc = ParseDocument ( example2 ) ; var element = doc.Descendants ( `` elem '' ) .Single ( ) ; Assert.That ( element.Value , Is.EqualTo ( `` -MyValue- '' ) ) ; } [ Test ] public void E_Loading_Example2_WorksAsExpected ( ) { var doc = LoadDocument ( new MemoryStream ( Encoding.UTF8.GetBytes ( example2 ) ) ) ; var element = doc.Descendants ( `` elem '' ) .Single ( ) ; Assert.That ( element.Value , Is.EqualTo ( `` \n\t-MyValue-\n '' ) ) ; } [ Test ] public void F_LoadingWithIgnoreWhitespace_Example2_WorksAsExpected ( ) { var doc = LoadDocument_IgnoreWhitespace ( new MemoryStream ( Encoding.UTF8.GetBytes ( example2 ) ) ) ; var element = doc.Descendants ( `` elem '' ) .Single ( ) ; Assert.That ( element.Value , Is.EqualTo ( `` MyValue '' ) ) ; } }",How should text nodes with CDATA and whitespace be interpreted in XML ? "C_sharp : I am trying to configure my middleware pipeline to use 2 different exception handlers to handle the same exception . For example , I 'm trying to have both my custom handler and in-built DeveloperExceptionPageMiddleware as follows : My objective is to have the custom handler do its own thing ( logging , telemetry , etc ) , and then pass on ( next ( ) ) to the other in-built handler which displays a page . My custom handler looks like this : I can not get CustomExceptionHandler to pass on processing to the next middleware . I get the following page instead:404 error : I tried switching around the order , but then the developer exception page takes over and the custom exception handler is not called.Is what I 'm trying to do possible at all ? Update : The solution was to take Simonare 's original suggestion and re-throw the exception in the Invoke method . I also had to remove any type of response-meddling by replacing the following in HandleExceptionAsync method : context.Response.ContentType = `` application/json '' ; context.Response.StatusCode = ( int ) code ; return context.Response.WriteAsync ( result ) ; with : return Task.CompletedTask ; public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; app.ConfigureCustomExceptionHandler ( ) ; } else { app.UseExceptionHandler ( `` /Home/Error '' ) ; app.ConfigureCustomExceptionHandler ( ) ; app.UseHsts ( ) ; } app.UseHttpsRedirection ( ) ; app.UseStaticFiles ( ) ; app.UseCookiePolicy ( ) ; app.UseAuthentication ( ) ; app.UseMvcWithDefaultRoute ( ) ; } public static class ExceptionMiddlewareExtensions { public static void ConfigureCustomExceptionHandler ( this IApplicationBuilder app ) { app.UseExceptionHandler ( appError = > { appError.Use ( async ( context , next ) = > { var contextFeature = context.Features.Get < IExceptionHandlerFeature > ( ) ; if ( contextFeature ! = null ) { //log error / do custom stuff await next ( ) ; } } ) ; } ) ; } }",How to configure multiple exception handlers "C_sharp : I 'm on Monotouch 5.2.6 and iOS SDK 5.0.1.I have a UIPageViewController that is a child container of another view controller.It is created like this : If I rotate the device ( Simulator ) , I get this exception in UIApplication.SendEvent ( ) : Objective-C exception thrown . Name : NSInternalInconsistencyException Reason : The number of provided view controllers ( 1 ) does n't match the number required ( 2 ) for the requested spine location ( UIPageViewControllerSpineLocationMid ) The spine location is NOT `` mid '' but `` min '' . Any ideas ? pageViewController = new UIPageViewController ( UIPageViewControllerTransitionStyle.PageCurl , UIPageViewControllerNavigationOrientation.Horizontal , UIPageViewControllerSpineLocation.Min ) ; this.AddChildViewController ( pageViewController ) ; pageViewController.DidMoveToParentViewController ( this ) ; this.viewCurrentMode.AddSubview ( pageViewController.View ) ;",NSInternalInconsistencyException from UIPageViewController when rotating "C_sharp : I am currently testing the performance of different methods for logging text data into a file . It seems that when I open/write/close a large amount of times , the extension used affects the performance . ( .txt and .log are ~7 times faster ) Code used : Results : Why is this happening ? private static void TestWriteSpeed ( FileInfo file ) { Stopwatch watch = new Stopwatch ( ) ; watch.Start ( ) ; for ( int i = 0 ; i < 5000 ; i++ ) { using ( StreamWriter writer = file.AppendText ( ) ) { writer.Write ( `` This is a test '' ) ; } } Console.WriteLine ( file.Name + `` : `` + watch.Elapsed ) ; } static void Main ( string [ ] args ) { TestWriteSpeed ( new FileInfo ( `` abc.txt '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.txt.01564611564 '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.01564611564.txt '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.xml '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.xml.01564611564 '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.config '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.config.01564611564 '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.exe '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.exe.01564611564 '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.log '' ) ) ; TestWriteSpeed ( new FileInfo ( `` abc.log.01564611564 '' ) ) ; Console.ReadLine ( ) ; } abc.txt 00:00:08.3826847 < -- -abc.txt.01564611564 00:00:59.7401633abc.01564611564.txt 00:00:08.0069698 < -- -abc.xml 00:00:58.2031820abc.xml.01564611564 00:00:59.3956204abc.config 00:00:58.4861308abc.config.01564611564 00:01:01.2474287abc.exe : 00:01:00.0924401abc.exe.01564611564 00:01:00.7371805abc.log 00:00:08.0009934 < -- -abc.log.01564611564 00:00:59.8029448","Why does file extension affect write speed ? ( C # , StreamWriter )" "C_sharp : I want to store Guids in a database which does not support Guid/uniqueidentifier data type , therefore I convert Guid to byte array using .ToByteArray ( ) method . However , this method converts value in a strage way : As I understand , this is because of endian ordering.I would like to know if this method will return the same result on every platform ( 86x hardware , 64x hardware , Linux , Windows etc ) and there will be no changes in byte order no matter on which platform I run my software . 11223344-5566-7788-9900-AABBCCDDEEFFwill become44 , 33 , 22 , 11 , 66 , 55 , 88 , 77 , 99 , 00 , AA , BB , CC , DD , EE , FF",Is Guid.ToByteArray ( ) cross-platform ? "C_sharp : I have read a lot about the dangers of double checked locking and I would try hard to stay away of it , but with that said I think they make a very interesting read.I was reading this article of Joe Duffy about implementing singleton with double checked locking : http : //www.bluebytesoftware.com/blog/PermaLink , guid,543d89ad-8d57-4a51-b7c9-a821e3992bf6.aspxAnd the ( variant of ) solution he seemed to propose is this : } My question is , does n't that still have the danger of writes being reordered ? Specifically these two lines : If those writes are inverted , then some other thread can still read null . class Singleton { private static object slock = new object ( ) ; private static Singleton instance ; private static int initialized ; private Singleton ( ) { } public Instance { get { if ( Thread.VolatileRead ( ref initialized ) == 0 ) { lock ( slock ) { if ( initialized == 0 ) { instance = new Singleton ( ) ; initialized = 1 ; } } } return instance ; } } instance = new Singleton ( ) ; initialized = 1 ;",Why is this double-checked locking correct ? ( .NET ) "C_sharp : I 've posted a few questions over the months about structure of ASP.NET applications and Database-Abstraction-Layers , for the purposes of rewriting ( from the ground-up ) , a legacy web application . I 've recently stumbled on MVC3/Entity-Code-First and after spending some time with it , have fallen in love with how it works , how things are abstracted out , and I 'm looking for any excuse to use it ! The legacy application is a C++/CLI windows service that generates it 's own HTML ( very old-school HTML at that with CSS just used for colours , and tables-abound ) , and with interface very tightly coupled to business-logic . Basically , anything is going to be an improvement.However , and perhaps this is because I have not spent enough time yet with MVC , I have a few nagging doubts and wondered if some of you MVC-Pros could waft their experience in my direction.The legacy app uses custom controls ( it 's own form of them ) to bind combo-boxes to data , and dynamically repopulate dependent combo-boxes based on selections in another . In ASP.NET , this question is answered easily as one just throws an asp : DataList control on the page , binds it to a data source and voila . A bit of simple code allows you to then filter other combo boxes on the selected value . It also would be easy in ASP.NET , to implement another data-list that even automated dependent data in this fashion ( which would mimic the behavior of the legacy app quite nicely ) . I ca n't seem to find a notion of custom controls in MVC , though I assume this kind of stuff is handled by jQuery calls to get data and throw it in to a combo box . But is this done for every combo-box on every page that has one ? Is this a case for partial views with appropriate parameters being passed , or this just stupid ? I guess this relates more to the Entity Framework than MVC , but most of the examples I 've found on the web , and tutorials , perform LINQ queries to return a collection of objects to display , e.g this , from the MvcMovie example : Which is then rendered using a @ foreach loop in the view . This is all great . The legacy application has a single browse page that is used by all the other areas of the system ( there are over 50 ) . It does this by inspecting the column order defined for the user logged on , flattening any foreign keys ( so that the field on the foreign table is displayed as opposed to the non-user-friendly primary key value ) and also allows the user to apply custom filters to any column . It does this also for tables that have upward of 100k rows . How would one go about writing something similar using the Entity-framework and views ? In ASP.NET I 'd probably solve this by dynamically generating a grid view of some sort and have it auto-generate the columns and apply the filters . This seems like it might me more work in MVC . I am missing something ? The legacy application has several operations that operate over large sets of data . Now because it was a service , it could launch these threads without worrying about being shut-down . One of my questions here on SO was about static managers being around and the introduction of an AppPool recycle , but I have decided that having an auxiliary service is a good option . That said , the legacy app applies an update statement to large groups of records rather than single rows . Is this possible with Entity-Framework without writing custom SQL against the database that bypasses the normal models ? I hope I do n't have to do something like this ( not that I would , this is just for example ) I suspect this could take a lot of time , whereas the legacy app would just do : So it 's not entirely clear to me how we use our models in this manner.The legacy application has some data panels in the layout that get carried around whatever page you 're on . Looking here on Stackoverflow , I found this question , which implies that every view needs to pass this information to the layout ? Is this so , or is there a better way ? Ideally , I 'd like my layout to be able to access a particular model/repository and display the data in a side-panel . Adding to every view page could be quite repetitive and prone to error . Not to mention the time it would take if I needed to modify something . A partial view would do here , but again I am unsure how to pass a model to it on the layout page.Finally , I was disappointed , after installing Ef-Code-First , to find that a really nice attribute , SourceName has not made it in , yet . This would be very nice in mapping against legacy tables/columns and I am not entirely sure why it has been left out at this point ( at least , my intellisense says it 's not there ! ) Has anyone got an idea when this might come about ? I could do without it for a while , but ultimately it would be incredibly useful.Sorry for the lengthy questions . After ages of investigative work in ASP.NET and MVC3 , I really want to go with MVC3 ! public ActionResult Index ( ) { var movies = from m in db.Movies where m.ReleaseDate > new DateTime ( 1984 , 6 , 1 ) select m ; return View ( movies.ToList ( ) ) ; } var records = from rec in myTable where someField = someValue select rec ; foreach ( rec in records ) rec.applyCalculation ( ) ; db.SaveDbChanges ( ) ; UPDATE myTableSET field1 = calcWHERE someField = someValue",Rewriting a legacy-proprietary Web Application to MVC3/Entity-Code-First "C_sharp : I 'm working on a .NET component that gets a set of data from the database , performs some business logic on that set of data , and then updates single records in the database via a stored procedure that looks something like spUpdateOrderDetailDiscountedItem.For small sets of data , this is n't a problem , but when I had a very large set of data that required an iteration of 368 stored proc calls to update the records in the database , I realized I had a problem . A senior dev looked at my stored proc code and said it looked fine , but now I 'd like to explore a better method for sending `` batch '' data to the database.What options do I have for updating the database in batch ? Is this possible with stored procs ? What other options do I have ? I wo n't have the option of installing a full-fledged ORM , but any advice is appreciated.Additional Background Info : Our current data access model was built 5 years ago and all calls to the db currently get executed via modular/static functions with names like ExecQuery and GetDataTable . I 'm not certain that I 'm required to stay within that model , but I 'd have to provide a very good justification for going outside of our current DAL to get to the DB.Also worth noting , I 'm fairly new when it comes to CRUD operations and the database . I much prefer to play/work in the .NET side of code , but the data has to be stored somewhere , right ? Stored Proc contents : ALTER PROCEDURE [ dbo ] . [ spUpdateOrderDetailDiscountedItem ] -- Add the parameters for the stored procedure here @ OrderDetailID decimal = 0 , @ Discount money = 0 , @ ExtPrice money = 0 , @ LineDiscountTypeID int = 0 , @ OrdersID decimal = 0 , @ QuantityDiscounted money = 0 , @ UpdateOrderHeader int = 0 , @ PromoCode varchar ( 6 ) = `` , @ TotalDiscount money = 0ASBEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements . SET NOCOUNT ON ; -- Insert statements for procedure here Update OrderDetail Set Discount = @ Discount , ExtPrice = @ ExtPrice , LineDiscountTypeID = @ LineDiscountTypeID , LineDiscountPercent = @ QuantityDiscounted From OrderDetail with ( nolock ) Where OrderDetailID = @ OrderDetailID if @ UpdateOrderHeader = -1 Begin -- This code should get code the last time this query is executed , but only then . exec spUpdateOrdersHeaderForSkuGroupSourceCode @ OrdersID , 7 , 0 , @ PromoCode , @ TotalDiscount End",What 's a good alternative to firing a stored procedure 368 times to update the database ? "C_sharp : I currently have method which is trying to find out what the obj is it recieved . It knows is on a certain interface , for example IService but I have code which looks at it and tries to tell me is it is for example Service1 or Service2.I currently a lot of if ( obj is thisObj ) style statements , what would be the best solution to make this code pretty ? here is a sample of what exactly I have : now having two isnt too much of a bad thing , but I am looking at having probably 20+ of these which just becomes awful to use.Any ideas ? ok further details I think are needed and here they are : prior to this method I have another method which is recieving a xml doc , which it them deserializes into the interface IService , so we have something like this : Hopefully that makes it a bit clearer . public void DoSomething ( IService service ) { if ( service is Service1 ) { //DO something } if ( service is Service2 ) { //DO something else } } private static void Method ( InnerXml ) { var messageObj = ( IServiceTask ) XmlSerialization.Deserialize ( typeof ( IServiceTask ) , InnerXml ) ; var service = GetService ( messageObj ) ; service.PerformTask ( xmlDoc ) ; } private static IService GetService ( IServiceTask messageObj ) { var service = new IService ( ) ; if ( messageObj is Task1 ) { service = ( SomeService ) messageObj ; } if ( messageObj is Task2 ) { service = ( SomeOtherService ) messageObj ; } return service ; }",TOO MANY if ( obj is thisObj ) statements "C_sharp : I 'm trying to use the Identity package of .NET Core with multiple classes that extend IdentityUser < Guid > but with a single UserRole class.I have multiple classes that extend UserStore < T > for each user type and a single class that extends RoleStore < UserRole > .The following is my startup.cs : My DbContext is not extending IdentityDbContext : I was getting multiple errors so I added the following to DbContext but I commented it out : I 'm getting many different errors : build Error on Instance 'Dal.IdentityStores.InternalUserStore ' for PluginType IUserStore - and Instance 'RoleManager ' for PluginType Microsoft.AspNetCore.Identity.RoleManager1 [ Models.Entities.Users.UserRole ] - and Instance 'Dal.IdentityStores.GenericUserRoleStore ' for PluginType Microsoft.AspNetCore.Identity.IRoleStore1 [ Models.Entities.Users.UserRole ] - and Instance 'Dal.IdentityStores.GenericUserRoleStore ' for PluginType Microsoft.AspNetCore.Identity.IRoleStore1 [ Models.Entities.Users.UserRole ] - and Instance 'Dal.IdentityStores.ContractorUserStore ' for PluginType Microsoft.AspNetCore.Identity.IUserStore1 [ Models.Entities.Contractors.Contractor ] - and Instance 'UserClaimsPrincipalFactory ' for PluginType Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1 [ Models.Entities.Contractors.Contractor ] - and Instance 'UserClaimsPrincipalFactory < Contractor , UserRole > ' for PluginType Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1 [ Models.Entities.Contractors.Contractor ] - and Instance 'UserManager ' for PluginType Microsoft.AspNetCore.Identity.UserManager1 [ Models.Entities.Homeowners.Homeowner ] - and Instance 'UserClaimsPrincipalFactory < Homeowner > ' for PluginType Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory1 [ Models.Entities.Homeowners.Homeowner ] This is the link to my repo services.AddIdentity < InternalUser , UserRole > ( IdentityOptions ) .AddDefaultTokenProviders ( ) .AddUserStore < InternalUserStore > ( ) .AddRoleStore < GenericUserRoleStore > ( ) ; services.AddIdentityCore < Contractor > ( IdentityOptions ) .AddRoles < UserRole > ( ) .AddDefaultTokenProviders ( ) .AddUserStore < ContractorUserStore > ( ) .AddRoleStore < GenericUserRoleStore > ( ) ; services.AddIdentityCore < Homeowner > ( IdentityOptions ) .AddRoles < UserRole > ( ) .AddDefaultTokenProviders ( ) .AddUserStore < HomeownerUserStore > ( ) .AddRoleStore < GenericUserRoleStore > ( ) ; public sealed class EntityDbContext : DbContext { } public DbSet < IdentityUserClaim < Guid > > UserClaims { get ; set ; } public DbSet < IdentityUserRole < Guid > > UserRoles { get ; set ; }",Multiple user type Identity - DbContext design "C_sharp : I 'm trying to figure out if .NET 4.0 's Enum.TryParse is thread safe.The source code ( decompiled ) is : What seems problematic to me is this line : What if another thread accessed result right after it 's been set to the default value , and before it is set to the parsed value ? [ EDIT ] Following Zoidberg 's answer , I 'd like to rephrase the question a bit.The question is , I guess , if Enum.TryParse is `` transactional '' ( or atomic ) .Say I have a static field , and pass it into Enum.TryParse : Now , when TryParse is being executed , another thread accesses MyField . TryParse will change MyField 's value to SomeEnum 's default value for a while , and only then will set it to the parsed value.This is not necessarily a bug in my code . I would expect Enum.TryParse to either set MyField to the parsed value or not touch it at all , not use it as its temporary field . [ SecuritySafeCritical ] public static bool TryParse < TEnum > ( string value , bool ignoreCase , out TEnum result ) where TEnum : struct { result = default ( TEnum ) ; /// ( * ) Enum.EnumResult enumResult = default ( Enum.EnumResult ) ; enumResult.Init ( false ) ; bool result2 ; if ( result2 = Enum.TryParseEnum ( typeof ( TEnum ) , value , ignoreCase , ref enumResult ) ) { result = ( TEnum ) enumResult.parsedEnum ; } return result2 ; } result = default ( TEnum ) ; /// ( * ) public static SomeEnum MyField ; ... .Enum.TryParse ( `` Value '' , out MyField ) ;",Enum.TryParse - is it thread safe ? "C_sharp : I have a class , which requires all calls to Calc to be performed on the same thread as the one on which Test was created . I need to create Test once ( expensive operation ) and call Calc multiple times.I 'd like to have a wrapper that will let me call Calc asynchronousely : One way to do it would be to create a BackgroundWorker or a Thread and use it as a guarantee that all operations on Test are on the same thread . For simplicity , we can assume that all calls to Calc ( ) will be executed sequentially , so no need to worry about queueing.Is there a more elegant RX way to do it ? public class Test { public int Calc ( ) ; } public class TestWrapper { private Test _test ; public IObservable < int > Calc ( ) ; }",Create an observable wrapper for a non thread safe class "C_sharp : Whilst putting together a T4 template I threw in a simple lambda expression : This causes the template to fail to generate with the error : On the line with the lambda expression.This has been checked outside of a template and works fine . Does T4 not support working with lambda expressions ? If not , are there any other language features that are unsupported in the context of a T4 template ? Thanks ! < # =string.Join ( `` , '' , updateFields.ConvertAll ( field = > field.Name ) .ToArray ( ) ) # > Compiling transformation : Invalid expression term ' > '",Lambda Expressions in T4 Templates "C_sharp : i 'm just sending a normal POST request using Ajax.BeginForm ... i output the form elements using the .TextBoxFor and .HiddenFor etc ... all as i should ... and when it 's posted via ajax to my action method , the object in the action method ( named `` Comment '' ) is not populated with the values ! Am i missing something ? here is the relevant part of my code to those who want to see it ... and ... .here is the Action Method , which raises the error ... the error is a null reference exception when i try to use the object : Dim db = New FPicDataContext Dim Updatable = ( From c In db.Comments Where c.CommentID = UpCom.CommentID ) .FirstOrDefault Updatable.Comment = UpCom.Comment ' THIS IS WHERE THE OBJECT IS NULL ERROR IS RAISED ! BASICALLY , ALL THE VALUES IN UPCOM ( AS COMMENT ) ARE 0 OR NOTHING . db.SubmitChanges ( ) Dim cm = New CommentModel With { .Comment = UpCom , .CommentDivId = `` CommentDiv '' & UpCom.CommentID.ToString } Return PartialView ( `` Comment '' , cm ) End Function < % Using Ajax.BeginForm ( `` UpdateComment '' , `` Home '' , New AjaxOptions With { .UpdateTargetId = Model.CommentDivId , .HttpMethod = FormMethod.Post } ) % > < % = Html.HiddenFor ( Function ( x ) x.Comment.CommentID ) % > < % = Html.TextAreaFor ( Function ( x ) x.Comment.Comment , 8 , 40 , New With { .style = `` overflow : hidden ; '' } ) % > < % = Html.ValidationMessageFor ( Function ( x ) x.Comment.Comment ) % > Function UpdateComment ( ByVal UpCom As Comment ) As ActionResult",Does MVC 2.0 model binding work with Ajax requests ? C_sharp : I have a static class to setup Autofac registration and its method is called in Application_Start . Something like this : So far I have n't found examples that dispose the container.Is this enough or should I return the container and then dispose of the container in Dispose method in Global.asax ? public static class RegisterAutofac { public static void Setup ( ) { var config = GlobalConfiguration.Configuration ; var builder = new ContainerBuilder ( ) ; //Do registration here ... var container = builder.Build ( ) ; var resolver = new AutofacWebApiDependencyResolver ( container ) ; GlobalConfiguration.Configuration.DependencyResolver = resolver ; } },How to dispose of Autofac container ? "C_sharp : This code works fine with me : BUT ... This means I have to repeat the last code which inside `` Button1_Click ( ) '' each time I need to do impersonation ( Doing something on the remote machine = server ) .So my question : Is it possible to do something like this illustration ? : [ DllImport ( `` advapi32.dll '' , SetLastError = true ) ] public static extern bool LogonUser ( string lpszUsername , string lpszDomain , string lpszPassword , int dwLogonType , int dwLogonProvider , ref IntPtr phToken ) ; [ DllImport ( `` kernel32.dll '' ) ] public static extern bool CloseHandle ( IntPtr token ) ; enum LogonType { Interactive = 2 , Network = 3 , Batch = 4 , Service = 5 , Unlock = 7 , NetworkClearText = 8 , NewCredentials = 9 } enum LogonProvider { Default = 0 , WinNT35 = 1 , WinNT40 = 2 , WinNT50 = 3 } private void Button1_Click ( ) { IntPtr token = IntPtr.Zero ; LogonUser ( `` Administrator '' , `` 192.168.1.244 '' , `` PassWord '' , ( int ) LogonType.NewCredentials , ( int ) LogonProvider.WinNT50 , ref token ) ; using ( WindowsImpersonationContext context = WindowsIdentity.Impersonate ( token ) ) { CloseHandle ( token ) ; /* Code_of_Do_Something */ } }",passing code to a function as parameter within `` using statement '' C_sharp : i saw that delegate is used for custom events . as far examplewhat i do here just declare delegate and assign a function name to delegate and call like fValue ( `` hello '' ) ; whenever it is required.instead of calling the GetFieldName ( ) through delegate i can call it directly . so i just want to know why should i use delegate to call function where as we can call function directly ... .what is the advantage of calling any function through delegate.so please tell me in what kind of scenario delegate usage is required except event handling . please guide me with sample code and simulate a situation where i need to call function through delegate except event handling . please show me some real life scenario where we have to call function through delegate . delegate string FuncRef ( string Val ) ; FuncRef fValue = GetFieldName ; fValue ( `` hello '' ) ;,The usage of delegate C_sharp : Someone knows how to find the longest substring composed of letters using using MatchCollection . public static Regex pattern2 = new Regex ( `` [ a-zA-Z ] '' ) ; public static string zad3 = `` ala123alama234ijeszczepsa '' ;,Finding the longest substring regex ? "C_sharp : Is it possible to do this in Java ? Maybe I 'm using the wrong syntax ? Also , is it possible to do something likeas is seen on c # ? Thanks ArrayList < Integer > iAL = new ArrayList < Integer > ( ) ; iAL.addAll ( Arrays.asList ( new Integer [ ] { 1 , 2 , 3 , 4 , 5 } ) ) ; for ( int i = 0 ; i < iAL.size ( ) ; ++i ) { System.out.println ( iAL [ i ] ) ; // < -- -- -- -- HERE IS THE PROBLEM } iAL.addAll ( new int [ ] { 1 , 2 , 3 , 4 , 5 } ) ;",ArrayLists and indexers in Java "C_sharp : I have seen some code and thought that something seems wrong with it , so I would like to know if it is acceptable for good coding or not , my first thought is no.Consider : Is this kind of direct access to the Backing Field an acceptable practice or is it bad coding - or should I ask what is the point of the Property Accessor , and if this is done internally in a class with public members , access is allowed by multiple components - is it possible to have a crash - I would venture in a multi threaded application a crash should be expected.Please any thoughts ? I have looked at this Link on SO and others > Why use private members then use public properties to set them ? EDITLet me be clear since there is good info being provided and rather respond to all answers and comments directly . I am not asking about what properties are for , not if I can do auto implemented properties , private setters , OnValueChange notifications , logic on the properties.My question is in regards to accessing that backing field directly - for example if you have say a mutlithreaded scenario - is n't the whole point of the synclock on the getters/setters - to control access to the backingfield ? Will this kind of code be acceptable in that scenario - just adding a syncLock to the getter and setter ? ? Keep in mind the code in the constructor of myClass is an example - the code can be in any additional method - such as the updated class - Method1END EDIT class MyClass { private string m_MySuperString ; public string MySuperString { get { return m_MySuperString ; } set { m_MySuperString = value ; } } public void MyMethod ( ) { if ( blah ! = yada ) { m_MySuperString = badabing ; } } public void MyOtherMethod ( ) { if ( blah == yada ) { m_MySuperString = badaboom ; } } }",Proper Coding Direct Access to the backing field of a Property C # "C_sharp : I 'm implementing an algorithm ( SpookyHash ) that treats arbitrary data as 64-bit integers , by casting the pointer to ( ulong* ) . ( This is inherent to how SpookyHash works , rewriting to not do so is not a viable solution ) .This means that it could end up reading 64-bit values that are not aligned on 8-byte boundaries.On some CPUs , this works fine . On some , it would be very slow . On yet others , it would cause errors ( either exceptions or incorrect results ) .I therefore have code to detect unaligned reads , and copy chunks of data to 8-byte aligned buffers when necessary , before working on them.However , my own machine has an Intel x86-64 . This tolerates unaligned reads well enough that it gives much faster performance if I just ignore the issue of alignment , as does x86 . It also allows for memcpy-like and memzero-like methods to deal in 64-byte chunks for another boost . These two performance improvements are considerable , more than enough of a boost to make such an optimisation far from premature.So . I 've an optimisation that is well worth making on some chips ( and for that matter , probably the two chips most likely to have this code run on them ) , but would be fatal or give worse performance on others . Clearly the ideal is to detect which case I am dealing with.Some further requirements : This is intended to be a cross-platform library for all systems that support .NET or Mono . Therefore anything specific to a given OS ( e.g . P/Invoking to an OS call ) is not appropriate , unless it can safely degrade in the face of the call not being available.False negatives ( identifying a chip as unsafe for the optimisation when it is in fact safe ) are tolerable , false positives are not.Expensive operations are fine , as long as they can be done once , and then the result cached.The library already uses unsafe code , so there 's no need to avoid that.So far I have two approaches : The first is to initialise my flag with : The other is that since the buffer copying necessary for avoiding unaligned reads is created using stackalloc , and since on x86 ( including AMD64 in 32-bit mode ) , stackallocing a 64-bit type may sometimes return a pointer that is 4-byte aligned but not 8-byte aligned , I can then tell at that point that the alignment workaround is n't needed , and never attempt it again : This latter though will only work on 32-bit execution ( even if unaligned 64-bit reads are tolerated , no good implementation of stackalloc would force them on a 64-bit processor ) . It also could potentially give a false positive in that the processor might insist on 4-byte alignment , which would have the same issue.Any ideas for improvements , or better yet , an approach that gives no false negatives like the two approaches above ? private static bool AttemptDetectAllowUnalignedRead ( ) { switch ( Environment.GetEnvironmentVariable ( `` PROCESSOR_ARCHITECTURE '' ) ) { case `` x86 '' : case `` AMD64 '' : // Known to tolerate unaligned-reads well . return true ; } return false ; // Not known to tolerate unaligned-reads well . } if ( ! AllowUnalignedRead & & length ! = 0 & & ( ( ( long ) message ) & 7 ) ! = 0 ) // Need to avoid unaligned reads . { ulong* buf = stackalloc ulong [ 2 * NumVars ] ; // buffer to copy into . if ( ( 7 & ( long ) buf ) ! = 0 ) // Not 8-byte aligned , so clearly this was unnecessary . { AllowUnalignedRead = true ; Thread.MemoryBarrier ( ) ; //volatile write",Detecting CPU alignment requirements "C_sharp : I have a simple modal that uses select2 to get a list of Products from the server . User can multiple choose products and hit Ok to refine a search.My following setup grabs the data from the modal and does an ajax call against a Controller action with a strongly typed view model that matches what the JS is trying to send via the ajax call.Ajax : Right before the ajax call goes to the controller I inspect the content and structure of exploreFilters : Here is how the form data looks on the POST request : On the other side I got a controller which takes a strongly-typed parameter with a structure similar to what exploreFilters has : And my strongly-typed view model : Once the controller action gets hit I can see that DateStart and DateEnd have been successfully bound but not my list of products.I can not change the datatype on the json request , it has to be html because my controller action is going to be returning html.I 've tried changing the capitalization on Id and Text , JSON.stringify ( which actually makes the dates not bind anymore ) What am I doing wrong ? var exploreFilters = { `` type '' : exploreType , `` products '' : $ ( ' # s2id_select2-products ' ) .select2 ( 'data ' ) , `` locations '' : $ ( `` # page-report__data '' ) .data ( `` criteria__locations '' ) , `` companies '' : $ ( `` # page-report__data '' ) .data ( `` criteria__companies '' ) , `` usertypes '' : $ ( `` # page-report__data '' ) .data ( `` criteria__usertypes '' ) , `` groupusers '' : $ ( `` # page-report__data '' ) .data ( `` criteria__groupusers '' ) , `` datestart '' : $ ( `` # page-report__data '' ) .data ( `` criteria__datestart '' ) , `` dateend '' : $ ( `` # page-report__data '' ) .data ( `` criteria__dateend '' ) } ; $ .ajax ( { dataType : `` html '' , type : `` POST '' , url : `` /Report/Group/FilteredView '' , data : exploreFilters , success : function ( html ) { if ( $ .trim ( html ) === `` '' ) $ targetSection.html ( ' < div class= '' page-report__empty '' > No data found . Please adjust your search filters and try again. < /div > ' ) ; else $ targetSection.html ( html ) ; } , error : function ( xhr , text , err ) { if ( text === `` timeout '' ) $ targetSection.html ( ' < div class= '' page-report__empty '' > The request timed out . Please try again. < /div > ' ) ; else $ targetSection.html ( ' < div class= '' page-report__empty '' > There has been an error. < /div > ' ) ; } } ) ; public ActionResult FilteredView ( ReportCriteriaViewModel criteria ) { throw new NotImplementedException ( ) ; } public class ReportCriteriaViewModel { public ProductViewModel [ ] Products { get ; set ; } public string [ ] Locations { get ; set ; } public string [ ] Companies { get ; set ; } public string UserTypes { get ; set ; } public string GroupUsers { get ; set ; } public string DateStart { get ; set ; } public string DateEnd { get ; set ; } } public class ProductViewModel { public Guid Id { get ; set ; } public string Text { get ; set ; } }",ajax post on MVC .NET does not pass array correctly "C_sharp : I got a List with pairs of integers . How do I remove pairs if they 're duplicates ? Distinct wont work cause the pair could be ( 2 , 1 ) instead of ( 1 , 2 ) .My list looks like this : ... I do n't need ( 2 , 3 ) and ( 3 , 2 ) I made a public struct FaceLine with public int A and B , then var faceline = new List < FaceLine > ( ) ; .I 'm new to C # and lost . 1 , 22 , 33 , 13 , 22 , 44 , 3",How to remove duplicate pairs in a List "C_sharp : Suppose I haveI want to turn it into List < MyObject > , but I have not been able to drop the nullable reference.Below is an MCVE . In my project I have nullable reference warnings turned to errors , so the commented out line below will not compile.If I do .Where ( e = > e ! = null ) .Select ( e = > e ! ) then it will be fine in the latest .NET Core 3.1.100 , however I can not extract this into an extension method.I tried adding this extension methodHowever it will not convert IEnumerable < MyObject ? > to IEnumerable < MyObject > and I am unsure why . This leads me to an error like : [ CS8619 ] Nullability of reference types in value of type 'List ' does n't match target type 'List'.Is there a way I can make the NotNull function above work somehow ? List < MyObject ? > list = ... ; public static IEnumerable < T > NotNull < T > ( this IEnumerable < T > enumerable ) { return enumerable.Where ( e = > e ! = null ) .Select ( e = > e ! ) ; }",Using Linq 's Where/Select to filter out null and convert the type to non-nullable can not be made into an extension method "C_sharp : We have a table in our SQL database with historical raw data I need to create charts from . We access the DB via Entity Framework and LINQ.For smaller datetime intervals , I can simply read the data and generate the charts : But we want to implement a feature where you can quickly `` zoom out '' from the charts to include larger date intervals ( last 5 days , last month , last 6 months , last 10 years and so on and so forth . ) We do n't want to chart every single data point for this . We want to use a sample of the data , by which I mean something like this -- Last 5 days : chart every data point in the tableLast month : chart every 10th data point in the tableLast 6 months : chart every 100th data pointThe number of data points and chart names are only examples . What I need is a way to pick only the `` nth '' row from the database . var mydata = entity.DataLogSet.Where ( dt = > dt.DateTime > dateLimit ) ;",Fetch every nth row with LINQ "C_sharp : I checked the document that long= int64 has range more than 900,000,000,000,000Here is my code : at runtime it gives me 919,965,907 instead of the correct 9,509,900,499.another testIt refuses to compile , saying integer overflow.But if i do thisThis works fine . int r = 99 ; long test1 = r*r*r*r*r ; long test2 = 99*99*99*99*99 ; long test3 = 10100200300 ;",why this would result in long integer overflow C_sharp : I am working on a project with a huge number of data tables and displaying them through ASP.net MVC screens.I find myself writing a lot of simple data annotations like this : This is getting quite tedious and was wondering if there is a way that I can either add a new attribute that says `` convertFromCamel '' ( or something ) or is there a way to overrideSo that if there is no data annotation it converts the existing field name from camel case.thanks in advance [ Display ( Name = `` Manager Name '' ) ] public string ManagerName { get ; set ; } [ Display ( Name = `` Employee Name '' ) ] public string EmployeeName { get ; set ; } [ Display ( Name = `` Employee No '' ) ] public string EmployeeNo { get ; set ; } [ Display ( Name = `` Manager Employee No '' ) ] public string ManagerEmployeeNo { get ; set ; } @ Html.DisplayNameFor ( m = > Model.First ( ) .EmployeeNo ),Automatically generating data annotations from camel case field names "C_sharp : Long-time joelonsoftware follower , 1st-time stackoverflow poster.I want to know `` how safely '' I can do the following ( C # ) : In practice , this ( apparently ) works , because box ( as a Control ) has a private text field ( a string ) which it uses to implement its Text property after its window handle is destroyed.I wo n't be satisfied by a general answer that `` you ca n't access an object after it 's Disposed '' because ( 1 ) I ca n't find any such blanket prohibition in MS docs , ( 2 ) I 'm not accessing an unmanaged resource , and ( 3 ) this code does n't throw any exception ( including ObjectDisposedException ) .I would like to do this so I can create and use a combined `` ShowAndDispose '' method to reduce the risk of forgetting to always call Dispose ( ) after ShowDialog ( ) .To complicate , the behavior changes in the debugger . If I break before Dispose ( ) ; then Quick Watch box and drill down into its Control base class ; then step past Dispose ( ) ; then box.Text returns `` '' ! In other scenarios box.Text returns the user-entered text . Form formDlg = new Form ( ) ; TextBox box = new TextBox ( ) ; formDlg.Controls.Add ( box ) ; formDlg.ShowDialog ( ) ; formDlg.Dispose ( ) ; string sUserEntered = box.Text ; // After parent Dispose 'd !",Access a control 's Text property after parent form Dispose ( ) 'd ? "C_sharp : I have a table that looks like this : I want to get the count by FruitType given a list of FruitIDs called TheFruitIDs . This is what I have : This code works but the problem is that sometimes I get a timeout error because the query runs for too long . How can I change this code to avoid the timeout problem ? FruitID | FruitType 23 | 2 215 | 2 256 | 1 643 | 3 var TheCounter = ( from f in MyDC.Fruits where TheFruitIDs.Contains ( f.FruitID ) group f by 0 into TheFruits select new MyCounterMode ( ) { CountType1 = ( int ? ) TheFruits.Where ( f = > f.FruitType == 1 ) .Count ( ) ? ? 0 , CountType2 = ( int ? ) TheFruits.Where ( f = > f.FruitType == 2 ) .Count ( ) ? ? 0 , ... . all the way to CountType6 } ) .Single ( ) ;",Linq to SQL count grouped elements generating a timeout "C_sharp : My goal is to output a modified XML file and preserve a special indentation that was present in the original file . The objective is so that the resulting file still looks like the original , making them easier to compare and merge through source control.My program will read a XML file and add or change one specific attribute.Here is the formatting I 'm trying to achieve / preserve : In this case , I simply wish to align all attributes past the first one with the first one.XmlWriterSettings provides formatting options , but they wo n't achieve the result I 'm looking for.These settings will put the first attribute on a newline , instead of keeping it on the same line as the node , and will line up attributes with the node.Here is the Load call , which asks to preserve whitespace : But it seems like it wo n't do what I expected.I tried to provide a custom class , which derives from XmlWriter to the XDocument.Save call , but I have n't managed to insert whitespace correctly without running into InvalidOperationException . Plus that solution seems overkill for the small addition I 'm looking for.For reference , this is my save call , not using my custom xml writer ( which does n't work anyway ) < Base Import= '' ..\commom\style.xml '' > < Item Width= '' 480 '' Height= '' 500 '' VAlign= '' Center '' Style= '' level1header '' > ( ... ) settings.Indent = true ; settings.NewLineOnAttributes = true ; MyXml = XDocument.Load ( filepath , LoadOptions.PreserveWhitespace ) ; XmlWriterSettings settings = new XmlWriterSettings ( ) ; settings.Indent = true ; settings.NewLineOnAttributes = true ; settings.OmitXmlDeclaration = true ; using ( XmlWriter writer = XmlWriter.Create ( filepath + `` _auto '' , settings ) ) { MyXml.Save ( writer ) ; }",How to use XDocument.Save to save a file using custom indentation for attributes C_sharp : After upgrading one of my websites to MVC 4 and upgrade all my packages in NuGet I seem to have lost the Send ( ) extension method for the MvcMailer package from NuGet . I have not made any code changes other then those necessary to upgrade the project and I have : At the top of my code file.Can someone please tell me what may be going on here ? using Mvc.Mailer ;,MvcMailer Send ( ) extension method missing in ASP.Net MVC 4 "C_sharp : I have an ASP.NET MVC routing question . First , let me explain my areas setup . It 's quite simple.I have a folder in my areas called `` Foo '' and controller called `` BarController.cs '' The Bar controller has several methods named `` DoStuff1 ( ) '' , `` DoStuff2 ( ) '' , etc.My website uses the following URLs : The first URL requires an id and uses the default Index ( ) method in the Bar controller to populate the webpage with a view and model.In the second and third URLs , I 'm using them for jQuery ajax calls.Here is the code from my area registrionMy problem is that for each new controller method I create , I have to add another route mapping in the area registrion file . For example , if I add the method DoStuff3 ( ) , I 'll need to add this to the area registration : How can I create a generic route mapping to handle the URLs I mentioned above that does n't require new additions to the area registration file for new controller methods ? Areas|+ -- Foo | + -- Controllers | + -- BarController.cs /foo/bar/15/foo/bar/dostuff1/foo/bar/dostuff2 context.MapRoute ( null , `` Foo/Bar/DoStuff1 '' , new { action = `` DoStuff1 '' , controller = `` Bar '' } ) ; context.MapRoute ( null , `` Foo/Bar/DoStuff2 '' , new { action = `` DoStuff2 '' , controller = `` Bar '' } ) ; context.MapRoute ( null , `` Foo/Bar/ { id } '' , new { action = `` Index '' , controller = `` Bar '' } ) ; context.MapRoute ( null , `` Foo/Bar/DoStuff3 '' , new { action = `` DoStuff3 '' , controller = `` Bar '' } ) ;",How To Prevent Multiple ASP.NET MVC Route Mappings "C_sharp : I 'm trying to create an async unit test for the project , but can not understand how to wait for the async subject to complete : Sync version of this test is works well : [ Test ] public async void MicroTest ( ) { var value = 2 ; var first = new AsyncSubject < int > ( ) ; var second = new AsyncSubject < int > ( ) ; first.Subscribe ( _ = > { value = _ ; second.OnCompleted ( ) ; } ) ; first.OnNext ( 1 ) ; // how to wait for the second subject to complete ? Assert.AreEqual ( value , 1 ) ; } [ Test ] public void MicroTest ( ) { var value = 2 ; var first = new Subject < int > ( ) ; var second = new Subject < int > ( ) ; first.Subscribe ( _ = > { value = _ ; second.OnCompleted ( ) ; } ) ; first.OnNext ( 1 ) ; Assert.AreEqual ( value , 1 ) ; }",Rx and async nunit test "C_sharp : I 've been developing a game in the Unity Game Engine that I hope will be able to use paged terrain for an infinite world ( common theme nowadays ) . My terrain generator uses perlin noise exclusively . But at this time , development has been seriously slowed by a bug : The page edges do n't match up , not even close . The problem is somewhere in the code where I generate terrain , or possibly in another piece of code that runs every time I 've finished generating a page . But the problem is definitely not in the unity function calls , so you can help me even if you are n't familiar with unity.Possible causes ... 1 ) Perlin noise sampled for the wrong location for each page , math fail.2 ) Random number generator is being reseeded between the generation of pages.3 ) Perlin noise is being reseeded between the generation of pages.4 ) ? I do n't know.NOTE : I 've pretty much ruled out numbers 2 and 3 , looking at all my other code . I only seed the generators once each , and Unity would n't just happen to reseed Random between runs of the generator.Actually , if you can describe a way of debugging that would make this easier , please advise . It would help me much more in the long run.Here is the code I run once for each page , with full commenting so you do n't have to know Unity3D ... Interesting and probably important detail : The tiles are properly connected with the tiles adjacent to their corners on the x/z directions . There 's a sampling shift going on any time that tiles do n't have the same x-to-z delta . In the image below , the right-side tile is +x and +z from the other tile . All of the tiles with this relationship are properly connected.Here 's the project files uploaded in a zip . Tell me if it 's not working or something ... http : //www.filefactory.com/file/4fc75xtd3yzl/n/FPS_zipTo see the terrain , press Play after switching to testScene if it does n't start there . GameObject generates the data and the terrain objects ( it has the RandomTerrain script from scripts/General/ attached ) . You can modify the parameters to the perlin noise from there . Please note that right now , only the first perlin octave , o_elevator is active in the terrain generation . All of the other public perlin octave variables have no influence , for the purpose of solving this glitch . /* x and y are the indices of the tile being loaded . The game maintains a square of pages loaded , where the number of pages per side is equal to loadSquares ( see below ) . x and y are the indices of the page to generate within that square . */ public void generate ( int x , int y ) { /* pagePos represents the world x and y coordinates of the bottom left corner of the page being generated . This is given by ... new Vector2 ( ( - ( float ) loadSquares / 2.0f + x + xCoord ) * tileSize , ( - ( float ) loadSquares / 2.0f + y + zCoord ) * tileSize ) ; This is because the origin tile 's center is at 0 , 0. xCoord represents the tile that the target object is on , which is what the loaded square is centered around . tileSize is the length of each side of each tile . */ Vector2 pagePos = getPagePos ( x , y ) ; //Here I get the number of samples x and y in the heightmap . int xlim = td [ x , y ] .heightmapWidth ; int ylim = td [ x , y ] .heightmapHeight ; //The actual data float [ , ] array = new float [ xlim , ylim ] ; //These will represent the minimum and maximum values in this tile . //I will need them to convert the data to something unity can use . float min = 0.0f ; float max = 0.0f ; for ( int cx = 0 ; cx < xlim ; cx++ ) { for ( int cy = 0 ; cy < ylim ; cy++ ) { //Here I actually sample the perlin function . //Right now it does n't look like terrain ( intentionally , testing ) . array [ cx , cy ] = sample ( new Vector3 ( ( float ) cx / ( float ) ( xlim - 1 ) * tileSize + pagePos.x , ( float ) cy / ( float ) ( ylim - 1 ) * tileSize + pagePos.y , 122.79f ) ) ; //On the first iteration , set min and max if ( cx == 0 & & cy == 0 ) { min = array [ cx , cy ] ; max = min ; } else { //update min and max min = Mathf.Min ( min , array [ cx , cy ] ) ; max = Mathf.Max ( max , array [ cx , cy ] ) ; } } } //Set up the Terrain object to receive the data float diff = max ! = min ? max - min : 10.0f ; tr [ x , y ] .position = new Vector3 ( pagePos.x , min , pagePos.y ) ; td [ x , y ] .size = new Vector3 ( tileSize , diff , tileSize ) ; //Convert the data to fit in the Terrain object /* Unity 's terrain only accepts values between 0.0f and 1.0f . Therefore , I shift the terrain vertically in the code above , and I squish the data to fit below . */ for ( int cx = 0 ; cx < xlim ; cx++ ) { for ( int cy = 0 ; cy < ylim ; cy++ ) { array [ cx , cy ] -= min ; array [ cx , cy ] /= diff ; } } //Set the data in the Terrain object td [ x , y ] .SetHeights ( 0 , 0 , array ) ; } }",Perlin terrain pages mismatched : elusive bug "C_sharp : I 'm learning to write custom type conversions in C # and I have a question I ca n't manage to resolve with Google / MSDN / earlier posted SO items.Normally , a C # program that narrows a numeric type does that via unchecked explicit conversion , e.g . : however , the following will give an overflow exception : My question is as follows : is the behavior of the checked / unchecked keyword implementable in an custom type conversion , e.g . : Of course , the code above is not the answer , but does anyone know if something like this is possible ? int i = 256 ; byte b = ( byte ) i ; // b == 0 byte b = checked ( ( byte ) i ) ; class Foo { public static explicit operator int ( Foo bar ) { if ( checked ) throw someEception else return some Foo to int conversion } }",C # - custom explicit conversion with checked/unchecked operator "C_sharp : Following this question I would like to know if the reuse of lambda parameter expression instances should be considered good or bad ? I sometimes get a complete LINQ expression tree where the same lambda parameter instance is local correctly used in a second , nonnested lambda : So the declaration of the same lambda parameter instance lparam is correct for both lambda1 and lambda2 . It is just that this shared lambda parameter instance forces IQueryProvider implementations to not associate additional global meaning based on the pure lambda parameter reference , as the same parameter could need to be interpreted differently during processing of a different lambda . Also , you will not get this kind of expression tree ( or should I say graph ? ) from LINQ by usingbecause there will be different parameter instances of ( Person x ) for both lambda expressions . The same goes fororIt also makes the expression tree to be rather a graph . Is that style of reuse of parameter instances considered good or bad ? So far , I have not found a clear answer to this from the authorities . // class Person { public int AProp { get ; set ; } public bool BProp { get ; set ; } } var lparam = Expression.Parameter ( typeof ( Person ) , '' x '' ) ; var lambda1 = ( Expression < Func < Person , int > > ) Expression.Lambda ( Expression.Property ( lparam , `` AProp '' ) , lparam ) ; var lambda2 = ( Expression < Func < Person , bool > > ) Expression.Lambda ( Expression.Property ( lparam , `` BProp '' ) , lparam ) ; var source = ( new Person [ 0 ] ) .AsQueryable ( ) ; var query = source.Where ( lambda2 ) .OrderBy ( lambda1 ) ; Expression < Func < Person , int > > lambda3 = x = > x.AProp ; Expression < Func < Person , bool > > lambda4 = x = > x.BProp ; var query = source.Where ( x = > x.BProp ) .OrderBy ( x = > x.AProp ) ; var query = from x in source where x.BProp order by x.AProp select x ;",Should LINQ lambda expression parameters be reused in a second lambda ? "C_sharp : I have ICOP VDX-6354 board running Win CE . I 'm trying to control the buzzer of the board from my C # program . I tried all the playsound etc `` coredll.dll '' platform invokes . none of them worked so far . So my last chance is to create my own DLL.The code above is available in the datasheet of the board . I want to compile it as a DLL then invoke it in my C # program likeI used a prefix as follows when I compiled : So that hopefully I would be able to control the buzzer . My problem is I could n't be successful compiling it . I followed the steps here but it did n't help me.What should I do step by step ? EDIT : I think I built the DLL . I tried another way to build the DLL found here.Now , I copied the DLL to my C # startup project 's Debug folder ( Other DLLs of the project are also in this folder ) . Then I try to invoke MyBeep function from MyBeep.DLL in my C # project by : But it gives the following exception . Ca n't find PInvoke DLL 'MyBeep.dll'.Am I missing something ? Please check the links given above that I cheated to build the DLL to understand what I did so far.Regards . unsigned char inp ( short addr ) { unsigned char cValue ; _asm { mov dx , addr in ax , dx mov cValue , al } return cValue ; } void outp ( int addr , unsigned char val ) { __asm { push edx mov edx , DWORD PTR addr mov al , BYTE PTR val out dx , al pop edx } } bool MyBeep ( DWORD dwFreq , DWORD dwDuration ) { outp ( 0x43 , 0xb6 ) ; // Set Buzzer outp ( 0x42 , ( 0x1234dc / dwFreq ) ) ; // Frequency LSB outp ( 0x42 , ( 0x1234dc / dwFreq ) > > 8 ) ; // Frequency MSB outp ( 0x61 , inp ( 0x61 ) | 0x3 ) ; // Start beep Sleep ( dwDuration ) ; outp ( 0x61 , inp ( 0x61 ) & 0xfc ) ; // End beep return TRUE ; } [ DllImport ( `` Buzzer.dll '' , EntryPoint = `` MyBeep '' ) ] public static extern void MyBeep ( uint dwFreq , uint dwDuration ) ; extern `` C '' __declspec ( dllexport ) bool MyBeep ( DWORD dwFreq , DWORD dwDuration ) [ DllImport ( `` MyBeep.dll '' , EntryPoint = `` MyBeep '' ) ] public static extern bool MyBeep ( UInt32 dwFreq , UInt32 dwDuration ) ;",How to create a DLL that will be used in C # "C_sharp : I was browsing the .NET Core source tree today and ran across this pattern in System.Collections.Immutable.ImmutableArray < T > : This pattern ( storing this in a local variable ) seems to be consistently applied in this file whenever this would otherwise be referenced multiple times in the same method , but not when it is only referenced once . So I started thinking about what the relative advantages might be to doing it this way ; it seems to me that the advantage is likely performance-related , so I went down this route a little further ... maybe I 'm overlooking something else.The CIL that gets emitted for the `` store this in a local '' pattern seems to look something like a ldarg.0 , then ldobj UnderlyingType , then stloc.0 so that later references come from ldloc.0 instead of a bare ldarg.0 like it would be to just use this multiple times.Maybe ldarg.0 is significantly slower than ldloc.0 , but not by enough for either the C # -to-CIL translation or the JITter to look for opportunities to optimize this for us , such that it makes more sense to write this weird-looking pattern in C # code any time we would otherwise emit two ldarg.0 instructions in a struct instance method ? Update : or , you know , I could have looked at the comments at the top of that file , which explain exactly what 's going on ... T IList < T > .this [ int index ] { get { var self = this ; self.ThrowInvalidOperationIfNotInitialized ( ) ; return self [ index ] ; } set { throw new NotSupportedException ( ) ; } }",What advantage is there to storing `` this '' in a local variable in a struct method ? "C_sharp : What I hoped would be an hour or two of work has now turned into quite the debacle with no result in sight.Problem : I am trying to serialise a copy of my NHibernate Configuration and store it in ... the project that was used to generate it ! Current manual solution : I have a project Foo that contains a series of DomainObject.Map.cs filesReferences an `` nhconfig.bin '' file for embedding as a resource.Contains a static method FooGenerateNHConfig that create a Configuration object and serialise it to nhconfig.bin.To generate it , I : ( first time only : create an empty nhconfig.bin that acts as placeholder ) .Build Foo.Call a unit test that calls FooGenerateNHConfig.Rebuild Foo.Deploy application.I 'm trying to automate this , and thought it would be a simple matter : Create a project Foo.BuildSupport that referenced Foo.Define a Task X in it which would call FooGenerateNHConfig.Setup an AfterCompile target that would call X.Unfortunately I 'm now getting 2 errors.Firstly , a somewhat odd exception : I think that 's FluentNHibernate complaining that it ca n't find the FluentNHibernate assembly ? Once I run the Task from visual studio the first time , visual studio ( devenv.exe ) locks my Foo.BuildSupport.dll AND my Foo.exe ( presumably because it just sees them as support libraries and not the actual build libraries ) , so I ca n't rebuild them . Generally , this is because vs assumes ( and probably rightfully so ) that the BuildSupport library is fairly static and does not rely What 's a good way to automate a process such as this ? I only have some preliminary thoughts right now but the only thing I can think of is building an entirely seperate executable to be run by msbuild ( saw a task to do the equivalent of this , ca n't find it now ) , or something rather involved involving a seperate appdomain and manually calling the function via reflection . But before I went further down this path , am I missing something easier and more obvious ? FluentNHibernate.Cfg.FluentConfigurationException : An invalid or incomplete configuration was used while creating a SessionFactory . Check PotentialReasons collection , and InnerException for more detail. -- - > System.Runtime.Serialization.SerializationException : Unable to find assembly 'FluentNHibernate , Version=1.1.0.685 , Culture=neutral , PublicKeyToken=8aa435e3cb308880 ' .",MSBuild task to build load my assembly and build a serialised NHibernate Configuration "C_sharp : Article Details of Regular Expression Behavior from MSDN says , that .NET devs decide to use for regular expressions traditional NFA engine , because it is faster than POSIX NFA , but it is not clear to me , why does this pattern works exponentially slow then ? This simple pattern matching take more than 30 minute to execute . But if .NET uses traditional NFA , it is possible to simulate it and find match in O ( M*N ) time in the worst case , where M is pattern length and N is text length , which surely is not true in this case . Article also explains that backtracking is the reason of slow execution , but I still have some questions that ca n't find answersWhat is backtracking ? is it only using already matched pattern again like this ( a|b ) c/1 ? Does traditional NFA support backtracking , if no what modification does it need ? If NFA supports it , but need more slower algorithm to simulate , why .NET ca n't check if backtracking exist in the pattern , and use one algorithm and use another if it does n't ? var regex = new Regex ( `` ( a|aa ) *b '' ) ; var b = regex.IsMatch ( `` aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac '' ) ;",Does .NET really use NFA for regular expression engine ? "C_sharp : I ’ m currently having issues with EF core 2.1 and a web api used by a native client to update an object which contains several levels of embedded objects.I ’ ve already read theses two topics : Entity Framework Core : Fail to update Entity with nested value objectshttps : //docs.microsoft.com/en-us/ef/core/saving/disconnected-entitiesI ’ ve learned through this that it is indeed not that obvious for now to update objects in EF Core 2 . But I ’ ve not yet managed to find a solution that works . On each attempt I ’ m having an exception telling me that a “ step ” is already tracked by EF.My model looks like this : //Deployment Scenario which have a one to many relationship with Application . A deployment scenario contain two lists of steps//Step , which is also quite complex and is also self-referencingHere ’ s my update method , I know it ’ s ugly and it shouldn ’ t be in the controller but I ’ m changing it every two hours as I try to implement solutions if find on the web . So this is the last iteration coming from https : //docs.microsoft.com/en-us/ef/core/saving/disconnected-entitiesSo far I ’ m getting this exception : The instance of entity type 'Step ' can not be tracked because another instance with the key value ' { ID : e29b3c1c-2e06-4c7b-b0cd-f8f1c5ccb7b6 } ' is already being tracked . I paid attention that no “ get ” operation was made previously by the client and even if it was the case I ’ ve put AsNoTracking on my get methods . The only operation made before the update by the client is “ _context.CIApplications.Any ( e = > e.ID == id ) ; ” to ckeck if I should Add a new record or update an existing one.I ’ ve been fighting with this issue since few days so I would really appreciate if someone could help me getting in the right direction.Many thanksUPDATE : I added the following code in my controller : The entries = _context.ChangeTracker.Entries ( ) ; line raise the `` step is already tracked '' exception right after adding the new deploymentScenario which contains the also new step.Just before it the new deploymentScenario and step are not in the tracker and I 've check in DB their IDs are not duplicated.I also check my Post method and now it 's failing too ... I reverted it to the default methods with no fancy stuff Inside : Entries are empty at the beginning and the _context.CIApplications.Add ( cIApplication ) ; line is still raising the exception still about the only one step included in the deploymentscenario ... So there obviously somthing wrong when I try to add stuff in my context , but right now I 'm feeling totally lost . It may can help here how I declare my context in startup : Add my context class : UPDATE 2Here 's a one drive link to a minima repro example . I have n't implemented PUT in the client as the post method already reproduce the issue.https : //1drv.ms/u/s ! AsO87EeN0Fnsk7dDRY3CJeeLT-4Vag //CIApplication the root class I ’ m trying to updatepublic class CIApplication : ConfigurationItem // - > derive of BaseEntity which holds the ID and some other properties { //Collection of DeploymentScenario public virtual ICollection < DeploymentScenario > DeploymentScenarios { get ; set ; } //Collection of SoftwareMeteringRules public virtual ICollection < SoftwareMeteringRule > SoftwareMeteringRules { get ; set ; } } public class DeploymentScenario : BaseEntity { //Collection of substeps public virtual ICollection < Step > InstallSteps { get ; set ; } public virtual ICollection < Step > UninstallSteps { get ; set ; } //Navigation properties Parent CI public Guid ? ParentCIID { get ; set ; } public virtual CIApplication ParentCI { get ; set ; } } public class Step : BaseEntity { public string ScriptBlock { get ; set ; } //Parent Step Navigation property public Guid ? ParentStepID { get ; set ; } public virtual Step ParentStep { get ; set ; } //Parent InstallDeploymentScenario Navigation property public Guid ? ParentInstallDeploymentScenarioID { get ; set ; } public virtual DeploymentScenario ParentInstallDeploymentScenario { get ; set ; } //Parent InstallDeploymentScenario Navigation property public Guid ? ParentUninstallDeploymentScenarioID { get ; set ; } public virtual DeploymentScenario ParentUninstallDeploymentScenario { get ; set ; } //Collection of sub steps public virtual ICollection < Step > SubSteps { get ; set ; } //Collection of input variables public virtual List < ScriptVariable > InputVariables { get ; set ; } //Collection of output variables public virtual List < ScriptVariable > OutPutVariables { get ; set ; } } public async Task < IActionResult > PutCIApplication ( [ FromRoute ] Guid id , [ FromBody ] CIApplication cIApplication ) { _logger.LogWarning ( `` Updating CIApplication `` + cIApplication.Name ) ; if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } if ( id ! = cIApplication.ID ) { return BadRequest ( ) ; } var cIApplicationInDB = _context.CIApplications .Include ( c = > c.Translations ) .Include ( c = > c.DeploymentScenarios ) .ThenInclude ( d = > d.InstallSteps ) .ThenInclude ( s = > s.SubSteps ) .Include ( c = > c.DeploymentScenarios ) .ThenInclude ( d = > d.UninstallSteps ) .ThenInclude ( s = > s.SubSteps ) .Include ( c = > c.SoftwareMeteringRules ) .Include ( c = > c.Catalogs ) .Include ( c = > c.Categories ) .Include ( c = > c.OwnerCompany ) .SingleOrDefault ( c = > c.ID == id ) ; _context.Entry ( cIApplicationInDB ) .CurrentValues.SetValues ( cIApplication ) ; foreach ( var ds in cIApplication.DeploymentScenarios ) { var existingDeploymentScenario = cIApplicationInDB.DeploymentScenarios.FirstOrDefault ( d = > d.ID == ds.ID ) ; if ( existingDeploymentScenario == null ) { cIApplicationInDB.DeploymentScenarios.Add ( ds ) ; } else { _context.Entry ( existingDeploymentScenario ) .CurrentValues.SetValues ( ds ) ; foreach ( var step in existingDeploymentScenario.InstallSteps ) { var existingStep = existingDeploymentScenario.InstallSteps.FirstOrDefault ( s = > s.ID == step.ID ) ; if ( existingStep == null ) { existingDeploymentScenario.InstallSteps.Add ( step ) ; } else { _context.Entry ( existingStep ) .CurrentValues.SetValues ( step ) ; } } } } foreach ( var ds in cIApplicationInDB.DeploymentScenarios ) { if ( ! cIApplication.DeploymentScenarios.Any ( d = > d.ID == ds.ID ) ) { _context.Remove ( ds ) ; } } //_context.Update ( cIApplication ) ; try { await _context.SaveChangesAsync ( ) ; } catch ( DbUpdateConcurrencyException e ) { if ( ! CIApplicationExists ( id ) ) { return NotFound ( ) ; } else { throw ; } } catch ( Exception e ) { } return Ok ( cIApplication ) ; } var existingStep = existingDeploymentScenario.InstallSteps.FirstOrDefault ( s = > s.ID == step.ID ) ; entries = _context.ChangeTracker.Entries ( ) ; if ( existingStep == null ) { existingDeploymentScenario.InstallSteps.Add ( step ) ; entries = _context.ChangeTracker.Entries ( ) ; } [ HttpPost ] public async Task < IActionResult > PostCIApplication ( [ FromBody ] CIApplication cIApplication ) { if ( ! ModelState.IsValid ) { return BadRequest ( ModelState ) ; } var entries = _context.ChangeTracker.Entries ( ) ; _context.CIApplications.Add ( cIApplication ) ; entries = _context.ChangeTracker.Entries ( ) ; await _context.SaveChangesAsync ( ) ; entries = _context.ChangeTracker.Entries ( ) ; return CreatedAtAction ( `` GetCIApplication '' , new { id = cIApplication.ID } , cIApplication ) ; } services.AddDbContext < MyAppContext > ( options = > options.UseSqlServer ( Configuration.GetConnectionString ( `` DefaultConnection '' ) , b = > b.MigrationsAssembly ( `` DeployFactoryDataModel '' ) ) , ServiceLifetime.Transient ) ; public class MyAppContext : DbContext { private readonly IHttpContextAccessor _contextAccessor ; public MyAppContext ( DbContextOptions < MyAppContext > options , IHttpContextAccessor contextAccessor ) : base ( options ) { _contextAccessor = contextAccessor ; } protected override void OnConfiguring ( DbContextOptionsBuilder optionsBuilder ) { optionsBuilder.EnableSensitiveDataLogging ( ) ; } public DbSet < Step > Steps { get ; set ; } //public DbSet < Sequence > Sequences { get ; set ; } public DbSet < DeploymentScenario > DeploymentScenarios { get ; set ; } public DbSet < ConfigurationItem > ConfigurationItems { get ; set ; } public DbSet < CIApplication > CIApplications { get ; set ; } public DbSet < SoftwareMeteringRule > SoftwareMeteringRules { get ; set ; } public DbSet < Category > Categories { get ; set ; } public DbSet < ConfigurationItemCategory > ConfigurationItemsCategories { get ; set ; } public DbSet < Company > Companies { get ; set ; } public DbSet < User > Users { get ; set ; } public DbSet < Group > Groups { get ; set ; } public DbSet < Catalog > Catalogs { get ; set ; } public DbSet < CIDriver > CIDrivers { get ; set ; } public DbSet < DriverCompatiblityEntry > DriverCompatiblityEntries { get ; set ; } public DbSet < ScriptVariable > ScriptVariables { get ; set ; } protected override void OnModelCreating ( ModelBuilder modelBuilder ) { //Step one to many with step for sub steps modelBuilder.Entity < Step > ( ) .HasMany ( s = > s.SubSteps ) .WithOne ( s = > s.ParentStep ) .HasForeignKey ( s = > s.ParentStepID ) ; //Step one to many with step for variables modelBuilder.Entity < Step > ( ) .HasMany ( s = > s.InputVariables ) .WithOne ( s = > s.ParentInputStep ) .HasForeignKey ( s = > s.ParentInputStepID ) ; modelBuilder.Entity < Step > ( ) .HasMany ( s = > s.OutPutVariables ) .WithOne ( s = > s.ParentOutputStep ) .HasForeignKey ( s = > s.ParentOutputStepID ) ; //Step one to many with sequence //modelBuilder.Entity < Step > ( ) .HasOne ( step = > step.ParentSequence ) .WithMany ( seq = > seq.Steps ) .HasForeignKey ( step = > step.ParentSequenceID ) .OnDelete ( DeleteBehavior.Cascade ) ; //DeploymentScenario One to many with install steps modelBuilder.Entity < DeploymentScenario > ( ) .HasMany ( d = > d.InstallSteps ) .WithOne ( s = > s.ParentInstallDeploymentScenario ) .HasForeignKey ( s = > s.ParentInstallDeploymentScenarioID ) ; //DeploymentScenario One to many with uninstall steps modelBuilder.Entity < DeploymentScenario > ( ) .HasMany ( d = > d.UninstallSteps ) .WithOne ( s = > s.ParentUninstallDeploymentScenario ) .HasForeignKey ( s = > s.ParentUninstallDeploymentScenarioID ) ; //DeploymentScenario one to one with sequences //modelBuilder.Entity < DeploymentScenario > ( ) .HasOne ( ds = > ds.InstallSequence ) .WithOne ( seq = > seq.IDeploymentScenario ) .HasForeignKey < DeploymentScenario > ( ds = > ds.InstallSequenceID ) .OnDelete ( DeleteBehavior.Cascade ) ; //modelBuilder.Entity < DeploymentScenario > ( ) .HasOne ( ds = > ds.UninstallSequence ) .WithOne ( seq = > seq.UDeploymentScenario ) .HasForeignKey < DeploymentScenario > ( ds = > ds.UninstallSequenceID ) ; //Step MUI config modelBuilder.Entity < Step > ( ) .Ignore ( s = > s.Description ) ; modelBuilder.Entity < Step > ( ) .HasMany ( s = > s.Translations ) .WithOne ( ) .HasForeignKey ( x = > x.StepTranslationId ) ; //Sequence MUI config //modelBuilder.Entity < Sequence > ( ) .Ignore ( s = > s.Description ) ; //modelBuilder.Entity < Sequence > ( ) .HasMany ( s = > s.Translations ) .WithOne ( ) .HasForeignKey ( x = > x.SequenceTranslationId ) ; //DeploymentScenario MUI config modelBuilder.Entity < DeploymentScenario > ( ) .Ignore ( s = > s.Name ) ; modelBuilder.Entity < DeploymentScenario > ( ) .Ignore ( s = > s.Description ) ; modelBuilder.Entity < DeploymentScenario > ( ) .HasMany ( s = > s.Translations ) .WithOne ( ) .HasForeignKey ( x = > x.DeploymentScenarioTranslationId ) ; //CIApplication relations //CIApplication one to many relation with Deployment Scenario modelBuilder.Entity < CIApplication > ( ) .HasMany ( ci = > ci.DeploymentScenarios ) .WithOne ( d = > d.ParentCI ) .HasForeignKey ( d = > d.ParentCIID ) .OnDelete ( DeleteBehavior.Cascade ) ; modelBuilder.Entity < CIApplication > ( ) .HasMany ( ci = > ci.SoftwareMeteringRules ) .WithOne ( d = > d.ParentCI ) .HasForeignKey ( d = > d.ParentCIID ) .OnDelete ( DeleteBehavior.Cascade ) ; // CIDriver relations // CIAPpplication one to many relation with DriverCompatibilityEntry modelBuilder.Entity < CIDriver > ( ) .HasMany ( ci = > ci.CompatibilityList ) .WithOne ( c = > c.ParentCI ) .HasForeignKey ( c = > c.ParentCIID ) .OnDelete ( DeleteBehavior.Restrict ) ; //ConfigurationItem MUI config modelBuilder.Entity < ConfigurationItem > ( ) .Ignore ( s = > s.Name ) ; modelBuilder.Entity < ConfigurationItem > ( ) .Ignore ( s = > s.Description ) ; modelBuilder.Entity < ConfigurationItem > ( ) .HasMany ( s = > s.Translations ) .WithOne ( ) .HasForeignKey ( x = > x.ConfigurationItemTranslationId ) ; //category MUI config modelBuilder.Entity < Category > ( ) .Ignore ( s = > s.Name ) ; modelBuilder.Entity < Category > ( ) .Ignore ( s = > s.Description ) ; modelBuilder.Entity < Category > ( ) .HasMany ( s = > s.Translations ) .WithOne ( ) .HasForeignKey ( x = > x.CategoryTranslationId ) ; //CI Categories Many to Many modelBuilder.Entity < ConfigurationItemCategory > ( ) .HasKey ( cc = > new { cc.CategoryId , cc.CIId } ) ; modelBuilder.Entity < ConfigurationItemCategory > ( ) .HasOne ( cc = > cc.Category ) .WithMany ( cat = > cat.ConfigurationItems ) .HasForeignKey ( cc = > cc.CategoryId ) ; modelBuilder.Entity < ConfigurationItemCategory > ( ) .HasOne ( cc = > cc.ConfigurationItem ) .WithMany ( ci = > ci.Categories ) .HasForeignKey ( cc = > cc.CIId ) ; //CI Catalog Many to Many modelBuilder.Entity < CICatalog > ( ) .HasKey ( cc = > new { cc.CatalogId , cc.ConfigurationItemId } ) ; modelBuilder.Entity < CICatalog > ( ) .HasOne ( cc = > cc.Catalog ) .WithMany ( cat = > cat.CIs ) .HasForeignKey ( cc = > cc.CatalogId ) ; modelBuilder.Entity < CICatalog > ( ) .HasOne ( cc = > cc.ConfigurationItem ) .WithMany ( ci = > ci.Catalogs ) .HasForeignKey ( cc = > cc.ConfigurationItemId ) ; //Company Customers Many to Many modelBuilder.Entity < CompanyCustomers > ( ) .HasKey ( cc = > new { cc.CustomerId , cc.ProviderId } ) ; modelBuilder.Entity < CompanyCustomers > ( ) .HasOne ( cc = > cc.Provider ) .WithMany ( p = > p.Customers ) .HasForeignKey ( cc = > cc.ProviderId ) .OnDelete ( DeleteBehavior.Restrict ) ; modelBuilder.Entity < CompanyCustomers > ( ) .HasOne ( cc = > cc.Customer ) .WithMany ( c = > c.Providers ) .HasForeignKey ( cc = > cc.CustomerId ) ; //Company Catalog Many to Many modelBuilder.Entity < CompanyCatalog > ( ) .HasKey ( cc = > new { cc.CatalogId , cc.CompanyId } ) ; modelBuilder.Entity < CompanyCatalog > ( ) .HasOne ( cc = > cc.Catalog ) .WithMany ( c = > c.Companies ) .HasForeignKey ( cc = > cc.CatalogId ) ; modelBuilder.Entity < CompanyCatalog > ( ) .HasOne ( cc = > cc.Company ) .WithMany ( c = > c.Catalogs ) .HasForeignKey ( cc = > cc.CompanyId ) ; //Author Catalog Many to Many modelBuilder.Entity < CatalogAuthors > ( ) .HasKey ( ca = > new { ca.AuthorId , ca.CatalogId } ) ; modelBuilder.Entity < CatalogAuthors > ( ) .HasOne ( ca = > ca.Catalog ) .WithMany ( c = > c.Authors ) .HasForeignKey ( ca = > ca.CatalogId ) ; modelBuilder.Entity < CatalogAuthors > ( ) .HasOne ( ca = > ca.Author ) .WithMany ( a = > a.AuthoringCatalogs ) .HasForeignKey ( ca = > ca.AuthorId ) ; //Company one to many with owned Catalog modelBuilder.Entity < Company > ( ) .HasMany ( c = > c.OwnedCatalogs ) .WithOne ( c = > c.OwnerCompany ) .HasForeignKey ( c = > c.OwnerCompanyID ) .OnDelete ( DeleteBehavior.Restrict ) ; //Company one to many with owned Categories modelBuilder.Entity < Company > ( ) .HasMany ( c = > c.OwnedCategories ) .WithOne ( c = > c.OwnerCompany ) .HasForeignKey ( c = > c.OwnerCompanyID ) .OnDelete ( DeleteBehavior.Restrict ) ; //Company one to many with owned CIs modelBuilder.Entity < Company > ( ) .HasMany ( c = > c.OwnedCIs ) .WithOne ( c = > c.OwnerCompany ) .HasForeignKey ( c = > c.OwnerCompanyID ) .OnDelete ( DeleteBehavior.Restrict ) ; //CIDriver one to many with DriverCompatibilityEntry modelBuilder.Entity < CIDriver > ( ) .HasMany ( c = > c.CompatibilityList ) .WithOne ( c = > c.ParentCI ) .HasForeignKey ( c = > c.ParentCIID ) .OnDelete ( DeleteBehavior.Restrict ) ; //User Group Many to Many modelBuilder.Entity < UserGroup > ( ) .HasKey ( ug = > new { ug.UserId , ug.GroupId } ) ; modelBuilder.Entity < UserGroup > ( ) .HasOne ( cg = > cg.User ) .WithMany ( ci = > ci.Groups ) .HasForeignKey ( cg = > cg.UserId ) ; modelBuilder.Entity < UserGroup > ( ) .HasOne ( cg = > cg.Group ) .WithMany ( ci = > ci.Users ) .HasForeignKey ( cg = > cg.GroupId ) ; //User one to many with Company modelBuilder.Entity < Company > ( ) .HasMany ( c = > c.Employees ) .WithOne ( u = > u.Employer ) .HasForeignKey ( u = > u.EmployerID ) .OnDelete ( DeleteBehavior.Restrict ) ; }",Entity Framework Core 2.1 failling to update entities with relations "C_sharp : I 'm trying to implement wrapper class which will simply connect to TCP server and wait for data . Once data submitted from server - I will receive this data and pass it onto subscribers of my class.All this works . Now I want to add external functionality to `` reset '' this class on a timer ( force reconnect every so often ) to keep connection alive . My idea is that Init method can be called as many times as needed to get socket reset . However , I do get various exceptions with this.Class code : Client code ( under button click on form ) Exceptions I get . First exception when button clicked 2nd time in from handler in DataReceived The IAsyncResult object was not returned from the corresponding asynchronous method on this class.On following clicks I get exception from handler in EstablishReceiver A request to send or receive data was disallowed because the socket is not connected and ( when sending on a datagram socket using a sendto call ) no address was suppliedHow do I properly ensure socket closed and re-opened ? namespace Ditat.GateControl.Service.InputListener { using System ; using System.ComponentModel ; using System.Net ; using System.Net.Sockets ; using System.Text ; public class BaseTCPSocketListener : IInputListener { # region Events/Properties public event EventHandler < Exception > OnError ; public event EventHandler < string > OnDataReceived ; private string host ; private int port ; private int delayToClearBufferSeconds = 5 ; private TcpClient client ; private readonly byte [ ] buffer = new byte [ 1024 ] ; /// < summary > /// Will accumulate data as it 's received /// < /summary > private string DataBuffer { get ; set ; } /// < summary > /// Store time of last data receipt . Need this in order to purge data after delay /// < /summary > private DateTime LastDataReceivedOn { get ; set ; } # endregion public BaseTCPSocketListener ( ) { // Preset all entries this.LastDataReceivedOn = DateTime.UtcNow ; this.DataBuffer = string.Empty ; } public void Init ( string config ) { // Parse info var bits = config.Split ( new [ ] { '| ' } , StringSplitOptions.RemoveEmptyEntries ) ; this.host = bits [ 0 ] ; var hostBytes = this.host.Split ( new [ ] { ' . ' } , StringSplitOptions.RemoveEmptyEntries ) ; var hostIp = new IPAddress ( new [ ] { byte.Parse ( hostBytes [ 0 ] ) , byte.Parse ( hostBytes [ 1 ] ) , byte.Parse ( hostBytes [ 2 ] ) , byte.Parse ( hostBytes [ 3 ] ) } ) ; this.port = int.Parse ( bits [ 1 ] ) ; this.delayToClearBufferSeconds = int.Parse ( bits [ 2 ] ) ; // Close open client if ( this.client ? .Client ! = null ) { this.client.Client.Disconnect ( true ) ; this.client = null ; } // Connect to client this.client = new TcpClient ( ) ; if ( ! this.client.ConnectAsync ( hostIp , this.port ) .Wait ( 2500 ) ) throw new Exception ( $ '' Failed to connect to { this.host } : { this.port } in allotted time '' ) ; this.EstablishReceiver ( ) ; } protected void DataReceived ( IAsyncResult result ) { // End the data receiving that the socket has done and get the number of bytes read . var bytesCount = 0 ; try { bytesCount = this.client.Client.EndReceive ( result ) ; } catch ( Exception ex ) { this.RaiseOnErrorToClient ( new Exception ( nameof ( this.DataReceived ) ) ) ; this.RaiseOnErrorToClient ( ex ) ; } // No data received , establish receiver and return if ( bytesCount == 0 ) { this.EstablishReceiver ( ) ; return ; } // Convert the data we have to a string . this.DataBuffer += Encoding.UTF8.GetString ( this.buffer , 0 , bytesCount ) ; // Record last time data received this.LastDataReceivedOn = DateTime.UtcNow ; this.RaiseOnDataReceivedToClient ( this.DataBuffer ) ; this.DataBuffer = string.Empty ; this.EstablishReceiver ( ) ; } private void EstablishReceiver ( ) { try { // Set up again to get the next chunk of data . this.client.Client.BeginReceive ( this.buffer , 0 , this.buffer.Length , SocketFlags.None , this.DataReceived , this.buffer ) ; } catch ( Exception ex ) { this.RaiseOnErrorToClient ( new Exception ( nameof ( this.EstablishReceiver ) ) ) ; this.RaiseOnErrorToClient ( ex ) ; } } private void RaiseOnErrorToClient ( Exception ex ) { if ( this.OnError == null ) return ; foreach ( Delegate d in this.OnError.GetInvocationList ( ) ) { var syncer = d.Target as ISynchronizeInvoke ; if ( syncer == null ) { d.DynamicInvoke ( this , ex ) ; } else { syncer.BeginInvoke ( d , new object [ ] { this , ex } ) ; } } } private void RaiseOnDataReceivedToClient ( string data ) { if ( this.OnDataReceived == null ) return ; foreach ( Delegate d in this.OnDataReceived.GetInvocationList ( ) ) { var syncer = d.Target as ISynchronizeInvoke ; if ( syncer == null ) { d.DynamicInvoke ( this , data ) ; } else { syncer.BeginInvoke ( d , new object [ ] { this , data } ) ; } } } } } private void ListenBaseButton_Click ( object sender , EventArgs e ) { if ( this.bsl == null ) { this.bsl = new BaseTCPSocketListener ( ) ; this.bsl.OnDataReceived += delegate ( object o , string s ) { this.DataTextBox.Text += $ '' Base : { DateTime.Now } - { s } '' + Environment.NewLine ; } ; this.bsl.OnError += delegate ( object o , Exception x ) { this.DataTextBox.Text += $ '' Base TCP receiver error : { DateTime.Now } - { x.Message } '' + Environment.NewLine ; } ; } try { this.bsl.Init ( `` 192.168.33.70|10001|10 '' ) ; this.DataTextBox.Text += `` BEGIN RECEIVING BSL data -- -- -- -- -- -- -- -- -- -- -- -- -- '' + Environment.NewLine ; } catch ( Exception exception ) { this.DataTextBox.Text += $ '' ERROR CONNECTING TO BSL -- -- -- -- -- -- { exception.Message } '' + Environment.NewLine ; } }",TcpClient exceptions when calling EndReceive and BeginReceive "C_sharp : When running 'docker build . -t project ' I get this error : My Dockerfile looks like this : I have installed the package listed in the error message from NuGet . When I run the command 'dotnet publish -c Release -o out ' in a terminal it works , but running it inside the Dockerfile keeps failing . Any ideas ? My package references : Output from RUN dotnet restore : Step 6/10 : RUN dotnet publish -c Release -o out -- - > Running in 73c3f5fa9112Microsoft ( R ) Build Engine version 16.5.0+d4cbfca49 for .NET CoreCopyright ( C ) Microsoft Corporation . All rights reserved . Restore completed in 55.93 ms for /app/Backend.csproj./usr/share/dotnet/sdk/3.1.200/Sdks/Microsoft.NET.Sdk/targets/Microsoft.PackageDependencyResolution.targets ( 234,5 ) : error NETSDK1064 : Package Microsoft.CodeAnalysis.Analyzers , version 2.9.8 was not found . It might have been deleted since NuGet restore . Otherwise , NuGet restore might have only partially completed , which might have been due to maximum path length restrictions . [ /app/Backend.csproj ] The command '/bin/sh -c dotnet publish -c Release -o out ' returned a non-zero code : 1 FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-envWORKDIR /app # Copy csproj and restore as distinct layersCOPY *.csproj ./RUN dotnet restore # Copy everything else and buildCOPY . ./RUN dotnet publish -c Release -o out # Build runtime imageFROM mcr.microsoft.com/dotnet/core/aspnet:3.1WORKDIR /appCOPY -- from=build-env /app/out . # Command used to start the projectENTRYPOINT [ `` dotnet '' , `` Project.dll '' ] < PackageReference Include= '' Microsoft.AspNetCore.Authentication.Facebook '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.AspNetCore.Authentication.Google '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.AspNetCore.Identity.EntityFrameworkCore '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.AspNetCore.Identity.UI '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.CodeAnalysis.Analyzers '' Version= '' 2.9.8 '' / > < PackageReference Include= '' Microsoft.CodeAnalysis.FxCopAnalyzers '' Version= '' 2.9.8 '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.Sqlite '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.SqlServer '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.EntityFrameworkCore.Tools '' Version= '' 3.1.2 '' / > < PackageReference Include= '' Microsoft.VisualStudio.Web.CodeGeneration.Design '' Version= '' 3.1.1 '' / > Step 4/10 : RUN dotnet restore -- - > Running in 1f26d6ac4244 Restore completed in 47.46 sec for /app/Backend.csproj.Removing intermediate container 1f26d6ac4244 -- - > f1a2994a2704",Building Dockerfile in ASP.NET Core project fails when running dotnet publish -c Release -o out "C_sharp : I am using CsvHelper to read CSV files into Dynamic C # object and I would like to iterate the List < dynamic > using foreach and get property names and values.var properties = d.GetType ( ) .GetProperties ( ) ; always return 0 but I can see at debug that there are properties . the CSV file contains this data : FileInfo file = new FileInfo ( `` C : \\Temp\\CSVTest.csv '' ) ; List < dynamic > dynObj ; using ( var reader = new StreamReader ( file.FullName ) ) using ( var csv = new CsvReader ( reader ) ) { dynObj = csv.GetRecords < dynamic > ( ) .ToList ( ) ; foreach ( var d in dynObj ) { var properties = d.GetType ( ) .GetProperties ( ) ; foreach ( var property in properties ) { var PropertyName = property.Name ; var PropetyValue = d.GetType ( ) .GetProperty ( property.Name ) .GetValue ( d , null ) ; } } } Id , Name , Barnd1 , one , abc2 , two , xyz",How to get property name and value from C # Dynamic object when using CsvHelper ? "C_sharp : Example : Anyway , I want it to return `` MyProgram.Testing.Test2 '' but instead Test2.GetInheritedClassName ( ) returns `` MyProgram.Testing.Test1 '' . What do I have to put into that static class to get it to return that ( if possible ) ? namespace MyProgram.Testing { public class Test1 { public void TestMethod ( ) { String actualType = this.GetType ( ) .FullName.ToString ( ) ; return ; } public static String GetInheritedClassName ( ) { return System.Reflection.MethodBase.GetCurrentMethod ( ) .ReflectedType.FullName ; } } public class Test2 : Test1 { } public class Test3 { String test2ClassName = Test2.GetInheritedClassName ( ) ; } }",C # Retrieving Classname in a static method "C_sharp : Is there any class in .NET library which can act as expiring Lazy < T > ? The idea is that Func < T > value factory lambda is passed there and invoked only first time or if timeout is passed.I 've created simple class to do that , but I 'd like to avoid inventing a wheel . public class ExpiringLazy < T > { private readonly object valueGetLock = new object ( ) ; private readonly Func < T > valueFactory ; private readonly TimeSpan timeout ; private T cachedValue ; private DateTime cachedTime ; public T Value { get { Thread.MemoryBarrier ( ) ; if ( cachedTime.Equals ( default ( DateTime ) ) || DateTime.UtcNow > cachedTime + timeout ) { lock ( valueGetLock ) { if ( cachedTime.Equals ( default ( DateTime ) ) || DateTime.UtcNow > cachedTime + timeout ) { cachedValue = valueFactory ( ) ; Thread.MemoryBarrier ( ) ; cachedTime = DateTime.UtcNow ; } } } return cachedValue ; } } public ExpiringLazy ( Func < T > valueFactory , TimeSpan timeout ) { if ( valueFactory == null ) throw new ArgumentNullException ( nameof ( valueFactory ) ) ; this.valueFactory = valueFactory ; this.timeout = timeout ; } }",Expiring Lazy < T > class "C_sharp : Using web-api 2 and identity 2 , I 'm trying to create an action to remove a user from roles using user id and role names . I 'm using the ApplicationUserManager provided by the nuget identity2 sample.My actionMy view model : ApplicationUserManager 's RemoveUserFromRolesAsync : My issue is that given a user belonging to the roles 'User ' and 'Mod ' , the user can not be removed from 'Mod ' . Posting the following json removes the user from the role 'User ' as expected : But given the following json , user is not removed from 'Mod ' , but is instead removed from 'User ' : Debugging shows that when given the role 'Mod ' , the correct user id and role name are passed into userRoleStore . [ HttpPost ] [ Route ( `` RemoveUserFromRole '' ) ] public async Task < IHttpActionResult > RemoveUserFromRole ( UserRolesViewModel model ) { if ( ! ModelState.IsValid ) return BadRequest ( ModelState ) ; var result = await UserManager.RemoveUserFromRolesAsync ( model.UserId , model.RoleNames ) ; if ( result.Errors.Any ( ) ) return InternalServerError ( ) ; return Ok ( ) ; } public class UserRolesViewModel { [ Required ] public string UserId { get ; set ; } [ Required ] public IList < string > RoleNames { get ; set ; } } public virtual async Task < IdentityResult > RemoveUserFromRolesAsync ( string userId , IList < string > roles ) { var userRoleStore = ( IUserRoleStore < ApplicationUser , string > ) Store ; var user = await FindByIdAsync ( userId ) .ConfigureAwait ( false ) ; if ( user == null ) throw new InvalidOperationException ( `` Invalid user Id '' ) ; var userRoles = await userRoleStore.GetRolesAsync ( user ) .ConfigureAwait ( false ) ; foreach ( var role in roles.Where ( userRoles.Contains ) ) await userRoleStore.RemoveFromRoleAsync ( user , role ) .ConfigureAwait ( false ) ; return await UpdateAsync ( user ) .ConfigureAwait ( false ) ; } { `` userId '' : `` 0d5f97e4-65a0-43ad-b889-0af98a7ff326 '' , `` roleNames '' : [ `` User '' ] } { `` userId '' : `` 0d5f97e4-65a0-43ad-b889-0af98a7ff326 '' , `` roleNames '' : [ `` Mod '' ] }",Ca n't remove users from specific role "C_sharp : This code works quite well in C # despite the fact that int can be implicitly converted to double and float : So , why this code wo n't compile ? ( The call is ambiguous between the following methods or properties : 'UserQuery.F ( double ) ' and 'UserQuery.F ( decimal ) ' ) All I did was replace the float variant of the function with a decimal variant . void Main ( ) { int x = 7 ; F ( x ) ; } void F ( double a ) { a.Dump ( `` double '' ) ; } void F ( float a ) { a.Dump ( `` float '' ) ; } void Main ( ) { int x = 7 ; F ( x ) ; } void F ( double a ) { a.Dump ( `` double '' ) ; } void F ( decimal a ) { a.Dump ( `` decimal '' ) ; }",C # The call is ambiguous between the following methods or properties : F ( double ) ' and ' F ( decimal ) ' "C_sharp : The requirements for my application are as follows . I need to store orders which look like this : Each order pertains to a specific stockcode ( string ) and has a price , volume and whether or not it is being bought or sold ( boolean ) associated with it.I need to do several operations on all orders that pertain to a specific stock , for example get the sum of the volume of orders for stockcode `` abc '' .I need to be able to add an order to the data structureI need to be able to remove an order from the data structureI need to be able to find out which order is offering the best price after an order is added or removed.Here is what I am thinking so far : And then I would store the orders in a Dictionary < string , List < Order > > . Where each stock code would be a key in the dictionary pointing to a list of orders for that stock . I would also maintain Dictionary matching an order id to a stock code.For adding a new order , I simply find the appropriate list of orders in the dictionary based on the current stock code , and insert the order . I would also add an entry in the orderstock dictionary matching the current order with the approrpriate list.For finding the best price , I look up the order list in the dictionary for the current stock code , sort the list and print out the highest order.Removing is tricky . I would first need to look up the appropriate list by stock code . I would then need to iterate through all the orders for that stock code and find the one that matches the current order id and remove it . This is obviously inefficient if there are a lot of orders for the current stock code . Is this the best way of storing this information ? public class Order : IComparable { private string _StockCode ; private bool _BidSide ; private int _Volume ; private decimal _Price ; private int _ExchangeOrderId ; public int CompareTo ( Order other ) { if ( _BidSide ! = other.BidSide ) { return _BidSide ? 1 : -1 ; } return decimal.Compare ( _Price , other.Price ) ; } }",What is the best C # Data Structure ( s ) For the Following Situation "C_sharp : I 'm building a .Net Core 3.1 console app and I want to use the build in console logging . There are a zillion articles on .net logging , but I have not been able to find a sample that actually does write in the console.It compiles and runs , and even writes `` Yup '' to the console , but the `` All done ! '' is not shown.Output in console window : This is my sample project structure : What am I missing ? It was a dispose of Services : Fix thanks to Jeremy Lakeman : namespace test { class Program { static void Main ( string [ ] args ) { var serviceProvider = new ServiceCollection ( ) .AddLogging ( config = > config.ClearProviders ( ) .AddConsole ( ) .SetMinimumLevel ( LogLevel.Trace ) ) .BuildServiceProvider ( ) ; //configure console logging serviceProvider .GetService < ILoggerFactory > ( ) ; var logger = serviceProvider.GetService < ILoggerFactory > ( ) .CreateLogger < Program > ( ) ; logger.LogDebug ( `` All done ! `` ) ; Console.Write ( `` Yup '' ) ; } } static void Main ( string [ ] args ) { using ( var serviceProvider = new ServiceCollection ( ) .AddLogging ( config = > config.ClearProviders ( ) .AddConsole ( ) .SetMinimumLevel ( LogLevel.Trace ) ) .BuildServiceProvider ( ) ) { //configure console logging serviceProvider .GetService < ILoggerFactory > ( ) ; var logger = serviceProvider.GetService < ILoggerFactory > ( ) .CreateLogger < Program > ( ) ; // run app logic logger.LogDebug ( `` All done ! `` ) ; } Console.Write ( `` Yup '' ) ; }",How to make console logger in .net core 3.1 console app work "C_sharp : General InformationI want to improve the performance of a program , issuing multiple HTTP requests to the same external API endpoint . Therefore , I have created a console application to perform some tests . The method GetPostAsync sends an asynchronous HTTP request to the external API and returns the result as a string.Additionally , I have implemented the methods below to test which one has the shortest execution time.Test ResultsUsing the integrated Stopwatch class , I have measured the execution time of the two methods and interestingly enough , the approach using Task.WhenAll performed way better than its counterpart : Issue 50 HTTP requestsTaskWhenAll : ~650msMultipleAwait : ~4500msWhy is the method using Task.WhenAll so much faster and are there any negative effects ( i.e exception handling , etc . ) when choosing this approach over the other ? private static async Task < string > GetPostAsync ( int id ) { var client = new HttpClient ( ) ; var response = await client.GetAsync ( $ '' https : //jsonplaceholder.typicode.com/posts/ { id } '' ) ; return await response.Content.ReadAsStringAsync ( ) ; } private static async Task TaskWhenAll ( IEnumerable < int > postIds ) { var tasks = postIds.Select ( GetPostAsync ) ; await Task.WhenAll ( tasks ) ; } private static async Task MultipleAwait ( IEnumerable < int > postIds ) { foreach ( var postId in postIds ) { await GetPostAsync ( postId ) ; } }",Performance of multiple awaits compared to Task.WhenAll "C_sharp : I 'm using AVAudioPlayer to play a sound when a user taps a row in a UITableView . If they tap the row again , the player stops and is disposed , and if they listen to the song until it 's finished then the FinshedPlaying handler disposes of the player . The problem I 'm having is that when I try to dispose of the player in the FinishedPlaying handler I get the error message : System.ObjectDisposedException : the player object was Dispose ( ) d during the callback , this has corrupted the state of the programHere 's the code , any idea what I 'm doing wrong ? void HandleOnRequestPlayMusic ( object sender , UrlEventArgs e ) { var url = Utils.UrlFromString ( e.Url ) ; string oldUrl = `` '' ; if ( musicPlayer ! = null ) { oldUrl = musicPlayer.Url.AbsoluteString ; KillAudioPlayer ( ) ; // no problems killing the audio player from here } if ( oldUrl ! = url.AbsoluteString ) { musicPlayer = AVAudioPlayer.FromUrl ( url ) ; musicPlayer.FinishedPlaying += HandleAudioFinished ; musicPlayer.Play ( ) ; } } void HandleAudioFinished ( object sender , AVStatusEventArgs e ) { KillAudioPlayer ( ) ; // killing audio player from here causes app to crash } void KillAudioPlayer ( ) { if ( musicPlayer ! = null ) { InvokeOnMainThread ( ( ) = > { musicPlayer.Stop ( ) ; musicPlayer.FinishedPlaying -= HandleAudioFinished ; musicPlayer.Dispose ( ) ; musicPlayer = null ; } ) ; } }",How do you dispose of AVAudioPlayer when FinishedPlaying event is invoked ? "C_sharp : I created a base class to help me reduce boilerplate code of the initialization of the immutable Objects in C # , I 'm using lazy initialization in order to try not to impact performance a lot , I was wondering how much am I affecting the performance by doing this ? This is my base class : Can be implemented like so : and can be used like this : public class ImmutableObject < T > { private readonly Func < IEnumerable < KeyValuePair < string , object > > > initContainer ; protected ImmutableObject ( ) { } protected ImmutableObject ( IEnumerable < KeyValuePair < string , object > > properties ) { var fields = GetType ( ) .GetFields ( ) .Where ( f= > f.IsPublic ) ; var fieldsAndValues = from fieldInfo in fields join keyValuePair in properties on fieldInfo.Name.ToLower ( ) equals keyValuePair.Key.ToLower ( ) select new { fieldInfo , keyValuePair.Value } ; fieldsAndValues.ToList ( ) .ForEach ( fv= > fv.fieldInfo.SetValue ( this , fv.Value ) ) ; } protected ImmutableObject ( Func < IEnumerable < KeyValuePair < string , object > > > init ) { initContainer = init ; } protected T setProperty ( string propertyName , object propertyValue , bool lazy = true ) { Func < IEnumerable < KeyValuePair < string , object > > > mergeFunc = delegate { var propertyDict = initContainer == null ? ObjectToDictonary ( ) : initContainer ( ) ; return propertyDict.Select ( p = > p.Key == propertyName ? new KeyValuePair < string , object > ( propertyName , propertyValue ) : p ) .ToList ( ) ; } ; var containerConstructor = typeof ( T ) .GetConstructors ( ) .First ( ce = > ce.GetParameters ( ) .Count ( ) == 1 & & ce.GetParameters ( ) [ 0 ] .ParameterType.Name == `` Func ` 1 '' ) ; return ( T ) ( lazy ? containerConstructor.Invoke ( new [ ] { mergeFunc } ) : DictonaryToObject < T > ( mergeFunc ( ) ) ) ; } private IEnumerable < KeyValuePair < string , object > > ObjectToDictonary ( ) { var fields = GetType ( ) .GetFields ( ) .Where ( f= > f.IsPublic ) ; return fields.Select ( f= > new KeyValuePair < string , object > ( f.Name , f.GetValue ( this ) ) ) .ToList ( ) ; } private static object DictonaryToObject < T > ( IEnumerable < KeyValuePair < string , object > > objectProperties ) { var mainConstructor = typeof ( T ) .GetConstructors ( ) .First ( c = > c.GetParameters ( ) .Count ( ) == 1 & & c.GetParameters ( ) .Any ( p = > p.ParameterType.Name == `` IEnumerable ` 1 '' ) ) ; return mainConstructor.Invoke ( new [ ] { objectProperties } ) ; } public T ToObject ( ) { var properties = initContainer == null ? ObjectToDictonary ( ) : initContainer ( ) ; return ( T ) DictonaryToObject < T > ( properties ) ; } } public class State : ImmutableObject < State > { public State ( ) { } public State ( IEnumerable < KeyValuePair < string , object > > properties ) : base ( properties ) { } public State ( Func < IEnumerable < KeyValuePair < string , object > > > func ) : base ( func ) { } public readonly int SomeInt ; public State someInt ( int someInt ) { return setProperty ( `` SomeInt '' , someInt ) ; } public readonly string SomeString ; public State someString ( string someString ) { return setProperty ( `` SomeString '' , someString ) ; } } //creating new empty objectvar state = new State ( ) ; // Set fields , will return an empty object with the `` chained methods '' .var s2 = state.someInt ( 3 ) .someString ( `` a string '' ) ; // Resolves all the `` chained methods '' and initialize the object setting all the fields by reflection.var s3 = s2.ToObject ( ) ;",Instantiating Immutable Objects With Reflection "C_sharp : I am loading MusicXML-files into my program . The problem : There are two “ dialects ” , timewise and partwise , which have different root-nodes ( and a different structure ) : andMy code for deserializing the partwise score so far is : What would be the best way to differentiate between the two dialects ? < ? xml version= '' 1.0 '' encoding='UTF-8 ' standalone='no ' ? > < ! DOCTYPE score-partwise PUBLIC `` -//Recordare//DTD MusicXML 2.0 Partwise//EN '' `` http : //www.musicxml.org/dtds/partwise.dtd '' > < score-partwise version= '' 2.0 '' > < work > ... < /work > ... < /score-partwise > < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' no '' ? > < ! DOCTYPE score-timewise PUBLIC `` -//Recordare//DTD MusicXML 2.0 Timewise//EN '' `` http : //www.musicxml.org/dtds/timewise.dtd '' > < score-timewise version= '' 2.0 '' > < work > ... < /work > ... < /score-timewise > using ( var fileStream = new FileStream ( openFileDialog.FileName , FileMode.Open ) ) { var xmlSerializer = new XmlSerializer ( typeof ( ScorePartwise ) ) ; var result = ( ScorePartwise ) xmlSerializer.Deserialize ( fileStream ) ; }",How do I differentiate types of XML files before deserializing ? "C_sharp : As I know , all operations in Akka.Net are asynchronous , and Context.Stop ( ) simply sends a Stop message to the actor . That means , actor will be alive for some time before it completely shuts down . And if I 'll call Context.Child ( ) right after Context.Stop ( ) with the name of the actor I just stopped , I will get the same actor . Here is the example codeMy application creates actors to process events from terminals . Each time new terminal connected , I create new actor by calling Context.Child ( ) using terminal name . When terminal disconnects , I stop the actor . Problem is that some times I receive Connect message right after Disconnect for same terminal , and as result I get actor that 's going be stopped . Is there any way to check that actor received Stop message and will be stopped soon ? var actor = context.Child ( actorName ) ; if ( actor.Equals ( ActorRefs.Nobody ) ) { actor = CreateNewActor ( ) ; } Context.Stop ( actor ) actor = context.Child ( actorName ) ; // what do we get here , same actor or ActorRefs.Nobody ?",Is there any way to wait for actor to be completely stopped ? "C_sharp : I have a simple C # /4.0 console app that reference Log4Net 1.2.13.0 in VS2010 . In debug mode the app compiles and runs fine on my machine . However , as soon as I change to 'Release ' I get the error `` Could not load file or assembly 'file : ///C : \Users\mike\Documents\Visual Studio 2010\Projects\xxxx\yyyyy\log4net.dll ' or one of its dependencies . Operation is not supported . '' In the AssemblyInfo.cs I have added the line : [ assembly : log4net.Config.XmlConfigurator ( Watch = true ) ] According to the configuration mgr , but Debug and Release are set to use platform x86 . This is also happening in another C # service application on my laptop , but I thought it easier if stick with getting it working here first.The app.config file contains a section for : Thanks in advanceMike < section name= '' log4net '' type= '' log4net.Config.Log4NetConfigurationSectionHandler , log4net '' / >",Console App with Log4Net compiles in Debug but not in Release mode "C_sharp : Is there a way to allow a list of tuples to deconstruct to a List < T > ? I get the following compile error with the following code sample : Can not implicitly convert type 'System.Collections.Generic.List < Deconstruct.Test > ' to 'System.Collections.Generic.List < ( int , int ) > ' using System ; using System.Collections.Generic ; namespace Deconstruct { class Test { public int A { get ; set ; } = 0 ; public int B { get ; set ; } = 0 ; public void Deconstruct ( out int a , out int b ) { a = this.A ; b = this.B ; } } class Program { static void Main ( string [ ] args ) { var test = new Test ( ) ; var ( a , b ) = test ; var testList = new List < Test > ( ) ; var tupleList = new List < ( int , int ) > ( ) ; tupleList = testList ; // ERROR HERE ... . } } }",Deconstruct with List < T > "C_sharp : There are similar questions around here but none that fit into my my particular case scenario.I have a Windows Form with a Button . The button is attached to the event handler as follows : In addition there is a combobox where a change in selection in supposed to trigger the button event handler as defined above.The code works exactly as intended at runtime but i get a dialog prompt at compile time which reads : object reference not set to an instance of an objectThere are no other errors or warning . A google search tells me that this message is an error caused if the program is trying to access a member of a reference type variable which is set to null.However when i run this code in debug mode , both the sender and event ( e ) variables are not null.So why is this dialog popping up ? And if this had been an error or warning - it should have shown as an error or warning but nothing of that sort happens . Here 's the screenshot : Edits : Answering Questions Raised in CommentsThere are no errors as you can see in the screenshot.The program works great - just this pop upThe popup is caused by the line : mybutton_Click ( sender , e ) ; in the combobox selectedIndexChanged function.The mybutton_Click ( sender , e ) does not use any of the arguments sender or e in the processing.I have not installed any VS extensions either . private void mybutton_Click ( object sender , EventArgs e ) { // do some processing here } private void mycombobox_SelectedIndexChanged ( object sender , EventArgs e ) { mybutton_Click ( sender , e ) ; // this is the line which pops up the dialog }",Object Reference Not Set "C_sharp : In several places in our code , we notice that if running under debugger it 'll show that there 's an unhandled exception in the code , however if running outside the debugger it will just ignore the exception completely as if it were caught . We have an exception handler that pops up an error submit dialog that 's hooked up to Application.ThreadException and AppDomain.CurrentDomain.UnhandledExceptionAnd neither of those appear to be catching them either . We also log our exceptions and nothing appears in the log.What are some possible reasons for this ? Edit : It seems that it is n't dependent on the type of exception throw , but rather where it is thrown . This was tested by just adding : It 'll show up under debugger but does n't show up outside , so in our case it 's not a ThreadAbortedException or anything that 's dependent on it being a specific type of exception . throw new Exception ( `` Test Exception '' ) ;",When can an exception in a .NET WinForms app just get eaten without being caught or bubbling up to a windows exception ? "C_sharp : I 'm using WindowChrome to restyle my window in an easy fast way but the problem is there is flickering when resizing the window , especially when resizing from left to right . When this part WindowChrome is removed everything goes back to normal . < Window x : Class= '' View.Settings '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' Height= '' 570 '' Width= '' 800 '' WindowStartupLocation= '' CenterOwner '' Background= '' { StaticResource DarkGrayBackground } '' ResizeMode= '' CanResize '' WindowStyle= '' SingleBorderWindow '' Title= '' Settings '' WindowState= '' Normal '' > < WindowChrome.WindowChrome > < WindowChrome CaptionHeight= '' 0 '' CornerRadius= '' 0 '' GlassFrameThickness= '' 1 '' UseAeroCaptionButtons= '' False '' ResizeBorderThickness= '' 5 '' NonClientFrameEdges= '' None '' / > < /WindowChrome.WindowChrome > < Border BorderBrush= '' Black '' BorderThickness= '' 1 '' > < DockPanel HorizontalAlignment= '' Stretch '' LastChildFill= '' True '' Margin= '' 0,0,0,0 '' VerticalAlignment= '' Stretch '' > < ! -- TitleBar -- > < Border DockPanel.Dock= '' Top '' BorderBrush= '' { StaticResource GrayBorder } '' BorderThickness= '' 0,0,0,1 '' > < Grid Height= '' 40 '' Background= '' { StaticResource WhiteBackground } '' > < DockPanel LastChildFill= '' False '' > < Image DockPanel.Dock= '' Left '' Margin= '' 0,0,5,0 '' > < /Image > < Label DockPanel.Dock= '' Left '' Content= '' { DynamicResource settings } '' Margin= '' 0,0,0,0 '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' > < /Label > < Button DockPanel.Dock= '' Right '' Style= '' { StaticResource CloseButton } '' x : Name= '' CloseBtn '' / > < /DockPanel > < /Grid > < /Border > < ! -- Left Menu -- > < Border DockPanel.Dock= '' Left '' Width= '' 180 '' Background= '' { StaticResource GrayBackground } '' BorderBrush= '' { StaticResource GrayBorder } '' BorderThickness= '' 0,0,1,0 '' > < DockPanel Margin= '' 0,40,0,0 '' Width= '' 180 '' LastChildFill= '' False '' > < Button DockPanel.Dock= '' Top '' Style= '' { StaticResource BigGrayButton } '' Content= '' { DynamicResource general } '' / > < /DockPanel > < /Border > < ! -- Bottom bar -- > < Border DockPanel.Dock= '' Bottom '' BorderBrush= '' { StaticResource GrayBorder } '' BorderThickness= '' 0,1,0,0 '' Height= '' 40 '' Background= '' { StaticResource WhiteBackground } '' > < DockPanel LastChildFill= '' False '' > < /DockPanel > < /Border > < ! -- Main Page -- > < ScrollViewer Background= '' { StaticResource DarkGrayBackground } '' IsTabStop= '' True '' HorizontalScrollBarVisibility= '' Auto '' VerticalScrollBarVisibility= '' Auto '' DockPanel.Dock= '' Top '' > < DockPanel LastChildFill= '' False '' Margin= '' 10,0,10,10 '' > < Label DockPanel.Dock= '' Top '' Height= '' 40 '' FontSize= '' 16 '' FontWeight= '' SemiBold '' VerticalContentAlignment= '' Center '' Content= '' { DynamicResource general } '' / > < Frame DockPanel.Dock= '' top '' x : Name= '' MainFrame '' > < /Frame > < /DockPanel > < /ScrollViewer > < /DockPanel > < /Border >",WPF WindowChrome causing flickering on resize "C_sharp : I 'm researching someone else 's code and there is a method like this : Why would someone use these attributes instead ofIs there any difference in the behavior , etc . ? public SomeClass DoSomething ( string param1 , [ Optional , DefaultParameterValue ( `` '' ) ] string optional ) public SomeClass DoSomething ( string param1 , string optional = `` '' )",What is the difference between OptionalAttribute and optional parameters in C # 4.0 "C_sharp : Sorry if the title is n't very clear , I could n't think of anything better ... I 'm receiving user input in the form of an IObservable < char > , and I 'd like to transform it to an IObservable < char [ ] > , by grouping the chars every time the user stops typing for more than 1 second . So , for instance , if the input is as follows : I 'd like the output observable to be : I suspect the solution is fairly simple , but I ca n't find the right approach ... I tried to use Buffer , GroupByUntil , Throttle and a few others , to no avail.Any idea would be welcome ! EDIT : I 've got something that almost works : But I need the delay to be reset every time a new character is typed ... hello ( pause ) world ( pause ) ! ( pause ) [ ' h ' , ' e ' , ' l ' , ' l ' , ' o ' ] [ ' w ' , ' o ' , ' r ' , ' l ' , 'd ' ] [ ' ! ' ] _input.Buffer ( ( ) = > _input.Delay ( TimeSpan.FromSeconds ( 1 ) ) ) .ObserveOnDispatcher ( ) .Subscribe ( OnCompleteInput ) ;","In Rx , how to group latest items after a period of time ?" "C_sharp : I want to read the performance NextValue ( ) 's of the `` ASP.NET '' performance counters category . However the counters of this category are always showing 0 , whereas other counters work as expected . The `` ASP.NET '' counters in perfmon.exe on the remote machine are working fine . The `` ASP.NET '' counters in perfmon.exe on my local machine targeting the remote machine also show 0 . Any ideas ? Permission or some kind of firewall issue ? var pc = new PerformanceCounter ( `` ASP.NET '' , `` Requests Current '' , `` '' , `` myRemoteMachine '' ) ; pc.NextValue ( ) ; // returns always 0pc.NextValue ( ) ; // returns always 0",ASP.NET Performance Counter always return 0 "C_sharp : I have an ELMAH custom ErrorLog that uses an EF Code-First context to store the errors : -The ErrorLog is wired up in the web.config : -I 'm already using Ninject elsewhere in the project . I 'd like to inject MyContext so that the ErrorLog is n't instantiating its own dependency , but I 'm not having any luck finding a hook in the documentation . ELMAH appears to be instantiating the ErrorLog internally , so the only option I seem to have is using a ServiceLocator inside my custom ErrorLog , which I 'd like to avoid if possible.Are there any better hooks available in ELMAH that I can use to inject ? class EntityFrameworkElmahErrorLog { public EntityFrameworkElmahErrorLog ( IDictionary config ) : this ( ) { } public override ErrorLogEntry GetError ( string id ) { using ( var context = new MyContext ( ) ) { var intId = Int64.Parse ( id , CultureInfo.InvariantCulture ) ; var item = context.ErrorLog.Single ( x = > x.Id == intId ) ; return new ErrorLogEntry ( this , id , ErrorXml.DecodeString ( item.Details ) ) ; } } // etc . } < errorLog type= '' MyProject.EntityFrameworkErrorLog , MyProject '' / >",How can I inject dependencies into an ELMAH custom ErrorLog ? "C_sharp : Consider the following code : Given that that the code calls the Close ( ) method , which closes the _client socket and sets it to null , while still inside the ` using ' block , what exactly happens behind the scenes ? Does the socket really get closed ? Are there side effects ? P.S . This is using C # 3.0 on the .NET MicroFramework , but I suppose the c # , the language , should function identically . The reason i am asking is that occasionally , very rarely , I run out of sockets ( which is a very precious resource on a .NET MF devices ) . // module level declarationSocket _client ; void ProcessSocket ( ) { _client = GetSocketFromSomewhere ( ) ; using ( _client ) { DoStuff ( ) ; // receive and send data Close ( ) ; } } void Close ( ) { _client.Close ( ) ; _client = null ; }",Dynamics of the using keyword "C_sharp : I 'm working on an application where the notion of Direction ( forwards/backwards ) is very important.The problem is that spread throughout the code base there are several different conventions : in some places it is true/false , and in others +1/-1.To try and bring this together , I created : I 'm now wondering if implicit conversions would be a good or bad idea : and whether there are classic gotchas which I am likely to encouter . public class DirectionClass { public bool Forwards { get ; set ; } public double Sign { get ; set ; } public EDirection { get ; set ; } //plus associated constructor overloads , implementing IEquatable , etc . } public static implicit operator DirectionClass ( double sign ) ; public static implicit operator DirectionClass ( bool forwards ) ; //etc..",Implicit operator - when is it a good/bad idea ? "C_sharp : I 'm new to c # so apologies if this is a noob question . I 'm trying to get clarity around the syntax or pattern for handling events in c # . So I have a Form object Form1 and a Button button1 in the form . I handle a Click event with a method like this in Form1.cs : which works fine . Now in another form Form2 I have a TreeView treeView1 , and I want to handle the BeforeExpand event . So I assumed it would be : which in fact does n't work : this method is never called when I expand a node . But several SO answers imply this is the way to do it , e.g this one.Anyway I found an alternative approach which does work for me . In the form constructor bind the event handler like this : So what 's the difference between these two approaches ? Why does n't the _event syntax work for a treeview ? Is there some difference between the event types ? Thanks private void button1_Click ( object sender , EventArgs e ) { Debug.WriteLine ( `` click ! `` ) ; } private void treeView1_BeforeExpand ( object sender , TreeViewCancelEventArgs e ) { Debug.WriteLine ( `` Hello ! `` ) ; } treeView1.BeforeExpand += new TreeViewCancelEventHandler ( anyMethodNameYouLike ) ;",Event handlers in c # - syntax/pattern "C_sharp : Is it possible to define the contents of a lambda expression ( delegate , Action , Func < > ) with Razor syntax , so that when this model method is executed in the view , it will insert that Razor content ? The intended purpose of this is for our developers to be able to define their own custom content to be inserted at a particular point in the CustomControl 's view.The following is stripped-down example code that mimics my current layout . The particular parts of focus are the RenderSideContent method definition and its executing call . Index.cshtml CustomControl.cshtml @ model My.PageModel @ My.CustomControl ( new CustomControlModel { AreaTitle = `` Details '' , RenderSideContent = ( ) = > { < div > @ using ( My.CustomWrapper ( `` General '' ) ) { My.BasicControl ( Model.Controls [ 0 ] ) } < /div > } } ) < div > @ Model.AreaTitle < div class= '' my-custom-content '' > @ Model.RenderSideContent ( ) < /div > < /div >",Is it possible for a lambda function to contain Razor syntax and be executed in a View ? "C_sharp : I really like using the foreach construct for `` for loops '' in C # . I think it 's very clean , efficient and readable . Is there a similar construct in TypeScript ? For example , instead of this : I 'd like to do this : setAuthorFilters ( selectedAuthors ) { selectedAuthors.forEach ( x = > this.setAuthorFilter ( x ) ) ; this.updateUrl ( ) ; } setAuthorFilter ( selectedAuthor ) { this.vm.SelectAuthors = this.vm.SelectAuthors.filter ( x = > x.id ! == selectedAuthor.id ) ; this.vm.PreviousSelectedAuthors = this.vm.CurrentSelectedAuthors.slice ( ) ; this.vm.CurrentSelectedAuthors.push ( selectedAuthor ) ; } setAuthorFilters ( selectedAuthors ) { foreach ( var selectedAuthor in selectedAuthors ) { this.vm.SelectAuthors = this.vm.SelectAuthors.filter ( x = > x.id ! == selectedAuthor.id ) ; this.vm.PreviousSelectedAuthors = this.vm.CurrentSelectedAuthors.slice ( ) ; this.vm.CurrentSelectedAuthors.push ( selectedAuthor ) ; } this.updateUrl ( ) ; }",Is there a foreach construct in TypeScript similar to the C # implementation ? "C_sharp : I 'm testing ASP.NET ( .NET 4 ) web-application under high load and have found that under some conditions HttpWebRequest.BeginGetResponse ( ) completes synchronously w/o throwing any exceptions.After running the following code in multiple ASP.NET threads under high-load I 've found `` WEBREQUEST COMPLETED SYNC ! '' message in logs.Pay attention that : In case thread pool capacity is reached an InvalidOperationException is thrownIn case error occurs during connection corresponding exception is thrownIn my case there are no exceptions ! I 've decompiled System.Net assembly and found that it is really possible under some conditions . But I did n't understand what these conditions mean ( System.Net.Connection.SubmitRequest ( HttpWebRequest request , bool forcedsubmit ) ) : When & why is this possible ? HttpWebRequest webRequest = ( HttpWebRequest ) WebRequest.Create ( url ) ; var result = webRequest.BeginGetResponse ( internalCallback , userState ) ; if ( result.CompletedSynchronously ) { Trace.Error ( `` WEBREQUEST COMPLETED SYNC ! `` ) ; } if ( this.m_Free & & this.m_WriteDone & & ! forcedsubmit & & ( this.m_WriteList.Count == 0 || request.Pipelined & & ! request.HasEntityBody & & ( this.m_CanPipeline & & this.m_Pipelining ) & & ! this.m_IsPipelinePaused ) ) { this.m_Free = false ; needReConnect = this.StartRequest ( request , true ) ; if ( needReConnect == TriState.Unspecified ) { flag = true ; this.PrepareCloseConnectionSocket ( ref returnResult ) ; this.Close ( 0 ) ; } }",Why HttpWebRequest.BeginGetResponse ( ) completes synchronously ? "C_sharp : Consider the following code : and here 's Order initialization in another class.Could you explain why it works ? As you see the Order has private set property , so I thought it would be impossible to set its value . public sealed class Order { public Order ( ) { Items = new List < OrderItem > ( ) ; } public List < OrderItem > Items { get ; private set ; } } public sealed class OrderItem { } var order = new Order { Items = { new OrderItem ( ) , new OrderItem ( ) } } ;",Why can I use a collection initializer with private set access from another class ? "C_sharp : When creating new objects in a LINQ statement , for example : With class A looking like this : And then modifying properties in A with a foreach loop : Why are the values not set when accessing the objects in the IEnumerable afterwards . E.g . the following assertion fails : I wonder why this happens . I would expect the foreach-statement to execute the query , and trigger the creation of the objects . MSDN documentation states : `` Execution of the query is deferred until the query variable is iterated over in a foreach or For Each loop '' .I have reproduced this behavior with .NET 4.5 and Mono 3.2.0 . Calling ToList on the IEnumerable before accessing the created object makes this problem go away . var list = new List < string > ( ) { `` a '' , `` b '' , `` c '' } ; var created = from i in list select new A ( ) ; class A { public string Label ; } foreach ( var c in created ) { c.Label = `` Set '' ; } Assert.AreEqual ( `` Set '' , created.ElementAt ( 2 ) .Label ) ;",Why is this LINQ query not executed when using foreach ? "C_sharp : What is the most idiomatic way with NUnit 2.6 to check equality of a property of an exception ? Code I 'd like to write but does not work : Expected 3 , but was < empty > I could use nested Assert expressions , but that seems overly complicated and unnecessary : edit In fact , the first code example does work . I do n't know why it did not work several times before posting this question Assert.That ( ( ) = > someObject.MethodThrows ( ) , Throws.TypeOf < SomeException > ( ) .With.Property ( `` Data '' ) .Count.EqualTo ( 3 ) , /* Data is a collection */ `` Exception expected '' ) ; Assert.AreEqual ( 3 , Assert.Throws < SomeException > ( ( ) = > someObject.MethodThrows ( ) , `` Exception expected '' ) .Data.Count ) ;",Check property of an exception with NUnit 2.6 "C_sharp : I have the following class : My question is : Can I check if Value is true , without == true ? The operator override works , but can I also use it like so ? Instead of ( this works , but normally I omit the == true in if statements.And how do I assign it to a value without use .Value = ? Thanks for you help : ) public class InterlockedBool { private int _value ; public bool Value { get { return _value > 0 ; } set { System.Threading.Interlocked.Exchange ( ref _value , value ? 1 : 0 ) ; } } public static bool operator == ( InterlockedBool obj1 , bool obj2 ) { return obj1.Value.Equals ( obj2 ) ; } public static bool operator ! = ( InterlockedBool obj1 , bool obj2 ) { return ! obj1.Value.Equals ( obj2 ) ; } public override bool Equals ( bool obj ) { return this.Value.Equals ( obj ) ; } } InterlockedBool ib = new InterlockedBool ( ) ; if ( ib ) { } if ( ib == true ) { }",If ( instance ) / implicit boolean conversion on a custom class "C_sharp : In C , in order to test if a pointer is null we can do : if ( p ! = NULL ) if ( p ! = 0 ) if ( p ) Why is n't there any equivalent in C # that would allow us to do the following ? instead of if ( object ) if ( object ! = null )",Why ca n't we do 'if ( object ) ' in C # to test if object is null ? "C_sharp : Here is my view in imageThe code is working fine , but ... When i submit the form , it only sends the value of first dropdownlist ( I checked on browser network received arguments ) , also when i view the page source it does n't show the generated options that I generated using ajax function.Here is my CodeAction that generate my first dropdownListAction that return json of second dropdownlist dataMy Ajax callMy ViewHTTPPost Action public ActionResult TwoDropDownList ( ) { HotelContext H = new HotelContext ( ) ; ViewBag.DropDownListOne = new SelectList ( H.Continent.ToList ( ) , `` Id '' , `` Name '' ) ; return View ( ) ; } [ HttpPost ] public JsonResult UpdateCountryDropDownList ( int ContinentId ) { HotelContext H = new HotelContext ( ) ; List < SelectListItem > CountryNames = new List < SelectListItem > ( ) ; List < Country > Co = H.Country.Where ( x = > x.ContinentId == ContinentId ) .ToList ( ) ; Co.ForEach ( x = > { CountryNames.Add ( new SelectListItem { Text = x.Name , Value = x.Id.ToString ( ) } ) ; } ) ; return Json ( CountryNames , JsonRequestBehavior.AllowGet ) ; } @ model Hotel.Models.Continent < script > $ ( document ) .ready ( function ( ) { $ ( `` # Name '' ) .change ( function ( ) { var ContinentoId = $ ( this ) .val ( ) ; $ .ajax ( { type : `` POST '' , dataType : `` json '' , data : { ContinentId : ContinentoId } , url : ' @ Url.Action ( `` UpdateCountryDropDownList '' , '' Home '' ) ' , success : function ( result ) { var Country = `` < select id='ddlCountry ' > '' ; Country = Country + ' < option value= '' '' > -- Select -- < /option > ' ; for ( var i = 0 ; i < result.length ; i++ ) { Country = Country + ' < option value= ' + result [ i ] .Value + ' > ' + result [ i ] .Text + ' < /option > ' ; } Country = Country + ' < /select > ' ; $ ( ' # Countries ' ) .html ( Country ) ; } , error : function ( xhr , ajaxOptions , thrownError ) { console.log ( arguments ) } } ) ; } ) ; } ) < /script > @ using ( Html.BeginForm ( ) ) { SelectList se = ViewBag.DropDownListOne ; @ Html.DropDownListFor ( x= > x.Name , se , '' -- Select -- '' ) < div id = '' Countries '' > @ Html.DropDownList ( `` ddlCountry '' , new List < SelectListItem > ( ) , '' -- Select -- '' ) < /div > < input type= '' submit '' value= '' submit '' style= '' margin-top:100px ; '' / > } [ HttpPost ] public string TwoDropDownList ( string Name , string ddlCountry ) { if ( string.IsNullOrEmpty ( Name ) || string.IsNullOrEmpty ( ddlCountry ) ) { return ( `` you must select Both '' ) ; } else return ( `` everything is working fine '' ) ; }","Problems Cascading dropdownlist , generated dropdown is n't posting selected value to server" "C_sharp : Here is a benchmark for methods return task , but run synchronizely under the hood.Output ( repeat 10,000/100,000/1000,000 times ) : Repeat 10,000 times , UsingTaskFromResult 10x faster than UsingAsyncModifier.Repeat 100,000 times , UsingTaskFromResult 2x faster than UsingAsyncModifier.Repeat 1,000,000 times , UsingAsyncModifier slightly faster than UsingTaskFromResult.What I think was , the async modifier just created an completed Task , something like Task.FromResult ( ) does . But the benchmark does not prove my idea.Why ? class MainClass { public static async Task < int > UsingAsyncModifier ( ) { return 10 ; } public static Task < int > UsingTaskCompletionSource ( ) { TaskCompletionSource < int > tcs = new TaskCompletionSource < int > ( ) ; tcs.SetResult ( 10 ) ; return tcs.Task ; } public static Task < int > UsingTaskFromResult ( ) { return Task.FromResult ( 10 ) ; } public static void Main ( string [ ] args ) { DateTime t = DateTime.Now ; const int repeat = 10000 ; // Results volatile while repeat grows . Console.WriteLine ( `` Repeat { 0 } times . `` , repeat ) ; int j = 0 ; for ( int i = 0 ; i < repeat ; i++ ) { j += UsingAsyncModifier ( ) .Result ; } Console.WriteLine ( `` UsingAsyncModifier : { 0 } '' , DateTime.Now - t ) ; t = DateTime.Now ; for ( int i = 0 ; i < repeat ; i++ ) { j += UsingTaskCompletionSource ( ) .Result ; } Console.WriteLine ( `` UsingTaskCompletionSource : { 0 } '' , DateTime.Now - t ) ; t = DateTime.Now ; for ( int i = 0 ; i < repeat ; i++ ) { j += UsingTaskFromResult ( ) .Result ; } Console.WriteLine ( `` UsingTaskFromResult : { 0 } '' , DateTime.Now - t ) ; } } Repeat 10000 times.UsingAsyncModifier : 00:00:00.1043980UsingTaskCompletionSource : 00:00:00.0095270UsingTaskFromResult : 00:00:00.0089460 Repeat 100000 times.UsingAsyncModifier : 00:00:00.1676000UsingTaskCompletionSource : 00:00:00.0872020UsingTaskFromResult : 00:00:00.0870180 Repeat 1000000 times.UsingAsyncModifier : 00:00:00.8458490UsingTaskCompletionSource : 00:00:00.8870980UsingTaskFromResult : 00:00:00.9027320",What is the overhead of an `` synchronized '' async method ? "C_sharp : Suppose I have an IEnumerable < T > , and I want to take the first element and pass the remaining elements to some other code . I can get the first n elements using Take ( n ) , but how can I then access the remaining elements without causing the enumeration to re-start ? For example , suppose I have a method ReadRecords that accepts the records in a CSV file as IEnumerable < string > . Now suppose that within that method , I want to read the first record ( the headers ) , and then pass the remaining records to a ReadDataRecords method that also takes IEnumerable < string > . Like this : If I were prepared to re-start the enumeration , then I could use dataRecords = records.Skip ( 1 ) . However , I do n't want to re-start it - indeed , it might not be re-startable . So , is there any way to take the first records , and then the remaining records ( other than by reading all the values into a new collection and re-enumerating them ) ? void ReadCsv ( IEnumerable < string > records ) { var headerRecord = records.Take ( 1 ) ; var dataRecords = ? ? ? ReadDataRecords ( dataRecords ) ; } void ReadDataRecords ( IEnumerable < string > records ) { // ... }","Can I take the first n elements from an enumeration , and then still use the rest of the enumeration ?" "C_sharp : I have two times in Ticks like so : Now as you can see comparing these two numbers tick1 == tick2 returns falsealthough the dates are the same ( apart from milliseconds ) .I would like to truncate the milliseconds off these numbers without converting it to a datetime ( because this would reduce efficiency ) I have looked at Math.Round which says : Rounds a value to the nearest integer or to the specified number of fractional digits.and also Math.Truncate neither of which I think do what I need.Looking at Datetime.Ticks it says : A single tick represents one hundred nanoseconds or one ten-millionth of a second . There are 10,000 ticks in a millisecond , or 10 million ticks in a second.Therefore I need to round the number down to the nearest ten million.Is this possible ? //2016-01-22​T17:34:52.648Zvar tick1 = 635890808926480754 ; //2016-01-22​T17:34:52.000Zvar tick2 = 635890808920000000 ;",How do I truncate milliseconds off `` Ticks '' without converting to datetime ? "C_sharp : I have a c # program which acts as client and many client program which is again a c # windows application connects to this c # server program to read data from sqlite database . To avoid lock issues when connecting multiple clients i have used below code , server gets hangs some times and need to restart the server program.Is it a good practce to make the return statement before finally ? Regardssangeetha System.Threading.Monitor.Enter ( Lock ) ; try { filter.Execute ( ) ; //get data from database Request.Clear ( ) ; return filter.XML ; //create xml and return to client } finally { System.Threading.Monitor.Exit ( Lock ) ; }",return statement before finally "C_sharp : Lets take this code : this function can be called from different threads . The goal is obviously to avoid fetching a page that is already scheduled for fetch . The filler object exposes an event that is subscribed via a lambda expression . My question is : can we say that the parameter npage is correctly handled in multithread scenario ? better : each event subscription receive its own npage parameter , or the last npage seen is propagate to all events ? public void Hit ( int npage ) { bool fetch = false ; lock ( pagesHit ) { if ( ! pagesHit.Contains ( npage ) ) { pagesHit.Add ( npage ) ; fetch = true ; } } if ( fetch ) { pageFiller.Completed += ( s , e ) = > { lock ( pagesHit ) { pagesHit.Remove ( npage ) ; } } ; } }","Lambda expression , outer variables in multithread" "C_sharp : I 'm currently reviewing/redoing code of a collegue of mine and stumbled upon a construct I 've never seen done before : With : Now as far as I understand it all but really severe errors can be captured this way ( 17+ class errors not as they will stay exceptions ) . Now what I get is that in some cases you could not want to have an exception thrown and catched , but instead want it as an info message ( or a flag set ) . In this case I see this as a useful construct.In the case of the code I 'm revieweing the errors is immediately checked after the sql command is executed and then an exception thrown with it as text.This got me to wonder if I 'm correctly seeing it that this negates the only advantage I could see of capturing the infomessage in the first place.So my question here is : what are the advantages of capturing the info messages of SQL connections ? Or with other words , is the one advantage I saw the only one or am I overlooking additional ones there ? con = new SqlConnection ( `` Data Source= ... .. '' ) ; con.FireInfoMessageEventOnUserErrors = true ; con.InfoMessage += new SqlInfoMessageEventHandler ( myInfoMessage ) ; void myInfoMessage ( object sender , SqlInfoMessageEventArgs e ) { foreach ( SqlError err in e.Errors ) { errors += err.LineNumber.ToString ( ) + `` : `` + err.Message + `` \r\n '' ; } }",What are advantages of capturing the Infomessages of SQL connections ? "C_sharp : I use the .NET 4 ( not .NET 4.5 or any other version of the framework ! ) Why different versions of Visual Studio will output different result of the same code using the SAME .NET Framework ? I have the followingIn Visual Studio 2013 the output is 10 20 30 40 50 ( Target .NET v == 4 ) .In Visual Studio 2010 the output is 50 50 50 50 50 ( Target .NET v == 4 ) .Where is the problem ? How to identify the C # ( not the .NET ! ) version used by each Studio for the .NET 4 C : \Windows\Microsoft.NET\Framework\v4.0.30319 > csc / ? Microsoft ( R ) Visual C # Compiler version 4.0.30319.33440 for Microsoft ( R ) .NET Framework 4.5 C : \Program Files ( x86 ) \Microsoft Visual Studio 10.0\VC > csc / ? Microsoft ( R ) Visual C # Compiler version 4.0.30319.33440 for Microsoft ( R ) .NET Framework 4.5 C : \Program Files ( x86 ) \Microsoft Visual Studio 12.0 > csc / ? Microsoft ( R ) Visual C # Compiler version 12.0.30110.0 for C # 5EDITCan I say that and this independently of the target framework of the concrete solution ? static void Main ( string [ ] args ) { var values = new List < int > ( ) { 1 , 2 , 3 , 4 , 5 } ; var funcs = new List < Func < int > > ( ) ; foreach ( var v in values ) { funcs.Add ( ( ) = > v * 10 ) ; } foreach ( var f in funcs ) { Console.WriteLine ( f ( ) ) ; } Console.ReadKey ( ) ; } VS 2010 == C # 4VS 2013 == C # 5",Why different versions of Visual Studio will output different result of the same code ? "C_sharp : I have a System.Windows.Forms.Listbox and a collection of tuple type values I 've created . That is , the new tuple type introduced in C # 7.0 . I 'm trying to bind the collection to the Listbox and set the DisplayMember to one of the elements in the tuple . Here 's an example : That does n't work , though . With the older-style Tuple < T > you could supposedly do what 's described in this answer : That does n't work either . Here 's what I 'm seeing in both cases : How can I accomplish this ? var l = new List < ( string name , int ID ) > ( ) { ( `` Bob '' , 1 ) , ( `` Mary '' , 2 ) , ( `` Beth '' , 3 ) } ; listBox1.DataSource = l ; listBox1.DisplayMember = `` name '' ; listBox1.DisplayMember = `` Item1 '' ; listBox1.ValueMember = `` Item3 '' ; // optional",How can I bind a collection of C # 7.0 tuple type values to a System.Windows.Forms.Listbox and set the display member to one of the elements ? "C_sharp : This is a simple question ( I hope ) , there are generic and non-generic methods in collection classes like List < T > that have methods such as Where and Where < T > .Example : Why use one over the other ( Generic or Non-Generic ) ? List < int > numbers = new List < int > ( ) { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 } ; IEnumerable < int > evens = numbers.Where ( ( x ) = > { return x % 2 == 0 ; } ) ; IEnumerable < int > evens2 = numbers.Where < int > ( ( x ) = > { return x % 2 == 0 ; } ) ;",C # List Generic Extension Method vs Non-Generic "C_sharp : I have made a WCF Service and it contains a method string SaveVideoInformation ( ) The purpose of this method is to run a process if it is not running.Following is the code of that method.The problem I am facing is when i call this method from Windows Form Tool Application , it run successfully and i can see the UI.but when i call this method from Windows Service , Process Starts but its UI is not visible . public string SaveVideoInformation ( string ID , string videoName ) { string Result = null ; try { Result = Insert ( ID , videoName ) ; Process [ ] pname = Process.GetProcessesByName ( `` AutoRunVideoWaterMarkingTook '' ) ; if ( pname.Length == 0 ) { Result += `` | Trying to run Process '' ; try { Process process = Process.Start ( @ '' ~\Debug\AutoRunVideoWaterMarkingTook.exe '' ) ; Result += `` | Process Ran Successfully '' ; } catch ( Exception ex ) { Result += `` | Exception While Running the process '' ; throw new Exception ( `` Unable to start Process ) ; } } else { Result += `` |Process Already Running '' ; } } catch ( Exception ex ) { Result = `` Not Done , '' + ex.Message ; } return Result ; }",UI of Process is not visible after Process.Start ( ) "C_sharp : Let 's suppose this very basic C # code : I have read that non fixed variables can be moved in memory by garbage collector.My question is : Is it possible that `` tab '' address change during my program execution ? I just want to understand.In fact , no matter if tab value change . var tab = new int [ 10 ] ;",Can C # GC move memory objects "C_sharp : I created a modified Pacman , but I want to add a firebolt shooting out from the mouth of the Pacman . My code is : How can I make a firebolt move in the direction the pacman is facing ? I have a form1 that when I press `` F '' it will fire a fireboltbut it cant seem to produce the firebolt image . Why is that ? namespace TestingPacman { class Firebolt { Bitmap firebolt0 = null ; Bitmap firebolt1 = null ; public Point fireboltposition ; int fireboltwidth = 0 ; int fireboltheight = 0 ; public Firebolt ( int x , int y ) { fireboltposition.X = x ; fireboltposition.Y = y ; if ( firebolt0 == null ) firebolt0 = new Bitmap ( `` firebolt0.gif '' ) ; if ( firebolt1 == null ) firebolt1 = new Bitmap ( `` firebolt1.gif '' ) ; int fireboltwidth = firebolt0.Width ; int fireboltheight = firebolt0.Height ; } public Rectangle GetFrame ( ) { Rectangle Labelrec = new Rectangle ( fireboltposition.X , fireboltposition.Y , fireboltwidth , fireboltheight ) ; return Labelrec ; } public void Draw ( Graphics g ) { Rectangle fireboltdecR = new Rectangle ( fireboltposition.X , fireboltposition.Y , fireboltwidth , fireboltheight ) ; Rectangle fireboltsecR = new Rectangle ( 0 , 0 , fireboltwidth , fireboltheight ) ; g.DrawImage ( firebolt0 , fireboltdecR , fireboltsecR , GraphicsUnit.Pixel ) ; } } namespace TestingPacman { public partial class Form1 : Form { // int inc = 0 ; Eater TheEater = new Eater ( 100,100 ) ; TimeDisplay time = new TimeDisplay ( ) ; int sec = 0 ; Score score = new Score ( ) ; int countofeaten=0 ; Random r = new Random ( ) ; private List < Label > redlabels = new List < Label > ( ) ; private List < Label > bluelabels = new List < Label > ( ) ; Firebolt firebolt ; List < Firebolt > listfirebolt = new List < Firebolt > ( ) ; private void Form1_Paint ( object sender , PaintEventArgs e ) { Graphics g = e.Graphics ; g.FillRectangle ( Brushes.White , 0 , 0 , this.ClientRectangle.Width , ClientRectangle.Height ) ; TheEater.Draw ( g ) ; foreach ( Firebolt f in listfirebolt ) f.Draw ( g ) ; } private void Form1_KeyDown ( object sender , KeyEventArgs e ) { timer1.Enabled = true ; string result = e.KeyData.ToString ( ) ; Invalidate ( TheEater.GetFrame ( ) ) ; switch ( result ) { case `` D1 '' : if ( TheEater.eaterwidth > = 9 & & TheEater.eaterheight > = 9 ) { TheEater.eaterwidth++ ; TheEater.eaterheight++ ; } break ; case `` F '' : listfirebolt.Add ( firebolt = new Firebolt ( TheEater.Position.X , TheEater.Position.Y ) ) ; Invalidate ( firebolt.GetFrame ( ) ) ; break ; case `` D2 '' : if ( TheEater.eaterwidth > 10 & & TheEater.eaterheight > 10 ) { TheEater.eaterwidth -- ; TheEater.eaterheight -- ; } break ; case `` D9 '' : TheEater.inc=TheEater.inc+2 ; break ; case `` D0 '' : TheEater.inc=TheEater.inc-2 ; break ; case `` Left '' : TheEater.MoveLeft ( ClientRectangle ) ; Invalidate ( TheEater.GetFrame ( ) ) ; break ; case `` Right '' : TheEater.MoveRight ( ClientRectangle ) ; Invalidate ( TheEater.GetFrame ( ) ) ; break ; case `` Up '' : TheEater.MoveUp ( ClientRectangle ) ; Invalidate ( TheEater.GetFrame ( ) ) ; break ; case `` Down '' : TheEater.MoveDown ( ClientRectangle ) ; Invalidate ( TheEater.GetFrame ( ) ) ; break ; default : break ; } RemoveifIntersected ( ) ; } label2.Text = score.Iskore.ToString ( ) ; } private void timer1_Tick ( object sender , EventArgs e ) { label1.Text = time.FormatTime ( sec++ ) ; } } }","i created a modified pacman , how to make him breath fire ?" "C_sharp : I 'm trying to figure out a way to automatically cast something to an Action or Func and the best I can come up with is something like this : There has to a better/easier way to do this , any thoughts ? [ TestFixture ] public class ExecutionTest { public void BadMethod ( ) { throw new Exception ( `` Something bad happened '' ) ; } [ Test ] public void TestBadMethod ( ) { // Want this , but it wo n't work ! ! // BadMethod.Execute ( ) .IgnoreExceptions ( ) ; // Ick ( ( Action ) BadMethod ) .Exec ( ) .IgnoreExceptions ( ) ; // Still ick ( ( Action ) BadMethod ) .IgnoreExceptions ( ) ; // Do not want ExtensionMethods.Exec ( BadMethod ) .IgnoreExceptions ( ) ; // Better but still meh this.Exec ( BadMethod ) .IgnoreExceptions ( ) ; } } public static class ExtensionMethods { public static Action Exec ( this Action action ) { return action ; } public static Action Exec ( this object obj , Action action ) { return action ; } public static void IgnoreExceptions ( this Action action ) { try { action ( ) ; } catch { } } }",Why ca n't I implicitly cast a Delegate with Extension methods ? "C_sharp : I have a WinForm application written in C # where I put a try-catch block in the Program.cs , in the program entry , the static void Main method , right in the beginning of the application like this : As you can see , the Application is put in a try-catch block and in the catch block , the only thing it does is to create an error log file.Now , so far so good . My application is running well and if I encounter a crash , the last Exception should be captured by the try-catch block and stored in the error log file . However , as I run my program for a while , I get an unhandled exception ( null reference ) . What surprise me is that the exception does not create an error log file.Now , this post shows that it is possibly caused by ThreadException or HandleProcessCorruptedStateExceptions ( the two most upvoted answers ) , but my case shows a simple null reference exception : Why would that be ? using System ; using System.IO ; using System.Windows.Forms ; namespace T5ShortestTime { static class Program { /// < summary > /// The main entry point for the application . /// < /summary > [ STAThread ] static void Main ( ) { try { Application.EnableVisualStyles ( ) ; Application.SetCompatibleTextRenderingDefault ( false ) ; Application.Run ( new T5ShortestTimeForm ( ) ) ; } catch ( Exception e ) { string errordir = Path.Combine ( Application.StartupPath , `` errorlog '' ) ; string errorlog = Path.Combine ( errordir , DateTime.Now.ToString ( `` yyyyMMdd_HHmmss_fff '' ) + `` .txt '' ) ; if ( ! Directory.Exists ( errordir ) ) Directory.CreateDirectory ( errordir ) ; File.WriteAllText ( errorlog , e.ToString ( ) ) ; } } } } Problem signature : Problem Event Name : CLR20r3 Problem Signature 01 : T5ShortestTime.exe Problem Signature 02 : 2.8.3.1 Problem Signature 03 : 5743e646 Problem Signature 04 : T5ShortestTime Problem Signature 05 : 2.8.3.1 Problem Signature 06 : 5743e646 Problem Signature 07 : 182 Problem Signature 08 : 1b Problem Signature 09 : System.NullReferenceException OS Version : 6.3.9600.2.0.0.272.7 Locale ID : 1033 Additional Information 1 : bb91 Additional Information 2 : bb91a371df830534902ec94577ebb4a3 Additional Information 3 : aba1 Additional Information 4 : aba1ed7202d796d19b974eec93d89ec2Read our privacy statement online : http : //go.microsoft.com/fwlink/ ? linkid=280262If the online privacy statement is not available , please read our privacy statement offline : C : \Windows\system32\en-US\erofflps.txt",Can C # WinForm static void Main NOT catching Exception ? "C_sharp : I am using the seed method to populate the database.Some of the objects have properties in cyrillic . Example : The objects are properly created in the database , however when I check the database in MS SQL management studio instead of the wine 's name being `` Шардоне '' , it is displayed as `` Øàðäîíå '' .Strangely , when I create the wine in my Startup class like this : everything is displayed properly in cyrillic in the database.Do you have an idea what may cause this ? context.Wines.AddOrUpdate ( new Wine ( ) { Id = 1 , Name = `` Шардоне '' , etc ... ... ... ... ... ... ... ... ... ... ... ... ... . var db = new WineSystemDbContext ( ) ; var ShardoneWine = new Wine { Name = `` Шардоне } ; db.Wines.Add ( ShardoneWine ) ;",Code First issue with seeding data in Cyrillic "C_sharp : I would like to be able to control the default code that 's generated for event 's when I use one of Visual Studio 's automatically generated blocks . The current template is as follows : I would like to change this to the following : Namely it 's the args argument that I always change.UPDATE : Further to this it is policy that we also include comments for private members here , thus another use-case for my requirement is to also generate the default comment.UPDATE 2 : I now retract the reasoning for wanting to rename e to args due to evidence of a non-standard naming convention , however I still would like to override the template if possible for explicit access modifier and default comments . void HandlerName ( object sender , HandlerEventArgs e ) { throw new NotImplementedException ( ) ; } private void HandlerName ( object sender , HandlerEventArgs args ) { throw new NotImplementedException ( ) ; }",Is it possible to alter the auto generated event handler code within visual studio ? "C_sharp : I have a query with many multi level includes : There are more includes than this . Of course , this causes EF Core 3.0 to generate many joins in the SQL query , which means it takes forever to execute ( 25+ seconds to retrieve 200 records ) . I have tried using the format .Include ( x = > x.LocalStats.StatType1 ) instead of Include and ThenInclude , but the results are the same.Is there any way of making this more efficient ? The docs suggest that : LINQ queries with an exceedingly high number of Include operators may need to be broken down into multiple separate LINQ queries in order to avoid the cartesian explosion problem.But I do n't see any explanation on how to actually accomplish this . var itemsToday = DatabaseContext.Items .Where ( f = > f.StartTime > DateTime.Today & & f.StartTime < DateTime.Today.AddDays ( 1 ) ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType1 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType2 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType3 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType4 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType5 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType6 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType7 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType8 ) .Include ( x = > x.LocalStats ) .ThenInclude ( x= > x.StatType9 ) .Include ( x = > x.LocalDetails ) ... .OrderBy ( f= > f.SomeOrderingCriterion ) ;",How to make multiple includes more efficient with EF Core 3.0 "C_sharp : I 've seen some guides or blogs that say using this to access a class 's own members is bad . However , I 've also seen some places where professionals are accessing with this . I tend to prefer explicitly using this , since it seems to make it clear that the thing I 'm accessing is part of the class.Is there some advantage or disadvantage to using this ? Is it simply a stylistic preference ? this.MyProperty = this.GetSomeValue ( ) ;","Should I use `` this '' to call class properties , members , or methods ?" "C_sharp : I have read several articles , tutorials and blog posts about the MVVM pattern . However there is one thing I do n't understand . Taking the three `` layers '' : ModelViewView ModelAs far as I have understood MVVM the model contains the `` raw '' data , e.g . a name and address in case of a Student class . The view model exposes properties to the view which represent data of the model.Example for a property in the view modelExample for the modelThis might sound a bit stupid but does n't this create a redundancy ? Why do I have to keep the name in the model and in the view model ? Why should one not handle the name on the view model completely ? public string Name { get { return model.Name ; } set { model.Name = value ; } } private string name ; public string Name { get { return name ; } set { name = value ; } }",What is the model in MVVM for ? "C_sharp : I have a class which has a property of the type SqlConnection . SqlConnection implements IDisposable . I have following questions : Should my class also implement IDisposable just because it has property of type IDisposable ? If yes , do I need to Dispose the property explicitly when I am disposing instance of my class ? E.g.Note : I know that there is a pattern to be followed while implementing IDisposable but my question is very specific to the case mentioned above . public class Helper : IDisposable { // Assume that it 's ANY OTHER IDisposable type . SqlConnection is just an example . public SqlConnection SqlConnection { get ; set ; } public void Dispose ( ) { if ( SqlConnection ! = null ) { SqlConnection.Dispose ( ) ; } } }","While disposing the class instance , do i need to dispose all its IDisposable members explicitly ?" "C_sharp : I have a couple of simple models . An PlaylistEntry model and a Playlist model which contains a collection of PlaylistEntry models.Playlist : PlaylistEntryWhen I add a PlaylistEntry to a Playlist in a detached state , I expect that when I attach and save changes , the changes to the PlaylistEntries list will also be saved . They do n't save and the list is empty.Here 's my code : That last ToList call returns the playlist I create but the PlaylistEntries collection on it is empty.Can anyone spot what I 'm doing wrong or suggest a different solution please ? I 've spent about 7 hours on this and ca n't for the life of me figure it out . public class Playlist { private ICollection < PlaylistEntry > playlistEntries ; public int PlaylistId { get ; set ; } public string Name { get ; set ; } public virtual ICollection < PlaylistEntry > PlaylistEntries { get = > this.playlistEntries ? ? ( this.playlistEntries = new HashSet < PlaylistEntry > ( ) ) ; set = > this.playlistEntries = value ; } } public class PlaylistEntry { [ DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] public int PlaylistEntryId { get ; set ; } public string FilePath { get ; set ; } [ ForeignKey ( `` Playlist '' ) ] public int PlaylistId { get ; set ; } [ Required ] public Playlist Playlist { get ; set ; } } var playlist = new Playlist { Name = `` My first playlist '' } ; using ( var context = new MusicPlayerContext ( stringBuilder ) ) { context.Playlists.Add ( playlist ) ; context.SaveChanges ( ) ; } playlist.PlaylistEntries.Add ( new PlaylistEntry { FilePath = `` lkdfj '' , PlaylistId = playlist.PlaylistId } ) ; using ( var context = new MusicPlayerContext ( stringBuilder ) ) { context.Playlists.Attach ( playlist ) ; context.Entry ( playlist ) .State = EntityState.Modified ; context.SaveChanges ( ) ; } using ( var context = new MusicPlayerContext ( stringBuilder ) ) { context.Playlists.Include ( x = > x.PlaylistEntries ) .ToList ( ) ; }",Collection in entity framework model is not updating "C_sharp : While bringing an application from .NET 3.5 to .NET 4.0 I 've run into this peculiar issue . ( culture is nl-BE ) I bind a TextBox like this ( in XAML ) to a DateTime value with an UpdateSourceTrigger on PropertyChanged ( LostFocus works as expected but as-you-type validation is required ) : Now when the contents of this textbox is ( for example ) 10/12/2000 and I want to edit it to be 09/03/1981 some obnoxious auto-correction occurs when i put the cursor at the end of 2000 and start 'backspacing ' away the year value ( when only the first digit ( ' 2 ' ) of '2000 ' is left the value automatically - including cursor jump - changes to 2002 again ) . Can I disable this auto-correction ? I ca n't seem to find what specifically introduced this behaviour . The same 'problem ' also occurs with FormatString=c for currency values.What I 've tried so far : Changing the FormatString to something more explicit like { 0 } { dd/MM/yyyy } ( same problem : starts auto-correcting when there are 2 digits for year left ) .Disabling the following snippet I 've added to my App.xaml.cs : The reasoning for this snippet to be included in the first place : have a look at this link.Am i missing something obvious here ? I ca n't reproduce this in 3.5 . Do I really have to roll my own ValueConverters for getting this to work properly ? That looks like a step back from StringFormat which was introduced in 3.5 sp 1.Output from DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns ( 'd ' ) does looks slightly different , nothing that would immediately explain the behaviour though ( probably unrelated ) : < TextBox Height= '' 23 '' Margin= '' 146,0,105,97.04 '' Name= '' txb_Geboortedatum '' VerticalAlignment= '' Bottom '' > < TextBox.Text > < Binding Path= '' Geboortedatum '' StringFormat= '' d '' UpdateSourceTrigger= '' PropertyChanged '' > < Binding.ValidationRules > < ExceptionValidationRule / > < /Binding.ValidationRules > < /Binding > < /TextBox.Text > < /TextBox > FrameworkElement.LanguageProperty.OverrideMetadata ( typeof ( FrameworkElement ) , new FrameworkPropertyMetadata ( XmlLanguage.GetLanguage ( CultureInfo.CurrentCulture.IetfLanguageTag ) ) ) ; .NET 3.5 .NET 4.0d/MM/yyyy d/MM/yyyyd/MM/yy d/MM/yydd-MM-yy dd-MM-yydd.MM.yy dd.MM.yyyyyy-MM-dd dd.MMM.yyyy yyyy-MM-dd",Auto correction behaviour on XAML bound datetime objects since .NET 4.0 ? "C_sharp : I 'm new in C # and trying to understand how to work with Lazy.I need to handle concurrent request by waiting the result of an already running operation . Requests for data may come in simultaneously with same/different credentials . For each unique set of credentials there can be at most one GetDataInternal call in progress , with the result from that one call returned to all queued waiters when it is readyIs that right way to use Lazy or my code is not safe ? Update : Is it good idea to start using MemoryCache instead of ConcurrentDictionary ? If yes , how to create a key value , because it 's a string inside MemoryCache.Default.AddOrGetExisting ( ) private readonly ConcurrentDictionary < Credential , Lazy < Data > > Cache= new ConcurrentDictionary < Credential , Lazy < Data > > ( ) ; public Data GetData ( Credential credential ) { // This instance will be thrown away if a cached // value with our `` credential '' key already exists . Lazy < Data > newLazy = new Lazy < Data > ( ( ) = > GetDataInternal ( credential ) , LazyThreadSafetyMode.ExecutionAndPublication ) ; Lazy < Data > lazy = Cache.GetOrAdd ( credential , newLazy ) ; bool added = ReferenceEquals ( newLazy , lazy ) ; // If true , we won the race . Data data ; try { // Wait for the GetDataInternal call to complete . data = lazy.Value ; } finally { // Only the thread which created the cache value // is allowed to remove it , to prevent races . if ( added ) { Cache.TryRemove ( credential , out lazy ) ; } } return data ; }",How to use Lazy to handle concurrent request ? "C_sharp : I am trying to determine if a user downloaded a file from FTP using MS Log Parser 2.2I have not been able to get parser SQL query going , although I have used several samples queries.Water Down Parser Query does not work : Error : Question : How do I create a query : Answers in C # are also welcomeVB.net Code : strSQL = `` SELECT date , COUNT ( * ) AS downloads , c-ip `` strSQL = strSQL & `` FROM C : \temp\Log\*.log `` strSQL = strSQL & `` WHERE cs-method='RETR ' `` strSQL = strSQL & `` GROUP BY date , c-ip `` RecordSet can not be used at this time [ Unknown Error ] - SELECT Date and Time of download - Where user = 'xxx ' - WHERE RETR = is a download - WHERE Filename = u_ex150709.log or xxx Dim rsLP As ILogRecordset = NothingDim rowLP As ILogRecord = NothingDim LogParser As LogQueryClassClass = NothingDim W3Clog As COMW3CInputContextClassClass = NothingDim UsedBW As Double = 0Dim Unitsprocessed As IntegerDim strSQL As String = NothingLogParser = New LogQueryClassClass ( ) W3Clog = New COMW3CInputContextClassClass ( ) TrystrSQL = `` SELECT date , COUNT ( * ) AS downloads , c-ip `` strSQL = strSQL & `` FROM C : \temp\Log\*.log `` strSQL = strSQL & `` WHERE cs-method='RETR ' `` strSQL = strSQL & `` GROUP BY date , c-ip `` 'run the query against W3C logrsLP = LogParser.Execute ( strSQL , W3Clog ) 'Error occurs in the line belowrowLP = rsLP.getRecord ( )",MS Log Parser 2.2 Query Error "C_sharp : ( Trying to find a title that sums up a problem can be a very daunting task ! ) I have the following classes with some overloaded methods that produce a call ambiguity compiler error : There are two very interesting things to note : Commenting out any of the implicit operator methods removes the ambiguity.Trying to rename the first method overload in VS will rename the first four calls in the Test ( ) method ! This naturally poses two questions : What it the logic behind the compiler error ( i.e . how did the compiler arrive to an ambiguity ) ? Is there anything wrong with this design ? Intuitively there should be no ambiguity and the offending call should be resolved in the first method overload ( OverloadedMethod ( MyClass l , MyClass r ) ) as MyDerivedClass is more closely related to MyClass rather than the castable but otherwise irrelevant MyCastableClass . Furthermore VS refactoring seems to agree with this intuition.EDIT : After playing around with VS refactoring , I saw that VS matches the offending method call with the first overload that is defined in code whichever that is . So if we interchange the two overloads VS matches the offending call to the one with the MyCastableClass parameter . The questions are still valid though . public class MyClass { public static void OverloadedMethod ( MyClass l ) { } public static void OverloadedMethod ( MyCastableClass l ) { } //Try commenting this out separately from the next implicit operator . //Comment out the resulting offending casts in Test ( ) as well . public static implicit operator MyCastableClass ( MyClass l ) { return new MyCastableClass ( ) ; } //Try commenting this out separately from the previous implicit operator . //Comment out the resulting offending casts in Test ( ) as well . public static implicit operator MyClass ( MyCastableClass l ) { return new MyClass ( ) ; } static void Test ( ) { MyDerivedClass derived = new MyDerivedClass ( ) ; MyClass class1 = new MyClass ( ) ; MyClass class2 = new MyDerivedClass ( ) ; MyClass class3 = new MyCastableClass ( ) ; MyCastableClass castableClass1 = new MyCastableClass ( ) ; MyCastableClass castableClass2 = new MyClass ( ) ; MyCastableClass castableClass3 = new MyDerivedClass ( ) ; OverloadedMethod ( derived ) ; //Ambiguous call between OverloadedMethod ( MyClass l ) and OverloadedMethod ( MyCastableClass l ) OverloadedMethod ( class1 ) ; OverloadedMethod ( class2 ) ; OverloadedMethod ( class3 ) ; OverloadedMethod ( castableClass1 ) ; OverloadedMethod ( castableClass2 ) ; OverloadedMethod ( castableClass3 ) ; } public class MyDerivedClass : MyClass { } public class MyCastableClass { }",Ambiguous call between overloads of two-way implicit castable types when a derived type of one is passed as parameter "C_sharp : I have a stock query application that returns data based upon a stock symbol.Basically , the AJAX call goes to ~/Stocks/GetStockData/ { id } where the { id } is the stock symbol.This works fine ... generally . Today I found that the stock `` Progressive Waste Solutions Ltd. '' , which has a symbol of BIN , blew up . Looking at the return data in the browser , I see it 's returning a 404 for this symbol.It occurred to me that BIN might be a reserved word , asking for some binary file or something . Is this the case ? How do I work around this without a whole lot of effort ? Are there other keywords that will also cause this problem ? UPDATEPer Artyom Neustroev , this could be a reserved keyword , and would be protected from routing to . He referenced an article which referenced a website which stated the way around this was to add the following configuration setting in the config file : ... which got me further . Upon running my site with this , the ajax call returned a 404.8 error : OK , this actually sorta makes sense . The routing was set to prevent someone from getting into my bin directory , and I approve of that sort of prevention.So I 'm wondering how to tell a particular group of methods that getting stuff like BIN , or CONFIG ( theoretically ) is ok if there is a defined route for it ? < configuration > < system.web > < httpRuntime relaxedUrlToFileSystemMapping= '' true '' / > < ! -- ... your other settings ... -- > < /system.web > < /configuration > HTTP Error 404.8 - Not FoundThe request filtering module is configured to deny a path in the URL that contains a hiddenSegment section .",ASP.NET MVC4 ... is `` BIN '' a reserved keyword ? "C_sharp : I have a class structure likeNow then , look at the noted line . If you remove : base ( ) then it will compile without an error . Why is this ? Is there a way to disable this behavior ? abstract class Animal { public Animal ( ) { //init stuff.. } } class Cat : Animal { public Cat ( bool is_keyboard ) : base ( ) //NOTE here { //other init stuff } }",Why is the base ( ) constructor not necessary ? "C_sharp : So , a pattern I use very often while working on my UWP app is to use a SemaphoreSlim instance to avoid race conditions ( I prefer not to use lock as it needs an additional target object , and it does n't lock asynchronously ) .A typical snippet would look like this : With the additional try/finally block around the whole thing , if the code in between could crash but I want to keep the semaphore working properly.To reduce the boilerplate , I tried to write a wrapper class that would have the same behavior ( including the try/finally bit ) with less code needed . I also did n't want to use a delegate , as that 'd create an object every time , and I just wanted to reduce my code without changing the way it worked.I came up with this class ( comments removed for brevity ) : And the way it works is that by using it you only need the following : One line shorter , and with try/finally built in ( using block ) , awesome . Now , I have no idea why this works , despite the discard operator being used.That discard _ was actually just out of curiosity , as I knew I should have just written var _ , since I needed that IDisposable object to be used at the end of the using block , and not discarder.But , to my surprise , the same IL is generated for both methods : The `` discarder '' IDisposable is stored in the field V_1 and correctly disposed.So , why does this happen ? The docs do n't say anything about the discard operator being used with the using block , and they just say the discard assignment is ignored completely.Thanks ! private readonly SemaphoreSlim Semaphore = new SemaphoreSlim ( 1 ) ; public async Task FooAsync ( ) { await Semaphore.WaitAsync ( ) ; // Do stuff here Semaphore.Release ( ) ; } public sealed class AsyncMutex { private readonly SemaphoreSlim Semaphore = new SemaphoreSlim ( 1 ) ; public async Task < IDisposable > Lock ( ) { await Semaphore.WaitAsync ( ) .ConfigureAwait ( false ) ; return new _Lock ( Semaphore ) ; } private sealed class _Lock : IDisposable { private readonly SemaphoreSlim Semaphore ; public _Lock ( SemaphoreSlim semaphore ) = > Semaphore = semaphore ; void IDisposable.Dispose ( ) = > Semaphore.Release ( ) ; } } private readonly AsyncMutex Mutex = new AsyncMutex ( ) ; public async Task FooAsync ( ) { using ( _ = await Mutex.Lock ( ) ) { // Do stuff here } } .method public hidebysig instance void T1 ( ) cil managed { .maxstack 1 .locals init ( [ 0 ] class System.Threading.Tasks.AsyncMutex mutex , [ 1 ] class System.IDisposable V_1 ) IL_0001 : newobj instance void System.Threading.Tasks.AsyncMutex : :.ctor ( ) IL_0006 : stloc.0 // mutex IL_0007 : ldloc.0 // mutex IL_0008 : callvirt instance class System.Threading.Tasks.Task ` 1 < class System.IDisposable > System.Threading.Tasks.AsyncMutex : :Lock ( ) IL_000d : callvirt instance ! 0/*class System.IDisposable*/ class System.Threading.Tasks.Task ` 1 < class System.IDisposable > : :get_Result ( ) IL_0012 : stloc.1 // V_1 .try { // Do stuff here.. IL_0025 : leave.s IL_0032 } finally { IL_0027 : ldloc.1 // V_1 IL_0028 : brfalse.s IL_0031 IL_002a : ldloc.1 // V_1 IL_002b : callvirt instance void System.IDisposable : :Dispose ( ) IL_0031 : endfinally } IL_0032 : ret }",Why does the C # 7 discard identifier _ still work in a using block ? "C_sharp : If I have a CryptoStream that I want to pass back to the user , the naïve approach would beI know that when I dispose the CryptoStream the underlying FileStream will also be disposed . The issue I am running in to is what do I do with rmCrypto and transform ? RijndaelManaged and ICryptoTransform are disposable classes , but disposing of the stream does not dispose those two objects.What is the correct way to handle this situation ? public Stream GetDecryptedFileStream ( string inputFile , byte [ ] key , byte [ ] iv ) { var fsCrypt = new FileStream ( inputFile , FileMode.Open , FileAccess.Read , FileShare.Read ) ; var rmCrypto = new RijndaelManaged ( ) ; var transform = rmCrypto.CreateDecryptor ( key , iv ) ; var cs = new CryptoStream ( fsCrypt , transform , CryptoStreamMode.Read ) ; return cs ; }",Can a CryptoStream be returned and still have everything dispose correctly ? "C_sharp : Given the followingHow can i create another expression that is a 'not ' of the existing one.i have triedbut this is not supported by the entity framework ... Regards Expression < Func < T , bool > > matchExpression ; Expression < Func < T , bool > > func3 = ( i ) = > ! matchExpression.Invoke ( i ) ;",how to 'not ' a lambda expression for entity framework "C_sharp : I wrote some code recently where I unintentionally reused a variable name as a parameter of an action declared within a function that already has a variable of the same name . For example : When I spotted the duplication , I was surprised to see that the code compiled and ran perfectly , which is not behavior I would expect based on what I know about scope in C # . Some quick Googling turned up SO questions that complain that similar code does produce an error , such as Lambda Scope Clarification . ( I pasted that sample code into my IDE to see if it would run , just to make sure ; it runs perfectly . ) Additionally , when I enter the Rename dialog in Visual Studio , the first x is highlighted as a name conflict.Why does this code work ? I 'm using C # 8 with Visual Studio 2019 . var x = 1 ; Action < int > myAction = ( x ) = > { Console.WriteLine ( x ) ; } ;",Why can I declare a child variable with the same name as a variable in the parent scope ? "C_sharp : EDITI tested release in 32 bit , and the code was compact . Therefore the below is a 64 bit issue.I 'm using VS 2012 RC . Debug is 32 bit , and Release is 64 bit . Below is the debug then release disassembly of a line of code : What is all the extra code in the 64 bit version doing ? It is testing for what ? I have n't benchmarked this , but the 32 bit code should execute much faster.EDITThe whole function : crc = ( crc > > 8 ) ^ crcTable [ ( ( val & 0x0000ff00 ) > > 8 ) ^ crc & 0xff ] ; 0000006f mov eax , dword ptr [ ebp-40h ] 00000072 shr eax,8 00000075 mov edx , dword ptr [ ebp-3Ch ] 00000078 mov ecx,0FF00h 0000007d and edx , ecx 0000007f shr edx,8 00000082 mov ecx , dword ptr [ ebp-40h ] 00000085 mov ebx,0FFh 0000008a and ecx , ebx 0000008c xor edx , ecx 0000008e mov ecx , dword ptr ds : [ 03387F38h ] 00000094 cmp edx , dword ptr [ ecx+4 ] 00000097 jb 0000009E 00000099 call 6F54F5EC 0000009e xor eax , dword ptr [ ecx+edx*4+8 ] 000000a2 mov dword ptr [ ebp-40h ] , eax -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - crc = ( crc > > 8 ) ^ crcTable [ ( ( val & 0x0000ff00 ) > > 8 ) ^ crc & 0xff ] ; 000000a5 mov eax , dword ptr [ rsp+20h ] 000000a9 shr eax,8 000000ac mov dword ptr [ rsp+38h ] , eax 000000b0 mov rdx,124DEE68h 000000ba mov rdx , qword ptr [ rdx ] 000000bd mov eax , dword ptr [ rsp+00000090h ] 000000c4 and eax,0FF00h 000000c9 shr eax,8 000000cc mov ecx , dword ptr [ rsp+20h ] 000000d0 and ecx,0FFh 000000d6 xor eax , ecx 000000d8 mov ecx , eax 000000da mov qword ptr [ rsp+40h ] , rdx 000000df mov rax , qword ptr [ rsp+40h ] 000000e4 mov rax , qword ptr [ rax+8 ] 000000e8 mov qword ptr [ rsp+48h ] , rcx 000000ed cmp qword ptr [ rsp+48h ] , rax 000000f2 jae 0000000000000100 000000f4 mov rax , qword ptr [ rsp+48h ] 000000f9 mov qword ptr [ rsp+48h ] , rax 000000fe jmp 0000000000000105 00000100 call 000000005FA5D364 00000105 mov rax , qword ptr [ rsp+40h ] 0000010a mov rcx , qword ptr [ rsp+48h ] 0000010f mov ecx , dword ptr [ rax+rcx*4+10h ] 00000113 mov eax , dword ptr [ rsp+38h ] 00000117 xor eax , ecx 00000119 mov dword ptr [ rsp+20h ] , eax public static uint CRC32 ( uint val ) { uint crc = 0xffffffff ; crc = ( crc > > 8 ) ^ crcTable [ ( val & 0x000000ff ) ^ crc & 0xff ] ; crc = ( crc > > 8 ) ^ crcTable [ ( ( val & 0x0000ff00 ) > > 8 ) ^ crc & 0xff ] ; crc = ( crc > > 8 ) ^ crcTable [ ( ( val & 0x00ff0000 ) > > 16 ) ^ crc & 0xff ] ; crc = ( crc > > 8 ) ^ crcTable [ ( val > > 24 ) ^ crc & 0xff ] ; // flip bits return ( crc ^ 0xffffffff ) ; }",Disassembly view of C # 64-bit Release code is 75 % longer than 32-bit Debug code ? "C_sharp : Anyone have any idea why this fails ? I was able to work around it with ParseExact , but I would like to understand why it is failing.Dates < `` Dec 24 '' work fine . Dates > = Dec 24 fail with this error : An unhandled exception of type 'System.FormatException ' occurred in mscorlib.dll Additional information : The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.EDIT : Thanks to Habib for noticing even when I did n't get an error it was not the result I was expecting . So be careful with the DateTime.Parse when not used with supported formats ! Here is what I did to fix the issue . I only have to handle two different formats . The current year would be `` MMM dd HH : mm '' otherwise it would be `` MMM dd yyyy '' DateTime test = DateTime.Parse ( `` Dec 24 17:45 '' ) ; if ( ! DateTime.TryParseExact ( inDateTime , `` MMM dd HH : mm '' , System.Globalization.CultureInfo.CurrentCulture , System.Globalization.DateTimeStyles.AllowWhiteSpaces , out outDateTime ) ) { if ( ! DateTime.TryParseExact ( inDateTime , `` MMM dd yyyy '' , System.Globalization.CultureInfo.CurrentCulture , System.Globalization.DateTimeStyles.AllowWhiteSpaces , out outDateTime ) ) { //Handle failure to Parse } }",C # DateTime.Parse Error "C_sharp : I 've got a one line method that resolves a null string to string.Empty which I thought might be useful as an extension method - but I ca n't find a useful way of making it so.The only way I could see it being useful is as a static method on the string class because obviously it ca n't be attributed to an instance as the instance is null and this causes a compiler error . [ Edit : Compiler error was due to uninitialized variable , which I misinterpreted ] I thought about adding it to a helper class but that just adds unnecessary complexity from a discoverability standpoint.So this question is in two parts I suppose : Does the .NET framework have a built in way of resolving a null string to string.Empty that is common knowledge that I have missed somewhere along the way ? If it does n't - does anyone know of a way to add this method as a static extension of the string class ? Cheers in advanceEdit : Okay , I guess I should 've been a little more clear - I 'm already well aware of null coallescing and I was using this in a place where I 've got a dozen or so strings being inspected for calculation of a hash code.As you can imagine , 12 lines of code closely following each other all containing the null coallescing syntax is an eyesore , so I moved the null coallescing operation out to a method to make things easier easier on the eyes . Which is perfect , however , it would be a perfect extension to the string object : over a dozen lines is a lot easier to read than : I was running into compiler problems when I did n't explicitly declare my string values as null but relied on the implicit : If however , you explicitly define : You can quite easily call : Thanks all for your input . int hashcode =FirstValue.ResolveNull ( ) .GetHashCode ( ) ^SecondValue.ResolveNull ( ) .GetHashCode ( ) ^ ... int hashcode = ( FirstValue ? ? String.Empty ) .GetHashCode ( ) ^ ( SecondValue ? ? String.Empty ) .GetHashCode ( ) ^ ... string s ; string s = null ; s.ResolveNull ( ) ;",Does .NET have a way of resolving a null string to String.Empty ? "C_sharp : I have numbers outputted from a FORTRAN program in the following format : How can I parse this as a double using C # ? I have tried the following without success : 0.12961924D+01 // note leading space , FORTRAN pads its output so that positive and negative// numbers are the same string lengthstring s = `` 0.12961924D+01 '' ; double v1 = Double.Parse ( s ) double v2 = Double.Parse ( s , NumberStyles.Float )",How to parse double in scientific format using C # "C_sharp : I have this methodAccording to the documentation I can find - and quite a lot of answers here - , it should start another program - SDCBackup.exe.It does n't . And I HAVE tried adding the .exe to the filename , but it does not make a difference . I get the messagebox with the message ... I have checked p and StartInfo and everything looks right . StartInfo.UseShellExecute is true.Debugging reveals , that it is the line p.Start ( ) ; that produces the exception . And the Exception is a System.ComponentModel.Win32Exception with message : File not foundDocumentation says , that the code above does the excat same thing as Run in Windows menu , but it obviously does not.If I write SDCBackup in the RUN section of Windows menu , SDCBackup.exe is started as it should . ( And SDCBackup.exe is a ClickOnce installation , that nobody really knows where to find - other than Windows itself ... ) So why does my code not do the trick ? private void StartSDCBackupSet ( ) { using ( Process p = new Process ( ) ) { p.StartInfo.FileName = `` SDCBackup '' ; try { p.Start ( ) ; BackIcon.ShowBalloonTip ( 5000 , `` Backup '' , `` Editor for settings startet '' , ToolTipIcon.Info ) ; } catch ( Exception ) { MessageBox.Show ( `` Program til settings blev ikke fundet '' ) ; } } }",C # Starting a program from another program "C_sharp : This is a WinForms C # application.The following two snippits show two different ways of initializing an object . They are giving different results.This works as expected : This does not work ( details below ) : Inside CameraWrapper I am using a third-party SDK to communicate with a camera . I register with an event on the SDK which is called when results are available . In case 1 ( initialization inside constructor ) , everything works as expected and the event handler inside CameraWrapper gets called . In case 2 , the event handler never gets called.I thought that these two styles of object initialization were identical , but it seems not to be the case . Why ? Here is the entire CameraWrapper class . The event handler should get called after a call to Trigger . public partial class Form1 : Form { private CameraWrapper cam ; public Form1 ( ) { cam = new CameraWrapper ( ) ; InitializeComponent ( ) ; } public partial class Form1 : Form { private CameraWrapper cam = new CameraWrapper ( ) ; public Form1 ( ) { InitializeComponent ( ) ; } class CameraWrapper { private Cognex.DataMan.SDK.DataManSystem ds ; public CameraWrapper ( ) { ds = new DataManSystem ( ) ; DataManConnectionParams connectionParams = new DataManConnectionParams ( `` 10.10.191.187 '' ) ; ds.Connect ( connectionParams ) ; ds.DmccResponseArrived += new DataManSystem.DmccResponseArrivedEventHandler ( ds_DmccResponseArrived ) ; } public void Trigger ( ) { SendCommand ( `` TRIGGER ON '' ) ; } void ds_DmccResponseArrived ( object sender , DmccResponseArrivedEventArgs e ) { System.Console.Write ( `` Num barcodes : `` ) ; System.Console.WriteLine ( e.Data.Length.ToString ( ) ) ; } void SendCommand ( string command ) { const string cmdHeader = `` || > '' ; ds.SendDmcc ( cmdHeader + command ) ; } }",Experiencing different behavior between object initialization in declaration vs. initialization in constructor "C_sharp : I am creating an authorization rule/policy for my ASP.NET 5 MVC application . Creating it was straightforward and pretty easy to do , and it is working ( with my basic tests ) . However , I now need to get my data context into the requirement.I created a constructor in my IAuthorizationRequirement implementation which takes a MyContext object which implements DbContext.I am registering the IAuthorizationRequirement like so in my Startup.cs file.Unfortunately , when my rule runs , MyContext is unaware of the connection strings which are used like so ( farther up in Startup.cs ) : I am using DI for these types otherwise ( and it is working ) .I know what I am doing is not right , but I do n't see how to make this right so that DI is being leveraged across everything . services.Configure < AuthorizationOptions > ( options = > { options.AddPolicy ( `` AllowProfileManagement '' , policy = > policy.Requirements.Add ( new AllowProfileManagementRequirement ( new MyRepository ( new MyContext ( ) ) ) ) ) ; } ) ; services.AddEntityFramework ( ) .AddSqlServer ( ) .AddDbContext < MemorialContext > ( options = > options.UseSqlServer ( Configuration [ `` Data : DefaultConnection : ConnectionString '' ] ) ) ; services.AddTransient < MyRepository > ( provider = > new MyRepository ( provider.GetRequiredService < MyContext > ( ) ) ) ;",Dependency Injection on AuthorizationOptions "C_sharp : I have a code example where a MatchCollection seems to hang the program when trying to use it with foreach.I am parsing css using a class CSSParser : and it works fine with input like this : but when I run it with a css string containing no attributes : the program is hanging on this line in CSSParser : The debugger stops marking the currently executing line , the loop block itself is never reached.Why is the MatchCollection hanging my program ? For completeness : using System ; using System.Collections.Generic ; using System.Linq ; using System.Text.RegularExpressions ; using Helpers.Extensions ; namespace Helpers.Utils { public class CSSParser { private readonly Dictionary < string , Dictionary < string , string > > _dict = new Dictionary < string , Dictionary < string , string > > ( ) ; private const string SelectorKey = `` selector '' ; private const string NameKey = `` name '' ; private const string ValueKey = `` value '' ; private const string GroupsPattern = @ '' ( ? < selector > ( ? : ( ? : [ ^ , { ] + ) \s* , ? \s* ) + ) \ { ( ? : ( ? < name > [ ^ } : ] + ) \s* : \s* ( ? < value > [ ^ } ; ] + ) ; ? \s* ) *\ } '' ; private const string CommentsPattern = @ '' ( ? < ! '' '' ) \/\*.+ ? \*\/ ( ? ! `` `` ) '' ; private readonly Regex _pattern = new Regex ( GroupsPattern , RegexOptions.IgnoreCase | RegexOptions.Multiline ) ; public CSSParser ( string cssString ) { var noCommentsString = Regex.Replace ( cssString , CommentsPattern , `` '' ) ; var matches = _pattern.Matches ( noCommentsString ) ; foreach ( Match item in matches ) { var selector = item.Groups [ SelectorKey ] .Captures [ 0 ] .Value.Trim ( ) ; var selectorParts = selector.Split ( ' , ' ) .Select ( s= > s.Trim ( ) ) ; foreach ( var part in selectorParts ) { if ( ! _dict.ContainsKey ( part ) ) _dict [ part ] = new Dictionary < string , string > ( ) ; } var classNameCaptures = item.Groups [ NameKey ] .Captures ; var valueCaptures = item.Groups [ ValueKey ] .Captures ; var count = item.Groups [ NameKey ] .Captures.Count ; for ( var i = 0 ; i < count ; i++ ) { var className = classNameCaptures [ i ] .Value.TrimIfNotNull ( ) ; var value = valueCaptures [ i ] .Value.TrimIfNotNull ( ) ; foreach ( var part in selectorParts ) { _dict [ part ] [ className ] = value ; } } } } public IEnumerable < KeyValuePair < string , string > > LookupValues ( string selector ) { IEnumerable < KeyValuePair < string , string > > result = new KeyValuePair < string , string > [ ] { } ; if ( _dict.ContainsKey ( selector ) ) { var subdict = _dict [ selector ] ; result = subdict.ToList ( ) ; } return result ; } public string LookupValue ( string selector , string style ) { string result = null ; if ( _dict.ContainsKey ( selector ) ) { var subdict = _dict [ selector ] ; if ( subdict.ContainsKey ( style ) ) result = subdict [ style ] ; } return result ; } } } [ TestMethod ] public void TestParseMultipleElementNames ( ) { const string css = @ '' h1 , h2 , h3 , h4 , h5 , h6 { font-family : Georgia , 'Times New Roman ' , serif ; color : # 006633 ; line-height : 1.2em ; font-weight : normal ; } '' ; var parser = new CSSParser ( css ) ; Assert.AreEqual ( `` normal '' , parser.LookupValue ( `` h4 '' , `` font-weight '' ) ) ; } [ TestMethod ] public void TestParseNoAttributesStyle ( ) { const string css = @ '' # submenu-container { } '' ; var parser = new CSSParser ( css ) ; Assert.IsFalse ( parser.LookupValues ( `` # submenu-container '' ) .Any ( ) ) ; } foreach ( Match item in matches ) namespace Helpers.Extensions { public static class StringExtension { public static string TrimIfNotNull ( this string input ) { return input ! = null ? input.Trim ( ) : null ; } } }",Can A MatchCollection hang the program when trying to iterate it ? "C_sharp : What I 'm trying to achieve is a self-compiled c # file without toxic output.I 'm trying to achieve this with Console.MoveBufferArea method but looks does not work.Eg . - save the code below with .bat extension : the output will be : What want is to rid of the // 2 > nul || .Is it possible ? Is there something wrong in my logic ( the ClearC method ) ? Do I need PInvoke ? // 2 > nul|| @ goto : batch/* : batch @ echo offsetlocal : : find csc.exeset `` frm= % SystemRoot % \Microsoft.NET\Framework\ '' for /f `` tokens=* delims= '' % % v in ( 'dir /b /a : d /o : -n `` % SystemRoot % \Microsoft.NET\Framework\v* '' ' ) do ( set netver= % % v goto : break_loop ) : break_loopset csc= % frm % % netver % \csc.exe : : csc.exe found % csc % /nologo /out : '' % ~n0.exe '' `` % ~dpsfnx0 '' % ~n0.exeendlocalexit /b 0*/public class Hello { public static void Main ( ) { ClearC ( ) ; System.Console.WriteLine ( `` Hello , C # World ! `` ) ; } private static void ClearC ( ) { System.Console.MoveBufferArea ( 0,0 , System.Console.BufferWidth , System.Console.BufferHeight-1 , 0,0 ) ; } } C : \ > // 2 > nul ||Hello , C # World !",Get the console buffer without the last line with C # ? C_sharp : I have a object in F # as follows ... I want to be able to create an instance of this object in a C # project . I have added as a reference the correct libraries to the project and can see the object via intellisense however I am not sure on the correct syntaxt to create an instance of the object . Currently I have the following in my C # project - which the compiler does n't like ... type Person ( ? name : string ) = let name = defaultArg name `` '' member x.Name = name var myObj1 = new Person ( `` mark '' ) ;,Create an object in C # from an F # object with optional arguments "C_sharp : I have three tables . Word - > WordForm - > SampleSentence . Each Word has different WordForms and then each form can have one or more SampleSentenceI am taking the data from these tables to a front-end client and this then modifies the data and adds or deletes WordForms and SampleSentences . I then bring the data back to the server . Is there some way that Entity Framework can check to see changes in the object that I bring back to the server and make changes to the database or do I have to do some form of comparison where I check the before and after of the Word , WordForm and Sample Sentence objects ? For reference here are the C # objects I 'm using : Here is what I have been able to come up with so far but this does not include checking for the SampleSentence and I am not sure how to do that : CREATE TABLE [ dbo ] . [ Word ] ( [ WordId ] VARCHAR ( 20 ) NOT NULL , [ CategoryId ] INT DEFAULT ( ( 1 ) ) NOT NULL , [ GroupId ] INT DEFAULT ( ( 1 ) ) NOT NULL , PRIMARY KEY CLUSTERED ( [ WordId ] ASC ) , CONSTRAINT [ FK_WordWordCategory ] FOREIGN KEY ( [ CategoryId ] ) REFERENCES [ dbo ] . [ WordCategory ] ( [ WordCategoryId ] ) , CONSTRAINT [ FK_WordWordGroup ] FOREIGN KEY ( [ GroupId ] ) REFERENCES [ dbo ] . [ WordGroup ] ( [ WordGroupId ] ) ) ; CREATE TABLE [ dbo ] . [ WordForm ] ( [ WordFormId ] VARCHAR ( 20 ) NOT NULL , [ WordId ] VARCHAR ( 20 ) NOT NULL , [ Primary ] BIT DEFAULT ( ( 0 ) ) NOT NULL , [ PosId ] INT NOT NULL , [ Definition ] VARCHAR ( MAX ) NULL , PRIMARY KEY CLUSTERED ( [ WordFormId ] ASC ) , CONSTRAINT [ FK_WordFormPos ] FOREIGN KEY ( [ PosId ] ) REFERENCES [ dbo ] . [ Pos ] ( [ PosId ] ) , CONSTRAINT [ FK_WordFormWord ] FOREIGN KEY ( [ WordId ] ) REFERENCES [ dbo ] . [ Word ] ( [ WordId ] ) ) ; CREATE TABLE [ dbo ] . [ SampleSentence ] ( [ SampleSentenceId ] INT IDENTITY ( 1 , 1 ) NOT NULL , [ WordFormId ] VARCHAR ( 20 ) NOT NULL , [ Text ] VARCHAR ( MAX ) NOT NULL , CONSTRAINT [ PK_SampleSentence ] PRIMARY KEY CLUSTERED ( [ SampleSentenceId ] ASC ) , CONSTRAINT [ FK_SampleSentenceWordForm ] FOREIGN KEY ( [ WordFormId ] ) REFERENCES [ dbo ] . [ WordForm ] ( [ WordFormId ] ) ) ; public class Word { public string WordId { get ; set ; } // WordId ( Primary key ) ( length : 20 ) public int CategoryId { get ; set ; } // CategoryId public int GroupId { get ; set ; } // GroupId // Reverse navigation public virtual System.Collections.Generic.ICollection < WordForm > WordForms { get ; set ; } // WordForm.FK_WordFormWord // Foreign keys public virtual WordCategory WordCategory { get ; set ; } // FK_WordWordCategory public virtual WordGroup WordGroup { get ; set ; } // FK_WordWordGroup public Word ( ) { CategoryId = 1 ; GroupId = 1 ; WordForms = new System.Collections.Generic.List < WordForm > ( ) ; } } public class WordForm { public string WordFormId { get ; set ; } // WordFormId ( Primary key ) ( length : 20 ) public string WordId { get ; set ; } // WordId ( length : 20 ) public bool Primary { get ; set ; } // Primary public int PosId { get ; set ; } // PosId public string Definition { get ; set ; } // Definition // Reverse navigation public virtual System.Collections.Generic.ICollection < SampleSentence > SampleSentences { get ; set ; } // SampleSentence.FK_SampleSentenceWordForm // Foreign keys public virtual Pos Pos { get ; set ; } // FK_WordFormPos public virtual Word Word { get ; set ; } // FK_WordFormWord public WordForm ( ) { Primary = false ; SampleSentences = new System.Collections.Generic.List < SampleSentence > ( ) ; } } public class SampleSentence : AuditableTable { public int SampleSentenceId { get ; set ; } // SampleSentenceId ( Primary key ) public string WordFormId { get ; set ; } // WordFormId ( length : 20 ) public string Text { get ; set ; } // Text // Foreign keys public virtual WordForm WordForm { get ; set ; } // FK_SampleSentenceWordForm } public async Task < IHttpActionResult > Put ( [ FromBody ] Word word ) { var oldObj = db.WordForms .Where ( w = > w.WordId == word.WordId ) .AsNoTracking ( ) .ToList ( ) ; var newObj = word.WordForms.ToList ( ) ; var upd = newObj.Where ( n = > oldObj.Any ( o = > ( o.WordFormId == n.WordFormId ) & & ( o.PosId ! = n.PosId || ! o.Definition.Equals ( n.Definition ) ) ) ) .ToList ( ) ; var add = newObj.Where ( n = > oldObj.All ( o = > o.WordFormId ! = n.WordFormId ) ) .ToList ( ) ; var del = oldObj.Where ( o = > newObj.All ( n = > n.WordFormId ! = o.WordFormId ) ) .ToList ( ) ; foreach ( var wordForm in upd ) { db.WordForms.Attach ( wordForm ) ; db.Entry ( wordForm ) .State = EntityState.Modified ; } foreach ( var wordForm in add ) { db.WordForms.Add ( wordForm ) ; } foreach ( var wordForm in del ) { db.WordForms.Attach ( wordForm ) ; db.WordForms.Remove ( wordForm ) ; } db.Words.Attach ( word ) ; db.Entry ( word ) .State = EntityState.Modified ; await db.SaveChangesAsync ( User , DateTime.UtcNow ) ; return Ok ( word ) ; }",Can I use Entity Framework Version 6 or 7 to update an object and its children automatically ? "C_sharp : I have this method : Now I want this method to also appear for IEnumerable < AnotherType > . So I wrote this which apparently doesn´t compile : I get the compiler-error : Member with the same signature already declaredI read Member with the same signature already defined with different type constraints which deals members with another return-type . However in my example I don´t distinguish on the methods return-type but on its param-list which is Func < MyType , TResult > in the first place and Func < IEnumerable < MyType > , TResult > in the second one . However the compiler can´t handle this.Is there another way than having another method-name for the second example ? public IEnumerable < MyType > DoSomething < TResult > ( Func < MyType , TResult > func ) where TResult : AnotherType public IEnumerable < MyType > DoSomething < TResult > ( Func < MyType , TResult > func ) where TResult : IEnumerable < AnotherType >",Can´t have two methods with same signature but different generic constraints "C_sharp : I ponder this question from time to time , so I thought I 'd ask you guys about it.Let 's say I have a database table that looks like this : This is just a table for ensuring referential integrity . It is basically an enum stored in the database for the purposes of ensuring that any Visiblity values that appear in other tables are always valid.Over in my front end , I have some choices.I could query this table and store it in , say , a Dictionary < string , int > or a Dictionary < int , string > .I could write an enum by hand and just manually edit the values in the rare event that there is a change to the table . E.g. , public enum Visiblity { Visible , Invisible , Collapsed } Something else ? ? ? ? Which would you advise and why ? Thanks . Table : VisibilityId Value -- -- -- - 0 Visible 1 Invisible 2 Collapsed",Syncing referential integrity tables and enums "C_sharp : The following works as expected ( LINQ to Entities ) : However , the following returns nothing : Topic.ParentId is a nullable int . It 's easy to work around , but this puzzles me . Can anyone shed any light ? var topics = ( from t in ctx.Topics where t.SubjectId == subjectId & & t.ParentId == null select new { t.Title , t.Id } ) .ToList ( ) ; int ? parent = null ; var topics = ( from t in ctx.Topics where t.SubjectId == subjectId & & t.ParentId == parent select new { t.Title , t.Id } ) .ToList ( ) ;",Nullable int not working as expected in LINQ ( C # ) "C_sharp : I 'm having a little difficulty getting Entity Framework 5 Enums to map to an integer column in a migration . Here 's what the code looks like : The migration looks like this : However when I save changes it does n't reflect them in the database.Database : [ Table ( `` UserProfile '' ) ] public class UserProfile { public enum StudentStatusType { Student = 1 , Graduate = 2 } [ Key ] public int UserId { get ; set ; } public string UserName { get ; set ; } public string FullName { get ; set ; } public StudentStatusType Status { get ; set ; } } public partial class EnumTest : DbMigration { public override void Up ( ) { AddColumn ( `` UserProfile '' , `` Status '' , c = > c.Int ( nullable : false , defaultValue:1 ) ) ; } public override void Down ( ) { DropColumn ( `` UserProfile '' , `` Status '' ) ; } } var user = new UserProfile ( ) ; user.Status = UserProfile.StudentStatusType.Graduate ; user.FullName = `` new '' ; user.UserName = `` new '' ; users.UserProfiles.Add ( user ) ; users.SaveChanges ( ) ; -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- |UserId | UserName | FullName | Status | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- |1 | new | new | 1 | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --",Incorrect value when saving enum "C_sharp : Recently i tested following program & i was expecting runtime error but it shows `` nan '' as output . Why & How ? I am using g++ compiler.Same way i also tried similar type of program in Java & C # & it shows again `` nan '' as output.I want to know that how floating point arithmetic is implemented & how it differes from integer arithmetic . Is it undefined behaviour in case of C++ ? If yes , why ? Please help me . # include < iostream > int main ( ) { float f=0.0f/0.0f ; std : :cout < < f ; return 0 ; } class Test { public static void main ( String args [ ] ) { float f=0.0f/0.0f ; System.out.println ( f ) ; } } class Test { public static void Main ( string [ ] args ) { float f=0.0f/0.0f ; Console.Write ( f ) ; } }",why 0.0f/0.0f does n't generate any runtime error ? C_sharp : I am using the Microsoft anti xss library and I noticed that for some reason it is removing the < ul > tag . I ca n't figure out why . For instance : This is returning : Any ideas ? string html = @ '' < ul > < li > this is a test < /li > < /ul > '' ; string sanitized = Sanitizer.GetSafeHtmlFragment ( html ) ; \r\n < li > this is a test < /li >,Anti XSS Library removing UL tag . Why ? "C_sharp : XML sample ( original link ) : I 'm wanting to get an instance of a class per record in the xml.i found similar examples in here but they only had a root , then one element deep . It works , right up until i put that other element in . i want to be able to do something like < records > < record index= '' 1 '' > < property name= '' Username '' > Sven < /property > < property name= '' Domain '' > infinity2 < /property > < property name= '' LastLogon '' > 12/15/2009 < /property > < /record > < record index= '' 2 '' > < property name= '' Username '' > Josephine < /property > < property name= '' Domain '' > infinity3 < /property > < property name= '' LastLogon '' > 01/02/2010 < /property > < /record > < record index= '' 3 '' > < property name= '' Username '' > Frankie < /property > < property name= '' Domain '' > wk-infinity9 < /property > < property name= '' LastLogon '' > 10/02/2009 < /property > < /record > < /records > foreach ( Record rec in myVar ) { Console.WriteLine ( `` ID : { 0 } User : { 1 } Domain : { 2 } LastLogon : { 3 } '' , rec.Index , rec.Username , rec.Domain , rec.LastLogon ) ; }",How do i get all `` properties '' from xml via linq to xml "C_sharp : I 'm trying to wrap my head around EF Cores owned objects and how i can control when to load certain chunks of data . Basically i 'm having a bunch of old legacy tables ( some with ~150 columns ) and want to model them using a root entity and several owned objects per table to achieve better segmentation and bundle certain functionalities . Example : There is an `` article '' entity containing ~20 properties for the most important fields of the underlying table . That entity also contains an OwnedObject `` StorageDetails '' wrapping a dozen more fields ( and all the functions concerned with storing stuff ) .Problem : I ca n't find a way to control if an owned object should be loaded immediatly or not . For some of them i would prefer to load them explicitly using Include ( ) ... Defining the model with OwnsOne and loading an article immediatly loads the StorageStuff . To load the OtherThing i have to Inlcude ( ) it in a query , which is basically what i want to achieve for the owned object . Is that possible ? If not , what other approach could you point me to ? public class Article : EntityBase { public string ArticleNumber { get ; set ; } // Owned object , shares article number as key . public StorageDetails StorageStuff { get ; set ; } // An Entity from another table having a foreign key reference public SomeOtherEntity OtherStuff { get ; set ; } } public class StorageDetails : OwnedObject < Article > { public Article Owner { get ; set ; } } // Somewhere during model creation ... builder.OwnsOne ( article = > article.StorageStuff ) ; builder.HasOne ( article = > article.OtherStuff ) ...",EFCore - How to exclude owned objects from automatic loading ? "C_sharp : I get a Exception type using so I change my code to catch that exception , and the code write only `` No '' .How can I catch the EntityException before reach Exception ? Thanks catch ( Exception e ) { log.Error ( e.GetType ( ) ) ; // it write 'System.Data.EntityException ' } try { ... } catch ( EntityException a ) { // need to do something log.Error ( `` I got it ! `` ) ; } catch ( Exception e ) { log.Error ( `` No '' ) ; }","C # , Catch Exception" C_sharp : 1 ) Why does the following codes differ.C # : Java:2 ) When migrating from one language to another what are the things we need to ensure for smooth transition . class Base { public void foo ( ) { System.Console.WriteLine ( `` base '' ) ; } } class Derived : Base { static void Main ( string [ ] args ) { Base b = new Base ( ) ; b.foo ( ) ; b = new Derived ( ) ; b.foo ( ) ; } public new void foo ( ) { System.Console.WriteLine ( `` derived '' ) ; } } class Base { public void foo ( ) { System.out.println ( `` Base '' ) ; } } class Derived extends Base { public void foo ( ) { System.out.println ( `` Derived '' ) ; } public static void main ( String [ ] s ) { Base b = new Base ( ) ; b.foo ( ) ; b = new Derived ( ) ; b.foo ( ) ; } },Why does Java and C # differ in oops ? "C_sharp : I was wondering what are the limitations of the background task called by a remote device . All I found in Microsoft 's documentation was the generic limitation of background task which is 30 seconds.But my simple test shows that it 's not the case for an app service called from another device . ( I 'm not sure about regular app services though . I did n't include them in my test ) Here 's my testing method : I put this code to OnBackgroundActivated of an app and registered a TimeTrigger background task . ( And I got deferral so task wo n't get closed unexpectedly because of await operations ) I got toast notifications for 20-25 seconds and nothing after that . So the process was killed before 30 seconds which is in line with the official documentation.Then I put the exact same code in RequestReceived event of my AppServiceConnection , and this code in OnBackgroundActivated ( which basically sets the RequestReceived event and gets the deferral : Then I created a connection and sent some data to this background task from another device ( using Rome APIs ) This time , it did n't stop before 30 seconds . My loop was 100 iterations , and I got toasts indicating that the background task did n't stop and was able to run ~500 seconds.But this was my loop , it might as well have continued even more with a longer loop.Is this the expected behavior ? What is the exact limitation of AppService background tasks called from a remote device ? Update : It seems that it 's necessary for the remote app ( who is calling this background task ) to stay opened . ( probably because the connection object should stay alive ? ) . If I close it , the background app service will be terminated after a few seconds . for ( int i = 0 ; i < 100 ; i++ ) { Common.ToastFunctions.SendToast ( ( i * 5 ) .ToString ( ) + `` seconds '' ) ; await System.Threading.Tasks.Task.Delay ( TimeSpan.FromSeconds ( 5 ) ) ; } this._backgroundTaskDeferral = args.TaskInstance.GetDeferral ( ) ; args.TaskInstance.Canceled += OnTaskCanceled ; var details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails ; if ( details ? .Name == `` com.ganjine '' ) //Remote Activation { _appServiceconnection = details.AppServiceConnection ; _appServiceconnection.RequestReceived += OnRequestReceived ; _appServiceconnection.ServiceClosed += AppServiceconnection_ServiceClosed ; }",Limitations of remote app service background task in UWP "C_sharp : I have an application that runs fine on .Net 2.0 SP2 , but fails to run properly on .NET 2.0 RTM . ( FYI : It fails when calling a method a managed DLL that is a wrapper for a native DLL for USB programming ) .I know you can give supported runtimes in the app.config of a C # .NET applicationHowever , is it also possible to specify a specific Service Pack version ? Thanks ! Edit : I did now find out which method fails between 2.0 and 2.0 SP2 . It is WaitHandle.WaitOne ( int ) which was added in 2.0 SP1 . A tip for everyone else having the problem , the compiler does n't say anything but if you ngen the executable with the problematic runtime , it does give you the exact error . E.g . : Rogier < startup > < supportedRuntime version= '' v2.0.5727 '' / > < supportedRuntime version= '' v4.0 '' / > < /startup > Warning : System.MissingMethodException : Method not found : 'Boolean System.Threading.WaitHandle.WaitOne ( Int32 ) ' . while resolving 0xa0000e1 - System.Threading.WaitHandle.WaitOne.11/11/2010 01:54:07 [ 3620 ] : Method not found : 'Boolean System.Threading.WaitHandle.WaitOne ( Int32 ) ' . while compiling method XXX",Is it possible to specify .NET service pack in `` supportedRuntime '' in app.config ? "C_sharp : Fairly new to raven . But just reading some of the documention ignorning a property seems pretty straight forward . But for some reason my property that I do not want save is being saved . Not sure why . Thanks for any help or guidance.This is property is created in a Entity project ( part of the solution of the web project ) I have no attributes on class btwNot sure what else to post , but this property is being saved . [ JsonIgnore ] public bool AllowedToEdit { get { return _allowedToEdit ; } set { _allowedToEdit = value ; } }",RavenDB storing property with JsonIgnore attribute "C_sharp : In the old days , we could conveniently initialize mutable collections using braces , as in the following example : Is there a similar syntax that can be used with BCL immutable collections ? I understand it is still a pre-release but maybe there is a recommended syntax , or at least this question will serve as feedback to implement these convenient initializers.In the mean time , the shortest I have found is the following : var myDictionary = new Dictionary < string , decimal > { { `` hello '' , 0m } , { `` world '' , 1m } } ; var myDictionary = new Dictionary < string , decimal > { { `` hello '' , 0m } , { `` world '' , 1m } } .ToImmutableDictionary ( ) ;",Can I initialize a BCL immutable collection using braces ? "C_sharp : I have the following code to perform a full-text search . It creates a query , gets the total number of rows returned by that query and then retrieves the actual rows for only the current page.This works fine , but it requires two round trips to the database . In the interest of optimizing the code , is there any way to rework this query so it only had one round trip to the database ? // Create IQueryablevar query = from a in ArticleServerContext.Set < Article > ( ) where a.Approved orderby a.UtcDate descending select a ; // Get total rows ( needed for pagination logic ) int totalRows = query.Count ( ) // Get rows for current pagequery = query.Skip ( ( CurrentPage - 1 ) * RowsPerPage ) .Take ( RowsPerPage ) ;",Performing two queries in a single round trip to the database C_sharp : The Shouldly assertion library for .NET somehow knows what expression the assertion method was called on so it is able to display it into the message . I tried to find out how it works but got lost in the source code . I suspect it looks into the compiled code but I would really like to see how this happens . From the documentationSomehow Shouldly knows the expression map.IndexOfValue ( `` boo '' ) and was able to display it in the test failure message . Does anyone know how this happens ? map.IndexOfValue ( `` boo '' ) .ShouldBe ( 2 ) ; // - > map.IndexOfValue ( `` boo '' ) should be 2 but was 1,How does the Shouldly assertion library know the expression the assertion was applied to ? "C_sharp : I have this code in my custom MembershipProvider : Resharper marks the second if-Statement and tells me , it would always evaluate to false.But why would this always evaluate to false ? I could easily pass null to the method as a parameter.Is this a bug or is Resharper right here ? PS 1 : I use Resharper 6.1PS 2 : I know using string.IsNullOrEmpty ( ) would be the way to go here anyway . I 'm just curious . public override void Initialize ( string name , System.Collections.Specialized.NameValueCollection config ) { if ( config == null ) throw new ArgumentNullException ( `` config '' ) ; if ( name == null ) name = `` MyCustomMembershipProvider '' ; ... }",Compare string to null - Why does Resharper think this is always false ? "C_sharp : I ca n't find any function that can help me with this and I do n't want to write crazy function that will HitTest every pixel of ListView area , to find out coords of needed Column ( if it ever possible to get Column from HitTest ) .Thanks to Yair Nevet comment , I wrote next function to determine Left position of needed Column : private int GetLeftOfColumn ( ColumnHeader column , ListView lv ) { if ( ! lv.Columns.Contains ( column ) ) return -1 ; int calculated_left = 0 ; for ( int i = 0 ; i < lv.Columns.Count ; i++ ) if ( lv.Columns [ i ] == column ) return calculated_left ; else calculated_left += lv.Columns [ i ] .Width + 1 ; return calculated_left ; }",Are there anyway to determine coordinates of Top-Left corner of Column in ListView ? "C_sharp : I 'm not understanding something about the way .Cast works . I have an explicit ( though implicit also fails ) cast defined which seems to work when I use it `` regularly '' , but not when I try to use .Cast . Why ? Here is some compilable code that demonstrates my problem . public class Class1 { public string prop1 { get ; set ; } public int prop2 { get ; set ; } public static explicit operator Class2 ( Class1 c1 ) { return new Class2 ( ) { prop1 = c1.prop1 , prop2 = c1.prop2 } ; } } public class Class2 { public string prop1 { get ; set ; } public int prop2 { get ; set ; } } void Main ( ) { Class1 [ ] c1 = new Class1 [ ] { new Class1 ( ) { prop1 = `` asdf '' , prop2 = 1 } } ; //works Class2 c2 = ( Class2 ) c1 [ 0 ] ; //does n't work : Compiles , but throws at run-time //InvalidCastException : Unable to cast object of type 'Class1 ' to type 'Class2 ' . Class2 c3 = c1.Cast < Class2 > ( ) .First ( ) ; }",IEnumerable.Cast not calling cast overload "C_sharp : I 'm creating a workflow tool that will be used on our company intranet . Users are authenticated using Windows Authentication and I 've set up a custom RoleProvider that maps each user to a pair of roles . One role indicates their seniority ( Guest , User , Senior User , Manager etc . ) and the other indicates their role/department ( Analytics , Development , Testing etc. ) . Users in Analytics are able to create a request that then flows up the chain to Development and so on : ModelsIn the controller I have a Create ( ) method that will create the Request header record and the first History item : Request ControllerEach further stage of the request will need to be handled by different users in the chain . A small subset of the process is : User creates Request [ Analytics , User ] Manager authorises Request [ Analytics , Manager ] Developer processes Request [ Development , User ] Currently I have a single CreateHistory ( ) method that handles each stage of the process . The status of the new History item is pulled up from the View : The CreateHistory View itself will render a different partial form depending on the Status . My intention was that I could use a single generic CreateHistory method for each of the stages in the process , using the Status as a reference to determine which partial View to render.Now , the problem comes in rendering and restricting available actions in the View . My CreateHistory View is becoming bloated with If statements to determine the availability of actions depending on the Request 's current Status : Making the right actions appear at the right time is the easy part , but it feels like a clumsy approach and I 'm not sure how I would manage permissions in this way . So my question is : Should I create a separate method for every stage of the process in the RequestController , even if this results in a lot of very similar methods ? An example would be : If so , how do I handle rendering the appropriate buttons in the View ? I only want a set of valid actions appear as controls.Sorry for the long post , any help would be greatly appreciated . public class Request { public int ID { get ; set ; } ... public virtual ICollection < History > History { get ; set ; } ... } public class History { public int ID { get ; set ; } ... public virtual Request Request { get ; set ; } public Status Status { get ; set ; } ... } public class RequestController : BaseController { [ HttpPost ] [ ValidateAntiForgeryToken ] public ActionResult Create ( RequestViewModel rvm ) { Request request = rvm.Request if ( ModelState.IsValid ) { ... History history = new History { Request = request , Status = Status.RequestCreated , ... } ; db.RequestHistories.Add ( history ) ; db.Requests.Add ( request ) ; ... } } } // GET : Requests/CreateHistorypublic ActionResult CreateHistory ( Status status ) { History history = new History ( ) ; history.Status = status ; return View ( history ) ; } // POST : Requests/CreateHistory [ HttpPost ] [ ValidateAntiForgeryToken ] public ActionResult CreateHistory ( int id , History history ) { if ( ModelState.IsValid ) { history.Request = db.Requests.Find ( id ) ; ... db.RequestHistories.Add ( history ) ; } } @ * Available user actions * @ < ul class= '' dropdown-menu '' role= '' menu '' > @ * Analyst has option to withdraw a request * @ < li > @ Html.ActionLink ( `` Withdraw '' , `` CreateHistory '' , new { id = Model.Change.ID , status = Status.Withdrawn } , null ) < /li > @ * Request manager approval if not already received * @ < li > ... < /li > @ * If user is in Development and the Request is authorised by Analytics Manager * @ < li > ... < /li > ... < /ul > public ActionResult RequestApproval ( int id ) { ... } [ MyAuthoriseAttribute ( Roles = `` Analytics , User '' ) ] [ HttpPost ] [ ValidateAntiForgeryToken ] public ActionResult RequestApproval ( int id , History history ) { ... } public ActionResult Approve ( int id ) { ... } [ MyAuthoriseAttribute ( Roles = `` Analytics , Manager '' ) ] [ HttpPost ] [ ValidateAntiForgeryToken ] public ActionResult Approve ( int id , History history ) { ... }",ASP MVC Workflow tool form logic and permissions "C_sharp : Why the C # 7 Compiler turns Local Functions into methods within the same class where their parent function is . While for Anonymous Methods ( and Lambda Expressions ) the compiler generates a nested class for each parent function , that will contain all of its Anonymous Methods as instance methods ? For example , C # code ( Anonymous Method ) : Will produce IL Code ( Anonymous Method ) similar to : While this , C # code ( Local Function ) : Will generate IL Code ( Local Function ) similar to : Note that DoIt function has turned into a static function in the same class as its parent function.Also the enclosed variable x has turned into a field in a nested struct ( not nested class as in the Anonymous Method example ) . internal class AnonymousMethod_Example { public void MyFunc ( string [ ] args ) { var x = 5 ; Action act = delegate ( ) { Console.WriteLine ( x ) ; } ; act ( ) ; } } .class private auto ansi beforefieldinit AnonymousMethod_Example { .class nested private auto ansi sealed beforefieldinit ' < > c__DisplayClass0_0 ' { .field public int32 x .method assembly hidebysig instance void ' < MyFunc > b__0 ' ( ) cil managed { ... AnonymousMethod_Example/ ' < > c__DisplayClass0_0 ' : :x call void [ mscorlib ] System.Console : :WriteLine ( int32 ) ... } ... } ... internal class LocalFunction_Example { public void MyFunc ( string [ ] args ) { var x = 5 ; void DoIt ( ) { Console.WriteLine ( x ) ; } ; DoIt ( ) ; } } .class private auto ansi beforefieldinit LocalFunction_Example { .class nested private auto ansi sealed beforefieldinit ' < > c__DisplayClass0_0 ' extends [ mscorlib ] System.ValueType { .field public int32 x } .method public hidebysig instance void MyFunc ( string [ ] args ) cil managed { ... ldc.i4.5 stfld int32 LocalFunction_Example/ ' < > c__DisplayClass1_0 ' : :x ... call void LocalFunction_Example : : ' < MyFunc > g__DoIt1_0 ' ( valuetype LocalFunction_Example/ ' < > c__DisplayClass1_0 ' & ) } .method assembly hidebysig static void ' < MyFunc > g__DoIt0_0 ' ( valuetype LocalFunction_Example/ ' < > c__DisplayClass0_0 ' & `` ) cil managed { ... LocalFunction_Example/ ' < > c__DisplayClass0_0 ' : :x call void [ mscorlib ] System.Console : :WriteLine ( int32 ) ... } }",Why Local Functions generate IL different from Anonymous Methods and Lambda Expressions ? "C_sharp : I 've read this question from Noseratio which shows a behaviour where TaskScheduler.Current is not the same after an awaitable has finished its operation.The answer states that : If there is no actual task being executed , then TaskScheduler.Current is the same as TaskScheduler.DefaultWhich is true . I already saw it here : TaskScheduler.Default Returns an instance of the ThreadPoolTaskScheduler TaskScheduler.Current If called from within an executing task will return the TaskScheduler of the currently executing task If called from any other place will return TaskScheduler.Default But then I thought , If so , Let 's do create an actual Task ( and not just Task.Yield ( ) ) and test it : First Messagebox is `` True '' , second is `` False '' Question : As you can see , I did created an actual task.I can understand why the first MessageBox yield True . Thats becuase of the : If called from within an executing task will return the TaskScheduler of the currently executing taskAnd that task does have ts which is the sent TaskScheduler.FromCurrentSynchronizationContext ( ) But why the context is not preserved at the second MessageBox ? To me , It was n't clear from Stephan 's answer.Additional information : If I write instead ( of the second messagebox ) : It does yield true . But why ? async void button1_Click_1 ( object sender , EventArgs e ) { var ts = TaskScheduler.FromCurrentSynchronizationContext ( ) ; await Task.Factory.StartNew ( async ( ) = > { MessageBox.Show ( ( TaskScheduler.Current == ts ) .ToString ( ) ) ; //True await new WebClient ( ) .DownloadStringTaskAsync ( `` http : //www.google.com '' ) ; MessageBox.Show ( ( TaskScheduler.Current == ts ) .ToString ( ) ) ; //False } , CancellationToken.None , TaskCreationOptions.None , ts ) .Unwrap ( ) ; } MessageBox.Show ( ( TaskScheduler.Current == TaskScheduler.Default ) .ToString ( ) ) ;",await does not resume context after async operation ? "C_sharp : i want to define a custom configuration section and have a property not yield a string but a system.type ( or null if the user types in a load of rubbish ) e.g . : in the C # ( in the current real world ) in the C # ( in an ideal world ) What I want is NOT to have to keep the item as a string in the C # and then convert that into a Type in the application ; i 'd like this to be done automatically as part of the responsibility of the ConfigurationManager.Is this possible ? I 'm OK to use a TypeConverter if I have to be , it just seems so weak to keep it as a string and then do the type lookup in the application . It 's not hard to do , just seems pointless when I know i 'm looking for a type , what is the value of having to explicitly do it . < myCustomConfig myAnnoyingType= '' System.String '' / > [ ConfigurationProperty ( `` myAnnoyingType '' ) ] public string MyAnnoyingType { get { return ( string ) this [ `` myAnnoyingType '' ] ; } } // else where in the appvar stringType = thatConfig.MyAnnoyingTypevar actualType = Type.GetType ( stringType ) ; // wow that was boring . [ ConfigurationProperty ( `` myAnnoyingType '' ) ] public Type MyAnnoyingType { get { return ( Type ) this [ `` myAnnoyingType '' ] ; } }",How do I get ConfigurationSection property as a System.Type "C_sharp : The MSDN page for UrlPathEncode states the UrlPathEncode should n't be used , and that I should use UrlEncode instead . Do not use ; intended only for browser compatibility . Use UrlEncode.But UrlEncode does not do the same thing as UrlPathEncode.My use case is that I want to encode a file system path so that a file can be downloaded . The spaces in a path need to be escaped , but not the forward slashes etc . UrlPathEncode does exactly this.Another method I 've tried is using Uri.EscapeDataString , but this escapes the slashes.Question : If I 'm not supposed to use UrlPathEncode , and UrlEncode does n't produce the required output , what method is equivalent and recommended ? // given the pathstring path = `` Directory/Path to escape.exe '' ; Console.WriteLine ( System.Web.HttpUtility.UrlPathEncode ( path ) ) ; // returns `` Installer/My % 20Installer.msi '' < - This is what I requireConsole.WriteLine ( System.Web.HttpUtility.UrlEncode ( path ) ) ; // returns `` Installer % 2fMy+Installer.msi '' // none of these return what I require , eitherConsole.WriteLine ( System.Web.HttpUtility.UrlEncode ( path , Encoding.ASCII ) ) ; Console.WriteLine ( System.Web.HttpUtility.UrlEncode ( path , Encoding.BigEndianUnicode ) ) ; Console.WriteLine ( System.Web.HttpUtility.UrlEncode ( path , Encoding.Default ) ) ; Console.WriteLine ( System.Web.HttpUtility.UrlEncode ( path , Encoding.UTF32 ) ) ; Console.WriteLine ( System.Web.HttpUtility.UrlEncode ( path , Encoding.UTF7 ) ) ; Console.WriteLine ( System.Web.HttpUtility.UrlEncode ( path , Encoding.UTF8 ) ) ; Console.WriteLine ( System.Web.HttpUtility.UrlEncode ( path , Encoding.Unicode ) ) ; // returns Directory % 2FPath % 20to % 20escape.exeConsole.WriteLine ( Uri.EscapeDataString ( path ) ) ;",UrlPathEncode ( ) alternative "C_sharp : I have the following cmdlet written in C # , it basically just throws an error : I 'm assuming ( I could be wrong ) , this is the equivalent in PowerShell ) The PowerShell version behaves as expected : The C # version however , crashes , with the following information : What am I doing wrong ? [ Cmdlet ( `` Use '' , `` Dummy '' ) ] public class UseDummyCmdlet : PSCmdlet { protected override void ProcessRecord ( ) { var errorRecord = new ErrorRecord ( new Exception ( `` Something Happened '' ) , `` SomethingHappened '' , ErrorCategory.CloseError , null ) ; ThrowTerminatingError ( errorRecord ) ; } } Function Use-Dummy ( ) { [ CmdletBinding ( ) ] Param ( ) process { $ errorRecord = New-Object System.Management.Automation.ErrorRecord -ArgumentList ( New-Object System.Exception ) , 'SomethingHappened ' , 'NotSpecified ' , $ null $ PSCmdlet.ThrowTerminatingError ( $ errorRecord ) } } Use-Dummy : Exception of type 'System.Exception ' was thrown.At line:1 char:10+ use-dummy < < < < + CategoryInfo : NotSpecified : ( : ) [ Use-Dummy ] , Exception + FullyQualifiedErrorId : SomethingHappened , Use-Dummy An exception of type 'System.Management.Automation.PipelineStoppedException ' occurred in System.Management.Automation.dll but was not handled in user codeAdditional information : The pipeline has been stopped .",How does ThrowTerminatingError work in C # ? "C_sharp : I have been looking at using in C # and I want to know if the following code is equivalent ; To this code ; using ( SqlConnection connection1 = new SqlConnection ( ) , connection2 = new SqlConnection ( ) ) { } using ( SqlConnection connection1 = new SqlConnection ( ) ) using ( SqlConnection connection2 = new SqlConnection ( ) ) { }",Different ways of using Using 's In C # "C_sharp : currently in c # 7 ( version 15.3.4 ) following code is valid to compile but both variables are legitimately unusable.If you try to use them , you get familiar error , variable might not be initialized before accessing.Some times in pattern matching you do n't care about exact type , as long as that type is in category that you want . here only apples and oranges as an example.Are there better approaches ? switch ( fruit ) { case Apple apple : case Orange orange : // impossible to use apple or orange break ; case Banana banana : break ; } List < Fruit > applesAndOranges = new List < Fruit > ( ) ; switch ( fruit ) { case Fruit X when X is Apple || X is Orange : applesAndOranges.Add ( X ) ; break ; case Banana banana : break ; }",Fall through in pattern matching "C_sharp : I am wondering if there is an easy way to turn a string like : 110811124209.197 into a datetime object where the format is yymmddhhmmss.sss . If was were using regular .net I would just use but it would seem that ParseExact is not apart DateTime in .net micro DateTime.ParseExact ( MyDateString , `` yyMMddHHmmtt.ttt '' ) ;",How to turn a string to a DateTime object in .NET Micro ? "C_sharp : Pressing a key in a text box , the KeyDown event occurs before KeyPress.I used a count and message boxes to see what would happen . The following is my code : When a key is pressed , this will show first ... ... followed by this : Should n't the KeyDown message box ( with NCount 1 ) show before the KeyPress message box ( with Ncount 2 ) ? int Ncount = 0 ; private void Textbox_KeyDown ( object sender , KeyEventArgs e ) { Ncount += 1 ; MessageBox.Show ( `` KeyDown 's Ncount : `` + Ncount.ToString ( ) ) ; } private void Textbox_KeyPress ( object sender , KeyPressEventArgs e ) { Ncount += 1 ; MessageBox.Show ( `` KeyPress 's Ncount : `` + Ncount.ToString ( ) ) ; } KeyPress 's Ncount : 2 KeyDown 's Ncount : 1",Why does KeyPress 's message box show before KeyDown 's ? "C_sharp : I fail to find documentation addressing this issue . ( perhaps I am just bad at using google ... ) My guess is that the answer is negative , however I did n't understand where this is addressed in the documentation . To be precise my question is the following.Suppose , I want to execute something like this : I understand that I can achieve the desired behavior by using the regular switch or if/else , however I was curious whether it is possible to use switch expression in this case . DirectoryInfo someDir = new DirectoryInfo ( @ '' .\someDir '' ) ; Console.WriteLine ( $ '' Would you like to delete the directory { someDir.FullName } ? `` ) ; string response = Console.ReadLine ( ) .ToLower ( ) ; response switch { `` yes '' = > { someDir.Delete ( ) ; ... MoreActions } , _ = > DoNothing ( ) } ;",Using blocks in C # switch expression ? "C_sharp : I 'm using .net Core 2.1 Web API . I 'm using action based authentication . So , I add every method [ Authorize ( Policy = `` ... .. '' ) ] like below . But , I do n't want write every time . I want taking policy name from method name automatically . How can I achieve this ? namespace University.API.Controllers { [ Route ( `` api/ [ controller ] '' ) ] [ ApiController ] public class UniversityController : ControllerBase { private readonly IUniversityService universityService ; public UniversityController ( IUniversityService universityService ) { this.universityService = universityService ; } [ Authorize ( Policy = `` GetUniversities '' ) ] [ HttpGet ( `` GetUniversities '' ) ] public async Task < ServiceResult > GetUniversities ( ) { return await universityService.GetUniversities ( ) ; } [ Authorize ( Policy = `` GetStudents '' ) ] [ HttpGet ( `` GetStudents '' ) ] public async Task < ServiceResult > GetStudents ( ) { return await universityService.GetStudents ( ) ; } [ Authorize ( Policy = `` DeleteUniversity '' ) ] [ HttpGet ( `` DeleteUniversity '' ) ] public async Task < ServiceResult > DeleteUniversity ( int universityId ) { return await universityService.DeleteUniversity ( universityId ) ; } } }",Adding policy attribute automatically in .net core web API "C_sharp : Trying to reduce repetition in my code by making a generic GET method . I am using OrmLite and its SQLExpressionVisitor update ... The goal is to pass in a lambda . I have seen a few other posts that I hoped would help but so far , no go ... It is clear the problem is how I am trying to get the criteria evaluated in the ev.Where statement , but the solution is escaping me ... Thanks in advance ... -LennyThis is the error I get ... variable ' x ' of type 'TW.Api.Models.CostCenter ' referenced from scope `` , but it is not definedHere is an example of code that works but is not generic ... .This is the model I referenced above ... for all reading this , here is the final code ... public IQueryable < T > Get < T > ( Predicate < T > criteria ) { using ( IDbConnection db = dbConnectionFactory.OpenDbConnection ( ) ) { SqlExpressionVisitor < T > ev = OrmLiteConfig.DialectProvider.ExpressionVisitor < T > ( ) ; ev.Where ( x = > criteria.Invoke ( x ) ) return db.Select ( ev ) .AsQueryable ( ) ; } } public IQueryable < CostCenter > Get ( Identity user ) { using ( IDbConnection db = dbConnectionFactory.OpenDbConnection ( ) ) { SqlExpressionVisitor < CostCenter > ev = OrmLiteConfig.DialectProvider.ExpressionVisitor < CostCenter > ( ) ; ev.Where ( x = > x.OrgId == user.OrgId ) ; ev.Where ( x = > x.VisibilityStockpointId == user.StockpointId ) ; `` return db.Select ( ev ) .AsQueryable ( ) ; } } [ Alias ( `` CostCenterDetail '' ) ] public class CostCenter { public Guid Id { get ; set ; } public Guid StockpointId { get ; set ; } public virtual Guid ? VisibilityStockpointId { get ; set ; } public string Description { get ; set ; } public string Number { get ; set ; } public string OrgId { get ; set ; } } public IQueryable < T > Get < T > ( Expression < Func < T , bool > > criteria ) { using ( IDbConnection db = dbConnectionFactory.OpenDbConnection ( ) ) { return db.Select ( criteria ) .AsQueryable ( ) ; } }",Generic Query Method "C_sharp : Given is a wcf rest service which runs with HttpClientCredentialType.Windows and enforces a user to authenticate via kerberos . When i run this as a console application , and then open the website http : //notebook50:87/test/ in internet explorer from another computer , i get a 'bad request ' response . I did enable kerberos logging , and it shows me KDC_ERR_PREAUTH_REQUIREDI can solve this problem by creating a windows service , and run it under 'Local System account ' . In this case , a client is able to authenticate . Question : What permission/settings does a user ( which runs this wcf service ) need in order to get the same behavior as when the application is running as windows service under local system ? Is this related with the Service Principle Name ? private static void Main ( string [ ] args ) { Type serviceType = typeof ( AuthService ) ; ServiceHost serviceHost = new ServiceHost ( serviceType ) ; WebHttpBinding binding = new WebHttpBinding ( ) ; binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly ; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows ; ServiceEndpoint basicServiceEndPoint = serviceHost.AddServiceEndpoint ( typeof ( IAuthService ) , binding , `` http : //notebook50:87 '' ) ; basicServiceEndPoint.Behaviors.Add ( new WebHttpBehavior ( ) ) ; Console.WriteLine ( `` wcf service started '' ) ; serviceHost.Open ( ) ; Console.ReadLine ( ) ; } public class AuthService : IAuthService { public List < string > GetUserInformation ( ) { List < string > userInfo = new List < string > ( ) ; userInfo.Add ( `` Environment.User = `` + Environment.UserName ) ; userInfo.Add ( `` Environment.UserDomain = `` + Environment.UserDomainName ) ; if ( OperationContext.Current ! = null & & OperationContext.Current.ServiceSecurityContext ! = null ) { userInfo.Add ( `` WindowsIdentity = `` + OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name ) ; userInfo.Add ( `` Auth protocol = `` + OperationContext.Current.ServiceSecurityContext.WindowsIdentity.AuthenticationType ) ; } else { userInfo.Add ( `` WindowsIdentity = empty '' ) ; } WebOperationContext.Current.OutgoingResponse.ContentType = `` text/plain '' ; return userInfo ; } } [ ServiceContract ] public interface IAuthService { [ OperationContract ] [ WebInvoke ( Method = `` GET '' , ResponseFormat = WebMessageFormat.Json , UriTemplate = `` test/ '' ) ] List < string > GetUserInformation ( ) ; }",WCF Rest service Windows authentication via Browser "C_sharp : Short versionIf I change this ... to this ... ... I still receive log messages , but they are corrupted.Either the messages do n't arrive , or they are formatted by a missing/deleted/removed method that does n't even exist in my current project ! For some unknown reason there is a problem with the specific string 'HardymanDatabaseLog ' I think it might be down to a corrupted instrumentation manifest that is manifestering somewhere.Read on to find out more ... ! ( thanks : o ) ) Long Version ( with pictures ) I have a simple console application that references EnterpriseLibrary.SemanticLogging via a nuget package.Using the example code from here , I added a BasicLogger class.When I run my simple app ... ... I get the following response in the log viewer console ( SemanticLogging-svc.exe ) ... which is correct ! BUT , if I now update the EventSource attribute to [ EventSource ( Name = `` HardymanDatabaseLog '' ) ] , and adjust my SemanticLogging-svc.xml to also reference HardymanDatabaseLog ... ... then I get the following response in the log viewer console ... ... Which has not only lost the first message , but corrupted the second ! If you look closely at the line that starts EventId : 1 then you can see it says Message : Application Started ... How , why and where is that message coming from ? ! ... even the Level : Informational bit is wrong ... my code has Level = Critical ! Before this problem started , I created a ( long since deleted ) method in the BasicLogger class that had the attribute [ Event ( 1 , Message = `` Application Started . `` , Level = EventLevel.Informational ) ] , and now , whenever I set EventSource ( Name= '' HardymanDatabaseLog '' ) , this phantom method is being called.To be clear ... the text 'Application Started ' no longer exists anywhere in my application ( I 'm using a completely new project ) ... The sole cause of this error is the reuse of the 'HardymanDatabaseLog ' EventSource name.Here 's what I 've done so far to try and clear whatever corrupted information is making things go awry : Restarted my computer ( standard ! ) Remove and re-add all references to Enterprise Library ( the problem persists between different solutions , so it ca n't be an application/solution level setting ) Stop and delete perfmon > Data Collector Sets > Event Trace Sessions > Microsoft-SemanticLogging-Etw-ConsoleEventSinkLook in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog to see if my app is registered ( certainly 'HardymanDatabaseLog ` was n't found anywhere in the registry ) Sleep on itSystem.Diagnostics.EventLog.DeleteEventSource ( `` HardymanDatabaseLog '' ) Clean/Rebuild/Clean/Build/Clean/etc/etc solutionRunning my application without the visual studio host applicationAnd this is what i tried but had no success with ... Determine if Enterprise Library persists configuration dataDetermine if the .NET EventSource persists configuration dataReinstall Enterprise Library ( only install-packages.ps1 is included with the download ) Banging my head on the keyboardAny and all help/suggestions gratefully appreciated.UpdateUsing JustDecompile , I 've found a method in the EventSource code that uses an object called a ManifestBuilder . That method appears to build an < instrumentationManifest / > document which could certainly contain all the information that seems to be lurking in the phantom method.Perhaps someone could shed some light on where these magic documents get stored in the context of .NET and Enterprise Library ? Update 2As @ Randy Levy has discovered by investigating the SLAB source , the problem can be fixed by deleting the files in C : \Users\ < UserName > \AppData\Local\Temp\7D2611AE-6432-4639-8B91-3E46EB56CADF . His answer also relates to this question ... SLAB , out-of-process : changing the signature of an event source method causes incorrect event logging.Thanks @ Randy Levy ! EventSource ( Name= '' BasicLogger '' ) public class BasicLogger : EventSource { ... } EventSource ( Name= '' HardymanDatabaseLog '' ) public class BasicLogger : EventSource { ... } using System.ComponentModel ; using System.Diagnostics.Tracing ; namespace Etw { class Program { static void Main ( string [ ] args ) { BasicLogger.Log.Error ( `` Hello1 '' ) ; BasicLogger.Log.Critical ( `` Hello2 '' ) ; } } [ EventSource ( Name = `` BasicLogger '' ) ] public class BasicLogger : EventSource { public static readonly BasicLogger Log = new BasicLogger ( ) ; [ Event ( 1 , Message = `` { 0 } '' , Level = EventLevel.Critical ) ] public void Critical ( string message ) { if ( IsEnabled ( ) ) WriteEvent ( 1 , message ) ; } [ Event ( 2 , Message = `` { 0 } '' , Level = EventLevel.Error ) ] public void Error ( string message ) { if ( IsEnabled ( ) ) WriteEvent ( 2 , message ) ; } [ Event ( 3 , Message = `` { 0 } '' , Level = EventLevel.Warning ) ] public void Warning ( string message ) { if ( IsEnabled ( ) ) WriteEvent ( 3 , message ) ; } [ Event ( 4 , Message = `` { 0 } '' , Level = EventLevel.Informational ) ] public void Informational ( string message ) { if ( IsEnabled ( ) ) WriteEvent ( 4 , message ) ; } } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration xmlns= '' http : //schemas.microsoft.com/practices/2013/entlib/semanticlogging/etw '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //schemas.microsoft.com/practices/2013/entlib/semanticlogging/etw SemanticLogging-svc.xsd '' > < sinks > < consoleSink name= '' ConsoleEventSink '' > < sources > < eventSource name= '' HardymanDatabaseLog '' level= '' LogAlways '' / > < /sources > < eventTextFormatter header= '' +=========================================+ '' / > < /consoleSink > < /sinks > < /configuration >","EventSource/Enterprise Library Logging caches deleted methods , ( possibly in a instrumentationManifest ! )" "C_sharp : I have just enabled the `` Concurrency Mode '' property to fixed of one of my entity.Everything works great when I try to update.But when I try to delete the entity , I always get this error : DBUpdateConcurrencyException Store update , insert , or delete statement affected an unexpected number of rows ( 0 ) . Entities may have been modified or deleted since entities were loaded . Refresh ObjectStateManager entries.Is there any way to disable DBUpdateConcurrencyException for delete operation ? If not , how can I manage this type of exception ? BTW , I have already looked at these kinds of solution : How to ignore a DbUpdateConcurrencyException when deleting an entity . Is there any way I can integrate this code with Breeze engine ? EDIT : I have upgraded from version 1.4.5 to 1.4.7 and I still have the same problem.If I look at the JSON object , would changing the entityState from `` Deleted '' to `` Detached '' would be a solution ? Is there any setting in Breeze that can help me do that ? [ HttpPost ] public SaveResult SaveChanges ( JObject saveBundle ) { try { return _breezeComponent.SaveChanges ( saveBundle ) ; } catch ( DbUpdateConcurrencyException ex ) { //Workaround needed } } { `` entities '' : [ { `` EventId '' : 11111 , `` EventName '' : `` Jon Doe '' , `` EventCity '' : `` Montreal '' , `` EventDate '' : `` 2014-01-24T00:00:00Z '' , `` TermDate '' : `` 2014-01-08T00:00:00Z '' , `` Insertedby '' : `` Terry '' , `` InsertDate '' : `` 2014-01-06T14:31:14.197Z '' , `` Updatedby '' : `` Terry '' , `` UpdateDate '' : `` 2014-01-07T15:50:53.037Z '' , `` entityAspect '' : { `` entityTypeName '' : `` Event : # Cds.Corpo.GuestList.Models '' , `` defaultResourceName '' : `` Events '' , `` entityState '' : `` Deleted '' , `` originalValuesMap '' : { } , `` autoGeneratedKey '' : { `` propertyName '' : `` EventId '' , `` autoGeneratedKeyType '' : `` Identity '' } } } ] , `` saveOptions '' : { } }",Breeze SaveChanges always throws DbUpdateConcurrencyException when deleting entity "C_sharp : I am currently working on making a large amount of requests to a web API . I have tried to async this process so that I can do so in a reasonable amount of time , however I am unable to throttle the connections so that I do n't send more than 10 requests/second . I am using a semaphore for the throttling but I am not entirely sure how it will work in this context as I have a nested loop . I am essentially getting a list of models , and each model has a list of days inside it . I need to make a request for each day inside the models . The amount of days can be anywhere from 1 to about 50 , 99 % of the time it 's only going to be 1 . So I want to async each model because there will be about 3000 of them , but I want to async the days in the case that there are multiple days that need to be completed . I need to stay at or under 10 requests/second so I thought the best way to do so would be to set a request limit of 10 on the entire operation . Is there a place that I can put a semaphore that will limit connections to the entire chain ? Each individual request also has to make two requests for 2 different pieces of data and this API does not support any sort of batching right now . I am sort of new to c # , very new to async and very new to WebRequests/HttpClient so any help is appreciated . I tried to add all relevant code here . If you need anything else let me know . public static async Task GetWeatherDataAsync ( List < Model > models ) { SemaphoreSlim semaphore = new SemaphoreSlim ( 10 ) ; var taskList = new List < Task < ComparisonModel > > ( ) ; foreach ( var x in models ) { await semaphore.WaitAsync ( ) ; taskList.Add ( CompDaysAsync ( x ) ) ; } try { await Task.WhenAll ( taskList.ToArray ( ) ) ; } catch ( Exception e ) { } finally { semaphore.Release ( ) ; } } public static async Task < Models > CompDaysAsync ( Model model ) { var httpClient = new HttpClient ( ) ; httpClient.DefaultRequestHeaders.Authorization = new Headers.AuthenticationHeaderValue ( `` Token '' , '' xxxxxxxx '' ) ; httpClient.Timeout = TimeSpan.FromMinutes ( 5 ) ; var taskList = new List < Task < Models.DateTemp > > ( ) ; foreach ( var item in model.list ) { taskList.Add ( WeatherAPI.GetResponseForDayAsync ( item , httpClient , Latitude , Longitude ) ) ; } httpClient.Dispose ( ) ; try { await Task.WhenAll ( taskList.ToArray ( ) ) ; } catch ( Exception e ) { } return model ; } public static async Task < DateTemp > GetResponseForDayAsync ( DateTemp date , HttpClient httpClient , decimal ? Latitude , decimal ? Longitude ) { var response = await httpClient.GetStreamAsync ( request1 ) ; StreamReader myStreamReader = new StreamReader ( response ) ; string responseData = myStreamReader.ReadToEnd ( ) ; double [ ] data = new double [ 2 ] ; if ( responseData ! = `` [ [ null , null ] ] '' ) { data = Array.ConvertAll ( responseData.Replace ( `` [ `` , `` '' ) .Replace ( `` ] '' , `` '' ) .Split ( ' , ' ) , double.Parse ) ; } else { data = null ; } ; double precipData = 0 ; var response2 = await httpClient.GetStreamAsync ( request2 ) ; StreamReader myStreamReader2 = new StreamReader ( response2 ) ; string responseData2 = myStreamReader2.ReadToEnd ( ) ; if ( responseData2 ! = null & & responseData2 ! = `` [ null ] '' & & responseData2 ! = `` [ 0.0 ] '' ) { precipData = double.Parse ( responseData2.Replace ( `` [ `` , `` '' ) .Replace ( `` ] '' , `` '' ) ) ; } date.Precip = precipData ; if ( data ! = null ) { date.minTemp = data [ 0 ] ; date.maxTemp = data [ 1 ] ; } return date ; }",Throttling concurrent async requests with loop "C_sharp : Related To : Create Expression Tree For SelectorCreate a Lambda Expression With 3 conditionsConvert Contains To Expression TreeConvert List.Contains to Expression TreeI want to Create Selector expression using Expression Tree for new class . Please Consider this code : I have big class ( MyClass ) that I want to select some of it 's Properties . But I want to create it dynamically . How I can do this ? Thanks s = > new Allocation { Id = s.Id , UnitName = s.UnitName , Address = s.NewAddress , Tel = s.NewTel }",Create Lambda Expression Selector For New Class Using Expression Tree "C_sharp : I have often found that if I have too many joins in a Linq query ( whether using Entity Framework or NHibernate ) and/or the shape of the resulting anonymous class is too complex , Linq takes a very long time to materialize the result set into objects.This is a generic question , but here 's a specific example using NHibernate : I know it 's not the query execution , because I put a sniffer on the database and I can see that the query is taking 0ms , yet the code is taking about a second to execute that query and bring back all of 11 records . So yeah , this is an overly complex query , having 8 joins between 9 tables , and I could probably restructure it into several smaller queries . Or I could turn it into a stored procedure - but would that help ? What I 'm trying to understand is , where is that red line crossed between a query that is performant and one that starts to struggle with materialization ? What 's going on under the hood ? And would it help if this were a SP whose flat results I subsequently manipulate in memory into the right shape ? EDIT : in response to a request in the comments , here 's the SQL emitted : EDIT 2 : Here 's the performance analysis from ANTS Performance Profiler : var libraryBookIdsWithShelfAndBookTagQuery = ( from shelf in session.Query < Shelf > ( ) join sbttref in session.Query < ShelfBookTagTypeCrossReference > ( ) on shelf.ShelfId equals sbttref.ShelfId join bookTag in session.Query < BookTag > ( ) on sbttref.BookTagTypeId equals ( byte ) bookTag.BookTagType join btbref in session.Query < BookTagBookCrossReference > ( ) on bookTag.BookTagId equals btbref.BookTagId join book in session.Query < Book > ( ) on btbref.BookId equals book.BookId join libraryBook in session.Query < LibraryBook > ( ) on book.BookId equals libraryBook.BookId join library in session.Query < LibraryCredential > ( ) on libraryBook.LibraryCredentialId equals library.LibraryCredentialId join lcsg in session .Query < LibraryCredentialSalesforceGroupCrossReference > ( ) on library.LibraryCredentialId equals lcsg.LibraryCredentialId join userGroup in session.Query < UserGroup > ( ) on lcsg.UserGroupOrganizationId equals userGroup.UserGroupOrganizationId where shelf.ShelfId == shelfId & & userGroup.UserGroupId == userGroupId & & ! book.IsDeleted & & book.IsDrm ! = null & & book.BookFormatTypeId ! = null select new { Book = book , LibraryBook = libraryBook , BookTag = bookTag } ) ; // add a couple of where clauses , then ... var result = libraryBookIdsWithShelfAndBookTagQuery.ToList ( ) ; SELECT DISTINCT book4_.bookid AS BookId12_0_ , libraryboo5_.librarybookid AS LibraryB1_35_1_ , booktag2_.booktagid AS BookTagId15_2_ , book4_.title AS Title12_0_ , book4_.isbn AS ISBN12_0_ , book4_.publicationdate AS Publicat4_12_0_ , book4_.classificationtypeid AS Classifi5_12_0_ , book4_.synopsis AS Synopsis12_0_ , book4_.thumbnailurl AS Thumbnai7_12_0_ , book4_.retinathumbnailurl AS RetinaTh8_12_0_ , book4_.totalpages AS TotalPages12_0_ , book4_.lastpage AS LastPage12_0_ , book4_.lastpagelocation AS LastPag11_12_0_ , book4_.lexilerating AS LexileR12_12_0_ , book4_.lastpageposition AS LastPag13_12_0_ , book4_.hidden AS Hidden12_0_ , book4_.teacherhidden AS Teacher15_12_0_ , book4_.modifieddatetime AS Modifie16_12_0_ , book4_.isdeleted AS IsDeleted12_0_ , book4_.importedwithlexile AS Importe18_12_0_ , book4_.bookformattypeid AS BookFor19_12_0_ , book4_.isdrm AS IsDrm12_0_ , book4_.lightsailready AS LightSa21_12_0_ , libraryboo5_.bookid AS BookId35_1_ , libraryboo5_.libraryid AS LibraryId35_1_ , libraryboo5_.externalid AS ExternalId35_1_ , libraryboo5_.totalcopies AS TotalCop5_35_1_ , libraryboo5_.availablecopies AS Availabl6_35_1_ , libraryboo5_.statuschangedate AS StatusCh7_35_1_ , booktag2_.booktagtypeid AS BookTagT2_15_2_ , booktag2_.booktagvalue AS BookTagV3_15_2_ FROM shelf shelf0_ , shelfbooktagtypecrossreference shelfbookt1_ , booktag booktag2_ , booktagbookcrossreference booktagboo3_ , book book4_ , librarybook libraryboo5_ , library librarycre6_ , librarycredentialsalesforcegroupcrossreference librarycre7_ , usergroup usergroup8_ WHERE shelfbookt1_.shelfid = shelf0_.shelfid AND booktag2_.booktagtypeid = shelfbookt1_.booktagtypeid AND booktagboo3_.booktagid = booktag2_.booktagid AND book4_.bookid = booktagboo3_.bookid AND libraryboo5_.bookid = book4_.bookid AND librarycre6_.libraryid = libraryboo5_.libraryid AND librarycre7_.librarycredentialid = librarycre6_.libraryid AND usergroup8_.usergrouporganizationid = librarycre7_.usergrouporganizationid AND shelf0_.shelfid = @ p0 AND usergroup8_.usergroupid = @ p1 AND NOT ( book4_.isdeleted = 1 ) AND ( book4_.isdrm IS NOT NULL ) AND ( book4_.bookformattypeid IS NOT NULL ) AND book4_.lightsailready = 1",Linq slowness materializing complex queries "C_sharp : So I have this datagridview that is linked to a Binding source that is binding to an underlying data table . The problem is I need to manual add rows to the datagridview.This can not be done while it is bound , so I have to work with the databinding.If I add the rows to the underlying datatable , when the datatable is saved , the rows are duplicated , probably because the binding source somehow got a hold of a copy and inserted it also.Adding it to the binding source is what I 've been trying to do but it 's not quite working.Let me explain exactly what my setup is : I have a database with two tables : CashReceiptTable and CashReceiptItemsTableCashReceiptItemsTable contains a FK to CashReceiptTable.The form allows the users to add , and modify the two tables.When the user enters a new cashreceipt , the cash receipt 's id is -1 , and the FK in cashReceiptitemstable is -1 . When the database is saved , cashReceipt 's id is updated , and I have to manually update cashreceiptitem 's FK.Here are the problems : When I try to update the CashReceiptID ( the FK ) in more than one row in cashreceiteitems binding source , the first row is updated , and disappears ( because it 's filtered ) , and the other rows are removed , and I can no longer access them.I have no idea why this is , I have n't updated the filter yet so they should still be there , but trying to access them throws RowNotInTableException.I 've managed a work around that copies the rows in the the binding source to an in memory array , deletes the first row in the binding source ( all the other rows just vanish ) , update the row 's FK and reinsert them into the binding source and save the table.This works okay , but why do the rows disappear ? I also have one more slight problem . When the CashReceiptsTable is empty and I am adding a new row to it , if I add more than one row to the CashReceiptsItemTable it causes problems . When manually adding the items to the binding source , adding a new row pops to previous row off and pushes it onto the datatable . This hides it from my FK updating routine and it is lost , it also removes it from the DataGridView.It only does that when I 'm adding the first row to CashReceiptsTable . Why does it do this , and how can I fix it ? I 'm posting my code that autopopulates it here : And this is the function that saves it to the database : private void autopopulate ( decimal totalPayment ) { //remove old rows for ( int i = 0 ; i < tblCashReceiptsApplyToBindingSource.List.Count ; i++ ) { DataRowView viewRow = tblCashReceiptsApplyToBindingSource.List [ i ] as DataRowView ; RentalEaseDataSet.tblCashReceiptsApplyToRow row = viewRow.Row as RentalEaseDataSet.tblCashReceiptsApplyToRow ; if ( row.CashReceiptsID == this.ReceiptID ) { tblCashReceiptsApplyToBindingSource.List.Remove ( viewRow ) ; i -- ; } } decimal payment = totalPayment ; //look for an exact amount foreach ( DataGridViewRow dueRow in dataViewDueRO.Rows ) { decimal due = -1 * ( Decimal ) dueRow.Cells [ Due.Index ] .Value ; if ( due == payment ) { String charge = ( String ) dueRow.Cells [ Description.Index ] .Value ; int chargeID = ManageCheckbooks.findTransactionID ( charge ) ; tblCashReceiptsApplyToBindingSource.AddNew ( ) ; RentalEaseDataSet.tblCashReceiptsApplyToRow row = ( ( DataRowView ) tblCashReceiptsApplyToBindingSource.Current ) .Row as RentalEaseDataSet.tblCashReceiptsApplyToRow ; row.CashReceiptsID = this.ReceiptID ; row.ApplyTo = chargeID ; row.Paid = payment ; //convert to positive payment = 0 ; break ; } } //if the exact amount was found , payment will = 0 , and this will do nothing , otherwise , //divy out everything left over ( which will be everything ) foreach ( DataGridViewRow dueRow in dataViewDueRO.Rows ) { String charge = ( String ) dueRow.Cells [ Description.Index ] .Value ; decimal due = ( Decimal ) dueRow.Cells [ Due.Index ] .Value ; if ( due > 0 || payment < = 0 ) { continue ; } int chargeID = ManageCheckbooks.findTransactionID ( charge ) ; payment += due ; //due is negative , so this will subtract how much the user owes tblCashReceiptsApplyToBindingSource.AddNew ( ) ; RentalEaseDataSet.tblCashReceiptsApplyToRow row = ( ( DataRowView ) tblCashReceiptsApplyToBindingSource.Current ) .Row as RentalEaseDataSet.tblCashReceiptsApplyToRow ; row.CashReceiptsID = this.ReceiptID ; row.ApplyTo = chargeID ; if ( payment > = 0 ) { //payment is enough to cover this row.Paid = due * -1 ; //convert to positive } else { //does n't have enough money to conver this , can only cover partial , or none row.Paid = ( due - payment ) * -1 ; //math : //money remaining $ 50 , current charge = $ 60 //payment = 50 + -60 = -10 //row [ `` Paid '' ] = ( -60 - -10 ) * -1 //row [ `` Paid '' ] = ( -60 + 10 ) * -1 //row [ `` Paid '' ] = -50 * -1 //row [ `` Paid '' ] = 50 } if ( payment < = 0 ) { break ; //do n't conintue , no more money to distribute } } isVirginRow = true ; } protected override void saveToDatabase ( ) { tblCashReceiptsBindingSource.EndEdit ( ) ; isVirginRow = false ; RentalEaseDataSet.tblCashReceiptsRow [ ] rows = rentalEaseDataSet.tblCashReceipts.Select ( `` ID < 0 '' ) as RentalEaseDataSet.tblCashReceiptsRow [ ] ; int newID = -1 ; if ( rows.Count ( ) > 0 ) { tblCashReceiptsTableAdapter.Update ( rows [ 0 ] ) ; newID = rows [ 0 ] .ID ; } tblCashReceiptsTableAdapter.Update ( rentalEaseDataSet.tblCashReceipts ) ; //update table /*foreach ( RentalEaseDataSet.tblCashReceiptsApplyToRow row in rentalEaseDataSet.tblCashReceiptsApplyTo.Select ( `` CashReceiptsID = -1 '' ) ) { row.CashReceiptsID = newID ; } */ //update binding source DataRowView [ ] applicationsOld = new DataRowView [ tblCashReceiptsApplyToBindingSource.List.Count ] ; RentalEaseDataSet.tblCashReceiptsApplyToRow [ ] applicationsNew = new RentalEaseDataSet.tblCashReceiptsApplyToRow [ tblCashReceiptsApplyToBindingSource.List.Count ] ; tblCashReceiptsApplyToBindingSource.List.CopyTo ( applicationsOld , 0 ) ; for ( int i = 0 ; i < applicationsOld.Count ( ) ; i++ ) { RentalEaseDataSet.tblCashReceiptsApplyToRow row = applicationsOld [ i ] .Row as RentalEaseDataSet.tblCashReceiptsApplyToRow ; if ( row.CashReceiptsID < 0 ) { applicationsNew [ i ] = rentalEaseDataSet.tblCashReceiptsApplyTo.NewRow ( ) as RentalEaseDataSet.tblCashReceiptsApplyToRow ; applicationsNew [ i ] [ `` ID '' ] = row.ID ; applicationsNew [ i ] [ `` CashReceiptsID '' ] = this.ReceiptID ; applicationsNew [ i ] [ 2 ] = row [ 2 ] ; applicationsNew [ i ] [ 3 ] = row [ 3 ] ; applicationsNew [ i ] [ 4 ] = row [ 4 ] ; //row.Delete ( ) ; } } for ( int i = 0 ; i < applicationsOld.Count ( ) ; i++ ) { try { if ( ( int ) applicationsOld [ i ] .Row [ `` ID '' ] < 0 ) { applicationsOld [ i ] .Row.Delete ( ) ; } } catch ( RowNotInTableException ) { break ; } } this.tblCashReceiptsApplyToBindingSource.Filter = `` CashReceiptsID = `` + this.ReceiptID ; foreach ( DataRow newRow in applicationsNew ) { if ( newRow == null ) { break ; } tblCashReceiptsApplyToBindingSource.AddNew ( ) ; ( ( DataRowView ) tblCashReceiptsApplyToBindingSource.Current ) .Row [ 0 ] = newRow [ 0 ] ; ( ( DataRowView ) tblCashReceiptsApplyToBindingSource.Current ) .Row [ 1 ] = newRow [ 1 ] ; ( ( DataRowView ) tblCashReceiptsApplyToBindingSource.Current ) .Row [ 2 ] = newRow [ 2 ] ; ( ( DataRowView ) tblCashReceiptsApplyToBindingSource.Current ) .Row [ 3 ] = newRow [ 3 ] ; ( ( DataRowView ) tblCashReceiptsApplyToBindingSource.Current ) .Row [ 4 ] = newRow [ 4 ] ; } tblCashReceiptsApplyToBindingSource.EndEdit ( ) ; checkForBadRows ( ) ; tblCashReceiptsApplyToTableAdapter.Update ( rentalEaseDataSet.tblCashReceiptsApplyTo ) ; tblCashReceiptsApplyToTableAdapter.Fill ( rentalEaseDataSet.tblCashReceiptsApplyTo ) ; }",DataBinding woes "C_sharp : I have a self-hosted WebApi application with a custom MediaTypeFormatterDepending on the `` name '' parameter ( Or thereby part of the URL ) , the application should format the request body to varying types.Here 's the actionHere 's the custom MediaTypeFormatter.ReadFromStreamAsync // http : //localhost/api/fire/test/ // Route : `` api/fire/ { name } '' , public HttpResponseMessage Post ( [ FromUri ] string name , object data ) { // Snip } public override Task < object > ReadFromStreamAsync ( Type type , Stream readStream , HttpContent content , IFormatterLogger formatterLogger ) { var name = `` test '' ; // TODO this should come from the current request var formatter = _httpSelfHostConfiguration.Formatters.JsonFormatter ; if ( name.Equals ( `` test '' , StringComparison.InvariantCultureIgnoreCase ) ) { return formatter.ReadFromStreamAsync ( typeof ( SomeType ) , readStream , content , formatterLogger ) ; } else { return formatter.ReadFromStreamAsync ( typeof ( OtherType ) , readStream , content , formatterLogger ) ; } }",Get requested URL Or an action Parameter i MediaTypeFormatter.ReadFromStreamAsync "C_sharp : Purpose : To import data from excel to ms access ( .mdb ) database.Reference : https : //www.mikesdotnetting.com/article/79/import-data-from-excel-to-access-with-asp-netTechnology : C # .net Windows FormsError : `` The Microsoft Jet database engine can not find the input table or query 'Persons $ ' . Make sure it exists and that its name is spelled correctly . `` Code : Note : I have created a MS Access database named `` DestinationDB.mdb '' with table name as `` Persons '' with the following fields : ContactID , FirstName , SecondName , AgeThereafter i have exported the same to excel in order to retain the header structure . Once this excel is exported , i added some 10 records to it manually.Both the files are located under `` c : //exportdb/source.xls '' & `` c : //exportdb/DestinationDB.mdb '' .Excel Snapshot : Ms Access Snapshot : Please help me to resolve the error stated above.Thanks ! private void button6_Click ( object sender , EventArgs e ) { string Access = @ '' c : \exportdb\DestinationDB.mdb '' ; string connect = @ '' Provider=Microsoft.Jet.OLEDB.4.0 ; Data Source=C : \exportdb\DestinationDB.mdb ; '' ; using ( OleDbConnection conn = new OleDbConnection ( connect ) ) { using ( OleDbCommand cmd = new OleDbCommand ( ) ) { cmd.Connection = conn ; cmd.CommandText = `` INSERT INTO [ MS Access ; Database= '' + Access + `` ] . [ Persons ] SELECT * FROM [ Persons $ ] '' ; conn.Open ( ) ; cmd.ExecuteNonQuery ( ) ; } } }",Excel to Access Import Error "C_sharp : I 'm trying to use a type-safe WeakReference in my Silverlight app . I 'm following the recipe on this site : http : //ondevelopment.blogspot.com/2008/01/generic-weak-reference.html only using the System.WeakReference and omitting the stuff that references Serialization . It 's throwing a ReflectionTypeLoadException when I try to run it , with this message : '' { System.TypeLoadException : Inheritance security rules violated while overriding member : 'Coatue.Silverlight.Shared.Cache.WeakReference ` 1..ctor ( ) ' . Security accessibility of the overriding method must match the security accessibility of the method being overriden . } '' Any suggestions ? EDIT : Here 's the code I 'm using : using System ; namespace Frank { public class WeakReference < T > : WeakReference where T : class { public WeakReference ( T target ) : base ( target ) { } public WeakReference ( T target , bool trackResurrection ) : base ( target , trackResurrection ) { } protected WeakReference ( ) : base ( ) { } public new T Target { get { return ( T ) base.Target ; } set { base.Target = value ; } } } }",Inherited WeakReference throwing ReflectionTypeLoadException in Silverlight "C_sharp : I 'm currently trying to create a very very simple sandbox.Some class A has a method Execute which is invoked in another AppDomain than the caller.Problem is I 've execution permission only and reflection is possible anyway.This is the code sample : UPDATEGreat ! Finally I did it . Thanks to your advices I 've revised my code and I 'd like to share it with you , since I had a hard time understanding how to do n't use CAS but use same kind of permissions in the new .NET 4.x and above security model , and the way of sandboxing using an AppDomain . That 's it : [ Serializable ] public class A : MarshalByRefObject { public void Execute ( ) { typeof ( A ) .GetConstructor ( Type.EmptyTypes ) .Invoke ( null ) ; // Fine - Why ? typeof ( B ) .GetConstructor ( Type.EmptyTypes ) .Invoke ( null ) ; // Fine - Why ? } } public class B { } class Program { static void Main ( string [ ] args ) { PermissionSet set = new PermissionSet ( PermissionState.None ) ; SecurityPermission security = new SecurityPermission ( SecurityPermissionFlag.Execution ) ; set.AddPermission ( security ) ; Evidence evidence = new Evidence ( ) ; AppDomainSetup setup = new AppDomainSetup ( ) ; setup.ApplicationBase = `` C : '' ; AppDomain domain = AppDomain.CreateDomain ( `` hello '' , evidence , setup , set ) ; A a = ( A ) domain.CreateInstanceAndUnwrap ( Assembly.GetExecutingAssembly ( ) .FullName , typeof ( A ) .FullName ) ; a.Execute ( ) ; } } using System ; using System.Reflection ; using System.Security ; using System.Security.Permissions ; using System.Security.Policy ; namespace ConsoleApplication1 { [ Serializable ] public class A : MarshalByRefObject { public void Execute ( ) { B b = new B ( ) ; // BOMB ! ERROR ! Security demand : reflection forbidden ! b.GetType ( ) .GetMethod ( `` ExecuteInB '' , BindingFlags.Instance | BindingFlags.NonPublic ) .Invoke ( b , null ) ; } } public class B { private void ExecuteInB ( ) { } } class Program { static void Main ( string [ ] args ) { PermissionSet set = new PermissionSet ( PermissionState.None ) ; SecurityPermission security = new SecurityPermission ( PermissionState.None ) ; security.Flags = SecurityPermissionFlag.Execution ; set.AddPermission ( security ) ; Evidence evidence = new Evidence ( ) ; AppDomainSetup setup = new AppDomainSetup ( ) ; setup.ApplicationBase = `` C : '' ; AppDomain domain = AppDomain.CreateDomain ( `` hola '' , evidence , setup , set ) ; A a = ( A ) domain.CreateInstanceAndUnwrap ( `` ConsoleApplication1 '' , `` ConsoleApplication1.A '' ) ; a.Execute ( ) ; } } }",Reflection not restricted even if it 's not in grant set "C_sharp : I 'm trying to change Power BI connection string using their API ( Microsoft.IdentityModel.Clients.ActiveDirectory ) . Using this API , I 'm able to publish .pbix file to my PBI account . But Getting Bad Request error while trying to update dataset connection string . Here is my code . Also I found in a blog that SetAllConnections only works on direct query connections . Anybody help please . var client = new HttpClient ( ) ; client.DefaultRequestHeaders.Add ( `` Accept '' , `` application/json '' ) ; client.DefaultRequestHeaders.Add ( `` Authorization '' , `` Bearer `` + accessToken ) ; var restUrlImportPbix = POWER_BI_SERVICE_ROOT_URL + $ '' datasets/ { dataset.id } /Default.SetAllConnections '' ; var postData = new { connectionString = _powerBISettings.DataConnectionString } ; var response = client.PostAsync ( restUrlImportPbix , new StringContent ( JsonConvert.SerializeObject ( postData ) , Encoding.UTF8 , `` application/json '' ) ) .Result ;",Unable to change Power BI connection string using API C_sharp : In WinForms I have an AssemblVersion However when the splash screen comes up it completely ignores the zeros showing : as the version which is very inconvenient since later I will actually want to have an assembly versionIs there a way to avoid this or do I Have to add some number at the beginning of last part of the version like so : [ assembly : AssemblyVersion ( `` 01.01.01.002 '' ) ] 1.1.1.2 [ assembly : AssemblyVersion ( `` 01.01.01.200 '' ) ] [ assembly : AssemblyVersion ( `` 01.01.01.102 '' ) ],Assembly version `` .001 '' becomes `` .1 '' "C_sharp : I am working with the following Entity Framework query . I know there 's a lot going on here but am hoping it 's clear enough that someone might be able to spot the issue.As is , this query generates the following run-time error : The wait operation timed outIf I change the section that declares selectedChoiceId to the following , the error goes away : Can anyone see how that code is consistently causing a time-out error ? ( Note : This code is part of a large application that has been running for several years . So I really do n't think this has anything to do with the connection string or anything like that . If I make the change above , it works consistently . ) var lineItems = from li in Repository.Query < CostingLineItem > ( ) let cid = ( li.ParentCostingPackage ! = null ) ? li.ParentCostingPackage.ParentCostingEvent.ProposalSection.Proposal.Costing.Id : li.ParentCostingEvent.ProposalSection.Proposal.Costing.Id where cid == costingId & & li.OriginalProductId.HasValue & & ( li.Quantity.HasValue & & li.Quantity.Value > 0 ) & & // li.QuantityUnitMultiplier Classifications.Contains ( li.OriginalProduct.ClassificationEnumIndex ) let selectedChoiceId = li.OriginalPackageOptionId.HasValue ? ( from c in li.OriginalPackageOption.CostingLineItems orderby ( c.IsIncluded ? ? false ) ? -2 : ( c.IsDefaultItem ? ? false ) ? -1 : c.Id select ( int ) c.OriginalPackageOptionChoiceId ) .FirstOrDefault ( ) : 0 where selectedChoiceId == 0 || ( li.OriginalPackageOptionChoiceId.HasValue & & li.OriginalPackageOptionId.Value == selectedChoiceId ) let hasProviderAvailable = li.OriginalProductItem.ProductItemVendors.Any ( piv = > piv.ProductPricings.Any ( pp = > pp.ProductItemVendor.CompanyId ! = null || pp.ProductItemVendor.HotelId ! = null ) ) select new { LineItem = li , ProductItem = li.OriginalProductItem , Product = li.OriginalProduct , Vendors = li.CostingLineItemVendors , HasProviderAvailable = hasProviderAvailable } ; let selectedChoiceId = 0",Entity Framework causing Timeout Error "C_sharp : I have a legacy HTTP/XML service that I need to interact with for various features in my application.I have to create a wide range of request messages for the service , so to avoid a lot of magic strings littered around the code , I 've decided to create xml XElement fragments to create a rudimentary DSL.For example.Instead of ... I 'm intended to use : With Root , Request and MessageData ( of course , these are for illustrative purposes ) defined as static methods which all do something similar to : This gives me a pseudo functional composition style , which I like for this sort of task.My ultimate question is really one of sanity / best practices , so it 's probably too subjective , however I 'd appreciate the opportunity to get some feedback regardless.I 'm intending to move these private methods over to public static class , so that they are easily accessible for any class that wants to compose a message for the service.I 'm also intending to have different features of the service have their messages created by specific message building classes , for improved maintainability.Is this a good way to implement this simple DSL , or am I missing some special sauce that will let me do this better ? The thing that leads me to doubt , is the fact that as soon as I move these methods to another class I increase the length of these method calls ( of course I do still retain the initial goal of removing the large volume magic strings . ) Should I be more concerned about the size ( loc ) of the DSL language class , than I am about syntax brevity ? CaveatsNote that in this instance the remote service poorly implemented , and does n't conform to any general messaging standards , e.g . WSDL , SOAP , XML/RPC , WCF etc . In those cases , it would obviously not be wise to create hand built messages . In the rare cases where you do have to deal with a service like the one in question here , and it can not be re-engineered for whatever reason , the answers below provide some possible ways of dealing with the situation . new XElement ( `` root '' , new XElement ( `` request '' , new XElement ( `` messageData '' , ... ) ) ) ; Root ( Request ( MessageData ( ... ) ) ) ; private static XElement Root ( params object [ ] content ) { return new XElement ( `` root '' , content ) ; }",Implementing a DSL in C # for generating domain specific XML "C_sharp : I have a class like this : And another class like this : The first class is a part of my project , the second class is from a framework library developed by another group within my organization . Notice the namespace of the first class has Token2 in the second place and the namespace of the second class has Token2 in the first place.The problem I am having is that I ca n't seem to reference the second class within the first because of what looks like a namespace collision . If I try to do this in the first class : the Visual Studio IDE highlights Token4 in red and says `` Can not resolve symbol 'Token4 ' '' . If I hover my mouse over Token2 where I am new'ing up Class1 , intellisense shows me `` namespace Token1.Token2 '' so it is clearly seeing the namespace of my project class and not seeing the namespace of my framework class.It would be very difficult to change the namespace of either class library due to the amount of code already in place . Is there a way to get around this ? namespace Token1.Token2.Token3 { public class Class1 { } } namespace Token2.Token4.Token5 { public class Class1 { } } namespace Token1.Token2.Token3 { public class Class1 { var frameworkClass1 = new Token2.Token4.Token5.Class1 ( ) ; } }",C # Referenced Namespace Hidden By Class Namespace "C_sharp : I 've found a behaviour in c # and I would like to know if it 's in the specs ( and can be expected to work on all platforms and new versions of the .NET runtime ) or if it 's undefined behaviour that just happens to work but may stop compiling at any time.So , let 's say I want to take existing classes , like these : now I would really like them to implement a common IText interface , like this one : but I ca n't change the classes directly because they are part of an external library . Now there are various ways to do this , through inheritance or with a decorator.But I was surprised to find out that doing simply this compiles and works on .NET 4.5 ( windows 7 64 bits ) .That 's it . This gets me drop-in replacements for HtmlTextBox and HtmlDiv that use their existing Text property as implementation for IText.I was half-expecting the compiler to yell at me , asking me to provide an explicit re-implementation of Text , but on .NET 4.5 this just works : In fact , I 've tried the same on mono ( whatever version ideone.com is using ) and mono does not yell at me either So I guess I 'm good to go , but before trying this on serious code I wanted to check if I 've misunderstood what is really happening here or if I ca n't rely on this to work . public class HtmlTextBox { public string Text { get ; set ; } } public class HtmlDiv { public string Text { get ; set ; } } public interface IText { string Text { get ; } } public class HtmlTextBox2 : HtmlTextBox , IText { } public class HtmlDiv2 : HtmlDiv , IText { } IText h2 = new HtmlTextBox2 { Text= '' Hello World '' } ; Console.WriteLine ( h2.Text ) ; //OUTPUT : hello world",c # behavior on interface implementation C_sharp : In this snippet : Is there a risk of ending up with ConstantB == `` Else '' ? Or do the assigments happen linearly ? class ClassWithConstants { private const string ConstantA = `` Something '' ; private const string ConstantB = ConstantA + `` Else '' ; ... },C # : Is this field assignment safe ? "C_sharp : [ Edit : I realized that the parameter that is failing is actually a double and not an integer . None of the integer timers fail according to the logs . Most of the timers and parameters are integers , but not all . Doubles are not atomic and the lack of locking may be the issue after all . ] I have an application that uses a class that contains properties for configurable values . Most of the properties being used in the app are derived . The values are set at start up and not changed while the main portion of the application is running.I find that very rarely the value returned is apparently zero because of an exception.The calling code looks lime this : The program is multi-threaded but the call to the individual property is only used in one thread . Other properties of the class are called in other threads . I do see the issue on other timers with similar properties.If I trap the exception and retry the assignment it works.Could there be something happening at my timer that would cause the execption other than the property returning zero ? Update # 1 - More code was requestedEach field is defined as a cfXXX ( Configuration Field ) constant . This ensures we do n't misspell the field names . A corresponding default value for each property is defined as DefXXX . The PareseXXX functions ( ParseInt in this sample ) accepts the string value from the configuration lookup and converts it to the corresponding value type or the provided default if it fails . Failure would be from a missing XML record ( new configuration option ) or one that was incorrectly edited.Code to load initial configuration data : private int _TimerInterval ; public int TimerInterval { get { return _TimerInterval ; } } private int _Factor1 ; public int Factor1 { set { _Factor1 = value ; _TimerInterval = _Factor1 * _Factor2 ; } get { return _Factor1 ; } } private int _Factor2 ; public int Factor2 { set { _Factor2 = value ; _TimerInterval = _Factor1 * _Factor2 ; } get { return _Factor2 ; } } Exception Message : ' 0 ' is not a valid value for 'Interval ' . 'Interval ' must be greater than 0.Exception Target Site : set_Interval exitTimer.Interval = _config.TimerInterval ; // Main Formpublic fMain ( ) { InitializeComponent ( ) ; config = new ConfigData ( ) ; config.LoadConfig ( ) ; // Other initializations } //ConfigData Class// XML config field namesprivate const string cfFactor1 = `` Factor1 '' ; private const string cfFactor1 = `` Factor2 '' ; private const string cfFactor3 = `` Factor3 '' ; private const string cfFactor4 = `` Factor4 '' ; //Default valuesprivate const int DefFactor1 = 1 ; private const int DefFactor2 = 50 ; private const int DefFactor3 = 1 ; private const int DefFactor4 = 25 ; public void LoadConfig ( ) { Factor1 = ParseInt ( ConfigurationManager.AppSettings [ cfFactor1 ] , DefFactor1 ) ; Factor2 = ParseInt ( ConfigurationManager.AppSettings [ cfFactor2 ] , DefFactor2 ) ; Factor3 = ParseInt ( ConfigurationManager.AppSettings [ cfFactor3 ] , DefFactor3 ) ; Factor4 = ParseInt ( ConfigurationManager.AppSettings [ cfFactor4 ] , DefFactor4 ) ; } int ParseInt ( string numberString , int aDefault = 0 ) { int result ; if ( ! int.TryParse ( numberString , out result ) ) { result = aDefault ; } return result ; }",Why would an integer property sometimes return a 0 ? "C_sharp : Here is the situation , I am developing a binary search tree and in each node of the tree I intend to store the height of its own for further balancing the tree during avl tree formation . Previously I had an iterative approach to calculate the height of a node during balancing the tree like the following . ( The following code belongs to a class called AVLTree < T > which is a child class of BinarySearchTree < T > ) But it was incurring a lot of performance overhead.Performance of an AVL Tree in C # So I went for storing the height value in each node at the time of insertion in the BinarySearchTree < T > . Now during balancing I am able to avoid this iteration and I am gaining the desired performance in AVLTree < T > .But now the problem is if I try to insert a large number of data say 1-50000 sequentially in BinarySearchTree < T > ( without balancing it ) , I am getting StackoverflowException . I am providing the code which is causing it . Can you please help me to find a solution which will avoid this exception and also not compromise with the performance in its child class AVLTree < T > ? I am getting the StackoverflowException in calculating the height at the following linein the Height property of BinaryTreeNode < T > class . If possible please suggest me some work around.BTW , thanks a lot for your attention to read such a long question : ) protected virtual int GetBalance ( BinaryTreeNode < T > node ) { if ( node ! = null ) { IEnumerable < BinaryTreeNode < T > > leftSubtree = null , righSubtree = null ; if ( node.Left ! = null ) leftSubtree = node.Left.ToEnumerable ( BinaryTreeTraversalType.InOrder ) ; if ( node.Right ! = null ) righSubtree = node.Right.ToEnumerable ( BinaryTreeTraversalType.InOrder ) ; var leftHeight = leftSubtree.IsNullOrEmpty ( ) ? 0 : leftSubtree.Max ( x = > x.Depth ) - node.Depth ; var righHeight = righSubtree.IsNullOrEmpty ( ) ? 0 : righSubtree.Max ( x = > x.Depth ) - node.Depth ; return righHeight - leftHeight ; } return 0 ; } public class BinaryTreeNode < T > { private BinaryTreeNode < T > _left , _right ; private int _height ; public T Value { get ; set ; } public BinaryTreeNode < T > Parent ; public int Depth { get ; set ; } public BinaryTreeNode ( ) { } public BinaryTreeNode ( T data ) { Value = data ; } public BinaryTreeNode < T > Left { get { return _left ; } set { _left = value ; if ( _left ! = null ) { _left.Depth = Depth + 1 ; _left.Parent = this ; } UpdateHeight ( ) ; } } public BinaryTreeNode < T > Right { get { return _right ; } set { _right = value ; if ( _right ! = null ) { _right.Depth = Depth + 1 ; _right.Parent = this ; } UpdateHeight ( ) ; } } public int Height { get { return _height ; } protected internal set { _height = value ; if ( Parent ! = null ) { Parent.UpdateHeight ( ) ; } } } private void UpdateHeight ( ) { if ( Left == null & & Right == null ) { return ; } if ( Left ! = null & & Right ! = null ) { if ( Left.Height > Right.Height ) Height = Left.Height + 1 ; else Height = Right.Height + 1 ; } else if ( Left == null ) Height = Right.Height + 1 ; else Height = Left.Height + 1 ; } } public class BinarySearchTree < T > { private readonly Comparer < T > _comparer = Comparer < T > .Default ; public BinarySearchTree ( ) { } public BinaryTreeNode < T > Root { get ; set ; } public virtual void Add ( T value ) { var n = new BinaryTreeNode < T > ( value ) ; int result ; BinaryTreeNode < T > current = Root , parent = null ; while ( current ! = null ) { result = _comparer.Compare ( current.Value , value ) ; if ( result == 0 ) { parent = current ; current = current.Left ; } if ( result > 0 ) { parent = current ; current = current.Left ; } else if ( result < 0 ) { parent = current ; current = current.Right ; } } if ( parent == null ) Root = n ; else { result = _comparer.Compare ( parent.Value , value ) ; if ( result > 0 ) parent.Left = n ; else parent.Right = n ; } } } if ( Parent ! = null ) { Parent.UpdateHeight ( ) ; }",How to avoid this stackoverflow exception ? "C_sharp : The Situation : I am creating an automated task which queries MySQL ( through ODBC ) and inserts the result set to a MS Access Database ( .mdb ) using OLEDB . The Code : The Issues : The memory usage goes very high ( 300MB++ ) while the MS Access file size does not change constantly ! Seems like the insert caches the data rather that saving it to disk.It is very slow ! I know my query executes within a few second but rather insertion process takes long.I have tried using prepared statement in MS Access and insert the values as parameters instead of string concat to create insert query . However I get this exception message : Data type mismatch in criteria expression.Anyone know how to fix this or have a better approach ? OleDbConnection accCon = new OleDbConnection ( ) ; OdbcCommand mySQLCon = new OdbcCommand ( ) ; try { //connect to mysql Connect ( ) ; mySQLCon.Connection = connection ; //connect to access accCon.ConnectionString = @ '' Provider=Microsoft.Jet.OLEDB.4.0 ; '' + @ '' Data source= `` + pathToAccess ; accCon.Open ( ) ; var cnt = 0 ; while ( cnt < 5 ) { if ( accCon.State == ConnectionState.Open ) break ; cnt++ ; System.Threading.Thread.Sleep ( 50 ) ; } if ( cnt == 5 ) { ToolBox.logThis ( `` Connection to Access DB did not open . Exit Process '' ) ; return ; } } catch ( Exception e ) { ToolBox.logThis ( `` Faild to Open connections . msg - > `` + e.Message + `` \\n '' + e.StackTrace ) ; } OleDbCommand accCmn = new OleDbCommand ( ) ; accCmn.Connection = accCon ; //access insert query structurevar insertAccessQuery = `` INSERT INTO { 0 } values ( { 1 } ) ; '' ; // key = > tbl name in access , value = > mysql query to b executedforeach ( var table in tblNQuery ) { try { mySQLCon.CommandText = table.Value ; //executed mysql query using ( var dataReader = mySQLCon.ExecuteReader ( ) ) { //variable to hold row data var rowData = new object [ dataReader.FieldCount ] ; var parameters = `` '' ; //read the result set from mysql query while ( dataReader.Read ( ) ) { //fill rowData with the row values dataReader.GetValues ( rowData ) ; //build the parameters for insert query for ( var i = 0 ; i < dataReader.FieldCount ; i++ ) parameters += `` ' '' + rowData [ i ] + `` ' , '' ; parameters = parameters.TrimEnd ( ' , ' ) ; //insert to access accCmn.CommandText = string.Format ( insertAccessQuery , table.Key , parameters ) ; try { accCmn.ExecuteNonQuery ( ) ; } catch ( Exception exc ) { ToolBox.logThis ( `` Faild to insert to access db . msg - > `` + exc.Message + `` \\n\\tInsert query - > `` + accCmn.CommandText ) ; } parameters = `` '' ; } } } catch ( Exception e ) { ToolBox.logThis ( `` Faild to populate access db . msg - > `` + e.Message + `` \\n '' + e.StackTrace ) ; } } Disconnect ( ) ; accCmn.Dispose ( ) ; accCon.Close ( ) ;",1GB of Data From MySQL to MS Access "C_sharp : I have a simple MVC4 model that adds a DateTime.Now to a List < DateTime > ( ) list . However when I do an EntityState.Modified , the changes are not being kept . I 've debugged this by modifying another property in the model and that saves fine . So I really am at a loss as to why this is not saving . If anyone has any ideas as to why its not saving that would be life saver material : The Model : Here 's my code : public class Page { public int Id { get ; set ; } public string PageURL { get ; set ; } public string Name { get ; set ; } public string Title { get ; set ; } public List < DateTime > Visits { get ; set ; } public Page ( ) { Visits = new List < DateTime > ( ) ; } } private ApplicationDbContext db = new ApplicationDbContext ( ) ; public ActionResult CookiePolicy ( ) { var page = db.Pages.FirstOrDefault ( c = > c.PageURL == `` cookiepolicy '' ) ; page.Visits.Add ( DateTime.Now ) ; // this list of datetime objects does not get updated page.Title = `` test `` ; //but this property does ViewBag.Title = page.Title ; db.Entry ( page ) .State = EntityState.Modified ; db.SaveChanges ( ) ; return View ( page ) ; }",MVC datetime list not saving "C_sharp : In F # : In C # or .NET BCL in general : Why ? Postscript : The reason I thought I had the `` right '' Equals was because this turned out to be true : [ 0 ] = [ 0 ] = true StructuralComparisons.Equals ( new int [ ] { 0 } , new int [ ] { 0 } ) == false var a = new { X = 3 , Y = new { Z = -1 } } ; var b = new { X = 3 , Y = new { Z = -1 } } ; StructuralComparisons.Equals ( a , b ) == true ;",StructuralComparisons for arrays C_sharp : Is there an analogous conditional-not-present attribute or maybe a way to use the Conditional attribute to only include a method if that symbol is not defined ? What I 'm looking for is something that works like this : Such that the method will not be included if the symbol SILVERLIGHT does exist.The reason I do n't want to use a simple # ifdef is so that I can take advantage of the compiler removing the calling statements without having to wrap every individual call in an # ifdef . [ Conditional ( `` ! SILVERLIGHT '' ) ] private void DoStuffThatSilverlightCant ( ) { ... },Is there an inverse of System.Diagnostics.ConditionalAttribute ? "C_sharp : After I updated my project to dotnet core 3.0RC1 ( might be in preview9 as well ) my code that used to work started throwing System.InvalidOperationException : Sequence contains no elements . The table in question is empty.If I add ToList ( ) so it looks like this DeafultIfEmpty ( ) .ToList ( ) .Max ( ) , it starts to work again . Could not find any information about a breaking change . When I run it works fine . That made me think maybe something wrong with EF Core . Then I created test in xUnit with exactly the same setup but there tests are passing ( table is empty as well , uses InMemoryDatabase instead of live SQL Server instance ) .I am truly puzzled . Relevant stack trace : EditProduct class:2nd editSql produced by ef core var value = context.Products.Where ( t = > t.CategoryId == catId ) .Select ( t = > t.Version ) .DefaultIfEmpty ( ) .Max ( ) ; var expectedZero = new List < int > ( ) .DefaultIfEmpty ( ) .Max ( ) ; System.InvalidOperationException : Sequence contains no elements . at int lambda_method ( Closure , QueryContext , DbDataReader , ResultContext , int [ ] , ResultCoordinator ) at bool Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor+QueryingEnumerable < T > +Enumerator.MoveNext ( ) at TSource System.Linq.Enumerable.Single < TSource > ( IEnumerable < TSource > source ) at TResult Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute < TResult > ( Expression query ) at TResult Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute < TResult > ( Expression expression ) at TSource System.Linq.Queryable.Max < TSource > ( IQueryable < TSource > source ) at ... ( my method that run the code ) [ Table ( `` tmpExtProduct '' , Schema = `` ext '' ) ] public partial class Product { [ Key ] [ DatabaseGenerated ( DatabaseGeneratedOption.None ) ] public int Version { get ; set ; } [ Column ( TypeName = `` datetime '' ) ] public DateTime ImportDate { get ; set ; } public int CategoryId { get ; set ; } public string Description { get ; set ; } [ ForeignKey ( nameof ( Ext.Category ) ) ] public int CategoryId { get ; set ; } [ InverseProperty ( nameof ( Ext.Category.Products ) ) ] public virtual Category Category { get ; set ; } } exec sp_executesql N'SELECT MAX ( [ t0 ] . [ Version ] ) FROM ( SELECT NULL AS [ empty ] ) AS [ empty ] LEFT JOIN ( SELECT [ p ] . [ Version ] , [ p ] . [ CategoryId ] , [ p ] . [ ImportDate ] , [ p ] . [ Description ] FROM [ ext ] . [ tmpExtProduct ] AS [ p ] WHERE ( ( [ p ] . [ CategoryId ] = @ __categoryId_0 ) AND @ __categoryId_0 IS NOT NULL ) ) AS [ t0 ] ON 1 = 1 ' , N ' @ __categoryId_0 int ' , @ __categoryId_0=5",DefaultIfEmpty ( ) .Max ( ) still throws 'Sequence contains no elements . ' "C_sharp : I do n't have much experience with using the yield keyword . I have these IEnumerable < T > extensions for Type Conversion.My question is does the first overloaded method have the same yield return effect that I 'm getting from the second method ? public static IEnumerable < TTo > ConvertFrom < TTo , TFrom > ( this IEnumerable < TFrom > toList ) { return ConvertFrom < TTo , TFrom > ( toList , TypeDescriptor.GetConverter ( typeof ( TTo ) ) ) ; } public static IEnumerable < TTo > ConvertFrom < TTo , TFrom > ( this IEnumerable < TFrom > toList , TypeConverter converter ) { foreach ( var t in toList ) yield return ( TTo ) converter.ConvertFrom ( t ) ; }",Overloaded use of yield return "C_sharp : I 'm using the code below . It 's designed for a certain type to limit it 's popup-ness in intellisense etc.Now I 'd like to use the same Get method for another type ( or , to be fully covered , a few another types but still a fix number of ) . So I added a second method and the code looks as follows.It strikes me that a better approach would be to keep it in the same method body and still cover all the regarded types . Is there a syntax for including e.g . two different types in the signature ? Something like this pseudo-code below.The best approach I can think of , as shown below , consists of a entry method for each type and the logic in a private place . It makes sense when the logic is extensive but looks kind of superfluous when it 's only a line or two . public static Generic Get < Generic > ( this Entity input ) { return ( Generic ) input ; } public static Generic Get < Generic > ( this Entity input ) { return ( Generic ) input ; } public static Generic Get < Generic > ( this Entity2 input ) { return ( Generic ) input ; } public static Generic Get < Generic > ( this [ Entity , Entity2 ] input ) { return ( Generic ) input ; } public static Generic Get < Generic > ( this Entity input ) { return CommonLogic ( input ) ; } public static Generic Get < Generic > ( this Entity2 input ) { return CommonLogic ( input ) ; } private static Generic CommonLogic ( Object input ) { return ( Generic ) input ; }",Extension method for precisely two different types "C_sharp : I was playing a bit with Eric Lippert 's Ref < T > class from here . I noticed in the IL that it looked like both anonymous methods were using the same generated class , even though that meant the class had an extra variable.While using only one new class definition seems somewhat reasonable , it strikes me as very odd that only one instance of < > c__DisplayClass2 is created . This seems to imply that both instances of Ref < T > are referencing the same < > c__DisplayClass2 Does n't that mean that y can not be collected until vart1 is collected , which may happen much later than after joik returns ? After all , there is no guarantee that some idiot wo n't write a function ( directly in IL ) which directly accesses y through vart1 aftrer joik returns . Maybe this could even be done with reflection instead of via crazy IL.Running IL DASM confirmed that vart1 and vart2 both used < > __DisplayClass2 , which contained a public field for x and for y . The IL of joik : sealed class Ref < T > { public delegate T Func < T > ( ) ; private readonly Func < T > getter ; public Ref ( Func < T > getter ) { this.getter = getter ; } public T Value { get { return getter ( ) ; } } } static Ref < int > joik ( ) { int [ ] y = new int [ 50000 ] ; int x = 5 ; Ref < int > vart1 = new Ref < int > ( delegate ( ) { return x ; } ) ; Ref < int [ ] > vart2 = new Ref < int [ ] > ( delegate ( ) { return y ; } ) ; return vart1 ; } .method private hidebysig static class Program/Ref ` 1 < int32 > joik ( ) cil managed { // Code size 72 ( 0x48 ) .maxstack 3 .locals init ( [ 0 ] class Program/Ref ` 1 < int32 > vart1 , [ 1 ] class Program/Ref ` 1 < int32 [ ] > vart2 , [ 2 ] class Program/ ' < > c__DisplayClass2 ' ' < > 8__locals3 ' , [ 3 ] class Program/Ref ` 1 < int32 > CS $ 1 $ 0000 ) IL_0000 : newobj instance void Program/ ' < > c__DisplayClass2 ' : :.ctor ( ) IL_0005 : stloc.2 IL_0006 : nop IL_0007 : ldloc.2 IL_0008 : ldc.i4 0xc350 IL_000d : newarr [ mscorlib ] System.Int32 IL_0012 : stfld int32 [ ] Program/ ' < > c__DisplayClass2 ' : :y IL_0017 : ldloc.2 IL_0018 : ldc.i4.5 IL_0019 : stfld int32 Program/ ' < > c__DisplayClass2 ' : :x IL_001e : ldloc.2 IL_001f : ldftn instance int32 Program/ ' < > c__DisplayClass2 ' : : ' < joik > b__0 ' ( ) IL_0025 : newobj instance void class Program/Ref ` 1/Func ` 1 < int32 , int32 > : :.ctor ( object , native int ) IL_002a : newobj instance void class Program/Ref ` 1 < int32 > : :.ctor ( class Program/Ref ` 1/Func ` 1 < ! 0 , ! 0 > ) IL_002f : stloc.0 IL_0030 : ldloc.2 IL_0031 : ldftn instance int32 [ ] Program/ ' < > c__DisplayClass2 ' : : ' < joik > b__1 ' ( ) IL_0037 : newobj instance void class Program/Ref ` 1/Func ` 1 < int32 [ ] , int32 [ ] > : :.ctor ( object , native int ) IL_003c : newobj instance void class Program/Ref ` 1 < int32 [ ] > : :.ctor ( class Program/Ref ` 1/Func ` 1 < ! 0 , ! 0 > ) IL_0041 : stloc.1 IL_0042 : ldloc.0 IL_0043 : stloc.3 IL_0044 : br.s IL_0046 IL_0046 : ldloc.3 IL_0047 : ret } // end of method Program : :joik",Discrete Anonymous methods sharing a class ? "C_sharp : I 've got a piece of code the goes out and does an HttpWebRequest to Google Wallet . The code works just fine on all my machines , except for this one computer at work that I 'm on right now . The Internet on this computer works just fine ( as I 'm using it right now to type this question ) and we have no proxy server at work.The problem is that it just hangs . It does n't even timeout . It just hangs with no error message or anything and I have to force close it . Here is the code : Stepping through the code on the Visual Studio debugger , I know that it hangs when it hits the following line : Specifically , the request.GetResponse ( ) part is what 's hanging . Running Fiddler , all I see is a gray entry that looks like this : There is nothing else . No response body . Do anyone have any suggestions on what could be going on ? The fact that its happening on just this one computer tells me that it may not be a programming issue . private static string GetLoginHtml ( ) { var request = ( HttpWebRequest ) WebRequest.Create ( LoginUrl ) ; var cookieJar = new CookieContainer ( ) ; request.Method = `` POST '' ; request.ContentType = `` application/x-www-form-urlencoded '' ; request.CookieContainer = cookieJar ; using ( var requestStream = request.GetRequestStream ( ) ) { string content = `` Email= '' + Username + `` & Passwd= '' + Password ; requestStream.Write ( Encoding.UTF8.GetBytes ( content ) , 0 , Encoding.UTF8.GetBytes ( content ) .Length ) ; using ( var sr = new StreamReader ( request.GetResponse ( ) .GetResponseStream ( ) ) ) { string html = sr.ReadToEnd ( ) ; string galxValue = ParseOutValue ( html , `` GALX '' ) ; return GetLoginHtml2 ( galxValue , cookieJar ) ; } } } using ( var sr = new StreamReader ( request.GetResponse ( ) .GetResponseStream ( ) ) ) 3 200 HTTP Tunnel to accounts.google.com:443 0",HttpWebRequest just hanging on one computer "C_sharp : In one of my current applications , I need to get customer data from a remote service ( CRM ) via Webservice / SOAP . But I also want to cache the data in the mysql database , so that I dont need to connect to the webservice for the next time ( data does not change often , remote service is slow and has bandwidth limit - so caching is OK / a must ) . I am quite sure about the technical part of this task , but I am not so sure about how to implement this clean and transparent in my web app . All my other data comes from a single mysql database , so I repositories which return lists or single entities queried from the database with NHibernate . My ideas so far:1 all in oneUse a CustomerRepository , which looks for the customer by Id , if successfull , then return it , else call the webservice and save the retrieved data to the database . Controller looks like this : Repository in pseudo / simple code like this : Although the above looks somewhat straightforward , I think the CustomerRepository class will grow quite large and ugly . So I dont like that approach at all . A repository should only load data from the database , that should be its `` contract '' in my app at least . 2 sepereate and sticked together in the controllerUse seperate classes for the repository ( db access ) and webservice ( remote access ) and let the controller do the work : Controller looks like this : Although this looks a bit better , I still dont like to put all that logic in the controller , because error handling if the service does not return data is omitted and could probably clutter things a bit more.Maybe I could make another service layer used by the Controller , but the code would be quite the same , but in another class.Actually I would like to have my Controller use a single Interface/Class , which encapsulates that stuff , but I dont want one class which `` does it all '' : accessing the repository , accessing the webservice , saving the data ... it feels somewhat wrong to me ... All ideas so far are / will probably become quite bloated with caching code , error handling , etc . I think . Maybe I could clean up a few things using AOP ? How would you implement stuff like the above ? Technical frameworks used : ASP.NET MVC , Spring.NET for DI , NHibernate as ORM , mysql as database , the remote service is accessed via SOAP . class Controller { private CustomerRepository Rep ; public ActionResult SomeAction ( int id ) { return Json ( Rep.GetCustomerById ( id ) ) ; } } class CustomerRepository { public Customer GetCustomerById ( int id ) { var cached = Database.FindByPK ( id ) ; if ( cached ! = null ) return cached ; var webserviceData = Webservice.GetData ( id ) ; var customer = ConvertDataToCustomer ( webserviceData ) ; SaveCustomer ( customer ) ; return customer ; } } class Controller { private CustomerRepository Rep ; private Webservice Service ; public ActionResult SomeAction ( int id ) { var customer = Rep.GetCustomerById ( id ) ; if ( customer ! = null ) return Json ( customer ) ; var remote = Service.GetCustomerById ( id ) ; Rep.SaveCustomer ( remote ) ; return Json ( remote ) ; } }",Getting data from remote service if not cached in database - suggestion needed "C_sharp : There are lots of articles talking about how to use Structure Map with ASP.NET Core , but not very many talking about console applications or windows services . The default behavior in ASP.Net Core is that StructureMap creates a Nested Container per HTTPRequest so that a concrete class will be instantiated only once per HTTP Request.I am creating a .Net Core Windows Service using the PeterKottas.DotNetCore.WindowsService nuget package . I setup StructureMap using this article : https : //andrewlock.net/using-dependency-injection-in-a-net-core-console-application/My windows service is setup on a Timer and performs an action every X number of seconds . I want each of these actions to use a nested container similar to how ASP.NET does it . In other words , I want everything created for polling pass # 1 to be disposed of once that polling pass completes . When polling pass # 2 starts I want all new instances of objects to be instantiated . However , within the scope of a single polling pass I only want one instance of each object to be created.What is the proper way to do this ? Here is my program classHere is my WindowsService class : public class Program { public static ILoggerFactory LoggerFactory ; public static IConfigurationRoot Configuration ; static void Main ( string [ ] args ) { var applicationBaseDirectory = AppContext.BaseDirectory ; string environment = Environment.GetEnvironmentVariable ( `` ASPNETCORE_ENVIRONMENT '' ) ; if ( string.IsNullOrWhiteSpace ( environment ) ) throw new ArgumentNullException ( `` Environment not found in ASPNETCORE_ENVIRONMENT '' ) ; ConfigureApplication ( applicationBaseDirectory , environment ) ; var serviceCollection = ConfigureServices ( ) ; var serviceProvider = ConfigureIoC ( serviceCollection ) ; ConfigureLogging ( serviceProvider ) ; var logger = LoggerFactory.CreateLogger < Program > ( ) ; logger.LogInformation ( `` Starting Application '' ) ; ServiceRunner < IWindowsService > .Run ( config = > { var applicationName = typeof ( Program ) .Namespace ; config.SetName ( $ '' { applicationName } '' ) ; config.SetDisplayName ( $ '' { applicationName } '' ) ; config.SetDescription ( $ '' Service that matches Previous Buyers to Vehicles In Inventory to Fine Upgrade Opportunities . `` ) ; config.Service ( serviceConfig = > { serviceConfig.ServiceFactory ( ( extraArgs , microServiceController ) = > { return serviceProvider.GetService < IWindowsService > ( ) ; } ) ; serviceConfig.OnStart ( ( service , extraArgs ) = > { logger.LogInformation ( $ '' Service { applicationName } started . `` ) ; service.Start ( ) ; } ) ; serviceConfig.OnStop ( ( service = > { logger.LogInformation ( $ '' Service { applicationName } stopped . `` ) ; service.Stop ( ) ; } ) ) ; serviceConfig.OnError ( error = > { logger.LogError ( $ '' Service { applicationName } encountered an error with the following exception : \n { error.Message } '' ) ; } ) ; } ) ; } ) ; } private static void ConfigureApplication ( string applicationBaseDirectory , string environment ) { Directory.SetCurrentDirectory ( AppDomain.CurrentDomain.BaseDirectory ) ; var builder = new ConfigurationBuilder ( ) .SetBasePath ( applicationBaseDirectory ) .AddJsonFile ( `` appsettings.json '' ) .AddJsonFile ( $ '' appsettings . { environment } .json '' , optional : true ) .AddEnvironmentVariables ( ) ; Configuration = builder.Build ( ) ; } private static IServiceCollection ConfigureServices ( ) { var serviceCollection = new ServiceCollection ( ) .AddLogging ( ) .AddOptions ( ) ; serviceCollection.AddDbContext < JandLReportingContext > ( options = > options.UseSqlServer ( Configuration.GetConnectionString ( `` JandLReporting '' ) ) , ServiceLifetime.Transient ) ; //serviceCollection.AddDbContext < JLMIDBContext > ( options = > options.UseSqlServer ( Configuration.GetConnectionString ( `` JLMIDB '' ) ) , ServiceLifetime.Scoped ) ; serviceCollection.Configure < TimerSettings > ( Configuration.GetSection ( `` TimerSettings '' ) ) ; serviceCollection.Configure < AppSettings > ( Configuration.GetSection ( `` AppSettings '' ) ) ; return serviceCollection ; } private static IServiceProvider ConfigureIoC ( IServiceCollection serviceCollection ) { //Setup StructureMap var container = new Container ( ) ; container.Configure ( config = > { config.Scan ( scan = > { scan.AssemblyContainingType ( typeof ( Program ) ) ; scan.AssembliesFromApplicationBaseDirectory ( ) ; scan.AssembliesAndExecutablesFromApplicationBaseDirectory ( ) ; scan.WithDefaultConventions ( ) ; } ) ; config.Populate ( serviceCollection ) ; } ) ; return container.GetInstance < IServiceProvider > ( ) ; } private static void ConfigureLogging ( IServiceProvider serviceProvider ) { LoggerFactory = serviceProvider.GetService < ILoggerFactory > ( ) .AddConsole ( Configuration.GetSection ( `` Logging '' ) ) .AddFile ( Configuration.GetSection ( `` Logging '' ) ) .AddDebug ( ) ; } } public class WindowsService : MicroService , IWindowsService { private readonly ILogger _logger ; private readonly IServiceProvider _serviceProvider ; private readonly TimerSettings _timerSettings ; public WindowsService ( ILogger < WindowsService > logger , IServiceProvider serviceProvider , IOptions < TimerSettings > timerSettings ) { _logger = logger ; _serviceProvider = serviceProvider ; _timerSettings = timerSettings.Value ; } public void Start ( ) { StartBase ( ) ; Timers.Start ( `` ServiceTimer '' , GetTimerInterval ( ) , async ( ) = > { await PollingPassAsyc ( ) ; } , ( error ) = > { _logger.LogCritical ( $ '' Exception while starting the service : { error } \n '' ) ; } ) ; } private async Task PollingPassAsyc ( ) { using ( var upgradeOpportunityService = _serviceProvider.GetService < IUpgradeOpportunityService > ( ) ) { await upgradeOpportunityService.FindUpgradeOpportunitiesAsync ( ) ; } } private int GetTimerInterval ( ) { return _timerSettings.IntervalMinutes * 60 * 1000 ; } public void Stop ( ) { StopBase ( ) ; _logger.LogInformation ( $ '' Service has stopped '' ) ; } }",StructureMap .Net Core Windows Service Nested Containers "C_sharp : The following code results in slow1 = 1323 ms , slow2 = 1311 ms and fast = 897 ms. How is that possible ? Here : Nested or not nested if-blocks ? they mention that Any modern compiler , and by that I mean anything built in the past 20 years , will compile these to the same code . let s = System.Diagnostics.Stopwatch ( ) let mutable a = 1s.Start ( ) for i in 0 .. 1000000000 do if i < 0 then if i < 0 then a < - 4printfn `` fast = % d '' s.ElapsedMillisecondss.Restart ( ) for i in 0 .. 1000000000 do if i < 0 & & i < 0 then a < - 4printfn `` slow1 = % d '' s.ElapsedMillisecondss.Restart ( ) for i in 0 .. 1000000000 do if i < 0 & i < 0 then a < - 4printfn `` slow2 = % d '' s.ElapsedMilliseconds",`` nested if '' versus `` if and '' performance using F # "C_sharp : My method which calls SQL Server returns a DataReader but because of what I need to do - which is return the DataReader to the calling method which resides in a page code-behind - I ca n't close the connection in the class of the method which calls SQL server . Due to this , I have no finally or using blocks.Is the correct way of disposing resources to make the class implement IDisposable ? Alternatively should I explicitly dispose the unmanaged resource ( class-level fields ) from the caller ? EDIT : I send the datareader back because I need to bind specific data from the datareader to a listitem control , so in the calling class ( Codebehind page ) , I do : new ListItem ( datareader [ `` dc '' ] ) ; ( along those lines ) .",Should I implement IDisposable here ? "C_sharp : I want that RegisterObjects be accessible from outside of the class , but also that the only way to populate the RegisterObjects list is through TryRegisterObject ( object o ) .Is this possible ? public class RegistrationManager { public List < object > RegisteredObjects ; public bool TryRegisterObject ( object o ) { // ... // Add or not to Registered // ... } }",Public List without Add "C_sharp : One of my clients had an app crash and i traced it due to this bug/feature i ca n't really explain.The WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) returns this string : - ? 2097695743Yes , that a minus , a space , a question mark and then the actual hash numbers.This is the code of a simple console app that show the weird behaviour.This is the text output : And this is a picture of the same output : My question is : How on earth is this possible ? UPDATE : the problem was with the funky windows settings for negative numbers . static void Main ( string [ ] args ) { Console.WriteLine ( `` From String : string name = WindowsIdentity.GetCurrent ( ) .Name '' ) ; string name = WindowsIdentity.GetCurrent ( ) .Name ; Console.WriteLine ( `` name : `` + name ) ; Console.WriteLine ( `` name.GetHashCode ( ) .GetType ( ) : `` + name.GetHashCode ( ) .GetType ( ) ) ; Console.WriteLine ( `` name.GetHashCode ( ) : `` + name.GetHashCode ( ) ) ; Console.WriteLine ( `` name.GetHashCode ( ) .ToString ( ) : `` + name.GetHashCode ( ) .ToString ( ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Direct '' ) ; Console.WriteLine ( `` WindowsIdentity.GetCurrent ( ) .Name : `` + WindowsIdentity.GetCurrent ( ) .Name ) ; Console.WriteLine ( `` WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) .GetType ( ) : `` + WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) .GetType ( ) ) ; Console.WriteLine ( `` WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) : `` + WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) ) ; Console.WriteLine ( `` WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) .ToString ( ) : `` + WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) .ToString ( ) ) ; Console.WriteLine ( ) ; Console.WriteLine ( ) ; Console.WriteLine ( `` Press Enter to continue '' ) ; Console.ReadLine ( ) ; } From String : string name = WindowsIdentity.GetCurrent ( ) .Namename : COMMARC\tjename.GetHashCode ( ) .GetType ( ) : System.Int32name.GetHashCode ( ) : - ? 2097695743name.GetHashCode ( ) .ToString ( ) : - ? 2097695743DirectWindowsIdentity.GetCurrent ( ) .Name : COMMARC\tjeWindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) .GetType ( ) : System.Int32WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) : - ? 2097695743WindowsIdentity.GetCurrent ( ) .Name.GetHashCode ( ) .ToString ( ) : - ? 2097695743Press Enter to continue",C # string.GetHashCode ( ) returns non int result "C_sharp : I need to create random numbers between 0 and upto 2 so I am using : My question is : will the sequence ever repeat / stop been random ? Should I recreate ( _random = new Random ( ) ; ) every day ? //field levelprivate static Random _random = new Random ( ) ; //used in a method_random.Next ( 0 , 2 )",Will Random.Next ever stop being random ? C_sharp : I have seen questions related to string builder but was not able to find relevant answer . My question is `` Is it wise to use string builder here ? if not how to use it wisely here '' .This method is going to run 100000 times . In order to save some memory I used stringbuilder here . but the problem is .ToString ( ) method . Anyway I will have to create a string using .ToString ( ) method so why not initialize filename as string rather than StringBuilder . All libraries method use string as a parameter not string builder why ? I think I got a lot of confusion in my concepts . internal bool isFileExists ( ) { StringBuilder fileName = new StringBuilder ( AppDomain.CurrentDomain.BaseDirectory + `` Registry\\ '' + postalCode + `` .html '' ) ; if ( System.IO.File.Exists ( fileName.ToString ( ) ) ) { return true ; } else { return false ; } },".ToString ( ) creates a new string from StringBuilder , so why not use string directly ?" "C_sharp : Confused and might be missing something simple..I 've gotI getbut , Queue < T > implements ICollection which defines SyncRoot as a public property.So , first of all , why is this hidden . Second , how can you hide a property of an interface you 're implementing ? var q = new Queue < object > ( ) ; lock ( q.SyncRoot ) { ... } Queue < T > does not provide a defintion for SyncRoot blah blah ...",How / Why is SyncRoot hidden on Queue < T > ? "C_sharp : While writing my own immutable ByteArray class that uses a byte array internally , I implemented the IStructuralEquatable interface . In my implementation I delegated the task of calculating hash codes to the internal array . While testing it , to my great surprise , I found that my two different arrays had the same structural hash code , i.e . they returned the same value from GetHashCode . To reproduce : IStructuralEquatable is quite new and unknown , but I read somewhere that it can be used to compare the contents of collections and arrays . Am I wrong , or is my .Net wrong ? Note that I am not talking about Object.GetHashCode ! Edit : So , I am apparently wrong as unequal objects may have equal hash codes . But is n't GetHashCode returning a somewhat randomly distributed set of values a requirement ? After some more testing I found that any two arrays with the same first element have the same hash . I still think this is strange behavior . IStructuralEquatable array11 = new int [ ] { 1 , 1 } ; IStructuralEquatable array12 = new int [ ] { 1 , 2 } ; IStructuralEquatable array22 = new int [ ] { 2 , 2 } ; var comparer = EqualityComparer < int > .Default ; Console.WriteLine ( array11.GetHashCode ( comparer ) ) ; // 32Console.WriteLine ( array12.GetHashCode ( comparer ) ) ; // 32Console.WriteLine ( array22.GetHashCode ( comparer ) ) ; // 64",Bug in Array.IStructuralEquatable.GetHashCode ? "C_sharp : How can I get Resharper to shove format strings into the resource file ? I have a MessageBox dialog that displays dynamic information like so : Note that the caption was easily localized to a resource file by Resharper , but I ca n't even get the option for the message body . Does the format markup automatically make this string non-localizable ? I would n't think so . I 'd hate to have to write my own code to work with the resource file if I can figure out how to make Resharper just send it there like it did for the other string . MessageBox.Show ( string.Format ( `` You have purchased ' { 0 } ' ( { 1 } ) . Currently , the value of { 0 } is { 2 : C } / share . `` , stock.Symbol , stock.CompanyName , stock.ValuePerShare ) , Resources.FrmMain_btnVoting_Click_Vote_Purchase , MessageBoxButtons.OK , MessageBoxIcon.Information ) ;",Resharper localize complex strings "C_sharp : I asked a question earlier and I got the tip to use XML deserialization to parse my XML contents to c # objects . After some googling and messing around I got a working deserialization , but I have a question.My XML file looks like this : ( This is just a part of the file ) I managed to deserialize this into objects and it works like it should.The problem is as follows : The < nd > elements under the < w > elements have a reference ID which is the same as an ID from a < n > element . It 's possible that multiple < w > elements have the same < n > element reference , hence the seperate < n > element.Currently code-wise I have a NodeReference object that represents the < nd > elements , but I want to directly link the Way class to the Node class based on the reference ID and the Node ID . So basically the Way class should have a List of Nodes rather than a list of NodeReferences . I should have a seperate list of nodes aswell to prevent Ways from having new instances with the same data ( e.g . If two Ways have a reference to the same Node they also should point to the same Node instance rather than two identical Node instances , if that makes sense.. ) I basically need to access the Lon/Lat/ID fields from a Node instance based on the NodeReference ID.Here 's my code : DataCollection classThe node classWayNodeReferenceReading the XML fileThanks in advance ! If you have questions or answers please do let me know ! < osm > < n id= '' 2638006578 '' l= '' 5.9295547 '' b= '' 52.5619519 '' / > < n id= '' 2638006579 '' l= '' 5.9301973 '' b= '' 52.5619526 '' / > < n id= '' 2638006581 '' l= '' 5.9303625 '' b= '' 52.5619565 '' / > < n id= '' 2638006583 '' l= '' 5.9389539 '' b= '' 52.5619577 '' / > < n id= '' 2638006589 '' l= '' 5.9386643 '' b= '' 52.5619733 '' / > < n id= '' 2638006590 '' l= '' 5.9296231 '' b= '' 52.5619760 '' / > < n id= '' 2638006595 '' l= '' 5.9358987 '' b= '' 52.5619864 '' / > < n id= '' 2638006596 '' l= '' 5.9335913 '' b= '' 52.5619865 '' / > < w id= '' 453071384 '' > < nd rf= '' 2638006581 '' / > < nd rf= '' 2638006590 '' / > < nd rf= '' 2638006596 '' / > < nd rf= '' 2638006583 '' / > < nd rf= '' 2638006578 '' / > < /w > < w id= '' 453071385 '' > < nd rf= '' 2638006596 '' / > < nd rf= '' 2638006578 '' / > < nd rf= '' 2638006581 '' / > < nd rf= '' 2638006583 '' / > < /w > < /osm > [ XmlRoot ( `` osm '' ) ] public class DataCollection { [ XmlElement ( `` n '' ) ] public List < Node > Nodes { get ; private set ; } [ XmlElement ( `` w '' ) ] public List < Way > Ways { get ; private set ; } public DataCollection ( ) { this.Nodes = new List < Node > ( ) ; this.Ways = new List < Way > ( ) ; } } [ Serializable ( ) ] public class Node { [ XmlAttribute ( `` id '' , DataType = `` long '' ) ] public long ID { get ; set ; } [ XmlAttribute ( `` w '' , DataType = `` double '' ) ] public double Lat { get ; set ; } [ XmlAttribute ( `` l '' , DataType = `` double '' ) ] public double Lon { get ; set ; } } [ Serializable ( ) ] public class Way { [ XmlAttribute ( `` id '' , DataType = `` long '' ) ] public long ID { get ; set ; } [ XmlElement ( `` nd '' ) ] public List < NodeReference > References { get ; private set ; } public Way ( ) { this.References = new List < NodeReference > ( ) ; } } [ Serializable ( ) ] public class NodeReference { [ XmlAttribute ( `` rf '' , DataType = `` long '' ) ] public long ReferenceID { get ; set ; } } public static void Read ( ) { XmlSerializer serializer = new XmlSerializer ( typeof ( DataCollection ) ) ; using ( FileStream fileStream = new FileStream ( @ '' path/to/file.xml '' , FileMode.Open ) ) { DataCollection result = ( DataCollection ) serializer.Deserialize ( fileStream ) ; // Example Requested usage : result.Ways [ 0 ] .Nodes } Console.Write ( `` '' ) ; }",C # XML Data Deserialization - Apply object relationship based on reference ID "C_sharp : How do I apply alpha mask , or clipping mask , so everything except the rectangle will be blurred ? I do the usual : GraphicsEffect- > EffectFactory- > Brush- > Set to SpriteVisual < Grid > < Image x : Name= '' BackgroundImage '' Source= '' /Assets/background.png '' / > < Rectangle x : Name= '' ClippingRect '' Margin= '' 50 '' Fill= '' # 30f0 '' / > < /Grid > var graphicsEffect = new BlendEffect { Mode = BlendEffectMode.Multiply , Background = new ColorSourceEffect { Name = `` Tint '' , Color = Windows.UI.Color.FromArgb ( 50,0,255,0 ) , } , Foreground = new GaussianBlurEffect ( ) { Name = `` Blur '' , Source = new CompositionEffectSourceParameter ( `` Backdrop '' ) , BlurAmount = ( float ) 20 , BorderMode = EffectBorderMode.Hard , } } ; var blurEffectFactory = _compositor.CreateEffectFactory ( graphicsEffect , new [ ] { `` Blur.BlurAmount '' , `` Tint.Color '' } ) ; var _brush = blurEffectFactory.CreateBrush ( ) ; _brush.SetSourceParameter ( `` Backdrop '' , _compositor.CreateBackdropBrush ( ) ) ; var blurSprite = _compositor.CreateSpriteVisual ( ) ; blurSprite.Size = new Vector2 ( ( float ) BackgroundImage.ActualWidth , ( float ) BackgroundImage.ActualHeight ) ; blurSprite.Brush = _brush ; ElementCompositionPreview.SetElementChildVisual ( BackgroundImage , blurSprite ) ;",how to apply mask to CompositionBrush "C_sharp : I am writing a desktop application in C # using the MVVM pattern with an Entity Framework model . I tend to use DependencyProperties in my VM 's and have come to ( generally ) prefer this system over implementing INotifyPropertyChanged . I would like to keep things consistent . My VM accesses the Entities in the Model and I have managed to keep things pretty separate - the View has no knowlege of the VM except for binding and command names and the Model has know knowlege of the VM . Using INotifyPropertyChanged in the VM , it seems pretty easy to update the Entities in the Model : ... where CurrentPerson is a Person object auto-created by the Entity Data Model . There is therefore no private field created specifically to store the Forename.With DependencyProperties , it appears that I would have to create a DP , add the default Property , using GetValue and Setvalue and then use the PropertyChangedCallback in order to update the CurrentPerson Entity . Calling a callback in this situation appears to be adding overhead for the sake of being consistent with my other VM's.The question is therefore whether one or other of these methods is the way I should do things ? In this instance , should I use a DependencyProperty or INotifyPropertyChanged ? One thing that should be pointed out is that this will potentially be a very large scale project ( with plugins and a lot of database accesses from different machines ) and that everything really should be as reusable , and the modules as `` disconnected '' , as possible . public string Forename { get { return CurrentPerson.Forename ; } set { if ( Forename ! = value ) { CurrentPerson.Forename = value ; NotifyPropertyChanged ( `` Forename '' ) ; } } }",Using DependencyProperty on ViewModel with Entity Framework "C_sharp : I spawn a foreground thread and a background thread , throwing an exception in each.As expected , the unhandled exception in the foreground thread terminates the process . However , the unhandled exception in the background thread just terminates the thread and does not bring the process to a halt , effectively going unobserved and failing silently.This program , therefore , produces the following output : This challenges my understanding about exception handling in threads . My understanding was that regardless of the nature of the thread , an unhandled exception , from v2.0 of the framework onwards , will bring the process to termination.Here is a quote from the documentation on this topic : The foreground or background status of a thread does not affect the outcome of an unhandled exception in the thread . In the .NET Framework version 2.0 , an unhandled exception in either foreground or background threads results in termination of the application . See Exceptions in Managed Threads.Further more , the page titled Exceptions in Managed Threads states as follows : Starting with the .NET Framework version 2.0 , the common language runtime allows most unhandled exceptions in threads to proceed naturally . In most cases this means that the unhandled exception causes the application to terminate . This is a significant change from the .NET Framework versions 1.0 and 1.1 , which provide a backstop for many unhandled exceptions — for example , unhandled exceptions in thread pool threads . See Change from Previous Versions later in this topic.ANOTHER INTERESTING OBSERVATIONInterestingly , if I cause the exception to be thrown in the completion callback instead of the actual action that is being done , the exception on the background thread in that case does cause a termination of the program . For code , please see below.YET ANOTHER INTERESTING OBSERVATIONFurther , even more interestingly , if you handle the exception in the action that you want to execute using APM , in the catch block ( set a breakpoint in the catch block in D2 ( ) ) , the Exception that appears has no stack trace other than the lambda being invoked . It has absolutely no information even about how it got there.Whereas this is not true for exceptions that you trap in a catch block in the completion callback , as in the case of D3 ( ) .I am using the C # 6.0 compiler in Visual Studio Community 2015 Edition and my program targets v4.5.2 of the .NET framework . using System ; using System.Threading ; namespace OriginalCallStackIsLostOnRethrow { class Program { static void Main ( string [ ] args ) { try { A2 ( ) ; // Uncomment this to see how the unhandled // exception in the foreground thread causes // the program to terminate // An exception in this foreground thread // *does* terminate the program // var t = new Thread ( ( ) = > { // throw new DivideByZeroException ( ) ; // } ) ; // t.Start ( ) ; } catch ( Exception ex ) { // I am not expecting anything from the // threads to come here , which is fine Console.WriteLine ( ex ) ; } finally { Console.WriteLine ( `` Press any key to exit ... '' ) ; Console.ReadKey ( ) ; } } static void A2 ( ) { B2 ( ) ; } static void B2 ( ) { C2 ( ) ; } static void C2 ( ) { D2 ( ) ; } static void D2 ( ) { Action action = ( ) = > { Console.WriteLine ( $ '' D2 called on worker # { Thread.CurrentThread.ManagedThreadId } . Exception will occur while running D2 '' ) ; throw new DivideByZeroException ( ) ; Console.WriteLine ( `` Do we get here ? Obviously not ! `` ) ; } ; action.BeginInvoke ( ar = > Console.WriteLine ( $ '' D2 completed on worker thread # { Thread.CurrentThread.ManagedThreadId } '' ) , null ) ; } } } Press any key to exit ... D2 called on worker # 6 . Exception will occur while running D2D2 completed on worker thread # 6 using System ; using System.Threading ; namespace OriginalCallStackIsLostOnRethrow { class Program { static void Main ( string [ ] args ) { try { // A2 ( ) ; A3 ( ) ; } catch ( Exception ex ) { Console.WriteLine ( ex ) ; } finally { Console.WriteLine ( `` Press any key to exit ... '' ) ; Console.ReadKey ( ) ; } } static void A2 ( ) { B2 ( ) ; } static void B2 ( ) { C2 ( ) ; } static void C2 ( ) { D2 ( ) ; } static void D2 ( ) { Action action = ( ) = > { try { Console.WriteLine ( $ '' D2 called on worker # { Thread.CurrentThread.ManagedThreadId } . Exception will occur while running D2 '' ) ; throw new DivideByZeroException ( ) ; // Console.WriteLine ( `` Do we get here ? Obviously not ! `` ) ; } catch ( Exception ex ) { Console.WriteLine ( ex ) ; } } ; action.BeginInvoke ( ar = > Console.WriteLine ( $ '' D2 completed on worker thread # { Thread.CurrentThread.ManagedThreadId } '' ) , null ) ; } static void A3 ( ) { B3 ( ) ; } static void B3 ( ) { C3 ( ) ; } static void C3 ( ) { D3 ( ) ; } static void D3 ( ) { Action action = ( ) = > { Console.WriteLine ( $ '' D2 called on worker # { Thread.CurrentThread.ManagedThreadId } . `` ) ; } ; action.BeginInvoke ( ar = > { Console.WriteLine ( $ '' D2 completed on worker thread # { Thread.CurrentThread.ManagedThreadId } . Oh , but wait ! Exception ! `` ) ; // This one on the completion callback does terminate the program throw new DivideByZeroException ( ) ; } , null ) ; } } }",Why does an unhandled exception in this background thread not terminate my process ? C_sharp : Im brand new to TPL dataflow so forgive me if this is a simple question.I have an input buffer block that takes a base class . How can I branch from there to a block based on the derived type ? So for example : Thanks ! var inputBlock = new BufferBlock < EventBase > ( ) ; //if EventBase is Meeting then go to block X//if EventBase is Appointment the go to block Y,How can I branch logic in TPL Dataflow ? "C_sharp : I am having some trouble with a custom circular progress bar control . I am trying to overlap the two of them at the lower right corner . It has a transparent background , which obviously in WinForms is showing the background , but has no effect on each other.Here is what I am seeing : I have been researching on stackoverflow , and have found a few answers to people having this issue with custom picturebox controls . Most of the solutions , seem to have no effect on the circular progress bar control . Some of the solutions I have tried is.I also have the code on the custom control for allowing transparent backgrounds . Obviously , as I stated , this does not effect overlapping controls.There is also a TransparentControl solution on stackoverflow which I saw people using . I have created the control , but either have no idea how to use it , or it does n't work in my situation . Here is the code from that control.Any assistance would be appreciated . This has been driving me nuts for hours . Thanks : ) UPDATE 1 : I tried using the following code snippet from examples posted below . This yielded the same results . I still have that blank space between the circular progress bars ( as seen in the picture ) . Still stumped . : ( UPDATE 2 : I tried setting the front circularprogressbar to use the back circularprogressbar as it 's parent in the FormLoad . That did n't work out either . It made them transparent to each other , but cut off any part of the top circularprogressbar that was n't within ' the boundaries of the back . protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams ; cp.ExStyle |= 0x20 ; return cp ; } } SetStyle ( ControlStyles.SupportsTransparentBackColor , true ) ; public class TransparentControl : Panel { public bool drag = false ; public bool enab = false ; private int m_opacity = 100 ; private int alpha ; public TransparentControl ( ) { SetStyle ( ControlStyles.SupportsTransparentBackColor , true ) ; SetStyle ( ControlStyles.Opaque , true ) ; this.BackColor = Color.Transparent ; } public int Opacity { get { if ( m_opacity > 100 ) { m_opacity = 100 ; } else if ( m_opacity < 1 ) { m_opacity = 1 ; } return this.m_opacity ; } set { this.m_opacity = value ; if ( this.Parent ! = null ) { Parent.Invalidate ( this.Bounds , true ) ; } } } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams ; cp.ExStyle = cp.ExStyle | 0x20 ; return cp ; } } protected override void OnPaint ( PaintEventArgs e ) { Graphics g = e.Graphics ; Rectangle bounds = new Rectangle ( 0 , 0 , this.Width - 1 , this.Height - 1 ) ; Color frmColor = this.Parent.BackColor ; Brush bckColor = default ( Brush ) ; alpha = ( m_opacity * 255 ) / 100 ; if ( drag ) { Color dragBckColor = default ( Color ) ; if ( BackColor ! = Color.Transparent ) { int Rb = BackColor.R * alpha / 255 + frmColor.R * ( 255 - alpha ) / 255 ; int Gb = BackColor.G * alpha / 255 + frmColor.G * ( 255 - alpha ) / 255 ; int Bb = BackColor.B * alpha / 255 + frmColor.B * ( 255 - alpha ) / 255 ; dragBckColor = Color.FromArgb ( Rb , Gb , Bb ) ; } else { dragBckColor = frmColor ; } alpha = 255 ; bckColor = new SolidBrush ( Color.FromArgb ( alpha , dragBckColor ) ) ; } else { bckColor = new SolidBrush ( Color.FromArgb ( alpha , this.BackColor ) ) ; } if ( this.BackColor ! = Color.Transparent | drag ) { g.FillRectangle ( bckColor , bounds ) ; } bckColor.Dispose ( ) ; g.Dispose ( ) ; base.OnPaint ( e ) ; } protected override void OnBackColorChanged ( EventArgs e ) { if ( this.Parent ! = null ) { Parent.Invalidate ( this.Bounds , true ) ; } base.OnBackColorChanged ( e ) ; } protected override void OnParentBackColorChanged ( EventArgs e ) { this.Invalidate ( ) ; base.OnParentBackColorChanged ( e ) ; } } Parent.Controls.Cast < Control > ( ) .Where ( c = > Parent.Controls.GetChildIndex ( c ) > Parent.Controls.GetChildIndex ( this ) ) .Where ( c = > c.Bounds.IntersectsWith ( this.Bounds ) ) .OrderByDescending ( c = > Parent.Controls.GetChildIndex ( c ) ) .ToList ( ) .ForEach ( c = > c.DrawToBitmap ( bmp , c.Bounds ) ) ; var pts = this.PointToScreen ( circularprogressbar1.Location ) ; pts = circularprogressbar2.PointToClient ( pts ) ; circularprogressbar1.Parent = circularprogressbar2 ; circularprogressbar1.Location = pts ;",Transparent Overlapping Circular Progress Bars ( Custom Control ) "C_sharp : Suppose I know that property Color of an object returns an enumeration that looks like this one : and I want to check that a specific object of unknown type ( that I know has Color property ) has Color set to Red . This is what I would do if I knew the object type : The problem is I do n't have a reference to the assembly with ColorEnum and do n't know the object type.So instead I have the following setup : and I can not cast because I do n't know the object type ( and the enum type ) . How should I check the Color ? does work but it looks like the worst examples of cargo cult code I 've seen in `` The Daily WTF '' .How do I do the check properly ? enum ColorEnum { Red , Green , Blue } ; ObjectType thatObject = obtainThatObject ( ) ; if ( thatObject.Color == ColorEnum.Red ) { //blah } dynamic thatObject = obtainThatObject ( ) ; if ( thatObject.Color.ToString ( ) == `` Red '' ) { //blah }",How do I check enum property when the property is obtained from dynamic in C # ? "C_sharp : From sample example 4 of MSDN `` Threading Tutorial '' Following code errors out at the line commented with `` -- -errors is here -- - '' .What is wrong ? using System ; using System.Threading ; public class MutexSample { static Mutex gM1 ; static Mutex gM2 ; const int ITERS = 100 ; static AutoResetEvent Event1 = new AutoResetEvent ( false ) ; static AutoResetEvent Event2 = new AutoResetEvent ( false ) ; static AutoResetEvent Event3 = new AutoResetEvent ( false ) ; static AutoResetEvent Event4 = new AutoResetEvent ( false ) ; public static void Main ( String [ ] args ) { Console.WriteLine ( `` Mutex Sample ... '' ) ; // Create Mutex initialOwned , with name of `` MyMutex '' . gM1 = new Mutex ( true , `` MyMutex '' ) ; // Create Mutex initialOwned , with no name . gM2 = new Mutex ( true ) ; Console.WriteLine ( `` - Main Owns gM1 and gM2 '' ) ; AutoResetEvent [ ] evs = new AutoResetEvent [ 4 ] ; evs [ 0 ] = Event1 ; // Event for t1 evs [ 1 ] = Event2 ; // Event for t2 evs [ 2 ] = Event3 ; // Event for t3 evs [ 3 ] = Event4 ; // Event for t4 MutexSample tm = new MutexSample ( ) ; Thread thread1 = new Thread ( new ThreadStart ( tm.t1Start ) ) ; Thread thread2 = new Thread ( new ThreadStart ( tm.t2Start ) ) ; Thread thread3 = new Thread ( new ThreadStart ( tm.t3Start ) ) ; Thread thread4 = new Thread ( new ThreadStart ( tm.t4Start ) ) ; thread1.Start ( ) ; // Does Mutex.WaitAll ( Mutex [ ] of gM1 and gM2 ) thread2.Start ( ) ; // Does Mutex.WaitOne ( Mutex gM1 ) thread3.Start ( ) ; // Does Mutex.WaitAny ( Mutex [ ] of gM1 and gM2 ) thread4.Start ( ) ; // Does Mutex.WaitOne ( Mutex gM2 ) Thread.Sleep ( 2000 ) ; Console.WriteLine ( `` - Main releases gM1 '' ) ; gM1.ReleaseMutex ( ) ; // t2 and t3 will end and signal Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` - Main releases gM2 '' ) ; gM2.ReleaseMutex ( ) ; // t1 and t4 will end and signal // Waiting until all four threads signal that they are done . WaitHandle.WaitAll ( evs ) ; Console.WriteLine ( `` ... Mutex Sample '' ) ; } public void t1Start ( ) { Console.WriteLine ( `` t1Start started , Mutex.WaitAll ( Mutex [ ] ) '' ) ; Mutex [ ] gMs = new Mutex [ 2 ] ; gMs [ 0 ] = gM1 ; // Create and load an array of Mutex for WaitAll call gMs [ 1 ] = gM2 ; Mutex.WaitAll ( gMs ) ; // Waits until both gM1 and gM2 are released Thread.Sleep ( 2000 ) ; Console.WriteLine ( `` t1Start finished , Mutex.WaitAll ( Mutex [ ] ) satisfied '' ) ; Event1.Set ( ) ; // AutoResetEvent.Set ( ) flagging method is done } public void t2Start ( ) { Console.WriteLine ( `` t2Start started , gM1.WaitOne ( ) '' ) ; gM1.WaitOne ( ) ; // Waits until Mutex gM1 is released -- -errors is here -- - Console.WriteLine ( `` t2Start finished , gM1.WaitOne ( ) satisfied '' ) ; Event2.Set ( ) ; // AutoResetEvent.Set ( ) flagging method is done } public void t3Start ( ) { Console.WriteLine ( `` t3Start started , Mutex.WaitAny ( Mutex [ ] ) '' ) ; Mutex [ ] gMs = new Mutex [ 2 ] ; gMs [ 0 ] = gM1 ; // Create and load an array of Mutex for WaitAny call gMs [ 1 ] = gM2 ; Mutex.WaitAny ( gMs ) ; // Waits until either Mutex is released Console.WriteLine ( `` t3Start finished , Mutex.WaitAny ( Mutex [ ] ) '' ) ; Event3.Set ( ) ; // AutoResetEvent.Set ( ) flagging method is done } public void t4Start ( ) { Console.WriteLine ( `` t4Start started , gM2.WaitOne ( ) '' ) ; gM2.WaitOne ( ) ; // Waits until Mutex gM2 is released Console.WriteLine ( `` t4Start finished , gM2.WaitOne ( ) '' ) ; Event4.Set ( ) ; // AutoResetEvent.Set ( ) flagging method is done } }",Why does MSDN sample from Threading Tutorial crash ? "C_sharp : I have a quick little application and wanted to give a try to develop using TDD . I 've never used TDD and actually did n't even know what it was until I found ASP.NET-MVC . ( My first MVC app had unit tests , but they were brittle , way coupled , took too much up keep , and were abandoned -- I 've come to learn unit tests ! = TDD ) .Background on app : I have a text dump of a purchase order read in as a string . I need to parse the text and return new purchase order number , new line item number , old purchase order number , old purchase order line number . Pretty simple.Right now I 'm only working on new purchase order details ( number/line ) and have a model like this : Now I want to add a method `` IsValid '' that should only be true if `` NewNumber '' and `` NewLine '' are both non-null . So I want to test it like : This is easy enough , but it seems like a bad compromise to allow public setters and a parameterless constructor . So the alternative is to feed in a 'purchaseOrderText ' value in the constructor , but then I 'm testing the code for 'GetNewNumber ' and 'GetNewLine ' as well.I 'm kind of stumped on how to write this as a testable class while trying to keep it locked up in terms of what makes sense for the model . This seems like it would be a common problem , so I 'm thinking I 'm just missing an obvious concept . public class PurchaseOrder { public string NewNumber { get ; private set ; } public string NewLine { get ; private set ; } new public PurchaseOrder ( string purchaseOrderText ) { NewNumber = GetNewNumber ( purchaseOrderText ) ; NewLine = GetNewLine ( purchaseOrderText ) ; } // ... definition of GetNewNumber / GetNewLine ... // both return null if they ca n't parse the text } public void Purchase_Order_Is_Valid_When_New_Purchase_Order_Number_And_Line_Number_Are_Not_Null ( ) { PurchaseOrder order = new PurchaseOrder ( ) { NewNumber = `` 123456 '' , NewLine = `` 001 '' } ; Assert.IsTrue ( order.IsValid ) ; }",TDD : Help with writing Testable Class "C_sharp : I found that $ attrs in vue is a very helpful thing in component design . If I have a component wrapping an `` a '' tag , I could use $ attrs to pass in all those native props without claiming them as parameters one by one . For example , I have a component like this : I have to declare parameters of `` Href , OnClick , Classes , Styles '' and so forth . But we know that tag `` a '' has huge amount of other attributes , like `` target , hreflang ... '' , not to mention `` input '' tag or so . I think it 's stupid to claim all of them as a unbelievable long parameter list.So dose Blazor provide such similar function for us developers ? < div > < a href= '' @ Href '' onclick= '' @ OnClick '' class= '' @ Classes '' style= '' @ Styles '' > @ Content < /a > < /div >",Does Blazor have some mechanism working like $ attrs in vue ? "C_sharp : Given these two statements ... The first statement returns false.The second statement returns true.I understand why the first statement returns false - when the boolean is boxed , it becomes a reference type , and the two references are not equal . But , why / how does the second statement result in true ? ( ( object ) false ) == ( ( object ) false ) ( ( object ) false ) .Equals ( ( object ) false )",What is the difference between using the == operator and the Equals method on a boxed boolean type ? "C_sharp : I 'm creating a Windows Form application which Dynamically creates controls based on data pulled from a Database.I have the code working great in the background which loads the data from the database and applies it to variables , the problem I am having is when trying to create the controls using this data , I get a multi-threading error ( Additional information : Cross-thread operation not valid : Control 'flowpanelMenuRules ' accessed from a thread other than the thread it was created on . ) I 'm using the BackgroundWorker_DoWork event and the code that fails is the following : The code before is a simple loop going through the variable ( which is pulled from the database ) and gathering the information.Has anybody had any experience in safely invoking the above line ? I just ca n't seem to get it to work at all : ( Thanks for the help , I can post more code if needed . Me.flowpanelMenuRules.Controls.Add ( PanelRule ( i ) )",VB/C # .net Dynamically Add Control Items with Background Worker "C_sharp : Using katana , why does the Startup class should not implement a respective interface , like for example : I think that it could be much more intuitive for the developers to understand what they should provide with to the WebApp.Start < T > method as the T argument instead of guessing and looking for examples , it should be more explicit : interface IStartup { void Configuration ( IAppBuilder app ) ; } public class MyStartup : IStartup { public void Configuration ( IAppBuilder app ) { ... } } public void Start < T > ( ) where T : IStartup","Why the required Startup class does't need to implement an appropriate interface , like IStartup ?" "C_sharp : I 've a class , say `` MyComputation '' which does a lot of computation in one long constructor . It takes typically about 20ms to run when executed on its own ( with no disk i/o or network operations ) . 100 or so instances of this class are created by a parent class , say `` ComputeParent '' , which queues them up in a ThreadPool as work items : '' myComputationCall '' looks like this : done_event is a static ManualResetEvent : I run ComputeParent about 500 or so times , for various input parameters . So I have a lot of nested classes . The problem is that the time it takes to execute ComputeParent gradually increases . There will be a certain amount of variation between how long it takes to run each particular ComputeParent , but the amount of time increases quite steadily ( geometrically , each successive iteration take longer by a longer amount ) .The memory consumption of the program does not noticably increase over time though it is quite high ( ~300MB ) . Its running on a computer with 8 logical cores , and the processor use seems to be very bursty . I 'm not sure what else might be relevant to the problem.I 'd prefer not to have to run ComputeParent through batch files , though the issue does not appear to arise when this is done . ThreadPool.QueueUserWorkItem ( myComputationCall , my_computation_data ) ; public static void myComputationCall ( Object my_computation_data ) { try { MyDataObject data = ( MyDataObject ) my_computation_data ; var computation_run = new MyComputation ( data.parameter1 , data.parameter2 ) ; data.result = computation_run.result ; } finally { if ( Interlocked.Decrement ( ref num_work_items_remaining ) == 0 ) done_event.Set ( ) ; } } private static ManualResetEvent done_event ; ... done_event = new ManualResetEvent ( false ) ;",C # ThreadPool application performance degrading over time "C_sharp : We all know that VB 's Nothing is similar , but not equivalent , to C # 's null . ( If you are not aware of that , have a look at this answer first . ) Just out of curiosity , I 'd like to know the following : Is there a VB.NET expression that always yields null ? To give a concrete example , take the following statement : Is it possible to replace ... with something , such that o is 5 when myBool is true and Nothing/null when myBool is false ? Obvious solutions that wo n't work : Nothing ( see the question to the linked answer above ) , DirectCast ( Nothing , Object ) ( throws a compile-time error with Option Strict On ) , DirectCast ( Nothing , Integer ? ) works for this example , but does not work in general ( if you replace 5 with 5.0 in this example , you 'd need to modify the cast ) .Obvious workarounds ( wo n't count as answers ) : Declare an Object variable or field , set it to Nothing and use that for ... , define a method or property that always returns Nothing , DirectCast the second parameter ( 5 ) to Object.Note : The example above is just an example . The question itself is written in bold . Dim o As Object = If ( myBool , 5 , ... )",Is there a VB.NET expression that *always* yields null ? "C_sharp : I opened our solution in Visual Studio 2015 yesterday and a few of our unit tests ( which ran fine in Visual Studio 2013 ) starting failing . Digger deeper I discovered it was because calling GetTypes ( ) on an assembly was returning different results . I 've been able to create a very simple test case to illustrate it.In both Visual Studio 2013 and 2015 I created a new console application using .NET Framework 4.5.2 . I put the following code in both projects.When I run in Visual Studio 2013 I get the following output ( as expected ) .VS2013Example.ProgramWhen I run in Visual Studio 2015 I get the following output ( not as expected ) .VS2015Example.ProgramVS2015Example.Program+ < > cSo what is that VS2015Example.Program+ < > c type ? Turns out it 's the lambda inside the .Where ( ) method . Yes , that 's right , somehow that local lambda is being exposed as a type . If I comment out the .Where ( ) in VS2015 then I no longer get that second line.I 've used Beyond Compare to compare the two .csproj files but the only differences are the VS version number , the project GUID , names of the default namespace and assembly , and the VS2015 one had a reference to System.Net.Http that the VS2013 one didn't.Has anyone else seen this ? Does anyone have an explanation as to why a local variable would be being exposed as a type at the assembly level ? class Program { static void Main ( string [ ] args ) { var types = typeof ( Program ) .Assembly.GetTypes ( ) .Where ( t = > ! t.IsAbstract & & t.IsClass ) ; foreach ( var type in types ) { Console.WriteLine ( type.FullName ) ; } Console.ReadKey ( ) ; } }",Behavior of Assembly.GetTypes ( ) changed in Visual Studio 2015 "C_sharp : I am trying to run the sample Vision API project . I basically copied and pasted the code Program.cs into my application and executed it.This line ( which is line # 36- # 37 in Program.cs ) throws a System.AggregateException in mscorlib.dll with Additional information : One or more errors occurred..By examining InnerException , I found out that the actual exception thrown is InvalidOperationException with Error deserializing JSON credential data..Nonetheless , my cloud project is a basic project , with a Service Account , and Cloud Vision API enabled , nothing else . I checked that my environment variable was set to the JSON file by writing : before the line above . The output of that ( just before the crash ) is ( something like ) : C : \Users\me\Documents\Projects\MyProject\MyProject-ba31aae6efa1.jsonI checked the file , and it is the file that I got when I enabled my service account . Every property in it looks fine ( i.e . project name is correct , path 's correct , ... ) .I installed the Google Cloud SDK and executed gcloud beta auth application-default login and authorized access to my cloud account.Any ideas on what might be causing this ? GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync ( ) .Result ; Console.WriteLine ( Environment.GetEnvironmentVariable ( `` GOOGLE_APPLICATION_CREDENTIALS '' ) ) ;",AggregateException when calling GetApplicationDefaultAsync ( ) "C_sharp : I know that when we use properties in C # , the compiler always generate getters and setters for them in CIL ( i.e. , get_PropertyName and set_PropertyName ) , for example , consider the following piece of code : This program will produce output with the methods of Test , among which there will be get_Name and set_Name - the getter and setters I was talking about.From my understanding then , if getters and setter are created `` behind the scenes '' then there should be a backing field created as well from which/to which the getters and setter get/set values.So , from the previous example , I can use reflection to inspect fields for Test class , like that : The ouput of this program is empty , I assume this is because the backing field that was created has private access , so we can not see it . But since I do n't know how to check it , can you please let me know if a backing field always gets created ( even if we have a simple property with only get ; and set ; ) ? class Program { class Test { public string Name { get ; set ; } } static void Main ( string [ ] args ) { //Here I 'm using reflection to inspect methods of Test class Type type = typeof ( Test ) ; foreach ( var item in type.GetMethods ( ) ) { Console.WriteLine ( item.Name ) ; } } } static void Main ( string [ ] args ) { Type type = typeof ( Test ) ; foreach ( var item in type.GetFields ( ) ) { Console.WriteLine ( item.Name ) ; } }",Do C # properties always have backup fields `` behind the scene '' ? "C_sharp : I 'm just reading this sample from the Dapper `` manual '' : Are the # t 's a special syntax for something ? Or are they just there to confuse me ? : ) connection.Execute ( @ '' set nocount on create table # t ( i int ) set nocount off insert # t select @ a a union all select @ b set nocount on drop table # t '' , new { a=1 , b=2 } ) .IsEqualTo ( 2 ) ;",Why the # ( hashes ) in Dapper sample "C_sharp : I am creating a simple ball and paddle program in C # and using mouse clicks to move the paddle . In order to register the mouse clicks , I have this The problem is that it does n't register a rapid succession of clicks . After one click , it takes about half a second to register the next click ( all clicks inbetween are lost ) . Is there a way for me to make the paddle move according to every click and register every click ? private void Form1_MouseClick ( object sender , MouseEventArgs e ) { if ( e.Button == MouseButtons.Right ) { paddle.movePaddleRight ( ) ; this.Invalidate ( ) ; } if ( e.Button == MouseButtons.Left ) { paddle.movePaddleLeft ( ) ; this.Invalidate ( ) ; } }",Faster MouseClick Response ? C_sharp : I have an async asp.net controller . This controller calls an async method . The method that actually performs the async IO work is deep down in my application . The series of methods between the controller and the last method in the chain are all marked with the async modifier . Here is an example of how I have the code setup : As you can see the controller calls C_Async ( x ) asynchronously then there is a chain of async methods to E_Async . There are methods between the controller and E_Async and all have the async modifier . Is there a performance penalty since there are methods using the async modifyer but not doing any async IO work ? Note : This is a simplified version of the real code there are more async methods between the controller and the E_Async method . public async Task < ActionResult > Index ( int [ ] ids ) { List < int > listOfDataPoints = dataPointService ( ids ) ; List < Task > dpTaskList = new List < Task > ( ) ; foreach ( var x in listOfDataPoints ) { dpTaskList.Add ( C_Async ( x ) ) ; } await Task.WhenAll ( dpTaskList ) ; return View ( ) ; } private async Task C_Async ( int id ) { //this method executes very fast var idTemp = paddID ( id ) ; await D_Async ( idTemp ) ; } private async Task D_Async ( string id ) { //this method executes very fast await E_Async ( id ) ; } private async Task E_Async ( string url ) { //this method performs the actual async IO result = await new WebClient ( ) .DownloadStringTaskAsync ( new Uri ( url ) ) saveContent ( result ) ; },async all the way down issue "C_sharp : I 've never posted a question of this nature before , so if it 's not proper for SO , just do n't hurt my feelings too bad and I 'll delete it.In the interest of keeping everything I care about as close to the left margin as possible , I keep wishing I could write something like : I think another reason is I like the extra screen real estate I get by using var when the type is already present on the right side of the assignment , but my brain has too many years of looking for the type on the left side . Then again , being stuck in my ways is n't such a good reason to wish for a spec ... DataService1.DataEntities dataEntities = new ( constructorArg1 , ... )",Has the C # spec ( team ? committee ? ) ever considered this object creation syntax ? "C_sharp : I 'm curious about how C # behaves when passing value/reference types into a method . I 'd like to pass a boxed value type into the method `` AddThree '' . The idea is to get in the caller function ( Main ) the result of the operations performed within `` AddThree '' .I 've tried this with pure reference types like string and I get the same result . If I `` wrap '' my int within a class and I use the `` wrap '' class in this example it works as I 'm expecting , ie , I get myBox = 6 . If I modify `` AddThree '' method signature to pass the parameter by ref , this also returns 6 . But , I do n't want to modify the signature or create a wrapper class , I want to just box the value . static void Main ( string [ ] args ) { int age = 3 ; object myBox = age ; AddThree ( myBox ) ; // here myBox = 3 but I was expecting to be = 6 } private static void AddThree ( object age2 ) { age2 = ( int ) age2 + 3 ; }",Boxing value type to send it to a method and get the result "C_sharp : I have a problem with the glfwSetCharCallback function . Whenever I call it , the glfwPollEvents throws an AccessViolationException saying : `` Attempted to read or write protected memory . This is often an indication that other memory is corrupt . `` I have created a very simple wrapper just to demonstrate the problem : And I call it like I would GLFW : The character is printed into the console and I get the AccessViolationException.What am I doing incorrectly ? All the DllImports specify the CDecl calling convention ( I 've tried the others on both PollEvents and SetCharCallback ) , I 've tried all CharSets on the SetCharCallback function and nothing worked.Could someone please help me ? Edit : Here is the GLFW3 Dll that I 'm using : http : //www.mediafire.com/ ? n4uc2bdiwdzdddaEdit 2 : Using the newest `` lib-msvc110 '' DLL made glfwSetCharCallback work . glfwSetKeyCallback and glfwSetCursorPosCallback do not work and continue to throw AccessViolationException . I will attempt to figure out what makes CharCallback so special , but honestly , I 've gone through the GLFW source code through and through and all the functions seem to do their thing in the same way . Maybe there 's something I 'm overlooking.Edit 3 : I 've tried everything , cdecl , stdcall , all the charsets , all versions of the dll , all combinations of arguments , etc . I 've made sure that the callbacks are not disposed by storing a reference to them . I 've also tried to purposefully crash the application by not reserving any space of arguments of glfwSetCharCallback ( which works as of now ) and I have n't managed to do it . This leads me to believe that the arguments themselves have no bearing on the application.The thing that really makes me think the fault is with GLFW itself is the fact that if I compile against the x86-64 dll , everything works perfectly . It is a little bit strange to use cdecl on x86-64 , because MSDN specifically states that the only calling convention is fastcall . using System ; using System.Runtime.InteropServices ; using System.Security ; namespace Test { public delegate void GlfwCharCallback ( GlfwWindow window , Char character ) ; [ StructLayout ( LayoutKind.Explicit ) ] public struct GlfwMonitor { private GlfwMonitor ( IntPtr ptr ) { _nativePtr = ptr ; } [ FieldOffset ( 0 ) ] private readonly IntPtr _nativePtr ; public static readonly GlfwMonitor Null = new GlfwMonitor ( IntPtr.Zero ) ; } [ StructLayout ( LayoutKind.Explicit ) ] public struct GlfwWindow { private GlfwWindow ( IntPtr ptr ) { _nativePtr = ptr ; } [ FieldOffset ( 0 ) ] private readonly IntPtr _nativePtr ; public static GlfwWindow Null = new GlfwWindow ( IntPtr.Zero ) ; } public class Wrap { [ DllImport ( `` GLFW3 '' , CallingConvention = CallingConvention.Cdecl ) , SuppressUnmanagedCodeSecurity ] private static extern Int32 glfwInit ( ) ; [ DllImport ( `` GLFW3 '' , CallingConvention = CallingConvention.Cdecl ) , SuppressUnmanagedCodeSecurity ] internal static extern GlfwWindow glfwCreateWindow ( Int32 width , Int32 height , [ MarshalAs ( UnmanagedType.LPStr ) ] String title , GlfwMonitor monitor , GlfwWindow share ) ; [ DllImport ( `` GLFW3 '' , CallingConvention = CallingConvention.Cdecl ) , SuppressUnmanagedCodeSecurity ] internal static extern void glfwSetCharCallback ( GlfwWindow window , GlfwCharCallback callback ) ; [ DllImport ( `` GLFW3 '' , CallingConvention = CallingConvention.Cdecl ) , SuppressUnmanagedCodeSecurity ] internal static extern void glfwPollEvents ( ) ; public static Boolean Init ( ) { return glfwInit ( ) == 1 ; } public static GlfwWindow CreateWindow ( Int32 width , Int32 height , String title , GlfwMonitor monitor , GlfwWindow share ) { return glfwCreateWindow ( width , height , title , monitor , share ) ; } public static void SetCharCallback ( GlfwWindow window , GlfwCharCallback callback ) { glfwSetCharCallback ( window , callback ) ; } public static void PollEvents ( ) { glfwPollEvents ( ) ; } } } using System ; namespace Test { class Program { static void Main ( ) { Wrap.Init ( ) ; var window = Wrap.CreateWindow ( 800 , 600 , `` None '' , GlfwMonitor.Null , GlfwWindow.Null ) ; Wrap.SetCharCallback ( window , ( glfwWindow , character ) = > Console.WriteLine ( character ) ) ; while ( true ) { Wrap.PollEvents ( ) ; } } } }",AccessViolationException with GLFW in C # "C_sharp : I 've seen ( and used ) on various projects this layout , with a group of fields followed by a group of properties : And I 've also encountered this layout with fields next to their property : Is there a reason to consider one better than the other ? I think most coding standards recommend Option # 1 , but sometimes it 's handy having the field next to the property that operates on it.Note : I 'm assuming non-trivial properties that ca n't use auto-implemented properties . private int MyIntField ; private string MyStringField ; public int MyInt { get { return MyIntField ; } set { MyIntField = value ; } } public string MyString { get { return MyStringField ; } set { MyStringField = value ; } } private int MyIntField ; public int MyInt { get { return MyIntField ; } set { MyIntField = value ; } } private string MyStringField ; public string MyString { get { return MyStringField ; } set { MyStringField = value ; } }",Do you group private fields or put them with their property ? "C_sharp : I had a little dispute ( which was very close to holy war : ) ) with my colleage , about the performance of access to list via indeces VS via enumerator . To operate with some facts , I wrote the following test : Actually , it just accesses the elements.As I expected , index access was faster . This are the results of Release build on my machine : However , I decided to change test a little : And now output was following : If we are enumerating the same list via interface , the performance is 2 times slower ! Why does this* happening ? this means `` enumerating via interface 2 times slower than enumerating the actual list '' .My guess is that runtime is using different Enumerators : the list 's in first test and a generic one in the second test . static void Main ( string [ ] args ) { const int count = 10000000 ; var stopwatch = new Stopwatch ( ) ; var list = new List < int > ( count ) ; var rnd = new Random ( ) ; for ( int i = 0 ; i < count ; i++ ) { list.Add ( rnd.Next ( ) ) ; } const int repeat = 20 ; double indeces = 0 ; double forEach = 0 ; for ( int iteration = 0 ; iteration < repeat ; iteration++ ) { stopwatch.Restart ( ) ; long tmp = 0 ; for ( int i = 0 ; i < count ; i++ ) { tmp += list [ i ] ; } indeces += stopwatch.Elapsed.TotalSeconds ; stopwatch.Restart ( ) ; foreach ( var integer in list ) { tmp += integer ; } forEach += stopwatch.Elapsed.TotalSeconds ; } Console.WriteLine ( indeces /repeat ) ; Console.WriteLine ( forEach /repeat ) ; } 0.0347//index access 0.0737//enumerating //the same as before ... IEnumerable < int > listAsEnumerable = list ; //the same as before ... foreach ( var integer in listAsEnumerable ) { tmp += integer ; } ... 0.0321//index access 0.1246//enumerating ( 2x slower ! )",Enumerating via interface - performance loss "C_sharp : There is sizeof ( ) and typeof ( ) , but why not a memberinfo ( ) returning an instance of System.Reflection.MemberInfo for the part of code selected in order to aid in reflection code.Example : I am trying to understand if there is a fundamental reason why this could be implemented in the C # spec.I am not bashing anything , I am just doing some wishful thinking , so be kind please . Program ( ) { Type t = typeof ( Foo ) ; Foo foo = new Foo ( ) ; PropertyInfo pi = memberinfo ( Foo.Name ) as PropertyInfo ; // or shall it be like this // PropertyInfo pi = memberinfo ( foo.Name ) as PropertyInfo ; string name = pi.GetValue ( foo , null ) ; }",Why not a memberinfo ( ) reflection function for C # "C_sharp : My question is very similar to the following two questions but I have an added requirement that these do not satisfy.How to set property value using Expressions ? How set value a property selector Expression < Func < T , TResult > > Just like those questions , I have an Expression < Func < TEntity , TProperty > > where I want to set a value to the specified property . And those solutions work great if the body of the expression is only one level deep , such as x = > x.FirstName but they do n't work at all if that body is deeper , like x = > x.Parent.FirstName.Is there some way to take this deeper expression and set the value to it ? I do n't need a terribly robust execution-deferred solution but I do need something that I can execute on an object and it would work whether 1-level or multiple levels deep . I also need to support most typical types you 'd expect in a database ( long , int ? , string , Decimal , DateTime ? , etc . although I do n't care about more complex things like geo types ) .For conversation 's sake , let 's say we 're working with these objects although assume we need to handle N levels deep , not just 1 or 2 : and let 's say this is our unit test : and our extension method we 're looking at ( I 'm not set on it needing to be an extension method but it seems simple enough ) would look like this : P.S . This version of code was written in the SO editor - my apologies for dumb syntax issues but this should be darn close ! # LockedDownWorkstationsSuck public class Parent { public string FirstName { get ; set ; } } public class Child { public Child ( ) { Mom = new Parent ( ) ; // so we do n't have to worry about nulls } public string FavoriteToy { get ; set ; } public Parent Mom { get ; set ; } } [ TestFixture ] public class Tests { [ Test ] public void MyTest ( ) { var kid = new Child ( ) ; Expression < Func < Child , string > > momNameSelector = ( ch = > ch.Mom.FirstName ) ; Expression < Func < Child , string > > toyNameSelector = ( ch = > ch.FavoriteToy ) ; kid.ExecuteMagicSetter ( momNameSelector , `` Jane '' ) ; kid.ExecuteMagicSetter ( toyNameSelector , `` Bopp-It ! `` ) ; Assert.That ( kid.Mom.FirstName , Is.EqualTo ( `` Jane '' ) ) ; Assert.That ( kid.FavoriteToy , Is.EqualTo ( `` Bopp-It ! `` ) ) ; } } public static TEntity ExecuteMagicSetter < TEntity , TProperty > ( this TEntity obj , Expression < Func < TEntity , TProperty > > selector , TProperty value ) where TEntity : class , new ( ) // I do n't require this but I can allow this restriction if it helps { // magic }",How to set a value from an Expression for nested levels of depthness ? "C_sharp : I have a question about async\await in a C # .NET app . I 'm actually trying to solve this problem in a Kinect based application but to help me illustrate , I 've crafted this analogous example : Imagine that we have a Timer , called timer1 which has a Timer1_Tick event set up . Now , the only action I take on that event is to update the UI with the current date time.This is simple enough , my UI updates every few hundredths of seconds and I can happily watch time go by.Now imagine that I also want to also calculate the first 500 prime numbers in the same method like so : This is when I experience the problem . The intensive method that calculates the prime numbers blocks the event handler from being run - hence my timer text box now only updates every 30 seconds or so.My question is , how can I resolve this while observing the following rules : I need my UI timer textbox to be as smooth as it was before , probably by pushing the intensive prime number calculation to a different thread . I guess , this would enable the event handler to run as frequently as before because the blocking statement is no longer there.Each time the prime number calculation function finishes , it 's result to be written to the screen ( using my PrintPrimeNumbersToScreen ( ) function ) and it should be immediately started again , just in case those prime numbers change of course.I have tried to do some things with async/await and making my prime number calculation function return a Task > but have n't managed to resolve my problem . The await call in the Timer1_Tick event still seems to block , preventing further execution of the handler.Any help would be gladly appreciated - I 'm very good at accepting correct answers : ) Update : I am very grateful to @ sstan who was able to provide a neat solution to this problem . However , I 'm having trouble applying this to my real Kinect-based situation . As I am a little concerned about making this question too specific , I have posted the follow up as a new question here : Kinect Frame Arrived Asynchronous private void Timer1_Tick ( object sender , EventArgs e ) { txtTimerValue.Text = DateTime.Now.ToString ( `` hh : mm : ss.FFF '' , CultureInfo.InvariantCulture ) ; } private void Timer1_Tick ( object sender , EventArgs e ) { txtTimerValue.Text = DateTime.Now.ToString ( `` hh : mm : ss.FFF '' , CultureInfo.InvariantCulture ) ; List < int > primeNumbersList = WorkOutFirstNPrimeNumbers ( 500 ) ; PrintPrimeNumbersToScreen ( primeNumbersList ) ; } private List < int > WorkOutFirstNPrimeNumbers ( int n ) { List < int > primeNumbersList = new List < int > ( ) ; txtPrimeAnswers.Clear ( ) ; int counter = 1 ; while ( primeNumbersList.Count < n ) { if ( DetermineIfPrime ( counter ) ) { primeNumbersList.Add ( counter ) ; } counter++ ; } return primeNumbersList ; } private bool DetermineIfPrime ( int n ) { for ( int i = 2 ; i < n ; i++ ) { if ( n % i == 0 ) { return false ; } } return true ; } private void PrintPrimeNumbersToScreen ( List < int > primeNumbersList ) { foreach ( int primeNumber in primeNumbersList ) { txtPrimeAnswers.Text += String.Format ( `` The value { 0 } is prime \r\n '' , primeNumber ) ; } }",Async Await to Keep Event Firing C_sharp : What I want : I 'm trying to store complex data types in roaming settings . This is how my object looks like : What is the problem : is giving an error : Data type not supportedWhat I have tried : Storing different members of Query class in different fields of composite settings . But the data members of Query class are again objects of different classes and hence can not be stored in composite.Values [ `` setting '' ] . Please refer : windows 8 app roaming storage with custom class . That question was answered by using the composite setting but is not applicable to mine.How do I proceed ? public abstract class Query { [ DataMember ] public Cube Cube { get ; private set ; } [ DataMember ] public List < Filter > Filters { get ; private set ; } [ DataMember ] public Slicer Slicer { get ; set ; } } Query q = ... ; RoamingSettings.Values [ `` query '' ] = q ;,storing complex data type in roaming settings "C_sharp : I 'm unable to get the desired result from JSON controller Action . I have searched the internet but no suggested solutions could solve my problem.My Controller Action : This is my jQuery ajax file : It is not returning productId , I have got error on this line : It is saying /Category/Details/undefined but I want id here instead of undefined . Please help . public JsonResult AutoComplete ( string term ) { var result = ( from c in db.CategoryContents where c.Title.ToLower ( ) .Contains ( term.ToLower ( ) ) select new { c.Title , c.ImageURL , Description = c.Category.Name + `` Review '' } ) .Distinct ( ) ; return Json ( result , JsonRequestBehavior.AllowGet ) ; } $ ( document ) .ready ( function ( ) { var displayLimit = 7 ; // jqueryui autocomplete configuration $ ( `` # term '' ) .autocomplete ( { source : function ( req , resp ) { // get JSON object from SearchController $ .ajax ( { url : `` /Search/AutoComplete '' , // SearchController JsonResult type : `` POST '' , dataType : `` json '' , data : { term : req.term } , success : function ( data ) { resp ( $ .map ( data , function ( item ) { return { label : item.Name , value : item.Name , imageURL : item.ImageURL , id : item.ID } ; } ) ) ; } } ) ; } , select : function ( event , ui ) { // keyword selected ; parse values and forward off to ProductController 's ViewProduct View var selected = ui.item ; var mdlNum , mdlName ; if ( selected.value ! == null ) { var array = selected.value.split ( ' ' ) ; mdlNum = array [ 0 ] .toLowerCase ( ) ; // mdlName = selected.value.replace ( array [ 0 ] , `` ) .trim ( ) .toLowerCase ( ) .replace ( / [ ^a-z0-9 ] +/g , ' ' ) ; // window.location.replace ( 'http : // ' + location.host + '/Search/Refine ? ref= ' + mdlNum + `` + mdlName ) ; window.location.replace ( 'http : // ' + location.host + '/Category/Details/ ' + ui.id ) ; } } , open : function ( ) { $ ( 'ul.ui-autocomplete ' ) .addClass ( 'opened ' ) } , close : function ( ) { $ ( 'ul.ui-autocomplete ' ) .removeClass ( 'opened ' ) .css ( 'display ' , 'block ' ) ; } } ) .data ( `` ui-autocomplete '' ) ._renderItem = function ( ul , item ) { //var inner_html = ' < a > < div id= '' example '' class= '' k-content '' > < div class= '' demo-section '' > < div class= '' .customers-list img '' > < img src= '' ' + `` ../common/theme/images/gallery/3.jpg '' + ' '' > < /div > < div class= '' customers-list h3 '' > ' + item.label + ' < /div > < div class= '' customers-list p '' > ' + item.description + ' < /div > < /div > < /div > < /a > ' ; var newText = String ( item.value ) .replace ( new RegExp ( this.term , `` gi '' ) , `` < strong > $ & < /strong > '' // `` < span class='ui-state-highlight ' > $ & < /span > '' ) ; var inner_html = ' < a > < div class= '' list_item_container '' > < div class= '' image '' > < img src= '' ' + item.imageURL + ' '' alt= '' '' / > < /div > < div class= '' labels '' > ' + newText + ' < /div > < div class= '' description '' > ' + item.id + ' < /div > < /div > < /a > ' ; return $ ( `` < li > < /li > '' ) .data ( `` item.autocomplete '' , item ) .append ( inner_html ) .appendTo ( ul ) ; } ; window.location.replace ( 'http : // ' + location.host + '/Category/Details/ ' + ui.id ) ;",Unable to retrieve value from json result MVC 4 "C_sharp : My scenario is about developing Math Problems . As a IProblem interface , I thought that the two main properties that it should contain are QuestionText and Response . QuestionText always will be a string , but Response sometimes can be a complex object ( a custom Fraction struc ) or another datatype like string , decimal , int , etc.As you can see , Response is object . I guessed this datatype because all problems by nature have a response . And as it 's an object , I define only get for future errors ( casting problems ) .My idea is later , in a concrete class to access to this property ( Response ) , without the necessity to cast . Check it out ? And here I 'm testing the value.Until now , it works , but I want to know if what I 'm doing is correct or a good practice . I 've seen another people use new operator to do this . Others do n't use the word base.Is this a good way ? Can it be causing future errors ? Please , give me a feedback about my design.EDIT : It 's really necessary to access to the Response in a non-generic interface . public interface IProblem { string QuestionText { get ; set ; } object Response { get ; } bool IsComplete ( ) ; bool IsCorrect ( ) ; } public abstract class Problem : IProblem { public string QuestionText { get ; set ; } public object Response { get ; protected set ; } public virtual bool IsComplete ( ) { return true ; } public abstract bool IsCorrect ( ) ; } public class BinaryProblem : Problem { public decimal N1 { get ; set ; } public decimal N2 { get ; set ; } public decimal Response { get { return ( decimal ) base.Response ; } set { base.Response = value ; } } public override bool IsCorrect ( ) { return N1 + N2 == Response ; } } static void Main ( string [ ] args ) { BinaryProblem p = new BinaryProblem ( ) ; p.N1 = 2 ; p.N2 = 4 ; p.Response = 6 ; IProblem p2 = p ; Console.WriteLine ( p2.Response ) ; Console.WriteLine ( p2.IsComplete ( ) .ToString ( ) ) ; }",How to encapsulate a property in a base class ? "C_sharp : Goal : Our application is built using multiple types ( e.g . Person , PersonSite ( ICollection ) , Site - I selected those classes because they have a relationship ) . What we want to do is to be able to export some properties from the first type ( Person ) in an excel table and then export some other properties from the second type ( PersonSite ) inside the same excel file but in a new table on the same sheet.The result should look like this : So for every PersonSite contained in the list , we would like to create a table that will be inserted just after the table of the Person.So this is how look the Person class ( subset of the class ) : Now the PersonSite class ( subset ) : The Site class ( subset ) : So we decided to write a CSVExporter class that use expressions to retrieve the properties that must be exported.This is the scheme we have to implement this : So the CSVTable use a generic type that is IObject ( as used in the different classes ) .A table can have multiple table ( e.g . The Person table has a PersonSite table and a PersonSite table has a Site table ) . But the type used is different since we navigate through the different classes ( those classes must have a relationship ) .When adding a subtable to a table we should provide en expression that will grab the items of the correct type from the main items ( Person = > Person.PersonSite ) So we wrote the following piece of code for the table : And finally here is the CSVExportTableColumn class : Has anyone ever done something like that ? Or are we heading to the wrong path ? If this seems to be a good path , how can we create the link ( relationship ) expression and use it to retrieve the correct items to use on the last call ? _________________ ________________________ ________________| | | | | ||PERSON PROPERTIES| | PERSONSITE PROPERTIES | |SITE PROPERTIES ||_________________| |________________________| |________________|| Name Person 1 | |Relation type for item 1| | Name for item 1||_________________| |________________________| |________________| |Relation type for item 2| | Name for item 2| |________________________| |________________| |Relation type for item 3| | Name for item 3| |________________________| |________________| _________________ ________________________ ________________| Name Person 2 | |Relation type for item 1| | Name for item 1||_________________| |________________________| |________________| |Relation type for item 2| | Name for item 1| |________________________| |________________| public class Person : IObject { public ICollection < PersonSite > PersonSites { get ; set ; } } public class PersonSite : IObject { public Person Person { get ; set ; } public Site Site { get ; set ; } public RelationType RelationType { get ; set ; } } public class Site : IObject { public ICollection < PersonSite > PersonSites { get ; set ; } } ____ | |0..* ______________ __|____|______ 1..* _______________| CSV EXPORTER |________| CSV TABLE ( T ) |__________| CSV COLUMN ( T ) ||______________| |______________| |_______________| | |1..* ______|________ | CSV ROWS ( T ) | |_______________| public class CSVExportTable < T > where T : IObject { private Matrix < string > Matrix { get ; set ; } private ICollection < CSVExportTableColumn < T > > Columns { get ; set ; } private ICollection < CSVExportTableRow < T > > Rows { get ; set ; } private ICollection < CSVExportTable < IObject > > SubTables { get ; set ; } private Expression < Func < T , object > > Link { get ; set ; } public CSVExportTable ( ) { this.Matrix = new Matrix < string > ( ) ; this.Columns = new List < CSVExportTableColumn < T > > ( ) ; this.SubTables = new List < CSVExportTable < IObject > > ( ) ; this.Rows = new List < CSVExportTableRow < T > > ( ) ; } public CSVExportTable < R > AddSubTable < R > ( Expression < Func < T , object > > link ) where R : IObject { /* This is where we create the link between the main table items and the subtable items ( = where we retreive Person = > Person.PersonSites as an ICollection < R > since the subtable has a different type ( T ! = R but they have the same interface ( IObject ) ) */ } public void AddColumn ( Expression < Func < T , object > > exportProperty ) { this.Columns.Add ( new CSVExportTableColumn < T > ( exportProperty ) ) ; } public Matrix < string > GenerateMatrix ( ) { int rowIndex= 0 ; foreach ( CSVExportTableRow < T > row in this.Rows ) { int columnIndex = 0 ; foreach ( CSVExportTableColumn < T > column in this.Columns ) { this.Matrix = this.Matrix.AddValue ( rowIndex , columnIndex , ( ( string ) column.ExportProperty.Compile ( ) .DynamicInvoke ( row.Item ) ) ) ; columnIndex++ ; } rowIndex++ ; } return this.Matrix ; } public Matrix < string > ApplyTemplate ( ICollection < T > items ) { // Generate rows foreach ( T item in items ) { this.Rows.Add ( new CSVExportTableRow < T > ( item ) ) ; } // Instantiate the matrix Matrix < string > matrix = new Matrix < string > ( ) ; // Generate matrix for every row foreach ( var row in this.Rows ) { matrix = GenerateMatrix ( ) ; // Generate matrix for every sub table foreach ( var subTable in this.SubTables ) { // This it where we should call ApplyTemplate for the current subTable with the elements that the link expression gave us ( ICollection ) . } } return matrix ; } } public class CSVExportTableColumn < T > where T : IObject { public Expression < Func < T , object > > ExportProperty { get ; set ; } public CSVExportTableColumn ( Expression < Func < T , object > > exportProperty ) { this.ExportProperty = exportProperty ; } }",Generic export to CSV with tables "C_sharp : Imagine an object you are working with has a collection of other objects associated with it , for example , the Controls collection on a WinForm . You want to check for a certain object in the collection , but the collection does n't have a Contains ( ) method . There are several ways of dealing with this.Implement your own Contains ( ) method by looping through all items in the collection to see if one of them is what you are looking for . This seems to be the `` best practice '' approach.I recently came across some code where instead of a loop , there was an attempt to access the object inside a try statement , as follows : My question is how poor of a programming practice do you consider the second option be and why ? How is the performance of it compared to a loop through the collection ? try { Object aObject = myCollection [ myObject ] ; } catch ( Exception e ) { //if this is thrown , then the object does n't exist in the collection }",Using unhandled exceptions instead of Contains ( ) ? "C_sharp : I have a series of code blocks that are taking too long . I do n't need any finesse when it fails . In fact , I want to throw an exception when these blocks take too long , and just fall out through our standard error handling . I would prefer to NOT create methods out of each block ( which are the only suggestions I 've seen so far ) , as it would require a major rewrite of the code base.Here 's what I would LIKE to create , if possible.I 've created a simple object to do this using the Timer class . ( NOTE for those that like to copy/paste : THIS CODE DOES NOT WORK ! ! ) It does not work because the System.Timers.Timer class captures , absorbs and ignores any exceptions thrown within , which -- as I 've discovered -- defeats my design . Any other way of creating this class/functionality without a total redesign ? This seemed so simple two hours ago , but is causing me much headache . public void MyMethod ( ... ) { ... using ( MyTimeoutObject mto = new MyTimeoutObject ( new TimeSpan ( 0,0,30 ) ) ) { // Everything in here must complete within the timespan // or mto will throw an exception . When the using block // disposes of mto , then the timer is disabled and // disaster is averted . } ... } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Timers ; public class MyTimeoutObject : IDisposable { private Timer timer = null ; public MyTimeoutObject ( TimeSpan ts ) { timer = new Timer ( ) ; timer.Elapsed += timer_Elapsed ; timer.Interval = ts.TotalMilliseconds ; timer.Start ( ) ; } void timer_Elapsed ( object sender , ElapsedEventArgs e ) { throw new TimeoutException ( `` A code block has timed out . `` ) ; } public void Dispose ( ) { if ( timer ! = null ) { timer.Stop ( ) ; } } }",How to create a generic timeout object for various code blocks ? "C_sharp : When utilising the MVVM pattern I am coming into some trouble when the Model objects become complex , that is , when they contain Properties which are non-primitive / not built-in . In my particular instance I have a ModelA which contains a collection of ModelB objects which themselves contains a collection of ModelC objects : I have a ModelAViewModel which permits access to the collection of ModelB Bs property . In this instance I have not created a ViewModel for ModelB . I have styled the ModelB and ModelC collections ( and individual instances ) by using DataTemplates : I have been advised that this is not the MVVM way of doing things and that each entity , that is , ModelB and ModelC should have their own ViewModel . I have been told to keep the Model classes but create ViewModels for them . I am unable to visualise how this is going to work.If I create a ModelBViewModel : I have a predicament - I already have ModelB instances within the ModelA class , I would now have other ModelB instances in the ModelBViewModel . Is it necessary to iterate through the original ModelB collection within ModelA and create the ModelBViewModels , setting the MyModelB property to match that in ModelA as I go ? It seems a bit complicated for what should be rather simple ? class ModelA { public string Name { get ; set ; } public OberservableCollection < ModelB > Bs { get ; set ; } } class ModelB { public string Make { get ; set ; } public ObservableCollection < ModelC > Cs { get ; set ; } } class ModelC { public string Brand { get ; set ; } } < DataTemplate x : Key= '' modelATemplate '' > < Grid Margin= '' 5 '' > < Grid.RowDefinitions > < RowDefinition / > < /Grid.RowDefinitions > < ScrollViewer Grid.Row= '' 2 '' VerticalScrollBarVisibility= '' Auto '' > < ItemsControl ItemsSource= '' { Binding Bs } '' ItemTemplate= '' { StaticResource modelBTemplate } '' / > < /ScrollViewer > < /Grid > < /DataTemplate > < DataTemplate x : Key= '' modelBTemplate '' > < Grid Margin= '' 5 '' HorizontalAlignment= '' Center '' > < Grid.RowDefinitions > < RowDefinition / > < RowDefinition / > < /Grid.RowDefinitions > < TextBlock Grid.Row= '' 0 '' Text= '' { Binding Make } '' > < ItemsControl Grid.Row= '' 1 '' ItemsSource= '' { Binding Mode=OneWay , Path=Cs } '' ItemTemplate= '' { StaticResource ResourceKey=modelCTemplate } '' > < /ItemsControl > < /Grid > < /DataTemplate > public class ModelBViewModel { ModelB MyModelB { get ; set ; } }",MVVM with complex Models "C_sharp : I 've used emacs for a long time , but I have n't been keeping up with a bunch of features . One of these is speedbar , which I just briefly investigated now . Another is imenu . Both of these were mentioned inin-emacs-how-can-i-jump-between-functions-in-the-current-file ? Using imenu , I can jump to particular methods in the module I 'm working in . But there is a parse hierarchy that I have to negotiate before I get the option to choose ( with autocomplete ) the method name.It goes like this . I type M-x imenu and then I get to choose Using or Types . The Using choice allows me to jump to any of the using statements at the top level of the C # file ( something like imports statements in a Java module , for those of you who do n't know C # ) . Not super helpful . I choose Types . Then I have to choose a namespace and a class , even though there is just one of each in the source module . At that point I can choose between variables , types , and methods . If I choose methods I finally get the list of methods to choose from . The hierarchy I traverse looks like this ; Only after I get to the 5th level do I get to select the thing I really want to jump to : a particular method.Imenu seems intelligent about the source module , but kind of hard to use . Am I doing it wrong ? UsingTypes Namespace Class Types Variables Methods method names","In Emacs , how can I use imenu more sensibly with C # ?" C_sharp : I 'm trying to understand the c # using directive ... Why does this work ... but this does not ? The second results in a compile error `` The type or namespace DataAnnotations can not be found . Are you missing are missing a using directive or an assembly reference ? using System ; using System.ComponentModel.DataAnnotations ; namespace BusinessRuleDemo { class MyBusinessClass { [ Required ] public string SomeRequiredProperty { get ; set ; } } } using System ; using System.ComponentModel ; namespace BusinessRuleDemo { class MyBusinessClass { [ DataAnnotations.Required ] public string SomeRequiredProperty { get ; set ; } } },c # using directive depth "C_sharp : I have noticed that seemingly equivalent code in F # and C # do not perform the same . The F # is slower by the order of magnitude . As an example I am providing my code which generates prime numbers/gives nth prime number in F # and C # . My F # code is : And C # looks like this : When I measure for different n I get advantage for C # of at least 7x as follows : n= 100 : C # =5milsec F # =64milsecn= 1000 : C # =22milsec F # =180milsecn= 5000 : C # =280milsec F # =2.05secn=10000 : C # =960milsec F # =6.95secMy questions : Are these two programs equivalent ? If yes , why are n't they compiled into a same/equivalent CLI ? If not , why not ? How can I/Can I improve my F # prime numbers generator to perform more similar to the C # one ? Generally , can I ( or why can I not ) always mimic C # code in F # so my F # code would perform equally fast ? Edit1 : I 've realized that the algorithm itself can be improved by traversing only through odd and not prime numbers in isprime , making it non-recursive , but this is kind of perpendicular fact to the questions asked : ) let rec isprime x =primes| > Seq.takeWhile ( fun i - > i*i < = x ) | > Seq.forall ( fun i - > x % i < > 0 ) and primes = seq { yield 2 yield ! ( Seq.unfold ( fun i - > Some ( i , i+2 ) ) 3 ) | > Seq.filter isprime } let n = 1000let start = System.DateTime.Nowprintfn `` % d '' ( primes | > Seq.nth n ) let duration = System.DateTime.Now - startprintfn `` Elapsed Time : `` System.Console.WriteLine duration class Program { static bool isprime ( int n ) { foreach ( int p in primes ( ) ) { if ( p * p > n ) return true ; if ( n % p == 0 ) return false ; } return true ; } static IEnumerable < int > primes ( ) { yield return 2 ; for ( int i=3 ; ; i+=2 ) { if ( isprime ( i ) ) yield return i ; } } static void Main ( string [ ] args ) { int n = 1000 ; var pr = primes ( ) .GetEnumerator ( ) ; DateTime start = DateTime.Now ; for ( int count=0 ; count < n ; count++ ) { pr.MoveNext ( ) ; } Console.WriteLine ( pr.Current ) ; DateTime end = DateTime.Now ; Console.WriteLine ( `` Duration `` + ( end - start ) ) ; } }",F # vs C # performance for prime number generator "C_sharp : Initial SituationI 'm developing a .NET Framework 4.0 , C # , Winform Application . The Application will list ( and test ) WebServiceOperations in a GridView ( with currently 60 DataRows = > WebServiceOperations ) .ObjectiveI have to test/call all of this operations with one click on a button . Every operation creates a new instance of a class . Within this class , i call the WebServiceOperation async and wait for the result . The result is then beeing validated . The whole code works smooth using delegates and events . Now it comes to the challenge/question : When clicking on that button , i use a for loop ( int i = 0 ; i < gridViewWsOperations.RowCount ; i++ ) = > with other words , currently i 'm firing 60 operations at them 'same time ' = > the Server gets overloaded processing 60 requests at the same time and i get timeouts . So i need to somehow throttle the number of concurrend requests to let 's say 10 at the same time . Consider , the for loop ( where i have to enqueue the requests ) is n't in the same thread as the method ( process_result event ) where i dequeue the requests . I tried it using ConcurrentQueue since this type of collection seems to be thread-safe.LinksConcurrentQueue at MSDNa sample code would really help ! -- - this is my solution/sample code -- - using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Collections.Concurrent ; using System.Threading ; namespace ConcurrentQueueSample { class Program { static SemaphoreSlim semaphoreSlim = new SemaphoreSlim ( 3 ) ; static void Main ( string [ ] args ) { System.Timers.Timer timer = new System.Timers.Timer ( ) ; timer.Elapsed += new System.Timers.ElapsedEventHandler ( timer_Elapsed ) ; timer.Interval = 1234 ; timer.Enabled = true ; timer.Start ( ) ; for ( int i = 0 ; i < 10 ; i++ ) new Thread ( go ) .Start ( i ) ; } static void timer_Elapsed ( object sender , System.Timers.ElapsedEventArgs e ) { semaphoreSlim.Release ( ) ; } static void go ( object i ) { Console.WriteLine ( `` id : { 0 } '' , i ) ; semaphoreSlim.Wait ( ) ; Console.WriteLine ( `` id : { 0 } is in '' , i ) ; Thread.Sleep ( 1250 ) ; Console.WriteLine ( `` id : { 0 } left ! `` , i ) ; } } }",C # throttling For loop "C_sharp : Im using a WPF ScrollViewer to host some controls . I 'd really like it to interact like on a touch device where it slowly eases back into place when you pull it too far.It does n't have a scrollbar - I have manual mouse scrolling with click and drag using this code : Is there an easy way to do this ? Currently it just acts like a normal scrolling textbox and will neither pull outside its normal range , nor slowly ease back . Point currentPoint = e.GetPosition ( this ) ; // Determine the new amount to scroll.Point delta = new Point ( scrollStartPoint.X - currentPoint.X , scrollStartPoint.Y - currentPoint.Y ) ; if ( Math.Abs ( delta.X ) < PixelsToMoveToBeConsideredScroll & & Math.Abs ( delta.Y ) < PixelsToMoveToBeConsideredScroll ) return ; scrollTarget.X = scrollStartOffset.X + delta.X ; scrollTarget.Y = scrollStartOffset.Y + delta.Y ; // Scroll to the new position.sv.ScrollToHorizontalOffset ( scrollTarget.X ) ; sv.ScrollToVerticalOffset ( scrollTarget.Y ) ;",Is there an easy way to make a ScrollViewer `` bouncy '' ? "C_sharp : I have an assembly , written in C++\CLI , which uses some of enumerations , provided by .Net . It has such kind of properties : it works fine , but when i use this assembly from my C # code , type of this property is and i have to make type-castThe question is simple : why is it so , and how to fix it ? property System : :ServiceProcess : :ServiceControllerStatus ^ Status { ServiceControllerStatus ^ get ( ) { return ( ServiceControllerStatus ) _status- > dwCurrentState ; } } System.Enum if ( ( ServiceControllerStatus ) currentService.Status == ServiceControllerStatus.Running ) //do smth",An Issue with converting enumerations in C++\CLI "C_sharp : I want to sort a List of Tuple < int , string > using the int value . In this example the following code is used : I noticed that if I changed the following line : to : the elements are again sorted . Does this mean that the default behaviour is to use the first item ? If yes , is there any performance difference between the two techniques ? List < Tuple < int , string > > list = new List < Tuple < int , string > > ( ) ; list.Add ( new Tuple < int , string > ( 1 , `` cat '' ) ) ; list.Add ( new Tuple < int , string > ( 100 , `` apple '' ) ) ; list.Add ( new Tuple < int , string > ( 2 , `` zebra '' ) ) ; list.Sort ( ( a , b ) = > a.Item1.CompareTo ( b.Item1 ) ) ; foreach ( var element in list ) { Console.WriteLine ( element ) ; } list.Sort ( ( a , b ) = > a.Item1.CompareTo ( b.Item1 ) ) ; list.Sort ( ) ;",What is the default behaviour when list of tuples is sorted ? "C_sharp : i 'm having a problem with merging two list of objecthere they are : If i can get all needed data at one time , i wont ask this question , but i 'm grabbing all data for fist one , and only after i can get data for second one.So , what i need in result is : to get IssueMoreInfo from second one , according to ID in both , like for id 10 in first one , we getting IssueMoreInfoText column in second one and pass it to firt one list in column ToolTipInfoTextHope for your help , guys , thanks first oneList < NSKData > NSKDataList = new List < NSKData > ( ) ; public class NSKData { public string ID { get ; set ; } public string Issue { get ; set ; } public string ToolTipInfoText { get ; set ; } public NSKData ( ) { } public NSKData ( string id , string issue , string tooltipinfo ) { ID = id ; Issue= issue ; ToolTipInfoText = tooltipinfo ; } } second one List < IssuesMoreInfo > IssuesMoreInfoList = new List < IssuesMoreInfo > ( ) ; public class IssuesMoreInfo { public string ID { get ; set ; } public string IssueMoreInfoText { get ; set ; } }",Merge two lists objects "C_sharp : I hope someone can help . I 'm getting to grips with the C # driver for MongoDB and how it handles serialization . Consider the following example classes : Note that SubThing has a property that references its parent . So when creating objects I do so like this : The ParentThing property is set to BsonIgnore because otherwise it would cause a circular reference when serialising to MongoDB.When I do serialize to MongoDB it creates the document exactly how I expect it to be : Here is the problem : When I deserialize I loose SubThing 's reference to its parent . Is there any way to configure deserialization so that the ParentThing property is always its parent document ? class Thing { [ BsonId ] public Guid Thing_ID { get ; set ; } public string ThingName { get ; set ; } public SubThing ST { get ; set ; } public Thing ( ) { Thing_ID = Guid.NewGuid ( ) ; } } class SubThing { [ BsonId ] public Guid SubThing_ID { get ; set ; } public string SubThingName { get ; set ; } [ BsonIgnore ] public Thing ParentThing { get ; set ; } public SubThing ( ) { SubThing_ID = Guid.NewGuid ( ) ; } } Thing T = new Thing ( ) ; T.ThingName = `` My thing '' ; SubThing ST = new SubThing ( ) ; ST.SubThingName = `` My Subthing '' ; T.ST = ST ; ST.ParentThing = T ; { `` _id '' : LUUID ( `` 9d78bc5c-2abd-cb47-9478-012f9234e083 '' ) , '' ThingName '' : `` My thing '' , '' ST '' : { `` _id '' : LUUID ( `` 656f17ce-c066-854d-82fd-0b7249c80ef0 '' ) , `` SubThingName '' : `` My Subthing '' }",How to get a reference to the parent object in a deserialized MongoDB document ? "C_sharp : Consider this code , In this code snippet , SomeEvent.invoke ( ) actually invokes SomeMethod ( ) of class A . So at this point , I 've few questions : On what instance of A , SomeMethod gets invoked ? How does B know the instance on which the delegate to be invoked ? How does CLR work here ? Also , SomeMethod is a private method , then how come B is able to invoke this method from outside of the class A ? EDIT : After reading first few answers , I came to know that Delegate has a Target property on which delegate gets invoked . But I could n't really understand as to at exactly what step this Target property is set ? Who set it ? When I write b.SomeEvent += this.SomeMethod ; , does it set the Target property as well ? How exactly ? public class A { // ... void f ( ) { B b = new B ( ) ; b.SomeEvent += this.SomeMethod ; } void SomeMethod ( ) { } } public class B { // ... public event SomeEventHandler SomeEvent ; void h ( ) { if ( SomeEvent ! = null ) { SomeEvent.invoke ( ) ; } } }",On what instance of class delegate gets invoked ? "C_sharp : The System.Linq.Expressions.ExpressionVisitor has a method named VisitExtension which seems to do nothing other than call the VisitChildren method on the Expression being visited.I understand what the VisitChildren does . I also understand that this virtual implementation can be and is perhaps meant to be overriden . So I gather from the documentation of the method on MSDN , which is sparing in words and briefly remarks : Visits the children of the extension expression.This can be overridden to visit or rewrite specific extension nodes.If it is not overridden , this method will call VisitChildren , which gives the node a chance to walk its children . By default , VisitChildren will try to reduce the node.I do not find this explanation helpful . Specifically , the phrase that jets me out of my abilities of comprehension is `` or rewrite specific extension nodes . `` I understand the rest of it , which pertains to the reduction or breaking down of the expression into sub-expressions.Also in the same namespace is an enumeration named ExpressionType , the purpose of which I understand very well . But of all its members , there is one member named Extension which I can not map to any syntactical token I am currently aware of.The documentation in this instance , too , is frustratingly laconic . It describes the value Extension as follows : An extension expression.It is obvious that the two -- ExpressionType.Extension and ExpressionVisitor.VisitExtension -- are related.But what is an extension ? Surely , as is glaringly obvious , extension methods have no place in this context . Which syntactical artifact does the expression extension refer to here ? protected internal virtual Expression VisitExtension ( Expression node ) { return node.VisitChildren ( this ) ; }",What 's the System.Linq.Expressions.ExpressionVisitor.VisitExtension and the System.Linq.Expressions.ExpressionType.Extension for ? "C_sharp : Visual Studio 2019 's code analysis and code suggestions started to highlight every line of code where I call a method that returns a value but do n't use that value at all and tells me to use the discard operator _.I do n't fully understand why that matters and it even seems wrong for Fluent API style code.Is there a functional difference between the two following lines ? Would it matter more if the return value is a reference ? If not , Is there a way to globally disable this inspection ? private int SomeMethod ( ) = > 0 ; ... SomeMethod ( ) ; _ = SomeMethod ( ) ; ...",Is there a point to using the C # discard operator for method return values ? "C_sharp : tl ; dr : I want to reuse the existing layouting logic of a pre-defined WPF panel for a custom WPF panel class . This question contains four different attempts to solve this , each with different downsides and thus a different point of failure . Also , a small test case can be found further down.The question is : How do I properly achieve this goal ofdefining my custom panel whileinternally reusing the layouting logic of another panel , withoutrunning into the problems described in my attempts to solve this ? I am trying to write a custom WPF panel . For this panel class , I would like to stick to recommended development practices and maintain a clean API and internal implementation . Concretely , that means : I would like to avoid copy and pasting of code ; if several portions of code have the same function , the code should exist only once and be reused.I would like to apply proper encapsulation and let outside users access only such members that can safely be used ( without breaking any of the internal logic , or without giving away any internal implementation-specific information ) .As for the time being , I am going to closely stick with an existing layout , I would like to re-use another panel 's layouting code ( rather than writing the layouting code again , as suggested e.g . here ) . For the sake of an example , I will explain based on DockPanel , though I would like to know how to do this generally , based on any kind of Panel.To reuse the layouting logic , I am intending to add a DockPanel as a visual child in my panel , which will then hold and layout the logical children of my panel.I have tried three different ideas on how to solve this , and another one was suggested in a comment , but each of them so far fails at a different point:1 ) Introduce the inner layout panel in a control template for the custom panelThis seems like the most elegant solution - this way , a control panel for the custom panel could feature an ItemsControl whose ItemsPanel property is uses a DockPanel , and whose ItemsSource property is bound to the Children property of the custom panel.Unfortunately , Panel does not inherit from Control and hence does not have a Template property , nor feature support for control templates.On the other hand , the Children property is introduced by Panel , and hence not present in Control , and I feel it could be considered hacky to break out of the intended inheritance hierarchy and create a panel that is actually a Control , but not a Panel.2 ) Provide a children list of my panel that is merely a wrapper around the children list of the inner panelSuch a class looks as depicted below . I have subclassed UIElementCollection in my panel class and returned it from an overridden version of the CreateUIElementCollection method . ( I have only copied the methods that are actually invoked here ; I have implemented the others to throw a NotImplementedException , so I am certain that no other overrideable members were invoked . ) This works almost correctly ; the DockPanel layout is reused as expected . The only issue is that bindings do not find controls in the panel by name ( with the ElementName property ) .I have tried returned the inner children from the LogicalChildren property , but this did not change anything : In an answer by user Arie , the NameScope class was pointed out to have a crucial role in this : The names of the child controls do not get registered in the relevant NameScope for some reason . This might be partially fixed by invoking RegisterName for each child , but one would need to retrieve the correct NameScope instance . Also , I am not sure whether the behaviour when , for instance , the name of a child changes would be the same as in other panels.Instead , setting the NameScope of the inner panel seems to be the way to go . I tried this with a straightforward binding ( in the TestPanel1 constructor ) : Unfortunately , this just sets the NameScope of the inner panel to null . As far as I could find out by means of Snoop , the actual NameScope instance is only stored in the NameScope attached property of either the parent window , or the root of the enclosing visual tree defined by a control template ( or possibly by some other key node ? ) , no matter what type . Of course , a control instance may be added and removed at different positions in a control tree during its lifetime , so the relevant NameScope might change from time to time . This , again , calls for a binding.This is where I am stuck again , because unfortunately , one can not define a RelativeSource for the binding based on an arbitrary condition such as *the first encountered node that has a non-null value assigned to the NameScope attached property.Unless this other question about how to react to updates in the surrounding visual tree yields a useful response , is there a better way to retrieve and/or bind to the NameScope currently relevant for any given framework element ? 3 ) Use an inner panel whose children list is simply the same instance as that of the outer panelRather than keeping the child list in the inner panel and forwarding calls to the outer panel 's child list , this works kind-of the other way round . Here , only the outer panel 's child list is used , while the inner panel never creates one of its own , but simply uses the same instance : Here , layouting and binding to controls by name works . However , the controls are not clickable.I suspect I have to somehow forward calls to HitTestCore ( GeometryHitTestParameters ) and to HitTestCore ( PointHitTestParameters ) to the inner panel . However , in the inner panel , I can only access InputHitTest , so I am neither sure how to safely process the raw HitTestResult instance without losing or ignoring any of the information that the original implementation would have respected , nor how to process the GeometryHitTestParameters , as InputHitTest only accepts a simple Point.Moreover , the controls are also not focusable , e.g . by pressing Tab . I do not know how to fix this.Besides , I am slightly wary of going this way , as I am not sure what internal links between the inner panel and the original list of children I am breaking by replacing that list of children with a custom object.4 ) Inherit directly from panel classUser Clemens suggests to directly have my class inherit from DockPanel . However , there are two reasons why that is not a good idea : The current version of my panel will rely on the layouting logic of DockPanel . However , it is possible that at some point in the future , that will not be enough any more and someone will indeed have to write custom layouting logic in my panel . In that case , replacing an inner DockPanel with custom layouting code is trivial , but removing DockPanel from the inheritance hierarchy of my panel would mean a breaking change.If my panel inherits from DockPanel , users of the panel might be able to sabotage its layouting code by messing around with properties exposed by DockPanel , in particular LastChildFill . And while it is just that property , I would like to use an approach that works with all Panel subtypes . For instance , a custom panel derived from Grid would expose the ColumnDefinitions and RowDefinitions properties , by which any automatically generated layout could be completely destroyed via the public interface of the custom panel.As a test case for observing the described issues , add an instance of the custom panel being tested in XAML , and within that element , add the following : The text block should be left of the text box , and it should show whatever is currently written in the text box.I would expect the text box to be clickable , and the output view not to display any binding errors ( so , the binding should work , as well ) .Thus , my question is : Can any one of my attempts be fixed to lead to a completely correct solution ? Or is there a completely other way that is preferrable to what I have tried to do what I am looking for ? using System ; using System.Windows ; using System.Windows.Controls ; namespace WrappedPanelTest { public class TestPanel1 : Panel { private sealed class ChildCollection : UIElementCollection { public ChildCollection ( TestPanel1 owner ) : base ( owner , owner ) { if ( owner == null ) { throw new ArgumentNullException ( `` owner '' ) ; } this.owner = owner ; } private readonly TestPanel1 owner ; public override int Add ( System.Windows.UIElement element ) { return this.owner.innerPanel.Children.Add ( element ) ; } public override int Count { get { return owner.innerPanel.Children.Count ; } } public override System.Windows.UIElement this [ int index ] { get { return owner.innerPanel.Children [ index ] ; } set { throw new NotImplementedException ( ) ; } } } public TestPanel1 ( ) { this.AddVisualChild ( innerPanel ) ; } private readonly DockPanel innerPanel = new DockPanel ( ) ; protected override UIElementCollection CreateUIElementCollection ( System.Windows.FrameworkElement logicalParent ) { return new ChildCollection ( this ) ; } protected override int VisualChildrenCount { get { return 1 ; } } protected override System.Windows.Media.Visual GetVisualChild ( int index ) { if ( index == 0 ) { return innerPanel ; } else { throw new ArgumentOutOfRangeException ( ) ; } } protected override System.Windows.Size MeasureOverride ( System.Windows.Size availableSize ) { innerPanel.Measure ( availableSize ) ; return innerPanel.DesiredSize ; } protected override System.Windows.Size ArrangeOverride ( System.Windows.Size finalSize ) { innerPanel.Arrange ( new Rect ( new Point ( 0 , 0 ) , finalSize ) ) ; return finalSize ; } } } protected override System.Collections.IEnumerator LogicalChildren { get { return innerPanel.Children.GetEnumerator ( ) ; } } BindingOperations.SetBinding ( innerPanel , NameScope.NameScopeProperty , new Binding ( `` ( NameScope.NameScope ) '' ) { Source = this } ) ; using System ; using System.Windows ; using System.Windows.Controls ; namespace WrappedPanelTest { public class TestPanel2 : Panel { private sealed class InnerPanel : DockPanel { public InnerPanel ( TestPanel2 owner ) { if ( owner == null ) { throw new ArgumentNullException ( `` owner '' ) ; } this.owner = owner ; } private readonly TestPanel2 owner ; protected override UIElementCollection CreateUIElementCollection ( FrameworkElement logicalParent ) { return owner.Children ; } } public TestPanel2 ( ) { this.innerPanel = new InnerPanel ( this ) ; this.AddVisualChild ( innerPanel ) ; } private readonly InnerPanel innerPanel ; protected override int VisualChildrenCount { get { return 1 ; } } protected override System.Windows.Media.Visual GetVisualChild ( int index ) { if ( index == 0 ) { return innerPanel ; } else { throw new ArgumentOutOfRangeException ( ) ; } } protected override System.Windows.Size MeasureOverride ( System.Windows.Size availableSize ) { innerPanel.Measure ( availableSize ) ; return innerPanel.DesiredSize ; } protected override System.Windows.Size ArrangeOverride ( System.Windows.Size finalSize ) { innerPanel.Arrange ( new Rect ( new Point ( 0 , 0 ) , finalSize ) ) ; return finalSize ; } } } < TextBox Name= '' tb1 '' DockPanel.Dock= '' Right '' / > < TextBlock Text= '' { Binding Text , ElementName=tb1 } '' DockPanel.Dock= '' Left '' / >",How to Reuse Existing Layouting Code for new Panel Class ? "C_sharp : I 'm working on an application where a client connects with a TCP connection which then triggers an amount of work that may potentially take a lot of time to complete . This work must be cancelled if the user drops the TCP connection.Currently , what I 'm doing is starting up a timer that periodically checks the networks streams connectivity by doing this : I would have liked to read the CanWrite , CanRead or Connected but they report the last status of the stream . Is writing zero bytes a reliable way of testing connectivity , or can this itself cause issues ? I can not write or read any real data on the stream since that would mess up the client . // stream is a Stream instancevar abort = false ; using ( new Timer ( x = > { try { stream.Write ( new byte [ 0 ] , 0 , 0 ) ; } catch ( Exception ) { abort = true ; } } , null , 1000 , 1000 ) ) { // Do expensive work here and check abort periodically }",Is writing zero bytes to a network stream a reliable way to detect closed connections ? "C_sharp : After some experimenting I parented an empty ( HeadCam ) to the character 's neck.This snippet allow rotation of the head synchronously to the CardboardHead/Camera . The character 's arms should n't move when only the head rotates as long in the range -60° to 60° after that I would like to move the whole character with the arms still visible . The following method works as long the character is n't rotated by more than 180° after that the characters flips by 180° how could I achieve constant rotation ? A java applet for testing the algorithm standalone : https : //github.com/3dbug/blender/blob/master/HeadCamRot.java void LateUpdate ( ) { neckBone.transform.rotation = Camera.transform.rotation * Quaternion.Euler ( 0,0 , -90 ) ; Camera.transform.position = HeadCam.transform.position ; } void LateUpdate ( ) { Quaternion camRot = Camera.transform.rotation * Quaternion.Euler ( 0,0 , -90 ) ; neckBone.transform.rotation = camRot ; float yrot = camRot.eulerAngles.y ; float ydelta = 0 ; if ( yrot < 300f & & yrot > 180 ) { ydelta = yrot - 300f ; } if ( yrot > 60f & & yrot < 180 ) { ydelta = yrot - 60 ; } playerObj.transform.rotation = Quaternion.Euler ( 0 , ydelta , 0 ) ; Camera.transform.position = HeadCam.transform.position ; }",How can character 's body be continuously rotated when its head is already turned by 60° ` ? "C_sharp : I would like make an extension method for the generic class A which takes yet another generictype ( in this example TC ) , but i guess that aint possible ? class Program { static void Main ( string [ ] args ) { var a = new A < B , B > ( ) ; a.DoIt < B > ( ) ; } } static class Ext { public static A < TA , TB > DoIt < TA , TB , TC > ( this A < TA , TB > a ) { return a ; } } class A < TA , TB > { } class B { }",Extra generic parameter in generic extension methods ? "C_sharp : I have an object o which guaranteed at runtime to be one of three types A , B , or C , all of which implement a common interface I. I can control I , but not A , B , or C. ( Thus I could use an empty marker interface , or somehow take advantage of the similarities in the types by using the interface , but I ca n't add new methods or change existing ones in the types . ) I also have a series of methods MethodA , MethodB , and MethodC . The runtime type of o is looked up and is then used as a parameter to these methods.Using this strategy , right now a check has to be performed on the type of o to determine which method should be invoked . Instead , I would like to simply have three overloaded methods : Now I 'm letting C # do the dispatch instead of doing it manually myself . Can this be done ? The naive straightforward approach does n't work , of course : Can not resolve method 'Method ( object ) ' . Candidates are : void Method ( A ) void Method ( B ) void Method ( C ) public void MethodA ( A a ) { ... } public void MethodB ( B b ) { ... } public void MethodC ( C c ) { ... } public void Method ( A a ) { ... } // these are all overloads of each otherpublic void Method ( B b ) { ... } public void Method ( C c ) { ... }",How do I dispatch to a method based on a parameter 's runtime type in C # < 4 ? "C_sharp : I want to query data from a view , which is a view of a table contains 583,000 records.So I write a simple query to query from the view like thisThis is the generated sqlI ran the query for 5 times.The first call took me 350ms and next calls took me 150ms on average on this query which was too slow , so I changed the query to be like thisI ran it for 5 timesThe first call took me 40ms and next calls took me only 1ms on average ! Do anyone has any ideas what I did wrong ? EnvironmentEntity Framework 5.0Oracle 11g DatabaseODP.NET 11.2 Release 3.NET Framework 4.5 var uuid = `` AB1-23456 '' ; dbSet.SingleOrDefault ( x = > x.UserKey == uuid ) ; SELECT `` Extent1 '' . `` UserKey '' AS `` UserKey '' , CAST ( `` Extent1 '' . `` IsDeleted '' AS number ( 3,0 ) ) AS `` C1 '' , `` Extent1 '' . `` FirstName '' AS `` FirstName '' , `` Extent1 '' . `` LastName '' AS `` LastName '' , `` Extent1 '' . `` UserLogin '' AS `` UserLogin '' , `` Extent1 '' . `` AccLocationKey '' AS `` AccLocationKey '' , `` Extent1 '' . `` CompanyKey '' AS `` CompanyKey '' FROM `` UsersView '' `` Extent1 '' WHERE ( 'AB1-23456 ' = `` Extent1 '' . `` UserKey '' ) var queryString = `` SELECT \ '' Extent1\ '' .\ '' UserKey\ '' AS \ '' UserKey\ '' , `` + `` CAST ( \ '' Extent1\ '' .\ '' IsDeleted\ '' AS number ( 3,0 ) ) AS \ '' IsDeleted\ '' , `` + `` \ '' Extent1\ '' .\ '' FirstName\ '' AS \ '' FirstName\ '' , `` + `` \ '' Extent1\ '' .\ '' LastName\ '' AS \ '' LastName\ '' , `` + `` \ '' Extent1\ '' .\ '' UserLogin\ '' AS \ '' UserLogin\ '' , `` + `` \ '' Extent1\ '' .\ '' AccLocationKey\ '' AS \ '' AccLocationKey\ '' , `` + `` \ '' Extent1\ '' .\ '' CompanyKey\ '' AS \ '' CompanyKey\ '' `` + `` FROM \ '' UsersView\ '' \ '' Extent1\ '' `` + `` WHERE ( 'AB1-23456 ' = \ '' Extent1\ '' .\ '' UserKey\ '' ) '' ; dbSet.SqlQuery ( queryString ) .SingleOrDefault ( ) ;",Why is SqlQuery a lot faster than using LINQ expression on views ? C_sharp : I have ( for example ) an object of type A that I want to be able to cast to type B ( similar to how you can cast an int to a float ) Data types A and B are my own.Is it possible to define the rules by which this casting occurs ? Example int a = 1 ; float b = ( float ) a ; int c = ( int ) b ;,Casting Between Data Types in C # "C_sharp : I 'm reading the book `` LINQ Pocket Reference '' and there is a particular example ( slightly modified below ) that I 'm having difficulty getting my head around ... The explanation in the book is a bit brief , so I was wondering if someone could break it down step-by-step for me so that it makes sense ... Outputs this : Which makes perfect sense to me ... However , this does not.which does n't ... Can someone give me a better explanation of exactly what is going on here ? IEnumerable < char > query2 = `` Not what you might expect '' ; foreach ( char vowel in `` aeiou '' ) { var t = vowel ; query2 = query2.Where ( c = > c ! = t ) ; // iterate through query and output ( snipped for brevity ) } Not wht you might expect Not wht you might xpct Not wht you mght xpct Nt wht yu mght xpct Nt wht y mght xpct IEnumerable < char > query2 = `` Not what you might expect '' ; foreach ( char vowel in `` aeiou '' ) { query2 = query2.Where ( c = > c ! = vowel ) ; // iterate through query and output ( snipped for brevity ) } Not wht you might expect Not what you might xpct Not what you mght expect Nt what yu might expect Not what yo might expect",LINQ Query - Explanation needed of why these examples are different "C_sharp : While I understand that changing the value of String.Empty would be a bad idea , I do n't understand why I ca n't do it.To get what I mean , consider the following class : I have a little console app that tries to manipulate these three readonly fields . It can successfully make Blue and Green into Pink , but Empty stays the same : Why ? Originally , I also asked why String.Empty was n't a constant . I found the answer to this part of my question on another post and deleted that part of the question ) .Note : None of the `` duplicates '' have a conclusive answer to this problem , that 's why I 'm asking this question . public class SomeContext { static SomeContext ( ) { } public static readonly string Green = `` Green '' ; public static readonly SomeContext Instance = new SomeContext ( ) ; private SomeContext ( ) { } public readonly string Blue = `` Blue '' ; public static void PrintValues ( ) { Console.WriteLine ( new { Green , Instance.Blue , String.Empty } .ToString ( ) ) ; } } SomeContext.PrintValues ( ) ; /// prints out : { Green = Green , Blue = Blue , Empty = } typeof ( SomeContext ) .GetField ( `` Blue '' ) .SetValue ( SomeContext.Instance , `` Pink '' ) ; typeof ( SomeContext ) .GetField ( `` Green '' , BindingFlags.Public | BindingFlags.Static ) .SetValue ( null , `` Pink '' ) ; typeof ( String ) .GetField ( `` Empty '' , BindingFlags.Public | BindingFlags.Static ) .SetValue ( null , `` Pink '' ) ; SomeContext.PrintValues ( ) ; /// prints out : { Green = Pink , Blue = Pink , Empty = }",Why ca n't I change the value of String.Empty ? "C_sharp : Why do this : Instead of this : I do n't understand why you 'd ever write ( ( System.Object ) p ) ? Regards , Dan // If parameter can not be cast to Point return false . TwoDPoint p = obj as TwoDPoint ; if ( ( System.Object ) p == null ) { return false ; } // If parameter can not be cast to Point return false . TwoDPoint p = obj as TwoDPoint ; if ( p == null ) { return false ; }",( ( System.Object ) p == null ) "C_sharp : I have a Parallel.ForEach code in my Windows Service . If ParallelOptions.MaxDegreeOfParallelism is set to -1 I 'm using the most of my CPU 's . However stopping the service lasts for half a minute . Some internal controller thread that should receive the signal that the service should be stopped is starved out of processor time . I set the process priority to below normal , but that could be irrelevant info here.What can I do to shorten the time of stopping the service even when all threads are busy ? I was toying with the idea to temporarily lower the priority of the threads from the thread pool , since I do n't have any async code , but Internet says that 's a bad idea , so asking here for a `` proper '' way.The threads ( both OS and .NET ) are in all cases different between OnStart and OnStop . Also , if stopping is very prolonged then the OS thread in which OnStop will sometimes eventually be called is a new thread , not showing earlier in the log.To build this code create new Windows service project , add ProjectInstaller class from designer , change Account to LocalService , and install once with InstallUtil . Make sure LocalService can write to C : \Temp . public partial class Service1 : ServiceBase { private ManualResetEvent stopEvent = new ManualResetEvent ( false ) ; private Task mainTask ; private StreamWriter writer = File.AppendText ( @ '' C : \Temp\Log.txt '' ) ; public Service1 ( ) { InitializeComponent ( ) ; writer.AutoFlush = true ; } protected override void OnStart ( string [ ] args ) { Log ( `` -- -- -- -- -- -- -- '' ) ; Log ( `` OnStart '' ) ; mainTask = Task.Run ( new Action ( Run ) ) ; } protected override void OnStop ( ) { Log ( `` OnStop '' ) ; stopEvent.Set ( ) ; mainTask.Wait ( ) ; Log ( `` -- -- -- -- -- -- -- '' ) ; } private void Log ( string line ) { writer.WriteLine ( String.Format ( `` { 0 : yyyy-MM-dd HH : mm : ss.fff } : [ { 1,2 } ] { 2 } '' , DateTime.Now , Thread.CurrentThread.ManagedThreadId , line ) ) ; } private void Run ( ) { try { using ( var sha = SHA256.Create ( ) ) { var parallelOptions = new ParallelOptions ( ) ; parallelOptions.MaxDegreeOfParallelism = -1 ; Parallel.ForEach ( Directory.EnumerateFiles ( Environment.SystemDirectory ) , parallelOptions , ( fileName , parallelLoopState ) = > { if ( stopEvent.WaitOne ( 0 ) ) { Log ( `` Stop requested '' ) ; parallelLoopState.Stop ( ) ; return ; } try { var hash = sha.ComputeHash ( File.ReadAllBytes ( fileName ) .OrderBy ( x = > x ) .ToArray ( ) ) ; Log ( String.Format ( `` file= { 0 } , sillyhash= { 1 } '' , fileName , Convert.ToBase64String ( hash ) ) ) ; } catch ( Exception ex ) { Log ( String.Format ( `` file= { 0 } , exception= { 1 } '' , fileName , ex.Message ) ) ; } } ) ; } } catch ( Exception ex ) { Log ( String.Format ( `` exception= { 0 } '' , ex.Message ) ) ; } } }",Stopping Parallel.ForEach in Windows Service with below normal priority "C_sharp : I just started using the TPL , and I want to make several calls to web services happen in parallel . From what I can gather , I see two ways of doing this.Either Parallel.ForEach : Or Task < T > : Disregarding if the syntax is correct or not , are these to equivilant ? Will they produce the same result ? If not , why ? and which is preferable ? List < ServiceMemberBase > list = new List < ServiceMemberBase > ( ) ; //Take list from somewhere . Parallel.ForEach ( list , member = > { var result = Proxy.Invoke ( member ) ; // ... //Do stuff with the result // ... } ) ; List < ServiceMemberBase > list = new List < ServiceMemberBase > ( ) ; //Take list from somewhere . ForEach ( var member in list ) { Task < MemberResult > .Factory.StartNew ( ( ) = > proxy.Invoke ( member ) ) ; } //Wait for all tasks to finish . //Process the result objects .",What would be a better way of using task parallel library "C_sharp : So topic is the questions . I get that method AsParallel returns wrapper ParallelQuery < TSource > that uses the same LINQ keywords , but from System.Linq.ParallelEnumerable instead of System.Linq.Enumerable It 's clear enough , but when i 'm looking into decompiled sources , i do n't understand how does it works . Let 's begin from an easiest extension : Sum ( ) method . Code : it 's clear , let 's go to Aggregate ( ) method . It 's a wrapper on InternalAggregate method that traps some exceptions . Now let 's take a look on it.and here is the question : how it works ? I see no concurrence safety for a variable , modified by many threads , we see only iterator and summing . Is it magic enumerator ? Or how does it works ? GetEnumerator ( ) returns QueryOpeningEnumerator < TOutput > , but it 's code is too complicated . [ __DynamicallyInvokable ] public static int Sum ( this ParallelQuery < int > source ) { if ( source == null ) throw new ArgumentNullException ( `` source '' ) ; else return new IntSumAggregationOperator ( ( IEnumerable < int > ) source ) .Aggregate ( ) ; } protected override int InternalAggregate ( ref Exception singularExceptionToThrow ) { using ( IEnumerator < int > enumerator = this.GetEnumerator ( new ParallelMergeOptions ? ( ParallelMergeOptions.FullyBuffered ) , true ) ) { int num = 0 ; while ( enumerator.MoveNext ( ) ) checked { num += enumerator.Current ; } return num ; } }",How AsParallel extension actually works "C_sharp : I was trying to solve problem # 14 from Project Euler , and had written the following C # ... Trouble was , it just ran and ran without seeming to stop.After searching for other people 's solution to the problem , I saw one looking very similar , except that he had used long instead of int . I did n't see why this should be necessary , as all of the numbers involved in this problem are well within the range of an int , but I tried it anyway.Changing int to long made the code run in just over 2 seconds.Anyone able to explain this to me ? int maxColl = 0 ; int maxLen = 0 ; for ( int i = 2 ; i < 1000000 ; i++ ) { int coll = i ; int len = 1 ; while ( coll ! = 1 ) { if ( coll % 2 == 0 ) { coll = coll / 2 ; } else { coll = 3 * coll + 1 ; } len++ ; } if ( len > maxLen ) { maxLen = len ; maxColl = i ; } }",Why does changing int to long speed up the execution ? "C_sharp : I 've got this collection with guid id . When i use Azure Query Explorer with collection selected in the combo box above it 's ok : But when i try to select it like that ( both from query exlorer and from c # code ) : I get : Syntax error , invalid numeric value token '357fa002'.I 've tried to put it in quotation marks ( both single and double ) around guid but with no success.. Microsoft docs state that this collection id does n't break any rules : https : //docs.microsoft.com/pl-pl/azure/documentdb/documentdb-create-collection Collection names must be between 1 and 255 characters , and can not contain / \ # ? or a trailing spaceHow can i query this collection using it 's id ? SELECT * FROM c SELECT * FROM 357fa002-dc7d-4ede-935a-6a0c80cf9239 c",how to select from collection with guid id ? C_sharp : Given searchString = `` 23423asdfa- '' '' This regular expression should evaluate to false but it does not ! Any ideas ? Regex rgx = new Regex ( @ '' [ \w- ] * '' ) ; rgx.IsMatch ( searchString ),Regular Expression that Matches Any Number or Letter or Dash "C_sharp : ( This question is a follow-up to C # accessing protected member in derived class ) I have the following code snippet : Now , we know that private and protected fields are private and protected for type , not instance.We also know that access modifiers should work at compile time.So , here is the question - why ca n't I access the FurColor field of the Fox class instance in RedFox ? RedFox is derived from Fox , so the compiler knows it has access to the corresponding protected fields . Also , as you can see in CorrectPaintFox , I can access the protected field of the RedFox class instance . So , why ca n't I expect the same from the Fox class instance ? public class Fox { protected string FurColor ; private string furType ; public void PaintFox ( Fox anotherFox ) { anotherFox.FurColor = `` Hey ! `` ; anotherFox.furType = `` Hey ! `` ; } } public class RedFox : Fox { public void IncorrectPaintFox ( Fox anotherFox ) { // This one is inaccessible here and results in a compilation error . anotherFox.FurColor = `` Hey ! `` ; } public void CorrectPaintFox ( RedFox anotherFox ) { // This is perfectly valid . anotherFox.FurColor = `` Hey ! `` ; } }",C # protected field access "C_sharp : I have a type which I am using as key in the IDictionary . The type is as following Now I have created a dictionary as following in my main as followingNow while debugging I found out that when emp1 is added to the collection only GetHashCode method is called of the key type , after that when emp2 is added to the collection only GetHashCode method is called again but in the case of emp3 both GetHashCode and Equals methods are called . May be it looks too naive being asking this question but why is n't Equals method not called when eqImp2 object is added to collection . What is happening inside . Please explain . public class Employee { public string Name { get ; set ; } public int ID { get ; set ; } public override bool Equals ( object obj ) { Employee emp = obj as Employee ; if ( emp ! = null ) return emp.Name.Equals ( this.Name ) ; return false ; } public override int GetHashCode ( ) { return this.Name.GetHashCode ( ) ; } } IDictionary < Employee , int > empCollection = new Dictionary < Employee , int > ( ) ; Employee emp1 = new Employee ( ) { Name = `` abhi '' , ID = 1 } ; Employee emp2 = new Employee ( ) { Name = `` vikram '' , ID = 2 } ; Employee emp3 = new Employee ( ) { Name = `` vikram '' , ID = 3 } ; empCollection.Add ( emp1 , 1 ) ; empCollection.Add ( emp2 , 2 ) ; empCollection.Add ( emp3 , 3 ) ;",Why is Equals ( ) being not called for the all objects while adding to collection "C_sharp : I have an application created in wpf which requires an updation when updation is available . Update is being compared from an xml file resides on server which contains software version . I have found a reference of video series of SharpUpdater on youtube link Sharp Updater in C # . It works fine for windows form application as I have downloaded and tried that in my application but when it comes to implement the same logic on wpf application it fails somewhere because the api used in this application have the references which work only of winform application . I have used another reference for auto updation Simple Auto Update , auto patch , for WPF Apps , without the Updater Block which also does n't seem to work for my need . I am just curious to know how to place our downloaded .exe in program files when so many restriction are there . For Updation the previous .exe I have used following snippetBut it restricts me to place my downloaded file to the folder which is in program files.Thank you for your grace . private void UpdateApplication ( string tempFilePath , string currentPath , string newPath , string launchArgs ) { string argument = `` /C choice /C Y /N /D Y /T 4 & Del /F /Q \ '' { 0 } \ '' & choice /C Y /N /D Y /T 2 & Move /Y \ '' { 1 } \ '' \ '' { 2 } \ '' & Start \ '' \ '' /D \ '' { 3 } \ '' \ '' { 4 } \ '' { 5 } '' ; ProcessStartInfo Info = new ProcessStartInfo ( ) ; Info.Arguments = String.Format ( argument , currentPath , tempFilePath , newPath , Path.GetDirectoryName ( newPath ) , Path.GetFileName ( newPath ) , launchArgs ) ; Info.WindowStyle = ProcessWindowStyle.Hidden ; Info.CreateNoWindow = true ; Info.FileName = `` cmd.exe '' ; Process.Start ( Info ) ; }",How to add Software updater in wpf without click once and any other third party tool ? "C_sharp : CRM 2016 exposes odata/web api , and has functions and actions out of the box . With the organization service , we can issue a request like this : Is it possible to mimic this functionality using functions/action or any other odata functionality ? I believe that the request should be something like this : However , I 'm not sure how to encode the rest of the request . // Create the van required resource object.RequiredResource vanReq = new RequiredResource { ResourceId = _vanId , ResourceSpecId = _specId } ; // Create the appointment request.AppointmentRequest appointmentReq = new AppointmentRequest { RequiredResources = new RequiredResource [ ] { vanReq } , Direction = SearchDirection.Backward , Duration = 60 , NumberOfResults = 10 , ServiceId = _plumberServiceId , // The search window describes the time when the resouce can be scheduled . // It must be set . SearchWindowStart = DateTime.Now.ToUniversalTime ( ) , SearchWindowEnd = DateTime.Now.AddDays ( 7 ) .ToUniversalTime ( ) , UserTimeZoneCode = 1 } ; // Verify whether there are openings available to schedule the appointment using this resource SearchRequest search = new SearchRequest { AppointmentRequest = appointmentReq } ; SearchResponse searched = ( SearchResponse ) _serviceProxy.Execute ( search ) ; if ( searched.SearchResults.Proposals.Length > 0 ) { Console.WriteLine ( `` Openings are available to schedule the resource . `` ) ; } crmOrg/api/v8.1/Search ( AppointmentRequest= @ request ) ? @ request=",how to get resource 's availability using web api ? "C_sharp : Can someone explain why the following AsObservable method creates an infinite loop even though the end of stream is reached ? A quick tests shows that it produces an infinite loop : Of course I could add an .SubscribeOn ( TaskPoolScheduler.Default ) but however , the infinite loop stays alive ( blocks a task pool scheduler + infinitely reads from Stream ) . [ UPDATE 2017-05-09 ] Shlomo posted a better example to reproduce this issue : public static class StreamExt { public static IObservable < byte > AsObservable ( this Stream stream , int bufferSize ) { return Observable .FromAsync ( cancel = > stream.ReadBytes ( bufferSize , cancel ) ) .Repeat ( ) .TakeWhile ( bytes = > bytes ! = null ) // EndOfStream .SelectMany ( bytes = > bytes ) ; } private static async Task < byte [ ] > ReadBytes ( this Stream stream , int bufferSize , CancellationToken cancel ) { var buf = new byte [ bufferSize ] ; var bytesRead = await stream .ReadAsync ( buf , 0 , bufferSize , cancel ) .ConfigureAwait ( false ) ; if ( bytesRead < 1 ) return null ; // EndOfStream var result_size = Math.Min ( bytesRead , bufferSize ) ; Array.Resize ( ref buf , result_size ) ; return buf ; } } class Program { static void Main ( string [ ] args ) { using ( var stream = new MemoryStream ( new byte [ ] { 1 , 2 , 3 } ) ) { var testResult = stream .AsObservable ( 1024 ) .ToEnumerable ( ) .ToArray ( ) ; Console.WriteLine ( testResult.Length ) ; } } } int i = 0 ; var testResult = Observable.FromAsync ( ( ) = > Task.FromResult ( i++ ) ) .Repeat ( ) .TakeWhile ( l = > l < 3 ) ; testResult.Subscribe ( b = > Console.WriteLine ( b ) , e = > { } , ( ) = > Console.WriteLine ( `` OnCompleted '' ) ) ; Console.WriteLine ( `` This is never printed . `` ) ;",Combination of Observable.FromAsync+Repeat+TakeWhile creates infinite loop "C_sharp : Should an asynchronous library method call await ? For example , assume I have a data services library method that has access to an Entity Framework 6 data context named 'repository ' . As far as I can see , I have two ways of defining this method : or without async/await decorationAt the application end-point , in this case an MVC controller action , , the call would be the same for either method : This scenario could , of course , be more complicated where the application calls a chain of asynchronous methods . Should each method in the chain call await , or should there only ever be one await statement at the end of the call chain , and what difference would this make ? public static async Task < IEnumerable < Blogs > > GetAllBlogsAsync ( EfDataContext db ) { return await db.Blogs .OrderByDescending ( b = > b.Date ) .SelectAsync ( ) ; } public static Task < IEnumerable < Blogs > > GetAllBlogsAsync ( EfDataContext db ) { return db.Blogs .OrderByDescending ( b = > b.Date ) .SelectAsync ( ) ; } public async Task < ActionResult > Blogs ( ) { var blogs = await BlogService.GetAllBlogs ( _blogRepository ) ; return View ( blogs ) ; }",Should C # Asynchronous Library Methods Call await ? "C_sharp : With my current settings , ReSharper breaks a long line like this : I think it 's better than not breaking the line at all , but breaking it at the dots of methods/properties makes more sense to me : ( It does n't have to look exactly like this . ) How can I setup ReSharper to do it this way ? I have n't found such option in its settings . var attributes = GetType ( ) .GetMethod ( ( string ) filterContext.RouteData.Values [ `` action '' ] ) .GetCustomAttributes ( typeof ( AutomaticRedirectToViewAttribute ) , false ) ; var attributes = GetType ( ) .GetMethod ( ( string ) filterContext.RouteData.Values [ `` action '' ] ) .GetCustomAttributes ( typeof ( AutomaticRedirectToViewAttribute ) , false ) ;",Automatic line breaks on dots in method chains in ReSharper "C_sharp : According to the definition : '' As interface is not an object by itself , I ca n't initialize it.If interface were allowed to declare fileds , then it needs storage location , so we can not declare fields inside interface . `` Incase of property say example when i declare inside the interface It is internally hooked as get_SayHello ( ) , set_SayHello ( ) in IL ( when i disassemble i can see the get and set methods ) .My question is still property needs some storage location , then how the property declaration is allowed inside the interface.Edit : This is what i understood.As I am new to C # , i am seeking your help . string SayHello { get ; set ; }",C # - Property Clarification "C_sharp : This is from a newer C # guy , I have been back and forth through different questions posed on here but I have n't found anything that answers directly to what I need to know . I have a console application that I want to pass arguments to , through the command line . This is what I have so far and it 's working for a single argument , now I got to add another but I ca n't seem to figure out where to start . If I take everything out of my else statement how can I set what the args are and assign ? Will the below work ? static void Main ( string [ ] args ) { if ( args == null || args.Length== 0 ) { Console.WriteLine ( `` that 's not it '' ) ; help ( ) ; } else { for ( int i = 0 ; i < args.Length ; i++ ) { backupfolder = args [ i ] ; } checks ( ) ; } } static void Main ( string [ ] args ) { if ( args == null || args.Length== 0 ) { Console.WriteLine ( `` that 's not it '' ) ; help ( ) ; } else { string backupfolder = args [ 0 ] ; string filetype = args [ 1 ] ; checks ( ) ; } }",C # Using Multiple Arguments "C_sharp : I was trying to develop a multicast receiver program and socket initialization was done as shown below : When my PC is not connected to a network , SetSocketOption method was throwing exception and even after network is connected , I was unable to receive data because socket options are not set.To avoid this I used a thread which runs in the background checking for network availability and once network is available , it sets the socket options.It works properly in some PC 's but in some others , NetworkInterface.GetIsNetworkAvailable ( ) returned true before network got connected ( while network was being identified ) . So , to make sure Socket options are set , I used a bool variable sockOptnSetwhich is set as true if all the statements in the try block is executed as shown inside the method public void SetSocketOptions ( ) This program works fine in all PC 's I tried , but I am doubtful about how much I can rely on this to work.My questions are:1 ) Is this good practice ? 2 ) If not , what are the possible errors or problems it may cause ? And how can I implement it in a better way ? public void initializeThread ( ) { statuscheckthread = new Thread ( SetSocketOptions ) ; statuscheckthread.IsBackground = true ; } private void Form1_Load ( object sender , EventArgs e ) { rxsock = new Socket ( AddressFamily.InterNetwork , SocketType.Dgram , ProtocolType.Udp ) ; iep = new IPEndPoint ( IPAddress.Any , 9191 ) ; rxsock.Bind ( iep ) ; ep = ( EndPoint ) iep ; initializeThread ( ) ; statuscheckthread.Start ( ) ; } public void SetSocketOptions ( ) { initializeThread ( ) ; //re-initializes thread thus making it not alive while ( true ) { if ( NetworkInterface.GetIsNetworkAvailable ( ) ) { bool sockOptnSet = false ; while ( ! sockOptnSet ) { try { rxsock.SetSocketOption ( SocketOptionLevel.IP , SocketOptionName.AddMembership , new MulticastOption ( IPAddress.Parse ( `` 224.50.50.50 '' ) ) ) ; rxsock.SetSocketOption ( SocketOptionLevel.IP , SocketOptionName.MulticastTimeToLive , 64 ) ; sockOptnSet = true ; } catch { //Catch exception here } } } break ; // Break out from loop once socket options are set } }",Is it good practice to put try-catch in a loop until all statements in the try block is executed without any exceptions ? "C_sharp : I have setup a standard ASP.NET MVC site with normal authentication . I have added roles , so new users get a specific role.Now , I want to be able to impersonate a user.Impersonating adviceImpersonating , when I search around , comes the following way : This does n't work by default , as you have to do two things:1 : Enable forms authentication:2 : Disable the module : The challengeHowever , doing this leaves a couple of challenges.When you impersonate , you can not log out . This is easily fixed byadding the following in LogOut : FormsAuthentication.SignOut ( ) ; The User.IsInRole ( Constants.Roles.Creditor ) ; stops working , sowe can not check if user in a roleWhat to do ? This COULD boil down to me - apparently - not fully understanding the membership framework despite trying . However , how do you get impersonate to work here ? I have no explicit reason to use `` Forms '' authentication , and the only reason I started on this path is Impersonating . So I see I have two obvious directions : A ) Implement impersonation in a different way , so I do n't touch myweb.config to use forms B ) Fix the role problem in formsAny help here ? : - ) FormsAuthentication.SetAuthCookie ( user.UserName , false ) ; < system.web > < authentication mode= '' Forms '' / > < /system.web > < system.webServer > < modules > < ! -- < remove name= '' FormsAuthentication '' / > -- > < /modules > < staticContent >",Impersonate a user in a standard ASP.NET MVC installation template "C_sharp : So , in the following snippet , why is ReadAsStringAsync an async method ? Originally I expected SendAsync to send the request and load the response stream into memory at which point reading that stream would be in-process CPU work ( and not really async ) .Going down the source code rabbit hole , I arrived at this : https : //github.com/dotnet/corefx/blob/0aa654834405dcec4aaa9bd416b2b31ab8d3503e/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs # L967This makes me think that maybe the connection is open until the response stream is actually read from some source outside of the process ? I fully expect that I am missing some fundamentals regarding how streams from Http Connections work . var response = await _client.SendAsync ( request ) ; var body = await response.Content.ReadAsStringAsync ( ) ; int count = await _stream.ReadAsync ( destination , cancellationToken ) .ConfigureAwait ( false ) ;",Why is ReadAsStringAsync async ? "C_sharp : Resharper 2016.2Current formattingExpected formattingWhich Resharper 2016.2 configuration can fix that ? Please note , initializer is inside argument brackets , not in variable . IEnumerable < Customer > customers = dbCustomers.Select ( customer = > new Customer { Name = customer.Name , Address = customer.Address , Number = customer.Number } ) ; IEnumerable < Customer > customers = dbCustomers.Select ( customer = > new Customer { Name = customer.Name , Address = customer.Address , Number = customer.Number } ) ;",How to fix Resharper object initializer indentation as method argument "C_sharp : My library is using isolated storage but only does so on demand . So I 'm using Lazy < T > .However , this throws : System.IO.IsolatedStorage.IsolatedStorageException `` Unable to determine granted permission for assembly . `` Does Lazy do something weird with threads that confuses isolated storage initialization ? Sample code : Full stack trace : using System ; using System.IO.IsolatedStorage ; namespace ConsoleApplication1 { class Program { static void Main ( string [ ] args ) { var thisWorks = IsolatedStorageFile.GetMachineStoreForAssembly ( ) ; thisWorks.Dispose ( ) ; var lazyStorage = new Lazy < IsolatedStorageFile > ( IsolatedStorageFile.GetMachineStoreForAssembly ) ; var thisFails = lazyStorage.Value ; thisFails.Dispose ( ) ; } } } System.IO.IsolatedStorage.IsolatedStorageException was unhandled Message=Unable to determine granted permission for assembly . Source=mscorlib StackTrace : Server stack trace : at System.IO.IsolatedStorage.IsolatedStorage.InitStore ( IsolatedStorageScope scope , Type domainEvidenceType , Type assemblyEvidenceType ) at System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForAssembly ( ) at System.Lazy ` 1.CreateValue ( ) Exception rethrown at [ 0 ] : at System.IO.IsolatedStorage.IsolatedStorage.InitStore ( IsolatedStorageScope scope , Type domainEvidenceType , Type assemblyEvidenceType ) at System.IO.IsolatedStorage.IsolatedStorageFile.GetMachineStoreForAssembly ( ) at System.Lazy ` 1.CreateValue ( ) at System.Lazy ` 1.LazyInitValue ( ) at System.Lazy ` 1.get_Value ( ) at ConsoleApplication1.Program.Main ( String [ ] args ) in C : \Users\Andrew Davey\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs : line 19 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at System.AppDomain.ExecuteAssembly ( String assemblyFile , Evidence assemblySecurity , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ThreadHelper.ThreadStart_Context ( Object state ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean ignoreSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( ) InnerException :",Lazily creating isolated storage "C_sharp : Consider : How does this even compile , nonetheless work ? I should not be able to assign a the different value to _value field outside of the constructor , as it 's marked with readonly . However , pass it by ref to a method , and it can indeed be manipulated.Is this dangerous ? Why ? It feels wrong to me , but I ca n't quite put my finger on it . class Foo { private readonly string _value ; public Foo ( ) { Bar ( ref _value ) ; } private void Bar ( ref string value ) { value = `` hello world '' ; } public string Value { get { return _value ; } } } // ... var foo = new Foo ( ) ; Console.WriteLine ( foo.Value ) ; // `` hello world ''",Why can readonly fields be modified through ref parameters ? C_sharp : I need to programmatically get the last author of a specific line in the Git history with C # .I tried using libgit2sharp : But this is the equivalent of the commandgit blame < file > And in fact I needgit blame -w < file > ( to ignore whitespace when comparing ) Libgit2sharp do not set the -w switch and do n't provide any parameter/option to set it.What are my options ? Do you know any other library compatible with the -w switch of the blame command ? var repo = new LibGit2Sharp.Repository ( gitRepositoryPath ) ; string relativePath = MakeRelativeSimple ( filename ) ; var blameHunks = repo.Blame ( relativePath ) ; // next : find the hunk which overlap the desired line number,Programmatically do `` Git blame -w '' in C # C_sharp : is it possible to do something like the following : I want to catch a custom exception and do something with it - easy : try { ... } catch ( CustomException ) { ... } But then i want to run the code used in the `` catch all '' block still run some other code which is relevant to all catch blocks ... or do i have to put whatever i want to do in all exception cases ( finally is not an option because i want it only to run for the exceptions ) into a separate method/nest the whole try/catch in another ( euch ) ... ? try { throw new CustomException ( `` An exception . `` ) ; } catch ( CustomException ex ) { // this runs for my custom exceptionthrow ; } catch { // This runs for all exceptions - including those caught by the CustomException catch },Reuse catch for all catches "C_sharp : I 'm making my first game for Windows Phone ( XNA ) . I use Accelerometer to change the position of a crosshair on the screen : Here is the code in my Initialize ( ) function ( note that Accelerometer is local variable declared only in this function ) : And the event handler : This works fine on Windows Phone Emulator , and on my Nokia Lumia 520 connected to the computer and launching from Visual Studio , however when I launch the game in the phone ( not connected to the computer ) , the accelerometer_CurrentValueChanged event appears to be called only once , on application startup.My solution was to make the accelerometer a member of my Game class , then code in Initialize ( ) like this : So my question is , why does this solution work ? And why is there a difference between application launched from VS and normally , even on the same device ? Accelerometer accelerometer = new Accelerometer ( ) ; accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged ; accelerometer.Start ( ) ; void accelerometer_CurrentValueChanged ( object sender , SensorReadingEventArgs < AccelerometerReading > e ) { lock ( accelerometerVectorLock ) { accelerometerVector = new Vector3 ( ( float ) e.SensorReading.Acceleration.X , ( float ) e.SensorReading.Acceleration.Y , ( float ) e.SensorReading.Acceleration.Z ) ; } } accelerometer = new Accelerometer ( ) ; accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged ; accelerometer.Start ( ) ;",Windows Phone 8 Accelerometer events "C_sharp : Firstly I have seen IEqualityComparer for anonymous type and the answers there do not answer my question , for the obvious reason that I need an IEqualityComparer not and IComparer for use with Linq 's Distinct ( ) method . I have checked the other answers too and these fall short of a solution ... The ProblemI have some code to manipulate and pull records in from a DataTablebut I need the distinct method to be case insensitive . What is throwing me here is the use of anonymous types . Attempted Solution 1If I had SomeClass which had concrete objects I could obviously do I could obviously do this where However , the use of anonymous types in the above Linq query are throwing me . Attempted Solution 2To attempt another solution to this ( and because I have the same issue elsewhere ) I generated the following generic comparer classso that I could attempt to do but this casts the returned value as IEnumerable < dynamic > which in turn effects my forthcoming use of cflist , so that in a following query the join fails . I do n't want to get into ugly casting to and from IEnumerable < T > s due to the heavy use of this code ... QuestionIs there a way I can create my an IEquailityComparer for my anonymous types ? Thanks for your time . var glext = m_dtGLExt.AsEnumerable ( ) ; var cflist = ( from c in glext orderby c.Field < string > ( m_strpcCCType ) , c.Field < string > ( m_strpcCC ) , c.Field < string > ( m_strpcCCDesc ) , c.Field < string > ( m_strpcCostItem ) select new { CCType = c.Field < string > ( m_strpcCCType ) , CC = c.Field < string > ( m_strpcCC ) , CCDesc = c.Field < string > ( m_strpcCCDesc ) , CostItem = c.Field < string > ( m_strpcCostItem ) } ) .Distinct ( ) ; public class SumObject { public string CCType { get ; set ; } public string CC { get ; set ; } public string CCDesc { get ; set ; } public string CostItem { get ; set ; } } List < SumObject > lso = new List < SumObject > ( ) { new SumObject ( ) { CCType = `` 1-OCC '' , CC = `` 300401 '' , CCDesc = `` Rooney '' , CostItem = `` I477 '' } , new SumObject ( ) { CCType = `` 1-OCC '' , CC = `` 300401 '' , CCDesc = `` Zidane '' , CostItem = `` I677 '' } , new SumObject ( ) { CCType = `` 1-OCC '' , CC = `` 300401 '' , CCDesc = `` Falcao '' , CostItem = `` I470 '' } , } ; var e = lso.Distinct ( new SumObjectComparer ( ) ) ; // Great : ] class SumObjectComparer : IEqualityComparer < SumObject > { public bool Equals ( SumObject x , SumObject y ) { if ( Object.ReferenceEquals ( x , y ) ) return true ; if ( Object.ReferenceEquals ( x , null ) || Object.ReferenceEquals ( y , null ) ) return false ; return x.CCType.CompareNoCase ( y.CCType ) == 0 & & x.CC.CompareNoCase ( y.CC ) == 0 & & x.CCDesc.CompareNoCase ( y.CCDesc ) == 0 & & x.CostItem.CompareNoCase ( y.CostItem ) == 0 ; } public int GetHashCode ( SumObject o ) { if ( Object.ReferenceEquals ( o , null ) ) return 0 ; int hashCCType = String.IsNullOrEmpty ( o.CCType ) ? 0 : o.CCType.ToLower ( ) .GetHashCode ( ) ; int hashCC = String.IsNullOrEmpty ( o.CC ) ? 0 : o.CC.ToLower ( ) .GetHashCode ( ) ; int hashCCDesc = String.IsNullOrEmpty ( o.CCDesc ) ? 0 : o.CCDesc.ToLower ( ) .GetHashCode ( ) ; int hashCostItem = String.IsNullOrEmpty ( o.CostItem ) ? 0 : o.CostItem.ToLower ( ) .GetHashCode ( ) ; return hashCCType ^ hashCC ^ hashCCDesc ^ hashCostItem ; } } public class GenericEqualityComparer < T > : IEqualityComparer < T > { Func < T , T , bool > compareFunction ; Func < T , int > hashFunction ; public GenericEqualityComparer ( Func < T , T , bool > compareFunction , Func < T , int > hashFunction ) { this.compareFunction = compareFunction ; this.hashFunction = hashFunction ; } public bool Equals ( T x , T y ) { return compareFunction ( x , y ) ; } public int GetHashCode ( T obj ) { return hashFunction ( obj ) ; } } var comparer = new GenericEqualityComparer < dynamic > ( ( x , y ) = > { /* My equality stuff */ } , o = > { /* My hash stuff */ } ) ; var cf = ( from o in cflist join od in glext on new { o.CCType , o.CC , o.CCDesc , o.CostItem } equals new { CCType = od.Field < string > ( m_strpcCCType ) , CC = od.Field < string > ( m_strpcCC ) , CCDesc = od.Field < string > ( m_strpcCCDesc ) , CostItem = od.Field < string > ( m_strpcCostItem ) } into c select new { ... }",IEqualityComparer for Annoymous Type "C_sharp : In this question , when mentioning the compiler , I 'm actually referring to the Roslyn compiler . The problem arises when using IntelliSense , which is presumed to be the same compiler.For demonstration purposes and completeness , the following classes are used ( using Visual Studio 2015 with C # 6.0 and .NET 4.6.1 ) : Behold the following extension method : The compiler is able to infer it while consuming like this : Also behold this overloaded extension method : The compiler is NOT able to infer T1 when typing it like this : This screenshot example will describe more of what I mean with not able to infer : Also I 'm getting this error message when hovering over the extension method with my mouse ( I 've replaced the < and > characters with [ and ] respectively , because StackOverflow can not format those in a quote ) : The type arguments for method 'FooBar [ T1 , T2 ] ( this Helper [ IEnumerable [ T1 ] ] , Expression [ Func [ T1 , IEnumerable [ T2 ] ] ] ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.But when completing it manually like this : the compiler is happy.Why ca n't the compiler/IntelliSense ( or the autocomplete feature of Visual Studio ) figure out T1 and wants me to specify the type arguments explicitly when I start typing ? Note that if I omit IEnumerable < > everywhere in my examples , the compiler can happily infer everything while typing.The compiler is also happy after you manually type in l = > l.B . It then knows T1 is A , so you can express the last argument with the help of IntelliSense . public class A { public IEnumerable < B > B { get ; set ; } } public class B { public IEnumerable < C > C { get ; set ; } } public class C { } public class Helper < T > { } public static void FooBar < T1 , T2 > ( this Helper < IEnumerable < T1 > > helper , Expression < Func < T1 , IEnumerable < T2 > > > expression ) { ... } Helper < IEnumerable < B > > helper = ... ; helper.FooBar ( l = > l.C ) ; //T1 is B and T2 is C public static void FooBar < T1 , T2 , T3 > ( this Helper < T1 > helper , Expression < Func < T1 , IEnumerable < T2 > > > expression1 , Expression < Func < T2 , IEnumerable < T3 > > > expression2 ) { ... } Helper < A > helper = ... ; helper.FooBar ( l = > l. //compiler/IntelliSense can not infer that T1 is A helper.FooBar ( l = > l.B , l = > l.C ) ; //compiler infers that T1 is A , T2 is B and T3 is C",Open generic type arguments can not be inferred from the usage "C_sharp : I have a simple client application that receives byte buffers from the network with a low throughput . Here is the code : The threading behavior of the application is quite curious : The SocketAsyncEventsArgsCompleted method is frequently run in new threads . I would have expected that after some time no new thread would be created . I would have expected the threads to be reused , because of the thread pool ( or IOCP thread pool ) and because the throughput is very stable.The number of threads stays low , but I can see in the process explorer that threads are frequently created and destroyed . Likewise , I would not have expected threads to be created or destroyed.Can you explain the application behavior ? Edit : The `` low '' throughput is 20 messages per second ( roughly 200 KB/s ) . If I increase the throughput to more than 1000 messages per second ( 50 MB/s ) , the application behavior does not change . private static readonly HashSet < int > _capturedThreadIds = new HashSet < int > ( ) ; private static void RunClient ( Socket socket ) { var e = new SocketAsyncEventArgs ( ) ; e.SetBuffer ( new byte [ 10000 ] , 0 , 10000 ) ; e.Completed += SocketAsyncEventsArgsCompleted ; Receive ( socket , e ) ; } private static void Receive ( Socket socket , SocketAsyncEventArgs e ) { var isAsynchronous = socket.ReceiveAsync ( e ) ; if ( ! isAsynchronous ) SocketAsyncEventsArgsCompleted ( socket , e ) ; } private static void SocketAsyncEventsArgsCompleted ( object sender , SocketAsyncEventArgs e ) { if ( e.LastOperation ! = SocketAsyncOperation.Receive || e.SocketError ! = SocketError.Success || e.BytesTransferred < = 0 ) { Console.WriteLine ( `` Operation : { 0 } , Error : { 1 } , BytesTransferred : { 2 } '' , e.LastOperation , e.SocketError , e.BytesTransferred ) ; return ; } var thread = Thread.CurrentThread ; if ( _capturedThreadIds.Add ( thread.ManagedThreadId ) ) Console.WriteLine ( `` New thread , ManagedId : `` + thread.ManagedThreadId + `` , NativeId : `` + GetCurrentThreadId ( ) ) ; //Console.WriteLine ( e.BytesTransferred ) ; Receive ( ( Socket ) sender , e ) ; }",Why is the Completed callback from SocketAsyncEventArgs frequently executed in newly created threads instead of using a bounded thread pool ? "C_sharp : I have a class that should delete some file when disposed or finalized . Inside finalizers I ca n't use other objects because they could have been garbage-collected already.Am I missing some point regarding finalizers and strings could be used ? UPD : Something like that : public class TempFileStream : FileStream { private string _filename ; public TempFileStream ( string filename ) : base ( filename , FileMode.Open , FileAccess.Read , FileShare.Read ) { _filename = filename ; } protected override void Dispose ( bool disposing ) { base.Dispose ( disposing ) ; if ( _filename == null ) return ; try { File.Delete ( _filename ) ; // < -- oops ! _filename could be gc-ed already _filename = null ; } catch ( Exception e ) { ... } } }",Which objects can I use in a finalizer method ? "C_sharp : I have a function that accepts an Enumerable . I need to ensure that the enumerator is evaluated , but I 'd rather not create a copy of it ( e.g . via ToList ( ) or ToArray ( ) ) if it is all ready in a List or some other `` frozen '' collection . By Frozen I mean collections where the set of items is already established e.g . List , Array , FsharpSet , Collection etc , as opposed to linq stuff like Select ( ) and where ( ) .Is it possible to create a function `` ForceEvaluation '' that can determine if the enumerable has deffered execution pending , and then evaluate the enumerable ? } After some more research I 've realized that this is pretty much impossible in any practical sense , and would require complex code inspection of each iterator.So I 'm going to go with a variant of Mark 's answer and create a white-list of known safe types and just call ToList ( ) anything not on that is not on the white-list.Thank you all for your help.Edit* After even more reflection , I 've realized that this is equivalent to the halting problem . So very impossible . public void Process ( IEnumerable < Foo > foos ) { IEnumerable < Foo > evalutedFoos = ForceEvaluation ( foos ) EnterLockedMode ( ) ; // all the deferred processing needs to have been done before this line . foreach ( Foo foo in foos ) { Bar ( foo ) ; } } public IEnumerable ForceEvaluation ( IEnumerable < Foo > foos ) { if ( ? ? ? ? ? ? ) { return foos } else { return foos.ToList ( ) } }",Is it possible to determine if an IEnumerable < T > has deffered execution pending ? "C_sharp : I have a task that looks like this : LongMethod calls a long running service , during which I can ’ t ( or at least , don ’ t think I can ) , constantly poll a cancellation token to see if it has been cancelled . However , I am interested in ‘ cancelling ’ , or ignoring , the callback method.When the TaskCallback is called , I am only interested in the ‘ result ’ if it is the from the most recent task ( let us assume that the service that LongMethod calls preserves order , and also assume that the user can click the button numerous times , but only the latest one is relevant ) .I have modified my code in the following way : after a task is created , I add it to the top of a stack . In the TaskCallback , I check to see if the task that has been passed to the callback is the most recent one ( i.e . a TryPeek at the top of the stack ) . If it is not , I just ignore the result.I am quite certain that this isn ’ t a ‘ best practices ’ solution . But what is ? Passing and maintaing cancellation tokens doesn ’ t really seem all that elegant , either . var task = Task.Factory.StartNew < object > ( LongMethod ) ; task.ContinueWith ( TaskCallback , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ; private ConcurrentStack < Task > _stack = new ConcurrentStack < Task > ( ) ; private void OnClick ( object sender , ItemClickEventArgs e ) { var task = Task.Factory.StartNew < object > ( LongMethod ) ; task.ContinueWith ( TaskCallback , TaskScheduler.FromCurrentSynchronizationContext ( ) ) ; _stack.Push ( task ) ; } private void TaskCallback ( Task < object > task ) { Task topOfStack ; if ( _stack.TryPeek ( out topOfStack ) ) //not the most recent { if ( task ! = topOfStack ) return ; } //else update UI }",Only need 'most recent ' Task - best practices for cancelling/ignoring ? C_sharp : what values does C # predefine for use ? # if SYMBOL //code # endif,What Predefined # if symbos does c # have ? "C_sharp : I 'm noticing strange behavior . I have merchant and order tables and doing two selects one , after other , selects are very simple ( select * from merchant , select * from order ) .Here is sql profiler trace , when I 'm selecting first merchants , then orders : notice , that orders select is taking whooping 75 seconds ( that is for a ~80.000 records , on a really decent machine 8gb ram , ssd , i7 ) .Now if I change the sequence and select first orders , then merchants : order query execution time dropped to 2.5 seconds in profiler , but in application it is about the same as in first case ( I guess because EF inside tries to bind orders to merchants , as there 's foreign key between them ) . So question is why profiler sees different times and what EF is doing in second case so long , may be something is configured wrong ? UPDATE : I 've started to localize the issue with clean EF model and it works ok . I 'm using EF T4 templates to generate context and entity classes , so may be it is outdated and causing problem , will give know if will find something concrete - I think that is somehow related with fixup collections , so looks like SQL profiler was misleading - I guess query was executed ok , just it waited on EF to complete reading results or smth ( I mean may be EF is doing something expesive while reading results ) . using ( var myEntities = new myEntities ( ) ) { var merchants = myEntities.Merchants.ToList ( ) ; var orders = myEntities.Orders.ToList ( ) ; }",EntityFramework - query execution time depends on select order ? "C_sharp : Is there a library out there that will allow me to write the following kind of code , which parses CSS and returns a queryable object modelI 've taken a look at dotless , downloaded their code and examined some of the relevant unit tests and fixtures . It looks promising but I ca n't quite work out how to use it to parse and query plain CSS . string input = `` p , span { font-family : arial ; } '' ; var cssRules = new Parser ( ) .Parse ( input ) ; var rule = cssRules.Find ( new Selector ( `` p '' ) ) .First ( ) ; Assert.That ( rule.Attribute ( `` font-family '' ) .Value , Is.Equal.To ( `` arial '' ) ) ;",Is there a CSS object model or CSS querying api for .net ? "C_sharp : Tried to reuse Sum but got this error : can not resolve method Sumhow can I change my syntax private static void AggregatesData ( User user ) { user.TotalActiveUsers = SumToolbarsData ( user.bars , ( tb = > tb.ActiveUsers ) ) ; user.TotalInstalls = SumToolbarsData ( user.bars , ( tb = > tb.Installs ) ) ; user.TotalBalance = SumToolbarsData ( user.bars , ( tb = > tb.Balance ) ) ; } private static T SumToolbarsData < T > ( List < Bar > bars , Func < Bar , T > selector ) { return bars.Sum < T > ( selector ) ; }",can not resolve method Sum C_sharp : I am trying to have my bot framework bot reply to a user by starting a thread . This way I can keep who the bot is talking to when in a channel with many people straight . According to the slack documentation what I need to do is set the thread_ts property to the ts property sent to my bot . I have tried a few things and have been unable to accomplish this . This is the most concise example I have : This is not working for me . var reply = ( Activity ) activity ; reply = reply.CreateReply ( `` reply '' ) ; reply.ChannelData = JObject.Parse ( $ '' { { thread_ts : ' { ts } ' } } '' ) ; await context.PostAsync ( reply ) ;,How can a bot start a thread in Slack "C_sharp : Is it possible to separate Date and time with `` .So it would be : Right now i have : and String.Format shows me just `` ddMMyyyy , HHmmss '' Thank you everyone for helping me ! ! ! But i will mark the first answer as the right one `` ddMMyyyy '' , '' HHmmss '' DateTime dt = aPacket.dtTimestamp ; string d = dt.ToString ( `` \ '' ddMMyyyy\ '' , \ '' HHmmss\ '' '' ) ;",Separate Date and time with `` ( String.Format ) "C_sharp : In C # I can declare the followingIn Haskell I would type out the above asWhat I do n't like about the Haskell counterpart is that I have to repeat field twice in the data definition of A ( this becomes more tiresome as the number of fields increases that are present in A that need to be in B ) . Is there a more concise way in Haskell to write B as a subclass of A ( that is somewhat similar to the C # way ) ? class A { int Field ; } class B : A { int Field2 ; } static int f ( A a ) { return a.Field ; } static int f ( B b ) { return a.Field + b.Field2 ; } static void Main ( string [ ] args ) { A a = new A ( ) { Field = 1 } ; A b = new B ( ) { Field = 1 , Field = 2 } ; Console.WriteLine ( f ( a ) + f ( b ) ) ; } data A = A { field : : Int } | B { field : : Int , field2 : : Int } f : : A - > Intf ( A a ) = af ( B a b ) = a + bmain : : IO ( ) main = do putStrLn $ show ( f ( a ) + f ( b ) ) where a = A 1 b = B 1 2",OOP style inheritance in Haskell "C_sharp : I have a bit of code that reads a json response from an HTTP server , it then parses this and inserts the data into a ListBox control.The event I fire off when the download is complete is the following : Now , when I do the items.add I presume it 's just joining up the 3 variables and adding it to one column in the ListBox . This works fine and I see all 3 items joined up and displayed.I want to separate this and make it look a bit nicer so I 've created some XAML to try and bind the variables to textblocks . The following is just binding the username . I also have a public class that get/sets all 3 variables.When running the above I get nothing displayed at all . I have a feeling it 's something simple ? Thanks . void webClient_OpenReadCompleted ( object sender , OpenReadCompletedEventArgs e ) { DataContractJsonSerializer ser = null ; try { ser = new DataContractJsonSerializer ( typeof ( ObservableCollection < UserLeaderboards > ) ) ; ObservableCollection < UserLeaderboards > users = ser.ReadObject ( e.Result ) as ObservableCollection < UserLeaderboards > ; foreach ( UserLeaderboards em in users ) { int Fid = em.id ; string Fusername = em.username ; int Fscore = em.score ; lstbLeaders.Items.Add ( Fid + Fusername + Fscore ) ; } } catch ( Exception ex ) { MessageBox.Show ( ex.Message ) ; } } < ListBox Height= '' 346 '' HorizontalAlignment= '' Left '' Margin= '' 5,221,0,0 '' Name= '' lstbLeaders '' VerticalAlignment= '' Top '' Width= '' 446 '' > < DataTemplate > < TextBlock Text= '' { Binding Source=Fusername } '' / > < /DataTemplate > < /ListBox >",Databinding with a listbox "C_sharp : I 'm running in a corner case here with regarding the difference with scoping of instance methods/properties in C # . Here is the code : The code compiles fine on MonoDevelop 3.0 , but gives an error in VS2010 saying : An object reference is required for the non-static field , method , or property `` Base.Execute '' Basically , it boils down to the fact that when calling base class 's constructor from derived class 's constructor , MS 's C # compiler does not allow access to derived class 's methods/properties , etc . How so ? public class Base { public EventHandler Click { get ; set ; } public Base ( EventHandler clickHandler ) { this.Click = clickHandler ; } } public class Derived : Base { public Derived ( ) : base ( ( sender , e ) = > Execute ( ) ) { } private void Execute ( ) { } }",The difference between Mono C # Compiler and MS C # Compiler Regarding Scope "C_sharp : I read this question 's answers that explain the order of the LINQ to objects methods makes a difference . My question is why ? If I write a LINQ to SQL query , it does n't matter the order of the LINQ methods-projections for example : The expression tree will be transformed to a rational SQL like this : When I Run the query , SQL query will built according to the expression tree no matter how weird the order of the methods.Why it does n't work the same with LINQ to objects ? when I enumerate an IQueryable all the projections can be placed in a rational order ( e.g . Order By after Where ) just like the Data Base optimizer does . session.Query < Person > ( ) .OrderBy ( x = > x.Id ) .Where ( x = > x.Name == `` gdoron '' ) .ToList ( ) ; SELECT * FROM Persons WHERE Name = 'gdoron ' ORDER BY Id ;",Why the order of LINQ to objects methods counts "C_sharp : With the following understanding about null coalescing operator ( ? ? ) in C # .While , by definition and usage , Case I and Case II are same.It is surprising to see that in Case-I compiler is able to implicitly cast int ? to int while in Case-II it shows error : 'Error 1 Can not implicitly convert type 'int ? ' to 'int ' '' What is it that I am missing about null-coalescing operator ? Thanks for your interest . int ? input = -10 ; int result = input ? ? 10 ; //Case - I//is same as : int result = input == null ? input : 10 ; // Case - II",Implicit casting of Null-Coalescing operator result "C_sharp : I am developing Interface for a sample project i wanted it to be as generic as possible so i created a interface like belowbut then it happened i had to duplicate the interface to do belowif you looked at above difference is just types they return , so i created something like below only to find i get error Can not Resolve Symbol T What am i doing wrong public interface IUserFactory { IEnumerable < Users > GetAll ( ) ; Users GetOne ( int Id ) ; } public interface IProjectFactory { IEnumerable < Projects > GetAll ( User user ) ; Project GetOne ( int Id ) ; } public interface IFactory { IEnumerable < T > GetAll ( ) ; T GetOne ( int Id ) ; }",How do i return IEnumerable < T > from a method "C_sharp : I have a list of invoices that have both start and end dates . Can I use LINQ to get all the start and end dates from the invoice list and put them into a new list of type Period : I can do this with a foreach as shown below but wanted to know if there was a better way to do this with LINQ . Period ( DateTime startDate , DateTime endDate ) { } ; foreach ( Invoice invoice in invoices ) { periods.Add ( new Period ( invoice.StartDate , invoice.EndDate ) ) ; }",Can I use LINQ to create a new list of objects from an existing list "C_sharp : I want a typed lookup helper function for a heterogenous collection : It should return a struct or class , else null if the item is not found.Below is an example using a trivial collection lookup , but it could be a database call or whatever.Is there any way to achieve this with a single method signature ? What I 've already tried : I understand that generic restrictions ca n't be used to disambiguate overloads . So I ca n't simply give these two methods the same name.Returning ( Default ) T is n't an option , since 0 is a valid int value.I have tried calling with < int ? > as the type , but as discussed , Nullable < T > is n't a reference type.Is there some way to indicate that I 'm going to return a boxed int ? public T GetClass < T > ( string key ) where T : class { object o ; if ( Contents.TryGetValue ( key , out o ) ) { return o as T ; } return null ; } public T ? GetStruct < T > ( string key ) where T : struct { object o ; if ( Contents.TryGetValue ( key , out o ) ) { if ( o is T ) { return ( T ? ) o ; } } return null ; }",How to implement generic collection lookup method that can return class or nullable struct ? "C_sharp : Consider the following methods.If we call DoA ( ) , do the subsequent interactions in DoB ( ) and DoC ( ) run in the context of DoA ( ) 's transaction as it pertains to SQL Server ? Does DoC ( ) run in the context of both DoA ( ) and DoB ( ) 's transactions ? ( Or am I grossly misunderstanding something ? ) DoA ( ) { using ( TransactionScope scope = new TransactionScope ) { using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; SqlCommand command = new SqlCommand ( query , connection ) ; command.ExecuteNonReader ( ) ; DoB ( ) ; scope.Complete ( ) ; } } } DoB ( ) { using ( TransactionScope scope = new TransactionScope ) { using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; SqlCommand command = new SqlCommand ( query , connection ) ; command.ExecuteNonReader ( ) ; DoC ( ) ; scope.Complete ( ) ; } } } DoC ( ) { using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; SqlCommand command = new SqlCommand ( query , connection ) ; command.ExecuteNonReader ( ) ; } }",Is TransactionScope implicitly applied until explicitly Completed ? "C_sharp : I am getting a list of objects separately ( and not from NHibernate ) and setting the parent objects IEnumerable equal to this returned object . Originally , we only needed to read the objects . Then we had the need to update only specific fields on the parent . Recently , we needed to update fields on the child . So far , all was well with SaveOrUpdate ( ) . Now , I need to update the children even if the collection of children was attached to a detached parent object ( not using NHibernate ) . The following code results in the parent being updated , but not the children . If I do all , then the children would be deleted if the parent does not have a collection . I do not want to do this because I am worried about legacy uses of this that does not account for this behavior . DESIRED BEHAVIOR : 1 . Cascade any changes to the collection ( whether in the parent was retrieved by NHibernate or not ) . 2 . Do not delete objects even if the parent does not have a collection of children.Is this possible ? This is our NHibernate save method : The DocumentFieldDTOMap looked like this : } If I change Cascade.SaveUpdate ( ) to Cascade.All ( ) the updates work , but will also delete . I want to eliminate the delete capability.UPDATE ( 1/27/2014 ) : I just verified that the deletes were cascading when the mapping was SaveUpdate ( ) , so this is n't as big an issue since I am not changing the existing functionality . I would still like to be able to update all cascading EXCEPT delete . An solution , if possible , would be great for future reference.UPDATE ( 2/10/2014 ) The following is the tests that verify that the children are deleted when cascade is `` SaveUpdate ( ) '' . The GetDocumentFieldDTOWithADO ( DocumentFieldID ) uses the same transaction as NHibernate and has 318 DocumentFieldOrgs on the first call ( before the save ) and 0 when called after the save . Maybe there is an issue with the test ? Does it delete the children because I call Merge ? UPDATED ( 2/11/2014 ) - Radim was correct in his answer below . NHibernate did not delete the children . It disassociated them from the parent . [ Transaction ] public int ? Save ( DocumentFieldDTO entity , bool autoFlush ) { var persisted = CurrentSession.Merge ( entity ) ; entity.DocumentFieldID = persisted.DocumentFieldID ; if ( autoFlush ) { CurrentSession.Flush ( ) ; } return entity.DocumentFieldID ; } public class DocumentFieldDTOMap : EntityMapBase { public DocumentFieldDTOMap ( ) { Table ( `` DocumentField '' ) ; Id ( m = & gt ; m.DocumentFieldID ) .GeneratedBy.Increment ( ) .UnsavedValue ( null ) ; Map ( x = & gt ; x.Name ) ; Map ( x = & gt ; x.DocumentSectionID ) .Not.Update ( ) ; // ... . Lots of other fields ... .// HasMany ( x = & gt ; x.DocumentFieldOrgs ) .Cascade.SaveUpdate ( ) .LazyLoad ( ) .KeyColumn ( `` DocumentFieldID '' ) ; } } [ Test ] public void Save_ShouldDeleteDocumentFieldOrgs_WhenSavingDocumentFieldWithoutDocFieldOrgsList ( ) { //arrange var expectedDocField = GetDocumentFieldDTOWithADO ( DocumentFieldID ) ; expectedDocField.DocumentFieldOrgs = null ; //act Repository.Save ( expectedDocField , false ) ; SessionFactory.GetCurrentSession ( ) .FlushAndEvict ( expectedDocField ) ; //assert var actualDocField = GetDocumentFieldDTOWithADO ( DocumentFieldID ) ; actualDocField.DocumentFieldOrgs.Should ( ) .BeEmpty ( `` DocumentFieldOrgs should be deleted if the parent does not have a child collection '' ) ; }",Is it possible to Cascade.All ( ) EXCEPT Delete ? "C_sharp : I found a problem on a task cancellation pattern , and I would like to understand why should work in this way.Consider this small program , where a secondary thread perform an async `` long '' task . In the mean time , the primary thread notifies for the cancellation.The program is a very simplified version of a bigger one , which could have many concurrent threads doing a `` long task '' . When the user ask to cancel , all the running task should be cancelled , hence the CancellationTokenSource collection.Despite locking the collection access , the thread accessing it is the same as the one requesting the cancellation . This is , the collection is modified during an iteration , and an exception is raised.For better clarity , you can comment out the whole `` foreach '' and uncomment the very last instruction , as follows : Doing so , there 's no exception , and the program terminates gracefully . However , it 's interesting to see the ID of the threads involved : Apparently , the `` finally '' body is run on the caller thread , but once off the `` Invoker '' , the thread is the secondary.Why the `` finally '' block is not executed in the secondary thread instead ? class Program { static MyClass c = new MyClass ( ) ; static void Main ( string [ ] args ) { Console.WriteLine ( `` program= '' + Thread.CurrentThread.ManagedThreadId ) ; var t = new Thread ( Worker ) ; t.Start ( ) ; Thread.Sleep ( 500 ) ; c.Abort ( ) ; Console.WriteLine ( `` Press any key ... '' ) ; Console.ReadKey ( ) ; } static void Worker ( ) { Console.WriteLine ( `` begin worker= '' + Thread.CurrentThread.ManagedThreadId ) ; try { bool result = c.Invoker ( ) .Result ; Console.WriteLine ( `` end worker= '' + result ) ; } catch ( AggregateException ) { Console.WriteLine ( `` canceled= '' + Thread.CurrentThread.ManagedThreadId ) ; } } class MyClass { private List < CancellationTokenSource > collection = new List < CancellationTokenSource > ( ) ; public async Task < bool > Invoker ( ) { Console.WriteLine ( `` begin invoker= '' + Thread.CurrentThread.ManagedThreadId ) ; var cts = new CancellationTokenSource ( ) ; c.collection.Add ( cts ) ; try { bool result = await c.MyTask ( cts.Token ) ; return result ; } finally { lock ( c.collection ) { Console.WriteLine ( `` removing= '' + Thread.CurrentThread.ManagedThreadId ) ; c.collection.RemoveAt ( 0 ) ; } Console.WriteLine ( `` end invoker '' ) ; } } private async Task < bool > MyTask ( CancellationToken token ) { Console.WriteLine ( `` begin task= '' + Thread.CurrentThread.ManagedThreadId ) ; await Task.Delay ( 2000 , token ) ; Console.WriteLine ( `` end task '' ) ; return true ; } public void Abort ( ) { lock ( this.collection ) { Console.WriteLine ( `` canceling= '' + Thread.CurrentThread.ManagedThreadId ) ; foreach ( var cts in collection ) //exception here ! { cts.Cancel ( ) ; } //collection [ 0 ] .Cancel ( ) ; } ; } } } public void Abort ( ) { lock ( this.collection ) { Console.WriteLine ( `` canceling= '' + Thread.CurrentThread.ManagedThreadId ) ; //foreach ( var cts in collection ) //exception here ! // { // cts.Cancel ( ) ; // } collection [ 0 ] .Cancel ( ) ; } ; } program=10begin worker=11begin invoker=11begin task=11canceling=10removing=10end invokerPress any key ... canceled=11",Why the task cancellation happens on the caller thread ? "C_sharp : This is my first Q # program and i 'm following this getting started link.https : //docs.microsoft.com/en-us/quantum/quantum-writeaquantumprogram ? view=qsharp-previewError is The name 'BellTest ' does not exist in the current context but its defined in the Bell.csI followed the steps and when building its having errors . I 'm not sure how to import the operations from .qs file to driver c # file as this error looks like it ca n't find that operation.Any help is really appreciated Here is the codeDriver.csBell.qs using Microsoft.Quantum.Simulation.Core ; using Microsoft.Quantum.Simulation.Simulators ; namespace Quantum.Bell { class Driver { static void Main ( string [ ] args ) { using ( var sim = new QuantumSimulator ( ) ) { // Try initial values Result [ ] initials = new Result [ ] { Result.Zero , Result.One } ; foreach ( Result initial in initials ) { var res = BellTest.Run ( sim , 1000 , initial ) .Result ; var ( numZeros , numOnes ) = res ; System.Console.WriteLine ( $ '' Init : { initial , -4 } 0s= { numZeros , -4 } 1s= { numOnes , -4 } '' ) ; } } System.Console.WriteLine ( `` Press any key to continue ... '' ) ; System.Console.ReadKey ( ) ; } } } namespace Quantum.Bell { open Microsoft.Quantum.Primitive ; open Microsoft.Quantum.Canon ; operation Set ( desired : Result , q1 : Qubit ) : ( ) { body { let current = M ( q1 ) ; if ( desired ! = current ) { X ( q1 ) ; } } } operation BellTest ( count : Int , initial : Result ) : ( Int , Int ) { body { mutable numOnes = 0 ; using ( qubits = Qubit [ 1 ] ) { for ( test in 1..count ) { Set ( initial , qubits [ 0 ] ) ; let res = M ( qubits [ 0 ] ) ; // Count the number of ones we saw : if ( res == One ) { set numOnes = numOnes + 1 ; } } Set ( Zero , qubits [ 0 ] ) ; } // Return number of times we saw a |0 > and number of times we saw a |1 > return ( count-numOnes , numOnes ) ; } } }",Quantum Program The name 'BellTest ' does not exist in the current context "C_sharp : I 'm working on an application that 's embedding Mono , and I 'd like to raise an event from the C++ layer into the C # layer . Here 's what I have : However , raiseMethod always comes back as NULL . Looking at the structure of the MonoEvent , it looks like the add and remove methods were populated , but not the raise ? Is there something special I have to do to get this to work ? EDIT : If it matters , here 's the ( basic ) form of the delegate , class , and events I 'm using in the C # layer . void* itr ( NULL ) ; MonoEvent* monoEvent ; while ( monoEvent= mono_class_get_events ( klass , & itr ) ) { if ( 0 == strcmp ( eventName , mono_event_get_name ( monoEvent ) ) ) raiseMethod = mono_event_get_raise_method ( monoEvent ) ; } public delegate void MyHandler ( uint id ) ; public class SimpleComponent : NativeComponent { public event MyHandler OnEnter ; public event MyHandler OnExit ; }",Embedded Mono : How do you raise an event in C++ ? "C_sharp : I want to sort an array that can contain different numeric types ( double , float , etc . ) .This code raises a System.ArgumentException ( `` Value is not a System.Single '' ) error : I know I can use LINQ to do this : But is there a faster way that does n't involve going through any having to cast each element ? Addendum : I would also like to be able to handle nulls in the list , so even the LINQ query 's cast wo n't help . new dynamic [ ] { 5L , 4D , 3F , 2U , 1M , 0UL } .ToList ( ) .Sort ( ) ; new dynamic [ ] { 5L , 4D , 3F , 2U , 1M , 0UL } .ToList ( ) .OrderBy ( x = > ( decimal ) x ) .ToArray ( ) ;",How to sort a dynamic array of heterogeneous numbers ? "C_sharp : The perfmon counter is using different NIC names compare to ipconfig/all and c # system call as you can see below ( this is from ipconfig/all ) I get HP NC364T PCIe Quad Port Gigabit Server Adapter # 3 . Exactly the same as ipconfig.BUT the perfmon is using HP NC364T PCIe Quad Port Gigabit Server Adapter _3 ( underscore instead of hash ) . Do I have to use a different call to get the same exact counter name as what the perfmon has ? If so , what is it ? Ethernet adapter HHHH : Connection-specific DNS Suffix . : Description . . . . . . . . . . . : HP NC364T PCIe Quad Port Gigabit Server Adapter # 3 Physical Address . . . . . . . . . : 00-1F-29-0D-26-59 DHCP Enabled . . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes IPv4 Address . . . . . . . . . . . : 166.49.47.10 ( Preferred ) Subnet Mask . . . . . . . . . . . : 255.255.255.240 Default Gateway . . . . . . . . . : NetBIOS over Tcpip . . . . . . . . : Disabled using System.Net.NetworkInformation ; NetworkInterface [ ] interfaces = NetworkInterface.GetAllNetworkInterfaces ( ) ;",C # performance counter and nic name "C_sharp : I have 2 classes , one derived from the other : How can I change my declaration ( s ) to be able to call the methods in the order `` 2 '' above in order to achieve a more fluent api ? class Animal { public Animal AnimalMethod ( ) { // do something return this ; } } class Dog : Animal { public Dog DogMethod ( ) { // do something return this ; } } var dog = new Dog ( ) ; dog.DogMethod ( ) .AnimalMethod ( ) ; // 1 - this works dog.AnimalMethod ( ) .DogMethod ( ) ; // 2 - this does n't",chaining methods in base and derived class "C_sharp : Ok this is more of an annoyance than a problem . There is no errorPageSubViewWhen Binding to BindingContext from the Source Reference of This , i get a XAML `` warning '' Can not resolve property 'IsVacate ' in data context of type 'object'Obviously the BindingContext is an object and untyped . However the above code compiles and worksWhat i want to do is cast it , firstly because i have OCD , however mainly because its easy to spot real problems on the IDE page channel barThe following seems logical but does n't work In the output i get [ 0 : ] Binding : ' ( viewModels : ChooseTargetLocationVm ' property not found on 'Inhouse.Mobile.Standard.ViewModels.ChooseTargetLocationVm ' , target property : 'Inhouse.Mobile.Standard.Views.ProductStandardView.Bound ' I understand the error , yet how else would i cast ? And just for stupidity , obviously the following wont compileSo is there a way to cast a BindingContext to a ViewModel so any SubProperty references are typed at design time ? UpdateThis is relevant for inside a DataTemplate or in this case when the control has its own BindingContext which is why i need to use the Source= { x : Reference This } to target the page.Note : < ContentPage.BindingContext > does n't work for me as i 'm using prism and unity and it does n't seem to play with well a default constructor on initial tests , though i might play around with this some more < ContentPage ... x : Name= '' This '' //hack to have typed xaml at design-time BindingContext= '' { Binding Source= { x : Static viewModels : ViewModelLocator.ChooseTargetLocationVm } } '' < views : ProductStandardView ... BindingContext= '' { Binding Product } '' > < Grid.Triggers > < DataTrigger Binding= '' { Binding Path=BindingContext.IsVacate , Source= { x : Reference This } } '' TargetType= '' Grid '' Value= '' true '' > < Setter Property= '' BackgroundColor '' Value= '' { StaticResource WarningColor } '' / > < /DataTrigger > < /Grid.Triggers > Binding= '' { Binding Path=BindingContext.IsVacate , Source= { x : Reference This } } '' Binding= '' { Binding Path=BindingContext . ( viewModels : ChooseTargetLocationVm.IsVacate ) , Source= { x : Reference This } } '' Binding= '' { Binding Path= ( ( viewModels : ChooseTargetLocationVm ) BindingContext ) .IsVacate , Source= { x : Reference This } } ''",Cast Binding Path so it recognises ViewModel property at Design-Time "C_sharp : There is a class with one property : Now I create a derived type with some method overrides : The generated type does n't contain the property anymore . Curiously the property appears again if you change the methodAttributes to MethodAttributes.Public for at least one method definition.Seems like a bug ? Edit : peverify does n't give an error.Edit : ( important comment of Fabian Schmied ) ECMA-335 Partition II , 10.3.3 : `` If a type overrides an inherited method via a MethodImpl , it can widen or narrow the accessibility of that method . '' public class BaseClass { public virtual string Property1 { get ; set ; } } [ Test ] public void name ( ) { var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly ( new AssemblyName ( `` Test '' ) , AssemblyBuilderAccess.RunAndSave ) ; var moduleBuilder = assemblyBuilder.DefineDynamicModule ( `` Test.dll '' ) ; var derivedBuilder = moduleBuilder.DefineType ( `` DerivedClass '' , TypeAttributes.Public , typeof ( BaseClass ) ) ; const MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.SpecialName | MethodAttributes.NewSlot ; var getterOverride = derivedBuilder.DefineMethod ( `` get_Property1 '' , methodAttributes , typeof ( string ) , Type.EmptyTypes ) ; var getterILGenerator = getterOverride.GetILGenerator ( ) ; getterILGenerator.Emit ( OpCodes.Ldnull ) ; getterILGenerator.Emit ( OpCodes.Ret ) ; derivedBuilder.DefineMethodOverride ( getterOverride , typeof ( BaseClass ) .GetMethod ( `` get_Property1 '' ) ) ; var setterOverride = derivedBuilder.DefineMethod ( `` set_Property1 '' , methodAttributes , typeof ( void ) , new [ ] { typeof ( string ) } ) ; var setterILGenerator = setterOverride.GetILGenerator ( ) ; setterILGenerator.Emit ( OpCodes.Ret ) ; derivedBuilder.DefineMethodOverride ( setterOverride , typeof ( BaseClass ) .GetMethod ( `` set_Property1 '' ) ) ; var derivedType = derivedBuilder.CreateType ( ) ; var props = derivedType.GetProperties ( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ) ; assemblyBuilder.Save ( `` Test.dll '' ) ; Assert.That ( props , Has.Length.EqualTo ( 1 ) ) ; }",Emit of explicit method override hides property "C_sharp : I have a function that is to be called if a list has changed since it was last called , what would be the best way of implementing this ? ex : I would have assumed make a variable to store the old list and compare , but how would I update the old list to the new list without copying it all out ? ( If I do an assign , it will update the `` old list '' too ) List < A > OurList = new List < A > ( ) ; private void Update ( ) { Boolean Changed = // ? if ( Changed ) CheckList ( OurList ) ; }",Least cpu intensive method of checking if a list has changed in c # "C_sharp : When a user comes to my site , there may be a template=foo passed in the query string . This value is being verified and stored in the Session . My file layout looks like this : Basically , if a user requests Index with template=test1 , I want to use Views/Templates/test1/Index.cshtml . If they have template=test2 , I want to use Views/Home/Index.cshtml ( because /Views/Templates/test2/Home/Index.cshtml does n't exist ) . And if they do not pass a template , then it should go directly to Views/Home . I 'm new to MVC and .NET in general , so I 'm not sure where to start looking . I 'm using MVC3 and Razor for the view engine . - Views/ - Templates/ - test1/ - Home - Index.cshtml - test2/ - Home - List.cshtml - Home/ - Index.cshtml",Search for .cshtml in multiple locations in MVC 3 ? "C_sharp : Is it possible to use yield inline at the ForEach method ? if not , is there a reason why it does n't work ? private static IEnumerable < string > DoStuff ( string Input ) { List < string > sResult = GetData ( Input ) ; sResult.ForEach ( x = > DoStuff ( x ) ) ; //does not work sResult.ForEach ( item = > yield return item ; ) ; //does work foreach ( string item in sResult ) yield return item ; }",foreach vs ForEach using yield "C_sharp : I have singleton object 'Service ' and two methods to initialize and release it : For the line with comment resharper ( I use version 5.1 ) displays a mentioned warning ... Question 1 : Why ? Question 2 : Why it does n't display `` similar '' message in 'EnsureServiceIsOpened ' method ? Thanks . public class BaseService { protected static readonly object StaticLockObject = new object ( ) ; } public abstract class WebServiceBase < TService > : BaseService where TService : System.Web.Services.Protocols.SoapHttpClientProtocol , new ( ) { protected static void EnsureServiceIsOpened ( ) { if ( Service == null ) { lock ( StaticLockObject ) { if ( Service == null ) { Service = new TService ( ) ; } } } } protected static void EnsureServiceIsClosed ( ) { if ( Service ! = null ) { lock ( StaticLockObject ) { if ( Service ! = null ) // Why expression is always true { Service.Dispose ( ) ; Service = null ; } } } }",Why expression is always true for 'double-checked-locking ' ? "C_sharp : A followup to Does .NET JIT optimize empty loops away ? : The following program just runs an empty loop a billion times and prints out the time to run . It takes 700 ms on my machine , and I 'm curious if there 's a way to get the jitter to optimize away the empty loop.As far as I can tell the answer is no , but I do n't know if there are hidden compiler options I might not have tried . I have made sure to compile in release mode and run with no debugger attached , but still 700 ms is being taken to run this empty loop . I also tried NGEN with the same result ( though my understanding is that it should produce the same compiled code as the JIT anyway , right ? ) . However I 've never used NGEN before and may be using it wrong.It seems like this would be something easy for the JIT to find and optimize away , but knowing very little about how jitters work in general , I 'm curious if there 's a specific reason this optimization would have been left out . Also the VC++ compiler definitely does seem to make this optimization , so I wonder why the discrepancy . Any ideas ? using System ; namespace ConsoleApplication1 { class Program { static void Main ( ) { var start = DateTime.Now ; for ( var i = 0 ; i < 1000000000 ; i++ ) { } Console.WriteLine ( ( DateTime.Now - start ) .TotalMilliseconds ) ; } } }",Is there a way to get the .Net JIT or C # compiler to optimize away empty for-loops ? "C_sharp : I 'm displaying RTF document in RichTextBox ( `` upgraded '' to RichEdit50W ) . Keywords in the document are linked to a webpage using a syntax : I do not want to underline the keywords . Until Windows 10 version 1803 ( and in all previous versions of Windows , including XP , Vista , 8 ) , whenever a color was set on the anchor ( note the \cf1 ) , the anchor was not underlined.But this no longer works in Windows 10 version 1803 . I 'm going to report this to Microsoft . But I 'm not really sure , if I was not relying on an undocumented behavior . I can imagine that this change is actually not a bug , but rather a fix . So I wonder whether there is not a more correct way to prevent hyperlinks from being underlined.Sample code : ( unwanted ) result on Windows 10 version 1803 : ( desired ) result on Windows 10 version 1706 : and the same result on Windows 7 : { \field { \*\fldinst { HYPERLINK `` '' https : //www.example.com/ '' '' } } { \fldrslt { \cf1 keyword\cf0 } } } public class ExRichText : RichTextBox { [ DllImport ( `` kernel32.dll '' , EntryPoint = `` LoadLibraryW '' , CharSet = CharSet.Unicode , SetLastError = true ) ] private static extern IntPtr LoadLibraryW ( string path ) ; protected override CreateParams CreateParams { get { var cp = base.CreateParams ; LoadLibraryW ( `` MsftEdit.dll '' ) ; cp.ClassName = `` RichEdit50W '' ; return cp ; } } } public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; ExRichText rtb = new ExRichText ( ) ; rtb.Parent = this ; rtb.SetBounds ( 10 , 10 , 200 , 100 ) ; rtb.Rtf = @ '' { \rtf1 { \colortbl ; \red255\green0\blue0 ; } bar { \field { \*\fldinst { HYPERLINK `` '' https : //www.example.com/ '' '' } } { \fldrslt { \cf1 link\cf0 } } } bar } '' ; } }",Hyperlinks without underline in RichTextBox on Windows 10 1803 "C_sharp : Recently , I 've come across C # examples that use a syntax that looks like the following : I really like it . It looks like JSON a bit . However , I do n't know what this syntax is called . For that reason , I 'm not sure how to learn more about it . I 'm really interested in trying to figure out how to define arrays of objects within a result . For instance , what if I wanted to return an array of items for prop3 ? What would that look like ? What is this syntax called ? var result = new { prop1 = `` hello '' , prop2 = `` world '' , prop3 = `` . '' } ;",Dynamic syntax in C # "C_sharp : Good morning ! I 'm writing a class for drawing histograms and , for user 's convenience , I 've decided to add a few convenience constructors.However , as soon as I recently switched to .NET code contracts from DevLabs , I want to make full use of preconditions for protection against my own ( or someone 's ) stupidity.There is a thing that confuses me . I do n't want the first constructor to ever call the second one if the contract is broken ; however , it is supposed that a call to this ( ... ) will be performed before executing the body of the first constructor.Will this code work as I want ? I have n't tried yet.And if not , is there a capability of solving such an issue ? public HistoGrapher ( IList < string > points , IList < T > values ) : this ( points.Select ( ( point , pointIndex ) = > new KeyValuePair < string , T > ( point , values [ pointIndex ] ) ) ) { Contract.Requires < ArgumentNullException > ( points ! = null , `` points '' ) ; Contract.Requires < ArgumentNullException > ( values ! = null , `` values '' ) ; Contract.Requires < ArgumentException > ( points.Count == values.Count , `` The lengths of the lists should be equal . `` ) ; } public HistoGrapher ( IEnumerable < KeyValuePair < string , T > > pointValuePairs ) { // useful code goes here }",Contract preconditions in an empty-body constructor "C_sharp : I got a MarshalByRefObject named `` DefaultMeasurement '' , which contains a List of IPoint-objects.When first retrieving the DefaultMeasurement object from the server all the points get serialized and during all subsequent calls to DefaultMeasurement.Points I get the list that was correct upon startup of my client . But in the meantime the state of at least one object in that list might have changed and I do n't get that current state , although in the server that state gets updated . How do I force an update of that list ? further clarification : - it will work once I do DefaultPoint : MarshalByRefObject , but that is not an option as it negatively affects performance- by 'update ' I mean changes to existing objects on the server , no adding / removing on the list itself- I might have up to 80k DefaultPoint objects public class DefaultMeasurement : MarshalByRefObject , IMeasurement { private List < IPoint > iPoints ; public this [ int aIndex ] { get { return iPoints [ aIndex ] ; } } } [ Serializable ] public class DefaultPoint : IPoint , ISerializable { public int Value { get ; set ; } }",.net remoting : Update already serialized objects "C_sharp : I have following code that 's capable of mapping Reader to simple objects . The trouble is in case the object is composite it fails to map . I am not able to perform recursion by checking the property if it is a class itselfprop.PropertyType.IsClass as Type is required to call DataReaderMapper ( ) . Any idea on how this may be achieved or some other approach ? Also , currently I am not wishing to use any ORM . public static class MapperHelper { /// < summary > /// extension Method for Reader : Maps reader to type defined /// < /summary > /// < typeparam name= '' T '' > Generic type : Model Class Type < /typeparam > /// < param name= '' dataReader '' > this : current Reader < /param > /// < returns > List of Objects < /returns > public static IEnumerable < T > DataReaderMapper < T > ( this IDataReader dataReader ) where T : class , new ( ) { T obj = default ( T ) ; //optimized taken out of both foreach and while loop PropertyInfo [ ] PropertyInfo ; var temp = typeof ( T ) ; PropertyInfo = temp.GetProperties ( ) ; while ( dataReader.Read ( ) ) { obj = new T ( ) ; foreach ( PropertyInfo prop in PropertyInfo ) { if ( DataConverterHelper.ColumnExists ( dataReader , prop.Name ) & & ! dataReader.IsDBNull ( prop.Name ) ) { prop.SetValue ( obj , dataReader [ prop.Name ] , null ) ; } } yield return obj ; } } }",Generic Relational to Composite C # Object Mapper "C_sharp : I swear this does n't make sense.Given I have this HttpRouteCollection from Web API , I am filtering based on some custom route types , specifically IAttributeRoute . I use httpRoutes.OfType < IAttributeRoute > ( ) but the loop is acting like there 's no elements.To be clear , when this loop gets hit , the entire collection are of type HttpAttributeRoute which directly implement IAttributeRoute . Furthermore , I have the same loop operating on the regular RouteCollection.This does n't work : Yet , this works fine : I swear I am not lying , it only works in the latter code . Like I said , doing this on a normal route collection is fine . The normal route collection has other types , not just IAttributeRoute , but the HttpRouteCollection only has IAttributeRoute , in its current state ( in the future it could have different type routes ) . Could that be a factor ? Am I missing something or is n't OfType doing what I 'm doing internally ? foreach ( IAttributeRoute route in GlobalConfiguration.Configuration.Routes.OfType < IAttributeRoute > ( ) ) { if ( ! string.IsNullOrWhiteSpace ( route.RouteName ) & & ! json.ContainsKey ( route.RouteName ) ) { json.Add ( route.RouteName , `` / '' + route.Url ) ; } } foreach ( var route in GlobalConfiguration.Configuration.Routes ) { if ( route is IAttributeRoute ) // uhhhh ? { var r = route as IAttributeRoute ; if ( ! string.IsNullOrWhiteSpace ( r.RouteName ) & & ! json.ContainsKey ( r.RouteName ) ) { json.Add ( r.RouteName , `` / '' + r.Url ) ; } } }",Enumerable.OfType < > ( ) not working as expected with route collection "C_sharp : I have a plug-in vector established using System.AddIn that accepts the body of a pre-defined method , munges the method body into boilerplate code , generates the assembly and executes the method.The assembly references System and System.Core and is sandboxed withThe only exception I can find reference to that could possible bring down the host is a stack overflow , which could be invoked any number of creative means , e.g . closing the body and declaring a recursive method etc ... And then there are the possible attack vectors exposed by the referenced assemblies , System and System.Core.My question is : How safe is this and what are some examples of malicious code that could potentially bring down the host and possible ways to prevent such attacks ? UPDATE : also for those familiar with the Managed AddIn Framework , apply the same question to AddInSecurityLevel.Internet . var pset = new PermissionSet ( PermissionState.None ) ; pset.AddPermission ( new SecurityPermission ( SecurityPermissionFlag.Execution ) ) ;",How safe is an AppDomain sandboxed with SecurityPermissionFlag.Execution ? "C_sharp : As we all know strings are implicitly instantiated , meaning that we do n't have to use new in order to get a reference to an object of one.Because of this it was always my belief that the framework is taking care of this , and hence I would get identical IL if I did something like this : However it appears that the first line is done using newobj instance void [ mscorlib ] System.String : :.ctor ( char [ ] ) and the second ldstr `` a '' .So in order to obtain a string reference , does ldstr internally call newobj and where can I see the specification / details to back this up ? String first = new String ( new char [ ] { ' a ' } ) ; string second = `` a '' ;",Does ldstr internally implement newobj ? "C_sharp : Code : My guess is : but , I 'm not sure . The ECMA guide did n't help distinguish , so I guess I 'm looking for assurance that my guess is correct . public interface IFoo { void Bar ( ) ; } public class FooClass : IFoo { /// < summary > ... < /summary > /// < seealso cref= '' ? `` / > //How do you reference the IFoo.Bar ( ) method public void Bar ( ) { } /// < summary > ... < /summary > /// < seealso cref= '' ? `` / > //How do you reference the standard Bar ( ) method void IFoo.Bar ( ) { } } < seealso cref= '' IFoo.Bar ( ) '' / > //Explicitly implemented interface method < seealso cref= '' Bar ( ) '' / > //Standard method",XML Comments -- How do you comment explicitly implemented interfaces properly ? "C_sharp : I have in my code the concept of command : And some concrete implementation like this one : Now I want to add some validation . The first thing I can do is add a if/throw check : Now , I 'm trying to use Code Contracts , because I 'm quite convinced of its usefulness to reduce bug risk . If I rewrote the method like this : The method compiles , the check is done at run-time . However , I got warning : warning CC1032 : CodeContracts : Method 'MyProject.DeleteItemCommand.Execute ' overrides 'MyProject.BaseCommand.Execute ' , thus can not add Requires.I understand this warning is issued because I 'm breaking the Liskov Principle.However , in my case , conditions are different from one concrete class to another . My BaseCommand class is actually defining some common attributes like CommandIdentifier , state , and other ultimate features I removed here to keep the question simple.While I understand the concepts of this principle , I do n't know what are the step I have to do to remove the warning properly ( do n't tell me about the # pragma warning remove ) .Should I stop using code contracts in this case , where concrete implementations have specific requirements ? Should I rewrite my commanding mechanism to have , for example , separation between the Command `` arguments '' and the Command `` execution '' ? ( having one CommandeExecutor < TCommand > per concrete class ) . This would result in a lot more classes in my project.Any other suggestion ? [ Edit ] As suggested by adrianm , convert properties to readonly , add constructor parameters to populate the properties and check properties in the contructor public abstract class BaseCommand { public BaseCommand ( ) { this.CommandId = Guid.NewGuid ( ) ; this.State = CommandState.Ready ; } public Guid CommandId { get ; private set ; } public CommandState State { get ; private set ; } protected abstract void OnExecute ( ) ; public void Execute ( ) { OnExecute ( ) ; State = CommandState.Executed ; } } public class DeleteItemCommand { public int ItemId { get ; set ; } protected override void OnExecute ( ) { var if = AnyKindOfFactory.GetItemRepository ( ) ; if.DeleteItem ( ItemId ) ; } } public class DeleteItemCommand { public int ItemId { get ; set ; } protected override void Execute ( ) { if ( ItemId == default ( int ) ) throw new VeryBadThingHappendException ( `` ItemId is not set , can not delete the void '' ) ; var if = AnyKindOfFactory.GetItemRepository ( ) ; if.DeleteItem ( ItemId ) ; } } public class DeleteItemCommand { public int ItemId { get ; set ; } public void Execute ( ) { Contract.Requires < VeryBadThingHappendException > ( ItemId ! = default ( int ) ) ; var if = AnyKindOfFactory.GetItemRepository ( ) ; if.DeleteItem ( ItemId ) ; } }","Code Contract , inheritance and Liskov Principle" "C_sharp : I have a collection of strings which I need to perform two operations on.The first of these can safely be processed independently in any order ( yay ) , but then the output must be processed sequentially ( boo ) in the original order.The following Plinq gets me most of the way there : This gets me most of the way there , but the problem is that because of the AsOrdered ( ) , Operation1 gets executed on every string first , then the result elements are sorted back to their original order , then finally Operation2 starts executing.Ideally , as soon as the first string ( ie myStrings [ 0 ] , not the first one returned ) is returned by an Operation1 call , I 'd like Operation2 to begin it 's work.So this is my attempt to solve the problem generically : Then I can re-write my original code block as : and Operation2 kicks off as soon as myStrings [ 0 ] comes out from Operation1.What I 'd like to know is : This is a fairly common problem/pattern within parallelisation , have I missed something out of the box that does this in the .Net framework ? Or is there a simpler way ? While the above extension method seems to do the job , how could it be improved ? Does anything in the code look like it 's a bad idea ? Thanks ! AndyJust in case you 're interested : Without the call to .WithMergeOptions ( ParallelMergeOptions.NotBuffered ) Operation2 does n't begin its work until all Operation1 calls have been started ( which is better than the original code which waited until they were all completed ) .The real life problem : Operation1 is searching for legal citations and references within large bodies of text ( eg : `` children act 1989 '' ) .These references are usually independent , but occasionally a transcript will contain something like `` section 6 of the previously mentioned act '' .Operation2 relies on captures from Operation1 to pick up these partial references . myStrings.AsParallel ( ) .AsOrdered ( ) .Select ( str = > Operation1 ( str ) ) .AsSequential ( ) .Select ( str = > Operation2 ( str ) ) ; //immagine Operation2 ( ) maintains some sort of state and must take the outputs from Operation1 in the original order public static class ParallelHelper { public static IEnumerable < U > SelectAsOrdered < T , U > ( this ParallelQuery < T > query , Func < T , U > func ) { var completedTasks = new Dictionary < int , U > ( ) ; var queryWithIndexes = query.Select ( ( x , y ) = > new { Input = x , Index = y } ) .AsParallel ( ) .Select ( t = > new { Value = func ( t.Input ) , Index = t.Index } ) .WithMergeOptions ( ParallelMergeOptions.NotBuffered ) ; int i = 0 ; foreach ( var task in queryWithIndexes ) { if ( i==task.Index ) { Console.WriteLine ( `` immediately yielding task : { 0 } '' , i ) ; i++ ; yield return task.Value ; U previouslyCompletedTask ; while ( completedTasks.TryGetValue ( i , out previouslyCompletedTask ) ) { completedTasks.Remove ( i ) ; Console.WriteLine ( `` delayed yielding task : { 0 } '' , i ) ; yield return previouslyCompletedTask ; i++ ; } } else { completedTasks.Add ( task.Index , task.Value ) ; } } yield break ; } } myStrings.AsParallel ( ) .SelectAsOrdered ( str = > Operation1 ( str ) ) .Select ( str = > Operation2 ( str ) ) ;","How to start processing the results of a Parallel query , in order , before the query has finished ?" "C_sharp : Using git show , I can fetch the contents of a particular file from a particular commit , without changing the state of my local clone : How can I achieve this programatically using libgit2sharp ? $ git show < file > $ git show < commit > : < file >",Download one file from remote ( git show ) using libgit2sharp "C_sharp : So I 'm trying to use the haversine formula in Unity to get the distance between two different points ( latitude and longitud given ) . The code is working ( no errors ) but I keep gettting a wrong result . I followed the entire formula so I do n't really know where the math/code problem is . Any idea ? Here 's the code : public float lat1 = 42.239616f ; public float lat2 = -8.72304f ; public float lon1 = 42.239659f ; public float lon2 = -8.722305f ; void operacion ( ) { float R = 6371000 ; // metres float omega1 = ( ( lat1/180 ) *Mathf.PI ) ; float omega2 = ( ( lat2/180 ) *Mathf.PI ) ; float variacionomega1 = ( ( ( lat2 - lat1 ) /180 ) *Mathf.PI ) ; float variacionomega2 = ( ( ( lon2 - lon1 ) / 180 ) * Mathf.PI ) ; float a = Mathf.Sin ( variacionomega1/2 ) * Mathf.Sin ( variacionomega1/2 ) + Mathf.Cos ( omega1 ) * Mathf.Cos ( omega2 ) * Mathf.Sin ( variacionomega2/2 ) * Mathf.Sin ( variacionomega2/2 ) ; float c = 2 * Mathf.Atan2 ( Mathf.Sqrt ( a ) , Mathf.Sqrt ( 1-a ) ) ; float d = R * c ; }",Haversine formula Unity "C_sharp : In MVC , sometimes I 'm setting specific property of ViewBag according to some condition.For example : In my View I 'm checking whether the property is null like this : Until now I was thinking that should throw an exception because if my condition is not satisfied then SomeProperty is never get set.And that 's why I was always using an else statement to set that property to null.But I just noticed , it does n't throw an exception even if the property does n't exists.For example in a Console Application if I do the following , I 'm getting a RuntimeBinderException : But it does n't happen when it comes to ViewBag.What 's the difference ? if ( someCondition ) { // do some work ViewBag.SomeProperty = values ; } return View ( ) ; @ if ( ViewBag.SomeProperty ! = null ) { ... } dynamic dynamicVariable = new { Name = `` Foo '' } ; if ( dynamicVariable.Surname ! = null ) Console.WriteLine ( dynamicVariable.Surname ) ;",Why ViewBag.SomeProperty does n't throw an exception when the property is not exists ? "C_sharp : I have a List < bool > and want to bitwise XOR the list ( to create check bits ) here is what I have currentlyQ : Is there a Linq one-liner to solve this more elegant ? List < bool > bList = new List < bool > ( ) { true , false , true , true , true , false , false } ; bool bResult = bList [ 0 ] ; for ( int i = 1 ; i < bList.Count ; i++ ) { bResult ^= bList [ i ] ; }",Bitwise operation to a List < bool > C_sharp : I 'm having an interface IJob from which all Job classes inherits and I have generic repo class which will process all kind of IJob's.The problem im facing is im not able to able convert Repository < Job1 > to Repository < IJob > even though Job1 is a type of IJob.CodeCan someone let me know why this wont be possible in C # and are there any other rules type conversion in C # generics ? internal class Program { public interface IJob { } public class Job1 : IJob { } public class Job2 : IJob { } public class Repository < TJob > where TJob : IJob { public List < TJob > GetJobs ( ) { return new List < TJob > ( ) ; } } private static void Main ( string [ ] args ) { IJob iJob = new Job1 ( ) ; // Valid Repository < IJob > repo = new Repository < Job1 > ( ) ; // Not Valid } },Are there any rules for type conversion between C # generics ? "C_sharp : In EF 6 I can do something like this : since EF7 ModelBuilder does n't have the Properties ( ) function , how do I do same thing in EF7 ? modelBuilder .Properties ( ) .Where ( p = > p.PropertyType == typeof ( string ) & & p.GetCustomAttributes ( typeof ( MaxLengthAttribute ) , false ) .Length == 0 ) .Configure ( p = > p.HasMaxLength ( 2000 ) ) ;",change all string property max length "C_sharp : I am building an MVC application . It behaves so weird . If I run it on my development server ( visual studio debugging ) it runs fine even when I restart my application several times by changing the web.config , but when I hosted it , it behaves so weird.For the first load , everything is normal . I can load all pages , post via ajax , etc just normal , but after I restart the server using HttpRuntime.UnloadAppDomain ( ) ; then everytime I post via ajax , I always get internal server error 500I do not know what is happening with the application , but I have suspicion that something is going wrong with the client ( user ) cache / cookies.I use [ ValidateJsonAntiForgeryToken ] attribute to the controller functions that receive the post.And this is the code that handles the json validation tokenThis is the example how I post it : I have @ Html.AntiForgeryToken ( ) in my view . Actually what is wrong with my application ? If the problem is that the user cookie is still being accepted by the system but it is not valid , then how to make the user cookie reset after the application being restarted ? -- -- -- -- -- -- -- -- -- -- -- -- -- -UpdateIt seems that the code is actually able to pass through the controller action , so there is no problem with the validation token , but when the code reached the line that tried to retrieve data from database , this happens Message : A network-related or instance-specific error occurred while establishing a connection to SQL Server . The server was not found or was not accessible . Verify that the instance name is correct and that SQL Server is configured to allow remote connections . ( provider : SQL Network Interfaces , error : 26 - Error Locating Server/Instance Specified ) This is my connection string : Conn string : Data Source=ip address ; Initial Catalog=the database name ; Integrated Security=False ; User ID=user ; Password=the password ; MultipleActiveResultSets=TrueThis is the code that produces error : If I run it using Incognito mode , it runs fine . So what is exactly going on with my application ? -- -- -- -- -- -- -- -- -- -Update 2After a further debugging , I am sure now that the problem lies in the cookies . These are the cookies : .ASPXAUTHASP.NET_SessionIdI use `` InProc '' as my session state , which should be reset after application recycle / restart , which is my aim , but I do not know why after application restart , the cookies are still there.So what I want is to invalidate the session for all user if the server is restarted.The solution are either : Get all the sessions from all users and invalidate itLogout all logon users at Application_End ( ) Both solutions are impossible from my research . Please help [ HttpPost ] [ ValidateJsonAntiForgeryToken ] public JsonResult LoadPage ( int id , string returnUrl , PageFormViewModel pageForm , string jsonFormModel ) [ AttributeUsage ( AttributeTargets.Method | AttributeTargets.Class , AllowMultiple = false , Inherited = true ) ] public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute , IAuthorizationFilter { public void OnAuthorization ( AuthorizationContext filterContext ) { if ( filterContext == null ) { throw new ArgumentNullException ( `` filterContext '' ) ; } var httpContext = filterContext.HttpContext ; var cookie = httpContext.Request.Cookies [ AntiForgeryConfig.CookieName ] ; AntiForgery.Validate ( cookie ! = null ? cookie.Value : null , httpContext.Request.Headers [ `` __RequestVerificationToken '' ] ) ; } } var getURL = $ ( ' # GetURL ' ) .val ( ) ; var returnUrl = $ ( ' # ReturnUrl ' ) .val ( ) ; var pageId = $ ( ' # PageId ' ) .val ( ) ; var token = $ ( 'input [ name= '' __RequestVerificationToken '' ] ' ) .val ( ) ; var headers = { } ; headers [ '__RequestVerificationToken ' ] = token ; var thePageForm = pageForm ; var theFormModel = formModel ; $ .ajax ( { type : 'POST ' , url : getURL , contentType : `` application/json ; charset=utf-8 '' , dataType : 'json ' , async : false , headers : headers , data : JSON.stringify ( { id : pageId , returnUrl : returnUrl , pageForm : thePageForm , jsonFormModel : theFormModel } ) , success : function ( model ) { //Load the page } error : function ( ) } ) ; PageViewModel model = new PageViewModel ( ) ; model.Page = dbPages.Pages.Where ( m = > m.Id == id ) .First ( ) ;","MVC4 : After server restart , can not post ajax internal server error 500" "C_sharp : I have tried to remove specific items from a listview using the RemoveAt ( ) method . But When I remove it the first time some items will stay . For example : see the image belowCode : private void button1_Click ( object sender , EventArgs e ) { for ( int i = 0 ; i < listView1.Items.Count ; i++ ) { if ( listView1.Items [ i ] .SubItems [ 0 ] .Text == `` A1 '' ) { listView1.Items.RemoveAt ( i ) ; } } } private void Form1_Load ( object sender , EventArgs e ) { for ( int i = 0 ; i < 3 ; i++ ) { ListViewItem lvi = new ListViewItem ( `` A1 '' ) ; lvi.SubItems.AddRange ( new string [ ] { `` desc '' + i.ToString ( ) , i.ToString ( ) } ) ; listView1.Items.Add ( lvi ) ; } for ( int i = 0 ; i < 2 ; i++ ) { ListViewItem lvi = new ListViewItem ( `` A2 '' ) ; lvi.SubItems.AddRange ( new string [ ] { `` desc '' + i.ToString ( ) , i.ToString ( ) } ) ; listView1.Items.Add ( lvi ) ; } }",Specified items will not be deleted when using ListView.Item.RemoveAt ( ) "C_sharp : I 'm shifting a project over from winforms to WPF . When my code was based on WinForms I used ( this.InvokeRequired ) to check if the thread has access . Now I use the following code based on my Mainform : The issue I have is that the Listbox is n't updating . There are no errors or exceptions , I 've tried updating other UI controls . The LogMessage is writing into the Output window so I 'm stumped . Here 's sample Console output : I 've tried updating other UI controls just to check if it 's an issue with my Listbox but with no luck.Other than switching over to CheckAccess ( ) the only other major change I 've made in the new WPF code is to base all the code running in the Background worker in another Class .. I 'm not sure if this could be part of the issue ? . -- @ JonRaynorI tried your idea : However my Listbox still is n't updating , if I output I see the list box array growing : But no change in the form . This is very confusing ! . // this is the delegate declaration to Allow Background worker thread to write to Log Output delegate void LogUpdateCallBack ( String LogMessage ) ; // method to update the Log Window from the Background Thread public void LogUpdate ( String LogMessage ) { Console.WriteLine ( `` Entering '' ) ; if ( ! Application.Current.Dispatcher.CheckAccess ( ) ) { Console.WriteLine ( `` Thread does n't have UI access '' ) ; LogUpdateCallBack callback = new LogUpdateCallBack ( LogUpdate ) ; Application.Current.Dispatcher.Invoke ( callback , LogMessage ) ; } else { Console.WriteLine ( `` Thread has UI access '' ) ; listBox_Output.Items.Add ( LogMessage ) ; Console.WriteLine ( LogMessage ) ; // listBox_Output.TopIndex = listBox_Output.Items.Count - 1 ; } Console.WriteLine ( `` Exiting '' ) ; } EnteringThread does n't have UI accessEnteringThread has UI accessMy LogMessage is output here ExitingExitingEnteringThread does n't have UI accessEnteringThread has UI accessMy LogMessage is output here ExitingExiting Application.Current.Dispatcher.BeginInvoke ( new LogUpdateCallBack ( LogUpdate ) , LogMessage ) Console.WriteLine ( listBox_Output ) ; System.Windows.Controls.ListBox Items.Count:2020System.Windows.Controls.ListBox Items.Count:2021System.Windows.Controls.ListBox Items.Count:2022System.Windows.Controls.ListBox Items.Count:2023System.Windows.Controls.ListBox Items.Count:2024System.Windows.Controls.ListBox Items.Count:2025",Issue with UI access from Background worker "C_sharp : I have a Windows Phone 8.1 Universal App that I am working on adding basic Cortana support to . A lot of the articles about this are for Silverlight etc . - I 'm finding it hard to find really good information about this.So far , I have activation working if the app is already running or suspended . However , if the app is completely exited , then upon activation it crashes immediately . I 've tried using Hockey and a simple `` LittleWatson '' routine to catch the crash , but it seems to happen too soon to be caught . I 've seen some references to doing a private beta and trying to get the crash dump , but I did n't have any luck with that so far.Here 's what my activation code looks like in app.xaml.cs : and here is my check for the command result : I 'm pretty sure from inserting messages etc . that it fails long before it gets this far.There 's likely something easy I 'm missing but I do n't know what ... What is causing the crash so early ? EDIT One thing I tried is using the `` debug without launch '' configuration to try to catch the exception . When I do this , the app appears to hang forever connected in the debugger on the splash screen . However , that did let me force a break . It hangs inwhich as best I can tell , just tells me the app is hanging somewhere . That 's the only line in the call stack . protected override void OnActivated ( IActivatedEventArgs args ) { base.OnActivated ( args ) ; ReceivedSpeechRecognitionResult = null ; if ( args.Kind == ActivationKind.VoiceCommand ) { var commandArgs = args as VoiceCommandActivatedEventArgs ; if ( commandArgs ! = null ) { ReceivedSpeechRecognitionResult = commandArgs.Result ; var rootFrame = Window.Current.Content as Frame ; if ( rootFrame ! = null ) { rootFrame.Navigate ( typeof ( CheckCredentials ) , null ) ; } } } } private async Task CheckForVoiceCommands ( ) { await Task.Delay ( 1 ) ; // not sure why I need this var speechRecognitionResult = ( ( App ) Application.Current ) .ReceivedSpeechRecognitionResult ; if ( speechRecognitionResult == null ) { return ; } var voiceCommandName = speechRecognitionResult.RulePath [ 0 ] ; switch ( voiceCommandName ) { // omitted } ( ( App ) Application.Current ) .ReceivedSpeechRecognitionResult = null ; } global : :Windows.UI.Xaml.Application.Start ( ( p ) = > new App ( ) ) ;",cortana invocation causes crash at startup "C_sharp : I 'm using the moq framework by Daniel Cazzulino , kzu Version 4.10.1.I want to moq so i can test a particular part of functionality ( below is the simplistic version of the Code i could extract ) The fluent/chain method so are designed so you can get object by an Id and include any additional information if required.i 'm having some trouble fetching the correct object when the function is calling the moq'ed method , which is currently returning the last moq'ed object which is wrong /*My current Moq setup*/class Program { static void Main ( string [ ] args ) { var mock = new Mock < IFluent > ( ) ; var c1 = new ClassA ( ) { Id = 1 , Records = new List < int > ( ) { 5 , 2 , 1 , 10 } , MetaData = new List < string > ( ) } ; var c2 = new ClassA ( ) { Id = 2 , Records = new List < int > ( ) , MetaData = new List < string > ( ) { `` X '' , `` Y '' , `` Z '' } } ; mock.Setup ( x = > x.GetById ( 1 ) .IncludeRecords ( ) .IncludeMetaData ( ) .Get ( ) ) .Returns ( c1 ) ; mock.Setup ( x = > x.GetById ( 2 ) .IncludeRecords ( ) .IncludeMetaData ( ) .Get ( ) ) .Returns ( c2 ) ; var result = new ComputeClass ( ) .ComputeStuff ( mock.Object ) ; Console.WriteLine ( result ) ; Console.ReadLine ( ) ; } } /*Fluent interface and object returned*/public interface IFluent { IFluent GetById ( int id ) ; IFluent IncludeRecords ( ) ; IFluent IncludeMetaData ( ) ; ClassA Get ( ) ; } public class ClassA { public int Id { get ; set ; } public ICollection < int > Records { get ; set ; } public ICollection < string > MetaData { get ; set ; } } /*the method which is doing the work*/public class ComputeClass { public string ComputeStuff ( IFluent fluent ) { var ids = new List < int > ( ) { 1 , 2 } ; var result = new StringBuilder ( ) ; foreach ( var id in ids ) { var resClass = fluent.GetById ( id ) .IncludeRecords ( ) .IncludeMetaData ( ) .Get ( ) ; result.Append ( $ '' Id : { id } , Records : { resClass.Records.Count } , MetaData : { resClass.MetaData.Count } { Environment.NewLine } '' ) ; } return result.ToString ( ) ; } } Current incorrect result /*Id : 1 , Records : 0 , MetaData : 3 Id : 2 , Records : 0 , MetaData : 3*/ Expected Result /*Id : 1 , Records : 3 , MetaData : 0 Id : 2 , Records : 0 , MetaData : 3*/",how to Moq Fluent interface / chain methods "C_sharp : Generally we use various static code analysis tools to analyze our code for validation . But I 've seen some conflicting scenarios.As an example if we use class variables , the StyleCop will suggest us to useinstead of , But this will pop up a Resharper error , `` Redundant qualifier '' and will suggest to not to use `` this . '' notation.So in such scenarios I need to check a more consistent reference to choose what is correct/Best . Is there any such resource that `` defines '' the correct conventions ? this.Name = myName Name = myName",How to deal with Conflicting coding conventions ? "C_sharp : I have a linq to sql query that returns some orders with non zero balance ( in fact , the query is a little bit complicated , but for simplicity I omitted some details ) . This query also should return orders with no CardItems ( both sub-queries return NULL in T-SQL , and comparing two NULLS gives FALSE , so I convert NULL result values of sub-queries to 0 for comparing ) .The problem is , that converting expression Sum ( i = > ( double ? ) i.Amount ) ? ? 0 produce COALESCE operator , which is ten times slower than exactly the same T-SQL query with replaced COALESCE to ISNULL because of sub-query in it . Is there any possibility to generate ISNULL in this situation ? var q = ( from o in db.Orders where db.Cards ( p = > p.OrderId == o.Id & & p.Sum + ( db.CardItems.Where ( i = > i.IncomeId == p.Id ) .Sum ( i = > ( double ? ) i.Amount ) ? ? 0 ) ! = ( db.CardItems.Where ( i = > i.DeductId == p.Id ) .Sum ( i = > ( double ? ) i.Amount ) ? ? 0 ) ) .Any ( ) select o ) ;",Make Linq to Sql generate T-SQL with ISNULL instead of COALESCE "C_sharp : I have a Windows Forms application ( C # , NET 3.5 ) installed using an MSI installer.In this application I have a button that when pressed opens a browser with a specific URL.I useto open the browser.This works fine when debugging , but after the installation it has less than optimal results . For example . If I install it with the Just Me options selected i opens my defaultbrowser ( FF ) with current settings . If I install it with the Everyone option , when I press the buttonit opens a version of IE with out any of my recent settings ( proxy , toolbars displayed etc ) As far as I can tell this issue is caused by the user associated with the application when installing.Taking into account that may users require proxies and personal browser settings and that the Just Me , Everyone choice should remain up to the user . What is the best course o action ? I tried calling Process.Start ( url ) with the current logged in user using But it also requires a password and asking for credentials is not an option.Do you have any other suggestions , am I using Process.Start ( ) incorrectly , are there settings I need to make during installation , is there anything I missed ? UPDATE : Using Process Explorer as data_smith suggested I noticed the following : If I install the application for Everyone it will start under the NTAUTHORITY\SYSTEM user hence the unconfigured browser.If I install the application with Just Me selected it starts underthe current userIs there a way , without asking for credentials , to make the application start ( at windows boot ) under the current user even though it is installed for everyone ? UPDATE : Following a suggestion by data_smith to use ShellExecute and the suggestions here and here I was able to solve the problem and get the desired behavior.The main issue was that when the installer finished the application was started with Process.Start ( ) ; This started the application as the NT AUTHORITY\SYSTEM user ( the users installers run under ) therefore all browsers opened by this application would also be under SYSTEM user . By using the suggestion from data_smith and the suggestions linked above I was able to start the process under the current user . After the computer is rebooted the application starts under the correct user as this is configured through registry entries . Process.Start ( url ) ; ProcessStartInfo.UserName = Environment.UserName",C # Windows Forms does not open default browser after installation "C_sharp : I create a Sitecore item through the Glass.Mapper like this : This works , except the standard values on the Car template are not applied - or if they are they are being immediatetely overwritten by the new Car properties . So if the Car object has a value of null for the Color property , this null is written to the field instead of the `` green '' value from the standard values on the Car template.I have looked for a sensible way to do this through Glass.Mapper , but have found nothing.Is there a way to do this through Glass.Mapper ? var homeItem = sitecoreContext.GetHomeItem < HomeItem > ( ) ; // Create the car itemICar car = sitecoreService.Create ( homeItem.BooksFolder , new Car { Tires = 4 , Seats=4 } ) ;",How to apply standard values to an item created with Glass.Mapper "C_sharp : Is the length of an unicode uppercase string always the same as the length of an original string , no matter what culture is used ? Is the length of an unicode lowercase string always the same as the length of an original string , no matter what culture is used ? In other words , is the following true in C # ? Note that I 'm not interested about the number of bytes : the question about that is already answered . text.ToUpper ( CultureInfo.CurrentCulture ) .Length == text.Lengthtext.ToLower ( CultureInfo.CurrentCulture ) .Length == text.Length",Is uppercase string always of the same length as the original one ? "C_sharp : I 've got a large collection of simple pair class : They are sorted by the ascending Timestamp . I want to trigger an event with the Value ( say , Action < double > ) for each item in the list at the appropriate time . The times are in the past , so I need to normalize the Timestamps such that the first one in the list is `` now '' . Can we set this up with the Reactive Extensions such that it triggers the next event after on the difference in time between two items ? public class Pair { public DateTime Timestamp ; public double Value ; }",use RX to trigger events at varying times ? "C_sharp : The ScrollableControl class has 2 protected boolean properties : HScroll and VScroll.As the document says : Gets or sets a value indicating whether the horizontal scroll bar is visible.And AutoScroll maintains the visibility of the scrollbars automatically . Therefore , setting the HScroll or VScroll properties to true have no effect when AutoScroll is enabled.So I use them like this , but the scrollbar is n't showed : If I use the following code , it works : When I put them torgether , the scrollbar is still invisible , and the values of HScroll and HorizontalScroll.Visible keep False.So what is the real use of HScroll and VScroll ? UpdateMy code and test class MyScrollableControl : ScrollableControl { public MyScrollableControl ( ) { this.AutoScroll = false ; this.HScroll = true ; } } this.HorizontalScroll.Visible = true ; this.AutoScroll = false ; this.HScroll = true ; this.HorizontalScroll.Visible = true ;",What 's the use of HScroll/VScroll in ScrollableControl ? "C_sharp : I 'm having a glitch with a controller that inherits from a base class . My base looks like : My controller inherits from this and defines a constructor like : TinyIOC creates the instance of the conntroller and supplies the constructor services . For some reason , ViewDidLoad runs before the constructor when I do this . When I remove the base class definition , it works with no issues.Any idea why a base class causes the issues ? I can logically assume it has to do with the objective-c compilation , but is there a workaround ? Thanks . public abstract class BaseUIViewController : UIViewController { public BaseUIViewController ( ) : base ( ) { } public BaseUIViewController ( .. ) : base ( .. ) { } } public class MyController : BaseUIViewController { public MyController ( ISOmeService service , IOtherService service ) { .. } override ViewDidLoad ( .. ) { .. } }",Xamarin iOS Controller Custom Inheritance Issues with Dependency Injection "C_sharp : So I have an object called , for lack of a better word , MatricesMatrix which is a Matrix of Matrices ( everything is stored as a double [ , ] ) . I want to strip all of the values from the inner matrices into one big Matrix . Here is what I have so far : Note that I have determined programmatically the total number of rows and columns the returnMatrix needs to have.Here are some more guidelines and output cases : Each element of the big matrix should be in the same position relative to the other elements of the big matrix that came from the Matrix inside of MatricesMatrix that the element came from.Each `` matrix '' ( no longer in matrix form ) inside of the big matrix should be in the same position relative to the other matrices inside of the big matrix as it was inside of the MatricesMatrix ( with no overlapping , and 0 's in any spaces left empty ) .CASE 1Given this input : a MatricesMatrix ( 2,2 ) with [ 0,0 ] = ( 2x2 matrix ) , [ 0,1 ] = ( 2x3 matrix ) , [ 1,0 ] = ( 2x2 matrix ) , and [ 1,1 ] = ( 2x3 matrix ) . That is , Output must be : CASE 2Given this input : a MatricesMatrix ( 2,2 ) with [ 0,0 ] = ( 1x1 matrix ) , [ 0,1 ] = ( 3x3 matrix ) , [ 1,0 ] = ( 2x2 matrix ) , and [ 1,1 ] = ( 4x4 matrix ) . That is , Output should be something like : Any assistance would be greatly appreciated ! UPDATE : Here is a unit test for Case 1 that should pass : public Matrix ConvertToMatrix ( ) { //Figure out how big the return matrix should be int totalRows = this.TotalRows ( ) ; int totalColumns = this.TotalColumns ( ) ; Matrix returnMatrix = new Matrix ( totalRows , totalColumns ) ; List < object > rowElementsList = new List < object > ( ) ; // '' outer '' index means an index of the MatricesMatrix // '' inner '' index means an index of a Matrix within the Matrices Matrix //outer row loop for ( int outerRowIndex = 0 ; outerRowIndex < NumberOfRows ; outerRowIndex++ ) { //outer column loop for ( int outerColumnIndex = 0 ; outerColumnIndex < NumberOfColumns ; outerColumnIndex++ ) { Matrix currentMatrix = GetElement ( outerRowIndex , outerColumnIndex ) ; object element = null ; //inner row loop for ( int innerRowIndex = 0 ; innerRowIndex < currentMatrix.NumberOfRows ; innerRowIndex++ ) { //inner column loop for ( int innerColumnIndex = 0 ; innerColumnIndex < currentMatrix.NumberOfColumns ; innerColumnIndex++ ) { element = currentMatrix.GetElement ( innerRowIndex , innerColumnIndex ) ; } } returnMatrix.SetElement ( outerRowIndex , outerColumnIndex , ( double ) element ) ; } } return returnMatrix ; } [ TestMethod ] public void MatricesMatrix_ConvertToMatrixTest ( ) { Matrix m1 = new Matrix ( 2 ) ; Matrix m2 = new Matrix ( 2 , 3 ) ; Matrix m3 = new Matrix ( 2 ) ; Matrix m4 = new Matrix ( 2 , 3 ) ; double [ ] m1Row1 = { 1 , 1 } ; double [ ] m1Row2 = { 1 , 1 } ; double [ ] m2Row1 = { 2 , 2 , 2 } ; double [ ] m2Row2 = { 2 , 2 , 2 } ; double [ ] m3Row1 = { 3 , 3 } ; double [ ] m3Row2 = { 3 , 3 } ; double [ ] m4Row1 = { 4 , 4 , 4 } ; double [ ] m4Row2 = { 4 , 4 , 4 } ; m1.SetRowOfMatrix ( 0 , m1Row1 ) ; m1.SetRowOfMatrix ( 1 , m1Row2 ) ; m2.SetRowOfMatrix ( 0 , m2Row1 ) ; m2.SetRowOfMatrix ( 1 , m2Row2 ) ; m3.SetRowOfMatrix ( 0 , m3Row1 ) ; m3.SetRowOfMatrix ( 1 , m3Row2 ) ; m4.SetRowOfMatrix ( 0 , m4Row1 ) ; m4.SetRowOfMatrix ( 1 , m4Row2 ) ; MatricesMatrix testMatricesMatrix = new MatricesMatrix ( 2 , 2 ) ; testMatricesMatrix.SetElement ( 0 , 0 , m1 ) ; testMatricesMatrix.SetElement ( 0 , 1 , m2 ) ; testMatricesMatrix.SetElement ( 1 , 0 , m3 ) ; testMatricesMatrix.SetElement ( 1 , 1 , m4 ) ; Matrix expectedResult = new Matrix ( 4 , 5 ) ; double [ ] expectedRow1 = { 1 , 1 , 2 , 2 , 2 } ; double [ ] expectedRow2 = { 1 , 1 , 2 , 2 , 2 } ; double [ ] expectedRow3 = { 3 , 3 , 4 , 4 , 4 } ; double [ ] expectedRow4 = { 3 , 3 , 4 , 4 , 4 } ; expectedResult.SetRowOfMatrix ( 0 , expectedRow1 ) ; expectedResult.SetRowOfMatrix ( 1 , expectedRow2 ) ; expectedResult.SetRowOfMatrix ( 2 , expectedRow3 ) ; expectedResult.SetRowOfMatrix ( 3 , expectedRow4 ) ; Matrix actualResult = testMatricesMatrix.ConvertToMatrix ( ) ; ( actualResult == expectedResult ) .Should ( ) .BeTrue ( ) ; }",Converting a 2D Array of 2D Arrays into a single 2D Array "C_sharp : I 'm writing a custom serializer for struct types for interop with a protocol I ca n't alter . I 'm using reflection to pull out structure member values and write them to a BinaryWriter . It 's only designed to support basic types and arrays of them.Obviously this is ugly , and it gets even more ugly when I want to do the same thing with arrays of these types too.What would be really nice is if I could do something like this : Then do a similar kind of thing for arrays.Any ideas ? if ( fi.FieldType.Name == `` Int16 '' ) bw.Write ( ( Int16 ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` UInt16 '' ) bw.Write ( ( UInt16 ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` Int32 '' ) bw.Write ( ( Int32 ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` UInt32 '' ) bw.Write ( ( UInt32 ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` Int64 '' ) bw.Write ( ( Int64 ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` UInt64 '' ) bw.Write ( ( UInt64 ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` Single '' ) bw.Write ( ( float ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` Double '' ) bw.Write ( ( double ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` Decimal '' ) bw.Write ( ( decimal ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` Byte '' ) bw.Write ( ( byte ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` SByte '' ) bw.Write ( ( sbyte ) fi.GetValue ( obj ) ) ; else if ( fi.FieldType.Name == `` String '' ) bw.Write ( ( string ) fi.GetValue ( obj ) ) ; bw.Write ( ( fi.FieldType ) fi.GetValue ( obj ) ) ;",Dynamic casting of unknown types for serialization "C_sharp : Possible Duplicate : Create Items from 3 collections using Linq I have performed a zippage of two sequences as follows.Now , I just realized that I 'll be using three sequences , not two . So I tried to redesign the code to something like this : Of course , it did n't work . Is there a way to deploy Zip to incorporate what I 'm aiming for ? Is there an other method for such usage ? Will I have to zip two of the sequences and then zip them with the third unzipping them in the process ? At this point I 'm about to create a simple for-loop and yield return the requested structure . Should I ? I 'm on .Net 4 . IEnumerable < Wazoo > zipped = arr1.Zip ( arr2 , ( outer , inner ) = > new Wazoo { P1 = outer , P2 = inner } ) ; IEnumerable < Wazoo > zipped = arr1.Zip ( arr2 , arr3 , ( e1 , e2 , e3 ) = > new Wazoo { P1 = e1 , P2 = e2 , P3 = e3 } ) ;",How to use Zip on three IEnumerables "C_sharp : Look at the sample code belowFor some reason returnValue variable will be of type bool and not bool ? . Why is that and how could it be avoided ? UPD : Here is a screenshot from my VS var genericNullableType = typeof ( Nullable < > ) ; var nullableType = genericNullableType.MakeGenericType ( typeof ( bool ) ) ; var returnValue = Activator.CreateInstance ( nullableType , ( object ) false ) ;",Activator.CreateInstance creates value of type T instead of Nullable < T > "C_sharp : I need to import tracks from a CD but so far I am unable in doing so . I can successfully import .mp3 or many other audio formats from a CD . For importing purpose first I scan files and folder of a CD . Then I show the list of files to user and copy files that user selects from list . Here is my code for scanning a Directory or a CD : I pass the CD path to this function and it creates a list of files for me . This code works fine when CD has only .mp3 or any famous Audio format . But it creates trouble when CD has .CDA extension tracks . As we know that .CDA files are itself does n't play , they are just shortcuts to the original media files . Now , this is where I am stuck right now . How to read .CDA files or import .CDA files media to our local Directory in universal windows app . List < StorageFile > allTrackFiles = null ; private async Task GetFiles ( StorageFolder folder ) { if ( ! scanningRemovableTask ) { return ; } try { if ( allTrackFiles == null ) { allTrackFiles = new List < StorageFile > ( ) ; } var items = await folder.GetItemsAsync ( ) ; foreach ( var item in items ) { if ( item.GetType ( ) == typeof ( StorageFile ) ) { StorageFile storageFile = item as StorageFile ; allTrackFiles.Add ( storageFile ) ; var basicProperties = await storageFile.GetBasicPropertiesAsync ( ) ; var musicProperties = await storageFile.OpenReadAsync ( ) ; } else await GetFiles ( item as StorageFolder ) ; } } catch ( Exception e ) { } }",How to import .CDA tracks from a CD in windows 10 universal app ? "C_sharp : I am developing windows application.In that i have date in the string format as > > fileDate= '' 15/03/2013 '' I want it to be get converted into date format as my database field is datetime.I used following things for it > > Both of these methods proved failure giving me error > > What can be mistake ? Is there another technique to do that ? DateTime dt = DateTime.ParseExact ( fileDate , `` yyyyy-DD-MM '' , CultureInfo.InvariantCulture ) ; DateTime dt = DateTime.Parse ( fileDate ) ; String was not recognized as a valid DateTime .",date conversion error "C_sharp : I am using .Net 4 and VS express 2010.I could make my post request but I cant set some of the headers . Below code work finesThe problems is that I cant set other headers like `` Accept '' , '' UserAgent '' , '' Referer '' , '' Connection '' I had tried the following ways but failFor the first line , the Accept property does n't existwhile for the second line , the header need to be edited with a proper method or property.I am a rookie and I had searched on google and stackoverflow.If you do n't know how to solve it , pointing out any direction in fixing this like reinstalling something would be really appreciated . WebRequest Request = Request.Create ( `` http : //example.com '' ) as HttpWebRequest ; Request.Method = `` POST '' ; Request.ContentType = `` application/x-www-form-urlencoded ; charset=UTF-8 '' ; Request.Headers.Set ( `` Accept-Encoding '' , `` gzip , deflate '' ) ; Request.Accept = `` */* '' ; Request.Headers.Set ( `` Accept '' , `` */* '' ) ;",Missing Properties in HttpWebRequest "C_sharp : Using VS2013 , in the following example two different errors are given when attempting to pass a function to a worker 's constructor , yet , lambda functions with the same prototype are ok.What am I doing wrong , and how can I change the definition of the GetA function to allow it to be passed ? In order to avoid confusion with similar-sounding questions caused by misunderstanding how class inheritance works , I 've intentionally avoided any inheritance in this example.WorkerA can only accept a Func < A > in it 's contructor.WorkerAorB is more flexible , and can accept either a Func < A > or a Func < B > .WorkerAandB is the most capable , and can accept a Func < A > and a Func < B > simultaneously ( or either ) . It is the closest to my real code.However , when code in the manager attempts to instantiate workers , WorkerA works as expected , but WorkerAorB gives the error : error CS0121 : The call is ambiguous between the following methods or properties : 'WorkerAorB.WorkerAorB ( System.Func < A > ) ' and 'WorkerAorB.WorkerAorB ( System.Func < B > ) 'WorkerAandB gives error CS0407 : ' A ManagerA.GetA ( ) ' has the wrong return typeIn each case , it seems that the compiler becomes unable to determine which overload to use when it is being passed a reference to a real function rather than a lambda or an existing Func < A > variable , and in the WorkerAandB case it is unambiguously selecting the WRONG overload , and giving an error about the return type of the passed function.Can the GetA or GetAstatic functions be modified in some way to help the compiler recognise the correct overload to use , or are only lambdas and/or explicitly-declared delegates allowed in this context ? Update : Some information that I 'd omitted from the example . In the real problem , classes A and B are in fact related . Also , on further reflection of the real problem , a call to like was in fact equivalent to So for the real problem , I 've done the equivalent of deleting the second constructor in the example problem , as it turns out the overload was redundant . In the meantime I 've accepted the answer that actually gave a potential solution to the problem ( albeit an obvious one that I 'd omitted to mention in the original question ) , even though it was n't what I eventually used . class A { } class B { } class WorkerA { public WorkerA ( Func < A > funcA ) { } } class WorkerAorB { public WorkerAorB ( Func < A > funcA ) { } public WorkerAorB ( Func < B > funcB ) { } } class WorkerAandB { public WorkerAandB ( Func < A > funcA , Func < B > funcB = null ) { } public WorkerAandB ( Func < B > funcB ) { } } class ManagerA { A GetA ( ) { return new A ( ) ; } static A GetAstatic ( ) { return new A ( ) ; } Func < A > GetAfunc = GetAstatic ; ManagerA ( ) { new WorkerA ( ( ) = > new A ( ) ) ; // ok new WorkerA ( GetA ) ; // ok new WorkerA ( GetAstatic ) ; // ok new WorkerAorB ( ( ) = > new A ( ) ) ; // ok new WorkerAorB ( ( ) = > new B ( ) ) ; // ok new WorkerAorB ( GetA ) ; // error CS0121 new WorkerAorB ( GetAstatic ) ; // error CS0121 new WorkerAorB ( ( ) = > GetA ( ) ) ; // ok new WorkerAorB ( GetAfunc ) ; // ok new WorkerAandB ( ( ) = > new A ( ) ) ; // ok new WorkerAandB ( GetA ) ; // error CS0407 new WorkerAandB ( GetAstatic ) ; // error CS0407 new WorkerAandB ( GetA , null ) ; // ok new WorkerAandB ( GetAstatic , null ) ; // ok new WorkerAandB ( GetAfunc ) ; // ok } } // class ManagerB or ManagerAandB left as an exercise to the reader ! class B : A { } public WorkerAandB ( Func < B > funcB ) { } new WorkerAandB ( GetB ) new WorkerAandB ( GetB , GetB )",Wrong overload giving compiler error "C_sharp : I do n't know to search or google it so I ask it here . I have an array of integers with fixed size and exactly with this logic.Now I am given a number for example 26 . And I shall find the numbers whose sum will make this number , in this case is [ 2,8,16 ] for a number of 20 it will be [ 4,16 ] for 40 it is [ 8,32 ] and for 63 it is all of these numbers [ 1,2,4,8,16,32 ] What is the proper algorithm for that ? I know strictly that there is always this continuation that the number is double of the previous value.as well as only the numbers from the given array will sum up to the given number and each number will be used only for once or noneIf it will be in C # method that takes array of ints and an int value and returns the array of ints that contains the ints that sum up this number from the given array will be preferred.Thank you sample [ 1,2,4,8,16,32 ]",Algorithm to get which values make sum of a given number from array C_sharp : So I am creating a list of lines in a text file like this : and looping through the lines like thisSimilary like I access the first two rows I would like to access the last and second last row individually var lines = File.ReadAllLines ( `` C : \\FileToSearch.txt '' ) .Where ( x = > ! x.EndsWith ( `` 999999999999 '' ) ) ; foreach ( var line in lines ) { if ( lineCounter == 1 ) { outputResults.Add ( oData.ToCanadianFormatFileHeader ( ) ) ; } else if ( lineCounter == 2 ) { outputResults.Add ( oData.ToCanadianFormatBatchHeader ( ) ) ; } else { oData.FromUsLineFormat ( line ) ; outputResults.Add ( oData.ToCanadianLineFormat ( ) ) ; } lineCounter = lineCounter + 1 ; textBuilder += ( line + `` < br > '' ) ; },Getting last two rows in a text file "C_sharp : I 'm trying to build a project in .NET 5.0 using Azure DevOps pipeline Build and I 'm received this errorError imageDoes someone know if Azure DevOps pipelines have support for building .NET 5.0 code ? 2020-11-14T01:59:45.8238544Z [ command ] '' C : \Program Files\dotnet\dotnet.exe '' build D : \a\1\s\XXX.csproj `` -dl : CentralLogger , \ '' D : \a\_tasks\DotNetCoreCLI_5541a522-603c-47ad-91fc-a4b1d163081b\2.178.0\dotnet-build-helpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll\ '' *ForwardingLogger , \ '' D : \a\_tasks\DotNetCoreCLI_5541a522-603c-47ad-91fc-a4b1d163081b\2.178.0\dotnet-build-helpers\Microsoft.TeamFoundation.DistributedTask.MSBuild.Logger.dll\ '' '' 2020-11-14T01:59:46.1472016Z Microsoft ( R ) Build Engine version 16.7.0+7fb82e5b2 for .NET2020-11-14T01:59:46.1473316Z Copyright ( C ) Microsoft Corporation . All rights reserved.2020-11-14T01:59:46.1473902Z 2020-11-14T01:59:46.6006398Z Determining projects to restore ... 2020-11-14T01:59:47.2059773Z Restored D : \a\1\s\XXX.csproj ( in 234 ms ) .2020-11-14T01:59:47.2119638Z 1 of 2 projects are up-to-date for restore . 2020-11-14T01:59:47.3209350Z # # [ error ] C : \Program Files\dotnet\sdk\3.1.403\Microsoft.Common.CurrentVersion.targets ( 1177,5 ) : Error MSB3644 : The reference assemblies for .NETFramework , Version=v5.0 were not found . To resolve this , install the Developer Pack ( SDK/Targeting Pack ) for this framework version or retarget your application . You can download .NET Framework Developer Packs at https : //aka.ms/msbuild/developerpacks2020-11-14T01:59:47.3261839Z C : \Program Files\dotnet\sdk\3.1.403\Microsoft.Common.CurrentVersion.targets ( 1177,5 ) : error MSB3644 : The reference assemblies for .NETFramework , Version=v5.0 were not found . To resolve this , install the Developer Pack ( SDK/Targeting Pack ) for this framework version or retarget your application . You can download .NET Framework Developer Packs at https : //aka.ms/msbuild/developerpacks [ D : \a\1\s\XXX.csproj ] 2020-11-14T01:59:47.3270768Z 2020-11-14T01:59:47.3274231Z Build FAILED.2020-11-14T01:59:47.3275925Z 2020-11-14T01:59:47.3277393Z C : \Program Files\dotnet\sdk\3.1.403\Microsoft.Common.CurrentVersion.targets ( 1177,5 ) : error MSB3644 : The reference assemblies for .NETFramework , Version=v5.0 were not found . To resolve this , install the Developer Pack ( SDK/Targeting Pack ) for this framework version or retarget your application . You can download .NET Framework Developer Packs at https : //aka.ms/msbuild/developerpacks [ D : \a\1\s\XXX.csproj ] 2020-11-14T01:59:47.3279484Z 0 Warning ( s ) 2020-11-14T01:59:47.3279860Z 1 Error ( s ) 2020-11-14T01:59:47.3280170Z 2020-11-14T01:59:47.3280537Z Time Elapsed 00:00:01.092020-11-14T01:59:47.3624731Z # # [ error ] Error : The process ' C : \Program Files\dotnet\dotnet.exe ' failed with exit code 1",Building .NET 5.0 project Azure DevOps pipeline "C_sharp : I have a litte confusion regarding method overriding and the validity of OOP priciples.I know everything regarding sealing , shadowing , overriding , virtual etc . but I came across a scenario , that just confused me . Suppose I have : According to everything I studied so far , a method declared as virtual or abstract ( in abstract class ) can be overriden using override keyword in child class . according to this , above code works perfect . When I remove the virtual keyword , and then try to override the method using override keyword , then compiler gives error as : can not override inherited member 'inheritence.classA.sayhello ( ) ' because it is not marked virtual , abstract , or overrideand then i removed the override key word , from child class , and provided the implementation as : In this case , the method could be overrided . I 'm able to override the method , which is not virtual or abstract . so , my question is:1 . Did it not violate the OOP principle ? since I 'm able to override the method , which is not marked as virtual in parent.2 . Why am I allowed to override the method this way ? which is not even marked virtual ? 3 . Removing virtual keyword from classA method , it gave me the feeling of sealed method in classA , when I tried to override that method in classB . ( as I mentioned the compiler error earlier ) . If i remove virtual , so that the child class may not override it , then WHY could the child class cleverly override it , removing its override keyword ? Is this ONLY the case , sealed keyword is designed for ? class classA { public virtual void sayhello ( ) { Console.WriteLine ( `` hello I 'm A '' ) ; } } ; class classB : classA { public override void sayhello ( ) { Console.WriteLine ( `` hello I 'm B '' ) ; } } ; class Program { static void Main ( string [ ] args ) { classB a = new classB ( ) ; a.sayhello ( ) ; } } class classB : classA { public void sayhello ( ) { Console.WriteLine ( `` hello I 'm B '' ) ; } } ;",confusion regarding overriding rules C # "C_sharp : I have to process like 1M entities to build facts . There should be about the same amount of resulting facts ( 1 million ) . The first issue that I had was the bulk insert it was slow with entity framework . So I used this pattern Fastest Way of Inserting in Entity Framework ( answer from SLauma ) . And I can insert entities real fast now about 100K in one minute . Another issue I ran into is the lack of memory to process everything . So I 've `` paged '' the processing . To avoid out of memory exception I would get if I make a list out of my 1 million resulting facts.The issue I have is that the memory is always growing even with the paging and I do n't understand why . After each batch no memory is released . I think this is weird because i fetch recons build facts and store them into the DB at each iteration of the loop . As soon as the loop is completed those should be released from memory . But it look like not because no memory is released after each iteration . Can you please tell me if you see something wrong before I dig more ? More specifically why no memory is released after an iteration of the while loop . The method provided by Slauma to optimize bulk insert with entity framework . static void Main ( string [ ] args ) { ReceiptsItemCodeAnalysisContext db = new ReceiptsItemCodeAnalysisContext ( ) ; var recon = db.Recons .Where ( r = > r.Transacs.Where ( t = > t.ItemCodeDetails.Count > 0 ) .Count ( ) > 0 ) .OrderBy ( r = > r.ReconNum ) ; // used for `` paging '' the processing var processed = 0 ; var total = recon.Count ( ) ; var batchSize = 1000 ; //100000 ; var batch = 1 ; var skip = 0 ; var doBatch = true ; while ( doBatch ) { // list to store facts processed during the batch List < ReconFact > facts = new List < ReconFact > ( ) ; // get the Recon items to process in this batch put them in a list List < Recon > toProcess = recon.Skip ( skip ) .Take ( batchSize ) .Include ( r = > r.Transacs.Select ( t = > t.ItemCodeDetails ) ) .ToList ( ) ; // to process real fast Parallel.ForEach ( toProcess , r = > { // processing a recon and adding the facts to the list var thisReconFacts = ReconFactGenerator.Generate ( r ) ; thisReconFacts.ForEach ( f = > facts.Add ( f ) ) ; Console.WriteLine ( processed += 1 ) ; } ) ; // saving the facts using pattern provided by Slauma using ( TransactionScope scope = new TransactionScope ( TransactionScopeOption.Required , new System.TimeSpan ( 0 , 15 , 0 ) ) ) { ReceiptsItemCodeAnalysisContext context = null ; try { context = new ReceiptsItemCodeAnalysisContext ( ) ; context.Configuration.AutoDetectChangesEnabled = false ; int count = 0 ; foreach ( var fact in facts.Where ( f = > f ! = null ) ) { count++ ; Console.WriteLine ( count ) ; context = ContextHelper.AddToContext ( context , fact , count , 250 , true ) ; //context.AddToContext ( context , fact , count , 250 , true ) ; } context.SaveChanges ( ) ; } finally { if ( context ! = null ) context.Dispose ( ) ; } scope.Complete ( ) ; } Console.WriteLine ( `` batch { 0 } finished continuing '' , batch ) ; // continuing the batch batch++ ; skip = batchSize * ( batch - 1 ) ; doBatch = skip < total ; // AFTER THIS facts AND toProcess SHOULD BE RESET // BUT IT LOOKS LIKE THEY ARE NOT OR AT LEAST SOMETHING // IS GROWING IN MEMORY } Console.WriteLine ( `` Processing is done { } recons processed '' , processed ) ; } class ContextHelper { public static ReceiptsItemCodeAnalysisContext AddToContext ( ReceiptsItemCodeAnalysisContext context , ReconFact entity , int count , int commitCount , bool recreateContext ) { context.Set < ReconFact > ( ) .Add ( entity ) ; if ( count % commitCount == 0 ) { context.SaveChanges ( ) ; if ( recreateContext ) { context.Dispose ( ) ; context = new ReceiptsItemCodeAnalysisContext ( ) ; context.Configuration.AutoDetectChangesEnabled = false ; } } return context ; } }",Memory growing unexpectedly while using entity framework to bulk insert "C_sharp : I have a client with a MVC application that accepts raw JSON requests . The ModelBinder maps incoming key/value pairs to the Controller Model properties , no problem there.The problem is they want to throw an error when they send an invalid key/value pair , and for the life of me I can not find the raw incoming data.For example , if I have a model with a string property MName but in their JSON request they send `` MiddleName '' : '' M '' , the ModelBinder will toss this invalid key and leave the MName property blank . This does not throw an error and ModelState.IsValid returns true.I know that I could throw a [ Required ] attribute on the property , but that 's not right , either , since there might be null values for that property , and still does n't get to the problem of detecting key/value pairs that do n't belong.This is n't a question of over-posting ; I 'm not trying to prevent an incoming value from binding to the model . I 'm trying to detect when an incoming value just did n't map to anything in the model.Since the values are coming in as application/json in the request body , I 'm not having luck even accessing , let along counting or enumerating , the raw request data . I can pull name/value pairs from ModelState.Keys but that only includes the fields that were successfully mapped . None of these keys are in the Request [ ] collection.And yes , this is in ASP.NET MVC 5 , not WebApi . Does WebAPI handle this any differently ? Any ideas ? Example : application/json : { `` FName '' : '' Joe '' , `` MName '' : '' M '' , `` LName '' : '' Blow '' } public class PersonModel { public string FName { get ; set ; } public string LName { get ; set ; } } public class PersonController ( ) : Controller { public ActionResult Save ( PersonModel person ) { if ( ModelState.IsValid ) // returns true // do things return View ( person ) } }",Determine when invalid JSON key/value pairs are sent in a .NET MVC request "C_sharp : I am using task factory to spawn parallel threads and my code is as below . I have the requirement to print the completion time of every thread but dont know how to check for every thread . Currently my code is waiting for all tasks to finish and then calculating the time . stp1.Start ( ) ; for ( int i = 0 ; i < tsk.Length ; i++ ) { tsk [ i ] = Task.Factory.StartNew ( ( object obj ) = > { resp = http.SynchronousRequest ( web , 443 , true , req ) ; } , i ) ; } try { Task.WaitAll ( tsk ) ; } stp1.Stop ( ) ;",storing the task completion time of every task using Task factory "C_sharp : How do I parse C # conditional compilation statement using Roslyn.In the following code , I want Roslyn to give the Conditional compilation statement node.I do n't get conditional compilation node in SyntaxTree and neither it is part of LeadingTrivia of } or TrailingTrivia of { What I get in LeadingTrivia of } is `` \t\t # endif\r\n\t\t '' and TrailingTrivia of { is `` \r\n '' which is not complete conditional compilation statement.Can someone point me to the right direction ? public abstract class TestClass { public int Get ( ) { # if DEBUG return 1 ; # else return 2 ; # endif } }",Parsing C # Conditional Compilation statements in roslyn "C_sharp : I am an iOS developer which has been asked to do development in Xamarin . I want to log the outputs in Xamarin . I am trying to find a library for this . I found one library for this called MetroLog.Link : https : //github.com/onovotny/MetroLogBut the problem is I am getting blue coloured output for every log level.Like this : I was expecting that the errors would be in red , warnings would be in orange , and others in green or blue or something , but I could not get the required output in the manner I thought I would . I am running sample project from their repo , which has source code as follows : Are there some changes that I need to make to the logging project when it has been added to my project ? Is there any other library which can solve my use case for logging ? If not then how can I achieve similar and coloured option from MetroLog ? I am open to other options ( open source project ) as well.MORE INFO or EXTENDED QUESTION : As I am used to iOS development I used to use the following statements in order to log the information : I am expecting some sort of quick logging option like the one for iOS as shown above without including any library . Is that possible ? ( including the class name and the method name which is executing the code ) Thanks . _log.Info ( `` Information - We are about to do magic ! '' ) ; _log.Warn ( `` Warning ! `` ) ; _log.Trace ( `` Trace some data . `` ) ; _log.Error ( `` Something bad happened at { 0 } '' , DateTime.Now ) ; _log.Fatal ( `` Danger Will Robinson ! `` ) ; NSLog ( @ '' % @ % @ started '' , [ self class ] , NSStringFromSelector ( _cmd ) ) ; NSLog ( @ '' % @ % @ ends `` , [ self class ] , NSStringFromSelector ( _cmd ) ) ;",Library for Logging in Xamarin and error reporting style in MetroLog "C_sharp : I am using COM Interop . I have a call in VB6 which returns a string of roughly 13000 chars . If I execute the call in pure VB6 it takes about 800ms to execute . If I execute it via c # and COM Interop it takes about 8 seconds . I 'm assuming the delay is caused by marshaling . If I am correct about marshaling , I 'd be grateful if someone could suggest the fastest way I can get this into C # . e.g . Would it be better to a ) expose it as a byte arrayb ) provide a byref string param into the VB6 layerI would appreciate some sample code as well . I tried the to no avail. -- Following on from Franci 's comment . I am simply referencing the VB6 dll ( so in process ) from a C # dll . Here 's an extract from OLEViewI should probably point out that the parameter ( p_oEventHistory ) is another COM object which I am instantiating in C # but that takes about 80msS Marshal.PtrToStringAuto ( Marshal.ReadIntPtr ( myCOMObject.GetString , 0 ) interface _MyCOMObect : IDispatch { ... [ id ( 0x60030006 ) ] HRESULT GetString ( [ in ] _IEventHistory* p_oEventHistory , [ out , retval ] _IXML** ) ; ... } ; [ uuid ( 09A06762-5322-4DC1-90DD-321D4EFC9C3E ) , version ( 1.0 ) , custom ( { 17093CC6-9BD2-11CF-AA4F-304BF89C0001 } , `` 0 '' ) ] coclass MyCOMObject { [ default ] interface _CFactory ; } ; [ odl , uuid ( C6E7413F-C63A-43E4-8B67-6AEAD132F5E5 ) , version ( 1.0 ) , hidden , dual , nonextensible , oleautomation ]",Fastest way to access VB6 String in C # "C_sharp : This might be a dumb question but I 'm really curious if I can do this . I wrote the following sample program : Y compiled this using mcs and then I diassembled the generated exe with monodis . Obtained the following code : I want to use ldsfld to load the value of b . If I change IL_0006 to ldsfld int32 Test.Test1 : :b , it will assemble , but when I run the executable I obtain an excpetion : Is there any way to use the static literal instead of just using ldc ? class Test1 { public const int b = 8 ; public static int z = 3 ; public static void Main ( string [ ] args ) { const int q = 6 ; Console.WriteLine ( q ) ; Console.WriteLine ( b ) ; Console.WriteLine ( z ) ; } } .field public static literal int32 b = int32 ( 0x00000008 ) .field public static int32 z// method line 2.method public static hidebysig default void Main ( string [ ] args ) cil managed { // Method begins at RVA 0x2058 .entrypoint // Code size 23 ( 0x17 ) .maxstack 8 IL_0000 : ldc.i4.6 IL_0001 : call void class [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_0006 : ldc.i4.8 IL_0007 : call void class [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_000c : ldsfld int32 Test.Test1 : :z IL_0011 : call void class [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_0016 : ret } // end of method Test1 : :Main Unhandled Exception : System.InvalidProgramException : Invalid IL code in Test.Test1 : Main ( string [ ] ) : IL_0006 : ldsfld 0x04000001 [ ERROR ] FATAL UNHANDLED EXCEPTION : System.InvalidProgramException : Invalid IL code in Test.Test1 : Main ( string [ ] ) : IL_0006 : ldsfld 0x04000001",CIL - How do I use a public static literal field ? "C_sharp : I 'm working on creating a JsonConverter for JSON.NET that is capable of serializing and deserializing expressions ( System.Linq.Expressions ) . I 'm down to the last 5 % or so of the work , and I 'm having problems being able to run a LINQ-to-SQL query generated from the deserialized expression.Here is the expression : This is a pretty straightforward grouping query in LINQ-to-SQL . TestQuerySource is an implementation of System.Data.Linq.DataContext . Bundle , BundleItem , Product , are all LINQ-to-SQL entities decorated with TableAttribute and other other mapping attributes . Their corresponding datacontext properties are all Table < T > properties as normal . In other words , nothing spectacularly notable here.However , when I attempt to run the query after the expression has been deserialized , I get the following error : I understand that this means that something the expression is doing can not be translated to SQL by the LINQ-to-SQL query provider . It appears that it has something to do with creating an anonymous type as part of the query , like as part of the join statement . This assumption is supported by comparing the string representation of the original and deserialized expressions : Original ( working ) : Deserialized ( broken ) : The problem seems to occur when a non-primitively typed property of an anonymous type needs be accessed . In this case the bi property is being accessed in order to get to BundleItem 's ProductID property.What I ca n't figure out is what the difference would be - why accessing the property in the original expression would work fine , but not in the deserialized expression.I 'm guessing the issue has something to do with some sort of information about the anonymous type getting lost during serialization , but I 'm not sure where to look to find it , or even what to be looking for.Other Examples : It is worth noting that simpler expressions like this one work fine : Even doing grouping ( without joining ) works as well : Simple joins work : Selecting an anonymous type works : Here are the string representations of the last example : Original : Deserialized : Expression < Func < TestQuerySource , Bundle > > expression = db = > ( from b in db.Bundles join bi in db.BundleItems on b.ID equals bi.BundleID join p in db.Products on bi.ProductID equals p.ID group p by b ) .First ( ) .Key ; System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation . -- - > System.NotSupportedException : The member ' < > f__AnonymousType0 ` 2 [ Bundle , BundleItem ] .bi ' has no supported translation to SQL . { db = > db.Bundles.Join ( db.BundleItems , b = > b.ID , bi = > bi.BundleID , ( b , bi ) = > new < > f__AnonymousType0 ` 2 ( b = b , bi = bi ) ) .Join ( db.Products , < > h__TransparentIdentifier0 = > < > h__TransparentIdentifier0.bi.ProductID , p = > p.ID , ( < > h__TransparentIdentifier0 , p ) = > new < > f__AnonymousType1 ` 2 ( < > h__TransparentIdentifier0 = < > h__TransparentIdentifier0 , p = p ) ) .GroupBy ( < > h__TransparentIdentifier1 = > < > h__TransparentIdentifier1. < > h__TransparentIdentifier0.b , < > h__TransparentIdentifier1 = > < > h__TransparentIdentifier1.p ) .First ( ) .Key } { db = > db.Bundles.Join ( db.BundleItems , b = > b.ID , bi = > bi.BundleID , ( b , bi ) = > new < > f__AnonymousType0 ` 2 ( b , bi ) ) .Join ( db.Products , < > h__TransparentIdentifier0 = > < > h__TransparentIdentifier0.bi.ProductID , p = > p.ID , ( < > h__TransparentIdentifier0 , p ) = > new < > f__AnonymousType1 ` 2 ( < > h__TransparentIdentifier0 , p ) ) .GroupBy ( < > h__TransparentIdentifier1 = > < > h__TransparentIdentifier1. < > h__TransparentIdentifier0.b , < > h__TransparentIdentifier1 = > < > h__TransparentIdentifier1.p ) .First ( ) .Key } Expression < Func < TestQuerySource , Category > > expression = db = > db.Categories.First ( ) ; Expression < Func < TestQuerySource , Int32 > > expression = db = > db.Categories.GroupBy ( c = > c.ID ) .First ( ) .Key ; Expression < Func < TestQuerySource , Product > > expression = db = > ( from bi in db.BundleItems join p in db.Products on bi.ProductID equals p.ID select p ) .First ( ) ; Expression < Func < TestQuerySource , dynamic > > expression = db = > ( from bi in db.BundleItems join p in db.Products on bi.ProductID equals p.ID select new { a = bi , b = p } ) .First ( ) ; { db = > db.BundleItems.Join ( db.Products , bi = > bi.ProductID , p = > p.ID , ( bi , p ) = > new < > f__AnonymousType0 ` 2 ( a = bi , b = p ) ) .First ( ) } { db = > db.BundleItems.Join ( db.Products , bi = > bi.ProductID , p = > p.ID , ( bi , p ) = > new < > f__AnonymousType0 ` 2 ( bi , p ) ) .First ( ) }",`` No supported translation to SQL '' after deserializing IQueryable expression "C_sharp : If I have a list of items ( e.g . List < string > items ) in C # , I can use both : andto get the total number of items . Is there a reason for them both being available ? Why not just have the method .Count ( ) ? I notice that if I filter the list ( and and end up with an IEnumerable < string > ) : then .Count ( ) has to be used . So why does List < string > allow .Count at all ? items.Count ( ) items.Count items.Distinct ( ) .Count ( )",Why does .Count work without parentheses ? "C_sharp : To illustrate my question , consider these trivial examples ( C # ) : So in the cases where we attempt a reference conversion ( corresponding to CIL instruction castclass ) , the exception thrown contains an excellent message of the form : Unable to cast object of type ' X ' to type ' Y'.Empirical evidence shows that this text message is often extremely helpful for the ( experienced or inexperienced ) developer ( bug fixer ) who needs to deal with the problem.In contrast , the message we get when an attempted unboxing ( unbox.any ) fails , is rather non-informative . Is there any technical reason why this must be so ? Specified cast is not valid . [ NOT HELPFUL ] In other words , why do we not receive a message like ( my words ) : Unable to unbox an object of type ' X ' into a value of type ' Y ' ; the two types must agree.respectively ( my words again ) : Unable to unbox a null reference into a value of the non-nullable type ' Y'.So to repeat my question : Is it `` accidental '' that the error message in one case is good and informative , and in the other case is poor ? Or is there a technical reason why it would be impossible , or prohibitively difficult , for the runtime to provide details of the actual types encountered in the second case ? ( I have seen a couple of threads here on SO that I am sure would never have been asked if the exception text for failed unboxings had been better . ) Update : Daniel Frederico Lins Leite 's answer led to him opening an issue on the CLR Github ( see below ) . This was discovered to be a duplicate of an earlier issue ( raised by Jon Skeet , people almost guessed it ! ) . So there was no good reason for the poor exception message , and people had already fixed it in the CLR . So I was not the first to wonder about this . We can look forward to the day when this improvement ships in the .NET Framework . object reference = new StringBuilder ( ) ; object box = 42 ; object unset = null ; // CASE ONE : bad reference conversions ( CIL instrcution 0x74 'castclass ' ) try { string s = ( string ) reference ; } catch ( InvalidCastException ice ) { Console.WriteLine ( ice.Message ) ; // Unable to cast object of type 'System.Text.StringBuilder ' to type 'System.String ' . } try { string s = ( string ) box ; } catch ( InvalidCastException ice ) { Console.WriteLine ( ice.Message ) ; // Unable to cast object of type 'System.Int32 ' to type 'System.String ' . } // CASE TWO : bad unboxing conversions ( CIL instrcution 0xA5 'unbox.any ' ) try { long l = ( long ) reference ; } catch ( InvalidCastException ice ) { Console.WriteLine ( ice.Message ) ; // Specified cast is not valid . } try { long l = ( long ) box ; } catch ( InvalidCastException ice ) { Console.WriteLine ( ice.Message ) ; // Specified cast is not valid . } try { long l = ( long ) unset ; } catch ( NullReferenceException nre ) { Console.WriteLine ( nre.Message ) ; // Object reference not set to an instance of an object . }",Why does 'unbox.any ' not provide a helpful exception text the way 'castclass ' does ? "C_sharp : C # 7.2 introduced reference semantics with value-types , and alongside this Microsoft have developed types like Span < T > and ReadOnlySpan < T > to potentially improve performance for apps that need to perform operations on contiguous regions of memory.According to the docs , one way of potentially improving performance is to pass immutable structs by reference by adding an in modifier to parameters of those types : What I 'm wondering is whether I ought to do this with types like ReadOnlySpan < T > . Should I be declaring methods that accept a read-only span like this : or simply like : Will the former offer any performance benefits over the latter ? I could n't find any documentation that explicitly advises in either direction , but I did find this example where they demonstrated a method that accepts a ReadOnlySpan and did not use the in modifier . void PerformOperation ( in SomeReadOnlyStruct value ) { } void PerformOperation < T > ( in ReadOnlySpan < T > value ) { } void PerformOperation < T > ( ReadOnlySpan < T > value ) { }",Should ReadOnlySpan < T > parameters use the `` in '' modifier ? "C_sharp : I 'm running on a 32-bit machine and I 'm able to confirm that long values can tear using the following code snippet which hits very quickly.But when I try something similar with doubles , I 'm not able to get any tearing . Does anyone know why ? As far as I can tell from the spec , only assignment to a float is atomic . The assignment to a double should have a risk of tearing . static void TestTearingLong ( ) { System.Threading.Thread A = new System.Threading.Thread ( ThreadA ) ; A.Start ( ) ; System.Threading.Thread B = new System.Threading.Thread ( ThreadB ) ; B.Start ( ) ; } static ulong s_x ; static void ThreadA ( ) { int i = 0 ; while ( true ) { s_x = ( i & 1 ) == 0 ? 0x0L : 0xaaaabbbbccccddddL ; i++ ; } } static void ThreadB ( ) { while ( true ) { ulong x = s_x ; Debug.Assert ( x == 0x0L || x == 0xaaaabbbbccccddddL ) ; } } static double s_x ; static void TestTearingDouble ( ) { System.Threading.Thread A = new System.Threading.Thread ( ThreadA ) ; A.Start ( ) ; System.Threading.Thread B = new System.Threading.Thread ( ThreadB ) ; B.Start ( ) ; } static void ThreadA ( ) { long i = 0 ; while ( true ) { s_x = ( ( i & 1 ) == 0 ) ? 0.0 : double.MaxValue ; i++ ; if ( i % 10000000 == 0 ) { Console.Out.WriteLine ( `` i = `` + i ) ; } } } static void ThreadB ( ) { while ( true ) { double x = s_x ; System.Diagnostics.Debug.Assert ( x == 0.0 || x == double.MaxValue ) ; } }",Simulate tearing a double in C # "C_sharp : Let 's say we have generic method : And we are invoking it with the following parameters : The results are : andCan someone explain me why typeof integer casted to object returns System.Object , but .GetType ( ) returns System.Int32 ? public void GenericMethod < T > ( T item ) { var typeOf = typeof ( T ) ; var getType = item.GetType ( ) ; } GenericMethod ( 1 ) GenericMethod ( ( object ) 1 ) typeOf = System.Int32getType = System.Int32 typeOf = System.ObjectgetType = System.Int32",typeof generic and casted type "C_sharp : I have some code which ignores a specific exception . of course this results in a compile time warning as ex is unused . Is there some standard accept noop which should be used to remove this warning ? try { foreach ( FileInfo fi in di.GetFiles ( ) ) { collection.Add ( fi.Name ) ; } foreach ( DirectoryInfo d in di.GetDirectories ( ) ) { populateItems ( collection , d ) ; } } catch ( UnauthorizedAccessException ex ) { //ignore and move onto next directory }",Ignoring exceptions "C_sharp : I recently came across the below piece of code in our applicationIn the above code , Advisors is a List and UpdateDefinitionBuilder is from MongoDB driver . Could you please let me know the use of -1 in the index of the list ? Editing after the below comments/answersThe OverviewProfile class is as below : And this is this the working code . This code updates the data to the mongo db based on the condition . There are no other methods inside this class , just other properties.This is one class , but the same usage is there for properties of multiple class , and even when we add a new List property and check , it works fine . var updateDefinition = new UpdateDefinitionBuilder < OverviewProfile > ( ) .Set ( a = > a.Advisors [ -1 ] .IsCurrent , advisor.IsCurrent ) ; public class OverviewProfile : BaseInvestorProfile { //Other properties public List < Advisor.View.Advisor > Advisors { get ; set ; } public OverviewProfile ( int id ) : base ( id ) { Advisors = new List < Advisor.View.Advisor > ( ) ; } }",-1 in the index of a list in C # "C_sharp : This is my first StackOverflow question so be nice ! : - ) I recently came across the following example in some C # source code : Which lead me to these questions : Is the use of `` # IF DEBUG '' unofficially deprecated ? If not what is considered to be a good implementation of its use ? Using a class factory and/or tools like MOQ , RhinoMocks , etc how could the above example be implemented ? public IFoo GetFooInstance ( ) { # IF DEBUG return new TestFoo ( ) ; # ELSE return new Foo ( ) ; # ENDIF }",Is ' # IF DEBUG ' deprecated in modern programming ? C_sharp : My bootstrapper inherits from UnityBootstrapper and I was attempting to unit test it and failed . I wanted to test that the correct modules get added in the ConfigureModuleCatalog method . Should I be trying to unit test this and if so how could I test it ? I 'm using .NET 4.5.1 and Prism 6 public class Bootstrapper : UnityBootstrapper { protected override DependencyObject CreateShell ( ) { return Container.Resolve < MainWindow > ( ) ; } protected override void InitializeShell ( ) { base.InitializeShell ( ) ; Application.Current.MainWindow = ( Window ) Shell ; Application.Current.MainWindow.Show ( ) ; } protected override void ConfigureModuleCatalog ( ) { ModuleCatalog moduleCatalog = ( ModuleCatalog ) ModuleCatalog ; moduleCatalog.AddModule ( typeof ( MainShellModule ) ) ; } },Should I be unit testing my bootstrapper and if so how ? "C_sharp : It seems ASP.NET implicitly interprets method named GetX and PostX as GET and POST methods respectively , because of their names are prefixed with HTTP method names . This is also the case for PUT and DELETE.I have a method unfortunately named Delete but I want it to be interpreted as a POST , so I explicitly specify it 's a POST using the [ HttpPost ] attribute . This works , as long as it 's not declared inside an interface ... How can I work around this , without having to specify the HttpPostAttribute for each implementation ? public interface IFooBarController { [ HttpPost ] void DoSomething ( ) ; [ HttpPost ] void Delete ( int id ) ; } public class FooBarController : IFooBarController { public void DoSomething ( ) { // This API method can only be called using POST , // as you would expect from the interface . } public void Delete ( int id ) { // This API method can only be called using DELETE , // even though the interface specifies [ HttpPost ] . } }",How to stop ASP.NET web API from implicitly interpretering the HTTP method ? "C_sharp : I 've a library that turns under CF.NET & .NET but serialization differs between both . As a result , a XML file generated under CF.NET is n't readable under .NET , and that is a big problem for me ! Here the code sample : CF.NET xml : .NET xmlHow can I modify my program in order to generate the same XML ? [ Serializable , XmlRoot ( `` config '' ) ] public sealed class RemoteHost : IEquatable < RemoteHost > { // ... } public class Program { public static void Main ( ) { RemoteHost host = new RemoteHost ( `` A '' ) ; List < RemoteHost > hosts = new List < RemoteHost > ( ) ; hosts.Add ( host ) ; XmlSerializer ser = new XmlSerializer ( typeof ( List < RemoteHost > ) ) ; ser.Serialize ( Console.Out , hosts ) ; } } < ? xml version= '' 1.0 '' ? > < ArrayOfConfig xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < config Name= '' A '' > < /config > < /ArrayOfConfig > < ? xml version= '' 1.0 '' encoding= '' ibm850 '' ? > < ArrayOfRemoteHost xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < RemoteHost Name= '' A '' > < /RemoteHost > < /ArrayOfRemoteHost >",XmlSerializer differs between .NET 3.5 & CF.NET 3.5 "C_sharp : I understand the use of the nameof ( ) operator for exception handling , logging , etc . But I do not understand the example below coming directly from some Microsoft code . How is that more useful than public static class SessionKeys { public static class Login { public static string AccessToken = nameof ( AccessToken ) ; public static string UserInfo = nameof ( UserInfo ) ; } } public static class SessionKeys { public static class Login { public static string AccessToken = `` AccessToken '' ; public static string UserInfo = `` UserInfo '' ; } }",nameof ( ) operator for static string "C_sharp : To check whether a string is empty I useAll the above statements produces the same output . What is the optimal method that I should use ? Again , both statements does the same thing . What is the best method to use ? I tried debugging and how to benchmark the performance of a C # statement ? var test = string.Empty ; if ( test.Length == 0 ) Console.WriteLine ( `` String is empty ! `` ) ; if ( ! ( test.Any ( ) ) ) Console.WriteLine ( `` String is empty ! `` ) ; if ( test.Count ( ) == 0 ) Console.WriteLine ( `` String is empty ! `` ) ; if ( String.IsNullOrWhiteSpace ( test ) ) Console.WriteLine ( `` String is empty ! `` ) ; var s = Convert.ToString ( test ) ; s = test.ToString ( CultureInfo.InvariantCulture ) ;",What is the most optimal method of checking if a string is empty ? C_sharp : If I have a type parameter constraint new ( ) : Is it true that new T ( ) will internally use the Activator.CreateInstance method ( i.e . reflection ) ? void Foo < T > ( ) where T : new ( ) { var t = new T ( ) ; },"Given `` where T : new ( ) '' , does `` new T ( ) '' use Activator.CreateInstance internally ?" "C_sharp : It seems that the static method Attribute.IsDefined is missing for UWP apps , I can navigate to the metadata for the Attribute class alright and the method is there , but the project wo n't compile stating that 'Attribute ' does not contain a definition for 'IsDefined ' - weird ( matter of fact , there are no static methods on that type at all according to IntelliSense ) .I was going to query for types with a certain attribute likeand am wondering if there is a workaround . var types = this.GetType ( ) .GetTypeInfo ( ) .Assembly.GetTypes ( ) .Where ( t = > Attribute.IsDefined ( t , typeof ( MyAttribute ) ) ) ;",Is there a replacement for Attribute.IsDefined in UWP apps ? "C_sharp : I have started using ConfigureAwait ( false ) with all the async sql objects.But my concern is , Will there be any implications with this approach ? .As this will run on a thread pool which is a separate thread from which it got originated i am not sure about the consequences if we dont run it on a single thread.Our application is wcf service which will process the 1000 's of records parallel.If some one helps to identity the business scenarios where it could be problem that would be helpful.Thanks connection.OpenAsync ( ) .ConfigureAwait ( false ) ; cmd.ExecuteNonQueryAsync ( ) .ConfigureAwait ( false ) ;",ConfigureAwait ( false ) with ADO.Net SQLConnection object "C_sharp : I am creating windows service which will connect to database using ODBC DSN , not using any username/password.Windows service is set as LocalService . ( And I tried changing it to Netwrok Service as well as LocalSystem ) I am using ODBC DSN as I will have different types of database ( Sqlite , Sql , MySQl etc . ) .At moment I am getting below error : Here is my code for connect odbc using dsn name ERROR [ 42000 ] [ Microsoft ] [ ODBC SQL Server Driver ] [ SQL Server ] Can not open database `` EmployeeDb '' requested by the login . The login failed.ERROR [ 42000 ] [ Microsoft ] [ ODBC SQL Server Driver ] [ SQL Server ] Can not open database `` EmployeeDb '' requested by the login . The login failed.StackTrace : at System.Data.Odbc.OdbcConnection.HandleError ( OdbcHandle hrHandle , RetCode retcode ) at System.Data.Odbc.OdbcConnectionHandle..ctor ( OdbcConnection connection , OdbcConnectionString constr , OdbcEnvironmentHandle environmentHandle ) at System.Data.Odbc.OdbcConnectionOpen..ctor ( OdbcConnection outerConnection , OdbcConnectionString connectionOptions ) at System.Data.Odbc.OdbcConnectionFactory.CreateConnection ( DbConnectionOptions options , DbConnectionPoolKey poolKey , Object poolGroupProviderInfo , DbConnectionPool pool , DbConnection owningObject ) at System.Data.ProviderBase.DbConnectionFactory.CreateConnection ( DbConnectionOptions options , DbConnectionPoolKey poolKey , Object poolGroupProviderInfo , DbConnectionPool pool , DbConnection owningConnection , DbConnectionOptions userOptions ) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection ( DbConnection owningConnection , DbConnectionPoolGroup poolGroup , DbConnectionOptions userOptions ) at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection ( DbConnection owningConnection , TaskCompletionSource ` 1 retry , DbConnectionOptions userOptions , DbConnectionInternal oldConnection , DbConnectionInternal & connection ) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal ( DbConnection outerConnection , DbConnectionFactory connectionFactory , TaskCompletionSource ` 1 retry , DbConnectionOptions userOptions ) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection ( DbConnection outerConnection , DbConnectionFactory connectionFactory , TaskCompletionSource ` 1 retry , DbConnectionOptions userOptions ) at System.Data.ProviderBase.DbConnectionInternal.OpenConnection ( DbConnection outerConnection , DbConnectionFactory connectionFactory ) at System.Data.Odbc.OdbcConnection.Open ( ) var conn = new OdbcConnection ( @ '' DSN=Employee '' ) ; conn.Open ( ) ; conn.Close ( ) ;",Can not open database from odbc connection ( using dsn ) using windows service ? "C_sharp : ReactiveUI has methods with signitures likeIn F # How would I construct an object likeIn C # I would do something likeEDITI 've triedandbut neither work public static ReactiveUI.ObservableAsPropertyHelper < TRet > ObservableToProperty < TObj , TRet > ( this TObj This , System.IObservable < TRet > observable , System.Linq.Expressions.Expression < System.Func < TObj , TRet > > property , TRet initialValue = null , System.Reactive.Concurrency.IScheduler scheduler = null ) System.Linq.Expressions.Expression < System.Func < TObj , TRet > > property , this.ObservableAsPropertyHelper ( observable , me = > me.MyProperty ) m.ObservableToProperty ( this , value , fun me - > me.Property ) m.ObservableToProperty ( this , value , new Linq.Expression.Expression ( fun me - > me.Property )",How to pass LinQ Expressions from F # to C # code "C_sharp : One day ago I started using Entity Framework CodeFirst in simple Windows Forms project ( C # ) . I created two models : Then I added one row into my database using Visual Studio Database Explorer ( local database using SqlServerCe 3.5 ) : SaveID = 1Player = `` TEST '' Age = 1Money = 1I also created form with ListView and wrote some code : But when I started program debugging ListView was empty . I set breakpoint , viewed local variables and saw that SavesSet count was 0.I added one row via code : And ListView displayed this one . But in my database there was nothing ( and its size did n't change ) . I restarted Visual Studio - and my trouble was still actual : ListView shows item , but database was empty . I checked ConnectionString in App.Config and in VS Database Explorer - they were equal.So , my question is : How can I explore my real database and where does it stores ? Update.My DbContext : And my App.Config : [ Table ( `` SavesSet '' ) ] public partial class Saves { public Saves ( ) { this.SkillsSet = new HashSet < Skills > ( ) ; } [ Key ] public int SaveID { get ; set ; } public string Player { get ; set ; } public int Age { get ; set ; } public int Money { get ; set ; } public virtual ICollection < Skills > SkillsSet { get ; set ; } } [ Table ( `` SkillsSet '' ) ] public partial class Skills { [ Key ] public int SkillID { get ; set ; } public string Name { get ; set ; } public int Value { get ; set ; } public int SavesSaveID { get ; set ; } public virtual Saves SavesSet { get ; set ; } } private SavesContext db = new SavesContext ( ) ; foreach ( Saves s in db.SavesSet.ToList ( ) ) { ListViewItem l = new ListViewItem ( ) ; l.Name = s.SaveID.ToString ( ) ; l.Text = s.Player ; ListViewSaves.Items.Add ( l ) ; } Saves s = new Saves ( ) ; s.Player = `` TestName '' ; s.Age = 5110 ; s.Money = 200 ; db.SavesSet.Add ( s ) ; db.SaveChanges ( ) ; public SavesContext ( ) : base ( `` Saves '' ) { } public DbSet < Saves > SavesSet { get ; set ; } public DbSet < Skills > SkillsSet { get ; set ; } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < configuration > < configSections > < /configSections > < connectionStrings > < add name= '' TextSim.Properties.Settings.Saves '' connectionString= '' Data Source=C : \Documents and Settings\My\My Documents\visual studio 2010\Projects\TextSim\TextSim\Saves.sdf '' providerName= '' System.Data.SqlServerCe.3.5 '' / > < /connectionStrings > < /configuration >",EntityFramework CodeFirst Database does n't update "C_sharp : Using reflector I get the following output : forWhat do the lines 11-14 do ? I call a function and get a result ( line 7 ) . I cast the result to the right returntype ( line c ) - why not return right now ? Somehow , the casted result is stored as a local variable - then there is an uncoditional jump to the next line , where the local variable is loaded again . Why ? In my opinion line 11-14 and the local variable can be omitted ... ? .method private hidebysig static class myModelTestarea.Foo Method ( ) cil managed { .maxstack 1 .locals init ( [ 0 ] class myModelTestarea.Foo CS $ 1 $ 0000 ) L_0000 : nop L_0001 : ldc.i4.0 L_0002 : newarr object L_0007 : call object myModelTestarea.Program : :Resolve ( object [ ] ) L_000c : castclass myModelTestarea.Foo L_0011 : stloc.0 L_0012 : br.s L_0014 L_0014 : ldloc.0 L_0015 : ret } private static Foo Method ( ) { return ( Foo ) Resolve ( ) ; } private static object Resolve ( params object [ ] args ) { return new Foo ( ) ; }",What are these opcodes for ? "C_sharp : If I have a web method that deletes a file when called and it accepts three parameters ( cNum , year , and fileName ) . Do I need to be worried about exploits of this method . The only thing I could think of would be using ..\..\..\ to drive the delete further up the folder structure . that should be pretty easy to remove that . But is there anything else that I should be worried about ? [ WebMethod ( EnableSession = true , Description = `` Method for deleting files uploaded by customers '' ) ] [ ScriptMethod ( ResponseFormat = ResponseFormat.Xml ) ] public Boolean deleteCustFiles ( string cNum , string year , string fileName ) { try { if ( String.IsNullOrEmpty ( cNum ) || String.IsNullOrEmpty ( year ) || String.IsNullOrEmpty ( fileName ) ) throw new Exception ( ) ; string path = Server.MapPath ( @ '' ~\docs\custFiles\ '' + year + @ '' \ '' + cNum + @ '' \ '' + fileName ) ; File.Delete ( path ) ; } catch { throw new Exception ( `` Unable to delete file '' ) ; } return true ; }",Checking File Path When Deleting A File "C_sharp : I 'm trying to follow the answer provided in this post , but I must be missing something trivial . I 've defined my DataTemplates as App.xaml as follows : Then , in my MainWindow.xaml I 've defined the following code : The code for MainViewModel contains a property CurrentView and an ICommand so I can switch views . Defined as follows : In my HomeView.xaml , I have defined a button that links to the MainViewModel to execute the SwitchView ICommand . This is shown below.When I start the application it does n't register the event , and clicking on the button does not fire the event to change the view . I 've tried putting breakpoints in both the ICommand get and the function call itself . At first , I thought maybe I needed to define MainViewModel in my data templates , but doing so results in the following error ( even though the project builds fine ) Ca n't put a Window in a styleCan anyone provide the missing piece I need to get this working ? < Application.Resources > < DataTemplate DataType= '' { x : Type vm : BlowerViewModel } '' > < v : BlowerView / > < /DataTemplate > < DataTemplate DataType= '' { x : Type vm : HomeViewModel } '' > < v : HomeView / > < /DataTemplate > < /Application.Resources > < Window x : Class= '' App.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : vm= '' clr-namespace : App.UI.ViewModel '' Title= '' MainWindow '' SizeToContent= '' WidthAndHeight '' > < Window.DataContext > < vm : MainViewModel / > < /Window.DataContext > < ContentControl Content= '' { Binding CurrentView } '' / > < /Window > public class MainViewModel : BaseViewModel { private BaseViewModel _currentView ; public MainViewModel ( ) { CurrentView = new HomeViewModel ( ) ; } public BaseViewModel CurrentView { get { return _currentView ; } set { if ( _currentView ! = value ) { _currentView = value ; RaiseChangedEvent ( `` CurrentView '' ) ; } } } public ICommand SwitchView { get { return new CommandHandler ( ( ) = > SwitchBlower ( ) ) ; } } protected void SwitchBlower ( ) { CurrentView = new BlowerViewModel ( ) ; } } < UserControl x : Class= '' App.UI.View.HomeView '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : vm= '' clr-namespace : App.UI.ViewModel '' Height= '' 300 '' Width= '' 300 '' > < Grid > < TextBlock > This is the homeview < /TextBlock > < Button Command= '' { Binding DataContext.SwitchView , RelativeSource= { RelativeSource AncestorType= { x : Type vm : MainViewModel } } , Mode=OneWay } '' Content= '' Test '' / > < /Grid > < /UserControl >",WPF Navigation using MVVM "C_sharp : If I have two collections of type T , and an IEqualityComparer that compares a subset of their properties , which collection would the resulting elements of an Intersect or Union come from ? The tests I 've run so far suggest the following : the item ( s ) from col1 winif col1 or col2 contain duplicate items ( as defined by the comparer ) within themselves , the first entry ( within col1 , then col2 ) wins.I 'm aware this should n't be an issue , as ( by definition ) I should be viewing the resulting objects as equal . It just occurred to me that using Union with a custom comparer could be a bit neater than the equivalent Join - though this only holds true if the above assumptions are guaranteeed . class DummyComparer : IEqualityComparer < Dummy > { public bool Equals ( Dummy x , Dummy y ) { return x.ID == y.ID ; } public int GetHashCode ( Dummy obj ) { return obj.ID.GetHashCode ( ) ; } } class Dummy { public int ID { get ; set ; } public string Name { get ; set ; } } [ Test ] public void UnionTest ( ) { var comparer = new DummyComparer ( ) ; var d1 = new Dummy { ID = 0 , Name = `` test0 '' } ; var d2 = new Dummy { ID = 0 , Name = `` test1 '' } ; var d3 = new Dummy { ID = 1 , Name = `` test2 '' } ; var d4 = new Dummy { ID = 1 , Name = `` test3 '' } ; var col1 = new Dummy [ ] { d1 , d3 } ; var col2 = new Dummy [ ] { d2 , d4 } ; var x1 = col1.Union ( col2 , comparer ) .ToList ( ) ; var x2 = col2.Union ( col1 , comparer ) .ToList ( ) ; var y1 = col1.Except ( col2 , comparer ) .ToList ( ) ; var y2 = col2.Except ( col1 , comparer ) .ToList ( ) ; var z1 = col1.Intersect ( col2 , comparer ) .ToList ( ) ; var z2 = col2.Intersect ( col1 , comparer ) .ToList ( ) ; Assert.AreEqual ( 2 , x1.Count ) ; Assert.Contains ( d1 , x1 ) ; Assert.Contains ( d3 , x1 ) ; Assert.AreEqual ( 2 , x2.Count ) ; Assert.Contains ( d2 , x2 ) ; Assert.Contains ( d4 , x2 ) ; Assert.AreEqual ( 0 , y1.Count ) ; Assert.AreEqual ( 0 , y2.Count ) ; Assert.AreEqual ( 2 , z1.Count ) ; Assert.Contains ( d1 , z1 ) ; Assert.Contains ( d3 , z1 ) ; Assert.AreEqual ( 2 , z2.Count ) ; Assert.Contains ( d2 , z2 ) ; Assert.Contains ( d4 , z2 ) ; }","Collection priority in LINQ Intersect , Union , using IEqualityComparer" "C_sharp : I am playing around with Scala.And I found 3 interesting things ( the title is the third one ) .1 a local variable declared as val is not interpreted as final.if i compile the above scala code into bytecode and then decompile that into java , it looks like this : we can see v2 is final , but v4 is not , why ? 2 scala compiler for .net adds override keyword to a lot of ( if not all ) public instance methodsif we compile the scala code shown above into CIL and then decompile it into C # , it 's like this : all public instance methods ( exclude the constructor ) are marked as override , why ? is that necessary ? 3 Scala compiler for .net looses the meaning of valin the above c # code , we can see that v2 is just a normal field , while in the java couter part , v2 is marked as final , should n't v2 be marked as readonly by the Scala compiler for .net ? ( a bug ? ) class HowAreVarAndValImplementedInScala { var v1 = 123 val v2 = 456 def method1 ( ) = { var v3 = 123 val v4 = 456 println ( v3 + v4 ) } } public class HowAreVarAndValImplementedInScala { private int v1 = 123 ; private final int v2 = 456 ; public int v1 ( ) { return this.v1 ; } public void v1_ $ eq ( int x $ 1 ) { this.v1 = x $ 1 ; } public int v2 ( ) { return this.v2 ; } public void method1 ( ) { int v3 = 123 ; int v4 = 456 ; Predef..MODULE $ .println ( BoxesRunTime.boxToInteger ( v3 + v4 ) ) ; } } public class HowAreVarAndValImplementedInScala : ScalaObject { private int v1 ; private int v2 ; public override int v1 ( ) { return this.v1 ; } public override void v1_ $ eq ( int x $ 1 ) { this.v1 = x $ 1 ; } public override int v2 ( ) { return this.v2 ; } public override void method1 ( ) { int v3 = 123 ; int v4 = 456 ; Predef $ .MODULE $ .println ( v3 + v4 ) ; } public HowAreVarAndValImplementedInScala ( ) { this.v1 = 123 ; this.v2 = 456 ; } }",Why does Scala compiler for .NET ignore the meaning of val ? "C_sharp : Here 's something very weird I had noticed.I 'm writing a CRM 2011 Silverlight extension and , well , all is fine on my local development instance . The application uses OData to communicate , and uses System.Threading.Tasks.Task a lot to perform all the operations in the background ( FromAsync is a blessing ) .However , I decided to test my application in CRM 2011 Online and found , to my surprise , that it would no longer work ; I would receive a Security Exception when ending retrieve tasks.Using Fiddler , I found that CRM is trying to redirect me to the Live login page , which did n't make much sense , considering I was already logged in.After some more attempts , I found that the errors were because I was accessing the service from a different thread than the UI thread.Here 's a quick example : It seems almost obvious that I 'm missing some fundamentals on how threads use permissions . Since using a separate thread is preferable in my case , is there any way to `` copy '' the permissions / authentication ? Perhaps some sort of impersonation ? EDIT : In case anyone else is struggling with this , using other threads ( or Task , as the case may be ) is possible as long as query.BeginExecute ( null , null ) ; is executed on the UI thread . You need a way to retrieve the returned IAsyncResult back to the calling thread , but you can do that using a ManualResetEvent.But I 'd still like to know why the darned permissions / authentication is n't shared between the threads ... //this will work private void button1_Click ( object sender , RoutedEventArgs e ) { var query = ctx.AccountSet ; query.BeginExecute ( ( result ) = > { textBox1.Text = query.EndExecute ( result ) .First ( ) .Name ; } , null ) ; } //this will fail private void button2_Click ( object sender , RoutedEventArgs e ) { System.Threading.Tasks.Task.Factory.StartNew ( RestAsync ) ; } void RestAsync ( ) { var query = ctx.AccountSet ; var async = query.BeginExecute ( null , null ) ; var task = System.Threading.Tasks.Task.Factory.FromAsync < Account > ( async , ( result ) = > { return query.EndExecute ( result ) .First ( ) ; // < - Exception thrown here } ) ; textBox1.Dispatcher.BeginInvoke ( ( ) = > { textBox1.Text = task.Result.Name ; } ) ; }",Copy permissions / authentication to child threads ... ? "C_sharp : Taking the following code , Resharper tells me that voicesSoFar and voicesNeededMaximum cause `` access to a modified closure '' . I read about these but what puzzles me here is that Resharper suggests fixing this by extracting the variables to right before the LINQ query . But that is where they are already ! Resharper stops complaining if I merely add int voicesSoFar1 = voicesSoFar right after int voicesSoFar = 0 . Is there some weird logic I do not understand that makes Resharper 's suggestion correct ? Or is there a way to safely `` access modified closures '' in cases like these without causing bugs ? // this takes voters while we have less than 300 voices int voicesSoFar = 0 ; int voicesNeededMaximum = 300 ; var eligibleVoters = voters.TakeWhile ( ( p = > ( voicesSoFar += p.Voices ) < voicesNeededMaximum ) ) ;",Does this code really cause an `` access to modified closure '' problem ? "C_sharp : How can I convert this text file content into a recursive collection of objects that I can bind to a TreeView ? i.e . I want to end up with a collection of 3 objects , the first one called countries which has a collection of three child objects : france , germany , italy , and so on ... ANSWER : thanks to all who helped out on this , here 's my code that successfully parses this text outline into a XAML tree : http : //tanguay.info/web/index.php ? pg=codeExamples & id=358The code below is as far as I got it , but it is not dealing with multiple children of parents correctly . countries-france -- paris -- bordeaux-germany-italysubjects-math -- algebra -- calculus-science -- chemistry -- biologyother-this-that using System ; using System.Collections.Generic ; using System.Text ; namespace TestRecursive2342 { class Program { static void Main ( string [ ] args ) { List < OutlineObject > outlineObjects = new List < OutlineObject > ( ) ; //convert file contents to object collection List < string > lines = Helpers.GetFileAsLines ( ) ; Stack < OutlineObject > stack = new Stack < OutlineObject > ( ) ; foreach ( var line in lines ) { OutlineObject oo = new OutlineObject ( line ) ; if ( stack.Count > 0 ) { OutlineObject topObject = stack.Peek ( ) ; if ( topObject.Indent < oo.Indent ) { topObject.OutlineObjects.Add ( oo ) ; stack.Push ( oo ) ; } else { stack.Pop ( ) ; stack.Push ( oo ) ; } } else { stack.Push ( oo ) ; } if ( oo.Indent == 0 ) outlineObjects.Add ( oo ) ; } outlineObjects.ForEach ( oo = > Console.WriteLine ( oo.Line ) ) ; Console.ReadLine ( ) ; } } public class OutlineObject { public List < OutlineObject > OutlineObjects { get ; set ; } public string Line { get ; set ; } public int Indent { get ; set ; } public OutlineObject ( string rawLine ) { OutlineObjects = new List < OutlineObject > ( ) ; Indent = rawLine.CountPrecedingDashes ( ) ; Line = rawLine.Trim ( new char [ ] { '- ' , ' ' , '\t ' } ) ; } } public static class Helpers { public static List < string > GetFileAsLines ( ) { return new List < string > { `` countries '' , `` -france '' , `` -- paris '' , `` -- bordeaux '' , `` -germany '' , `` -italy '' , `` subjects '' , `` -math '' , `` -- algebra '' , `` -- calculus '' , `` -science '' , `` -- chemistry '' , `` -- biology '' , `` other '' , `` -this '' , `` -that '' } ; } public static int CountPrecedingDashes ( this string line ) { int tabs = 0 ; StringBuilder sb = new StringBuilder ( ) ; foreach ( var c in line ) { if ( c == '- ' ) tabs++ ; else break ; } return tabs ; } } }",How can I convert a text-file outline list into a recursive collection of objects ? "C_sharp : I have a console application which should paint a random picture in MSPaint ( mouse down - > let the cursor randomly paint something - > mouse up . This is what I have so far ( I added comments to the Main method for better understanding what I want to achieve ) : I got this code for the click simulation from here.The click gets simulated but it does n't paint anything . It seems that the click does n't work inside MSPaint . The cursor changes to the `` cross '' of MSPaint but as I mentioned ... the click does n't seem to work.FindWindow sets the value of hwndMain to value 0 . Changing the parameter mspaint to MSPaintApp does n't change anything . The value of hwndMain stays 0.If it helps , here is my OpenPaint ( ) method : What am I doing wrong ? [ DllImport ( `` user32.dll '' , CallingConvention = CallingConvention.StdCall ) ] public static extern void mouse_event ( long dwFlags , uint dx , uint dy , long cButtons , long dwExtraInfo ) ; private const int MOUSEEVENTF_LEFTDOWN = 0x201 ; private const int MOUSEEVENTF_LEFTUP = 0x202 ; private const uint MK_LBUTTON = 0x0001 ; public delegate bool EnumWindowsProc ( IntPtr hWnd , IntPtr parameter ) ; [ DllImport ( `` user32.dll '' , SetLastError = true ) ] static extern IntPtr FindWindow ( string lpClassName , string lpWindowName ) ; [ DllImport ( `` user32.dll '' , SetLastError = true ) ] public static extern IntPtr FindWindowEx ( IntPtr parentHandle , IntPtr childAfter , string className , string windowTitle ) ; [ DllImport ( `` user32.dll '' , CharSet = CharSet.Auto ) ] static extern IntPtr SendMessage ( IntPtr hWnd , UInt32 Msg , IntPtr wParam , IntPtr lParam ) ; [ DllImport ( `` user32.dll '' , SetLastError = true ) ] public static extern bool EnumChildWindows ( IntPtr hwndParent , EnumWindowsProc lpEnumFunc , IntPtr lParam ) ; static IntPtr childWindow ; private static bool EnumWindow ( IntPtr handle , IntPtr pointer ) { childWindow = handle ; return false ; } public static void Main ( string [ ] args ) { OpenPaint ( ) ; // Method that opens MSPaint IntPtr hwndMain = FindWindow ( `` mspaint '' , null ) ; IntPtr hwndView = FindWindowEx ( hwndMain , IntPtr.Zero , `` MSPaintView '' , null ) ; // Getting the child windows of MSPaintView because it seems that the class name of the child is n't constant EnumChildWindows ( hwndView , new EnumWindowsProc ( EnumWindow ) , IntPtr.Zero ) ; Random random = new Random ( ) ; Thread.Sleep ( 500 ) ; // Simulate a left click without releasing it SendMessage ( childWindow , MOUSEEVENTF_LEFTDOWN , new IntPtr ( MK_LBUTTON ) , CreateLParam ( random.Next ( 10 , 930 ) , random.Next ( 150 , 880 ) ) ) ; for ( int counter = 0 ; counter < 50 ; counter++ ) { // Change the cursor position to a random point in the paint area Cursor.Position = new Point ( random.Next ( 10 , 930 ) , random.Next ( 150 , 880 ) ) ; Thread.Sleep ( 100 ) ; } // Release the left click SendMessage ( childWindow , MOUSEEVENTF_LEFTUP , new IntPtr ( MK_LBUTTON ) , CreateLParam ( random.Next ( 10 , 930 ) , random.Next ( 150 , 880 ) ) ) ; } private static void OpenPaint ( ) { Process.process = new Process ( ) ; process.StartInfo.FileName = `` mspaint.exe '' ; process.StartInfo.WindowStyle = `` ProcessWindowStyle.Maximized ; process.Start ( ) ; }",Simulate mouse click in MSPaint "C_sharp : I heavily suspect my problem is due to some security issue but here 's the full description just in case I 'm mistaken.I have a DLL that was originally written in C ( not C++ ) . I 'm using DllImport to call the methods in this library . A declaration looks something like this : The C declaration in the header file looks like this : So I created a sample page in my WebApplication project in visual studio whose code-behind looks like this : When I debug the program and step past the GetConnectionString ( ) method call I get an : I see the same issue with any calls I make to the interop DLL from a web service or webpage in my WebApplication project . The same sequence of calls works fine in a ConsoleApplication I wrote when testing this.The same code works fine when called from a WindowsConsole app . The example is simplified a bit from the actual usage , but the results are the same . In the real solution I have a project that is just in charge of managing the interactions with the C-API and that is what my webservice is calling , but I 've run the example above and get the behavior I 've explained . [ DllImport ( @ '' MyAntiquatedLibrary.dll '' ) [ SecurityPermission ( SecurityAction.Assert , Unrestricted = true ) ] internal static extern void GetConnectionString ( string port , string server , string instance , [ Out ] StringBuilder output ) ; void GetConnectionString ( const char far *Portname , const char far *ServerName const char far *InstanceName , char far *retConnectionName ) ; protected void Page_Load ( object sender , EventArgs e ) { try { var connectionString = new StringBuilder ( ) ; GetConnectionString ( null , `` myHost '' , `` myInstance '' , connectionString ) ; MyLabel.Text = connectionString.ToString ( ) ; } catch ( Exception ex ) { MyLabel.Text = string.Format ( `` Something went wrong : { 0 } '' , ex.Message ) ; } } AccessViolationException was unhandled.Attempted to read or write protected memory . This is often an indication that other memory is corrupt .",ASP.NET DllImport Causes App to Quit C_sharp : This is not to solve any particular problem . Simply a compiler question . Why does the following code not result in compile error ? It 's comparing a reference type to primitive type . Both null and false have to to be interpreted into something for the compiler to do comparison . Or is the parser simply scanning for such pattern and replace it with false ? if ( null == false ) { },Why null == false does not result in compile error in c # ? "C_sharp : I am trying to create TypeConverter which will convert my custom type to ICommand if I am binding it to Button Command.Unfortunetly WPF is not calling my converter.Converter : Xaml : Converter will be invoked if I will bind to content like : Any ideas how I can get TypeConverter to work ? public class CustomConverter : TypeConverter { public override bool CanConvertTo ( ITypeDescriptorContext context , Type destinationType ) { if ( destinationType == typeof ( ICommand ) ) { return true ; } return base.CanConvertTo ( context , destinationType ) ; } public override object ConvertTo ( ITypeDescriptorContext context , CultureInfo culture , object value , Type destinationType ) { if ( destinationType == typeof ( ICommand ) ) { return new DelegateCommand < object > ( x = > { } ) ; } return base.ConvertTo ( context , culture , value , destinationType ) ; } } < Button Content= '' Execute '' Command= '' { Binding CustomObject } '' / > < Button Content= '' { Binding CustomObject } '' / >",WPF not calling TypeConverter when DependencyProperty is interface "C_sharp : I want to do a method with a signature like this : Basically , it takes a property selector ( ex : p = p.Name ) , a string value and a enum value that can be StartsWith , EndsWith , Contains , Exact ; for text matching options.How can I implement the method in a way that LINQ2Entities can understand ? I already implemented the method using nested invocation expressions like this : The problem is that Linq2Entities does n't support Invocation expressions.Any advice on this ? Thanks ! Expression < Func < TSource , bool > > CreatePropertyFilter < TSource > ( Expression < Func < TSource , string > > selector , string value , TextMatchMode matchMode ) ; Expression < Func < string , bool > > comparerExpression ; switch ( matchMode ) { case TextMatchMode.StartsWith : comparerExpression = p = > p.StartsWith ( value ) ; break ; case TextMatchMode.EndsWith : comparerExpression = p = > p.EndsWith ( value ) ; break ; case TextMatchMode.Contains : comparerExpression = p = > p.Contains ( value ) ; break ; default : comparerExpression = p = > p.Equals ( value ) ; break ; } var equalityComparerParameter = Expression.Parameter ( typeof ( IncomingMail ) , null ) ; var equalityComparerExpression = Expression.Invoke ( comparerExpression , Expression.Invoke ( selector , equalityComparerParameter ) ) ; var equalityComparerPredicate = Expression.Lambda < Func < IncomingMail , bool > > ( equalityComparerExpression , equalityComparerParameter ) ;",Parameterized Linq Expression Help "C_sharp : In the below adapter design pattern sample code , why a new class is introduced instead of using multiple interface in the client ? I have the below queries related to the above code.What , if ShoppingPortalClient directly inherits VendorAdaptee ? In which scenario we need adapter class ? why instead of simple inheritance a needed class , creating this pattern to access another class method ? interface ITarget { List < string > GetProducts ( ) ; } public class VendorAdaptee { public List < string > GetListOfProducts ( ) { List < string > products = new List < string > ( ) ; products.Add ( `` Gaming Consoles '' ) ; products.Add ( `` Television '' ) ; products.Add ( `` Books '' ) ; products.Add ( `` Musical Instruments '' ) ; return products ; } } class VendorAdapter : ITarget { public List < string > GetProducts ( ) { VendorAdaptee adaptee = new VendorAdaptee ( ) ; return adaptee.GetListOfProducts ( ) ; } } class ShoppingPortalClient { static void Main ( string [ ] args ) { ITarget adapter = new VendorAdapter ( ) ; foreach ( string product in adapter.GetProducts ( ) ) { Console.WriteLine ( product ) ; } Console.ReadLine ( ) ; } }",what is the need of Adapter Design pattern ? "C_sharp : Here is some class : And I 'm trying to instanciate object of this class by doing this : And all I get is a System.MissingMethodException ( there is no no-arg constructor for this object ) ... What is wrong with my code ? public class MyClass < T , C > : IMyClass where T : SomeTClass where C : SomeCClass { private T t ; private C c ; public MyClass ( ) { this.t= Activator.CreateInstance < T > ( ) ; this.c= Activator.CreateInstance < C > ( ) ; } } Type type = typeof ( MyClass < , > ) .MakeGenericType ( typeOfSomeTClass , typeOfSomeCClass ) ; object instance = Activator.CreateInstance ( type ) ;","Class < T , C > and Activator.CreateInstance" "C_sharp : I have two custom classes Grid , and Element : Element : To illustrate the situation please see this picture : There is a container for that classes called Data : I read text files in which there are a lot of data : Grids and ElementsThis is the format for grids ( simplified ) : GRID ID X Y ZAnd for the element ELEMENT ID GRID1 GRID2 GRID3 GRID4So , the GRID entry provides the position and ID of a grid point and ELEMENT provides the ID of grids of that element and it 's own ID.What I want is to associate for each element all 4 grids , this way I will have the coordinates of each grid inside of the element object.For that I read the file two times ( because the element entry comes before grid and to simplify things ) : the first time I read it I fill the Grids list ( from the Data class ) .The second time I fill the Elements list and do more stuff . When I fill the Elements list I can only fill the ID of the associated Grid.If you 've read till here we have this class Data that contains two lists of Grid and Elements.For the association I 've come up with this method : It loops through each element and then through each grid of that element ( 4 in this case ) , then it looks in the whole list of grids what grid has the same ID . When it founds the first , it assigns that grid , this way the element have the `` complete '' Grid object , not the one with only ID filled ( because that it 's the only thing I can get when I read the file ) .Here comes the problem : these files are pretty big : around 20 000 grid points and 10 000 elements , if I loop for each element looking each time the whole collection of grids ( 4 times ) it is : 20 000 x 10 000 = 200 000 000 operations . So the computer ca n't handle it , and I think it must be improved.Could anyone give a hint or help me to optimize this problem ? Thank you . public class Grid { public double ID { get ; set ; } public double X { get ; set ; } public double Y { get ; set ; } public double Z { get ; set ; } public MyClass MoreProperties { get ; set ; } public Grid ( int id , double x , double y , double z ) { this.ID = id ; this.X = x ; this.Y = y ; this.Z = z ; } } public abstract class Element { public int ID { get ; set ; } public int NumberOfGrids { get ; set ; } public List < Grid > Grids { get ; set ; } //4 Grids in this case public Element ( ) { Grids = new List < Grid > ( ) ; } } class Data : ModelBase { public List < Grid > Grids { get ; set ; } public List < Element > Elements { get ; set ; } } public void AsociateGridsToElements ( ) { foreach ( Element elem in Elements ) { for ( int i = 0 ; i < elem.Grids.Count ; i++ ) { elem.Grids [ i ] = Grids.Where ( g = > g.ID == elem.Grids [ i ] .ID ) .FirstOrDefault ( ) ; } } }",Linq in large lists "C_sharp : Taken from article on async await by Stephen Cleary : Figure 2 Exceptions from an Async Void Method Can ’ t Be Caught with Catch ... any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started ... What does that actually mean ? I wrote an extended example to try and glean more info . It has the same behaviour as Figure 2 : Debug output : I want more detailsIf there is no current synchronization context ( as in my example ) , where is the exception raised ? What are the differences between async void ( with no await ) and voidThe compiler warns CS1998 C # This async method lacks 'await ' operators and will run synchronously.If it runs synchronously with no await , why is it behaving differently from simply void ? Does async Task with no await also behave differently from Task ? What are the differences in compiler behaviour between async void and async Task . Is a Task object really created under-the-hood for async void as suggested here ? Edit . To be clear , this is n't a question about best practices - it is a question about compiler / runtime implementation . private async void ThrowExceptionAsync ( ) { throw new InvalidOperationException ( ) ; } public void AsyncVoidExceptions_CannotBeCaughtByCatch ( ) { try { ThrowExceptionAsync ( ) ; } catch ( Exception ) { // The exception is never caught here ! throw ; } } static void Main ( ) { AppDomain.CurrentDomain.UnhandledException += ( sender , ex ) = > { LogCurrentSynchronizationContext ( `` AppDomain.CurrentDomain.UnhandledException '' ) ; LogException ( `` AppDomain.CurrentDomain.UnhandledException '' , ex.ExceptionObject as Exception ) ; } ; try { try { void ThrowExceptionVoid ( ) = > throw new Exception ( `` ThrowExceptionVoid '' ) ; ThrowExceptionVoid ( ) ; } catch ( Exception ex ) { LogException ( `` AsyncMain - Catch - ThrowExceptionVoid '' , ex ) ; } try { // CS1998 C # This async method lacks 'await ' operators and will run synchronously . async void ThrowExceptionAsyncVoid ( ) = > throw new Exception ( `` ThrowExceptionAsyncVoid '' ) ; ThrowExceptionAsyncVoid ( ) ; } // exception can not be caught , despite the code running synchronously . catch ( Exception ex ) { LogException ( `` AsyncMain - Catch - ThrowExceptionAsyncVoid '' , ex ) ; } } catch ( Exception ex ) { LogException ( `` Main '' , ex ) ; } Console.ReadKey ( ) ; } private static void LogCurrentSynchronizationContext ( string prefix ) = > Debug.WriteLine ( $ '' { prefix } - `` + $ '' CurrentSynchronizationContext : { SynchronizationContext.Current ? .GetType ( ) .Name } `` + $ '' - { SynchronizationContext.Current ? .GetHashCode ( ) } '' ) ; private static void LogException ( string prefix , Exception ex ) = > Debug.WriteLine ( $ '' { prefix } - Exception - { ex.Message } '' ) ; Exception thrown : 'System.Exception ' in ConsoleApp3.dllAsyncMain - Catch - ThrowExceptionVoid - Exception - ThrowExceptionVoidException thrown : 'System.Exception ' in ConsoleApp3.dllAn exception of type 'System.Exception ' occurred in ConsoleApp3.dll but was not handled in user codeThrowExceptionAsyncVoidAppDomain.CurrentDomain.UnhandledException - CurrentSynchronizationContext : - AppDomain.CurrentDomain.UnhandledException - Exception - ThrowExceptionAsyncVoidThe thread 0x1c70 has exited with code 0 ( 0x0 ) .An unhandled exception of type 'System.Exception ' occurred in System.Private.CoreLib.ni.dllThrowExceptionAsyncVoidThe program ' [ 18584 ] dotnet.exe ' has exited with code 0 ( 0x0 ) .",What are the differences between ` async void ` ( with no await ) vs ` void ` "C_sharp : Almost every SO 's answer regarding this topic , states that : LINQ does n't work perfectly with async Also : I recommend that you not think of this as `` using async within LINQ '' But in Stephen 's book there is a sample for : Problem : You have a collection of tasks to await , and you want to do some processing on each task after it completes . However , you want to do the processing for each one as soon as it completes , not waiting for any of the other tasks.One of the recommended solutions was : Question # 1 : I do n't understand why now async inside a LINQ statement - does work . Did n't we just say `` do n't think about using async within LINQ '' ? Question # 2 : When the control reaches the await t here — What is actually happen ? Does the control leaves the ProcessTasksAsync method ? or does it leaves the anonymous method and continue the iteration ? static async Task < int > DelayAndReturnAsync ( int val ) { await Task.Delay ( TimeSpan.FromSeconds ( val ) ) ; return val ; } // This method now prints `` 1 '' , `` 2 '' , and `` 3 '' .static async Task ProcessTasksAsync ( ) { // Create a sequence of tasks . Task < int > taskA = DelayAndReturnAsync ( 2 ) ; Task < int > taskB = DelayAndReturnAsync ( 3 ) ; Task < int > taskC = DelayAndReturnAsync ( 1 ) ; var tasks = new [ ] { taskA , taskB , taskC } ; var processingTasks = tasks.Select ( async t = > { var result = await t ; Trace.WriteLine ( result ) ; } ) .ToArray ( ) ; // Await all processing to completeawait Task.WhenAll ( processingTasks ) ; }",async within a LINQ code - Clarification ? "C_sharp : I have the following code in an unit testwhich I call byI want to ensure that all the methods from the interface are declared as virtual . The reason is because I 'm applying a spring.net aspect and it will only apply to virtual methods.The problem I 'm having is that implMember.IsVirtual is always true , even when they are not declared as so in the declaring type . What is wrong with my TestMethodsOf logic ? Cheers public bool TestMethodsOf < T , I > ( ) { var impl = typeof ( T ) ; var valid = true ; foreach ( var iface in impl.GetInterfaces ( ) .Where ( i = > typeof ( I ) .IsAssignableFrom ( i ) ) ) { var members = iface.GetMethods ( ) ; foreach ( var member in members ) { Trace.Write ( `` Checking if method `` + iface.Name + `` . '' + member.Name + `` is virtual ... '' ) ; var implMember = impl.GetMethod ( member.Name , member.GetParameters ( ) .Select ( c = > c.ParameterType ) .ToArray ( ) ) ; if ( ! implMember.IsVirtual ) { Trace.WriteLine ( string.Format ( `` FAILED '' ) ) ; valid = false ; continue ; } Trace.WriteLine ( string.Format ( `` OK '' ) ) ; } } return valid ; } Assert.IsTrue ( TestMethodsOf < MyView , IMyView > ( ) ) ;","Reflection says that interface method are virtual in the implemented type , when they are n't ?" "C_sharp : Consider the following Win32 API struct : When porting this object to C # , should I follow the name naming conventions used here , like so : or can I go all out , and write my struct in a C # style , like so : Whilst the second approach seems much more elegant , I would like to know if it is advisable to invoke native functionality using a struct written in that fashion , or if there are any other pitfalls when porting structs from C/C++ . typedef struct _SECURITY_ATTRIBUTES { DWORD nLength ; LPVOID lpSecurityDescriptor ; BOOL bInheritHandle ; } SECURITY_ATTRIBUTES , *PSECURITY_ATTRIBUTES , *LPSECURITY_ATTRIBUTES ; public struct _SECURITY_ATTRIBUTES { public int nLength ; public unsafe byte* lpSecurityDescriptor ; public int bInheritHandle ; } public struct SecurityAttributes { private int length ; private unsafe byte* securityDescriptor ; private int bInheritHandle ; public Int32 Length { get { return this.length ; } set { this.length = value ; } } public Byte* SecurityDescriptor { get { return this.seurityDescriptor ; } set { this.securityDescriptor = value ; } } public Int32 InheritHandle { get { return this.bInheritHandle ; } set { this.bInheritHandle = value ; } } public SecurityAttributes ( int length , byte* securityDescriptor , int inheritHandle ) { this.length = length ; this.securityDescriptor = securityDescriptor ; this.inheritHandle = inheritHandle ; } }",C/C++ Interoperability Naming Conventions with C # "C_sharp : I need to generate test cases ( using IEnumerable < TestCaseData > ) from JSON objects that have values set . I could n't find any tools online that would generate C # classes that have values set ( Plenty that generate classes ) . Deserializing Json in test cases would invalidate test ( One should only be testing the code ) , so I did this regex.It 's not perfect but worked just fine with most basic well formatted JSON when all properties are of same type ( decimals or bools ) , pattern : `` ( [ a-zA-Z ] ? [ a-zA-Z0-9 ] . * ) '' ? : ? ( ( true|false|null ) | ( [ \d ] . * ) ) , replace $ 1 = $ 2M however when there are many types and they are mixed I get screwed . I am sure someone ran into this before me and I am reinventing wheel so in a nutshell.How do I make this : to become this : What fastest/most convenient solution is to generate C # classes that have properties set from JSON objects ? { `` LegalFeeNet '' : 363.54 , `` LegalFeeVat '' : 72.708 , `` DiscountNet '' : 0.0 , `` DiscountVat '' : 0.0 , `` OtherNet '' : 12.0 , `` OtherVat '' : 2.4 , `` DisbursementNet '' : 220.0 , `` DisbursementVat '' : 0.0 , `` AmlCheck '' : null , `` LegalSubTotal '' : 363.54 , `` TotalFee '' : 450.648 , `` Discounts '' : 0.0 , `` Vat '' : 75.108 , `` DiscountedPrice '' : 360.5184 , `` RecommendedRetailPrice '' : 450.648 , `` SubTotal '' : 375.54 , `` Name '' : `` Will '' , `` IsDiscounted '' : false , `` CustomerCount '' : 3 } ClassName { LegalFeeNet = 363.54M , LegalFeeVat = 72.708M , DiscountNet = 0.0M , DiscountVat = 0.0M , OtherNet = 12.0M , OtherVat = 2.4M , DisbursementNet = 220.0M , DisbursementVat = 0.0M , AmlCheck = nullM , LegalSubTotal = 363.54M , TotalFee = 450.648M , Discounts = 0.0M , Vat = 75.108M , DiscountedPrice = 360.5184M , RecommendedRetailPrice = 450.648M , SubTotal = 375.54M , Name = `` Will '' , IsDiscounted = false , CustomerCount = 3 }",Convert JSON to C # inline class with values set C_sharp : According to best practices it is recommended to use .ConfigureAwait ( false ) with async/await keywords if you can : Can you please give me an example of a situation when I can not use .ConfigureAwait ( false ) ? await Task.Run ( RunSomethingAsync ) .ConfigureAwait ( false ) ;,When I can not use ConfigureAwait ( false ) ? "C_sharp : I have a class with several int properties : I have a LINQ expression I wish to use on a List < Foo > . I want to be able to use this expression to filter/select from the list by looking at any of the three properties . For example , if I were filtering by a : However , I want to be able to do that with any of f.a , f.b , or f.c . Rather than re-type the LINQ expression 3 times , I 'd like to have some method which would take an argument to specify which of a , b , or c I want to filter on , and then return that result . Is there any way to do this in C # ? Nothing immediately comes to mind , but it feels like something that should be possible . class Foo { string bar { get ; set ; } int a { get ; set ; } int b { get ; set ; } int c { get ; set ; } } return listOfFoo.Where ( f = > f.a > = 0 ) .OrderBy ( f = > f.a ) .Take ( 5 ) .Select ( f = > f.bar ) ;",C # re-use LINQ expression for different properties with same type "C_sharp : So , let 's say I have an interface IThingFactory : Now , let 's say I have a concrete implementation that retrieves Things from a database . Now , let 's also say I have a concrete implementation that wraps an existing IThingFactory and checks for a Thing 's presence in , say , an in-memory cache before hitting the wrapped IThingFactory . Something like : How would I deal with a scenario like this using dependency injection with something like , say , Ninject , so that I could configure the DI container so that I can inject or remove a caching proxy like this , or , say , something that does logging , or ( insert here ) ? public interface IThingFactory { Thing GetThing ( int thingId ) ; } public class CachedThingFactory : IThingFactory { private IThingFactory _wrapped ; private Dictionary < int , Thing > _cachedThings ; public CachedThingFactory ( IThingFactory wrapped ) { this._wrapped = wrapped ; _cachedThings = new Dictionary < int , Thing > ( ) ; } public Thing GetThing ( int thingId ) { Thing x ; if ( _cachedThings.TryGetValue ( thingId , out x ) ) return x ; x = _wrapped.GetThing ( thingId ) ; _cachedThings [ thingId ] = x ; return x ; } }",Dependency Injection : How to configure interface bindings for wrapping "C_sharp : It seems to me that when I use the WeakReference class on a delegate method of an object class , the object class gets collected by the GC but there is still another copy of it residing in the WeakReference ? I find it difficult to explain in words . I will give an example . I have the following object class called TestObject : Now , in my main application , I attempt to refer to the method TestMethod in TestObject via a WeakReference . The intention is so that the TestObject can be collected by GC when all hard references are gone . This is how my main application looks like : This is the output when I run the above code : Here 's the weird thing . On the first line , obj could print `` Hello 1 '' because it was just initialised and obj was holding a reference to the TestObject . All correct . Next , obj was set to null with obj = null and GC was forced to collect . So , in the second line of the output , obj is true to be null . Finally on the last line , since the GC has collected the obj away , I 'm expecting it to either throw a NullReferenceException or just print nothing on the output . However , it actually printed the same thing as on the first line of the output ! Should n't the TestObject be collected by the GC at this point already ? ! This begs the question if the TestObject that was first held in obj was later collected by the GC or not after I set obj to null.If I had passed the whole object into WeakReference , ie , new WeakReference ( obj ) , instead of a delegate into the WeakReference , it would have worked perfectly . Unfortunately , in my code , I need to pass into the WeakReference a delegate . How can I have the WeakReference to work correctly so that the GC can collect away the object by only having referenced to a delegate ? class TestObject { public string message = `` '' ; private delegate string deleg ( ) ; public TestObject ( string msg ) { message = msg ; } public Delegate GetMethod ( ) { deleg tmp = this.TestMethod ; return tmp ; } public string TestMethod ( ) { return message ; } } static void Main ( string [ ] args ) { var list = new List < WeakReference > ( ) ; var obj = new TestObject ( `` Hello 1 '' ) ; list.Add ( new WeakReference ( obj.GetMethod ( ) ) ) ; Console.WriteLine ( `` Initial obj : `` + ( ( Delegate ) list [ 0 ] .Target ) .DynamicInvoke ( ) ) ; //Works fine obj = null ; //Now , obj is set to null , the TestObject ( `` Hello 1 '' ) can be collected by GC GC.Collect ( ) ; //Force GC Console.WriteLine ( `` Is obj null : `` + ( ( obj ) == null ? `` True '' : `` False '' ) ) ; Console.WriteLine ( `` After GC collection : `` + ( ( Delegate ) list [ 0 ] .Target ) .DynamicInvoke ( ) ) ; Console.ReadKey ( ) ; }",GC does n't collect when WeakReference references a delegate ? C_sharp : I 'm trying to bind two values into the content of one label with a space in the middle . I 'm following an example from MSDN ( MSDN Article ) but my labels are empty . Here is the code I have : Class : Setting the items source : XAML : If I bind a single value it works perfectly E.g.So it does n't appear to be a problem retrieving the values . public class Item { //Other properties removed to shorten public string name { get ; set ; } public string typeLine { get ; set ; } } ItemsDisplay.ItemsSource = searchResults ; < ItemsControl Name= '' ItemsDisplay '' > < ItemsControl.ItemTemplate > < DataTemplate > < Grid > < ! -- COLUMN DEFINITIONS ETC REMOVED TO SHORTEN -- > < StackPanel Grid.Column= '' 1 '' > < Label Name= '' ItemName '' Margin= '' 10 '' > < Label.Content > < MultiBinding StringFormat= '' { } { 0 } { 1 } '' > < Binding Path= '' name '' / > < Binding Path= '' typeLine '' / > < /MultiBinding > < /Label.Content > < /Label > < /StackPanel > < /Grid > < /DataTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl > < StackPanel Grid.Column= '' 1 '' > < Label Name= '' ItemName '' Margin= '' 10 '' Content= '' { Binding Path=name } '' / > < Label Name= '' ItemType '' Margin= '' 10 '' Content= '' { Binding Path=typeLine } '' / > < /StackPanel >,WPF Multibinding not working - Labels are blank "C_sharp : In FluentAssertions , you can make various claims in various formats.are both valid assertions.Why is Should a method and not a property ? I have n't seen any examples in which Should takes a parameter , so it seems to me like it could have easily been a property.You can also assert thatHere , And is a property instead of a method . Should n't And and Should each be the same type of element ( methods/properties ) ? TL ; DRWas there a valid reason behind the design choice to make Should a method in FluentAssertions instead of a property ? x.Should ( ) .BeEquivalentTo ( y ) ; x.ShouldBeEquivalentTo ( y ) ; x.Should ( ) .NotBeNull ( ) .And.BeEquivalentTo ( y ) ;","In FluentAssertions , why is Should a method instead of a property ?" "C_sharp : I 'm curious as to why the following code works ( run under the VS debugger ) : If x is indeed null , what instance does HasValue refer to ? Is HasValue implemented as an extension method , or does the compiler special case this to make it magically work ? int ? x = null ; nullx.HasValuefalse",Why can an int ? set to null have instance properties ? "C_sharp : I have 100 pages on my site , but I want download only part a page instead of all page content.I want just one box of each page to download , the file size is 10 KB.For this I Use WebClient and htmlagilitypack . WebClient Client = new WebClient ( ) ; var result = Encoding.GetEncoding ( `` UTF-8 '' ) .GetString ( Client.DownloadData ( URL ) ) ;",How can I download only part of a page ? "C_sharp : Maybe I am doing something wrong here but it seems weird to me that when I try to match the string `` radiologic examination eye detect foreign body '' against the regular expression `` \b*ct\b '' on regexr.com then I find no match but when I try and do the same thing using a C # program , it matches . C # code is given below . Am I doing/checking something wrong ? Thanks in advance ! string desc = `` radiologic examination eye detect foreign body '' ; string regex = `` \\b '' + `` *ct '' + `` \\b '' ; if ( Regex.IsMatch ( desc , regex ) ) { String x = Regex.Replace ( desc , regex , `` `` + `` ct '' + `` `` ) .Trim ( ) ; Console.WriteLine ( x ) ; }",C # Regular Expression matching but not Regexr.com "C_sharp : If you implement a custom PowerShell Host with System.Management.Automation ( SMA ) , all of the automatic variables are avaialable , except it seems that $ PROFILE is empty . How would one go about recreating it ? Is it always in UserProfile + \Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ? Or do I need to be worried about it being in other places ? To clarify , I only care about CurrentUserCurrentHost profile.DetailsGiven this PowerShell script : Running it against system PowerShell has the following output : Running it with a Custom C # PowerShell Host ( a System.Management.Automation.Host.PSHost implementation ) shows : Backgroundhttps : //github.com/chocolatey/choco/issues/667This has been tested in PowerShell v3 / System.Managment.Automation ( SMA ) v3 but it could easily be proven out in other PowerShell versions . Write-Output `` _Profiles_ '' Write-Output `` CurrentUserCurrentHost = ' $ ( $ Profile.CurrentUserCurrentHost ) ' '' Write-Output `` CurrentUserAllHosts = ' $ ( $ Profile.CurrentUserAllHosts ) ' '' Write-Output `` AllUsersCurrentHost = ' $ ( $ Profile.AllUsersCurrentHost ) ' '' Write-Output `` AllUsersAllHosts = ' $ ( $ Profile.AllUsersAllHosts ) ' '' _Profiles_CurrentUserCurrentHost = ' C : \Users\rob\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'CurrentUserAllHosts = ' C : \User\rob\Documents\WindowsPowerShell\profile.ps1'AllUsersCurrentHost = ' C : \Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1'AllUsersAllHosts = ' C : \Windows\System32\WindowsPowerShell\v1.0\profile.ps1 ' _Profiles_CurrentUserCurrentHost = `` CurrentUserAllHosts = `` AllUsersCurrentHost = `` AllUsersAllHosts = ``",How do I recreate PowerShell $ profile variable ? It 's empty in a custom Host "C_sharp : If this is the decorator pattern . What is the difference between the decorator pattern and composition ? I have seen examples of this pattern where inheritance is used . For instance the Java example on Wikipedia.I do n't see the need to use inheritance at all , or am I missing something ? public interface IMovable { void Move ( ) ; } public interface IUnloadable { void Unload ( ) ; } public class Vehicle : IMovable { public void Move ( ) { Console.Write ( `` moving '' ) ; } } public class Truck : IMovable , IUnloadable { private Vehicle Veh ; public Truck ( Vehicle veh ) { this.Veh = veh ; } public void Move ( ) { Veh.Move ( ) ; Console.Write ( `` reverse with beepy noise as well '' ) ; } public void Unload ( ) { Console.Write ( `` Unload '' ) ; } }",Decorator pattern in C # without Inheritance . Is this correct ? "C_sharp : Try debugging the following simple program , and mouse over x in each step ( or `` Add Watch '' for x or whatever ) .So , apparently VS has its own way to display a System.Double . Which method does it call for this purpose ? Is there a way I can get the very same string representation programmatically ? ( Tried this out with Visual Studio 2010 Professional . ) using System ; using System.Globalization ; static class Program { static double x ; static void Main ( ) { x = 2d ; // now debugger shows `` 2.0 '' , as if it has used // x.ToString ( `` F1 '' , CultureInfo.InvariantCulture ) x = 8.0 / 7.0 ; // now debugger shows `` 1.1428571428571428 '' , as if it had used // x.ToString ( `` R '' , CultureInfo.InvariantCulture ) // Note that 17 significant figures are shown , not the usual 15. x = -1e-200 / 1e200 ; // now debugger shows `` 0.0 '' ; there is no indication that this is really negative zero // Console.WriteLine ( 1.0 / x ) ; // this is negative infinity } }",How does Visual Studio display a System.Double during debugging ? "C_sharp : I am trying to make a back propagation neural network.Based upon the the tutorials i found here : MSDN article by James McCaffrey . He gives many examples but all his networks are based upon the same problem to solve . So his networks look like 4:7:3 > > 4input - 7hidden - 3output.His output is always binary 0 or 1 , one output gets a 1 , to classify an Irish flower , into one of the three categories.I would like to solve another problem with a neural network and that would require me 2 neural networks where one needs an output inbetween 0..255 and another inbetween 0 and 2times Pi . ( a full turn , circle ) . Well essentially i think i need an output that range from 0.0 to 1.0 or from -1 to 1 and anything in between , so that i can multiply it to becomme 0..255 or 0..2PiI think his network does behave , like it does because of his computeOutputs Which I show below here : The network uses the folowing hyperTan functionIn above a function makes for the output layer use of Softmax ( ) and it is i think critical to problem here . In that I think it makes his output all binary , and it looks like this : How to rewrite softmax ? So the network will be able to give non binary answers ? Notice the full code of the network is here . if you would like to try it out.Also as to test the network the following accuracy function is used , maybe the binary behaviour emerges from it private double [ ] ComputeOutputs ( double [ ] xValues ) { if ( xValues.Length ! = numInput ) throw new Exception ( `` Bad xValues array length '' ) ; double [ ] hSums = new double [ numHidden ] ; // hidden nodes sums scratch array double [ ] oSums = new double [ numOutput ] ; // output nodes sums for ( int i = 0 ; i < xValues.Length ; ++i ) // copy x-values to inputs this.inputs [ i ] = xValues [ i ] ; for ( int j = 0 ; j < numHidden ; ++j ) // compute i-h sum of weights * inputs for ( int i = 0 ; i < numInput ; ++i ) hSums [ j ] += this.inputs [ i ] * this.ihWeights [ i ] [ j ] ; // note += for ( int i = 0 ; i < numHidden ; ++i ) // add biases to input-to-hidden sums hSums [ i ] += this.hBiases [ i ] ; for ( int i = 0 ; i < numHidden ; ++i ) // apply activation this.hOutputs [ i ] = HyperTanFunction ( hSums [ i ] ) ; // hard-coded for ( int j = 0 ; j < numOutput ; ++j ) // compute h-o sum of weights * hOutputs for ( int i = 0 ; i < numHidden ; ++i ) oSums [ j ] += hOutputs [ i ] * hoWeights [ i ] [ j ] ; for ( int i = 0 ; i < numOutput ; ++i ) // add biases to input-to-hidden sums oSums [ i ] += oBiases [ i ] ; double [ ] softOut = Softmax ( oSums ) ; // softmax activation does all outputs at once for efficiency Array.Copy ( softOut , outputs , softOut.Length ) ; double [ ] retResult = new double [ numOutput ] ; // could define a GetOutputs method instead Array.Copy ( this.outputs , retResult , retResult.Length ) ; return retResult ; private static double HyperTanFunction ( double x ) { if ( x < -20.0 ) return -1.0 ; // approximation is correct to 30 decimals else if ( x > 20.0 ) return 1.0 ; else return Math.Tanh ( x ) ; } private static double [ ] Softmax ( double [ ] oSums ) { // determine max output sum // does all output nodes at once so scale does n't have to be re-computed each time double max = oSums [ 0 ] ; for ( int i = 0 ; i < oSums.Length ; ++i ) if ( oSums [ i ] > max ) max = oSums [ i ] ; // determine scaling factor -- sum of exp ( each val - max ) double scale = 0.0 ; for ( int i = 0 ; i < oSums.Length ; ++i ) scale += Math.Exp ( oSums [ i ] - max ) ; double [ ] result = new double [ oSums.Length ] ; for ( int i = 0 ; i < oSums.Length ; ++i ) result [ i ] = Math.Exp ( oSums [ i ] - max ) / scale ; return result ; // now scaled so that xi sum to 1.0 } public double Accuracy ( double [ ] [ ] testData ) { // percentage correct using winner-takes all int numCorrect = 0 ; int numWrong = 0 ; double [ ] xValues = new double [ numInput ] ; // inputs double [ ] tValues = new double [ numOutput ] ; // targets double [ ] yValues ; // computed Y for ( int i = 0 ; i < testData.Length ; ++i ) { Array.Copy ( testData [ i ] , xValues , numInput ) ; // parse test data into x-values and t-values Array.Copy ( testData [ i ] , numInput , tValues , 0 , numOutput ) ; yValues = this.ComputeOutputs ( xValues ) ; int maxIndex = MaxIndex ( yValues ) ; // which cell in yValues has largest value ? int tMaxIndex = MaxIndex ( tValues ) ; if ( maxIndex == tMaxIndex ) ++numCorrect ; else ++numWrong ; } return ( numCorrect * 1.0 ) / ( double ) testData.Length ; }",Getting a neural network to output anything inbetween -1.0 and 1.0 "C_sharp : I 've been trying to implement a loosely coupled application in an asp.net MVC5 app . I have a controller : And service being used in this controller is : And the repository being used in the service class is : The interfaces used for the service and repository are as such : The constructor for HeaderController takes in the MenuService using Constructor Injection , and I have ninject as the DI container handling this.It all works great - except , in my controller , I can still do this : ... which breaks the architecture . How can I prevent the 'new ' being used in this way ? public class HeaderController : Controller { private IMenuService _menuService ; public HeaderController ( IMenuService menuService ) { this._menuService = menuService ; } // // GET : /Header/ public ActionResult Index ( ) { return View ( ) ; } public ActionResult GetMenu ( ) { MenuItem menu = this._menuService.GetMenu ( ) ; return View ( `` Menu '' , menu ) ; } } public class MenuService : IMenuService { private IMenuRespository _menuRepository ; public MenuService ( IMenuRespository menuRepository ) { this._menuRepository = menuRepository ; } public MenuItem GetMenu ( ) { return this._menuRepository.GetMenu ( ) ; } } public class MenuRepository : IMenuRespository { public MenuItem GetMenu ( ) { //return the menu items } } public interface IMenuService { MenuItem GetMenu ( ) ; } public interface IMenuRespository { MenuItem GetMenu ( ) ; } MenuItem menu = new MenuService ( new MenuRepository ( ) ) ;",How to prevent constructor misuse in c # class "C_sharp : .NET 4 introduces covariance . I guess it is useful . After all , MS went through all the trouble of adding it to the C # language . But , why is Covariance more useful than good old polymorphism ? I wrote this example to understand why I should implement Covariance , but I still do n't get it . Please enlighten me . using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace Sample { class Demo { public delegate void ContraAction < in T > ( T a ) ; public interface IContainer < out T > { T GetItem ( ) ; void Do ( ContraAction < T > action ) ; } public class Container < T > : IContainer < T > { private T item ; public Container ( T item ) { this.item = item ; } public T GetItem ( ) { return item ; } public void Do ( ContraAction < T > action ) { action ( item ) ; } } public class Shape { public void Draw ( ) { Console.WriteLine ( `` Shape Drawn '' ) ; } } public class Circle : Shape { public void DrawCircle ( ) { Console.WriteLine ( `` Circle Drawn '' ) ; } } public static void Main ( ) { Circle circle = new Circle ( ) ; IContainer < Shape > container = new Container < Circle > ( circle ) ; container.Do ( s = > s.Draw ( ) ) ; //calls shape //Old school polymorphism ... how is this not the same thing ? Shape shape = new Circle ( ) ; shape.Draw ( ) ; } } }",How is covariance cooler than polymorphism ... and not redundant ? "C_sharp : I 'm trying to figure out what the limitations really means when deploying for iOS from Xamarin.http : //developer.xamarin.com/guides/ios/advanced_topics/limitations/I was under the impression that you have no JIT and thus any MakeGenericMethod or MakeGenericType would NOT work as that would require JIT compilation.Also I understood that when running on the simulator , these restrictions does not apply since the simulator is not running in the full AOT ( Ahead of Time ) mode.After setting up my Mac so that I could deploy to my phone , I would except the following test to fail when running on the actual device ( iPhone ) .The thing is that completes successfully and I ca n't really understand why . Does not this code require JIT compilation ? In an effort to `` make it break '' , I also did a test with MakeGenericType.How can this work when there is no JIT ? Am I missing something ? [ Test ] public void InvokeGenericMethod ( ) { var method = typeof ( SampleTests ) .GetMethod ( `` SomeGenericMethod '' ) ; var closedMethod = method.MakeGenericMethod ( GetTypeArgument ( ) ) ; closedMethod.Invoke ( null , new object [ ] { 42 } ) ; } public static void SomeGenericMethod < T > ( T value ) { } private Type GetTypeArgument ( ) { return typeof ( int ) ; } [ Test ] public void InvokeGenericType ( ) { var type = typeof ( SomeGenericClass < > ) .MakeGenericType ( typeof ( string ) ) ; var instance = Activator.CreateInstance ( type ) ; var method = type.GetMethod ( `` Execute '' ) ; method.Invoke ( instance , new object [ ] { `` Test '' } ) ; } public class SomeGenericClass < T > { public void Execute ( T value ) { } }",MakeGenericMethod/MakeGenericType on Xamarin.iOS "C_sharp : I am developing a C # application . Since I have some algorithms for least-squares fit in C/C++ that would be too cumbersome too translate , I have made the C++ code into a dll and then created a wrapper in C # .In the C # code , I have defined a struct that is passed to the unmanaged C++ code as a pointer . The struct contains the initial guesstimates for the fitting functions , and it is also used to return the results of the fit.It appears to me that you must define the struct in both the managed and the unmanaged code . However , someone using my source code in in the future might decide to change the fields of the struct in the C # application , without understanding that they also have to change the struct in the native code . This will result in a run-time error at best ( and produce erroneous results at worse ) , but there will be no error message telling the developer / end user what is wrong.From my understanding , it impossible to create a test in the unmanaged C++ DLL that checks if the struct contains the correct fields , but is it posible to have the DLL returning a struct of the correct format to the C # wrapper ? Otherwise , what ways are there to reduce the risk that some careless programmer in the future causes run-time errors that are hard to detect ? Sample code : // ... algorithm //C++struct InputOutputStruct { double a , b , c ; } extern `` C '' __declspec ( dllexport ) void DoSomethingToStruct ( InputOutputStruct* s ) { } //C # using System.Runtime.InteropServices ; [ StructLayout ( LayoutKind.Sequential ) ] public struct InputOutputStruct { public double a , b , c ; } [ DllImport ( `` CpluplusDll.dll '' ) ] public static unsafe extern bool DoSomethingToStruct ( InputOutputStruct* s ) ; class CSharpWrapper { static void Main ( string [ ] args ) { InputOutputStruct s = new InputOutputStruct ( ) ; unsafe { InputOutpustruct* sPtr = & s ; DoSomethingToStruct ( sPtr ) ; s = *sPtr ; } } }",.net wrapper for native dll - how to minimize risk of run-time error ? "C_sharp : I have a scenario where I run a UWP client application , a UWP IOT application and a .NET Core application using a shared code base.In .NET Core RC1 I built a Class Library ( Package ) and used `` dotnet5.4 '' as the base framework for that library.Using `` generate build output '' I could reference the created nuget packages from the .NET Core application ( console ) and using a workaround ( copy the packages from % local % .dnx - > % local % .nuget ) the UWP applications were able to reference and use the package as well.Now in RC2 things have changed a bit and I am again able to consume the upgraded library ( tooling upgraded in project file , changes to project.json , netstandard1.4 ( since 1.5 does not work with UAP10 according to this ) ) perfectly using the .NET Core console application.For UWP I can not add the library since I get dozens of infamouserrors.After some looking around , I tried to isolate the issue and found out that I ca n't even add a reference to System.IO.FileSystem.Watcher due to : I have a minimal solution to reproduce the issue uploaded to OneDrive.I made no changes to the blank UWP template except for the dependencies in project.json : Note : I updated Microsoft.NETCore.UniversalWindowsPlatform to the latest version . I added NETStandard.Library and Microsoft.NETCore.Platforms.Help is greatly appreciated ! Thanks in advance-Simon `` [ ... ] provides a compile-time reference assembly [ ... ] but there is no run-time assembly compatible with [ ... ] '' System.IO.FileSystem.Watcher 4.0.0-rc2-24027 provides a compile-time reference assembly for System.IO.FileSystem.Watcher on UAP , Version=v10.0 , but there is no run-time assembly compatible with win10-arm-aot.Some packages are not compatible with UAP , Version=v10.0 ( win10-x64-aot ) .System.IO.FileSystem.Watcher 4.0.0-rc2-24027 provides a compile-time reference assembly for System.IO.FileSystem.Watcher on UAP , Version=v10.0 , but there is no run-time assembly compatible with win10-x64.Some packages are not compatible with UAP , Version=v10.0 ( win10-arm ) .Some packages are not compatible with UAP , Version=v10.0 ( win10-x86-aot ) .System.IO.FileSystem.Watcher 4.0.0-rc2-24027 provides a compile-time reference assembly for System.IO.FileSystem.Watcher on UAP , Version=v10.0 , but there is no run-time assembly compatible with win10-x86.System.IO.FileSystem.Watcher 4.0.0-rc2-24027 provides a compile-time reference assembly for System.IO.FileSystem.Watcher on UAP , Version=v10.0 , but there is no run-time assembly compatible with win10-x86-aot.System.IO.FileSystem.Watcher 4.0.0-rc2-24027 provides a compile-time reference assembly for System.IO.FileSystem.Watcher on UAP , Version=v10.0 , but there is no run-time assembly compatible with win10-arm.Some packages are not compatible with UAP , Version=v10.0 ( win10-x64 ) .System.IO.FileSystem.Watcher 4.0.0-rc2-24027 provides a compile-time reference assembly for System.IO.FileSystem.Watcher on UAP , Version=v10.0 , but there is no run-time assembly compatible with win10-x64-aot.Some packages are not compatible with UAP , Version=v10.0 ( win10-x86 ) .Some packages are not compatible with UAP , Version=v10.0 ( win10-arm-aot ) . `` dependencies '' : { `` Microsoft.ApplicationInsights '' : `` 2.1.0-beta4 '' , `` Microsoft.ApplicationInsights.PersistenceChannel '' : `` 2.0.0-beta3 '' , `` Microsoft.ApplicationInsights.WindowsApps '' : `` 1.1.1 '' , `` Microsoft.NETCore.Platforms '' : `` 1.0.1-rc2-24027 '' , `` Microsoft.NETCore.UniversalWindowsPlatform '' : `` 5.1.0 '' , `` NETStandard.Library '' : `` 1.5.0-rc2-24027 '' , `` System.IO.FileSystem.Watcher '' : `` 4.0.0-rc2-24027 '' } ,",UWP application and .NET Core RC2 : can not reference netstandard1.4 packages "C_sharp : I want to display some objects in a treeview , but so far unfortunately without success . I 've a ObservableCollection < ICustom > of objects : Settings.ListOfCustomersThe interface of the object ICustom : The ObservableCollection < IValue > ListOfValues has also some properties like : My View : Question : How can I display display these objects in a TreeView ? My approach ( see `` My View '' ) does not work . int Id { get ; } int age { get ; } CustomerType CustomerType { get ; } ObservableCollection < IValue > ListOfValues { get ; } String Name { get ; } < TreeView ItemsSource= '' { Binding ListOfCustomers , UpdateSourceTrigger=PropertyChanged } '' > < TreeView.Resources > < HierarchicalDataTemplate DataType= '' { x : Type customerConfig : ICustomer } '' > < TextBlock Text= '' { Binding Id } '' / > < /HierarchicalDataTemplate > < HierarchicalDataTemplate DataType= '' { x : Type valueConfig : IValue } '' ItemsSource= '' { Binding ListOfValues } '' > < StackPanel > < TextBlock Text= '' { Binding Name } '' / > < /StackPanel > < /HierarchicalDataTemplate > < /TreeView.Resources > < /TreeView >",TreeView with nested List "C_sharp : ReSharper suggested to enumerate an IEnumerable < T > to a list or array since I had `` possible multiple enumerations of IEnumerable < T > '' .The automatic code re-factoring suggested has some optimization built in to see whether IEnumerable < T > already is an array before calling ToArray ( ) .Is n't this optimization already built-in the original LINQ method ? If not , what would be the motivation not to do so ? var list = source as T [ ] ? ? source.ToArray ( ) ;",Is ToArray ( ) optimized for arrays ? "C_sharp : I would like to programmatically list and control virtual machines classic ( old one ) in Azure . For managed it is not problem , there are libraries and the rest API is working , but once I am calling the old API for listing classic , I got 403 ( Forbidden ) .Is the code fine ? Do I need to manage credentials for old API on another place ? My code is here : UPDATE 1 : Response details : Update 2 : I found that same API is used by powershell command Get-AzureVMImage and it is working from powershell . Powershell ask me first to login to Azure with interactive login windows by email and password and the the request use Bearer header to authenticate like mine code.If I sniff the access token ( Bearer header ) from communication created by Powershell , I can communicate with that API with success.Update 3 : SOLVED , answer bellow . static void Main ( string [ ] args ) { string apiNew = `` https : //management.azure.com/subscriptions/xxxxxxxxxxxxxxxxxxxxxxxx/providers/Microsoft.Compute/virtualMachines ? api-version=2018-06-01 '' ; string apiOld = `` https : //management.core.windows.net/xxxxxxxxxxxxxxxxxxxxxxxx/services/vmimages '' AzureRestClient client = new AzureRestClient ( credentials.TenantId , credentials.ClientId , credentials.ClientSecret ) ; //OK - I can list the managed VMs . string resultNew = client.GetRequestAsync ( apiNew ) .Result ; // 403 forbidden string resultOld = client.GetRequestAsync ( apiOld ) .Result ; } public class AzureRestClient : IDisposable { private readonly HttpClient _client ; public AzureRestClient ( string tenantName , string clientId , string clientSecret ) { _client = CreateClient ( tenantName , clientId , clientSecret ) .Result ; } private async Task < string > GetAccessToken ( string tenantName , string clientId , string clientSecret ) { string authString = `` https : //login.microsoftonline.com/ '' + tenantName ; string resourceUrl = `` https : //management.core.windows.net/ '' ; var authenticationContext = new AuthenticationContext ( authString , false ) ; var clientCred = new ClientCredential ( clientId , clientSecret ) ; var authenticationResult = await authenticationContext.AcquireTokenAsync ( resourceUrl , clientCred ) ; var token = authenticationResult.AccessToken ; return token ; } async Task < HttpClient > CreateClient ( string tenantName , string clientId , string clientSecret ) { string token = await GetAccessToken ( tenantName , clientId , clientSecret ) ; HttpClient client = new HttpClient ( ) ; client.DefaultRequestHeaders.Accept.Clear ( ) ; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ( `` Bearer '' , token ) ; return client ; } public async Task < string > GetRequestAsync ( string url ) { return await _client.GetStringAsync ( url ) ; } } HTTP/1.1 403 ForbiddenContent-Length : 288Content-Type : application/xml ; charset=utf-8Server : Microsoft-HTTPAPI/2.0Date : Mon , 22 Oct 2018 11:03:40 GMTHTTP/1.1 403 ForbiddenContent-Length : 288Content-Type : application/xml ; charset=utf-8Server : Microsoft-HTTPAPI/2.0Date : Mon , 22 Oct 2018 11:03:40 GMT < Error xmlns= '' http : //schemas.microsoft.com/windowsazure '' xmlns : i= '' http : //www.w3.org/2001/XMLSchema-instance '' > < Code > ForbiddenError < /Code > < Message > The server failed to authenticate the request . Verify that the certificate is valid and is associated with this subscription. < /Message > < /Error >",How to list Virtual Machines Classic in Azure "C_sharp : When I use DebuggerVisualizer attribute as followsc # vb.netI can reuse Dataset Visualiser in my visualisers dll . This allows to have built in VS visualizer as first ( default ) even when a custom DataTable visualizer is defined ( How to specify order of debugger visualizers in Visual Studio ) .I would like to achieve the same behavior for `` Text Visualiser '' . [ assembly : DebuggerVisualizer ( typeof ( DataSetVisualizer ) , typeof ( DataSetVisualizerSource ) , Target = typeof ( DataTable ) , Description = `` My DataTable Visualizer '' ) ] < Assembly : DebuggerVisualizer ( GetType ( DataSetVisualizer ) , GetType ( DataSetVisualizerSource ) , Target : = GetType ( DataTable ) , Description : = `` My DataTable Visualizer '' ) >",Which class is used for `` Text Visualizer '' ? "C_sharp : I have put together a simple application that monitors file creation events , creates some objects from the files content , and does some processing . Here is the sample code : It all works fine , but when I uncomment AsParallel ( and the next two lines ) it does n't yield results right away . This delay is probably caused by PLINQ partitioning ? However , I expect this query to yield items as soon as they are added to the BlockingCollection . Is this possible to achieve using PLINQ ? class Program { private const string Folder = `` C : \\Temp\\InputData '' ; static void Main ( string [ ] args ) { var cts = new CancellationTokenSource ( ) ; foreach ( var obj in Input ( cts.Token ) ) Console.WriteLine ( obj ) ; } public static IEnumerable < object > Input ( CancellationToken cancellationToken ) { var fileList = new BlockingCollection < string > ( ) ; var watcher = new FileSystemWatcher ( Folder ) ; watcher.Created += ( source , e ) = > { if ( cancellationToken.IsCancellationRequested ) watcher.EnableRaisingEvents = false ; else if ( Path.GetFileName ( e.FullPath ) == `` STOP '' ) { watcher.EnableRaisingEvents = false ; fileList.CompleteAdding ( ) ; File.Delete ( e.FullPath ) ; } else fileList.Add ( e.FullPath ) ; } ; watcher.EnableRaisingEvents = true ; return from file in fileList.GetConsumingEnumerable ( cancellationToken ) //.AsParallel ( ) //.WithCancellation ( cancellationToken ) //.WithDegreeOfParallelism ( 5 ) let obj = CreateMyObject ( file ) select obj ; } private static object CreateMyObject ( string file ) { return file ; } }",Making PLINQ and BlockingCollection work together "C_sharp : What 's the point of DataTable.AsTableValuedParameter method which returns a SqlMapper.ICustomQueryParameter when having to pass a datatable as TVP to DB using Dapper ? I could send TVPs to DB just as normal datatable and execute queries just fine . I am not sure what performing AsTableValuedParameter on it buys additionally.For e.g . this works : Also , an additional question , what is the need for typeName optional parameter in AsTableValuedParameter method ? Works fine without it too . int rowsAffected = await conn.ExecuteAsync ( `` MyProc '' , new { myVar = ( DataTable ) GetThatDataTable ( ) , } , commandType : CommandType.StoredProcedure ) ;",Understanding SqlMapper.ICustomQueryParameter "C_sharp : I have a basic MVC view model with annotations , for example : I have a strongly-typed view based upon this view model . When I run the application locally , the following code generates `` Your Name '' label : When the application is deployed on IIS7 with .NET 4 application pool , the label says `` YourName '' ( without a space ) . This is very bizzare and I did n't come across this before . Does anybody have an idea what might be causing this ? Cache is cleared , this has been tested from a range of web clients and result is the same.Edit : Edit 2All annotations on that field are being ignored . There are other text type fields and they have the same issue . This is happening only on a live server . Live server is IIS 7 which has been configured over Plesk 10.2 . Wondering whether this is a bug since I 'm using MVC 3 RTM.Edit 3Within the same view model I have the Email property : This property is used within a view : But it works perfectly fine : ( So the email property works fine in both live and dev environment . Other properties work only in dev environment.Edit 4Removing MaxLength and MinLength annotations fixed the problem . I would still like to use MaxLength and MinLength annotations as part of my model validation routines though . [ Required ( ErrorMessage= '' Your Name Required '' ) ] [ Display ( Name = `` Your Name '' ) ] [ DataType ( DataType.Text ) ] [ MaxLength ( 120 , ErrorMessage = `` Must be under 120 characters '' ) ] public String YourName { get ; set ; } @ Html.LabelFor ( model = > model.YourName ) @ model MVC.Web.Models.ContactUsModel < div > @ Html.LabelFor ( model = > model.YourName ) @ Html.EditorFor ( model = > model.YourName ) < /div > [ Required ( ErrorMessage = `` Your Email Is Required '' ) ] [ Display ( Name = `` Your Email '' ) ] [ RegularExpression ( @ '' ^\w+ ( [ -+. ' ] \w+ ) * @ \w+ ( [ -. ] \w+ ) *\.\w+ ( [ - . ] \w+ ) * $ '' , ErrorMessage = `` Your Email Is Invalid '' ) ] [ DataType ( DataType.Text ) ] public String FromEmail { get ; set ; } < div > @ Html.LabelFor ( model = > model.FromEmail ) @ Html.EditorFor ( model = > model.FromEmail ) < /div > [ MinLength ( 3 , ErrorMessage = `` Minimum 3 Characters '' ) ] [ MaxLength ( 30 , ErrorMessage = `` Maximum 30 Characters '' ) ]",IIS does n't recognise view model annotations "C_sharp : I 'm using Ninject to instantiate some objects with a constructor arg passed , e.g . : The number of instances I need of this class wo n't be known until runtime , but what I want to do is ensure that each variation of myArg results in a different singleton instance ( so asking for the same value twice returns the same instance , but different args return different instances ) .Does anyone know of a good , preferably built-in , way of doing this ? I found an article written for an older version of Ninject How To Ensure One Instance per Variation of Activation Parameters but was hoping there 'd be a tidier solution for the newer version.EditHere 's what I went with , adapted from Akim 's answer below : class MyClass { public MyClass ( string myArg ) { this.myArg = myArg ; } } private readonly ConcurrentBag < string > scopeParameters = new ConcurrentBag < string > ( ) ; internal object ParameterScope ( IContext context , string parameterName ) { var param = context.Parameters.First ( p = > p.Name.Equals ( parameterName ) ) ; var paramValue = param.GetValue ( context , context.Request.Target ) as string ; paramValue = string.Intern ( paramValue ) ; if ( paramValue ! = null & & ! scopeParameters.Contains ( paramValue ) ) { scopeParameters.Add ( paramValue ) ; } return paramValue ; } public override void Load ( ) { Bind < MyClass > ( ) .ToSelf ( ) .InScope ( c = > ParameterScope ( c , `` myArg '' ) ) ; Bind < IMyClassFactory > ( ) .ToFactory ( ) ; }",Ninject Memoize Instances in Singleton Scope "C_sharp : I am implementing a class that will be used concurrently from multiple threads . Most of the properties get and set primitive types which can be handled properly by the Interlocked class . The class includes a Guid property . This is not as straight-forward to implement in a thread-safe manner . Is this how you would implement the property ? Thanks in advance.UPDATE : So the only proposed solution up to this point does n't include the use of any `` Threading '' classes or constructs . So I am going to pose the question that I 've already posed in comments : My understanding is that reference/primitive values types assignments are atomic however Interlocked will guarantee the change is propagated to all threads . If we could simply just assign the value , why does Interlocked expose APIs to exchange reference types and primitive values ? private Byte [ ] _activityId ; public Guid ActivityId { get { return new Guid ( this._activityId ) ; } set { Byte [ ] bytes = value.ToByteArray ( ) ; Interlocked.Exchange ( ref this._activityId , bytes ) ; } }",Is this the proper way to implement a thread-safe read/write Guid property ? "C_sharp : I have a button bound to a ICommandAfter some tasks is done , I made the button visible , except that they look disabled until I click something , why is that ? The RemoveCommand looks like belowafter uploads , the CanExecute callback returns True , so button should be enabled , but it looks disabled till I click something , why is this happening ? Video of the Problem < Button Content= '' Remove '' Command= '' { Binding RemoveCommand } '' x : Name= '' btnRemove '' Visibility= '' Collapsed '' / > public ICommand RemoveCommand { get { if ( _removeCommand == null ) { _removeCommand = new RelayCommand ( ( ) = > { if ( RemoveRequested ! = null ) RemoveRequested ( this , EventArgs.Empty ) ; } , ( ) = > { // CanExecute Callback if ( Status == WorkStatus.Processing || Status == WorkStatus.Pending ) { Debug.WriteLine ( `` Returning False '' + Status ) ; return false ; } Debug.WriteLine ( `` Returning True '' ) ; return true ; // After uploads , this returns True , in my Output Window . } ) ; } return _removeCommand ; }",Buttons looks disabled until I click something "C_sharp : Is there a syntax in C # that allows me to define a private property , like in Typescript ? Example : Typescript : In C # I have to do this : update 1 : I 'm looking for a syntax sugar for AspNet core dependency injection . constructor ( private field1 : string ) { } private readonly string field1 ; public MyClass ( string field1 ) { this.field1 = field1 ; }",Define private properties in C # like Typescript "C_sharp : I am looking for a framework-defined interface that declares indexer . In other words , I am looking for something like this : I just wonder whether .Net framework contains such interface ? If yes , what is it called ? You might ask why I ca n't just create the interface myself . Well , I could have . But if .Net framework already has that why should I reinvent the wheel ? public interface IYourList < T > { T this [ int index ] { get ; set ; } }",Interface that Entails the Implementation of Indexer "C_sharp : I have a Silverlight application that displays a list of items in a ListBox . Each item represents a different 'page ' of my application so I have a style that is applied to the ItemContainerStyle property that looks like this : The style is very simple . It simply displays the Border when the ListBoxItem 's visual state is equal to 'Selected ' . Notice that the content is hosted by a ContentControl as I want to be able to change the Foreground property when the item is in the 'Selected ' state . This works brilliantly as can be seen by the screenshot below : Now I want the selected item to invoke navigation so the idea I had was to create a DataTemplate that sets the content of each item to a HyperLinkButton : Now this does n't work as the ItemTemplate hosts it 's content in a ContentControl rather than a ContentPresenter so I have had to update the ListBoxItem template to use a ContentPresenter instead.I now get the following result : When I click on the HyperLinkButton the ListBoxItem is now no longer selected ( I can click just outside the HyperLinkButton and the ListBoxItem becomes selected ) . What I really want is for the ListBoxItem to become selected when the HyperLinkButton is clicked . The HyperLinkButton has no concept of selection so I can not bind to the ListBoxItem 's IsSelected property.Note : The actual navigation works perfectly , the problem is purely with the appearance of the ListBoxItems.So my questions are : Can I make it so that when the HyperLinkButton is clicked , the ListBoxItem becomes selected like the first image ? I will also need some way of changing the foreground of the HyperLinkButton when it is selected as this is no longer done in the items template due to me swapping the ContentControl fro a ContentPresenter.Note : I could probably solve this problem by binding the SelectedItem property of the ListBox to my viewModel and handling the navigation there negating the requirement to have a HyperLinkButton hosted by each ListBoxItem but I am interested in knowing if it is possible using styles and templates to achieve my desired result.UpdateI have tried a couple of things to try and resolve this but so far have been unsuccessful . The first thing I tried was applying a new style to the HyperLinkButton control in my DataTemplate which essentially removes all of the default look and feel from the control but my application still behaves in the way described above.The second thing I tried was setting the IsHitTestVisible property to false . This allows me to click 'through ' the HyperLinkbutton and select the ListBoxItem but this means that the navigation is now no longer invoked . < Style x : Key= '' navigationItemContainerStyle '' TargetType= '' ListBoxItem '' > < Setter Property= '' Margin '' Value= '' 5,3 '' / > < Setter Property= '' FontSize '' Value= '' 16 '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate > < Grid Cursor= '' Hand '' > < VisualStateManager.VisualStateGroups > < ! -- code omitted -- ! > < /VisualStateManager.VisualStateGroups > < Border x : Name= '' contentBorder '' Background= '' { StaticResource navigationHighlightBrush } '' CornerRadius= '' 3 '' Opacity= '' 0 '' / > < ContentControl x : Name= '' content '' Margin= '' 10,5 '' Content= '' { Binding } '' Foreground= '' DarkGray '' / > < /Grid > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < DataTemplate x : Key= '' navigationListBoxItemTemplate '' > < HyperlinkButton Content= '' { Binding } '' Background= '' Transparent '' / > < /DataTemplate > < ContentPresenter x : Name= '' content '' Margin= '' 10,5 '' / >",How to correctly use a button in a listbox itemtemplate / datatemplate ? "C_sharp : I am using sysmon to capture a bunch of event information ( network connections , DLL loads , etc ) . I want to pull that information and use it for various purposes , but it does n't seem like there is any way to retrieve the nested logs . They reside atAll of the code I 've tried only pulls the `` standard '' Event Logs . For example : has `` Application '' , `` Hardware Events '' , `` Internet Explorer '' , etc.I know how to create and retrieve custom event logs , but that does n't seem to apply here , as these logs are not in the standard locations . Any help you can provide would be very much appreciated ! Event Viewer/Applications and Services/Microsoft/Windows/Sysmon/Operational EventLog [ ] eventLogs = EventLog.GetEventLogs ( ) ;",C # - Read Nested Event Log From Custom Application "C_sharp : Constructing an OpenId provider , I 've run into the curious problem that only Stack Exchange sites will accept it.Discovery works fine , and watching log traffic I 'm sending ( what to me looks like ) a valid response back.Wonderfully , there are no compliance tests* to tell me what 's wrong , nor do most sites which offer logins via OpenId give you any useful error messages . Stack Overflow gives some , but it seems to be the only relying party that just accepts my assertions , so ... yeah.Anyway , if I try to login to ( for example ) Typepad I ultimately redirect back to a url like https : //www.typepad.com/secure/services/signin/openid ? openid-check=1 & archetype.quickreg=1 & tos_locale=en_US & portal=typepad & oic.time=1303249620-9db5665031c9c6b36031 & openid.claimed_id=https : //example/user/8c481fb7-1b5c-4e50-86b5-xxxxxxxxx & openid.identity=https : //example/user/8c481fb7-1b5c-4e50-86b5-xxxxxxxxx & openid.sig=hoaxQrsN4BBg6H8kp50NoQwpHmcO96BBe+jB3oOP2UA= & openid.signed=claimed_id , identity , assoc_handle , op_endpoint , return_to , response_nonce , ns.alias3 , alias3.mode & openid.assoc_handle= { 634388464235195799 } { oqMrOA== } { 32 } & openid.op_endpoint=https : //example/openid/provider & openid.return_to=https : //www.typepad.com/secure/services/signin/openid ? openid-check=1 & archetype.quickreg=1 & tos_locale=en_US & portal=typepad & oic.time=1303249620-9db5665031c9c6b36031 & openid.response_nonce=2011-04-19T21:47:03Z1aa4NZ48 & openid.mode=id_res & openid.ns=http : //specs.openid.net/auth/2.0 & openid.ns.alias3=http : //openid.net/srv/ax/1.0 & openid.alias3.mode=fetch_responseBroken out for ( slightly ) easier reading : Here 's XRDS for the user ( since discovery seems ok ) .If you dig into TypePad 's html , you find the following error message ... which is why I use them as an example . Kind of useless , but its something.This code is very heavily based on the example MVC project that ships with dotNetOpenAuth , the SendAssertion implementation is where I suspect things are getting ill.Sorry this is such a huge info dump , but I have n't got a lot to go on and accordingly ca n't really narrow it down to something simple.So I guess the ultimate question is ... any ideas what I 'm doing wrong here ? *OK , there are sort of tests . But nothing says `` ah-ha , this is broken . '' openid-check=1archetype.quickreg=1tos_locale=en_USportal=typepadoic.time=1303249620-9db5665031c9c6b36031openid.claimed_id=https : //example/user/8c481fb7-1b5c-4e50-86b5-xxxxxxxxxopenid.identity=https : //example/user/8c481fb7-1b5c-4e50-86b5-xxxxxxxxxopenid.sig=hoaxQrsN4BBg6H8kp50NoQwpHmcO96BBe+jB3oOP2UA=openid.signed=claimed_id , identity , assoc_handle , op_endpoint , return_to , response_nonce , ns.alias3 , alias3.modeopenid.assoc_handle= { 634388464235195799 } { oqMrOA== } { 32 } openid.op_endpoint=https : //example/openid/provideropenid.return_to=https : //www.typepad.com/secure/services/signin/openid ? openid-check=1archetype.quickreg=1tos_locale=en_USportal=typepadoic.time=1303249620-9db5665031c9c6b36031openid.response_nonce=2011-04-19T21:47:03Z1aa4NZ48openid.mode=id_resopenid.ns=http : //specs.openid.net/auth/2.0openid.ns.alias3=http : //openid.net/srv/ax/1.0openid.alias3.mode=fetch_response < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < xrds : XRDSxmlns : xrds= '' xri : // $ xrds '' xmlns : openid= '' http : //openid.net/xmlns/1.0 '' xmlns= '' xri : // $ xrd* ( $ v*2.0 ) '' > < XRD > < Service priority= '' 10 '' > < Type > http : //specs.openid.net/auth/2.0/signon < /Type > < LocalID > https : //example/user/8c481fb7-1b5c-4e50-86b5-xxxxxxxxx < /LocalID > < Type > http : //openid.net/extensions/sreg/1.1 < /Type > < Type > http : //axschema.org/contact/email < /Type > < URI > https : //example/openid/provider < /URI > < /Service > < Service priority= '' 20 '' > < Type > http : //openid.net/signon/1.0 < /Type > < Type > http : //openid.net/extensions/sreg/1.1 < /Type > < Type > http : //axschema.org/contact/email < /Type > < URI > https : //example/openid/provider < /URI > < /Service > < /XRD > < /xrds : XRDS > < ! -- Error Code : unexpected_url_redirect -- > protected ActionResult SendAssertion ( IAuthenticationRequest authReq ) { // Not shown : redirect to a prompt if needed if ( authReq.IsDirectedIdentity ) { authReq.LocalIdentifier = Current.LoggedInUser.GetClaimedIdentifier ( ) ; } if ( ! authReq.IsDelegatedIdentifier ) { authReq.ClaimedIdentifier = authReq.LocalIdentifier ; } authReq.IsAuthenticated = this.UserControlsIdentifier ( authReq ) ; if ( authReq.IsAuthenticated.Value ) { // User can setup an alias , but we do n't actually want relying parties to store that since it can change over time authReq.ClaimedIdentifier = Current.LoggedInUser.GetClaimedIdentifier ( ) ; authReq.LocalIdentifier = Current.LoggedInUser.GetClaimedIdentifier ( ) ; // Not shown : responding to AX and SREG requests } var req = OpenIdProvider.PrepareResponse ( authReq ) ; var ret = req.AsActionResult ( ) ; return ret ; }",Nearly all OpenId relying parties reject assertions from my dotNetOpenAuth backed provider "C_sharp : I 've two comboBoxes one above another . The problem appear if you open the form that contain this comboBoxes and avoid mouse over at lower comboBox , you just click on first comboBox and from drop down list choose item that is located right over the second comboBox . Once you click on an item the drop down list will close but your mouse will remain over the second comboBox . But this comboBox will not highlight and react on your clicks at all . Take a look at this picture please : Both comboBoxes IsEditable = false ; But if you move your mouse out of the 2nd comboBox and back over to it - everything will works fine . Help me please how to fix this.UPD . XAML : < ComboBox Background= '' { x : Null } '' Height= '' 33 '' HorizontalAlignment= '' Left '' IsEditable= '' False '' IsEnabled= '' True '' Margin= '' 10,151,0,0 '' Name= '' comboBox2 '' VerticalAlignment= '' Top '' Width= '' 239 '' VerticalContentAlignment= '' Center '' FontSize= '' 14 '' IsReadOnly= '' False '' Text= '' '' SelectionChanged= '' comboBox2_SelectionChanged '' TabIndex= '' 6 '' HorizontalContentAlignment= '' Left '' Padding= '' 10,3 '' FontWeight= '' SemiBold '' AllowDrop= '' False '' Cursor= '' Hand '' IsTabStop= '' True '' / > < ComboBox Background= '' { x : Null } '' FontSize= '' 14 '' Height= '' 33 '' HorizontalAlignment= '' Left '' IsEditable= '' False '' IsEnabled= '' True '' Margin= '' 10,190,0,0 '' Name= '' comboBox3 '' VerticalAlignment= '' Top '' VerticalContentAlignment= '' Center '' Width= '' 439 '' IsReadOnly= '' False '' Text= '' '' SelectionChanged= '' comboBox3_SelectionChanged '' TabIndex= '' 8 '' HorizontalContentAlignment= '' Left '' Padding= '' 10,3 '' FontWeight= '' SemiBold '' ClipToBounds= '' False '' Cursor= '' Hand '' IsHitTestVisible= '' True '' SnapsToDevicePixels= '' True '' UseLayoutRounding= '' True '' / >",C # WPF comboBox strange issue "C_sharp : I am using Topshelf to create a Windows Service . This service will attempt recovery the first 3 failures , but after that , it no longer work.Inspecting the service in Services on the host reveals : The service recovery code looks like this : Inspecting the Event Log shows the following messages after failed recovery : As is evident from the above . The fourth time does not trigger recovery.Is this a Windows error , a Topshelf issue , or is there something wrong in my configuration ? First Failure : Restart the ServiceSecond Failure : Restart the ServiceSubsequent Failures : Restart the ServiceReset fail count after : 1 daysRestart service after : 2 minutes f.EnableServiceRecovery ( r = > { r.RestartService ( 2 ) ; r.RestartService ( 5 ) ; r.RestartService ( 5 ) ; r.OnCrashOnly ( ) ; r.SetResetPeriod ( 1 ) ; } ) ; The MyService service terminated unexpectedly . It has done this 1 time ( s ) . The following corrective action will be taken in 120000 milliseconds : Restart the service.The MyService service terminated unexpectedly . It has done this 2 time ( s ) . The following corrective action will be taken in 300000 milliseconds : Restart the service.The MyService service terminated unexpectedly . It has done this 3 time ( s ) . The following corrective action will be taken in 300000 milliseconds : Restart the service.The MyService service terminated unexpectedly . It has done this 4 time ( s ) .",Topshelf halts service recovery after third attempt "C_sharp : I 'm using XDocument to update the XML file with Isolated Storage . However , after save the updated XML file , some extra characters are added automatically.Here is my XML file before update : Then after the file is updated and saved , it becomes : I 've spent a lot of time trying to find and fix the problem but no solutions were found . The solution in the post xdocument save adding extra characters can not help me fix my problem.Here 's my C # code : < inventories > < inventory > < id > I001 < /id > < brand > Apple < /brand > < product > iPhone 5S < /product > < price > 750 < /price > < description > The newest iPhone < /description > < barcode > 1234567 < /barcode > < quantity > 75 < /quantity > < inventory > < /inventories > < inventories > < inventory > < id > I001 < /id > < brand > Apple < /brand > < product > iPhone 5S < /product > < price > 750 < /price > < description > The best iPhone < /description > < barcode > 1234567 < /barcode > < quantity > 7 < /quantity > < inventory > < /inventories > ies > private void UpdateInventory ( string id ) { using ( IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication ( ) ) { using ( IsolatedStorageFileStream stream = isf.OpenFile ( `` inventories.xml '' , FileMode.OpenOrCreate , FileAccess.ReadWrite ) ) { XDocument doc = XDocument.Load ( stream ) ; var item = from c in doc.Descendants ( `` inventory '' ) where c.Element ( `` id '' ) .Value == id select c ; foreach ( XElement e in item ) { e.Element ( `` price '' ) .SetValue ( txtPrice.Text ) ; e.Element ( `` description '' ) .SetValue ( txtDescription.Text ) ; e.Element ( `` quantity '' ) .SetValue ( txtQuantity.Text ) ; } stream.Position = 0 ; doc.Save ( stream ) ; stream.Close ( ) ; NavigationService.Navigate ( new Uri ( `` /MainPage.xaml '' , UriKind.Relative ) ) ; } } }",Extra characters in XML file after XDocument Save "C_sharp : I have the following code : Where weight is a Func < T , double > .The problem is I want weight to be executed as few times as possible . This means it should be executed at most once for each item . I could achieve this by saving it to an array . However , if any weight returns a negative value , I do n't want to continue execution.Is there any way to accomplish this easily within the LINQ framework ? IEnumerable < KeyValuePair < T , double > > items = sequence.Select ( item = > new KeyValuePair < T , double > ( item , weight ( item ) ) ) ; if ( items.Any ( pair = > pair.Value < 0 ) ) throw new ArgumentException ( `` Item weights can not be less than zero . `` ) ; double sum = items.Sum ( pair = > pair.Value ) ; foreach ( KeyValuePair < T , double > pair in items ) { ... }",Can I cache partially-executed LINQ queries ? "C_sharp : I am trying to find an elegant implementation of the Execute ( .. ) method below that takes in a lambda expression . Is what I 'm trying to do even possible ? It seems like I should be able to because the compiler will allow me to pass such a lambda expression ( in the form of an Action ) . How would you implement the Execute method above given these specifications ? static void Main ( string [ ] args ) { // This should execute SomeOperation ( ) synchronously Execute ( ( ) = > SomeOperation ( ) ) ; // This should begin execution of SomeOperationAsync ( ) , but not wait ( fire and forget ) Execute ( ( ) = > SomeOperationAsync ( ) ) ; // This should await the execution of SomeOperationAsync ( ) ( execute synchronously ) Execute ( async ( ) = > await SomeOperationAsync ( ) ) ; }",Execution of C # Lambda expressions based on async annotations "C_sharp : I want to write a RavenDB query that filters by a value if it is available , but if that value is not available , I want it to return all objects . For example , in linq to objects , I can do something like this : But the following will not work : Because userEntry is not an indexed value , this throws an exception.How can I accomplish this ? var matches = people.Where ( x = > x.LastName == userEntry || userEntry == string.Empty ) .ToList ( ) ; var matches = RavenSession.Query < Person > ( ) .Where ( x = > x.LastName == userEntry || userEntry == string.Empty ) .ToList ( ) ;",RavenDB - Optional where clause "C_sharp : Why I get a compiler error here : and not here , if I 'm performing the same operation : I 'm learning the usage of checked and the MSDN web site does n't clear why the OverflowException is raised in the first code snippet : By default , an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type . If the expression contains one or more non-constant values , the compiler does not detect the overflow.It only explains the behavior but not the reasons for that behavior . I 'd like to know what happens under the hood . int a = 2147483647 + 10 ; int ten = 10 ; int b = 2147483647 + ten ;",Integer overflow exception "C_sharp : I 'm developing a blog application shared by non-profit organizations . I want each organization to be able to change their own blog settings . I have taken a singleton pattern ( from BlogEngine.net ) and modified it . ( I understand that it is no longer a singleton pattern . ) I have tested this approach and it seems to work fine in a development environment . Is this pattern a good practice ? Are there issues , which may arise when this is placed in a production environment ? ( Portions of code were omitted for brevity . ) Thanks for any help , comment , etc . public class UserBlogSettings { private UserBlogSettings ( ) { Load ( ) ; } public static UserBlogSettings Instance { get { string cacheKey = `` UserBlogSettings- '' + HttpContext.Current.Session [ `` userOrgName '' ] .ToString ( ) ; object cacheItem = HttpRuntime.Cache [ cacheKey ] as UserBlogSettings ; if ( cacheItem == null ) { cacheItem = new UserBlogSettings ( ) ; HttpRuntime.Cache.Insert ( cacheKey , cacheItem , null , DateTime.Now.AddMinutes ( 1 ) , Cache.NoSlidingExpiration ) ; } return ( UserBlogSettings ) cacheItem ; } } }",Is this modified C # singleton pattern a good practice ? "C_sharp : I have a service which is consuming an SMS REST API using HttpClient : The API returns an error , but I would like to be able to log it . So I need to log both the failing status code ( which I can read from response.StatusCode ) and the associated content ( which may contain additional error useful details ) .This code fails on the instruction await response.Content.ReadAsStringAsync ( ) with this exception : System.ObjectDisposedException : Can not access a disposed object . Object name : 'System.Net.Http.HttpConnection+HttpConnectionResponseContent ' . Module `` System.Net.Http.HttpContent '' , in CheckDisposed Module `` System.Net.Http.HttpContent '' , in ReadAsStringAsyncSome sources suggest that you should n't read the response content when the status code is not in the success range ( 200-299 ) , but what if the response really contains useful error details ? .NET version used : .NET Core 2.1.12 on AWS lambda linux runtime . HttpClient http = this._httpClientFactory.CreateClient ( ) ; // Skipped : setup HttpRequestMessageusing ( HttpResponseMessage response = await http.SendAsync ( request ) ) { try { _ = response.EnsureSuccessStatusCode ( ) ; } catch ( HttpRequestException ) { string responseString = await response.Content.ReadAsStringAsync ( ) ; // Fails with ObjectDisposedException this._logger.LogInformation ( `` Received invalid HTTP response status ' { 0 } ' from SMS API . Response content was { 1 } . `` , ( int ) response.StatusCode , responseString ) ; throw ; } }",Ca n't read HttpResponseMessage content when the status code is not success "C_sharp : I 'd like to make some operations according to a given collection type ( using reflexion ) , regardless of the generic type.Here is my code : It works for now , but it gets obvious to me that it 's not the most safe solution.I tried that too , it actualy compiles but does n't work ... I also tried to test all interfaces of the given collection type , but it implies an exclusivity for interfaces in collections ... I hope I made myself clear , my english lack of training : ) void MyFct ( Type a_type ) { // Check if it 's type of List < > if ( a_type.Name == `` List ` 1 '' ) { // Do stuff } // Check if it 's type of Dictionary < , > else if ( a_type.Name == `` Dictionary ` 2 '' ) { // Do stuff } } void MyFct ( Type a_type ) { // Check if it 's type of List < > if ( a_type == typeof ( List < > ) ) { // Do stuff } // Check if it 's type of Dictionary < , > else if ( a_type == typeof ( Dictionary < , > ) ) { // Do stuff } }",Generic collections type test "C_sharp : I was playing with async / await when I came across the following : I expected the result to be `` 12345 '' , but it was `` 1235 '' . Somehow ' 4 ' was eaten up.If I split Line X into : Then the expected `` 12345 '' results.Why is it so ? ( Using VS2012 ) class C { private static string str ; private static async Task < int > FooAsync ( ) { str += `` 2 '' ; await Task.Delay ( 100 ) ; str += `` 4 '' ; return 5 ; } private static void Main ( string [ ] args ) { str = `` 1 '' ; var t = FooAsync ( ) ; str += `` 3 '' ; str += t.Result ; // Line X Console.WriteLine ( str ) ; } } int i = t.Result ; str += i ;",Task < T > .Result and string concatenation "C_sharp : Reading a book : NHibernate 3 : Beginners guide I found a fragment that made me curious : Time for action – Creating a base entity ( ... ) Add a new class to the folder Domain of the project and call it Entity . Make the class abstract and generic in T. Your code should look similar to the following code snippet : My question is : what is the point of the fragment where T : Entity < T > ? I understand that the where section can be applied to add constraints on the type T , but the code above looks like it would be never possible to instantiate such class ( if it were n't abstract anyway ) . using System ; namespace OrderingSystem.Domain { public abstract class Entity < T > where T : Entity < T > { } }",C # generics : what 's the point of the `` X < T > where T : X < T > '' generic type constraint ? "C_sharp : I 'm getting an Org.BouncyCastle.Security.InvalidKeyException with error message Public key presented not for certificate signature when validating a pdf with LtvVerifier.This problem has arisen after circumventing an issue with CRL LDAP URIs . The code used to perform the verification is the same as the previous post : Auxiliary function that builds a List of X509Certificates from the certificate chain : A custom verifier , just copied from sample : I have re-implemented LtvVerifier and CrlVerifier as explained in the previous question . The CRL validation is done ok . The certificate chain includes the certificate that was used to sign the PDF and the CA root certificate . The function CrlVerifier.Verify is throwing the mentioned exception when calling the next line : And this is the relevant stack trace of Org.BouncyCastle.Security.InvalidKeyException : And a link to the pdf that I try to validate public static bool Validate ( byte [ ] pdfIn , X509Certificate2 cert ) { using ( var reader = new PdfReader ( pdfIn ) ) { var fields = reader.AcroFields ; var signames = fields.GetSignatureNames ( ) ; if ( ! signames.Any ( n = > fields.SignatureCoversWholeDocument ( n ) ) ) throw new Exception ( `` None signature covers all document '' ) ; var verifications = signames.Select ( n = > fields.VerifySignature ( n ) ) ; var invalidSignature = verifications.Where ( v = > ! v.Verify ( ) ) ; var invalidTimeStamp = verifications.Where ( v = > ! v.VerifyTimestampImprint ( ) ) ; if ( invalidSignature.Any ( ) ) throw new Exception ( `` Invalid signature found '' ) ; } using ( var reader = new PdfReader ( pdfIn ) ) { var ltvVerifier = new LtvVerifier ( reader ) { OnlineCheckingAllowed = false , CertificateOption = LtvVerification.CertificateOption.WHOLE_CHAIN , Certificates = GetChain ( cert ) .ToList ( ) , VerifyRootCertificate = false , Verifier = new MyVerifier ( null ) } ; var ltvResult = new List < VerificationOK > { } ; ltvVerifier.Verify ( ltvResult ) ; if ( ! ltvResult.Any ( ) ) throw new Exception ( `` Ltv verification failed '' ) ; } return true ; } private static X509.X509Certificate [ ] GetChain ( X509Certificate2 myCert ) { var x509Chain = new X509Chain ( ) ; x509Chain.Build ( myCert ) ; var chain = new List < X509.X509Certificate > ( ) ; foreach ( var cert in x509Chain.ChainElements ) { chain.Add ( DotNetUtilities.FromX509Certificate ( cert.Certificate ) ) ; } return chain.ToArray ( ) ; } class MyVerifier : CertificateVerifier { public MyVerifier ( CertificateVerifier verifier ) : base ( verifier ) { } override public List < VerificationOK > Verify ( X509.X509Certificate signCert , X509.X509Certificate issuerCert , DateTime signDate ) { Console.WriteLine ( signCert.SubjectDN + `` : ALL VERIFICATIONS DONE '' ) ; return new List < VerificationOK > ( ) ; } } if ( verifier ! = null ) result.AddRange ( verifier.Verify ( signCert , issuerCert , signDate ) ) ; // verify using the previous verifier in the chain ( if any ) return result ; in Org.BouncyCastle.X509.X509Certificate.CheckSignature ( AsymmetricKeyParameter publicKey , ISigner signature ) in Org.BouncyCastle.X509.X509Certificate.Verify ( AsymmetricKeyParameter key ) in iTextSharp.text.pdf.security.CertificateVerifier.Verify ( X509Certificate signCert , X509Certificate issuerCert , DateTime signDate ) in iTextSharp.text.pdf.security.RootStoreVerifier.Verify ( X509Certificate signCert , X509Certificate issuerCert , DateTime signDate ) in PdfCommon.CrlVerifierSkippingLdap.Verify ( X509Certificate signCert , X509Certificate issuerCert , DateTime signDate ) in c : \Projects\digit\Fuentes\PdfCommon\CrlVerifierSkippingLdap.cs : line 76 in iTextSharp.text.pdf.security.OcspVerifier.Verify ( X509Certificate signCert , X509Certificate issuerCert , DateTime signDate ) in PdfCommon.LtvVerifierSkippingLdap.Verify ( X509Certificate signCert , X509Certificate issuerCert , DateTime sigDate ) in c : \Projects\digit\Fuentes\PdfCommon\LtvVerifierSkippingLdap.cs : line 221 in PdfCommon.LtvVerifierSkippingLdap.VerifySignature ( ) in c : \Projects\digit\Fuentes\PdfCommon\LtvVerifierSkippingLdap.cs : line 148 in PdfCommon.LtvVerifierSkippingLdap.Verify ( List ` 1 result ) in c : \Projects\digit\Fuentes\PdfCommon\LtvVerifierSkippingLdap.cs : line 112",Pades LTV verification in iTextSharp throws Public key presented not for certificate signature for root CA certificate "C_sharp : I created button with style but after creating button style it looses default effect of the button and when I directly put attribute in button than I will get those default effects like when I click I can see blue background.I also try to put Visual Manager but it is not working . Kindly somebody can help me to know what I am doing wrongMy Button Style : I also change in VisualStateManager like thisMy Button Tag < Style TargetType= '' Button '' x : Key= '' MenuButtonStyle '' > < Setter Property= '' HorizontalAlignment '' Value= '' Stretch '' / > < Setter Property= '' Foreground '' Value= '' Black '' / > < Setter Property= '' FontFamily '' Value= '' Sitka Heading '' / > < Setter Property= '' FontSize '' Value= '' 20 '' / > < Setter Property= '' Template '' > < Setter.Value > < ControlTemplate TargetType= '' Button '' > < Grid > < VisualStateManager.VisualStateGroups > < VisualStateGroup x : Name= '' CommonStates '' > < VisualState x : Name= '' Normal '' / > < VisualState x : Name= '' Pressed '' > < Storyboard > < ColorAnimation Duration= '' 0 '' Storyboard.TargetName= '' ButtonTextElement '' Storyboard.TargetProperty= '' ( TextBlock.Foreground ) . ( SolidColorBrush.Color ) '' To= '' Blue '' / > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' ( UIElement.Visibility ) '' Storyboard.TargetName= '' normalImage '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' > < DiscreteObjectKeyFrame.Value > < Visibility > Collapsed < /Visibility > < /DiscreteObjectKeyFrame.Value > < /DiscreteObjectKeyFrame > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' ( UIElement.Visibility ) '' Storyboard.TargetName= '' mouseOverImage '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' > < DiscreteObjectKeyFrame.Value > < Visibility > Visible < /Visibility > < /DiscreteObjectKeyFrame.Value > < /DiscreteObjectKeyFrame > < /ObjectAnimationUsingKeyFrames > < /Storyboard > < /VisualState > < VisualState x : Name= '' MouseOver '' > < Storyboard > < ColorAnimation Duration= '' 0 '' Storyboard.TargetName= '' ButtonTextElement '' Storyboard.TargetProperty= '' ( TextBlock.Foreground ) . ( SolidColorBrush.Color ) '' To= '' Blue '' / > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' ( UIElement.Visibility ) '' Storyboard.TargetName= '' normalImage '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' > < DiscreteObjectKeyFrame.Value > < Visibility > Collapsed < /Visibility > < /DiscreteObjectKeyFrame.Value > < /DiscreteObjectKeyFrame > < /ObjectAnimationUsingKeyFrames > < ObjectAnimationUsingKeyFrames Storyboard.TargetProperty= '' ( UIElement.Visibility ) '' Storyboard.TargetName= '' mouseOverImage '' > < DiscreteObjectKeyFrame KeyTime= '' 0 '' > < DiscreteObjectKeyFrame.Value > < Visibility > Visible < /Visibility > < /DiscreteObjectKeyFrame.Value > < /DiscreteObjectKeyFrame > < /ObjectAnimationUsingKeyFrames > < /Storyboard > < /VisualState > < /VisualStateGroup > < /VisualStateManager.VisualStateGroups > < Border BorderBrush= '' Black '' BorderThickness= '' 0,0,0,0.5 '' Margin= '' 30,0,0,0 '' Grid.ColumnSpan= '' 2 '' / > < TextBlock x : Name= '' ButtonTextElement '' Text= '' { TemplateBinding Content } '' Margin= '' 30,0 '' Foreground= '' { TemplateBinding Foreground } '' Grid.Column= '' 0 '' VerticalAlignment= '' { TemplateBinding VerticalAlignment } '' / > < Image x : Name= '' normalImage '' Source= '' /Assets/menu-arrow-left.png '' Grid.Column= '' 1 '' Stretch= '' None '' HorizontalAlignment= '' Right '' Margin= '' 0,0,30,0 '' / > < Image x : Name= '' mouseOverImage '' Source= '' /Assets/menu-arrow-left-hover.png '' Grid.Column= '' 1 '' Stretch= '' None '' HorizontalAlignment= '' Right '' Visibility= '' Collapsed '' Margin= '' 0,0,30,0 '' / > < /Grid > < /ControlTemplate > < /Setter.Value > < /Setter > < /Style > < ColorAnimation Storyboard.TargetName= '' MouseOverVisualElement '' Storyboard.TargetProperty= '' TextBlock.Foreground '' To= '' Red '' / > < Button Style= '' { StaticResource MenuButtonStyle } '' Content= '' Home '' / >",Silverlight button Mouse Over like hover effect "C_sharp : I 've been using C # for a while , but recently noticed that the behaviour of one of my unit tests changed depending on which variation of collection initialiser expression I used : var object = new Class { SomeCollection = new List < int > { 1 , 2 , 3 } } ; var object = new Class { SomeCollection = { 1 , 2 , 3 } } ; Up until this point I assumed that the second form was just syntactic sugar and was semantically equivalent to the first form . However , switching between these two forms resulted in my failing unit test passing.The example code below demonstrates this : When I run this , the first assignment works fine but the second results in a NullReferenceException.My gut feeling is that behind the scenes the compiler is treating these two expressions as this : Is that assumption accurate ? void Main ( ) { var foo1 = new Foo { Items = new List < int > { 1 , 2 , 3 } } ; var foo2 = new Foo { Items = { 1 , 2 , 3 } } ; foo1.Dump ( ) ; foo2.Dump ( ) ; } class Foo { public List < int > Items { get ; set ; } } var foo1 = new Foo ( ) ; foo1.Items = new List < int > { 1 , 2 , 3 } ; var foo2 = new Foo ( ) ; foo2.Items.Add ( 1 ) ; foo2.Items.Add ( 2 ) ; foo2.Items.Add ( 3 ) ;",What is the difference between these two variations of collection initialiser expressions ? "C_sharp : I have the following code behind , which works : And I have the code , that I want to have , but it does n't work . Even setter is never invoked : The use of that is in XAML : Why the standard property works and dependency property does n't ? public DataTemplate ItemTemplate { get { return _list.ItemTemplate ; } set { _list.ItemTemplate = value ; } } public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register ( `` ItemTemplate '' , typeof ( DataTemplate ) , typeof ( MyUserControl ) ) ; public DataTemplate ItemTemplate { get { return ( DataTemplate ) GetValue ( ItemTemplateProperty ) ; } set { _list.ItemTemplate = value ; SetValue ( ItemTemplateProperty , value ) ; } } < Window.Resources > < DataTemplate x : Key= '' ItemTemplate '' > < TextBlock Text= '' { Binding Path=Name } '' / > < /DataTemplate > < /Window.Resources > < local : MyUserControl ItemTemplate= '' { StaticResource ItemTemplate } '' / >","Standard property works , but dependency property does n't in WPF" "C_sharp : I have a piece of code that makes the Visual Studio 2008 IDE run very slow , consume vast amounts of memory and then eventually causes it to crash . I suspect VS is hitting an OS memory limit.The following code is not my real application code , but it simulates the problem . Essentially I am trying to find the minimum value within a tree using LINQ.Has anyone else seen something similar ? class LinqTest { public class test { public int val ; public List < test > Tests ; } private void CrashMe ( ) { test t = new test ( ) ; //Uncomment this to cause the problem //var x = t.Tests.Min ( c = > c.Tests.Min ( d = > d.Tests.Min ( e = > e.Tests.Min ( f= > f.Tests.Min ( g= > g.Tests.Min ( h = > h.val ) ) ) ) ) ) ; } }",Nested Linq Min ( ) crashes Visual Studio "C_sharp : This problem is mainly bother some as Visual Studio IDE is telling me that it cant find the resource , but when I build the application I am not having any problem.In my Visual Studio i have this : Here is an example of my Universal App architecture is as Follows : Example.windowsPhoneExample.ShareEventhought i have reference DmBlueBrush in my Style Page like this : In Visual Studio it will tell me that it cant find it , but when I build the application it will find this resource . Have I not reference something correctly for my IDE to work ? I am using Visual Studio 2013 Professional Version 12.0.31101.00 Update 4.Edit 1 : in App.xaml in Shared i Have : - > MainPage.xaml - > Style.xaml- > App.Xaml has Style.xaml referenced < SolidColorBrush x : Key= '' DmBlueBrush '' Color= '' { StaticResource DmBlue } '' / > < Application xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' > < Application.Resources > < ResourceDictionary > < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' Theme/Styles.xaml '' / > < ResourceDictionary Source= '' Theme/Other.xaml '' / > < /ResourceDictionary.MergedDictionaries > < /ResourceDictionary > < /Application.Resources > < /Application >",Visual Studio Universal App Resource is not found when in Shared folder "C_sharp : Based on the following question , I found some odd behaviour of the c # compiler.The following is valid C # : What I do find strange is the compiler 'deconstructing ' the passed delegate.The ILSpy output is as follows : As one can see , it automatically decides to use the Invoke method of the delegate . But why ? As it is , the code is unclear . Do we have a triply-wrapped delegate ( actual ) or is the inner delegate just 'copied ' to the outer ones ( my initial thought ) .Surely if the intent was like the compiler emitted the code , one should have written : Similar to the decompiled code.Can anyone justify the reason for this 'surprising ' transformation ? Update : I can only think of one possible use-case for this ; delegate type conversion . Eg : Perhaps the compiler should emit a warning if the same delegate types are used . static void K ( ) { } static void Main ( ) { var k = new Action ( new Action ( new Action ( K ) ) ) ) ; } new Action ( new Action ( new Action ( null , ldftn ( K ) ) , ldftn ( Invoke ) ) .Invoke ) ; var k = new Action ( new Action ( new Action ( K ) .Invoke ) .Invoke ) ; delegate void Baz ( ) ; delegate void Bar ( ) ; ... var k = new Baz ( new Bar ( new Action ( K ) ) ) ;",C # compiler oddity with delegate constructors "C_sharp : I 'm browsing the source code of StyleCop , and I found a curious thing : What is this thing ? Is it just a simple field where at-sign is used to indicate that it is a field , and not a namespace keyword ? If so , may at-sign be used for any reserved word ( for example @ dynamic , @ using , etc . ) ? /// < summary > /// The namespace that the rule is contained within./// < /summary > private string @ namespace ; // [ ... ] internal Rule ( string name , string @ namespace , string checkId , string context , bool warning ) : this ( name , @ namespace , checkId , context , warning , string.Empty , null , true , false ) { Param.Ignore ( name , @ namespace , checkId , context , warning ) ; }",What is @ namespace field in C # class ? C_sharp : I 'm trying to run the following code : I expected that the Exception would be caught in the following location : But this is not happening . Why is this so ? class Program { static void Main ( string [ ] args ) { var task = Task.Factory.StartNew ( ( ) = > { throw new ApplicationException ( `` message '' ) ; } ) ; try { task.ContinueWith ( t = > Console.WriteLine ( `` End '' ) ) ; } catch ( AggregateException aex ) { Console.Write ( aex.InnerException.Message ) ; } } } catch ( AggregateException aex ) { Console.Write ( aex.InnerException.Message ) ; },Why is this exception not caught ? C_sharp : I had a project in vb.net that used XML Literals to process large blocks of SQL like so : But cant seem to find its equivalent for C # Any suggestions ? Dim SQL As String = < a > Use testalter table BarFoo alter column CouponName nvarchar ( 328 ) alter table Foo alter column IngredientName nvarchar ( 328 ) alter table Bar alter column IngredientShortDescription nvarchar ( 328 ) alter table FooBar alter column ItemName nvarchar ( 328 ) < /a > .Value,How to achieve multi-line strings in C # ; an alternative to VB 's XML Literals ? "C_sharp : In our codebase , we have a battery of custom error checking functions ( like those listed here ) to check arguments less verbosely . For example , to check an argument for null I use : The one disadvantage of this approach is that R # gives the warning `` possible NullReferenceException '' on future uses of the value because it 's not smart enough to detect this as a null check ( or at least something that would fail if theArgument were null ) . Is there any way to indicate that this method checks against the argument being null ? For example , when I try to run a static extension like Select ( ) on such a value , R # warns me of 'possible null assignment to entity marked with NotNull attribute ' , but I ca n't find any documentation of such an attribute nor do I see it in the reference source for Enumerable.Select ( ) . Throw.IfNull ( theArgument , `` theArgument '' ) ;",How to indicate to R # that a function checks a variable for null "C_sharp : I am trying to make the selected text visible in a text box control after I found the text via a search box.I tried the following code : ScrollToCaret method scrolls to the end of the selected text or the last line of the selected text . So if it spans to multiple lines and the height of this part is bigger than the height of textbox , part of the selected text may remain invisible.Please notice I ca n't set the caret to the selection start too because I will loose highlight on the selected text.How can I make sure the selected text is visible or in other words scroll to the first line of the selected text while keeping it highlighted ? String searchText = `` multiple lines of text . `` ; int position = textBox.Text.IndexOf ( searchText ) ; textBox.SelectionStart = position ; textBox.SelectionLength = searchText.Length ; textBox.ScrollToCaret ( ) ; // caret is at the end of the selected text","` ScrollToCaret ` scrolls to the end of the selected text , how can I scroll to the begining of it ?" "C_sharp : I 'm trying to make a simple feet to meter converter , but this happens : This is the code I have currently . At first , feet & meter were int , but I could n't divide an int by 3.281 . I changed them to decimals and now I have this error : Error CS0019 Operator '/ ' can not be applied to operands of type 'decimal ' and 'double'If I ca n't divide decimals by ints , and if I ca n't use the / symbol on decimals , how am I supposed to divide by decimals ? using System ; using System.Windows ; using System.Windows.Controls ; namespace CoolConversion { /// < summary > /// Interaction logic for MainWindow.xaml /// < /summary > public partial class MainWindow : Window { decimal feet ; decimal meter ; public MainWindow ( ) { InitializeComponent ( ) ; } private void TextBox_TextChanged ( object sender , TextChangedEventArgs e ) { feet = Convert.ToDecimal ( Feet.Text ) ; meter = feet / 3.281 ; } } }",Feet to Meter Converter in C # is broken ? "C_sharp : I 've been going over and over this in my head , and I ca n't seem to come up with a good reason why C # closures are mutable . It just seems like a good way to get some unintended consequences if you are n't aware of exactly what 's happening.Maybe someone who is a little more knowledgeable can shed some light on why the designers of C # would allow state to change in a closure ? Example : This will print `` hello '' for the first call , but the outside state changes for the second call , printing `` goodbye . '' The closure 's state was updated to reflect the changes to the local variable . var foo = `` hello '' ; Action bar = ( ) = > Console.WriteLine ( foo ) ; bar ( ) ; foo = `` goodbye '' ; bar ( ) ;",Are there any good reasons why closures are n't immutable in C # ? "C_sharp : First off , I know this question can be answered with a simple response that an empty string is not a null value . In addition , I only recently discovered the cast operators earlier in the year via another stackoverflow question and do n't have a ton of experience with them . Even still , the reason why it 's not entirely that simple is these cast operators when combined with the null coalescing operator , are billed as an elegant solution to dealing with error conditions like missing elements or attributes in LINQ expressions . I started using the approach described by ScottH in `` Improving LINQ Code Smell ... '' and by ScottGu `` Null coalescing operator ( and using it with LINQ ) '' as a way to guard against invalid/missing data in a concise and semi-elegant fashion . From what I can gather that seems to be one of the motivations for putting all the cast overloads in the LINQ classes in the first place.So , in my mind the use case of dealing with a missing value is n't all that different than dealing with an empty one and in the linked articles , this approach is billed as a good way to go about dealing with such situations.Scenario : If the @ Length attribute is missing , the cast results in a null value and the ? ? operator returns 0 ; If the @ Length attribute exists but is empty the cast internally branches on int.tryparse and throws a format exception . Of course for my usage , I wish it would n't and would simply return null so I could continue using this approach in my already somewhat convoluted LINQ code.Ultimately it 's not so much that I ca n't come up with a solution but more so that I 'm interested to hear if there 's an obvious approach that I 've missed or if it anyone has a good perspective on why the missing value scenario was addressed but empty value scenario was not.EditIt seems there 's a few key points I should try and highlight : The linked articles are from MS staff that I admire and look to for guidance . These articles seem to propose ( or at least call attention to ) an improved/alternate approach for dealing with optional valuesIn my case optional values sometimes come in the form of missing elements or attributes but also come in the form of empty elements or valuesThe described approach works as expected for missing values but fails for empty valuesCode that follows the described approach appears to be guarding against the lack of optional values but in fact is fragile and breaks in a particular case . It 's the appearance of protection when in fact you 're still at risk that concerns meThis can be highlighted by stating that both linked examples fail with a runtime exception if the target element exists but is emptyFinally , it seems the key takeaway is the described approach works great when you have a contract in place ( possibly via schema ) which ensures the element or attribute will never be empty but in cases where that contract does not exist , this approach is invalid and an alternate is needed int length = ( int ? ) elem.Attribute ( `` Length '' ) ? ? 0 ;",Why do the nullable explicit cast LINQ operators throw invalid format exceptions on empty values ? "C_sharp : I am using an IEnumerable extension to loop through a collection and also get its index : The ForEach extension is the following : But when I try to compile it I get the following error message : Argument 1 : can not convert from 'void ' to 'System.Web.WebPages.HelperResult'How can I solve this ? Do I need a new extension ? @ Model.ForEach ( ( card , i ) = > { @ < li class= '' c @ ( i ) '' > @ card.Text < /li > ; } ) public static void ForEach < T > ( this IEnumerable < T > source , Action < T , Int32 > action ) { Int32 i = 0 ; foreach ( T item in source ) { action ( item , i ) ; i++ ; } } // ForEach",Use ForEach extension in Razor "C_sharp : Can anyone see what I 'm doing wrong here ? The Assert.IsTrue ( parses ) always fails.I have also tried it thus , with the same result : [ TestMethod ] public void Can_Parse_To_DateTime ( ) { DateTime expected = new DateTime ( 2011 , 10 , 19 , 16 , 01 , 59 ) ; DateTime actual ; string value = `` Wed Oct 19 16:01:59 PDT 2011 '' ; string mask = `` ddd MMM dd HH : mm : ss xxx YYYY '' ; bool parses = DateTime.TryParseExact ( value , mask , CultureInfo.InvariantCulture , DateTimeStyles.None , out actual ) ; Assert.IsTrue ( parses ) ; Assert.AreEqual ( expected , actual ) ; } [ TestMethod ] public void parsing ( ) { DateTime expected = new DateTime ( 2011 , 10 , 19 , 16 , 01 , 59 ) ; DateTime actual ; string value = `` Wed Oct 19 16:01:59 PDT 2011 '' ; string mask = `` ddd MMM dd HH : mm : ss YYYY '' ; // note removal of `` xxx `` value = value.Remove ( 20 , 4 ) ; // removal of the `` PDT `` bool parses = DateTime.TryParseExact ( value , mask , CultureInfo.InvariantCulture , DateTimeStyles.None , out actual ) ; Assert.IsTrue ( parses ) ; Assert.AreEqual ( expected , actual ) ; }",Why does this DateTime parse always fail ? "C_sharp : i have this method in my data access class and i have a unit test to make sure it does work properly , but my test does n't test the exception so my question is should i create a new test to force the exception to be raised or should i just trust that the catch block will work just fine in case of an exception ? is it worth the effort ? here is an example : public void UpdateProject ( Project project ) { using ( var transaction = _session.BeginTransaction ( ) ) { try { _session.Update ( project ) ; _session.Flush ( ) ; transaction.Commit ( ) ; } catch ( HibernateException ) { transaction.Rollback ( ) ; throw ; } } }",Should I force exceptions to test them ? C_sharp : With : Why can I do ( compile ) : but not : var Foo = new [ ] { new { Something = 321 } } ; Console.WriteLine ( Foo [ 0 ] .Something ) ; Foo.ForEach ( x = > Console.WriteLine ( x.Something ) ) ;,"Anonymous Type , Enumerator and Lambda expression" "C_sharp : I am not looking to improve performance or memory usage , this question was purely sparked from curiosity.Main QuestionGiven the following class will the C # compiler ( Mono + .NET ) pack the two short variables into 4 bytes or will they consume 8 bytes ( with alignment ) ? Secondary QuestionIf the answer to the above question was not 4 bytes , would the following alternative offer any advantages ( where SomeClass is used in very large quantities ) : public class SomeClass { short a ; short b ; } // Warning , my bit math might not be entirely accurate ! public class SomeClass { private int _ab ; public short a { get { return _ab & 0x00ff ; } set { _ab |= value & 0x00ff ; } public short b { get { return _ab > > 8 ; } set { _ab |= value < < 8 ; } } }",How are small data types packed in C # "C_sharp : I 've got a strange problem regarding linq-to-sql , and i 've really tried search around for it . Im designing a sql database and where have just recently tried to retrieve an object from it . The problem is with multiple joins . All my tables use identity-columns as primary keys.Db designed as followed : MasterTable : Id ( primary key , identity column , int ) , MasterColumn1 ( nvarchar ( 50 ) ) Slave1 : Id ( primary key , identity column , int ) , MasterId ( int , primary key - > MasterTable Id ) , SlaveCol1Slave2 : Id ( primary key , identity column , int ) , MasterId ( int , primary key - > MasterTable Id ) , SlaveColumn2code used : And the log is : Why oh why does it not do two outer joins instead ? I really care about this because I have a much larger db with many tables referring to the one and the same table ( all have one-to-many relation ) and having 20 selects round-trips to databaseserver is not optimal ! As i side-note . I can produce wanted result by using explicit outer-joins like so : But i want to use the references Linq-To-Sql provides and not manual joins ! How ? -- -- -- -- -- - edit -- -- -- -- -- -- -- -- -I 've also tried prefetching like this : same result = ( var db = new TestDbDataContext ( ) { Log = Console.Out } ; var res = from f in db.MasterTables where f.MasterColumn1 == `` wtf '' select new { f.Id , SlaveCols1 = f.Slave1s.Select ( s = > s.SlaveCol1 ) , SlaveCols2 = f.Slave2s.Select ( s = > s.SlaveColumn2 ) } ; foreach ( var re in res ) { Console.Out.WriteLine ( re.Id + `` `` + string.Join ( `` , `` , re.SlaveCols1.ToArray ( ) ) + `` `` + string.Join ( `` , `` , re.SlaveCols2.ToArray ( ) ) ) ; } SELECT [ t0 ] . [ Id ] , [ t1 ] . [ SlaveCol1 ] , ( SELECT COUNT ( * ) FROM [ FR ] . [ Slave1 ] AS [ t2 ] WHERE [ t2 ] . [ MasterId ] = [ t0 ] . [ Id ] ) AS [ value ] FROM [ FR ] . [ MasterTable ] AS [ t0 ] LEFT OUTER JOIN [ FR ] . [ Slave1 ] AS [ t1 ] ON [ t1 ] . [ MasterId ] = [ t0 ] . [ Id ] WHERE [ t0 ] . [ MasterColumn1 ] = @ p0ORDER BY [ t0 ] . [ Id ] , [ t1 ] . [ Id ] -- @ p0 : Input NVarChar ( Size = 3 ; Prec = 0 ; Scale = 0 ) [ wtf ] -- Context : SqlProvider ( Sql2008 ) Model : AttributedMetaModel Build : 3.5.30729.5420SELECT [ t0 ] . [ SlaveColumn2 ] FROM [ FR ] . [ Slave2 ] AS [ t0 ] WHERE [ t0 ] . [ MasterId ] = @ x1 -- @ x1 : Input Int ( Size = 0 ; Prec = 0 ; Scale = 0 ) [ 1 ] -- Context : SqlProvider ( Sql2008 ) Model : AttributedMetaModel Build : 3.5.30729.54201 SlaveCol1Wtf SlaveCol2Wtf var db = new TestDbDataContext ( ) { Log = Console.Out } ; var res = from f in db.MasterTables join s1 in db.Slave1s on f.Id equals s1.MasterId into s1Tbl from s1 in s1Tbl.DefaultIfEmpty ( ) join s2 in db.Slave2s on f.Id equals s2.MasterId into s2Tbl from s2 in s2Tbl.DefaultIfEmpty ( ) where f.MasterColumn1 == `` wtf '' select new { f.Id , s1.SlaveCol1 , s2.SlaveColumn2 } ; foreach ( var re in res ) { Console.Out.WriteLine ( re.Id + `` `` + re.SlaveCol1 + `` `` + re.SlaveColumn2 ) ; } using ( new DbConnectionScope ( ) ) { var db = new TestDbDataContext ( ) { Log = Console.Out } ; DataLoadOptions loadOptions = new DataLoadOptions ( ) ; loadOptions.LoadWith < MasterTable > ( c = > c.Slave1s ) ; loadOptions.LoadWith < MasterTable > ( c = > c.Slave2s ) ; db.LoadOptions = loadOptions ; var res = from f in db.MasterTables where f.MasterColumn1 == `` wtf '' select f ; foreach ( var re in res ) { Console.Out.WriteLine ( re.Id + `` `` + string.Join ( `` , `` , re.Slave1s.Select ( s = > s.SlaveCol1 ) .ToArray ( ) ) + `` `` + string.Join ( `` , `` , re.Slave2s.Select ( s = > s.SlaveColumn2 ) .ToArray ( ) ) ) ; } }",Linq-to-sql not producing multiple outer-joins ? "C_sharp : It seems that in many unit tests , the values that parameterize the test are either baked in to the test themselves , or declared in a predetermined way.For example , here is a test taken from nUnit 's unit tests ( EqualsFixture.cs ) : This has the advantage of being deterministic ; if you run the test once , and it fails , it will continue to fail until the code is fixed . However , you end up only testing a limited set of values.I ca n't help but feel like this is a waste , though ; the exact same test is probably run with the exact same parameters hundreds if not thousands of times across the life of a project.What about randomizing as much input to all unit tests as possible , so that each run has a shot of revealing something new ? In the previous example , perhaps : ( If the code expected a string , perhaps a random string known to be valid for the particular function could be used each time ) The benefit would be that the more times you run a test , the much larger set of possible values you know it can handle correctly.Is this useful ? Evil ? Are there drawbacks to this ? Am I completely missing the point of unit testing ? Thank you for your thoughts . [ Test ] public void Int ( ) { int val = 1 ; int expected = val ; int actual = val ; Assert.IsTrue ( expected == actual ) ; Assert.AreEqual ( expected , actual ) ; } [ Test ] public void Int ( ) { Random rnd = new Random ( ) ; int val = rnd.Next ( ) ; int expected = val ; int actual = val ; Console.WriteLine ( `` val is { 0 } '' , val ) ; Assert.IsTrue ( expected == actual ) ; Assert.AreEqual ( expected , actual ) ; }",Nondeterminism in Unit Testing "C_sharp : I am making an application to connect to a local SQL Server database , and I am using the following method to create the connection string and test for exceptions . From my research there should be an exception thrown if the connection can not be opened , but if I pass nonsense credentials or empty strings no exception is thrown . If I pass in correct information I am able to connect and use the connection string to pull in data . With the bad connection string I get an exception later when trying to fill a SqlDataAdapter with the data.Also , with the nonsense connection strings myConnection.State is open when I debug and check that . Is there a problem with my understanding of how the exception catching should work ? Am I correct in thinking that the SqlConnection State should not be open when I am unable to connect to the database because of a bad credentials ? public void connect ( string user , string password , string server , string database ) { connectString = `` user id= '' + user + `` ; '' + `` password= '' + password + `` ; '' + `` server= '' + server + `` ; '' + `` Trusted_Connection=yes ; '' + `` database= '' + database + `` ; '' + `` connection timeout=5 '' ; myConnection = new SqlConnection ( connectString ) ; try { myConnection.Open ( ) ; isConnected = true ; } catch ( SqlException ) { isConnected = false ; } catch ( InvalidOperationException ) { isConnected = false ; } }",No exception when opening SqlConnection in C # "C_sharp : So , this question was just asked on SO : How to handle an `` infinite '' IEnumerable ? My sample code : Can someone please explain why this is lazy evaluated ? I 've looked up this code in Reflector , and I 'm more confused than when I began . Reflector outputs : For the numbers method , and looks to have generated a new type for that expression : This makes no sense to me . I would have assumed it was an infinite loop until I put that code together and executed it myself.EDIT : So I understand now that .Take ( ) can tell the foreach that the enumeration has 'ended ' , when it really has n't , but should n't Numbers ( ) be called in it 's entirety before chaining forward to the Take ( ) ? The Take result is what is actually being enumerated over , correct ? But how is Take executing when Numbers has not fully evaluated ? EDIT2 : So is this just a specific compiler trick enforced by the 'yield ' keyword ? public static void Main ( string [ ] args ) { foreach ( var item in Numbers ( ) .Take ( 10 ) ) Console.WriteLine ( item ) ; Console.ReadKey ( ) ; } public static IEnumerable < int > Numbers ( ) { int x = 0 ; while ( true ) yield return x++ ; } public static IEnumerable < int > Numbers ( ) { return new < Numbers > d__0 ( -2 ) ; } [ DebuggerHidden ] public < Numbers > d__0 ( int < > 1__state ) { this. < > 1__state = < > 1__state ; this. < > l__initialThreadId = Thread.CurrentThread.ManagedThreadId ; }",Can someone please explain this lazy evaluation code ? "C_sharp : I 've got two huge ( > 100000 items ) collections of PathGeometry I need to compare using PathGeometry.Combine something like this : To my surprise PathGeometry is part of the GUI and does use the dispatcher , which sometimes causes problems since my calculations do run in some background thread without GUI using Parallel.ForEach ( ) So I 'm looking for an alternative to PathGeometry which is not connected to the GUI.My figures are quite complex and add a lot of PathFigures to the PathGeometry.Figures.I 'm creating those PathGeometries myself from some bloated government xml files , so it would be no problem to create something else instead . But I need a function to create an intersection of two of these geometries ( not adding them to each other ) to get the area which both geometries cover , such as the red area in this diagram : List < PathGeometry > firstList ; List < PathGeometry > secondList ; [ ... ] foreach ( PathGeometry pg1 in firstList ) foreach ( PathGeometry pg2 in secondList ) { PathGeometry intergeo = PathGeometry.Combine ( pg1 , pg2 , GeometryCombineMode.Intersect , null ) ; if ( intergeo.GetArea ( ) > 0 ) { // do whatever with intergeo.GetArea ( ) } }",non-GUI alternative to PathGeometry ? "C_sharp : Let 's say I have the following generic combination generator static method : Perhaps I am not understanding this correctly , but does n't this build the entire combos list in RAM ? If there are a large number of items the method might cause the computer to run out of RAM . Is there a way to re-write the method to use a yield return on each combo , instead of returning the entire combos set ? public static IEnumerable < IEnumerable < T > > GetAllPossibleCombos < T > ( IEnumerable < IEnumerable < T > > items ) { IEnumerable < IEnumerable < T > > combos = new [ ] { new T [ 0 ] } ; foreach ( var inner in items ) combos = combos.SelectMany ( c = > inner , ( c , i ) = > c.Append ( i ) ) ; return combos ; }",C # how to yield return SelectMany ? "C_sharp : I have a method like the following : I then created a class : I 'd like to be able to callwhere it would use the type of THIS class to pass to the HandleBase . This would in essentially get all HandleBase that have an owner of THIS type.How can I achieve this ? EDIT : I 'm using .NET 2.0 so solutions greater than 2.0 will not work.The idea is to have ControlBase have a collection of other ControlBase for `` children '' . Then they can be queried based on their type with GetControls < T > ( ) . This would allow me to , for example , get all HandleBase for a Shape . Then I can take all of these and set Visible=false or do something else with them . Thus I can manipulate children of a specific type for a collection.HandleBase < TOwner > requires the TOwner since it has a reference to the `` owning type '' . So you can only add anything that extends HandleBase to a Shape . Make sense ? Thanks for all the help ! public IEnumerable < T > GetControls < T > ( ) : where T : ControlBase { // removed . } public class HandleBase < TOwner > : ControlBase : TOwner { // Removed } GetControls < HandleBase < this.GetType ( ) > > ;",C # Pass Generics At Runtime "C_sharp : Throwing this exception : String was not recognized as a valid DateTime . I 'm sure it 's the lack of a leading 0 in the month . What 's the correct format string ? DateTime dt = DateTime.ParseExact ( `` 1122010 '' , `` Mddyyyy '' , System.Globalization.CultureInfo.CurrentCulture ) ;",Parse Simple DateTime "C_sharp : Similar to this question : C # Constructor Design but this question is slight different.I have a class Customer and a class CustomerManager . When an instance is created of the CustomerManager class I want to load all the customers . And this is where I got stuck . I can do this several ways : Load all the customers in the constructor ( I do n't like this one because it can take a while if I have many customers ) In every method of the CustomerManager class that performs database related actions , check the local list of customers is loaded and if not , load the list : Create a method which loads all the customers . This method must be called before calling methods which performs database related actions : In the class : In the form : What is the best way to do this ? EDIT : I have the feeling that I am misunderstood here . Maybe it is because I was n't clear enough . In the CustomerManager class I have several methods which depends on the local list ( _customers ) . So , my question is , where should I fill that list ? public method FindCustomer ( int id ) { if ( _customers == null ) // some code which will load the customers list } public LoadData ( ) { // some code which will load the customers list } CustomerManager manager = new CustomerManager ( ) ; manager.LoadData ( ) ; Customer customer = manager.FindCustomer ( int id ) ;",C # Where to load initial data in an object ? "C_sharp : Is it necessary to flush a Stream after flushing a StreamWriter ? public static async Task WriteStringAsync ( this Stream stream , string messageString ) { var encoding = new UTF8Encoding ( false ) ; //no BOM using ( var streamWriter = new StreamWriter ( stream , encoding ) ) { await streamWriter.WriteAsync ( messageString ) ; await streamWriter.FlushAsync ( ) ; } await stream.FlushAsync ( ) ; //is this necessary ? }",Double flush required ? "C_sharp : I want to have a button in each row of a GridView to perform actions on this row . I 'm able to get the click , but how do I determine which row this button belongs to ? What I have at the moment is this : Is there maybe some way to bind the item on this row to the RoutedEventArgs ? < ListView ItemsSource= '' { Binding Calibrations } '' > < ListView.View > < GridView > < GridView.Columns > < GridViewColumn Header= '' Voltage [ kV ] '' Width= '' 70 '' DisplayMemberBinding= '' { Binding Voltage } '' / > < GridViewColumn Header= '' Filter '' Width= '' 100 '' DisplayMemberBinding= '' { Binding FilterName } '' / > < GridViewColumn Header= '' Calibration Date '' Width= '' 100 '' DisplayMemberBinding= '' { Binding CalibrationDate } '' / > < GridViewColumn Header= '' Calibration '' Width= '' 60 '' > < GridViewColumn.CellTemplate > < DataTemplate > < Button Content= '' Start '' Click= '' OnStart '' / > < /DataTemplate > < /GridViewColumn.CellTemplate > < /GridViewColumn > < /GridView.Columns > < /GridView > < /ListView.View > < /ListView > private void OnStart ( object sender , RoutedEventArgs e ) { // how do I know , on which item this button is }",Button in GridView : How do I know which Item ? "C_sharp : I 'm experimenting with linq and generics . For now , I just implemented a GetAll method which returns all records of the given type.This works fine . Next , I would like to precompile the query : Here , i get the following : What is the problem with this ? I guess the problem is with the result of the execution of the precompiled query , but I am unable to fanthom why . class BaseBL < T > where T : class { public IList < T > GetAll ( ) { using ( TestObjectContext entities = new TestObjectContext ( ... ) ) { var result = from obj in entities.CreateObjectSet < T > ( ) select obj ; return result.ToList ( ) ; } } } class BaseBL < T > where T : class { private readonly Func < ObjectContext , IQueryable < T > > cqGetAll = CompiledQuery.Compile < ObjectContext , IQueryable < T > > ( ( ctx ) = > from obj in ctx.CreateObjectSet < T > ( ) select obj ) ; public IList < T > GetAll ( ) { using ( TestObjectContext entities = new TestObjectContext ( ... ) ) { var result = cqGetAll.Invoke ( entities ) ; return result.ToList ( ) ; } } } base { System.Exception } = { `` LINQ to Entities does not recognize the method'System.Data.Objects.ObjectSet ` 1 [ admin_model.TestEntity ] CreateObjectSet [ TestEntity ] ( ) ' method , and this method can not be translated into a store expression . '' }","Linq-to-entities , Generics and Precompiled Queries" "C_sharp : This is issue about LANGUAGE DESIGN.Please do not answer to the question until you read entire post ! Thank you.With all helpers existing in C # ( like lambdas , or automatic properties ) it is very odd for me that I can not pass property by a reference . Let 's say I would like to do that : I get error so I write instead : And now it works . But please notice two things : it is general template , I did n't put anywhere type , only `` var '' , so it applies for all types and number of properties I have to passI have to do it over and over again , with no benefit -- it is mechanical workThe existing problem actually kills such useful functions as Swap . Swap is normally 3 lines long , but since it takes 2 references , calling it takes 5 lines . Of course it is nonsense and I simply write `` swap '' by hand each time I would like to call it . But this shows C # prevents reusable code , bad.THE QUESTIONSo -- what bad could happen if compiler automatically create temporary variables ( as I do by hand ) , call the function , and assign the values back to properties ? Is this any danger in it ? I do n't see it so I am curious what do you think why the design of this issue looks like it looks now.Cheers , EDIT As 280Z28 gave great examples for beating idea of automatically wrapping ref for properties I still think wrapping properties with temporary variables would be useful . Maybe something like this : Otherwise no real Swap for C # : - ( foo ( ref my_class.prop ) ; { var tmp = my_class.prop ; foo ( tmp ) ; my_class.prop = tmp ; } Swap ( inout my_class.prop1 , inout my_class.prop2 ) ;",why C # does not provide internal helper for passing property as reference ? "C_sharp : I have 3 Tables . Metadata , Rules , and a NxN relationship MetadataRules.I 'm inserting a Metadata , and my object contains a list of Rules that are retrieved from DB.When i perform an insert , all the rules in myListOfRules are duplicated in the Rules table , instead of just creating a relationship.I 'm inserting it with : What should i do to not duplicate the Rules ? Thanks ! myMetadata.Rules = myListOfrules ; public static void InserirTipoMetadata ( TA_TIPO_METADATA tipoMetadata ) { using ( EnterpriseContext context = new EnterpriseContext ( ) ) { context.TipoMetadata.AddObject ( tipoMetadata ) ; context.SaveChanges ( System.Data.Objects.SaveOptions.DetectChangesBeforeSave ) ; } }",Entity Framework Insert Many to many creates duplicated data "C_sharp : Suppose I 'd like a call in a unit test to return an anonymous type that looks like this - Could Autofixture generate anonymousType ? If so , what 's the syntax ? var anonymousType = { id = 45 , Name= '' MyName '' , Description= '' Whatever '' }",Can Autofixture create an anonymous type ? "C_sharp : The reflection code below returns : How can I get the Cars root type through reflection ? Not IList < Car > - how can I get Car ? System.Collections.Generic.IList ` 1 [ TestReflection.Car ] Cars using System ; using System.Reflection ; using System.Collections.Generic ; namespace TestReflection { class MainClass { public static void Main ( string [ ] args ) { Type t = typeof ( Dealer ) ; MemberInfo [ ] mi = t.GetMember ( `` Cars '' ) ; Console.WriteLine ( `` { 0 } '' , mi [ 0 ] .ToString ( ) ) ; Console.ReadLine ( ) ; } } class Dealer { public IList < Car > Cars { get ; set ; } } class Car { public string CarModel { get ; set ; } } }",Is parsing the only way to obtain the Member type ? "C_sharp : I am converting some Fortran90 code to C # . I have some knowledge of Fortran77 but am not familiar with Fortran90 . I have run across the following line of code that I am not certain how to translate.I am thinking this should be converted as : My uncertainty stems from the fact that there exists an implied do loop construction for initializing arrays ; i.e.but I have never seen the word `` product '' used as in the Fortran statement in question . I know there is an intrinsic function for vector or matrix multiplication called PRODUCT but `` product '' is not an array in the code I am working with and the syntax of the intrisic function PRODUCT uses MASK so clearly my statement is not using this function.Any insight or help would be greatly appreciated . Thank you . C1 = real ( product ( ( / ( -1 , i1=1 , m-1 ) / ) ) *product ( ( / ( i1 , i1=2 , m ) / ) ) ) int product1 = -1 ; int product2 = 1 ; for ( int i1 = 1 ; i1 < = ( m-1 ) ; i1++ ) { product1 *= -1 ; } for ( int i2 = 2 , i2 < = m ; i2++ ) { product2 *= i2 ; } float C1 = ( float ) ( product1 * product2 ) ; A = ( /2*I , I = 1,5/ )",Fortran90 to C # Conversion Issue "C_sharp : I 'm a student and I got a homework i need some minor help with = ) Here is my task : Write an application that prompts the user to enter the size of a square and display a square of asterisks with the sides equal with entered integer . Your application works for side ’ s size from 2 to 16 . If the user enters a number less than 2 or greater then 16 , your application should display a square of size 2 or 16 , respectively , and an error message.This is how far I 've come : I need help with ... ... what control statment ( if , for , while , do-while , case , boolean ) to use inside the `` if '' control.My ideas are like ... do I write a code that writes out the boxes for every type of number entered ? That 's a lot of code ... ..there must be a code containing some `` variable++ '' that could do the task for me , but then what control statement suits the task best ? But if I use a `` variable++ '' how am I supposed to write the spaces in the output , because after all , it has to be a SQUARE ? ! ? ! = ) I 'd love some suggestions on what type of statements to use , or maybe just a hint , of course not the whole solution as I am a student ! start : int x ; string input ; Console.Write ( `` Enter a number between 2-16 : `` ) ; input = Console.ReadLine ( ) ; x = Int32.Parse ( input ) ; Console.WriteLine ( `` \n '' ) ; if ( x < = 16 & x > = 2 ) { control statement code code code } else { Console.WriteLine ( `` You must enter a number between 2 and 16 '' ) ; goto start ; }",C # - Suggestions of control statement needed "C_sharp : Creating a class that implements DynamicObjectI can callAnd the value of result is `` dynamic test = new Test ( ) ; var result = test.Posts ; '' That 's fine.What I 'm wondering is , when TryGetMember is invoked is it possible to get the chained value.So if I called : I can then do something like : Is something like that possible ? I ca n't figure out a way to do it . So far I have : Which is thanks to Bartosz.But looks like it 's basically what Marc has supplied . Give 's me a good starting point ! I 'll leave this open for now for any other suggestions.This question has resulted in https : //gist.github.com/3798206 https : //github.com/phillip-haydon/Raven.DynamicSessionNot a real project , just prototyping but achieved what we wanted . public class Test : DynamicObject { public override bool TryGetMember ( GetMemberBinder binder , out object result ) { if ( binder.Name == ( `` Posts '' ) ) { result = `` property accessed was 'Posts ' '' ; return true ; } return base.TryGetMember ( binder , out result ) ; } } dynamic test = new Test ( ) ; var result = test.Posts ; dynamic test = new Test ( ) ; var result = test.Posts.Load ( 123 ) ; if ( binder.Name == ( `` Posts '' ) ) { if ( ... == `` Load '' ) result = this.Load < Post > ( ... 123 ) ; return true ; } class Program { static void Main ( string [ ] args ) { dynamic test = new Test ( ) ; dynamic result = test.Posts.Load ( 123 ) ; Console.WriteLine ( result.Name ) ; dynamic result2 = test.Posts.Load ( 909 ) ; Console.WriteLine ( result2.Name ) ; Console.ReadKey ( ) ; } } public class Test : DynamicObject { public override bool TryGetMember ( GetMemberBinder binder , out object result ) { if ( binder.Name == ( `` Posts '' ) ) { result = new ChainBuilder ( this , `` Post '' ) ; return true ; } return base.TryGetMember ( binder , out result ) ; } public T Load < T > ( int id ) where T : Post , new ( ) { if ( id == 123 ) return new T { Id = 123 , Name = `` Bananas '' } ; return new T { Id = 0 , Name = `` Others '' } ; } private class ChainBuilder : DynamicObject { public dynamic OriginalObject { get ; set ; } public string PropertyInvoked { get ; set ; } public ChainBuilder ( DynamicObject originalObject , string propertyInvoked ) { OriginalObject = originalObject ; PropertyInvoked = propertyInvoked ; } public override bool TryInvokeMember ( InvokeMemberBinder binder , object [ ] args , out object result ) { if ( binder.Name == `` Load '' ) { result = OriginalObject.Load < Post > ( ( int ) args [ 0 ] ) ; return true ; } return base.TryInvokeMember ( binder , args , out result ) ; } } } public class Post { public int Id { get ; set ; } public string Name { get ; set ; } }",Possible to get chained value of DynamicObject ? "C_sharp : I 've got wcf service for wcf straming . I works.But I must integrate it with our webserice.is there any way , to have webmethod like this : I service is a class which I copy from WCF service to my asmx.And is there any way to integrate App.config from wcf with web.config ? [ webmethod ] public Stream GetStream ( string path ) { return Iservice.GetStream ( path ) ; }",WCF streaming on asmx ? "C_sharp : In a program I 'm reading in some data files , part of which are formatted as a series of records each in square brackets . Each record contains a section title and a series of key/value pairs.I originally wrote code to loop through and extract the values , but decided it could be done more elegantly using regular expressions . Below is my resulting code ( I just hacked it out for now in a console app - so know the variable names are n't that great , etc.Can you suggest improvements ? I feel it should n't be necessary to do two matches and a substring , but ca n't figure out how to do it all in one big step : string input = `` [ section1 key1=value1 key2=value2 ] [ section2 key1=value1 key2=value2 key3=value3 ] [ section3 key1=value1 ] '' ; MatchCollection matches=Regex.Matches ( input , @ '' \ [ [ ^\ ] ] *\ ] '' ) ; foreach ( Match match in matches ) { string subinput = match.Value ; int firstSpace = subinput.IndexOf ( ' ' ) ; string section = subinput.Substring ( 1 , firstSpace-1 ) ; Console.WriteLine ( section ) ; MatchCollection newMatches = Regex.Matches ( subinput.Substring ( firstSpace + 1 ) , @ '' \s* ( \w+ ) \s*=\s* ( \w+ ) \s* '' ) ; foreach ( Match newMatch in newMatches ) { Console.WriteLine ( `` { 0 } = { 1 } '' , newMatch.Groups [ 1 ] .Value , newMatch.Groups [ 2 ] .Value ) ; } }",Can you improve this C # regular expression code ? "C_sharp : This is a UserControl that I am using.this.CardHolderName.Content is a label that is in the UI of the user control.I am still getting the error , `` The calling thread can not access this object because a different thread owns it '' even though I am using Dispatcher.BeginInvoke.Is there something wrong in the way the Dispatcher is used ? } EDIT : I am instantiating that user control inside a content control and the code-behind is : EDIT 1 : Code for start-Monitoring : public partial class PersonCredential : UserControl { public PersonCredential ( ) { InitializeComponent ( ) ; Dispatcher.BeginInvoke ( ( Action ) ( ( ) = > { SCLib type = new SCLib ( ) ; type.StartMonitoring ( ) ; type.CardArrived += ( string ATR ) = > { this.CardHolderName.Content = ATR ; } ; } ; } ) ) ; public partial class MainWindow : Window { PersonCredential personCredential { get ; set ; } public MainWindow ( ) { InitializeComponent ( ) ; var personCredential = new CoffeeShop.PersonCredential ( ) ; //create an instance of user control . this.personCredentials.Content = personCredential ; // assign it to the content control inside the wpf main window .. // blah blah } public async void StartMonitoring ( ) { // Wait for user to press a key try { this.establishContext ( ) ; await Task.Run ( new Action ( WaitForReaderArrival ) ) ; ////WaitForReaderArrival ( ) ; if ( IsReaderArrived ( ) )",Different thread owns it in WPF C_sharp : When I use : does anyone know which table and field User.Identity.Name corresponds to when I use the 'standard asp.net membership provider tables ' like these : Thanks . Membership.GetUser ( User.Identity.Name ) aspnet_Membershipaspnet_Users,Membership.GetUser - table + field "C_sharp : Today I was working on a TextToSpeech app and I 've came across a situation where I need to check if the selected voice by the user is installed on the computer.For this , I could either use a foreach : Or a lamda expression : The installedVoices is a ReadOnlyCollection < InstalledVoice > from SpeechSynthesizer.Definitely , the lambda expression looks more cleaner than the foreach but which one is better practice ? From what I have tested the foreach seems to be slightly faster than the lambda expression.Also , both foreach and lambda can be extended in the future if there is need for immediate action on the InstalledVoice . bool foundVoice = false ; foreach ( var v in installedVoices ) { if ( v.VoiceInfo.Name.Contains ( selectedVoice ) & & v.VoiceInfo.Culture.ToString ( ) == selectedCulture ) { foundVoice = true ; break ; } } var foundVoice = installedVoices.FirstOrDefault ( v = > v.VoiceInfo.Name.Contains ( selectedVoice ) & & v.VoiceInfo.Culture.ToString ( ) == selectedCulture ) ;",Is it good practice to use lambda expressions instead of foreach ? "C_sharp : I 've written a CSharpSyntaxRewriter that I am using to remove attributes from methods , but I am struggling to keep anything from before the attribute ( upto the previous method ) when I remove all attributes from a method.This works perfectly for methods with more than one attribute , but not for just one.Here 's a minimal repro : Full version is here on my gist ( before anyone points out any other issues ) .Expected output is : Actual output is : Any ideas on what I need to do to keep the whitespace ( or even comments ! ! ) ? I 've messed around with every combination of Trivia I can think of . Changing the SyntaxRemoveOptions results in NullReferenceExceptions inside the Roslyn codebase and using the *Trivia extension methods results in the attributes not been removed anymore - just whitespace . void Main ( ) { var code = @ '' namespace P { class Program { public void NoAttributes ( ) { } // ? ? ? [ TestCategory ( `` '' Atomic '' '' ) ] public void OneAtt1 ( ) { } [ TestCategory ( `` '' Atomic '' '' ) ] public void OneAtt2 ( ) { } [ TestMethod , TestCategory ( `` '' Atomic '' '' ) ] public void TwoAtts ( ) { } } } '' ; var tree = CSharpSyntaxTree.ParseText ( code ) ; var rewriter = new AttributeRemoverRewriter ( ) ; var rewrittenRoot = rewriter.Visit ( tree.GetRoot ( ) ) ; Console.WriteLine ( rewrittenRoot.GetText ( ) .ToString ( ) ) ; } public class AttributeRemoverRewriter : CSharpSyntaxRewriter { public override SyntaxNode VisitAttributeList ( AttributeListSyntax attributeList ) { var nodesToRemove = attributeList .Attributes .Where ( att = > ( att.Name as IdentifierNameSyntax ) .Identifier.Text.StartsWith ( `` TestCategory '' ) ) .ToArray ( ) ; if ( nodesToRemove.Length == attributeList.Attributes.Count ) { //Remove the entire attribute return attributeList .RemoveNode ( attributeList , SyntaxRemoveOptions.KeepNoTrivia ) ; } else { //Remove just the matching ones recursively foreach ( var node in nodesToRemove ) return VisitAttributeList ( attributeList.RemoveNode ( node , SyntaxRemoveOptions.KeepNoTrivia ) ) ; } return base.VisitAttributeList ( attributeList ) ; } } namespace P { class Program { public void NoAttributes ( ) { } // ? ? ? public void OneAtt1 ( ) { } public void OneAtt2 ( ) { } [ TestMethod ] public void TwoAtts ( ) { } } } namespace P { class Program { public void NoAttributes ( ) { } public void OneAtt1 ( ) { } public void OneAtt2 ( ) { } [ TestMethod ] public void TwoAtts ( ) { } } }",How to remove all member attribute but leave an empty line ? "C_sharp : I 'm trying to force Linq to preform an inner join between two tables . I 'll give an example.Now I 'm working with unusual database as there 's a reason beyond my control for people to be missing from the People table but have a record in CompanyPositions . I want to filter out CompanyPositions with missing People by joining the tables.Linq sees this join as redundant and removes it from the SQL it generates.However it 's not redundant in my case . I can fix it like thisHowever this now creates a needless where clause in my SQL . As a purest I 'd like to remove this . Any idea 's or does the current database design tie my hands ? CREATE TABLE [ dbo ] . [ People ] ( [ PersonId ] [ int ] NOT NULL , [ Name ] [ nvarchar ] ( MAX ) NOT NULL , [ UpdatedDate ] [ smalldatetime ] NOT NULL ... Other fields ... ) CREATE TABLE [ dbo ] . [ CompanyPositions ] ( [ CompanyPositionId ] [ int ] NOT NULL , [ CompanyId ] [ int ] NOT NULL , [ PersonId ] [ int ] NOT NULL , ... Other fields ... ) return ( from pos in CompanyPositions join p in People on pos.PersonId equals p.PersonId select pos ) .ToList ( ) ; SELECT [ Extent1 ] . [ CompanyPositionId ] AS [ CompanyPositionId ] , [ Extent1 ] . [ CompanyId ] AS [ CompanyId ] , ... . FROM [ dbo ] . [ CompanyPositions ] AS [ Extent1 ] // The min date check will always be true , here to force linq to perform the inner joinvar minDate = DateTimeExtensions.SqlMinSmallDate ; return ( from pos in CompanyPositions join p in People on pos.PersonId equals p.PersonId where p.UpdatedDate > = minDate select pos ) .ToList ( ) ;",Forcing linq to perform inner joins "C_sharp : If I would like to write a method that takes a variable number of `` TDerived '' where TDerived is any subclass of a class `` Base '' , is there any way to do this ? The following code only works with a single specific specified subclass : ie if I have then I can not dosince I get `` best overloaded match ... has some invalid arguments '' .Regardless of how the compiler handles the type constraints and variadic functions , this seems ( as far as I can tell ) completely type-safe . I know I could cast , but if this is type safe why not allow it ? EDIT : Perhaps a more convincing example : void doStuff < TDerived > ( params TDerived [ ] args ) where TDerived : Base { //stuff } class Super { } class Sub0 : Super { } class Sub1 : Super { } Sub0 s0 = new Sub0 ( ) ; Sub1 s1 = new Sub1 ( ) ; doStuff ( s0 , s1 ) ; void doStuff < TDerived > ( params SomeReadOnlyCollection < TDerived > [ ] args ) where TDerived : Base { foreach ( var list in args ) { foreach ( TDerived thing in list ) { //stuff } } }",Specifying `` any subclass '' in a C # type constraint rather than `` one particular subclass '' "C_sharp : I have a solution that looks like this : Winform WCF ( Client ) IdentityService4 self-hosted in Windows ServiceWCF HTTPS service self-hosted in Windows ServiceBoth the IdentitySErvice4 and the WCF service is using a function certificate . The client is using a client certificate loaded from the Windows Store . The client service is installed to the Windows Store from a smart card with a third party software . If the card is removed , the certificate is removed from the store.The flow looks like this : 1 Client loads the certificate from a store and binds it to the tookenhandler like this : 2 . The client sends the request to the IdentityServices that reads the client certificate and uses it to authenticate and generate a client token that is returned back.3 . The client creates a WCF channel to the service using the client certificate , the token is also attached to this channel like this 4 . The client sends the first message to the WCF service . The third party software will react and demand a pin for the client certificate when this is granted the message is forwarded to the WCF service where the token is validated against the IdentityService4.Real proxy is used to make it possible to switch to another service if needed . In this case , it only has URL to the one online WCF service.5 The client token will be refreshed every 30 min by the clientThis all works great at the beginning but after a random amount of calls it will fail , some times its the WCF service that it fails to contact and at this point the IdentityService might still be able to communicate with . The exception is thrown in the code shown in point 4 above and looks like this : e.ToString ( ) `` System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation . -- - > System.ServiceModel.Security.SecurityNegotiationException : Could not establish secure channel for SSL/TLS with authority '139.107.245.141:44310 ' . -- - > System.Net.WebException : The request was aborted : Could not create SSL/TLS secure channel.\r\n at System.Net.HttpWebRequest.GetResponse ( ) \r\n at System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelRequest.WaitForReply ( TimeSpan timeout ) \r\n -- - End of inner exception stack trace -- -\r\n\r\nServer stack trace : \r\n at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException ( WebException webException , HttpWebRequest request , HttpAbortReason abortReason ) \r\n at System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelRequest.WaitForReply ( TimeSpan timeout ) \r\n at System.ServiceModel.Channels.RequestChannel.Request ( Message message , TimeSpan timeout ) \r\n at System.ServiceModel.Dispatcher.RequestChannelBinder.Request ( Message message , TimeSpan timeout ) \r\n at System.ServiceModel.Channels.ServiceChannel.Call ( String action , Boolean oneway , ProxyOperationRuntime operation , Object [ ] ins , Object [ ] outs , TimeSpan timeout ) \r\n at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService ( IMethodCallMessage methodCall , ProxyOperationRuntime operation ) \r\n at System.ServiceModel.Channels.ServiceChannelProxy.Invoke ( IMessage message ) \r\n\r\nException rethrown at [ 0 ] : \r\n at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage ( IMessage reqMsg , IMessage retMsg ) \r\n at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke ( MessageData & msgData , Int32 type ) \r\n at myapp.ServiceContracts.ImyappClientService.LogData ( GeneralFault generalFault ) \r\n -- - End of inner exception stack trace -- -\r\n at System.RuntimeMethodHandle.InvokeMethod ( Object target , Object [ ] arguments , Signature sig , Boolean constructor ) \r\n at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal ( Object obj , Object [ ] parameters , Object [ ] arguments ) \r\n at System.Reflection.RuntimeMethodInfo.Invoke ( Object obj , BindingFlags invokeAttr , Binder binder , Object [ ] parameters , CultureInfo culture ) \r\n at System.Reflection.MethodBase.Invoke ( Object obj , Object [ ] parameters ) \r\n at myapp.Client.Main.Classes.Service_Management.CustomProxy ` 1.Invoke ( IMessage msg ) in C : \myapp\Produkter\myapp Utveckling\Solution\myapp.Client.Main\Classes\Service Management\CustomProxy.cs : line 74 '' stringSome times it will first fail the WCF service but then work again and then fail again ( exacly the same vall ) while when the IdentityService4 connection starts to fail it will fail every time with this exception : token.Exception.ToString ( ) `` System.Net.Http.HttpRequestException : An error occurred while sending the request . -- - > System.Net.WebException : The request was aborted : Could not create SSL/TLS secure channel.\r\n at System.Net.HttpWebRequest.EndGetRequestStream ( IAsyncResult asyncResult , TransportContext & context ) \r\n at System.Net.Http.HttpClientHandler.GetRequestStreamCallback ( IAsyncResult ar ) \r\n -- - End of inner exception stack trace -- -\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) \r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) \r\n at System.Net.Http.HttpClient.d__58.MoveNext ( ) \r\n -- - End of stack trace from previous location where exception was thrown -- -\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) \r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) \r\n at IdentityModel.Client.TokenClient.d__26.MoveNext ( ) '' stringThis code is used to test the IdentityService connection while in the client It 's the token.The exception that will hold the exception above.public static async Task LoginSiths ( ) { try { var host = `` 139.107.245.141 '' ; var port = 44312 ; var url = $ '' https : // { host } : { port } /connect/token '' ; The only way out is to restart the client ( none of the services needs to be restarted ) . After the client have been restarted it can log in as before again and do calls.If I add this to the start of my client : then I will get problem almost instantly after login ( that varies slowly at this point ) .Is there any way to know why I get an SSL exception ? Note , this post have been updated 2017-04-07 01:00 , this is to give a more collected picture of what 's going on . The problem really consisted of two problems , one is still active and is explained above , the other was due to a bug in IdentityService4 that we found a workaround for . public override TokenClient GetTokenClient ( string host , string port ) { var certificate = SmartCardHandler.GetInstance ( ) .Result.CurrentCertificate ( ) ; if ( certificate == null ) throw new Exception ( `` Certificate is missing '' ) ; var handler = new WebRequestHandler ( ) ; handler.ServerCertificateValidationCallback = PinPublicKey ; var url = $ '' https : // { host } : { port } /connect/token '' ; handler.ClientCertificates.Add ( certificate ) ; return new TokenClient ( url , ClientTypes.Siths , `` secret '' , handler ) ; } token = await tokenClient.RequestCustomGrantAsync ( ClientTypes.Siths , `` MyApp.wcf offline_access '' ) ; private async Task < ChannelFactory < T > > CreateChannelFactory ( LoginTypeBase loginType , MyAppToken token ) { var service = await _ConsulService.GetServiceBlocking ( loginType.MyAppServicesToUse , forceRefresh : true , token : new CancellationTokenSource ( TimeSpan.FromSeconds ( 30 ) ) .Token ) ; if ( service == null ) throw new MyAppServiceCommunicationException ( ) ; var cert = loginType.ClientCertificate ; var uri = loginType.GetMyAppClientServiceURL ( service.Address , service.Port ) ; var header = AddressHeader.CreateAddressHeader ( nameof ( MyAppToken ) , nameof ( MyAppToken ) , token ) ; var endpointAddress = new EndpointAddress ( uri , header ) ; ServiceEndpoint serviceEndpoint = null ; if ( loginType.LoginType == LoginType.SmartCard || loginType.LoginType == LoginType.UsernamePasswordSLL ) { var binding = new NetHttpsBinding ( `` netHttpsBinding '' ) ; binding.Security.Mode = BasicHttpsSecurityMode.Transport ; if ( loginType.LoginType == LoginType.SmartCard ) binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate ; else binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None ; serviceEndpoint = new ServiceEndpoint ( ContractDescription.GetContract ( typeof ( T ) ) , binding , endpointAddress ) ; } else { var binding = new NetHttpBinding ( `` netHttpBinding '' ) ; serviceEndpoint = new ServiceEndpoint ( ContractDescription.GetContract ( typeof ( T ) ) , binding , endpointAddress ) ; } serviceEndpoint.EndpointBehaviors.Add ( new ProtoEndpointBehavior ( ) ) ; serviceEndpoint.EndpointBehaviors.Add ( new CustomMessageInspectorBehavior ( ) ) ; var v = new ChannelFactory < T > ( serviceEndpoint ) ; if ( loginType.LoginType == LoginType.SmartCard ) { v.Credentials.ClientCertificate.Certificate = cert ; //v.Credentials.ClientCertificate.SetCertificate ( StoreLocation.CurrentUser , StoreName.My , X509FindType.FindByThumbprint , cert.Thumbprint ) ; } return v ; } } public override IMessage Invoke ( IMessage msg ) { var methodCall = ( IMethodCallMessage ) msg ; var method = ( MethodInfo ) methodCall.MethodBase ; var channel = GetChannel ( false ) ; var retryCount = 3 ; do { try { var result = method.Invoke ( channel , methodCall.InArgs ) ; var returnmessage = new ReturnMessage ( result , null , 0 , methodCall.LogicalCallContext , methodCall ) ; return returnmessage ; } catch ( Exception e ) { if ( e is TargetInvocationException & & e.InnerException ! = null ) { if ( e.InnerException is FaultException ) return new ReturnMessage ( ErrorHandler.Instance.UnwrapAgentException ( e.InnerException ) , msg as IMethodCallMessage ) ; if ( e.InnerException is EndpointNotFoundException || e.InnerException is TimeoutException ) channel = GetChannel ( true ) ; } retryCount -- ; } } while ( retryCount > 0 ) ; throw new Exception ( `` Retrycount reached maximum . Customproxy Invoke '' ) ; } private async Task RefreshToken ( LoginTypeBase loginType ) { if ( _MyAppToken == null ) return ; var tokenClient = await GetTokenClient ( loginType ) ; var result = ! string.IsNullOrEmpty ( _refreshToken ) ? await tokenClient.RequestRefreshTokenAsync ( _refreshToken , _cancelToken.Token ) : await tokenClient.RequestCustomGrantAsync ( `` siths '' , cancellationToken : _cancelToken.Token ) ; if ( string.IsNullOrEmpty ( result.AccessToken ) ) throw new Exception ( $ '' Accesstoken har blivit null försökte refresha med { tokenClient.ClientId } { _refreshToken } { DateTime.Now } '' ) ; _MyAppToken.Token = result.AccessToken ; _refreshToken = result.RefreshToken ; } var handler = new WebRequestHandler ( ) ; handler.ServerCertificateValidationCallback = PinPublicKey ; handler.ClientCertificates.Add ( SmartCardHandler.GetInstance ( ) .Result.CurrentCertificate ( ) ) ; var client = new TokenClient ( url , ClientTypes.Siths , `` secret.ro101.orbit '' , handler ) ; TokenResponse token = await client.RequestCustomGrantAsync ( ClientTypes.Siths , `` orbit.wcf offline_access '' ) ; if ( token.IsError ) MessageBox.Show ( `` Failed ! `` ) ; else MessageBox.Show ( `` Success ! `` ) ; } catch ( Exception ex ) { MessageBox.Show ( `` Exception : `` + ex.ToString ( ) ) ; } } ServicePointManager.MaxServicePointIdleTime = 1 ;",WCF application with client certificate fails after a while ? "C_sharp : Dummy code : This method complains with int/float/double , that ca n't find these methods ( op_Addition ) .So how to build a general addition method ? public object Addition ( object a , object b ) { var type = a.GetType ( ) ; var op = type.GetMethod ( `` op_Addition '' , BindingFlags.Static | BindingFlags.Public ) ; return op.Invoke ( null , new object [ ] { a , b } ) ; }","where is op_addition in [ int , float , double ]" "C_sharp : I am programatically adding text in a custom RichTextBox using a KeyPress event : The problem is that inserting text in such a way does n't trigger the CanUndo flag.As such , when I try to Undo / Redo text ( by calling the Undo ( ) and Redo ( ) methods of the textbox ) , nothing happens.I tried programatically evoking the KeyUp ( ) event from within a TextChanged ( ) event , but that still did n't flag CanUndo to true.How can I undo text that I insert without having to create lists for Undo and Redo operations ? Thanks SelectedText = e.KeyChar.ToString ( ) ;",C # : Unable to undo inserted text "C_sharp : Consider the following example : This compiles just fine , because IEnumerable < T > is covariant in T.However , if I do exactly the same thing but now with generics : I get the compiler error Can not convert expression type 'System.Collection.Generic.List ' to return type 'System.Collection.Generic.IEnumerable'What am I doing wrong here ? class Base { } class Derived : Base { } class Test1 { private List < Derived > m_X ; public IEnumerable < Base > GetEnumerable ( ) { return m_X ; } } class Test2 < TBase , TDerived > where TDerived : TBase { private List < TDerived > m_X ; public IEnumerable < TBase > GetEnumerable ( ) { return m_X ; } }",Why ca n't I use covariance with two generic type parameters ? "C_sharp : In .NET the BinarySearch algorithm ( in Lists , Arrays , etc . ) appears to fail if the items you are trying to search inherit from an IComparable instead of implementing it directly : Where : Is there a way around this ? Implementing CompareTo ( B other ) in class B does n't seem to work . List < B > foo = new List < B > ( ) ; // B inherits from A , which implements IComparable < A > foo.Add ( new B ( ) ) ; foo.BinarySearch ( new B ( ) ) ; // InvalidOperationException , `` Failed to compare two elements in the array . '' public abstract class A : IComparable < A > { public int x ; public int CompareTo ( A other ) { return x.CompareTo ( other.x ) ; } } public class B : A { }",C # BinarySearch breaks when inheriting from something that implements IComparable < T > ? C_sharp : I 'm wondering if it 's possible to get this working : It works until there are no more images for that product at which point it throws ... I made a fix for it but I 'd prefer to keep it as minimal as possible and stay in Linq so was hoping there was a way to get my initial statement to function.The ugly fix : product.PrimaryImage = db.ProductImages .Where ( p = > p.Product.ID == product.ID ) .OrderBy ( p = > p.Order ? ? 999999 ) .ThenBy ( p = > p.ID ) .FirstOrDefault ( ) .Name ; db.SaveChanges ( ) ; System.NullReferenceException : Object reference not set to an instance of an object . ProductImages primaryProductImage = db.ProductImages.Where ( p = > p.Product.ID == product.ID ) .OrderBy ( p = > p.Order ? ? 999999 ) .ThenBy ( p = > p.ID ) .FirstOrDefault ( ) ; string primaryImage = ( primaryProductImage ! = null ) ? primaryProductImage.Name : null ; product.PrimaryImage = primaryImage ; db.SaveChanges ( ) ;,Minimalist LINQ approach - System.NullReferenceException "C_sharp : Is there any way to construct a list of type List < string > which contains a single string N times without using a loop ? Something similar to String ( char c , int count ) but instead for List of strings . List < string > list = new List < string > ( ) { `` str '' , `` str '' , `` str '' , ... .. N times } ;",Creating a List < string > containing a single string N times "C_sharp : Having just answered a question about calling VB6 methods with parentheses , I remembered that you could force ByRef parameter values to be passed ByVal . Researching , I found this still works in VB.NET.However , I can not find anything similar in C # that allows for this . This past year I have had to reference a lot of VB.NET class libraries that take in ByRef for no good reason ( trust me , I checked ) . This has forced me to set properties on objects to local variables in order to pass them in . Not a major issue , but not very clean if you ask me.I am wondering if there is a syntactical solution that I am not aware of.As an example of my current pattern that I would like to avoid : In VB6 and VB.NET , you can just do the following to force ByVal on a ByRef parameter.EDIT : I am not asking about the differences between ByRef and ByVal . I am asking if C # has a similar way to force a ByRef parameter to be pass ByVal . See this MSDN doc of the VB.NET functionality.http : //msdn.microsoft.com/en-us/library/chy4288y.aspx var tempSomeObject = BarObject.FooProperty ; SomeVb6BusinessLogicMethod ( ref tempSomeObject ) ; // Continue to do work and set other temp objects due to ref constraint SomeVb6BusinessLogicMethod ( ( BarObject.FooProperty ) ) 'Note the extra parens",Is there a way to force a parameter to be passed by value instead of ref in C # like you can in VB ? "C_sharp : I have an app that is written using c # and ASP.NET MVC 5 . I 'm also using Unity.Mvc for dependency injection.Along with many other classes , the class MessageManager is registered in the IoC container . However , the MessageManager class depends on an instance of TempDataDictionary to perform its work . This class is used to write temporary data for the views.In order to resolve an instance of MessageManager I need to also register an instance of TempDataDictionary . I would need to be able to add values to TempDataDictionary from the MessageManager class and then I would need to access the temp data from the view . Therefore , I need to be able to access the same instance of TempDataDictionary in the views so I can write out the messages to the user.Also , if the controller redirects the user elsewhere , I do n't want to lose the message , I still want to be able to show the message on the next view.I tried the following to register both TempDataDictionary and MessageManager : Then in my view , I have the following to resolve to an instance of IMessageManagerHowever , the message gets lost for some reason . That is , when I resolve manager , TempDataDictionary does n't contain any messages that were added by MessageManager from the controller.How can I correctly register an instance of the TempDataDictionary so the data persists until it is viewed ? UPDATEDHere is my IMessageManager interface Container.RegisterType < TempDataDictionary > ( new PerThreadLifetimeManager ( ) ) .RegisterType < IMessageManager , MessageManager > ( ) ; var manager = DependencyResolver.Current.GetService < IMessageManager > ( ) ; public interface IMessageManager { void AddSuccess ( string message , int ? dismissAfter = null ) ; void AddError ( string message , int ? dismissAfter = null ) ; void AddInfo ( string message , int ? dismissAfter = null ) ; void AddWarning ( string message , int ? dismissAfter = null ) ; Dictionary < string , IEnumerable < FlashMessage > > GetAlerts ( ) ; }",How can I correctly inject ` TempDataDictionary ` into my classes ? "C_sharp : IntroductionI have an application that imports lab instrument data while it is running . This data is imported and then displayed in a ListView at an interval set by the end-user as per his or her testing requirements . When a value of interest appears in this ListView that they watch , they then press a Start button and the application begins performing calculations on that datum and subsequent data until a Stop button is pressed . So on the left side of the screen is a View for displaying the imported data and on the right side is another View for watching the values and statistics as they are calculated and displayed.The Current CodeThe View that displays the ListView where data is imported to is the ImportProcessView.xaml and it sets its DataContext to the ImportProcessViewModel.cs . The VM I 've just introduced has a property ObservableCollection < IrData > that the ListView , I 've also just described , binds to . Now to the interesting part ... The ImportProcessView has a ContentControl that sets it 's content dynamically a UserControl representing the controls and fields specific to the type of Phase that is chosen by the end-user.There are three PhaseViews , each in its own User Control and each sets it 's DataContext to the ImportProcessViewModel . As a result I am getting some severe VM bloat to the tune of 2000 lines . Ridiculous . I know . The reason for the bloat is because the ImporProcessViewModel is maintaining state through properties for each of the three PhaseViews and not only that but contains methods for performing calculations whose data is stored and displayed in these `` PhaseViews '' .What I am trying to achieveObviously before the ImportProcessViewModel becomes more unwieldy , I need to break it up so that each PhaseView has its own ViewModel , but also such that each ViewModel maintains a relationship back to the ImportProcessViewModel for sake of the dependency imposed by the ObservableCollection of IrData.R & DI 've done my research on ViewModels communicating with each other , but most of the results involve applications that were written with a specific MVVM framework . I am not using a framework , and at this point in the project it would be too late to refactor it to start using one.I did , however , find this article and the answer offered by 'hbarck ' suggests something simple like composition to achieve the result I want , but since I do n't have much experience with DataTemplates I do n't understand what is meant when he/she suggests exposing `` the UserControl 's ViewModel as a property on the main ViewModel , and bind a ContentControl to this property , which would then instantiate the View ( i.e . the UserControl ) through a DataTemplate '' Specifically , I do n't understand what is meant by `` bind a ContentControl to this property which would then instantiate the View through a DataTemplate '' .Can someone clarify by way of an code example what is meant by instantiating a view through a DataTemplate in the context of this example ? Additionally , is this a good approach ( as suggested by 'hbarck ' ) ? As one can see , I am already setting the Content property of a ContentControl to the Phase View that is to be instantiated . I just do n't know know what involving a DataTemplate would look like . < StackPanel Background= '' White '' Margin= '' 5 '' > < ContentControl Content= '' { Binding CurrentPhaseView } '' / > < /StackPanel >",ViewModels that talk to each other without a Framework "C_sharp : Most of time we represent concepts which can never be less than 0 . For example to declare length , we write : The name expresses its purpose well but you can assign negative values to it . It seems that for some situations , you can represent your intent more clearly by writing it this way instead : Some disadvantages that I can think of : unsigned types ( uint , ulong , ushort ) are not CLS compliant so you ca n't use it with other languages that do n't support this.Net classes use signed types most of the time so you have to castThoughts ? int length ; uint length ;",Using Unsigned Primitive Types "C_sharp : I have a question about disposing objects.Consider this IDisposable classOn the first constructor , MyProp is injected . So MyClass is not the owner of the object . But on the second constructor , MyProp is created locally.Should I always dispose MyProp , or should I check first if it is injected or not . public class MyClass : DisposableParentClass { private MyProp _prop ; public MyClass ( MyProp prop ) { _prop = prop ; } public MyClass ( ) { _prop = new MyProp ( ) ; } protected override void Dispose ( bool disposing ) { if ( disposing ) { _prop.Dispose ( ) ; } base.Dispose ( disposing ) ; } } public class MyClass : DisposableParentClass { private MyProp _prop ; private bool _myPropInjected = false ; public MyClass ( MyProp prop ) { _prop = prop ; _myPropInjected = true ; } public MyClass ( ) { _prop = new MyProp ( ) ; } protected override void Dispose ( bool disposing ) { if ( disposing ) { if ( ! _myPropInjected ) { _prop.Dispose ( ) ; } } base.Dispose ( disposing ) ; } }",How to properly dispose objects : injected vs. owned "C_sharp : I went through whole documantation and didnt find how to set RBF network . I found some RBF example in ConsoleExmpales/Examples/Radial , but it looks like it doesnt work anymore , beceause some methods have been changed in Encog.So far I am stuck on this : When I run this , I get error `` Total number of RBF neurons must be some integer to the power of 'dimensions ' . '' on SetRBFCentersAndWidthsEqualSpacing . It works if I change this method for RandomizeRBFCentersAndWidths until train.iteration ( ) is reached , where i get `` Index was outside the bounds of the array '' .I understand how RBF network works , but I am confused from all parameters in SetRBFCentersAndWidthsEqualSpacing method , can someone explain it more detail ? . public static double [ ] [ ] XORInput = { new [ ] { 0.0 , 0.0 } , new [ ] { 1.0 , 0.0 } , new [ ] { 0.0 , 1.0 } , new [ ] { 1.0 , 1.0 } } ; public static double [ ] [ ] XORIdeal = { new [ ] { 0.0 } , new [ ] { 1.0 } , new [ ] { 1.0 } , new [ ] { 0.0 } } ; int dimension = 8 ; int numNeuronsPerDimension = 64 ; double volumeNeuronWidth = 2.0 / numNeuronsPerDimension ; bool includeEdgeRBFs = true ; RBFNetwork n = new RBFNetwork ( dimension , numNeuronsPerDimension , 1 , RBFEnum.Gaussian ) ; n.SetRBFCentersAndWidthsEqualSpacing ( 0 , 1 , RBFEnum.Gaussian , volumeNeuronWidth , includeEdgeRBFs ) ; //n.RandomizeRBFCentersAndWidths ( 0 , 1 , RBFEnum.Gaussian ) ; INeuralDataSet trainingSet = new BasicNeuralDataSet ( XORInput , XORIdeal ) ; SVDTraining train = new SVDTraining ( n , trainingSet ) ; int epoch = 1 ; do { train.Iteration ( ) ; Console.WriteLine ( `` Epoch # '' + epoch + `` Error : '' + train.Error ) ; epoch++ ; } while ( ( epoch < 1 ) & & ( train.Error > 0.001 ) ) ;","Encog C # RBF network , how to start ?" "C_sharp : The naming convention for constants in C # is Pascal casing : But sometimes we need to represent already-existing constants from the Windows API.For example , I do n't know how to name this : What should I name it ? Keeping it as WS_EX_COMPOSITED allows me to quickly associate it with the WinAPI , but it 's wrong.Some options : WsExComposited -- Too hungarianComposited -- Too shortWsEx enum with Composited in it -- Still hungarianExtendedWindowsStyles.Composited -- Constant in a class ? Enum ? It should be noted that the objectives for a good naming are : It must be readable.It must not trigger FxCop and StyleCop , even if that means hiding it from them . private const int TheAnswer = 42 ; /// < summary > /// With this style turned on for your form , /// Windows double-buffers the form and all its child controls./// < /summary > public const int WS_EX_COMPOSITED = 0x02000000 ;",Naming Windows API constants in C # "C_sharp : I just wondered what 's the easiest way to replace a string characters that must be replaced subsequently . For example : The desired result : [ [ ] Hello World [ ] ] The actual result : [ [ [ ] ] Hello World [ ] ] The reason is obviously the second replace on the already modified string.So how to replace all occurences of `` bad '' characters with characters that contain `` bad '' characters ? A quick measurement of all approaches revealed that the StringBuilder is the most efficient way.190kb file ( all in milliseconds ) 7MB fileBy the way , the direct StringBuilder approach from John was twice as fast as the Aggregate approach from Sehe.I 've made an extension out of it : var str = `` [ Hello World ] '' ; //enclose all occurences of [ and ] with brackets [ ] str = str.Replace ( `` [ `` , '' [ [ ] '' ) .Replace ( `` ] '' , '' [ ] ] '' ) ; regexTime 40.5065 replaceTime 20.8891 stringBuilderTime 6.9776 regexTime 1209.3529 replaceTime 403.3985 stringBuilderTime 175.2583 public static String EncloseChars ( this string input , char [ ] charsToEnclose , String leftSide , String rightSide ) { if ( charsToEnclose == null || leftSide == null || rightSide == null ) throw new ArgumentException ( `` Invalid arguments for EncloseChars '' , charsToEnclose == null ? `` charsToEnclose '' : leftSide == null ? `` leftSide '' : `` rightSide '' ) ; Array.Sort ( charsToEnclose ) ; StringBuilder sb = new StringBuilder ( ) ; foreach ( char c in input ) { if ( Array.BinarySearch ( charsToEnclose , c ) > -1 ) sb.Append ( leftSide ) .Append ( c ) .Append ( rightSide ) ; else sb.Append ( c ) ; } return sb.ToString ( ) ; } '' [ Hello World ] '' .EncloseChars ( new char [ ] { ' [ ' , ' ] ' } , '' [ `` , '' ] '' ) ;",Replacing bad characters of a String with bad characters "C_sharp : I am creating a new C # OData4 Web API with a class named Call that has dynamic properties , which OData 4 allows via `` Open Types '' . I believe I 've set everything up and configured it correctly but the serialized response does not include the dynamic properties.Did I configure something wrong ? public partial class Call { public int Id { get ; set ; } public string Email { get ; set ; } public IDictionary < string , object > DynamicProperties { get ; } } public class CallController : ODataController { [ EnableQuery ] public IQueryable < Call > GetCall ( [ FromODataUri ] int key ) { return _context.Call.GetAll ( ) ; } } public static partial class WebApiConfig { public static void Register ( HttpConfiguration config ) { AllowUriOperations ( config ) ; ODataModelBuilder builder = new ODataConventionModelBuilder ( ) ; builder.ComplexType < Call > ( ) ; var model = builder.GetEdmModel ( ) ; config.MapODataServiceRoute ( RoutePrefix.OData4 , RoutePrefix.OData4 , model ) ; } private static void AllowUriOperations ( HttpConfiguration config ) { config.Count ( ) ; config.Filter ( ) ; config.OrderBy ( ) ; config.Expand ( ) ; config.Select ( ) ; } }",C # WebAPI not serializing dynamic properties correctly "C_sharp : I 'm using System.Speech to recognize some phrases or words . One of them is Set timer . I would like to expand this to Set timer for X seconds , and having the code set a timer for X seconds . Is this possible ? I have little to no experience with this so far , all I could find is that I have to do something with the grammar class.Right now I have set up my recognition engine like this : Is there a way to do this ? SpeechRecognitionEngine = new SpeechRecognitionEngine ( ) ; SpeechRecognitionEngine.SetInputToDefaultAudioDevice ( ) ; var choices = new Choices ( ) ; choices.Add ( `` Set timer '' ) ; var gb = new GrammarBuilder ( ) ; gb.Append ( choices ) ; var g = new Grammar ( gb ) ; SpeechRecognitionEngine.LoadGrammarAsync ( g ) ; SpeechRecognitionEngine.RecognizeAsync ( RecognizeMode.Multiple ) ; SpeechRecognitionEngine.SpeechRecognized += OnSpeechRecognized ;",How to extract variables from speech recognition "C_sharp : I 'm having trouble figuring out how to get Powershell to call an indexer on my class . The class looks something like this ( vastly simplified ) : If I new up this class I ca n't just use the bracket operator on it - I get an `` unable to index '' error . I also tried using get_item ( ) , which is what Reflector shows me the indexer ultimately becomes in the assembly , but that gets me a `` does n't contain a method named get_item '' error.UPDATE : this appears specific to my use of explicit interfaces . So my new question is : is there a way to get Powershell to see the indexer without switching away from explicit interfaces ? ( I really do n't want to modify this assembly if possible . ) public interface IIntCounters { int this [ string counterName ] { get ; set ; } } public class MyClass : IIntCounters { public IIntCounters Counters { get { return this ; } } int IIntCounters.this [ string counterName ] { get { ... return something ... } } }",How to call an indexer on a C # class from PowerShell ? "C_sharp : I have a url that authenticates my credentials on a server . Is there a way to make it invisible ? The simple code looks exactly like this : however ProcessWindowStyle.Hidden does n't seem to do the trick . If I set UseShellExecute to false then I get Win32Exception with the message The system can not find the file specifiedThe url is a authentication on Spotify server to get the playlists and it looks something like this https : //accounts.spotify.com/authorize/client_id=26d287105as12315e12ds56e31491889f3cd293..Is there an other way to make this process invisible ? Edit : http sampleThe entire .cs file containing the sample above : And they are called like this : The github url with a full runnable sampe is here : https : //github.com/JohnnyCrazy/SpotifyAPI-NETDownload it and run the Spotify Test to connect to Spotify 's web api to reproduce the sample I have . public void DoAuth ( ) { String uri = GetUri ( ) ; ProcessStartInfo startInfo = new ProcessStartInfo ( uri ) ; startInfo.WindowStyle = ProcessWindowStyle.Hidden ; Process.Start ( startInfo ) ; } public void DoAuth ( ) { String uri = GetUri ( ) ; HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( uri ) ; HttpWebResponse webResponse ; try { webResponse = ( HttpWebResponse ) request.GetResponse ( ) ; Console.WriteLine ( `` Error code : { 0 } '' , webResponse.StatusCode ) ; using ( Stream data = webResponse.GetResponseStream ( ) ) using ( var reader = new StreamReader ( data ) ) { //do what here ? } } catch ( Exception e ) { throw ; } } using SpotifyAPI.Web.Enums ; using SpotifyAPI.Web.Models ; using System ; using System.IO ; using System.Net ; using System.Text ; using System.Threading ; namespace SpotifyAPI.Web.Auth { public class ImplicitGrantAuth { public delegate void OnResponseReceived ( Token token , String state ) ; private SimpleHttpServer _httpServer ; private Thread _httpThread ; public String ClientId { get ; set ; } public String RedirectUri { get ; set ; } public String State { get ; set ; } public Scope Scope { get ; set ; } public Boolean ShowDialog { get ; set ; } public event OnResponseReceived OnResponseReceivedEvent ; /// < summary > /// Start the auth process ( Make sure the internal HTTP-Server ist started ) /// < /summary > public void DoAuth ( ) { String uri = GetUri ( ) ; HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( uri ) ; HttpWebResponse webResponse ; try { webResponse = ( HttpWebResponse ) request.GetResponse ( ) ; Console.WriteLine ( `` Error code : { 0 } '' , webResponse.StatusCode ) ; using ( Stream data = webResponse.GetResponseStream ( ) ) using ( var reader = new StreamReader ( data ) ) { //nothing } } catch ( Exception e ) { throw ; } /*ProcessStartInfo startInfo = new ProcessStartInfo ( uri ) ; startInfo.WindowStyle = ProcessWindowStyle.Hidden ; Process.Start ( startInfo ) ; */ } private String GetUri ( ) { StringBuilder builder = new StringBuilder ( `` https : //accounts.spotify.com/authorize/ ? `` ) ; builder.Append ( `` client_id= '' + ClientId ) ; builder.Append ( `` & response_type=token '' ) ; builder.Append ( `` & redirect_uri= '' + RedirectUri ) ; builder.Append ( `` & state= '' + State ) ; builder.Append ( `` & scope= '' + Scope.GetStringAttribute ( `` `` ) ) ; builder.Append ( `` & show_dialog= '' + ShowDialog ) ; return builder.ToString ( ) ; } /// < summary > /// Start the internal HTTP-Server /// < /summary > public void StartHttpServer ( int port = 80 ) { _httpServer = new SimpleHttpServer ( port , AuthType.Implicit ) ; _httpServer.OnAuth += HttpServerOnOnAuth ; _httpThread = new Thread ( _httpServer.Listen ) ; _httpThread.Start ( ) ; } private void HttpServerOnOnAuth ( AuthEventArgs e ) { OnResponseReceivedEvent ? .Invoke ( new Token { AccessToken = e.Code , TokenType = e.TokenType , ExpiresIn = e.ExpiresIn , Error = e.Error } , e.State ) ; } /// < summary > /// This will stop the internal HTTP-Server ( Should be called after you got the Token ) /// < /summary > public void StopHttpServer ( ) { _httpServer.Dispose ( ) ; _httpServer = null ; } } } _auth.OnResponseReceivedEvent += _auth_OnResponseReceivedEvent ; _auth.StartHttpServer ( 8000 ) ; _auth.DoAuth ( ) ;",Process.Start url with hidden WindowStyle "C_sharp : I am looking at the Roslyn September 2012 CTP with Reflector , and I noticed that the ChildSyntaxList struct has the following : That is , there is a GetEnumerator method which returns a struct.It looks like thatusing a struct is a performance gain similar to the BCL List < T > .Enumerator struct , as noted in this answer , and thatthe struct does not implement IDisposable so as to not have to worry about bugs that could arise from doing so , as noted on Eric Lippert 's blog.However , unlike the BCL List < T > class , there is a nested EnumeratorImpl class . Is the purpose of this toavoid having a disposable struct , andavoid boxing within the explicitly implemented IEnumerable < SyntaxNodeOrToken > .GetEnumerator and IEnumerable.GetEnumerator methods ? Are there any other reasons ? public struct ChildSyntaxList : IEnumerable < SyntaxNodeOrToken > { private readonly SyntaxNode node ; private readonly int count ; public Enumerator GetEnumerator ( ) { return node == null ? new Enumerator ( ) : new Enumerator ( node , count ) ; } IEnumerator < SyntaxNodeOrToken > IEnumerable < SyntaxNodeOrToken > .GetEnumerator ( ) { return node == null ? SpecializedCollections.EmptyEnumerator < SyntaxNodeOrToken > ( ) : new EnumeratorImpl ( node , count ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return node == null ? SpecializedCollections.EmptyEnumerator < SyntaxNodeOrToken > ( ) : new EnumeratorImpl ( node , count ) ; } public struct Enumerator { internal Enumerator ( SyntaxNode node , int count ) { /* logic */ } public SyntaxNodeOrToken Current { get { /* logic */ } } public bool MoveNext ( ) { /* logic */ } public void Reset ( ) { /* logic */ } } private class EnumeratorImpl : IEnumerator < SyntaxNodeOrToken > { private Enumerator enumerator ; internal EnumeratorImpl ( SyntaxNode node , int count ) { enumerator = new Enumerator ( node , count ) ; } public SyntaxNodeOrToken Current { get { return enumerator.Current ; } } object IEnumerator.Current { get { return enumerator.Current ; } } public void Dispose ( ) { } public bool MoveNext ( ) { return enumerator.MoveNext ( ) ; } public void Reset ( ) { enumerator.Reset ( ) ; } } }",Why have Enumerator struct and EnumeratorImpl class ? "C_sharp : I seem to be mentally stuck in a Flyweight pattern dilemma.First , let 's say I have a disposable type DisposableFiddle and a factory FiddleFactory : Then , in my opinion , it 's quite clear to the client of FiddleFactory that the factory claims no ownership of the created fiddle and that it 's the client 's responsibility to dispose the fiddle when done with it.However , let 's instead say that I want to share fiddles between clients by using the Flyweight pattern : Then I feel morally obliged to make the factory itself disposable , since it creates the fiddles and keeps references to them during all of their lifetime . But that would cause problems to the clients that assumed they owned the fiddles and should therefore dispose them.Is the problem actually that I call the factory FiddleFactory instead of , say , FiddlePool , and the `` creation '' method CreateFiddle instead of GetFiddle ? Like this : Then it 's clearer to the client that it 'll not own the returned fiddle and it 's the pool 's responsibility to dispose the fiddles.Or can this only be readily solved documentation-wise ? Is there a way out of the dilemma ? Is there even a dilemma ? : - ) public interface DisposableFiddle : IDisposable { // Implements IDisposable } public class FiddleFactory { public DisposableFiddle CreateFiddle ( SomethingThatDifferentiatesFiddles s ) { // returns a newly created fiddle . } } public class FiddleFactory { private Dictionary < SomethingThatDifferentiatesFiddles , DisposableFiddle > fiddles = new ... ; public DisposableFiddle CreateFiddle ( SomethingThatDifferentiatesFiddles s ) { // returns an existing fiddle if a corresponding s is found , // or a newly created fiddle , after adding it to the dictionary , // if no corresponding s is found . } } public class FiddlePool : IDisposable { private Dictionary < SomethingThatDifferentiatesFiddles , DisposableFiddle > fiddles = new ... ; public DisposableFiddle GetFiddle ( SomethingThatDifferentiatesFiddles s ) { // returns an existing fiddle if a corresponding s is found , // or a newly created fiddle , after adding it to the dictionary , // if no corresponding s is found . } // Implements IDisposable }",Flyweight and Factory problem with IDisposable "C_sharp : I have a list of objects , each with a bool ShouldRun ( ) method on them.I am currently iterating over the list of objects , and checking ShouldRun ( ) on each object , and calling Run ( ) on the first one to return trueI would like to do this in parallel , because evaluating shouldRun can take a decent amount of time , and it is advantageous to let later elements in the collection start their evaluation early.However , I can not think of a way to do this that will satisfy these conditions : 1 Only run one item 2 Do not run a later item if an earlier item is true , or has not finished evaluating yet3 If all `` earlier '' items have returned false , and a middle item returns true , do not wait on a later item to finish evaluating because you know it ca n't override anything earlier.I thought of doing a parallel `` where '' linq query to retrieve all the items that shouldRun ( ) and then sorting , but this will violate condition # 3Ideas ? Background info : The system is for a generalized robotics AI system.Some of the higher priority tasks can be triggered by immediately known sensor variables eg : Im falling over , fix it ! other tasks might be computationally intensive ( do image recognition from the camera , and approach visible objectives ) other tasks might be database or remotely driven ( look up a list of probable objective locations from a database , and then navigate there to see if you can get into visible range of one of them ) Some of the tasks themselves have child tasks , which is essentially going to start this process over recursively at a subset of tasks , and the grandchild task will be passed up through the chain foreach ( child in Children ) { if ( child.ShouldRun ( ) ) { child.Run ( ) ; break ; } }",Efficient foreach child evaluation in parallel "C_sharp : Why does i have this error and how to fix it . Thanks for help Error 4 Can not convert lambda expression to type 'System.Delegate ' because it is not a delegate type void provider_GetAssignmentsComplete ( object sender , QP_Truck_Model.Providers.GetAssignmentsEventArgs e ) { lvMyAssignments.Dispatcher.BeginInvoke ( ( ) = > { lvMyAssignments.ItemsSource = e.HandOverDocs ; } ) ; }",C # BeginInvoke problem "C_sharp : I have a TextBox in WPF . I want to restrict the length of the text in the TextBox . There is an easy way to restrict the number of characters by the property MaxLength.In my use case I need to restrict the text not by the number of characters but by length of the binary representation of the text in a given encoding . As the program is used by germans there are some umlaut , that consume two byte.I already have a method , that checks , if a given string fits into the given length : Does anybody has an idea how to tie this function to the textbox in a way , that the user has no possibility to enter too much characters to exceed the maximum byte length . Solutions without EventHandler are prefered as the TextBox is inside a DataTemplate . public bool IsInLength ( string text , int maxLength , Encoding encoding ) { return encoding.GetByteCount ( text ) < maxLength ; }",Constraint length of Text in TextBox by its encoded representation C_sharp : I am hoping for fruitful answer to this . How should i move the settings provided in web.config for asp.net membership into a database for cross application customization . For example membership information include belowExtra.NET 2.0ASP.NET 2.0Relatedmoving asp.net membership specific settings to a separate config file < providers > < add name= '' OdbcProvider '' type= '' Samples.AspNet.Membership.OdbcMembershipProvider '' connectionStringName= '' OdbcServices '' enablePasswordRetrieval= '' true '' enablePasswordReset= '' true '' requiresQuestionAndAnswer= '' true '' writeExceptionsToEventLog= '' true '' / > < /providers > < /membership >,Moving asp.net membership web.config settings to Database Is this even possible ? "C_sharp : I have a List < CustomPoint > points ; which contains close to million objects.From this list I would like to get the List of objects that are occuring exactly twice . What would be the fastest way to do this ? I would also be interested in a non-Linq option also since I might have to do this in C++ also.based on this answer , i tried , but this is giving zero objects in the new list.Can someone guide me on this ? public class CustomPoint { public double X { get ; set ; } public double Y { get ; set ; } public CustomPoint ( double x , double y ) { this.X = x ; this.Y = y ; } } public class PointComparer : IEqualityComparer < CustomPoint > { public bool Equals ( CustomPoint x , CustomPoint y ) { return ( ( x.X == y.X ) & & ( y.Y == x.Y ) ) ; } public int GetHashCode ( CustomPoint obj ) { int hash = 0 ; hash ^= obj.X.GetHashCode ( ) ; hash ^= obj.Y.GetHashCode ( ) ; return hash ; } } list.GroupBy ( x = > x ) .Where ( x = > x.Count ( ) = 2 ) .Select ( x = > x.Key ) .ToList ( ) ;",Getting List of Objects that occurs exaclty twice in a list "C_sharp : I 'm attempting to use the ReaderWriterLockSlim class to manage a list.There are many reads to this list and few writes , my reads are fast whereas my writes are slow.I have a simple test harness written to check how the lock works.If the following situation occursThen the outcome is as followsIs there any way of changing the behaviour of the lock so that any Read requests that were queued before a write lock are allowed to complete before the write locks are granted ? EDIT : The code that demonstrates the issue I have is below Thread 1 - Start WriteThread 2 - Start ReadThread 3 - Start Write Thread 1 starts its write and locks the list.Thread 2 adds itself to the read queue.Thread 3 adds itself to the write queue.Thread 1 finishes writing and releases the lockThread 3 aquires the lock and starts its writeThread 3 finishes writing and releases the lockThread 2 performs its read public partial class SimpleLock : System.Web.UI.Page { public static ReaderWriterLockSlim threadLock = new ReaderWriterLockSlim ( ) ; protected void Page_Load ( object sender , EventArgs e ) { List < String > outputList = new List < String > ( ) ; Thread thread1 = new Thread ( delegate ( object output ) { ( ( List < String > ) output ) .Add ( `` Write 1 Enter '' ) ; threadLock.EnterWriteLock ( ) ; ( ( List < String > ) output ) .Add ( `` Write 1 Begin '' ) ; Thread.Sleep ( 100 ) ; ( ( List < String > ) output ) .Add ( `` Write 1 End '' ) ; threadLock.ExitWriteLock ( ) ; ( ( List < String > ) output ) .Add ( `` Write 1 Exit '' ) ; } ) ; thread1.Start ( outputList ) ; Thread.Sleep ( 10 ) ; Thread thread2 = new Thread ( delegate ( object output ) { ( ( List < String > ) output ) .Add ( `` Read 2 Enter '' ) ; threadLock.EnterReadLock ( ) ; ( ( List < String > ) output ) .Add ( `` Read 2 Begin '' ) ; Thread.Sleep ( 100 ) ; ( ( List < String > ) output ) .Add ( `` Read 2 End '' ) ; threadLock.ExitReadLock ( ) ; ( ( List < String > ) output ) .Add ( `` Read 2 Exit '' ) ; } ) ; thread2.Start ( outputList ) ; Thread.Sleep ( 10 ) ; Thread thread3 = new Thread ( delegate ( object output ) { ( ( List < String > ) output ) .Add ( `` Write 3 Enter '' ) ; threadLock.EnterWriteLock ( ) ; ( ( List < String > ) output ) .Add ( `` Write 3 Begin '' ) ; Thread.Sleep ( 100 ) ; ( ( List < String > ) output ) .Add ( `` Write 3 End '' ) ; threadLock.ExitWriteLock ( ) ; ( ( List < String > ) output ) .Add ( `` Write 3 Exit '' ) ; } ) ; thread3.Start ( outputList ) ; thread1.Join ( ) ; thread2.Join ( ) ; thread3.Join ( ) ; Response.Write ( String.Join ( `` < br / > '' , outputList.ToArray ( ) ) ) ; } }",ReaderWriterLockSlim Blocking reads until all queued writes are complete "C_sharp : I always thought that the answer to this was no , but I can not find any source stating this.In my class below , can I access ( managed ) fields/properties of an instance of C in the finalizer , i.e . in ReleaseUnmanaged ( ) ? What restrictions , if any , are there ? Will GC or finalization ever have set these members to null ? The only thing I can find is that stuff on the finalizer queue can be finalized in any order . So in that case , since the recommendation is that types should allow users to call Dispose ( ) more than once , why does the recommended pattern bother with a disposing boolean ? What bad things might happen if my finalizer called Dispose ( true ) instead of Dispose ( false ) ? public class C : IDisposable { private void ReleaseUnmanaged ( ) { } private void ReleaseOtherDisposables ( ) { } protected virtual void Dispose ( bool disposing ) { ReleaseUnmanaged ( ) ; if ( disposing ) { ReleaseOtherDisposables ( ) ; } } ~ C ( ) { Dispose ( false ) ; } public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } }",Can I access reference type instance fields/properties safely within a finalizer ? "C_sharp : I 've been tasked with creating a partially editable RichTextBox . I 've seen suggestions in Xaml adding TextBlock elements for the ReadOnly sections , however this has the undesireable visual effect of not wrapping nicely . ( It should appear as a single block of continuous text . ) I 've patched together a working prototype using some reverse string formatting to restrict/allow edits and coupled that with dynamic creation of inline Run elements for displaying purposes . Using a dictionary to store the current values of the editable sections of text , I update the Run elements accordingly upon any TextChanged event trigger - with the idea that if an editable section 's text is completely deleted , it will be replaced back to its default value.In the string : `` Hi NAME , welcome to SPORT camp . `` , only NAME and SPORT are editable.Problem : Deleting the entire text value in a particular run removes that run ( and the following run ) from the RichTextBox Document . Even though I add them all back , they no longer display correctly on screen . For example , using the edited string from the above setup : User highlights the text `` John '' and clicks Delete , instead of saving the empty value , it should be replaced with the default text of `` NAME '' . Internally this happens . The dictionary gets the correct value , the Run.Text has the value , the Document contains all the correct Run elements . But the screen displays : Expected : `` Hi NAME , welcome to Tennis camp . `` Actual : `` Hi NAMETennis camp . `` Sidenote : This loss-of-Run-element behavior can also be duplicated when pasting . Highlight `` SPORT '' and paste `` Tennis '' and the Run containing `` camp . '' is lost.Question : How do I keep every Run element visible even through destructive actions , once they 've been replaced ? Code : I have tried to strip down the code to a minimum example , so I 've removed : Every DependencyProperty and associated binding in the xamlLogic recalculating caret position ( sorry ) Refactored the linked string formatting extension methods from the first link to a single method contained within the class . ( Note : this method will work for simple example string formats . My code for more robust formatting has been excluded . So please stick to the example provided for these testing purposes . ) Made the editable sections clearly visible , nevermind the color scheme.To test , drop the class into your WPF project Resource folder , fix the namespace , and add the control to a View . ╔═══════╦════════╗ ╔═══════╦════════╗Default values : ║ Key ║ Value ║ Edited values : ║ Key ║ Value ║ ╠═══════╬════════╣ ╠═══════╬════════╣ ║ NAME ║ NAME ║ ║ NAME ║ John ║ ║ SPORT ║ SPORT ║ ║ SPORT ║ Tennis ║ ╚═══════╩════════╝ ╚═══════╩════════╝ `` Hi NAME , welcome to SPORT camp . '' `` Hi John , welcome to Tennis camp . '' using System.Collections.Generic ; using System.Linq ; using System.Text.RegularExpressions ; using System.Windows.Controls ; using System.Windows.Documents ; using System.Windows.Media ; namespace WPFTest.Resources { public class MyRichTextBox : RichTextBox { public MyRichTextBox ( ) { this.TextChanged += MyRichTextBox_TextChanged ; this.Background = Brushes.LightGray ; this.Parameters = new Dictionary < string , string > ( ) ; this.Parameters.Add ( `` NAME '' , `` NAME '' ) ; this.Parameters.Add ( `` SPORT '' , `` SPORT '' ) ; this.Format = `` Hi { 0 } , welcome to { 1 } camp . `` ; this.Text = string.Format ( this.Format , this.Parameters.Values.ToArray < string > ( ) ) ; this.Runs = new List < Run > ( ) { new Run ( ) { Background = Brushes.LightGray , Tag = `` Hi `` } , new Run ( ) { Background = Brushes.Black , Foreground = Brushes.White , Tag = `` NAME '' } , new Run ( ) { Background = Brushes.LightGray , Tag = `` , welcome to `` } , new Run ( ) { Background = Brushes.Black , Foreground = Brushes.White , Tag = `` SPORT '' } , new Run ( ) { Background = Brushes.LightGray , Tag = `` camp . '' } , } ; this.UpdateRuns ( ) ; } public Dictionary < string , string > Parameters { get ; set ; } public List < Run > Runs { get ; set ; } public string Text { get ; set ; } public string Format { get ; set ; } private void MyRichTextBox_TextChanged ( object sender , TextChangedEventArgs e ) { string richText = new TextRange ( this.Document.Blocks.FirstBlock.ContentStart , this.Document.Blocks.FirstBlock.ContentEnd ) .Text ; string [ ] oldValues = this.Parameters.Values.ToArray < string > ( ) ; string [ ] newValues = null ; bool extracted = this.TryParseExact ( richText , this.Format , out newValues ) ; if ( extracted ) { var changed = newValues.Select ( ( x , i ) = > new { NewVal = x , Index = i } ) .Where ( x = > x.NewVal ! = oldValues [ x.Index ] ) .FirstOrDefault ( ) ; string key = this.Parameters.Keys.ElementAt ( changed.Index ) ; this.Parameters [ key ] = string.IsNullOrWhiteSpace ( newValues [ changed.Index ] ) ? key : newValues [ changed.Index ] ; this.Text = richText ; } else { e.Handled = true ; } this.UpdateRuns ( ) ; } private void UpdateRuns ( ) { this.TextChanged -= this.MyRichTextBox_TextChanged ; foreach ( Run run in this.Runs ) { string value = run.Tag.ToString ( ) ; if ( this.Parameters.ContainsKey ( value ) ) { run.Text = this.Parameters [ value ] ; } else { run.Text = value ; } } Paragraph p = this.Document.Blocks.FirstBlock as Paragraph ; p.Inlines.Clear ( ) ; p.Inlines.AddRange ( this.Runs ) ; this.TextChanged += this.MyRichTextBox_TextChanged ; } public bool TryParseExact ( string data , string format , out string [ ] values ) { int tokenCount = 0 ; format = Regex.Escape ( format ) .Replace ( `` \\ { `` , `` { `` ) ; format = string.Format ( `` ^ { 0 } $ '' , format ) ; while ( true ) { string token = string.Format ( `` { { { 0 } } } '' , tokenCount ) ; if ( ! format.Contains ( token ) ) { break ; } format = format.Replace ( token , string.Format ( `` ( ? 'group { 0 } ' . * ) '' , tokenCount++ ) ) ; } RegexOptions options = RegexOptions.None ; Match match = new Regex ( format , options ) .Match ( data ) ; if ( tokenCount ! = ( match.Groups.Count - 1 ) ) { values = new string [ ] { } ; return false ; } else { values = new string [ tokenCount ] ; for ( int index = 0 ; index < tokenCount ; index++ ) { values [ index ] = match.Groups [ string.Format ( `` group { 0 } '' , index ) ] .Value ; } return true ; } } } }",How to stop RichTextBox Inline from being deleted in TextChanged ? "C_sharp : I was exploring the sources of ASP.NET core on GitHub to see what kind of tricks the ASP.NET team used to speed up the framework . I saw something that intrigued me . In the source code of the ServiceProvider , in the Dispose implementation , they enumerate a dictionary , and they put a comment to indicate a performance trick : What is the difference if the dictionary is enumerated like that ? It has a performance impact ? Or it 's because allocate a ValueCollection will consume more memory ? private readonly Dictionary < IService , object > _resolvedServices = new Dictionary < IService , object > ( ) ; // Code removed for brevitypublic void Dispose ( ) { // Code removed for brevity // PERF : We 've enumerating the dictionary so that we do n't allocate to enumerate . // .Values allocates a KeyCollection on the heap , enumerating the dictionary allocates // a struct enumerator foreach ( var entry in _resolvedServices ) { ( entry.Value as IDisposable ) ? .Dispose ( ) ; } _resolvedServices.Clear ( ) ; } foreach ( var entry in _resolvedServices.Values ) { ( entry as IDisposable ) ? .Dispose ( ) ; }",Enumerate Dictionary.Values vs Dictionary itself "C_sharp : I have run in to a little bit of a problem which is not solved by the generally available solutions to seemingly the same problem.Consider : I have a set of dynamically generated classes , inheriting from a known base Class ( lets call it BaseClass ) .These dynamically generated classes also have dynamically generated Properties with associated attributes.The attributes are also of a custom class , though not dynamically generated : Then I want to , runtime of course , fetch the value of this assigned attribute : where target is a subclass of BaseClass . The List result is however empty , and this baffles me.I add the attribute usingwhere dataType is the type to store in the attribute and tb is the TypeBuilder for the class.If I do getCustomAttributes ( ) on the property , I get the expected attributes except the one I 'm looking for . But if I do getCustomAttributesData ( ) I get all of them , but the one I 'm looking for is of type CustomAttributeData and is not castable to TypeAttribute ( if i examine the instance in the VS debugger i can see that the contained information is for a TypeAttribute ) .I 'm guessing that this is a symptom of the problem , but I can not find the cause - much less the solution.Can anybody point out to me why the result list is empty ? [ AttributeUsage ( AttributeTargets.Property ) ] class TypeAttribute : Attribute { private Type _type ; public Type Type { get { return _type ; } } public TypeAttribute ( Type t ) { _type = t ; } } List < PropertyInfo > result = target.GetType ( ) .GetProperties ( ) .Where ( p = > p.GetCustomAttributes ( typeof ( TypeAttribute ) , true ) //.Where ( ca = > ( ( TypeAttribute ) ca ) . ) .Any ( ) ) .ToList ( ) ; PropertyBuilder propertyBuilder = tb.DefineProperty ( propertyName , PropertyAttributes.HasDefault , propertyType , null ) ; ConstructorInfo classCtorInfo = typeof ( TypeAttribute ) . GetConstructor ( new Type [ ] { typeof ( Type ) } ) ; CustomAttributeBuilder myCABuilder = new CustomAttributeBuilder ( classCtorInfo , new object [ ] { getType ( dataType ) } ) ; propertyBuilder.SetCustomAttribute ( myCABuilder ) ;",Get Attribute from Dynamically generated Class "C_sharp : I ca n't figure out a discrepancy between the time it takes for the Contains method to find an element in an ArrayList and the time it takes for a small function that I wrote to do the same thing . The documentation states that Contains performs a linear search , so it 's supposed to be in O ( n ) and not any other faster method . However , while the exact values may not be relevant , the Contains method returns in 00:00:00.1087087 seconds while my function takes 00:00:00.1876165 . It might not be much , but this difference becomes more evident when dealing with even larger arrays . What am I missing and how should I write my function to match Contains 's performances ? I 'm using C # on .NET 3.5.EDIT : Okay , now , lads , look : I made an average of 100 running times for two versions of my function ( forward and backward loop ) and for the default Contains function . The times I 've got are 136 and 133 milliseconds for my functions and a distant winner of 87 for the Contains version . Well now , if before you could argue that the data was scarce and I based my conclusions on a first , isolated run , what do you say about this test ? Not does only on average Contains perform better , but it achieves consistently better results in each run . So , is there some kind of disadvantage in here for 3rd party functions , or what ? public partial class Window1 : Window { public bool DoesContain ( ArrayList list , object element ) { for ( int i = 0 ; i < list.Count ; i++ ) if ( list [ i ] .Equals ( element ) ) return true ; return false ; } public Window1 ( ) { InitializeComponent ( ) ; ArrayList list = new ArrayList ( ) ; for ( int i = 0 ; i < 10000000 ; i++ ) list.Add ( `` zzz `` + i ) ; Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; //Console.Out.WriteLine ( list.Contains ( `` zzz 9000000 '' ) + `` `` + sw.Elapsed ) ; Console.Out.WriteLine ( DoesContain ( list , `` zzz 9000000 '' ) + `` `` + sw.Elapsed ) ; } } public partial class Window1 : Window { public bool DoesContain ( ArrayList list , object element ) { int count = list.Count ; for ( int i = count - 1 ; i > = 0 ; i -- ) if ( element.Equals ( list [ i ] ) ) return true ; return false ; } public bool DoesContain1 ( ArrayList list , object element ) { int count = list.Count ; for ( int i = 0 ; i < count ; i++ ) if ( element.Equals ( list [ i ] ) ) return true ; return false ; } public Window1 ( ) { InitializeComponent ( ) ; ArrayList list = new ArrayList ( ) ; for ( int i = 0 ; i < 10000000 ; i++ ) list.Add ( `` zzz `` + i ) ; Stopwatch sw = new Stopwatch ( ) ; long total = 0 ; int nr = 100 ; for ( int i = 0 ; i < nr ; i++ ) { sw.Reset ( ) ; sw.Start ( ) ; DoesContain ( list , '' zzz '' ) ; total += sw.ElapsedMilliseconds ; } Console.Out.WriteLine ( total / nr ) ; total = 0 ; for ( int i = 0 ; i < nr ; i++ ) { sw.Reset ( ) ; sw.Start ( ) ; DoesContain1 ( list , `` zzz '' ) ; total += sw.ElapsedMilliseconds ; } Console.Out.WriteLine ( total / nr ) ; total = 0 ; for ( int i = 0 ; i < nr ; i++ ) { sw.Reset ( ) ; sw.Start ( ) ; list.Contains ( `` zzz '' ) ; total += sw.ElapsedMilliseconds ; } Console.Out.WriteLine ( total / nr ) ; } }",How can I make my function run as fast as `` Contains '' on an ArrayList ? "C_sharp : The main question in about the maximum number of items that can be in a collection such as List . I was looking for answers on here but I do n't understand the reasoning.Assume we are working with a List < int > with sizeof ( int ) = 4 bytes ... Everyone seems to be sure that for x64 you can have a maximum 268,435,456 int and for x86 a maximum of 134,217,728 int . Links : List size limitation in C # Where is the maximum capacity of a C # Collection < T > defined ? What 's the max items in a List < T > ? However , when I tested this myself I see that it 's not the case for x86 . Can anyone point me to where I may be wrong ? For x64 : 268435456 ( expected ) For x86 : 67108864 ( 2 times less than expected ) Why do people say that a List containing 134217728 int is exactly 512MB of memory ... when you have 134217728 * sizeof ( int ) * 8 = 4,294,967,296 = 4GB ... what 's way more than 2GB limit per process.Whereas 67108864 * sizeof ( int ) * 8 = 2,147,483,648 = 2GB ... which makes sense . I am using .NET 4.5 on a 64 bit machine running windows 7 8GB RAM . Running my tests in x64 and x86.EDIT : When I set capacity directly to List < int > ( 134217728 ) I get a System.OutOfMemoryException.EDIT2 : Error in my calculations : multiplying by 8 is wrong , indeed MB =/= Mbits . I was computing Mbits . Still 67108864 ints would only be 256MB ... which is way smaller than expected . //// Test engine set to ` x86 ` for ` default processor architecture ` [ TestMethod ] public void TestMemory ( ) { var x = new List < int > ( ) ; try { for ( long y = 0 ; y < long.MaxValue ; y++ ) x.Add ( 0 ) ; } catch ( Exception ) { System.Diagnostics.Debug.WriteLine ( `` Actual capacity ( int ) : `` + x.Count ) ; System.Diagnostics.Debug.WriteLine ( `` Size of objects : `` + System.Runtime.InteropServices.Marshal.SizeOf ( x.First ( ) .GetType ( ) ) ) ; //// This gives us `` 4 '' } }",Maximum capacity of Collection < T > different than expected for x86 "C_sharp : I 'm having a hard time finding what , I think , should be a fairly simple method.I think we 've all used this : In C # , I 've have to write stuff like this : This works , but it 's just wordy.Out of frustration , I wrote an extension method to accomplish what I 'm trying to do.Now , I can write shorter code : It feels dirty , however , to write my own method for something that I just ca n't find in the framework.Any help you folks can offer would be great , ThanksEDIT : Thanks everyone for the in-depth anaylsis . I think I 'll keep using my In ( ) method . select someThing from someTable where someColumn in ( 'item1 ' , 'item2 ' ) if ( someEnum == someEnum.Enum1 || someEnum == someEnum.Enum2 || someEnum == someEnum.Enum3 ) { this.DoSomething ( ) ; } namespace System { public static class SystemExtensions { public static bool In < T > ( this T needle , params T [ ] haystack ) { return haystack.Contains ( needle ) ; } } } if ( someEnum.In ( someEnum.Enum1 , someEnum.Enum2 , someEnum.Enum3 ) ) this.DoSomething ( ) ; if ( someInt.In ( CONSTANT1 , CONSTANT2 ) ) this.DoSomethingElse ( ) ;",C # In ( ) method ? ( like Sql ) "C_sharp : When using await , by default the SynchronizationContext ( if one exists ) is captured and the codeblocks after the await ( continuation blocks ) is executed using that context ( which results in thread context switches ) .While this default might make sense in the context of the UI where you want to be back on the UI-thread after an asynchronous operation completes , it does n't seem make sense as the default for most other scenarios . It certainly does n't make sense for internal library code , becauseIt comes with the overhead of unnecessary thread context switches.It is very easy to accidentaly produce deadlocks ( as documented here or here ) .It seems to me that Microsoft have decided for the wrong default.Now my question : Is there any other ( preferably better ) way to solve this than by cluttering all await calls in my code with .ConfigureAwait ( false ) ? This is just so easy to forget and makes the code less readable . Update : Would it maybe suffice to call await Task.Yield ( ) .ConfigureAwait ( false ) ; at the beginning of each method ? If this would guarantee me that I will be on a thread without a SynchronizationContext aferwards , all subsequent await calls would not capture any context . public async Task DoSomethingAsync ( ) { // We are on a thread that has a SynchronizationContext here . await DoSomethingElseAsync ( ) ; // We are back on the same thread as before here // ( well sometimes , depending on how the captured SynchronizationContext is implemented ) }","disable capturing context in all library code , ConfigureAwait ( false )" "C_sharp : We 're facing a major performance problem after upgrading EF Core 2.2 to EF Core 3.0 . Imagine a simple data model with a single collection navigation property and hundreds of fields ( the reality looks even darker ) : andDuring item retrieval , we 're querying as followed : Straight forward , up until this point . In EF 2.2 , fetching that queryable results in two separate queries , one for Item and one for the AddInfo - level . These queries usually fetch 10.000 items and around 250.000 AddInfos.In EF Core 3.0 however , a single query is being generated , left-joining AddInfo to Item that on first glance appears to be the better option . Our Item however needs to be fetched with all 100+ fields , which is why projecting to a smaller class or anonymous type ( adding a call to the .Select ( ... ) -method ) is n't feasible . Therefore , the result set has so much redundancy in it ( each Item approx . 25 times ) that the query itself takes too long to run in an acceptable time.Does EF-Core 3.0 provide any option that would enable us to switch back to the query-behavior of the good old EF Core 2.2 times without extensive changes to our data model ? We 're already profiting from this change in other parts of the application , but not in this particular scenario.Many thanks in advance ! UpdateAfter further investigation I found that this issue is already adressed with Microsoft here and out of the box , there seems to be no way to configure the split query execution . public class Item { [ Key ] public int ItemID { get ; set ; } public ICollection < AddInfo > AddInfos { get ; set ; } ... // consisting of another 100+ properties ! } public class AddInfo { [ Key ] public int AddInfoID { get ; set ; } public int ? ItemID { get ; set ; } public string SomePayload { get ; set ; } } ... var myQueryable = this._context.Items.Include ( i = > i.AddInfos ) .Where ( **some filter** ) ; ... // moar filtersvar result = myQueryable.ToList ( ) ;",Entity Framework Core 3.0 performance impact for including collection navigation properties ( cartesian explosion ) "C_sharp : I have a problem with streaming video . I developed the server on ASP.NET Web API 2 and implemented 2 methods : The first method:2 ) The second method : Both of these methods worked on Web-client and Android-client , but iOS-client does n't show video.I think , that problem may be with codec of video ( but I used codecs , which recommend Apple ) or http-headers . if ( Request.Headers.Range ! = null ) { try { var httpResponce = Request.CreateResponse ( ) ; httpResponce.Content = new PushStreamContent ( ( Action < Stream , HttpContent , TransportContext > ) WriteContentToStream ) ; return httpResponce ; } catch ( Exception ex ) { return new HttpResponseMessage ( HttpStatusCode.InternalServerError ) ; } } else { return new HttpResponseMessage ( HttpStatusCode.RequestedRangeNotSatisfiable ) ; } /*method for streaming*/private async void WriteContentToStream ( Stream outputStream , HttpContent content , TransportContext transportContext ) { string relativeFilePath = `` ~/App_Data/Videos/4.mp4 '' ; try { var filePath = System.Web.Hosting.HostingEnvironment.MapPath ( relativeFilePath ) ; int bufferSize = 1000 ; byte [ ] buffer = new byte [ bufferSize ] ; using ( var fileStream = new FileStream ( filePath , FileMode.Open , FileAccess.Read , FileShare.Read ) ) { int totalSize = ( int ) fileStream.Length ; while ( totalSize > 0 ) { int count = totalSize > bufferSize ? bufferSize : totalSize ; int sizeOfReadedBuffer = fileStream.Read ( buffer , 0 , count ) ; await outputStream.WriteAsync ( buffer , 0 , sizeOfReadedBuffer ) ; totalSize -= sizeOfReadedBuffer ; } } } catch ( HttpException ex ) { if ( ex.ErrorCode == -2147023667 ) { return ; } } finally { outputStream.Close ( ) ; } } public HttpResponseMessage Test ( ) { if ( Request.Headers.Range ! = null ) { try { string relativeFilePath = `` ~/App_Data/Videos/4.mp4 '' ; var filePath = System.Web.Hosting.HostingEnvironment.MapPath ( relativeFilePath ) ; HttpResponseMessage partialResponse = Request.CreateResponse ( HttpStatusCode.PartialContent ) ; partialResponse.Headers.AcceptRanges.Add ( `` bytes '' ) ; var stream = new FileStream ( filePath , FileMode.Open , FileAccess.Read ) ; partialResponse.Content = new ByteRangeStreamContent ( stream , Request.Headers.Range , new MediaTypeHeaderValue ( `` video/mp4 '' ) ) ; return partialResponse ; } catch ( Exception ) { return new HttpResponseMessage ( HttpStatusCode.InternalServerError ) ; } } else { return new HttpResponseMessage ( HttpStatusCode.RequestedRangeNotSatisfiable ) ; } }",Problems with streaming video for IOS Client ( Server developed on ASP.NET WEB API 2 ) C_sharp : This is my Action methodWhat is the best practice for returning this error ? In a userfriendly way and in a way that I could identity this error when it occurs . var model= db.PageData.FirstOrDefault ( ) ; if ( model==null ) { //return Error } reutrn View ( model ) ;,what is the best practice for returning a error in asp.net mvc C_sharp : i use the following XSLT by using XMLSpy : If i try to use it in my source ( XslCompiledTransform ) i get an exception telling me that the function 'lower-case ( ) ' is not part of the XSLT synthax.So i changed the transformation a little bit : Now my exception is that the script or external object prefixed by 'http : //www.w3.org/2005/xpath-functions ' can not be found.Whats the matter here ? How can i fix it ? Regards < ? xml version= '' 1.0 '' encoding= '' UTF-16 '' ? > < xsl : stylesheet version= '' 2.0 '' xmlns : xsl= '' http : //www.w3.org/1999/XSL/Transform '' xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' xmlns : fn= '' http : //www.w3.org/2005/xpath-functions '' > < xsl : output method= '' xml '' version= '' 1.0 '' encoding= '' UTF-16 '' indent= '' yes '' / > < xsl : template match= '' * '' > < xsl : element name= '' { lower-case ( local-name ( ) ) } '' > < xsl : apply-templates select= '' @ * '' / > < xsl : apply-templates select= '' * | text ( ) '' / > < /xsl : element > < /xsl : template > < xsl : template match= '' @ * '' > < xsl : attribute name= '' { lower-case ( local-name ( ) ) } '' > < xsl : value-of select= '' . `` / > < /xsl : attribute > < /xsl : template > < /xsl : stylesheet > fn : lower-case,XSLT lower-case using .NET C_sharp : To test that something throws for example an ArgumentException I can do this : How can I check that the ParamName is correct in a clear way ? And bonus question : Or would you perhaps perhaps recommend not testing this at all ? Assert.Throws < ArgumentException > ( ( ) = > dog.BarkAt ( deafDog ) ) ;,"C # , NUnit : Clear way of testing that ArgumentException has correct ParamName" "C_sharp : I 'm pretty stumped with this so if anyone has any ideas . I have the generic methodAnd I want to call this method from another generic method , but this generic method does n't have the type constraint `` where TClass : class '' This does n't work , I get the error `` The type 'T ' must be a reference type in order to use it as parameter 'TClass ' '' Which I understand . But my question is this - is there anything I can do with C # syntax in order to `` filter '' the generic type `` T '' to pass it to `` this.Bar '' if it is a class . Something like ... .I realise I could use reflection to call Foo , but this just seems like cheating . Is there something I can do with C # to pass `` T '' on with the constraint at runtime ? Also - I ca n't change the constraint on the method `` Bar '' as it comes from an interface so the constraint has to match the constraint on the interface public void Foo < TClass > ( TClass item ) where TClass : class { } public void Bar < T > ( T item ) { this.Foo < T > ( item ) ; } public void Bar < T > ( T item ) { if ( typeof ( T ) .IsClass ) this.Foo < T **as class** > ( ) ; }",Adding generic constraints at runtime ? "C_sharp : I have 2 partial classes in main/editor projects unity , but unity show me error message `` error CS1061 : Type 'Engine.Test ' does not contain a definition for 'radius ' and no extension method 'radius ' of type 'Engine.Test ' could be found . Are you missing an assembly reference ? `` ./Assets/Test.cs ( in main project ) : ./Assets/Editor/TestEditor.cs ( in project Editor ) : What am i doing wrong ? namespace Engine { public partial class Test : MonoBehaviour { [ SerializeField ] private float radius = 1f ; } } namespace Engine { public partial class Test { private void OnDrawGizmosSelected ( ) { Gizmos.color = new Color ( 1f , 1f , 0f , 0.3f ) ; Gizmos.DrawSphere ( new Vector3 ( 0,0,0 ) , radius ) ; // in `` this '' context field `` radius '' not found } } }",Unity partial class does not contain a definition "C_sharp : According to the documentation here : https : //developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/v3/020_key_concepts/0700_other_topics # SalesItemLineDetailI should have the ability to set a UnitPrice so my Invoices show UnitPrice , Qty and a SubTotal.I have Invoices working great but I am missing this critical piece of information , here is my code for generating a Line on an Invoice : Does anyone have this working ? What am I missing here ? foreach ( var i in orderItems ) { Line invLine = new Line ( ) ; invLine.Id = i.ItemID ; invLine.Amount = i.SubTotal.Value ; invLine.AmountSpecified = true ; invLine.Description = i.ItemName ; invLine.DetailType = LineDetailTypeEnum.SalesItemLineDetail ; invLine.DetailTypeSpecified = true ; SalesItemLineDetail silDetails = new SalesItemLineDetail ( ) ; silDetails.Qty = i.Qty ; silDetails.QtySpecified = true ; silDetails.ItemRef = new ReferenceType ( ) { Value = i.ItemID } ; invLine.AnyIntuitObject = silDetails ; invoice.Line [ lineCount ] = invLine ; lineCount += 1 ; }",No UnitPrice available on SalesItemLineDetail using IPP .NET SDK for QuickBooks v3.0 ? "C_sharp : I have a ASP.NET Core application that has two endpoints . One is the MVC and the other is the Grpc . I need that the kestrel publishs each endpoint on different sockets . Example : localhost:8888 ( MVC ) and localhost:8889 ( Grpc ) .I know how to publish two endpoints on Kestrel . But the problem is that it 's publishing the MVC and the gRPC on both endpoints and I do n't want that . This is because I need the Grpc requests use Http2 . On the other hand , I need that MVC requests use Http1on my Statup.cs I haveI need a way to make endpoints.MapGrpcService < ComunicacaoService > ( ) ; be published on one socket and the endpoints.MapControllerRoute ( `` default '' , '' { controller } / { action=Index } / { id ? } '' ) ; on another one . public void Configure ( IApplicationBuilder app ) { // ... . app.UseEndpoints ( endpoints = > { endpoints.MapGrpcService < ComunicacaoService > ( ) ; endpoints.MapControllerRoute ( `` default '' , `` { controller } / { action=Index } / { id ? } '' ) ; } ) ; // ...",Publish two different endpoints on Kestrel for two different endpoints on ASP.NET Core "C_sharp : Before Swashbuckle 5 it was possible to define and register a ISchemaFilter that could provide an example implementation of a model : The Schema.Example would take an arbitrary object , and it would properly serialize when generating the OpenApi Schema.However , with the move to .NET Core 3 and Swashbuckle 5 the Schema.Example property is no longer an object and requires the type Microsoft.OpenApi.Any.IOpenApiAny . There does not appear to be a documented path forward regarding how to provide a new example.I 've attempted , based on looking at code within Microsoft.OpenApi , to build my own implementation of an IOpenApiAny but any attempt to use it to generate an example fails from within Microsoft.OpenApi.Writers.OpenApiWriterAnyExtensions.WriteObject ( IOpenApiWriter writer , OpenApiObject entity ) before its Write method is even called . I do n't claim that the code below is fully correct , but I would have expected it to at a minimum light up a path and to how to move forward.What is the proper way to transition ISchemaFilter examples to Swashbuckle 5.0 so that the appropriate serialization rules are respected ? public class MyModelExampleSchemaFilter : ISchemaFilter { public void Apply ( Schema schema , SchemaFilterContext context ) { if ( context.SystemType.IsAssignableFrom ( typeof ( MyModel ) ) ) { schema.Example = new MyModel { Name = `` model name '' , value = 42 } ; } } } /// < summary > /// A class that recursively adapts a unidirectional POCO tree into an < see cref= '' IOpenApiAny '' / > /// < /summary > /// < remarks > /// < para > This will fail if a graph is provided ( backwards and forwards references < /para > /// < /remarks > public class OpenApiPoco : IOpenApiAny { /// < summary > /// The model to be converted /// < /summary > private readonly object _model ; /// < summary > /// Initializes a new instance of the < see cref= '' OpenApiPoco '' / > class . /// < /summary > /// < param name= '' model '' > the model to convert to an < see cref= '' IOpenApiAny '' / > < /param > public OpenApiPoco ( object model ) { this._model = model ; } /// < inheritdoc / > public AnyType AnyType = > DetermineAnyType ( this._model ) ; # region From Interface IOpenApiExtension /// < inheritdoc / > public void Write ( IOpenApiWriter writer , OpenApiSpecVersion specVersion ) { this.Write ( this._model , writer , specVersion ) ; } # endregion private static AnyType DetermineAnyType ( object model ) { if ( model is null ) { return AnyType.Null ; } var modelType = model.GetType ( ) ; if ( modelType.IsAssignableFrom ( typeof ( int ) ) || modelType.IsAssignableFrom ( typeof ( long ) ) || modelType.IsAssignableFrom ( typeof ( float ) ) || modelType.IsAssignableFrom ( typeof ( double ) ) || modelType.IsAssignableFrom ( typeof ( string ) ) || modelType.IsAssignableFrom ( typeof ( byte ) ) || modelType.IsAssignableFrom ( typeof ( byte [ ] ) ) // Binary or Byte || modelType.IsAssignableFrom ( typeof ( bool ) ) || modelType.IsAssignableFrom ( typeof ( DateTimeOffset ) ) // DateTime || modelType.IsAssignableFrom ( typeof ( DateTime ) ) // Date ) { return AnyType.Primitive ; } if ( modelType.IsAssignableFrom ( typeof ( IEnumerable ) ) ) // test after primitive check so as to avoid catching string and byte [ ] { return AnyType.Array ; } return AnyType.Object ; // Assume object } private void Write ( object model , [ NotNull ] IOpenApiWriter writer , OpenApiSpecVersion specVersion ) { if ( writer is null ) { throw new ArgumentNullException ( nameof ( writer ) ) ; } if ( model is null ) { writer.WriteNull ( ) ; return ; } var modelType = model.GetType ( ) ; if ( modelType.IsAssignableFrom ( typeof ( int ) ) || modelType.IsAssignableFrom ( typeof ( long ) ) || modelType.IsAssignableFrom ( typeof ( float ) ) || modelType.IsAssignableFrom ( typeof ( double ) ) || modelType.IsAssignableFrom ( typeof ( string ) ) || modelType.IsAssignableFrom ( typeof ( byte [ ] ) ) // Binary or Byte || modelType.IsAssignableFrom ( typeof ( bool ) ) || modelType.IsAssignableFrom ( typeof ( DateTimeOffset ) ) // DateTime || modelType.IsAssignableFrom ( typeof ( DateTime ) ) // Date ) { this.WritePrimitive ( model , writer , specVersion ) ; return ; } if ( modelType.IsAssignableFrom ( typeof ( IEnumerable ) ) ) // test after primitive check so as to avoid catching string and byte [ ] { this.WriteArray ( ( IEnumerable ) model , writer , specVersion ) ; return ; } this.WriteObject ( model , writer , specVersion ) ; // Assume object } private void WritePrimitive ( object model , IOpenApiWriter writer , OpenApiSpecVersion specVersion ) { switch ( model.GetType ( ) ) { case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( string ) ) : // string writer.WriteValue ( ( string ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( byte [ ] ) ) : // assume Binary ; ca n't differentiate from Byte and Binary based on type alone // if we chose to treat byte [ ] as Byte we would Base64 it to string . eg : writer.WriteValue ( Convert.ToBase64String ( ( byte [ ] ) propertyValue ) ) ; writer.WriteValue ( Encoding.UTF8.GetString ( ( byte [ ] ) model ) ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( bool ) ) : // boolean writer.WriteValue ( ( bool ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( DateTimeOffset ) ) : // DateTime as DateTimeOffset writer.WriteValue ( ( DateTimeOffset ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( DateTime ) ) : // Date as DateTime writer.WriteValue ( ( DateTime ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( double ) ) : // Double writer.WriteValue ( ( double ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( float ) ) : // Float writer.WriteValue ( ( float ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( int ) ) : // Integer writer.WriteValue ( ( int ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( long ) ) : // Long writer.WriteValue ( ( long ) model ) ; break ; case TypeInfo typeInfo when typeInfo.IsAssignableFrom ( typeof ( Guid ) ) : // Guid ( as a string ) writer.WriteValue ( model.ToString ( ) ) ; break ; default : throw new ArgumentOutOfRangeException ( nameof ( model ) , model ? .GetType ( ) .Name , `` unexpected model type '' ) ; } } private void WriteArray ( IEnumerable model , IOpenApiWriter writer , OpenApiSpecVersion specVersion ) { writer.WriteStartArray ( ) ; foreach ( var item in model ) { this.Write ( item , writer , specVersion ) ; // recursive call } writer.WriteEndArray ( ) ; } private void WriteObject ( object model , IOpenApiWriter writer , OpenApiSpecVersion specVersion ) { var propertyInfos = model.GetType ( ) .GetProperties ( ) ; writer.WriteStartObject ( ) ; foreach ( var property in propertyInfos ) { writer.WritePropertyName ( property.Name ) ; var propertyValue = property.GetValue ( model ) ; switch ( propertyValue.GetType ( ) ) { case TypeInfo typeInfo // primitives when typeInfo.IsAssignableFrom ( typeof ( string ) ) // string || typeInfo.IsAssignableFrom ( typeof ( byte [ ] ) ) // assume Binary or Byte || typeInfo.IsAssignableFrom ( typeof ( bool ) ) // boolean || typeInfo.IsAssignableFrom ( typeof ( DateTimeOffset ) ) // DateTime as DateTimeOffset || typeInfo.IsAssignableFrom ( typeof ( DateTime ) ) // Date as DateTime || typeInfo.IsAssignableFrom ( typeof ( double ) ) // Double || typeInfo.IsAssignableFrom ( typeof ( float ) ) // Float || typeInfo.IsAssignableFrom ( typeof ( int ) ) // Integer || typeInfo.IsAssignableFrom ( typeof ( long ) ) // Long || typeInfo.IsAssignableFrom ( typeof ( Guid ) ) : // Guid ( as a string ) this.WritePrimitive ( propertyValue , writer , specVersion ) ; break ; case TypeInfo typeInfo // Array test after primitive check so as to avoid catching string and byte [ ] when typeInfo.IsAssignableFrom ( typeof ( IEnumerable ) ) : // Enumerable as array of objects this.WriteArray ( ( IEnumerable ) propertyValue , writer , specVersion ) ; break ; case TypeInfo typeInfo // object when typeInfo.IsAssignableFrom ( typeof ( object ) ) : // Object default : this.Write ( propertyValue , writer , specVersion ) ; // recursive call break ; } } writer.WriteEndObject ( ) ; } }",Transitioning ISchemaFilter examples to Swashbuckle 5.0 "C_sharp : I am new to WP7 coding.I am looking for sample code or guiding on the following task : I had 3 html pages on remote server and I want to download the contents of each of the page and post it to 3 different panorama page ( show as a textblock ) .I had written 3 set of webclient to load the html page ; it can be shown as where it suppose to be . My issue facing is , when/during the downloading , the UI thread is `` freez '' and unresponsive.Can anyone guide me / show me the sample code that I can put the thread to background and once it finish , and shown in the UI ? This is the code that I use to download the HTML page.I 'd modified the above code as per suggestion by Sinh Pham , and it work perfectly as it expected . But , Since I need to run 3 instant of it to download the page from different souce at he same time ; the code break . Any idea ? private async void GetNewsIndex ( string theN ) { string newsURI = newsURL + theN ; string fileName = theN + `` -temp.html '' ; string folderName = `` news '' ; prgBar01.Visibility = System.Windows.Visibility.Visible ; try { Task < string > contentDataDownloaded = new WebClient ( ) .DownloadStringTaskAsync ( new Uri ( newsURI ) ) ; string response = await contentDataDownloaded ; WriteTempFile ( theN , response.ToString ( ) ) ; string contentData = ProcessDataToXMLNews ( fileName , folderName ) ; WritenewsIndexXMLFile ( newsIndexURI , folderName , contentData ) ; DisplayNewsIndex ( ) ; } catch { // } }",freeze in UI during download content in WP7 "C_sharp : I have a small demo WinForms app . One of the Forms is my Add New Person form . I used the Details View instead of the DataGridView from my Data Sources . When I enter data and click the save button on the Navigator there are zero changes , However I put a MovePrevious and a MoveNext after my AddNew in the form Load , everything works as expected . Why do I need to toggle the BindingSource Position before it will recognize changes and save ? public partial class AddPersonForm : Form { private readonly DemoContext _context ; public AddPersonForm ( ) { _context = new DemoContext ( ) ; InitializeComponent ( ) ; } protected override void OnLoad ( EventArgs e ) { _context.People.Load ( ) ; personBindingSource.DataSource = _context.People.Local.ToBindingList ( ) ; personBindingSource.AddNew ( ) ; personBindingSource.MovePrevious ( ) ; personBindingSource.MoveNext ( ) ; base.OnLoad ( e ) ; } private void personBindingNavigatorSaveItem_Click ( object sender , EventArgs e ) { int changes = _context.SaveChanges ( ) ; Debug.WriteLine ( `` # of changes : `` + changes ) ; } }",Why do I need to change the Binding Source Position before I can SaveChanges "C_sharp : Consider the following code sample : This gives the error A local variable named 'test ' can not be declared in this scope because it would give a different meaning to 'test ' , which is already used in a 'child ' scope to denote something elseBut I do n't understand why ? The outer test variable starts in line 7 and not in line 2 , so where 's the problem to declare a second variable called test on line 4 with a scope ending on line 5 ? // line # { // 1 // 2 { // 3 double test = 0 ; // 4 } // 5 // 6 double test = 0 ; // 7 } // 8",C # scope question "C_sharp : I 'm trying emulate the Tint Effect of Open XML . What it does is change the hue of pixels in an image by shifting the hue . It takes 2 parameters : 1 ) the hue ( in degrees ) and 2 ) the amt ( the amount , a percentage ) . It is # 2 that I 'm having issues with . The spec states : Tint : Shifts effect color values either towards or away from hue by the specified amount . amt ( Amount ) - Specifies by how much the color value is shifted . hue ( Hue ) - Specifies the hue towards which to tint . Never minding the XML construction , I can emulate values that have an amt of 100 % . So for example , if I want Blue ( hue : 240° ) , I can create this ( the Tinted one ) . Here 's an example : Original and Tinted ( hue = 240 , Amount = 100 % ) . This is achieved simply by setting the hue to 240 , keeping saturation and luminance the same and converting to RGB and writing each pixel.Here 's what I ca n't achieve though : Hue=240 ( blue ) , Amount = 30 % , 50 % and 80 % , respectively Again , the spec for Amount says Specifies by how much the color value is shifted . I 've tried all sorts of ways here to get this to work , but ca n't seem to ( hue=hue*amount , originalhue * amount + hue , etc . ) More examples : Hue=120 ( green ) , Amount = 30 % , 50 % , 80 % and 100 % , respectively . The 100 % one I can get . Here are some value lists of a single pixel in the pictures above : Pixel 159 , 116 - Blue PicturesPixel 159 , 116 - Green PicturesSo , the question is : Does anyone know how this should work ? Note : This is not a duplicate of : Changing the tint of a bitmap while preserving the overall brightness Rotate Hue using ImageAttributes in C # ... or anything else I could find on SO Hue Amount R G B | H S LOriginal 244 196 10 | 48 0.92 0.5Blue 240 30 % 237 30 45 | 356 0.85 0.52Blue 240 50 % 245 9 156 | 323 0.93 0.5Blue 240 80 % 140 12 244 | 273 0.91 0.5Blue 240 100 % 12 12 244 | 240 0.91 0.5 Hue Amount R G B | H S LOriginal 244 196 10 | 48 0.92 0.5Green 120 30 % 211 237 30 | 68 0.85 0.52Green 120 50 % 159 237 30 | 83 0.85 0.52Green 120 80 % 81 237 29 | 105 0.85 0.52Green 120 100 % 29 237 29 | 120 0.85 0.52",Tinting Towards or Away from a Hue By a Certain Percentage "C_sharp : I have a model that has an integer property . When the model is submitted with 23443 , the model binder works great and the value is available in the action . But if the model is submitted with a thousands separator like 23,443 , the value is n't parsed and the property is zero . But I found that a property with the type of decimal could have the thousands separator and it would parse and be populated correctly.I found out that by default Int32.Parse ( ) does n't parse thousands separator but Decimal.Parse ( ) does allow thousands separator . I do n't want to have to write a check like : every time I deal with these fields . It looks ugly , and moves all the validation out of the model attributes . Changing the type of the property to decimal just to make the model binding work does n't seem like a smart idea . When I look into the model binder , it looks like it 's using TypeConverter to complete the conversions from string to the type . And it looks like Int32Converter uses Int32.Parse ( ) with NumberStyles.Integer . Is there a way to change the behavior of Int32Converter to allow the thousands separator to be parsed by default ? Maybe override the default NumberStyles on Int32.Parse ( ) across the entire app ? Or is adding my own model binder which parses the integers with NumberStyles.AllowThousands the only/correct course of action ? public ActionResult Save ( Car model , FormCollection form ) { Int32 milage ; if ( model.MyProperty == 0 & & Int32.TryParse ( form [ `` MyProperty '' ] , NumberStyles.AllowThousands , CultureInfo.InvariantCulture , out milage ) { model.MyProperty = milage ; } else ModelState.AddModelError ( `` Invalid '' , `` Property looks invalid '' ) ; [ ... ] }",Change default NumberStyles on integers ? "C_sharp : I am trying to detect Circle inside Rectangle in AForge . I have successfully determined Rectangles but unable to find circles inside Rectangle . How to find shape inside another shape in AForge . string strPath = Server.MapPath ( `` ~/Recipt001.png '' ) ; Bitmap myBitmap = new Bitmap ( strPath ) ; //Some filters Grayscale , invert , threshold//Blod Filtering BlobCounter blobCounter = new BlobCounter ( ) ; blobCounter.ProcessImage ( temp ) ; blobCounter.ObjectsOrder = ObjectsOrder.YX ; blobCounter.FilterBlobs = true ; Blob [ ] blobs = blobCounter.GetObjectsInformation ( ) ; Graphics g = Graphics.FromImage ( myBitmap ) ; Pen redPen = new Pen ( Color.Red , 2 ) ; SimpleShapeChecker shapeChecker = new SimpleShapeChecker ( ) ; // dictionary of color to highlight different shapesDictionary < PolygonSubType , Color > colors = new Dictionary < PolygonSubType , Color > ( ) ; colors.Add ( PolygonSubType.Unknown , Color.White ) ; colors.Add ( PolygonSubType.Trapezoid , Color.Orange ) ; colors.Add ( PolygonSubType.Parallelogram , Color.Red ) ; colors.Add ( PolygonSubType.Rectangle , Color.Green ) ; colors.Add ( PolygonSubType.Square , Color.Blue ) ; colors.Add ( PolygonSubType.Rhombus , Color.Gray ) ; colors.Add ( PolygonSubType.EquilateralTriangle , Color.Pink ) ; colors.Add ( PolygonSubType.IsoscelesTriangle , Color.Purple ) ; colors.Add ( PolygonSubType.RectangledTriangle , Color.SkyBlue ) ; colors.Add ( PolygonSubType.RectangledIsoscelesTriangle , Color.SeaGreen ) ; for ( int i = 0 , n = blobs.Length ; i < n ; i++ ) { List < IntPoint > corners ; List < IntPoint > edgePoints = blobCounter.GetBlobsEdgePoints ( blobs [ i ] ) ; Point center ; double radius ; if ( shapeChecker.IsQuadrilateral ( edgePoints , out corners ) ) { if ( shapeChecker.CheckPolygonSubType ( corners ) == PolygonSubType.Rectangle ) { g.DrawPolygon ( redPen , ToPointsArray ( corners ) ) ; } } } redPen.Dispose ( ) ; g.Dispose ( ) ;",How to find circle inside Rectangle in AForge "C_sharp : I 've searched StackOverflow but still can not understand the correct syntax to use Single , First ( or default ) queries.I 'm willing to make a query to catch first the translation in specific language . If there is no such translation on the db , get the first one in English.Here is what I got so far : EditObs . : items is an IEnumerable locale = `` ja-jp '' ; var items = from c in db.Contents.Include ( `` Translation '' ) where c.RegionalInfo.Any ( x = > x.RegionId == locale ) select c ;",First ? Single ? Or Default ? "C_sharp : In the pluralsight video of http : //www.asp.net/mvc . The model object member were changed to virtual in the middle of a video . He did n't give detail description of the change . Could any one elaborate the necessity ? BTW , is the IDBContext in the video follows repository pattern ? Should the code use repository pattern for best practice if it 's not ? Update : It should be a variety of repository pattern . Usually repository pattern create one class for one model object IRepository < T > . This one put all the model object in one interface Restaurants , Reviews . How this one compares with the typical one ? public class Restaurant { public virtual int ID { get ; set ; } public virtual string Name { get ; set ; } public virtual Address Address { get ; set ; } public virtual ICollection < Review > Reviews { get ; set ; } } public interface IDbContext { IQueryable < Restaurant > Restaurants { get ; } IQueryable < Review > Reviews { get ; } int SaveChanges ( ) ; T Attach < T > ( T entity ) where T : class ; T Add < T > ( T entity ) where T : class ; T Delete < T > ( T entity ) where T : class ; }",Why the members of the domain object ( POCO ) are defined virtual ? "C_sharp : I have this code I run in linqpad : It produces this output : Note the last two lines : x.Equals ( y ) is false but y.Equals ( x ) is true . So the decimal considers itself equal to a long with the same value but the long does n't consider itself equal to the decimal that has the same value.What 's the explanation for this behavior ? Update : I accepted Lee 's answer.I was very curious about this and wrote this little program : Which I then disassembled in IL : You can see indeed that the long value is converted to decimal.Thank you guys ! long x = long.MaxValue ; decimal y = x ; x.Dump ( ) ; y.Dump ( ) ; ( x == y ) .Dump ( ) ; ( y == x ) .Dump ( ) ; Object.Equals ( x , y ) .Dump ( ) ; Object.Equals ( y , x ) .Dump ( ) ; x.Equals ( y ) .Dump ( ) ; y.Equals ( x ) .Dump ( ) ; 9223372036854775807 9223372036854775807 True True False False False True using System ; namespace TestConversion { class Program { static void Main ( string [ ] args ) { long x = long.MaxValue ; decimal y = x ; Console.WriteLine ( x ) ; Console.WriteLine ( y ) ; Console.WriteLine ( x == y ) ; Console.WriteLine ( y == x ) ; Console.WriteLine ( Object.Equals ( x , y ) ) ; Console.WriteLine ( Object.Equals ( y , x ) ) ; Console.WriteLine ( x.Equals ( y ) ) ; Console.WriteLine ( y.Equals ( x ) ) ; Console.ReadKey ( ) ; } } } .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint .maxstack 2 .locals init ( [ 0 ] int64 x , [ 1 ] valuetype [ mscorlib ] System.Decimal y ) L_0000 : nop L_0001 : ldc.i8 9223372036854775807 L_000a : stloc.0 L_000b : ldloc.0 L_000c : call valuetype [ mscorlib ] System.Decimal [ mscorlib ] System.Decimal : :op_Implicit ( int64 ) L_0011 : stloc.1 L_0012 : ldloc.0 L_0013 : call void [ mscorlib ] System.Console : :WriteLine ( int64 ) L_0018 : nop L_0019 : ldloc.1 L_001a : call void [ mscorlib ] System.Console : :WriteLine ( valuetype [ mscorlib ] System.Decimal ) L_001f : nop L_0020 : ldloc.0 L_0021 : call valuetype [ mscorlib ] System.Decimal [ mscorlib ] System.Decimal : :op_Implicit ( int64 ) L_0026 : ldloc.1 L_0027 : call bool [ mscorlib ] System.Decimal : :op_Equality ( valuetype [ mscorlib ] System.Decimal , valuetype [ mscorlib ] System.Decimal ) L_002c : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_0031 : nop L_0032 : ldloc.1 L_0033 : ldloc.0 L_0034 : call valuetype [ mscorlib ] System.Decimal [ mscorlib ] System.Decimal : :op_Implicit ( int64 ) L_0039 : call bool [ mscorlib ] System.Decimal : :op_Equality ( valuetype [ mscorlib ] System.Decimal , valuetype [ mscorlib ] System.Decimal ) L_003e : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_0043 : nop L_0044 : ldloc.0 L_0045 : box int64 L_004a : ldloc.1 L_004b : box [ mscorlib ] System.Decimal L_0050 : call bool [ mscorlib ] System.Object : :Equals ( object , object ) L_0055 : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_005a : nop L_005b : ldloc.1 L_005c : box [ mscorlib ] System.Decimal L_0061 : ldloc.0 L_0062 : box int64 L_0067 : call bool [ mscorlib ] System.Object : :Equals ( object , object ) L_006c : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_0071 : nop L_0072 : ldloca.s x L_0074 : ldloc.1 L_0075 : box [ mscorlib ] System.Decimal L_007a : call instance bool [ mscorlib ] System.Int64 : :Equals ( object ) L_007f : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_0084 : nop L_0085 : ldloca.s y L_0087 : ldloc.0 L_0088 : call valuetype [ mscorlib ] System.Decimal [ mscorlib ] System.Decimal : :op_Implicit ( int64 ) L_008d : call instance bool [ mscorlib ] System.Decimal : :Equals ( valuetype [ mscorlib ] System.Decimal ) L_0092 : call void [ mscorlib ] System.Console : :WriteLine ( bool ) L_0097 : nop L_0098 : call valuetype [ mscorlib ] System.ConsoleKeyInfo [ mscorlib ] System.Console : :ReadKey ( ) L_009d : pop L_009e : ret }",Why is Equals between long and decimal not commutative ? C_sharp : I want to create a stub for this interface in RhinoMocks.I have a read only property and i want to increment his value every time i call the IncrementValue ( ) method . Is this possible ? I do n't want to create a class new for this stub . public interface ICell { int Value { get ; } void IncrementValue ( ) ; },Stub the behavior of a readOnly property "C_sharp : Will compiler optimize this code or will the collection be initialized after each method call ? If answer is negative , I recommend to use this solution : Creating a constant Dictionary in C # private string Parse ( string s ) { var dict = new Dictionary < string , string > { { `` a '' , `` x '' } , { `` b '' , `` y '' } } ; return dict [ s ] ; }",Will compiler optimize collections initialization ? "C_sharp : I am trying to use aleagpu but I get the System.TypeInitializationException . I have tried to google what the problem is but I could n't find any solution , so please help . The program is the simplest possible : I am imagining that there is something wrong in my installation , because the program is a copied example from aleagpu 's homepage.My system is : Windows 10.NET v4.5.2VS 2015 CommunityNVIDIA GPU computing toolkit CUDA v8.0Alea is installed from NuGet November 9 . 2016Alea ( 3.0.1 ) Alea.IL ( 2.2.0.3307 ) Alea.CUDA ( 2.2.0.3307 ) Alea.CUDA.IL ( 2.2.0.3307 ) Alea.CUDA.Unbound ( 2.2.0.3307 ) The variables in PATH is correct.I have tried the AleaSample.CS.ParallelForAutoMemMgt as well with the same result . class Klazz { private const int N = 100 ; private const int Length = 10000000 ; var gpu = Gpu.Default ; // here is the Exception thrown public static void Unmanaged ( ) { var data = new int [ Length ] ; for ( var k = 0 ; k < N ; k++ ) gpu.For ( 0 , data.Length , i = > data [ i ] += 1 ) ; } }",TypeInitializationException thrown by aleagpu "C_sharp : I need to write a bunch of methods that take 1..N generic type parameters , eg : Inside Foo ( ) I would like to do something for each type , egIs there any way to parameterize this so that I am not editing every variation of Foo ( ) , something analogous to : Ideally , I 'd also like to be able to get an array or collection of the types as well : int Foo < T1 > ( ) ; int Foo < T1 , T2 > ( ) ; int Foo < T1 , T2 , T3 > ( ) ; ... int Foo < T1 , T2 , T3 ... TN > ( ) ; int Foo < T1 , T2 , T3 > ( ) { this.data = new byte [ 3 ] ; // allocate 1 array slot per type } int Foo < T1 , T2 , T3 > ( ) { this.data = new byte [ _NUMBER_OF_GENERIC_PARAMETERS ] ; } int Foo < T1 , T2 , T3 > ( ) { this.data = new byte [ _NUMBER_OF_GENERIC_PARAMETERS ] ; // can do this Type [ ] types = new Type [ ] { T1 , T2 , T3 } ; // but would rather do this Type [ ] types = _ARRAY_OR_COLLECTION_OF_THE_GENERIC_PARAMETERS ; }",C # generics : any way to refer to the generic parameter types as a collection ? C_sharp : Do i have to set my if statement as Is there a way to have something like if ( Test == `` test1 '' || Test == `` test2 '' || Test == `` test3 '' ) { //do something } if ( Test == `` test1 '' : '' test2 '' : '' test3 '' ),Can I have an if statement like this ? If Test = `` test1 '' or `` test2 '' or `` test3 '' without going the long way ? C_sharp : Here is a my code inside a c # project that targets .NET Core 3.0 ( so I should be in C # 8.0 ) with Visual Studio 2019 ( 16.3.9 ) The compile error is : CS1061 'SumRequest ' does not contain a definition for 'ToJson ' and no accessible extension method 'ToJson ' accepting a first argument of type 'SumRequest ' could be found ( are you missing a using directive or an assembly reference ? ) Can someone shed some light on this behavior ? public interface IJsonAble { public string ToJson ( ) = > System.Text.Json.JsonSerializer.Serialize ( this ) ; } public class SumRequest : IJsonAble { public int X { get ; set ; } public int Y { get ; set ; } public void Tmp ( ) { new SumRequest ( ) .ToJson ( ) ; //compile error } },Default implementation in interface is not seen by the compiler ? "C_sharp : I 'm having some trouble with computed data from a static class in a C # Xunit test being computed twice.The actual production code this would be used for is much more complicated , but the code that follows is enough to exhibit the issue I am seeing.In the code below I have a randomly generated , lazily loaded int seeded off of the current time.All I am testing here is that this property is equal to itself . I insert the property 's value into the test via a MemberData function.Since the property ought to only be initialized once , I 'd expect that this test should always pass . I would expect that the static field would be initialized when the RandomIntMemberData function is run and never again.However , this test consistently fails . The value inserted into the test , and the value tested against are always different.Further if I debug , I only see the initialization code being hit once . That is , the value being tested . I never see the initialization of the value being tested against.Am I misunderstanding something , or is Xunit doing some weird behind the scenes magic to setup it 's input data , then initializing the value again when the test is actually run ? Minimal Code to Reproduce BugThe Test public static class TestRandoIntStaticClass { private static readonly Lazy < int > LazyRandomInt = new Lazy < int > ( ( ) = > { // lazily initialize a random interger seeded off of the current time // according to readings , this should happen only once return new Random ( ( int ) DateTime.Now.Ticks ) .Next ( ) ; } ) ; // according to readings , this should be a thread safe operation public static int RandomInt = > LazyRandomInt.Value ; } public class TestClass { public static IEnumerable < object [ ] > RandomIntMemberData ( ) { var randomInt = new List < object [ ] > { new object [ ] { TestRandoIntStaticClass.RandomInt } , } ; return randomInt as IEnumerable < object [ ] > ; } [ Theory ] [ MemberData ( nameof ( RandomIntMemberData ) ) ] public void RandoTest ( int rando ) { // these two ought to be equal if TestRandoIntStaticClass.RandomInt is only initialized once Assert.True ( rando == TestRandoIntStaticClass.RandomInt , $ '' { nameof ( rando ) } = { rando } but { nameof ( TestRandoIntStaticClass.RandomInt ) } = { TestRandoIntStaticClass.RandomInt } '' ) ; } }",Static Data from xunit MemberData function is computed twice "C_sharp : I am using a badly written 3rd party ( C/C++ ) Api . I used it from managed code ( C++/ CLI ) . Get sometimes `` access violation errors '' . And this crash whole application . I know i can not handle those errors [ what can i do if a pointer acess to illegal memory location etc ] .But I do not want my application crash as a whole . At least if there is a real problem , my application gracefully should say `` OK.I can not do my job.BYE. `` : - ) then it least execute some alternative scenarious and finally close itself.But there seems to be no way , to catch ( may be wrong term , the rigth word may be to be informed about ) access violation and similiar errors.Is there a way to be informed about those errors . So i can execute my alternative scenarious.PS : Standard Exception handling does not solve this . # include `` stdafx.h '' # include < iostream > using namespace System ; using namespace std ; static void ThrowingManagedException ( ) { throw gcnew ArgumentException ( `` For no good reason '' ) ; } static void ThrowingNativeException ( ) { throw std : :exception ( `` For no good reason '' ) ; } static void SomeBadThingsHappen ( ) { short a [ 1 ] ; a [ 0 ] =1 ; a [ 2 ] = 2 ; // SomeOne make stupid mistake } int main ( array < System : :String ^ > ^args ) { Console : :WriteLine ( L '' Test Exceptions '' ) ; try { SomeBadThingsHappen ( ) ; //ThrowingNativeException ( ) ; //ThrowingManagedException ( ) ; } catch ( Exception^ e ) { Console : :WriteLine ( `` Something awful happened : `` + e ) ; } Console : :WriteLine ( `` Press enter to exit '' ) ; Console : :Read ( ) ; return 0 ; }","Handling errors while using unmanaged code in a managed one ( C++ , C , C++/CLI , C # )" C_sharp : Consider a piece of code like : Can I be certain that the WebClient.Dispose ( ) call occurs and that any exception produced is rethrown to the caller as if there was no call to ContinueWith ? Can clients observe this ContinueWith ? ( e.g . will later calls to ContinueWith remove the Dispose call ? ) private Task < string > Download ( ) { var wc = new WebClient ( ) ; Task < string > backgroundDownload = wc.DownloadStringTaskAsync ( this.Uri ) ; // Make sure the WebClient is disposed no matter what . backgroundDownload.ContinueWith ( ( downloadTask ) = > { wc.Dispose ( ) ; } ) ; return backgroundDownload ; },Is it safe to use ContinueWith as a `` finally '' operation ? "C_sharp : Paste the above code into a usercontrol . Drop the usercontrol onto a form and anchor it to all 4 points.In the designer ( Under Visual Studio 2010 ) it renders perfectly ( even as you resize ) . Run it and try and resize the form and the ellipse becomes skewed.Here are two examples both after resizes the first while running , the second in the designer.Obviously the behavior in the designer ca n't always be assumed to be the same ( Although it would be nice ) but my understanding is that the code above is completely legal . Am I wrong ? private void UserControl1_Paint ( object sender , PaintEventArgs e ) { e.Graphics.DrawEllipse ( Pens.Black , new Rectangle ( -200 , -500 , this.Width + 400 , this.Height + 420 ) ) ; }",Bug or am I doing something wrong ? Usercontrol Painting "C_sharp : I have a code engine that plays long WAV files by playing smaller chunks in succession using the waveOutOpen and waveOutWrite API methods . In order to update my UI as the file plays , from the callback function as each buffer completes playing I Invoke a separate thread ( because you want to do as little as possible inside the callback function ) that calls a method in my form.The form contains a class level EventHandler that handles a method within which I update UI elements with new information . In the form method called from the waveOutWrite callback function , I use the Invoke method like so : Everythings works , but it appears that once in a while there is a noticeable lag or delay in the updating of the UI elements . This is easy to see because I am using the UpdateDisplay method to drive an animation , so the delays appear as `` hiccups '' where the sprite appears to freeze for a split second before it jumps to its expected position.Is it possible that there is sometimes a long ( maybe 10-15 milliseconds ) delay involved in cross-thread communication like this ? If so , what 's a better way of handling something like this ? Update : by the way , I 'm definitely not sure that Invoke is the culprit here . Another possibility is a lag between when a chunk of audio finishes playing and when the callback function actually gets called.Update 2 : per itowlson 's suggestion , I used a System.Diagnostics.Stopwatch to benchmark the lag between Invoke and method call . Out of 1156 measurements , I got 1146 at 0ms , 8 at 1ms , and 2 at 2ms . I think it 's safe to say Invoke is not my culprit here . if ( _updatedisplay == null ) { // UpdateDisplay contains code to set control properties on the form _updatedisplay = new EventHandler ( UpdateDisplay ) ; } Invoke ( _updatedisplay ) ;",How long is the delay between Control.Invoke ( ) and the calling of its Delegate ? "C_sharp : Code : I am getting the error message as Can not define PRIMARY KEY constraint on nullable column in table 'AspNetRoles'.Namespace of MigrationBuilder - Microsoft.Data.Entity.Relational.Migrations.BuildersHow to assign NOT NULL to the above code in ASP.NET MVC 6 migrationBuilder.AddPrimaryKey ( `` AspNetRoles '' , `` PK_AspNetRoles '' , new [ ] { `` Id '' } , isClustered : true ) ;",ASP.NET MVC 6 - Assigning NOT NULL to the Primary Key in Entity Framework 7 "C_sharp : This StackOverflow answer completely describes that a HashSet is unordered and its item enumeration order is undefined and should not be relied upon.However , This brings up another question : should I or should I not rely upon the enumeration order between two or more sebsequent enumerations ? Given there are no insertions or removals.For example , lets say I have added some items to a HashSet : Now , when I enumerate this set via foreach , let us say I receive this sequence : The question is : will the order preserve if I enumerate the set times and times again given I do no modifications ? Will it always be the same ? HashSet < int > set = new HashSet < int > ( ) ; set.Add ( 1 ) ; set.Add ( 2 ) ; set.Add ( 3 ) ; set.Add ( 4 ) ; set.Add ( 5 ) ; // Result : 1 , 3 , 4 , 5 , 2 .",Does HashSet preserve order between enumerations ? "C_sharp : I have to make a Diffie Hellman agreement with a third party that communicates the public keys in the .NET ECDiffieHellmanCng XmlString format . I can not change their code.What they send looks like this : They generate that using typical .NET Framework code like this : They expect to receive my public key in the same format.They use my public key like this : I work in .NET core 2.1 . Unfortunately the ECDiffieHellmanCng classes and the like are currently not implemented in .NET core.I thought I could use the BouncyCastle for .NET Core package for this : https : //www.nuget.org/packages/BouncyCastle.NetCore/I would assume these both implement the same standard and they would be compatible.I know how to do the agreement completely with the bouncy castle , however it 's not clear to me how to do that starting with the X and Y values in the xml that come out of the .NET ECDiffieHellmanCng and how to make sure I use compatible parameters.It 's also not clear to me how I get the X and Y values from the bouncy castle public key that I generate to send back to them.It does n't help that the bouncy castle for .net api is not exactly the same as the java api and the documentation is limited.Update 1 : After reading some comments below , it appears indeed that the ECDiffieHellmanCng are partially implemented in .NET Core . Most of the logic works but only ToXmlString and FromXmlString do n't work . That 's ok , I can work around that.However I 'm now running into a different problem . The curve that the other side uses is oid:1.3.132.0.35.However when I try to use this in .NET core , even with a basic example like this : Then I get this error : The error message is not clear to me . Is that curve really not supported ? Or is something wrong in the parameters , but then what exactly ? It would surprise me if the curve is not supported because nistP521 curve is supported and according to this IBM document I found online they are the same : https : //www.ibm.com/support/knowledgecenter/en/linuxonibm/com.ibm.linux.z.wskc.doc/wskc_r_ecckt.html < ECDHKeyValue xmlns= '' http : //www.w3.org/2001/04/xmldsig-more # '' > < DomainParameters > < NamedCurve URN= '' urn : oid:1.3.132.0.35 '' / > < /DomainParameters > < PublicKey > < X Value= '' 11 '' xsi : type= '' PrimeFieldElemType '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' / > < Y Value= '' 17 '' xsi : type= '' PrimeFieldElemType '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' / > < /PublicKey > < /ECDHKeyValue > using ( ECDiffieHellmanCng dhKey = new ECDiffieHellmanCng ( ) ) { dhKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash ; dhKey.HashAlgorithm = CngAlgorithm.Sha256 ; Console.WriteLine ( dhKey.PublicKey.ToXmlString ( ) ) ; } ECDiffieHellmanCngPublicKey pbkey = ECDiffieHellmanCngPublicKey.FromXmlString ( xmlHere ) ; using ( ECDiffieHellman dhBob = ECDiffieHellman.Create ( ECCurve.CreateFromValue ( `` 1.3.132.0.35 '' ) ) ) { using ( ECDiffieHellman dhAlice = ECDiffieHellman.Create ( ECCurve.CreateFromValue ( `` 1.3.132.0.35 '' ) ) ) { byte [ ] b = dhAlice.DeriveKeyMaterial ( dhBob.PublicKey ) ; byte [ ] b2 = dhBob.DeriveKeyMaterial ( dhAlice.PublicKey ) ; Console.WriteLine ( b.SequenceEqual ( b2 ) ) ; } } Unhandled Exception : System.PlatformNotSupportedException : The specified curve 'ECDSA_P521 ' or its parameters are not valid for this platform . -- - > Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException : The parameter is incorrect at System.Security.Cryptography.CngKeyLite.SetProperty ( SafeNCryptHandle ncryptHandle , String propertyName , Byte [ ] value ) at System.Security.Cryptography.CngKeyLite.SetCurveName ( SafeNCryptHandle keyHandle , String curveName ) at System.Security.Cryptography.CngKeyLite.GenerateNewExportableKey ( String algorithm , String curveName ) at System.Security.Cryptography.ECCngKey.GenerateKey ( ECCurve curve ) -- - End of inner exception stack trace -- - at System.Security.Cryptography.ECCngKey.GenerateKey ( ECCurve curve ) at System.Security.Cryptography.ECDiffieHellman.Create ( ECCurve curve ) at TestCore.Program.Main ( String [ ] args )",.NET ECDiffieHellmanCng and BouncyCastle Core compatible agreement "C_sharp : I have following tableData SampleI want to select only records which have occured after 5 mins from previous selected record and including the first record within the datasetDesired output isI am trying GroupBy but does n't give dateThank you in advance . CREATE TABLE [ dbo ] . [ DeviceLogs ] ( [ DeviceLogId ] [ int ] IDENTITY ( 1,1 ) NOT NULL , [ UserId ] [ nvarchar ] ( 50 ) NULL , [ LogDate ] [ datetime2 ] ( 0 ) NULL , ) GO 1 1 2013-05-29 11:05:15 //accepted ( its the first occurance for userid 1 ) 2 1 2013-05-29 11:05:20 //discarded ( within 5 mins from 1st record ) 3 1 2013-05-29 11:07:56 //discarded ( within 5 mins from 1st record ) 4 1 2013-05-29 11:11:15 //accepted ( after 5 mins from 1st occurance ) 5 2 2013-05-29 11:06:05 //accepted ( its the first occurance for userid 2 ) 6 2 2013-05-29 11:07:18 //discarded ( within 5 mins from 1st record ) 7 2 2013-05-29 11:09:38 //discarded ( within 5 mins from 1st record ) 8 2 2013-05-29 11:12:15 //accepted ( after 5 mins from 1st occurance ) 1 1 2013-05-29 11:05:15 4 1 2013-05-29 11:11:15 5 2 2013-05-29 11:06:05 8 2 2013-05-29 11:12:15 db.DeviceLogs.GroupBy ( g= > new { g.LogDate.Year , g.LogDate.Month , g.LogDate.Day , g.LogDate.Hour , g.LogDate.Minutes , g.UserID } ) .Select ( s= > new { UserID=s.Key.UserID , s. ? ? ? } ) ;",Select only first record within a time interval "C_sharp : Assuming an instance of MyClass is not rooted in any other way , will the private static reference here prevent it from being garbage collected ? public class MyClass { private static MyClass heldInstance ; public MyClass ( ) { heldInstance = this ; } }",Can a class that references itself in a static field be garbage collected ? "C_sharp : I was playing around with Constrained Execution Regions tonight to better round out my understanding of the finer details . I have used them on occasion before , but in those cases I mostly adhered strictly to established patterns . Anyway , I noticed something peculiar that I can not quite explain.Consider the following code . Note , I targeted .NET 4.5 and I tested it with a Release build without the debugger attached.What would you think the output of this program would be ? didfinally=Truedidfinally=FalseBefore you guess read the documentation . I include the pertinent sections below . A constrained execution region ( CER ) is part of a mechanism for authoring reliable managed code . A CER defines an area in which the common language runtime ( CLR ) is constrained from throwing out-of-band exceptions that would prevent the code in the area from executing in its entirety . Within that region , user code is constrained from executing code that would result in the throwing of out-of-band exceptions . The PrepareConstrainedRegions method must immediately precede a try block and marks catch , finally , and fault blocks as constrained execution regions . Once marked as a constrained region , code must only call other code with strong reliability contracts , and code should not allocate or make virtual calls to unprepared or unreliable methods unless the code is prepared to handle failures . The CLR delays thread aborts for code that is executing in a CER.and The reliability try/catch/finally is an exception handling mechanism with the same level of predictability guarantees as the unmanaged version . The catch/finally block is the CER . Methods in the block require advance preparation and must be noninterruptible.My particular concern right now is guarding against thread aborts . There are two kinds : your normal variety via Thread.Abort and then the one where a CLR host can go all medieval on you and do a forced abort . finally blocks are already protected against Thread.Abort to some degree . Then if you declare that finally block as a CER then you get added protection from CLR host aborts as well ... at least I think that is the theory.So based on what I think I know I guessed # 1 . It should print didfinally=True . The ThreadAbortException gets injected while the code is still in the try block and then the CLR allows the finally block to run as would be expected even without a CER right ? Well , this is not the result I got . I got a totally unexpected result . Neither # 1 or # 2 happened for me . Instead , my program hung at Thread.Abort . Here is what I observe.The presence of PrepareConstrainedRegions delays thread aborts inside try blocks.The absence of PrepareConstrainedRegions allows them in try blocks.So the million dollar question is why ? The documentation does not mention this behavior anywhere that I can see . In fact , most of the stuff I am reading is actually suggesting that you put critical uninterruptable code in the finally block specifically to guard against thread aborts.Perhaps , PrepareConstrainedRegions delays normal aborts in a try block in addition to the finally block . But CLR host aborts are only delayed in the finally block of a CER ? Can anyone provide more clarity on this ? public class Program { public static void Main ( string [ ] args ) { bool toggle = false ; bool didfinally = false ; var thread = new Thread ( ( ) = > { Console.WriteLine ( `` running '' ) ; RuntimeHelpers.PrepareConstrainedRegions ( ) ; try { while ( true ) { toggle = ! toggle ; } } finally { didfinally = true ; } } ) ; thread.Start ( ) ; Console.WriteLine ( `` sleeping '' ) ; Thread.Sleep ( 1000 ) ; Console.WriteLine ( `` aborting '' ) ; thread.Abort ( ) ; Console.WriteLine ( `` aborted '' ) ; thread.Join ( ) ; Console.WriteLine ( `` joined '' ) ; Console.WriteLine ( `` didfinally= '' + didfinally ) ; Console.Read ( ) ; } }",Can this unexpected behavior of PrepareConstrainedRegions and Thread.Abort be explained ? "C_sharp : I have two ReorderList One is a parent and other is its child . I want to change dynamically the ConnectionString property of SqlDataSource through code behind but I am unable to change ConnectionString property of Child ReorderList even I tried OnItemDataBound and tried to find the control and change its property but could not . Here is a sample of code which I am using : I can change the ConnectionString of SqlDataSource1 through code behind and its accessible but SqlDataSource2 is not accessible . Anyone kindly give me a clue how to achieve this as I want to assign Connection String from code behind . < div class= '' reorderListDemo '' style= '' width : 100 % '' > < cc1 : ReorderList ID= '' ReorderList1 '' runat= '' server '' DataSourceID= '' SqlDataSource1 '' DataKeyField= '' RecordingFilterId '' AllowReorder= '' true '' SortOrderField= '' Priority '' PostBackOnReorder= '' False '' > < ItemTemplate > < table style= '' width : 100 % '' cellpadding= '' 0 '' cellspacing= '' 0 '' border= '' 0 '' > < tr > < td width= '' 6 % '' style= '' padding-left:5px ; padding-top:3px ; '' > < a href= '' javascript : switchViews ( 'divRF < % # Eval ( `` RecordingFilterId '' ) % > ' , 'dragHandle < % # Eval ( `` RecordingFilterId '' ) % > ' ) ; '' > < img id= '' imgdivRF < % # Eval ( `` RecordingFilterId '' ) % > '' border= '' 0 '' src= '' Images/expand.png '' / > < /a > < /td > < td width= '' 34 % '' > < asp : Label ID= '' Label7 '' runat= '' server '' Text= ' < % # Eval ( `` Name '' ) % > ' meta : resourcekey= '' Label7Resource1 '' / > < /td > < /tr > < tr > < td colspan= '' 6 '' width= '' 100 % '' style= '' padding-right:10px ; '' > < div id= '' divRF < % # Eval ( `` RecordingFilterId '' ) % > '' style= '' display : none ; width : 99 % ; '' > < table style= '' width : 100 % ; '' cellspacing= '' 0 '' cellpadding= '' 0 '' border= '' 0 '' > < tbody > < tr > < td style= '' color : white ; width : 15 % ; padding-left : 30px ; '' class= '' topleft '' align= '' left '' > < div > < b > < asp : Label ID= '' Label3 '' runat= '' server '' Text= '' Rule '' meta : resourcekey= '' Label3Resource2 '' > < /asp : Label > < /b > < /div > < /td > < /tr > < /tbody > < /table > < div class= '' reorderListDemo '' style= '' margin-left : 0px ; width : 97 % ; '' > < cc1 : ReorderList ID= '' ReorderList2 '' runat= '' server '' PostBackOnReorder= '' False '' CallbackCssStyle= '' callbackStyle '' AllowReorder= '' True '' DataKeyField= '' RuleId '' SortOrderField= '' Priority '' > < ItemTemplate > < table style= '' width : 100 % '' cellpadding= '' 0 '' cellspacing= '' 0 '' border= '' 0 '' > < tr > < td align= '' left '' style= '' padding-left : 10px ; width : 15 % ; '' > < asp : Label ID= '' Label6 '' runat= '' server '' ToolTip= ' < % # Eval ( `` RuleName '' ) % > ' Text= ' < % # Eval ( `` RuleName '' ) .ToString ( ) .Length > 14 ? Eval ( `` RuleName '' ) .ToString ( ) .Substring ( 0,12 ) + `` .. '' : Eval ( `` RuleName '' ) .ToString ( ) % > ' / > < /td > < /tr > < /table > < /ItemTemplate > < ReorderTemplate > < asp : Panel ID= '' Panel2 '' runat= '' server '' CssClass= '' reorderCue '' meta : resourcekey= '' Panel2Resource1 '' > < /asp : Panel > < /ReorderTemplate > < DragHandleTemplate > < div class= '' dragHandleChild '' id= '' dragHandle < % # Eval ( `` RecordingFilterId '' ) % > '' > < /div > < /DragHandleTemplate > < /cc1 : ReorderList > < asp : SqlDataSource ID= '' SqlDataSource2 '' runat= '' server '' ConnectionString= '' < % $ ConnectionStrings : MyConnectionString % > '' ProviderName= '' < % $ ConnectionStrings : MyConnectionString.ProviderName % > '' OnDeleted= '' OnRuleDeleted '' SelectCommand= '' SELECT RuleId , RecordingFilterId , RuleName , RecordingAction , RecordingCondition , ExtensionValue , Priority , CallType FROM rules WHERE ( [ RecordingFilterId ] = @ RecordingFilterId ) and RuleName & lt ; & gt ; `` ORDER BY [ Priority ] asc '' UpdateCommand= '' UPDATE [ Rules ] SET [ Priority ] = @ Priority WHERE RuleId = @ original_RuleID '' DeleteCommand= '' exec DeleteRule @ original_RuleID '' OldValuesParameterFormatString= '' original_ { 0 } '' > < DeleteParameters > < asp : Parameter Name= '' original_RuleID '' / > < /DeleteParameters > < SelectParameters > < asp : ControlParameter ControlID= '' lblCategoryName '' Name= '' RecordingFilterId '' PropertyName= '' Text '' Type= '' String '' / > < /SelectParameters > < UpdateParameters > < asp : Parameter Name= '' Priority '' Type= '' Int32 '' / > < asp : Parameter Name= '' original_RuleID '' Type= '' String '' / > < /UpdateParameters > < /asp : SqlDataSource > < /div > < /div > < /td > < /tr > < /table > < /ItemTemplate > < ReorderTemplate > < asp : Panel ID= '' Panel2 '' runat= '' server '' CssClass= '' reorderCue '' > < /asp : Panel > < /ReorderTemplate > < DragHandleTemplate > < div class= '' dragHandle '' id= '' dragHandle < % # Eval ( `` RecordingFilterId '' ) % > '' > < /div > < /DragHandleTemplate > < /cc1 : ReorderList > < /div > < asp : SqlDataSource ID= '' SqlDataSource1 '' runat= '' server '' ConnectionString= '' < % $ ConnectionStrings : MyConnectionString % > '' ProviderName= '' < % $ ConnectionStrings : MyConnectionString.ProviderName % > '' SelectCommand= '' SELECT RecordingFilterId , Name , Description , SystemFilter , Priority FROM recordingfilters WHERE SystemFilter= ' 1 ' AND STATUS =1 order BY Priority '' UpdateCommand= '' UPDATE [ recordingfilters ] SET [ Priority ] = @ Priority WHERE RecordingFilterId = @ original_RecordingFilterId '' OnDeleted= '' OnFilterDeleted '' DeleteCommand= '' exec DeleteRecordingFilter @ original_RecordingFilterId '' OldValuesParameterFormatString= '' original_ { 0 } '' > < DeleteParameters > < asp : Parameter Name= '' original_RecordingFilterId '' / > < /DeleteParameters > < UpdateParameters > < asp : Parameter Name= '' Priority '' Type= '' Int32 '' / > < asp : Parameter Name= '' original_RecordingFilterId '' Type= '' String '' / > < /UpdateParameters > < /asp : SqlDataSource >",How to change ConnectionString property of SqlDataSource by Code Behind which is in Child ReorderList ? "C_sharp : If I have a generic interface with a struct constraint like this : I can supply an enumeration as my type T like so , because an enum satisfies a struct constraint : C # 7.3 added an Enum constraint . The following code , which was previously illegal , now compiles : However , to my surprise , the following fails to compile : ... with the error CS0453 The type 'T ' must be a non-nullable value type in order to use it as parameter 'T ' in the generic type or method 'IStruct'Why is this ? I would expect a generic type constrained by Enum to be usable as a type argument where the type is constrained by struct but this does n't seem to be the case - I am having to change my Enum constraint to struct , Enum . Is my expectation wrong ? public interface IStruct < T > where T : struct { } public class EnumIsAStruct : IStruct < DateTimeKind > { } public class MCVE < T > : IStruct < T > where T : struct , Enum { } public class MCVE < T > : IStruct < T > where T : Enum { }",Why is a generic type constrained by 'Enum ' failing to qualify as a 'struct ' in C # 7.3 ? "C_sharp : I am working on a WPF application where I have a Window level double-click event that maximizes the app window when a user double-clicks anywhere within the window . However , I also have a custom control within the app window , and a separate double-click event within the custom control . When a user double-clicks in the custom control , only the control 's double-click event should fire , and the window should not resize . My code looks something like this : And my XAML looks something like this : Unfortunately , with this code in place , when the user double-clicks in the control , the control event fires , but the Window event fires as well . I have tried setting e.Handled=true in the control event , but the Window event fires anyway . The only thing that has stopped the Window level double-click event from firing is handling the custom control 's preview double-click event using this : Though the preview event stops the Window double-click before it can fire , I ca n't use it without having to refactor a good bit of code . My custom control has a few child controls that also handle its double-click event . If the preview event gets called at the parent control level , the double-click event never tunnels down through the child controls , and thus double-clicking does n't do what I want it to do . If possible , I would like to avoid having to refactor any of the code in the child controls . That being said , my question is this : Is there any way to stop the Window-level double-click event from firing once the control 's double-click event has been handled ? I 've been driving myself crazy trying to figure this out.. any help is appreciated ! public class Window { private void window_DoubleClick ( object sender , EventArgs e ) { /// Maximize/minimize window } private void myCustomControl_DoubleClick ( object sender , EventArgs e ) { /// Do other things , but PLEASE do n't resize ! e.Handled = true ; } } < Window x : class= '' MyProject.MyWindow '' MouseDoubleClick= '' window_DoubleClick '' > < Grid Grid.Row= '' 0 '' Margin= '' 0 '' > < local : myCustomControl MouseDoubleClick= '' myCustomControl_DoubleClick '' / > < /Grid > < /Window > private void myCustomControl_PreviewMouseDoubleClick ( object sender , MouseButtonEventArgs e ) { e.Handled = true ; }","Double-click event fires at window level and control level , even when it is handled within the control" "C_sharp : I have a JSON feed that looks like this ( I removed some fields that are n't necessary for this example ) : There are two types of transactions in this feed : internal transactions that have a recipient , and external transactions that have a hsh and recipient_address.I created the following classes to accomodate this structure : So we have a base class for all paged results ( PagedResult ) with a specific implementation for transactions ( TransactionPagedResult ) . This result has a collection containing 0..* transactions ( abstract class Transaction ) . They 're not of the type Transaction though , but of type InternalTransaction or ExternalTransaction which are implementations of Transaction.My question is how I can let JSON.NET handle this . I want JSON.NET to see whether the current transaction it 's parsing is an InternalTransaction or an ExternalTransaction , and add the according type to the IEnumerable < Transaction > collection in TransactionPagedResult.I created my own JsonConverter that I added as a property to the IEnumerable < Transaction > with the [ JsonConverter ( typeof ( TransactionCreationConverter ) ) ] attribute , but this did n't work , I get the following error : Additional information : Error reading JObject from JsonReader . Current JsonReader item is not an object : StartArray . Path 'transactions ' , line 1 , position 218.I understand this is because JSON.NET tries to deserialize the whole collection , but I want it to deserialize each object inside the collection one by one.Anyone ? { `` total_count '' : 2 , `` num_pages '' : 1 , `` current_page '' : 1 , `` balance '' : { `` amount '' : `` 0.00001199 '' , `` currency '' : `` BTC '' } , `` transactions '' : [ { `` transaction '' : { `` id '' : `` 5018f833f8182b129c00002f '' , `` created_at '' : `` 2012-08-01T02:34:43-07:00 '' , `` sender '' : { `` id '' : `` 5011f33df8182b142400000e '' , `` name '' : `` User Two '' , `` email '' : `` user2 @ example.com '' } , `` recipient '' : { `` id '' : `` 5011f33df8182b142400000a '' , `` name '' : `` User One '' , `` email '' : `` user1 @ example.com '' } } } , { `` transaction '' : { `` id '' : `` 5018f833f8182b129c00002e '' , `` created_at '' : `` 2012-08-01T02:36:43-07:00 '' , `` hsh '' : `` 9d6a7d1112c3db9de5315b421a5153d71413f5f752aff75bf504b77df4e646a3 '' , `` sender '' : { `` id '' : `` 5011f33df8182b142400000e '' , `` name '' : `` User Two '' , `` email '' : `` user2 @ example.com '' } , `` recipient_address '' : `` 37muSN5ZrukVTvyVh3mT5Zc5ew9L9CBare '' } } ] }",How to deserialize collection with different types ? "C_sharp : I have a class that defines a CallRate type . I need to add the ability to create multiple instances of my class by reading the data from a file.I added a static method to my class CallRate that returns a List < CallRate > . Is it ok for a class to generate new instances of itself by calling one of its own constructors ? It works , I just wonder if it 's the proper thing to do . List < CallRates > cr = CallRates.ProcessCallsFile ( file ) ;",Should a c # class generate instances of itself ? "C_sharp : Using Postsharp , how do you set the return value after an exception has been thrown ? I thought this would work : namespace MvcApplication3.Controllers { public class ValuesController : ApiController { // GET api/values/5 [ MyExceptionHandler ] public string Get ( int id ) { string value = GetValue ( id ) ; return value ; } private string GetValue ( int id ) { throw new DivideByZeroException ( ) ; } } [ Serializable ] public class MyExceptionHandler : OnExceptionAspect { public override void OnException ( MethodExecutionArgs args ) { args.FlowBehavior = FlowBehavior.Continue ; args.ReturnValue = `` Error Getting Value '' ; } } }",Postsharp : How to set the return value after an exception "C_sharp : I 'm frequently frustrated by the amount of logging I have to include in my code and it leads me to wonder if there 's a better way of doing things.I do n't know if this has been done or if someone has come up with a better idea but I was wondering is there a way anyone knows of to `` inject '' a logger into an application such that it passively monitors the thread and quietly logs processes as they occur without having to do things like : What would be great is if I could say to my logger : It would then monitor everything that goes on inside of that method including passed in arguments along with method calls and values passed into those methods , exceptions that occur etc.Has anyone implemented something like this in the past ? Could it even be implemented ? Is logging in this fashion just a pipe dream ? I 'd love to design something that would do this , but I just do n't even know where I 'd begin . Of course , I do n't want to reinvent the wheel either , if it 's already been done , it would be great if someone could point me in the right direction.Any suggestions would be gratefully received ... Edit : I thought I 'd comment on an answer which queried as to the level of detail required in the log . It is frequently required that configurable levels of logging be provided such that if the configuration specifies detailed logging then everything is logged , whereas if critical logging is configured then only certain information is logged along with exceptions . If fatal logging is configured then only information which causes the application to die would be logged . Would something like this be configurable or would AOP require 3 or 4 different builds depending on the number of logging levels ? I frequently use 4 levels : Fatal , Critical , Information , Detailed public void MyProcess ( int a , string b , object c ) { log ( String.Format ( `` Entering process MyProcess with arguments : [ a ] = [ { 0 } ] ; [ b ] = [ { 1 } ] ; [ c ] = [ { 2 } ] '' , a.ToString ( ) , b , c.ToString ( ) ) ; try { int d = DoStuff ( a ) log ( String.Format ( `` DoStuff ( { 0 } ) returned value { 1 } '' , a.ToString ( ) , d.ToString ( ) ) ) ; } catch ( Exception ex ) { log ( String.Format ( `` An exception occurred during process DoStuff ( { 0 } ) \nException : \n { 1 } '' , a.ToString ( ) , ex.ToString ( ) ) ) } } Monitor ( MyClass.MyMethod )",Is passive logging possible in .NET ? "C_sharp : I 'm using HttpClient trying to execute a POST method in Web API controller . The controller method is synchronous . I 'm doing so this way : After that I 'm calling Wait : When running this code , I see the http finish executing , yet the result value is always false . What can I be missing ? Edit : I now tried an async approach yet it did n't help me as wellTest project : What am I doing wrong ? When debugging I see that the controller method returns a good response , yet it never reaches back to my test var response = owin.HttpClient.PostAsJsonAsync ( uri , body ) ; var result = response.Wait ( 15000 ) ; public IHttpActionResult Add ( Item item ) { var result = _db.AddItem ( item ) ; return Ok ( result ) ; } TestServer _owinTestServer ; public async Task < HttpResponse message > Method1 ( string url , object body ) { return await _owinTestServer.HttpClient.PostAsJsonAsync ( url , body ) ; } public async Task < ItemPreview > Method2 ( object body ) ; { return await Method1 ( `` .. '' , body ) .Result.Content.ReadAsAsync < ItemPreview > ( ) ; } [ TestMethod ] public void test1 ( ) { Item item = new ( ... ) ; Method2 ( item ) .Continue with ( task = > { // Never reach here } }",Task.Wait always returns false although task finished "C_sharp : Is there a way to make the .NET Forms PropertyGrid respect the DisplayNameAttribute when it sorts properties of multiple selected objects . When a single object is select the PropertyGrid sorts based on the DisplayNameAttribute but when multiple objects are selected , it uses the actual property name to sort . The following code demonstrates the issue : The previous code makes a Form with two PropertyGrids . The left grid contains a single object in its selection , while the right grid contains two objects in its selection . All objects are of the same type . The left grid sorts the properties based on the DisplayNameAttribute while the right sorts based on the actual property name . In both cases the DisplayNameAttribute is presented as the properties name in the grid : Can I force the PropertyGrid to always use the DisplayNameAttribute when sorting ? static class Program { [ STAThread ] static void Main ( ) { Form myForm1 = new Form ( ) ; myForm1.Width = 820 ; myForm1.Height = 340 ; PropertyGrid grid1 = new PropertyGrid ( ) ; grid1.Left = 0 ; grid1.Top = 0 ; grid1.Width = 400 ; grid1.Height = 300 ; myForm1.Controls.Add ( grid1 ) ; grid1.SelectedObject = new MyObject ( ) ; PropertyGrid grid2 = new PropertyGrid ( ) ; grid2.Left = 400 ; grid2.Top = 0 ; grid2.Width = 400 ; grid2.Height = 300 ; myForm1.Controls.Add ( grid2 ) ; object [ ] objects = new object [ ] { new MyObject ( ) , new MyObject ( ) } ; grid2.SelectedObjects = objects ; Application.Run ( myForm1 ) ; } } public class MyObject { [ DisplayName ( `` ZZZZ '' ) ] public int AProperty { get ; set ; } [ DisplayName ( `` BBBB '' ) ] public int BProperty { get ; set ; } }",.Net Forms PropertyGrid ignores DisplayNameAttribute when sorting properties on multiple selected objects "C_sharp : Since a struct in C # consists of the bits of its members , you can not have a value type T which includes any T fields : My understanding is that an instance of the above type could never be instantiated*—any attempt to do so would result in an infinite loop of instantiation/allocation ( which I guess would cause a stack overflow ? ** ) —or , alternately , another way of looking at it might be that the definition itself just does n't make sense ; perhaps it 's a self-defeating entity , sort of like `` This statement is false . `` Curiously , though , if you run this code : ... you will get the following output : It seems we are being `` lied '' to here*** . Obviously I understand that the primitive types like int , double , etc . must be defined in some special way deep down in the bowels of C # ( you can not define every possible unit within a system in terms of that system ... can you ? —different topic , regardless ! ) ; I 'm just interested to know what 's going on here.How does the System.Int32 type ( for example ) actually account for the storage of a 32-bit integer ? More generally , how can a value type ( as a definition of a kind of value ) include a field whose type is itself ? It just seems like turtles all the way down.Black magic ? *On a separate note : is this the right word for a value type ( `` instantiated '' ) ? I feel like it carries `` reference-like '' connotations ; but maybe that 's just me . Also , I feel like I may have asked this question before—if so , I forget what people answered . **Both Martin v. Löwis and Eric Lippert have pointed out that this is neither entirely accurate nor an appropriate perspective on the issue . See their answers for more info . ***OK , I realize nobody 's actually lying . I did n't mean to imply that I thought this was false ; my suspicion had been that it was somehow an oversimplification . After coming to understand ( I think ) thecoop 's answer , it makes a lot more sense to me . // Struct member 'T.m_field ' of type 'T ' causes a cycle in the struct layoutstruct T { T m_field ; } BindingFlags privateInstance = BindingFlags.NonPublic | BindingFlags.Instance ; // Give me all the private instance fields of the int type.FieldInfo [ ] int32Fields = typeof ( int ) .GetFields ( privateInstance ) ; foreach ( FieldInfo field in int32Fields ) { Console.WriteLine ( `` { 0 } ( { 1 } ) '' , field.Name , field.FieldType ) ; } m_value ( System.Int32 )",How are the `` primitive '' types defined non-recursively ? "C_sharp : Let 's say i have such structureSo the Form class contains the list of fields , let 's say that the Field itself is represented with such structureThe Field is basically composite structure , each Field contains the list of child fields . So the structure is hierarchical . Also Field has reference to the FieldType class.And at the end we have reference to the DataTypeWhat I want to achieve is to get the difference of such complex structure , let 's say if I have some sort of Comparer it will give me structured difference for the whole form as one class , let 's say DifferenceResult . When I said structured difference I mean that it should be something like that.Difference for the Form fields ( output Form has difference in Version field ( different color ) Differences for the Fields collection , including the hierarchy of the fields to the edited fieldSame behavior for the FieldType and DataTypeDetect removing and adding the Field into the Form ( so probably each Difference will have a Type ) What I have right now . I started with generic approach and tried to use ReflectionComparer implementing IEqualityComparer interfaceAnd Difference classBut probably it 's not the way I want to go , because I should compare Field more precisely taking in consideration that each Field has Id , which can be different for different forms as well and I want to take more control of the comparing process . For me it sounds more like a diff tool.So I am looking for good pattern and pretty good structure to publish the Difference to the client code , which can easily visualize it ? public class Form { # region Public Properties public List < Field > Fields { get ; set ; } public string Id { get ; set ; } public string Name { get ; set ; } public string Version { get ; set ; } public int Revision { get ; set ; } # endregion } public class Field { # region Public Properties public string DisplayName { get ; set ; } public List < Field > Fields { get ; set ; } public string Id { get ; set ; } public FieldKind Type { get ; set ; } public FieldType FieldType { get ; set ; } # endregion } public class FieldType { # region Public Properties public DataType DataType { get ; set ; } public string DisplayName { get ; set ; } public string Id { get ; set ; } # endregion } public class DataType { # region Public Properties public string BaseType { get ; set ; } public string Id { get ; set ; } public string Name { get ; set ; } public List < Restriction > Restrictions { get ; set ; } # endregion } public bool Equals ( T x , T y ) { var type = typeof ( T ) ; if ( typeof ( IEquatable < T > ) .IsAssignableFrom ( type ) ) { return EqualityComparer < T > .Default.Equals ( x , y ) ; } var enumerableType = type.GetInterface ( typeof ( IEnumerable < > ) .FullName ) ; if ( enumerableType ! = null ) { var elementType = enumerableType.GetGenericArguments ( ) [ 0 ] ; var elementComparerType = typeof ( DifferenceComparer < > ) .MakeGenericType ( elementType ) ; var elementComparer = Activator.CreateInstance ( elementComparerType , new object [ ] { _foundDifferenceCallback , _existedDifference } ) ; return ( bool ) typeof ( Enumerable ) .GetGenericMethod ( `` SequenceEqual '' , new [ ] { typeof ( IEnumerable < > ) , typeof ( IEnumerable < > ) , typeof ( IEqualityComparer < > ) } ) .MakeGenericMethod ( elementType ) .Invoke ( null , new [ ] { x , y , elementComparer } ) ; } foreach ( var propertyInfo in type.GetProperties ( ) ) { var leftValue = propertyInfo.GetValue ( x ) ; var rightValue = propertyInfo.GetValue ( y ) ; if ( leftValue ! = null ) { var propertyComparerType = typeof ( DifferenceComparer < > ) .MakeGenericType ( propertyInfo.PropertyType ) ; var propertyComparer = Activator.CreateInstance ( propertyComparerType , new object [ ] { _foundDifferenceCallback , _existedDifference } ) ; if ( ! ( ( bool ) typeof ( IEqualityComparer < > ) .MakeGenericType ( propertyInfo.PropertyType ) .GetMethod ( `` Equals '' ) .Invoke ( propertyComparer , new object [ ] { leftValue , rightValue } ) ) ) { // Create and publish the difference with its Type } } else { if ( ! Equals ( leftValue , rightValue ) ) { // Create and publish the difference with its Type } } } //return true if no differences are found } public struct Difference { public readonly string Property ; public readonly DifferenceType Type ; public readonly IExtractionable Expected ; public readonly IExtractionable Actual ; }",Pattern to get objects structured difference and statistics or how to create diff tool "C_sharp : I 've been trying to get my head around the Reactive Extensions for .NET of late , but have hit a bit of a conceptual wall : I ca n't work out why IObservable.First ( ) blocks.I have some sample code that looks a bit like this : What I was expecting to happen was for itemA to be referentially equal to a and to be able to access its members , etc . What happens instead is that First ( ) blocks and the Assert.AreEqual ( ) is never reached . Now , I know enough to know that when using Rx , code should Subscribe ( ) to IObservables , so it 's likely that I 've just done the wrong thing here . However , it 's not possible , based on the various method signatures to do either of : orWhat am I missing ? var a = new ListItem ( a ) ; var b = new ListItem ( b ) ; var c = new ListItem ( c ) ; var d = new ListItem ( d ) ; var observableList = new List < ListItem > { a , b , c , d } .ToObservable ( ) ; var itemA = observableList.First ( ) ; // Never reachedAssert.AreEqual ( expectedFoo , itemA.Foo ) ; observableList.First ( ) .Subscribe ( item = > Assert.AreEqual ( expectedFoo , item ) ) ; observableList.Subscribe ( SomeMethod ) .First ( ) // This does n't even make sense , right ?",Why does IObservable < T > .First ( ) block ? "C_sharp : When using MVVM we are disposing view ( while viewmodel persists ) .My question is how to restore ListView state when creating new view as close as possible to one when view was disposed ? ScrollIntoView works only partially . I can only scroll to a single item and it can be on top or bottom , there is no control of where item will appears in the view.I have multi-selection ( and horizontal scroll-bar , but this is rather unimportant ) and someone may select several items and perhaps scroll further ( without changing selection ) . Ideally binding ScrollViewer of ListView properties to viewmodel would do , but I am afraid to fall under XY problem asking for that directly ( not sure if this is even applicable ) . Moreover this seems to me to be a very common thing for wpf , but perhaps I fail to formulate google query properly as I ca n't find related ListView+ScrollViewer+MVVM combo.Is this possible ? I have problems with ScrollIntoView and data-templates ( MVVM ) with rather ugly workarounds . Restoring ListView state with ScrollIntoView sounds wrong . There should be another way . Today google leads me to my own unanswered question.I am looking for a solution to restore ListView state . Consider following as mcve : xaml : This is a window with ContentControl which content is bound to DataContext ( toggled by button to be either null or ViewModel instance ) .I 've added IsSelected support ( try to select some items , hiding/showing ListView will restore that ) .The aim is : show ListView , scroll ( it 's 100x100 size , so that content is bigger ) vertically and/or horizontally , click button to hide , click button to show and at this time ListView should restore its state ( namely position of ScrollViewer ) . public class ViewModel { public class Item { public string Text { get ; set ; } public bool IsSelected { get ; set ; } public static implicit operator Item ( string text ) = > new Item ( ) { Text = text } ; } public ObservableCollection < Item > Items { get ; } = new ObservableCollection < Item > { `` Item 1 '' , `` Item 2 '' , `` Item 3 long enough to use horizontal scroll '' , `` Item 4 '' , `` Item 5 '' , new Item { Text = `` Item 6 '' , IsSelected = true } , // select something `` Item 7 '' , `` Item 8 '' , `` Item 9 '' , } ; } public partial class MainWindow : Window { ViewModel _vm = new ViewModel ( ) ; public MainWindow ( ) { InitializeComponent ( ) ; } void Button_Click ( object sender , RoutedEventArgs e ) = > DataContext = DataContext == null ? _vm : null ; } < StackPanel > < ContentControl Content= '' { Binding } '' > < ContentControl.Resources > < DataTemplate DataType= '' { x : Type local : ViewModel } '' > < ListView Width= '' 100 '' Height= '' 100 '' ItemsSource= '' { Binding Items } '' > < ListView.ItemTemplate > < DataTemplate > < TextBlock Text= '' { Binding Text } '' / > < /DataTemplate > < /ListView.ItemTemplate > < ListView.ItemContainerStyle > < Style TargetType= '' ListViewItem '' > < Setter Property= '' IsSelected '' Value= '' { Binding IsSelected } '' / > < /Style > < /ListView.ItemContainerStyle > < /ListView > < /DataTemplate > < /ContentControl.Resources > < /ContentControl > < Button Content= '' Click '' Click= '' Button_Click '' / > < /StackPanel >",Restore ListView state MVVM "C_sharp : I am trying to make a function that can receive unlimited amount of arguments without crating GC.I know that this can be done with the params keyword but it creates GC . Also understand that you can pass array to to the function but I want to know if it is possible to pass unlimited method arguments without creating GC and without creating array or list and passing it to the List.This is the example with the param code : When executed even with the StartCoroutine function commented out , it allocates 80 bytes . At first , I thought this was happening because I used the foreach loop then I changed that to a for loop but it still creating GC then I realized that params GameObject [ ] is causing it . See the Profiler below fore more visual information on this : So , how can I create a method that takes unlimited arguments without generating GC ? Please ignore the use of GameObject.Find function used in the Update function . That 's just used for an example to get the reference of Objects I want during run-time . I have a script implemented to handle that but not related what 's in this question . void Update ( ) { GameObject player1 = GameObject.Find ( `` Player1 '' ) ; GameObject player2 = GameObject.Find ( `` Player2 '' ) ; GameObject enemy1 = GameObject.Find ( `` Enemy1 '' ) ; GameObject enemy2 = GameObject.Find ( `` Enemy2 '' ) ; GameObject enemy3 = GameObject.Find ( `` Enemy3 '' ) ; Vector3 newPos = new Vector3 ( 0 , 0 , 0 ) ; moveObjects ( newPos , 3f , player1 , player2 , enemy1 , enemy2 , enemy3 ) ; } void moveObjects ( Vector3 newPos , float duration , params GameObject [ ] objs ) { for ( int i = 0 ; i < objs.Length ; i++ ) { //StartCoroutine ( moveToNewPos ( objs [ i ] .transform , newPos , duration ) ) ; } }",Unlimited method arguments without GC "C_sharp : In a LINQ query , the order of operators is from-where-select : If we put the select clause first like in traditional select-from-where SQL , it fails to compile : What is the reason behind this restriction ? int [ ] numbers = new int [ 7 ] { 0 , 1 , 2 , 3 , 4 , 5 , 6 } ; var numQuery = from num in numbers where ( num % 2 ) == 0 select num ; var numQuery = select num // error : ; expected from num in numbers where ( num % 2 ) == 0 ;",Why ca n't select come first in a LINQ query ? "C_sharp : Most recently I have been working on an application that is leveraged by a TCP client-server model ( reverse connection ) . In order to improve the performance of long-running operations , I have made it so that a single instance of the client application can make a number of outgoing socket connections to the server . When the server application accepts an incoming connection , the child socket representing that connection is encapsulated in a new instance of a class called a ServerChildSocket . I need some way to effectively group all of the ServerChildSocket instances that propagated from the same client application instance but I am struggling to develop a working approach let alone a good approach.My objective is to group ServerChildSocket instances accordingly in a class similar to this ... How can I identify which connections originated from the same client application instance and then assign the connection to an instance of the UserState class accordingly ? I believe that the client application would need to send some preliminary information about the connections ' intent ( main connection ? download connection ? etc . ) as soon as the connection has been established . I am struggling to think of a way to bring this all together , though . class UserState { ServerChildSocket MainConnection { get ; set ; } ServerChildSocket FileDownloadConnection { get ; set ; } ServerChildSocket VoiceChatConnection { get ; set ; } }",How can I group socket connections by the client application instance they propagated from ? "C_sharp : The UIElement class defines static RoutedEvent members MouseLeftButtonDownEvent and MouseLeftButtonUpEvent -- but there is no MouseMoveEvent . As far as I can tell , neither does any class in the framework hierarchy . There is the regular event definition : So you can write : but you ca n't use the other form , which allows you to subscribe to even handled events : So my question is twofold : Why is there no MouseMoveEvent defined anywhere ? Is there a workaround that allows you to get a notification for MouseMove events even when they are handled ? EditI see that the MSDN docs acknowledge this as a limitation : A limitation of this technique is that the AddHandler API takes a parameter of type RoutedEvent that identifies the routed event in question . Not all Silverlight routed events provide a RoutedEvent identifier , and this consideration thus affects which routed events can still be handled in the Handled case.Edit # 2Per @ HansPassant , the general answer is that `` MouseMove '' events can not be marked as `` handled '' , thus they always bubble . This is true of the TextBox , except for an apparent edge case : when you click on the TextBox 's text area , thus activating the drag-to-select thingo , the `` MouseMove '' events no longer get triggered . I have no idea why that would be . Note -- for anyone curious -- I am trying to write a behavior that allows the user to drag/drop a TextBox . The TextBox control intercepts mouse events by default , in order to allow text selection . public event MouseEventHandler MouseMove ; void AttachHandler ( UIElement element ) { element.MouseMove += OnMouseMove ; } void AttachHandler ( UIElement element ) { element.AddHandler ( UIElement.MouseMoveEvent , new MouseEventHandler ( OnMouseMove ) , true ) ; }","Why is there no MouseMoveEvent -- or , how to use AddHandler for the mouse move event" "C_sharp : I 'd like to know if there 's a way I can write a function to `` pass through '' an IAsyncEnumerable ... that is , the function will call another IAsyncEnumerable function and yield all results without having to write a foreach to do it ? I find myself writing this code pattern a lot . Here 's an example : For whatever reason ( due to layered design ) my function MyFunction wants to call MyStringEnumerator but then just yield everything without intervention . I have to keep writing these foreach loops to do it . If it were an IEnumerable I would return the IEnumerable . If it were C++ I could write a macro to do it.What 's best practice ? async IAsyncEnumerable < string > MyStringEnumerator ( ) ; async IAsyncEnumerable < string > MyFunction ( ) { // ... do some code ... // Return all elements of the whole stream from the enumerator await foreach ( var s in MyStringEnumerator ( ) ) { yield return s ; } }",Pass-through for IAsyncEnumerable ? "C_sharp : I have the following code : When I check my database profile ( SqlServer 2012 ) I can see an horrible full table scan without any `` TOP '' clause.The interesting part : If I do something similar but specifying a concrete orderby : The profile shows a beautiful `` TOP '' clause.I would like to avoid having lot 's of methods , one for each `` orderby '' possibility . Any hint would be very appreciated . public List < anEntity > Get ( int page , int pagesize , Func < anEntity , IComparable > orderby ) { using ( var ctx = new MyContext ( ) ) { return ctx.anEntity.OrderBy ( orderby ) .Skip ( pagesize * page ) .Take ( pagesize ) .ToList ( ) ; } } return ctx.anEntity.OrderBy ( x = > x.aField ) .Skip ( pagesize * page ) .Take ( pagesize ) .ToList ( ) ;",Entity Framework 5 performing full table scan "C_sharp : For example , I have an observable of some collections which indicates statuses of objects ( I get it periodically through REST API ) .I want to create a DynamicCache object and update it each time the source gives me a new result . So I wrote : But now every time a user changes its status , .Transform ( ... ) method creates a new instance of UserViewModel , which is n't the desired behaviour.Can I somehow determine a rule of updating existing ViewModel 's properties ( in the derived collection ) when source item with the same Id is changing instead of creating a new one every time ? class User { int Id { get ; } string Name { get ; } string Status { get ; } } IObservable < User > source ; var models = new SourceCache < User , int > ( user = > user.Id ) ; models.Connect ( ) .Transform ( u = > new UserViewModel ( ) { ... } ) ... .Bind ( out viewModels ) .Subscribe ( ) ; source.Subscribe ( ul = > models.EditDiff ( ul , ( a , b ) = > a.Status == b.Status ) ) ;",Create derrived collection of ViewModels with DynamicData which updates existing item instead of creating a new one on source item change "C_sharp : I 'm using the HttpContext.Current.Cache to cache expensive data queries with a CacheItemUpdateCallback.The idea is that the user has to load the data once and then the updatecallback keeps the object updated every 30 minutes.This is how I insert / overwrite the cache : For test reasons I set the expiration date like this ( update every 20 seconds ) : This all works fine . That means , it 's updating the expensive object every 20 seconds - but only for about 25 minutes . Then the trigger 'updateCallBack ' is not called anymore ! I guess the problem is that the IIS disposes the cache so the callback 'CacheItemUpdateCallBack ' is not fired anymore ... But that is only a guess.That leads me to my question : Is there any setting I have to set in app.config or in the IIS ? Or what am I doing wrong ? EDIT : Furthermore , I do n't understand why the Insert overload with CacheItemUpdateCallback does not have a parameter CacheItemPriority.However , the overload with CacheItemRemovedCallback does have a priority parameter . Maybe , if I could set the CacheItemPriority to 'High ' it would already solve my issue.EDIT : I found the issue : There is an idle timeout property for each application pool which was set to 20 minutes . HttpContext.Current.Cache.Insert ( cacheID , cachedObject , null , expiryTimeStamp , Cache.NoSlidingExpiration , updateCallBack ) ; var expiryTimeStamp = DateTime.Now.Add ( new TimeSpan ( 0 , 0 , 20 ) ) ;",Caching Expiration not working as expected "C_sharp : Suppose I have such pseudo code using some pseudo ORM ( ok in my case it 's Linq2Db ) .When will Connection be closed in db ? Would it be closed at all in that case ? What connection would be closed - those in using statement or those in lambda expression ? .NET compiler is creating anonymous class for lambdas , so it will copy connection to that class . When would that connection be closed ? Somehow I managed to get Timeout expired . The timeout period elapsed prior to obtaining a connection from the pool . This may have occurred because all pooled connections were in use and max pool size was reached . I materialized queries and exception disappeared . But I 'm wondering how this thing works . static IEnumerable < A > GetA ( ) { using ( var db = ConnectionFactory.Current.GetDBConnection ( ) ) { return from a in db.A select a ; } } static B [ ] DoSmth ( ) { var aItems = GetA ( ) ; if ( ! aItems.Any ( ) ) return null ; return aItems.Select ( a = > new B ( a.prop1 ) ) .ToArray ( ) ; }",When will connection be closed in case of IEnumerable with using "C_sharp : I 'm using Autofac with .Net MVC 3 . It seems that Autofac disposes of the lifetime scope in Application_EndRequest , which makes sense . But that 's causing this error when I try to find a service in my own code that executes during EndRequest : For reference , here 's the code I 'm using to try to resolve services : Is there any way I can have code that is executed from EndRequest take advantage of Autofac for service resolution ? Edit : I thought of doing it with a separate scope just during EndRequest , as Jim suggests below . However , this means any services that are registered as InstancePerHttpRequest will get a new instance during EndRequest , which seems non-ideal . MESSAGE : Instances can not be resolved and nested lifetimes can not be created from this LifetimeScope as it has already been disposed.STACKTRACE : System.ObjectDisposedException at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent ( IComponentRegistration registration , IEnumerable ` 1 parameters ) at Autofac.ResolutionExtensions.ResolveOptionalService ( IComponentContext context , Service service , IEnumerable ` 1 parameters ) at System.Web.Mvc.DependencyResolverExtensions.GetService [ TService ] ( IDependencyResolver resolver ) public T GetInstance < T > ( ) { return DependencyResolver.Current.GetService < T > ( ) ; }",How can I use Autofac in EndRequest ? "C_sharp : In a class library , I have a file that is set to copy to output directory at NewFolder1/HTMLPage1.htm.I tried this : But the error is : ould not find a part of the path ' C : \Program Files ( x86 ) \Common Files\Microsoft Shared\DevServer\10.0\NewFolder1\HTMLPage1.htm'.How do I read this file ? var foo = File.ReadAllText ( `` NewFolder1/HTMLPage1.htm '' ) ;",Get File that was ` copied to output directory ` in a class library "C_sharp : On good old Win2k , the highest supported version of the .NET Framework is 2.0 . If one would like to run modern C # applications ( for example , which use LINQ ) , the Mono Framework may be the solution . Unfortunately it is not clear whether Windows 2000 is supported by Mono . The Download page says the latest version ( 3.0.1-beta ) `` works on all versions of Windows XP , 2003 , Vista and Windows 7 '' , but the Release Notes displayed by the installer claims that `` this build runs on Windows 2000 or later '' .As a quick test , I tried to compile and run the following code on a Win2k box , using different versions of Mono ( 2.0 , 2.10.9 , 3.0.1-beta ) : I opened the Mono Command Prompt , changed the working directory to that of Test.cs , and tried to compile it by mcs Test.cs . The old version 2.0 worked , I just had to use gmcsinstead of mcs . I could successfully run the executable on Mono2.0 . ( When I tried to run it on .Net 2.0 , I got an exception , as I expected . ) In case of version 2.10.9 and 3.0.1-beta , nothing happened : no exe was created and no error message was displayed . These versions work on Windows XP , I could compile the code and run the executable.Questions : Is Windows 2000 still supported by Mono ? What happened to Mono between version 2.0 and 3.0 , which could explain the the above mentioned compilation problem ? What could be done to make the latest version work on Win2k ? // Test.csusing System ; using System.Linq ; public static class Test { public static void Main ( ) { Console.WriteLine ( Environment.Version ) ; int [ ] numbers1 = { 5 , 4 , 1 , 3 , 9 , 8 , 6 , 7 , 2 , 0 } ; var numbers2 = from number in numbers1 where number < 5 select number ; Func < int , int > negate = number = > -1 * number ; foreach ( var number in numbers2 ) Console.WriteLine ( negate ( number ) ) ; } }",Mono on Windows 2000 SP4 "C_sharp : So code analysis is telling me that Enumarble.Where ( this ... ) is returning an instance of WhereListIterator < T > , which is ( looks to be ) an internal type within the .NET framework that implements IDisposable.Coverity does n't like IDisposable 's to go un-disposed , and is therefore suggesting I dispose of said instance . Obviously I ca n't dispose of the instance without doing some type checking , as Enumerable.Where ( this ... ) is said to return IEnumerable < T > , which does not ihnerit from IDisposable.My question is this : Does .NET expect me to dispose of the WhereListIterator < T > , or does the iterator dispose of itself ( say , after each enumeration ) . If I 'm not expected to dispose of it , then why is the interface implemented ? This leads me to a third , slightly unrelated question : If IDisposable was implemented explicitly , would Coverity ( code analysis ) still think that I should dispose of it ? Code Example : var myList = new List < int > { 1 , 2 , 3 , 4 } ; var evenNumbers = myList.Where ( x = > x % 2 == 0 ) ; foreach ( var number in evenNumbers ) { Console.WriteLine ( number ) ; } if ( evenNumbers is IDisposable ) { ( ( IDisposable ) evenNumbers ) .Dispose ( ) ; // This line will be executed }","Coverity , Enumerable.Where ( this ... ) , and IDisposable" "C_sharp : I 'm curious how the web.config is loaded into a application , is any reference to values in the web.config actually parsing the web.config file , or upon application start does it load the values into a singleton or something ? This came to my mind as I wanted to check for a value in the web.config on a per request basis in the global.asax.cs : protected void Application_BeginRequest ( object sender , EventArgs e ) { if ( ConfigurationManager.AppSettings [ `` abc '' ] ! = null ) { } }","Once the application starts up , how are values read from the web.config ?" "C_sharp : I was testing something out using LinqPad and was surprised that the following code did not produce an exception : This produces the following output : Fortunately , I was hoping for this behavior , but I was under the assumption that this would cause an OverflowException to be thrown.From System.OverflowException : An OverflowException is thrown at run time under the following conditions : An arithmetic operation produces a result that is outside the range of the data type returned by the operation . A casting or conversion operation attempts to perform a narrowing conversion , and the value of the source data type is outside the range of the target data type . Why does n't the operation lSmallValue - lBigValue fall into the first category ? ulong lSmallValue = 5 ; ulong lBigValue = 10 ; ulong lDifference = lSmallValue - lBigValue ; Console.WriteLine ( lDifference ) ; Console.WriteLine ( ( long ) lDifference ) ; 18446744073709551611-5",Why does n't this produce an overflow exception ? "C_sharp : I need to get the two letter ISO region name , ISO 3166 - ISO 3166-1 alpha 2 , for countries . My problem is that I only have the country names in Swedish , for example Sverige for Sweden and Tyskland for Germany . Is it possible to get RegionInfo from only this information ? I know it is possible for English country names.Works : https : //stackoverflow.com/a/14262292/3850405 var countryName = `` Sweden '' ; //var countryName = `` Denmark '' ; var regions = CultureInfo.GetCultures ( CultureTypes.SpecificCultures ) .Select ( x = > new RegionInfo ( x.LCID ) ) ; var englishRegion = regions.FirstOrDefault ( region = > region.EnglishName.Contains ( countryName ) ) ; var twoLetterISORegionName = englishRegion.TwoLetterISORegionName ;","C # get RegionInfo , TwoLetterISORegionName , by Swedish country name" "C_sharp : I have a bindinglist of activity , and each activity has a bindinglist of BuyOrdersIf I understand correctly , i can select the activity , but I can not access any method inside the activity . How do I access the method without creating a new instance of a bindinglist ? I tought this would work , but no bindingListActivty.Select ( k = > k._dataGridViewId == 1 ) ; bindingListActivty.Select ( k = > k._dataGridViewId == 1 ) .addBuyOrders ( new BuyOrders ( ) ) ;",Add object to a BindingList in a BindingList "C_sharp : I have ASP.NET WEB API project with Web.conig file . When it builds in VS2015 , no errors and no warnings are reported . However when I build this project on TeamCity using MSBuild build step , I get warning MSB3247 : Looks like app.config file is being considered by MSBuild instead of Web.config , because it proposes to add bindingRedirtect , which are already present in my Web.config file . I double-checked this by copy-pasting Web.config and renaming it to App.config . This removed the warning . When App.config is deleted - warning reappears . So my questions are 1 ) why although MSBuild seems to be using app.config does not fail when I have only Web.config in the project ; 2 ) How can I give a hint to MSBuild to use Web.config for binding redirect ? 3 ) why building exactly the same project in VS does not yield a warning ? [ ResolveAssemblyReferences ] ResolveAssemblyReference [ 14:30:01 ] : [ ResolveAssemblyReference ] No way to resolve conflict between `` protobuf-net , Version=2.0.0.602 , Culture=neutral , PublicKeyToken=257b51d87d2e4d67 '' and `` protobuf-net , Version=2.0.0.480 , Culture=neutral , PublicKeyToken=257b51d87d2e4d67 '' . Choosing `` protobuf-net , Version=2.0.0.602 , Culture=neutral , PublicKeyToken=257b51d87d2e4d67 '' arbitrarily . [ 14:30:01 ] : [ ResolveAssemblyReference ] No way to resolve conflict between `` Newtonsoft.Json , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=30ad4fe6b2a6aeed '' and `` Newtonsoft.Json , Version=4.5.0.0 , Culture=neutral , PublicKeyToken=30ad4fe6b2a6aeed '' . Choosing `` Newtonsoft.Json , Version=6.0.0.0 , Culture=neutral , PublicKeyToken=30ad4fe6b2a6aeed '' arbitrarily . [ 14:30:01 ] : [ ResolveAssemblyReference ] Consider app.config remapping of assembly `` protobuf-net , Culture=neutral , PublicKeyToken=257b51d87d2e4d67 '' from Version `` 2.0.0.602 '' [ ] to Version `` 2.0.0.668 '' [ D : \TeamCity\buildAgent\work\2772494ce0e0bbd7\branches\Stategic.Window.Release1\src\Strategic.Window\packages\protobuf-net.2.0.0.668\lib\net40\protobuf-net.dll ] to solve conflict and get rid of warning . [ 14:30:01 ] : [ ResolveAssemblyReference ] Consider app.config remapping of assembly `` Newtonsoft.Json , Culture=neutral , PublicKeyToken=30ad4fe6b2a6aeed '' from Version `` 6.0.0.0 '' [ ] to Version `` 7.0.0.0 '' [ D : \TeamCity\buildAgent\work\2772494ce0e0bbd7\branches\Stategic.Window.Release1\src\Strategic.Window\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll ] to solve conflict and get rid of warning . [ 14:30:01 ] : [ ResolveAssemblyReference ] Consider app.config remapping of assembly `` RazorEngine , Culture=neutral , PublicKeyToken=9ee697374c7e744a '' from Version `` 3.0.8.0 '' [ ] to Version `` 3.7.4.0 '' [ D : \TeamCity\buildAgent\work\2772494ce0e0bbd7\branches\Stategic.Window.Release1\src\Strategic.Window\packages\RazorEngine.3.7.4\lib\net45\RazorEngine.dll ] to solve conflict and get rid of warning . [ 14:30:01 ] : [ ResolveAssemblyReference ] Consider app.config remapping of assembly `` WebGrease , Culture=neutral , PublicKeyToken=31bf3856ad364e35 '' from Version `` 1.5.1.25624 '' [ ] to Version `` 1.5.2.14234 '' [ D : \TeamCity\buildAgent\work\2772494ce0e0bbd7\branches\Stategic.Window.Release1\src\Strategic.Window\packages\WebGrease.1.5.2\lib\WebGrease.dll ] to solve conflict and get rid of warning . [ 14:30:01 ] W : [ ResolveAssemblyReference ] C : \Program Files ( x86 ) \MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets ( 1819 , 5 ) : warning MSB3247 : Found conflicts between different versions of the same dependent assembly . In Visual Studio , double-click this warning ( or select it and press Enter ) to fix the conflicts ; otherwise , add the following binding redirects to the `` runtime '' node in the application configuration file : < assemblyBinding xmlns= '' urn : schemas-microsoft-com : asm.v1 '' > < dependentAssembly > < assemblyIdentity name= '' protobuf-net '' culture= '' neutral '' publicKeyToken= '' 257b51d87d2e4d67 '' / > < bindingRedirect oldVersion= '' 0.0.0.0-2.0.0.668 '' newVersion= '' 2.0.0.668 '' / > < /dependentAssembly > < /assemblyBinding > < assemblyBinding xmlns= '' urn : schemas-microsoft-com : asm.v1 '' > < dependentAssembly > < assemblyIdentity name= '' Newtonsoft.Json '' culture= '' neutral '' publicKeyToken= '' 30ad4fe6b2a6aeed '' / > < bindingRedirect oldVersion= '' 0.0.0.0-7.0.0.0 '' newVersion= '' 7.0.0.0 '' / > < /dependentAssembly > < /assemblyBinding > < assemblyBinding xmlns= '' urn : schemas-microsoft-com : asm.v1 '' > < dependentAssembly > < assemblyIdentity name= '' RazorEngine '' culture= '' neutral '' publicKeyToken= '' 9ee697374c7e744a '' / > < bindingRedirect oldVersion= '' 0.0.0.0-3.7.4.0 '' newVersion= '' 3.7.4.0 '' / > < /dependentAssembly > < /assemblyBinding > < assemblyBinding xmlns= '' urn : schemas-microsoft-com : asm.v1 '' > < dependentAssembly > < assemblyIdentity name= '' WebGrease '' culture= '' neutral '' publicKeyToken= '' 31bf3856ad364e35 '' / > < bindingRedirect oldVersion= '' 0.0.0.0-1.5.2.14234 '' newVersion= '' 1.5.2.14234 '' / > < /dependentAssembly > < /assemblyBinding >",MSBuild step in TeamCity considers app.config instead of web.config for ASP.NET WEB API project resulting in warning MSB3247 C_sharp : I 've seen this pattern a few times now : And I 've been wondering : Why is this better than using catch for rollbacks ? What are the differences between the two ways of making sure changes are rolled back on failure ? bool success = false ; try { DoSomething ( ) ; success = true ; } finally { if ( ! success ) Rollback ( ) ; } try { DoSomething ( ) ; } catch { Rollback ( ) ; throw ; },Using finally instead of catch "C_sharp : Using the following code as an example : If I run this program in a regular way ( without a break point or any other interruption ) , everything works without exception or error ( as you would expect it ) . Now if I put a break point on the if statement and move the cursor to the curly brace as described in the following picture ( using my mouse , not using F10 , so skipping the if ( true ) statement ) : I get an exception of type System.NullReferenceException when the debugger executes the statement string foo = null It seems to be linked to the fact that the variable foo is used in the lambda expression inside the if statement . I have tested and reproduced this on Visual Studio 2012 and 2013 ( pro and ultimate ) . Any idea on why this could be happening ? if ( true ) { string foo = null ; List < string > bar = new List < string > { `` test '' } ; bar.Any ( t = > t == foo ) ; }",Debugger stepping in if statement and lambda expression "C_sharp : I think I must be missing something , why ca n't I compile this : class Foo < T > where T : Bar { T Bar ; } abstract class Bar { } class MyBar : Bar { } static void Main ( string [ ] args ) { var fooMyBar = new Foo < MyBar > ( ) ; AddMoreFoos ( fooMyBar ) ; } static void AddMoreFoos < T > ( Foo < T > FooToAdd ) where T : Bar { var listOfFoos = new List < Foo < Bar > > ( ) ; listOfFoos.Add ( FooToAdd ) ; //Does n't compile listOfFoos.Add ( ( Foo < Bar > ) FooToAdd ) ; //does n't compile }",Why ca n't you cast a constrained open generic typed to the constrained type ? "C_sharp : If you have declared a struct : What is the result of creating a variable of type EmptyResult in an instance ? Would you expect an allocation on the stack , or is it effectively a no-op ? struct EmptyResult { } public Foo ( ) { EmptyResult result ; }",What does newing an empty struct do in C # ? "C_sharp : Say there is a method , Is there a way to transform M ( ) to M ( a : .. , b : .. , c : .. ) at the call-site ? I am using Visual Studio 2013 ( Ultimate ) 2017 Professional with ReSharper 8 ReSharper 2018.1 . A built-in solution ( or extension if such is required ) that utilized either would be suitable.This is similar to Is there any tools to help me refactor a method call from using position-based to name-based parameters , although I expect to start with no arguments ; and am asking the question 4 years later . void M ( int a , int b , int c /* and many more */ )","`` Automatically insert all named arguments '' at method call-site , in code" C_sharp : I am trying to run the following in LINQHowever get an error : The cast to value type 'Double ' failed because the materialized value is null . Either the result type 's generic parameter or the query must use a nullable type.I tried to add on ? ? 0 ; such that : As suggested in other posts however this yields an error : operator ' ? ? ' can not be applied to operands double or intAny suggestions ? EDIT : my model double totalDistance = ( from g in db.Logs join h in db.Races on g.raceId equals h.RaceId where g.userId == id select h.distance ) .Sum ( ) ; double totalDistance = ( from g in db.Logs join h in db.Races on g.raceId equals h.RaceId where g.userId == id select h.distance ) .Sum ( ) ? ? 0 ; namespace RacePace.Models { public class Race { public int RaceId { get ; set ; } [ DisplayName ( `` Race Setting '' ) ] public string place { get ; set ; } [ DisplayName ( `` Distance ( km ) '' ) ] public double distance { get ; set ; } [ DisplayName ( `` Date '' ) ] public DateTime date { get ; set ; } [ DisplayName ( `` Commencement Time '' ) ] public DateTime timeStarted { get ; set ; } [ DisplayName ( `` Active '' ) ] public Boolean active { get ; set ; } [ DisplayName ( `` Description '' ) ] public string description { get ; set ; } [ DisplayName ( `` Creator '' ) ] public int UserId { get ; set ; } } },Getting null error LINQ ; can not then use ? "C_sharp : I 'm using Reactive Extensions for easy event handling in my ViewModels ( Silverlight and/or Wp7 apps ) . For sake of simplicity let 's say I have a line like this in the ctor of my VM : this returns an IDisposable object , which if disposed will unsubscribe . ( Am I right in this assumption ? ) If I hold no reference to it , sooner or later it will be collected , and my handler will be unsubscribed.I usually have a List < IDisposable > in my VM , and I add subscriptions to it , yet I feel dirty about it , as if I 'm not doing something in a correct Rx way . What is the best practice , recommended pattern on situations like this ? Observable.FromEvent < PropertyChangedEventArgs > ( h = > MyObject.PropertyChanged += h , h = > MyObject.PropertyChanged -= h ) .Where ( e= > e.PropertyName == `` Title '' ) .Throttle ( TimeSpan.FromSeconds ( 0.5 ) ) .Subscribe ( e= > { /*do something*/ } ) ;",What to do with IObservers being disposed ? "C_sharp : I 'm working on adding some functionality and fixing some bugs in this code I found here : http : //www.c-sharpcorner.com/uploadfile/a644fc/multicolumn-combobox-with-configurable-display-and-value-members-and-fast-search-functionality/One issue is that the grid attached to the textbox stays in the same position on the screen when you move the window . I 'm trying to fix this by hiding the grid whenever the parent form is moved . In the MultiColumnComboBox class file , I 'm using this line of codeto add my function , parent_Move in the parent 's move event . The issue is that Parent is always null . Is there any way to add to the parent 's move event from the class file ? Or is there any other way to determine if the parent form 's screen location changed ? I 'm planning on using this control a lot and would prefer to find a way to fix the issue in the class rather than in each file where I would call it . Thank you guys for any help you can give me . this.Parent.Move += new System.EventHandler ( this.parent_Move ) ;",Move Event for Parent Form "C_sharp : I 'm trying to combine 2 lists from these : I get the error for a simple Union command : Here 's the error : What do I need to do to achieve this merge ? var quartEst = Quarterly_estimates.OrderByDescending ( q = > q.Yyyy ) .ThenByDescending ( q = > q.Quarter ) .Where ( q = > q.Ticker.Equals ( `` IBM '' ) & & q.Eps ! = null ) .Select ( q = > new { ticker = q.Ticker , Quarter = q.Quarter , Year = q.Yyyy , Eps = q.Eps } ) .AsEnumerable ( ) .Where ( q = > Convert.ToInt32 ( string.Format ( `` { 0 } { 1 } '' , q.Year , q.Quarter ) ) > Convert.ToInt32 ( finInfo ) ) ; var quartAct = Quarterlies.OrderByDescending ( q = > q.Yyyy ) .ThenByDescending ( q = > q.Quarter ) .Where ( q = > q.Ticker.Equals ( `` IBM '' ) & & Convert.ToInt16 ( q.Yyyy ) > = DateTime.Now.Year - 3 ) .Select ( q = > new { Tick = q.Ticker , Quarter = q.Quarter , Year = q.Yyyy , Eps = q.Eps_adj } ) .AsEnumerable ( ) .Where ( q = > Convert.ToInt32 ( string.Format ( `` { 0 } { 1 } '' , q.Year , q.Quarter ) ) < = Convert.ToInt32 ( finInfo ) ) ; var quartComb = quartEst.Union ( quartAct ) ; Instance argument : can not convert from 'System.Collections.Generic.List < AnonymousType # 1 > ' to 'System.Linq.IQueryable < AnonymousType # 2 > '",How to merge LINQ querys of lambdas which return of anonymous type ? "C_sharp : I 've been using ReSharper for the past months and , advertising aside , I ca n't see myself coding without it . Since I love living on the bleeding `` What the hell just went wrong '' edge , I decided to try my luck w/ the latest ReSharper 4.5 nightly builds . It 's all nice.However , I 've noticed that the using directives grouping format has changed , and I wanted to know which is closer to the general standards : [ OLD ] [ NEW ] Other than just lazy loading references , does it serve any special purpose ? ( Been reading Scott Hanselman 's take on this @ http : //www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx ) Thanks ; # region Using directivesusing System.X ; using System.Y ; using System.Z ; using System.A ; # regionnamespace X { ... } namespace X { # region Using directivesusing System.X ; using System.Y ; using System.Z ; using System.A ; # region ... }",Organizing using directives "C_sharp : I 'm a bit confused and ca n't explain this behaviour : thoughI 'm using Unity Version 5.3.5f1 . Vector3 k = new Vector3 ( Mathf.NegativeInfinity , Mathf.NegativeInfinity , Mathf.NegativeInfinity ) ; Debug.Log ( k==k ) ; // evaluates to False Debug.Log ( Mathf.Mathf.NegativeInfinity == Mathf.Mathf.NegativeInfinity ) // evaluates to True as expected",Why does this evaluate to False ? "C_sharp : object does n't implement Stage , therefore neither TIn nor TOut could ever be object , right ? So why does the compiler think that PipelineElement < object , object > and PipelineElement < TIn , TOut > can become identical ? EDIT : Yes , it is perfectly possible to implement the same generic interface multiple times : public interface PipelineElement < in TIn , out TOut > { IEnumerable < TOut > Run ( IEnumerable < TIn > input , Action < Error > errorReporter ) ; } public interface Stage { } public abstract class PipelineElementBase < TIn , TOut > : PipelineElement < object , object > , PipelineElement < TIn , TOut > where TIn : Stage where TOut : Stage { IEnumerable < object > PipelineElement < object , object > .Run ( IEnumerable < object > input , Action < Error > errorReporter ) { return this.Run ( input.Cast < TIn > ( ) , errorReporter ) .Cast < object > ( ) ; } public abstract IEnumerable < TOut > Run ( IEnumerable < TIn > input , Action < Error > errorReporter ) ; } public interface MyInterface < A > { } public class MyClass : MyInterface < string > , MyInterface < int > { }",Why does this result in CS0695 ? "C_sharp : I 'm trying to encode a KeyValuePair < string , string > to UTF-8 key='value ' using the Span < byte > overloads in .NET Core 2.1.Whoever wrote the GetBytes ( ReadOnlySpan < char > chars , Span < byte > bytes ) method was obviously a disciple of Yoda , because there is no TryGetBytes alternative , which is odd since Utf8Formatter provides TryWrite for all non-string primitive types.So I have two options for writing an extension method to do this.Option 1 : Option 2 : Which is better for performance , assuming that the `` not enough space '' case will be hit fairly frequently ( say , 1 time in 50 ) on a hot path ? public static bool TryGetBytes ( this Encoding encoding , ReadOnlySpan < char > str , Span < byte > bytes , out int written ) { try { written = Encoding.UTF8.GetBytes ( str , span ) ; return true ; } catch ( ArgumentException ) { written = 0 ; return false ; } public static bool TryGetBytes ( this Encoding encoding , ReadOnlySpan < char > str , Span < byte > bytes , out int written ) { if ( encoding.GetByteCount ( str ) > span.Length ) { written = 0 ; return false ; } written = Encoding.UTF8.GetBytes ( str , span ) ; return true ; }",Which is better for performance with Encoding.UTF8.GetBytes with Span - GetByteCount or try/catch "C_sharp : I was following a question where the OP had something like thisAnd then in the view was able to do something like this My expectation was that the result of the cast would be null and I stated as much . I was corrected that it should work and it was demonstrated via .net fiddle . To my surprise the dropdownlist was populated with the items.My question : How is it that when done in the view , List < SelectListItem > safely casts to SelectList [ HttpGet ] public ActionResult Index ( ) { var options = new List < SelectListItem > ( ) ; options.Add ( new SelectListItem { Text = `` Text1 '' , Value = `` 1 '' } ) ; options.Add ( new SelectListItem { Text = `` Text2 '' , Value = `` 2 '' } ) ; options.Add ( new SelectListItem { Text = `` Text3 '' , Value = `` 3 '' } ) ; ViewBag.Status = options ; return View ( ) ; } @ Html.DropDownList ( `` Status '' , ViewBag.Status as SelectList )",How does List < SelectListItem > safely cast to SelectList in view "C_sharp : I have a generic interface IRepository < T > and two implementations xrmRepository < T > and efRepository < T > I want to change the binding based on T , more specifically use xrmRepository when T derives from Entity . How can I accomplish that ? I currently have : But when I try to resolve IRepository < Contact > it goes to efRepository , even though Contact inherits Entity.I do n't want to use Named Bindings otherwise I will have to add the names everywhere . kernel.Bind ( typeof ( IRepository < > ) ) .To ( typeof ( efRepository < > ) ) .InRequestScope ( ) ; kernel.Bind ( typeof ( IRepository < > ) ) .To ( typeof ( xrmRepository < > ) ) .When ( request = > request.Service.GetGenericArguments ( ) [ 0 ] .GetType ( ) .IsSubclassOf ( typeof ( Entity ) ) ) .InRequestScope ( ) ;",Ninject Contextual Binding w/ Open Generics "C_sharp : I am trying to simply load a dll written in C # at run time and create an instance of a class in that dll.No errors are thrown , and if I step through the code I can walk though the FileReleaseHandler Class as it executes the constructor but the value of handler is always null.What am I missing here ? or even is there a better way I should be going about this ? Assembly a = Assembly.LoadFrom ( @ '' C : \Development\DaDll.dll '' ) ; Type type = a.GetType ( `` FileReleaseHandler '' , true ) ; TestInterface.INeeedHelp handler = Activator.CreateInstance ( type ) as TestInterface.INeeedHelp ;",Dynamically Loading a DLL "C_sharp : I want to type Korean text in my ediatble area inside a winform application.But Characters are repeating , I have tried to override the default WndProc , but nothing working.When I type in English , breakpoint hits WM_CHAR , But When I type in Korean it hits WM_IME_COMPOSITION on first character , and then after first character it hits WM_IME_COMPOSITION first and then hits WM_CHAR.I have observed that it types first character correct.e.g . ㅁ ( Korean Character ) On typing second character.ㅁㅂㅁ ( First char , second char , first char ) . I want the behaviour as it is in notepad switch ( m.WParam.ToInt32 ( ) ) { case Common.Interop.Window.WM_IME_CHAR : break ; case Common.Interop.Window.WM_IME_ENDCOMPOSITION : PassCharToScreen ( m ) ; break ; case Common.Interop.Window.WM_CHAR : PassCharToScreen ( m ) ; break ; case Common.Interop.Window.WM_IME_NOTIFY : break ; case Common.Interop.Window.WM_IME_COMPOSITION : PassCharToScreen ( m ) ; break ; case Common.Interop.Window.WM_IME_COMPOSITIONFULL : break ;",How to take Korean input in Winform ? "C_sharp : I 'm using the MVC 3 introduced WebGrid , but ca n't ca n't apply my own extension methods when passing a delegate for the format param.Using : I got I 've tried casting , not to avail If I use an standard method , it works : I 've also tried to put the extension in the same namespace , with no results.How can I use my beloved extensions ? Edit : The namespace per se it 's not the problem , the namespace where the extension is available for all the views and classes , and I can use it in the same view without problem . The problem is when using it in the delegate . Grid.Column ( `` MyProperty '' , `` MyProperty '' , format : @ < span class= '' something '' > @ item.MyProperty.MyExtensionMethodForString ( ) < /span > ) ERROR : 'string ' does not contain a definition for 'MyExtensionMethodForString ' Grid.Column ( `` MyProperty '' , `` MyProperty '' , format : @ < span class= '' something '' > @ ( ( string ) ( item.MyProperty ) .MyExtensionMethodForString ( ) ) < /span > ) Grid.Column ( `` MyProperty '' , `` MyProperty '' , format : @ < span class= '' something '' > @ ( Utils.MyExtensionMethodForString ( item.MyProperty ) ) < /span > )",Why ca n't I use my extension method in a delegate in the Razor WebGrid "C_sharp : It 's my understanding that the static readonly String wo n't get generated until the static constructor is called on the class . But , the static constructor wo n't be called until one of the static methods or variables is accessed.In a multi-threaded environment is it possible to run into issues because of this ? Basically , is the static constructor by default singleton locked or do I have to do this myself ? That is ... do I have to do the following : public class MyClass < T > { public static readonly String MyStringValue ; static MyClass ( ) { MyStringValue = GenerateString ( ) ; } private static String GenerateString ( ) { //Dynamically generated ONCE per type ( hence , not const ) } public void Foo ( ) { Console.WriteLine ( MyStringValue ) ; } } private static Object MyLock ; static MyClass ( ) { lock ( MyLock ) { if ( MyStringValue == null ) MyStringValue = GenerateString ( ) ; } }",C # - Static readonly strings -- possible to run into multithread issues ? "C_sharp : Regardless of whether we should , can we use IHostedService in an Azure Functions App ? Here is an attempt to register a hosted service ( background service , specifically ) as IHostedService : The Functions App then throws the following exception : internal sealed class Startup : FunctionsStartup { public override void Configure ( IFunctionsHostBuilder builder ) { builder.Services.AddHostedService < ExampleBackgroundService > ( ) ; } } Microsoft.Azure.WebJobs.Script.InvalidHostServicesException : 'The following service registrations did not match the expected services : [ Invalid ] ServiceType : Microsoft.Extensions.Hosting.IHostedService , Lifetime : Singleton , ImplementationType : ExampleBackgroundService '",IHostedService usable in Azure Functions App ? C_sharp : Is it possible to call an IronRuby method from C # with a delegate as parameter in such a way that yield would work ? The following gives me a wrong number of arguments ( 1 for 0 ) exception . Action < string > action = Console.WriteLine ; var runtime = Ruby.CreateRuntime ( ) ; var engine = runtime.GetEngine ( `` rb '' ) ; engine.Execute ( @ '' class YieldTest def test yield 'From IronRuby ' end end `` ) ; object test = engine.Runtime.Globals.GetVariable ( `` YieldTest '' ) ; dynamic t = engine.Operations.CreateInstance ( test ) ; t.test ( action ) ;,Calling IronRuby from C # with a delegate "C_sharp : My question concerns type-checking in a chain of generic methods . Let 's say I have an extension method that attempts to convert a byte array to an int , decimal , string , or DateTime.This calls a method called FromString that translates the concatenated string to a specific type . Unfortunately , the business logic is completely dependent on the type T. So I end up with a megalithic if-else block : At this point , I would prefer multiple methods with the same name and different return types , something along the lines of this : ... but I realize this is not valid , as T ca n't be constrained to a specific type , and without it , all of the methods will have the same conflicting signature . Is there a feasible way to implement FromString without the excessive type-checking ? Or might there be a better way to approach this problem altogether ? public static T Read < T > ( this ByteContainer ba , int size , string format ) where T : struct , IConvertible { var s = string.Concat ( ba.Bytes.Select ( b = > b.ToString ( format ) ) .ToArray ( ) ) ; var magic = FromString < T > ( s ) ; return ( T ) Convert.ChangeType ( magic , typeof ( T ) ) ; } private static T FromString < T > ( string s ) where T : struct { if ( typeof ( T ) .Equals ( typeof ( decimal ) ) ) { var x = ( decimal ) System.Convert.ToInt32 ( s ) / 100 ; return ( T ) Convert.ChangeType ( x , typeof ( T ) ) ; } if ( typeof ( T ) .Equals ( typeof ( int ) ) ) { var x = System.Convert.ToInt32 ( s ) ; return ( T ) Convert.ChangeType ( x , typeof ( T ) ) ; } if ( typeof ( T ) .Equals ( typeof ( DateTime ) ) ) ... etc ... } // < WishfulThinking > private static decimal FromString < T > ( string s ) { return ( decimal ) System.Convert.ToInt32 ( s ) / 100 ; } private static int FromString < T > ( string s ) { return System.Convert.ToInt32 ( s ) ; } // < /WishfulThinking >",Avoid excessive type-checking in generic methods ? "C_sharp : In the .NET reference source for the String class , there are various comments referencing something called the EE.The first is on m_stringLength : It 's found again again for .Empty : It 's also on Length : I would venture that it might have something to do with an Engine or is External , but I 'd like an actual reference defining what it is.What does the EE mean ? //NOTE NOTE NOTE NOTE//These fields map directly onto the fields in an EE StringObject . See object.h for the layout.// [ NonSerialized ] private int m_stringLength ; // The Empty constant holds the empty string value . It is initialized by the EE during startup.// It is treated as intrinsic by the JIT as so the static constructor would never run.// Leaving it uninitialized would confuse debuggers.////We need to call the String constructor so that the compiler does n't mark this as a literal.//Marking this as a literal would mean that it does n't show up as a field which we can access //from native.public static readonly String Empty ; // Gets the length of this string///// This is a EE implemented function so that the JIT can recognise is specially/// and eliminate checks on character fetchs in a loop like : /// for ( int I = 0 ; I < str.Length ; i++ ) str [ i ] /// The actually code generated for this will be one instruction and will be inlined .",What does the acronym EE mean in the .NET reference source ? "C_sharp : After getting back into Python , I 'm starting to notice and be annoyed more and more by my C # coding style requiring braces everywherepreferring the ( subjective ) much cleaner looking python counter-partis there any way I can go about hiding these braces ( as they do take up about 30 % of my coding screen on average and just look ugly ! ) if ( ... ) { return ... ; } else { return ... ; } if ... : return ... else return ...",Hide curly braces in C # "C_sharp : I was reading through the .NET sources when I found this : As you can see , the constructor of the Decimal structure copies the method argument to a local variable rather than using it directly . I was wondering what the comment means and how it relates to performance & optimization ? My guess is that once you want to modify the existing argument , method can be no longer inlined ? http : //referencesource.microsoft.com/ # mscorlib/system/decimal.cs # f9a4da9d6e110054 # references // Constructs a Decimal from an integer value.//public Decimal ( int value ) { // JIT today ca n't inline methods that contains `` starg '' opcode . // For more details , see DevDiv Bugs 81184 : x86 JIT CQ : // Removing the inline striction of `` starg '' . int value_copy = value ; if ( value_copy > = 0 ) { flags = 0 ; } else { flags = SignMask ; value_copy = -value_copy ; } lo = value_copy ; mid = 0 ; hi = 0 ; }",.NET local variable optimization "C_sharp : I noticed that using RestSharp : Execute < T > ( ) , when T as below It deserialized the JSON from Execute < Result > ( ) correctly into Result object , However when the class has IEnumerable property like belowExecute < Result > ( ) does not fill ( deserialize ) into the object Result.I am suspecting it is because of IEnumerable < T > being read only and Restsharp is unable to deserialize data because of that ? Is it the case ? public class Result { public List < DBData > Data { get ; set ; } public int Total { get ; set ; } public bool Success { get ; set ; } } public class Result { public IEnumerable < DBData > Data { get ; set ; } public int Total { get ; set ; } public bool Success { get ; set ; } }",RestSharp : Execute < T > ( ) with T having IEnumerable property "C_sharp : In class 's derived from a Component I sometimes see events declared like : Instead of just : I 'm tempted to to refactor to use the shorter method , but I am hesitant in case there are some advantages to using the Component EventHanderList that I am missing.The only advantages I can currently think of are : When the component is disposed , all items in the EventHandlerList are removed , effectively automatically unhooking event handlers.Possibly less memory fragmentation because of all the attached delegates going into the single EventHandlerList.Is there anything else ? ( This is not a question about the general use of explicit add + removes on events . ) private static readonly object LoadEvent = new object ( ) ; public event EventHandler < MyEventArgs > Load { add { Events.AddHandler ( LoadEvent , value ) ; } remove { Events.RemoveHandler ( LoadEvent , value ) ; } } protected virtual void OnLoad ( MyEventArg e ) { var evnt = ( EventHandler < MyEventArg > ) Events [ LoadEvent ] ; if ( evnt ! = null ) evnt ( this , e ) ; } public event EventHandler < MyEventArgs > Load ; protected virtual void OnLoad ( MyEvent e ) { if ( Load ! = null ) Load ( this , e ) ; }",What are the advantages of adding delegate instances to Component.Events ( EventHandlerList ) ? "C_sharp : I was wondering why I get such disparate results between apparently equal algorithms in C # and F # .F # code variants : Full F # code ( 4s ) : Full C # code ( 22s ) : The F # code takes more than 22s on any of its variants ( I assumed different implementations would yield different running times but that does n't seem to be the case ) . On the other hand , the C # code seems to be way faster . Both yield the same final sum result , so I guess the algorithms are equivalent . I double checked and the F # code seems to be compiled with the -- optimize+ flag.Am I doing something wrong ? open System { 1I.. ( bigint ( Int32.MaxValue / 100 ) ) } | > Seq.sumlet mutable sum = 0Ifor i in 1I.. ( bigint ( Int32.MaxValue / 100 ) ) do sum < - sum + isumlet sum = ref 0Ifor i in 1I.. ( bigint ( Int32.MaxValue / 100 ) ) do sum : = ! sum + isum [ < EntryPoint > ] let main argv = let sw = new Stopwatch ( ) sw.Start ( ) printfn `` % A '' ( { 1I.. ( bigint ( Int32.MaxValue / 100 ) ) } | > Seq.sum ) sw.Stop ( ) printfn `` took % A '' sw.Elapsed Console.ReadKey ( ) | > ignore 0 static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; BigInteger sum = new BigInteger ( 0 ) ; BigInteger max = new BigInteger ( Int32.MaxValue / 100 ) ; Console.WriteLine ( max ) ; for ( BigInteger i = new BigInteger ( 1 ) ; i < = max ; ++i ) { sum += i ; } sw.Stop ( ) ; Console.WriteLine ( sum ) ; Console.WriteLine ( sw.Elapsed ) ; Console.ReadKey ( ) ; }",Bad F # code performance on simple loop compared to C # - Why ? "C_sharp : I have a class in a C # program ( .Net 4.61 ) that uses Word and the Amyuni PDF suite to build a formatted PDF file . During the process , four temporary PDF files are created in the user 's temp folder : When the process completes , I have the following cleanup method that runs to delete any temp files generated during the process : This works file on nearly all of the deployed Windows systems ( all 64-bit Windows 7 systems ) , however on a few of them , when the EraseTempFiles method deletes the third of the temporary files , the application immediately exits . No exceptions are thrown ( I 've surrounded the File.Delete in a try-catch to determine this ) .The files can be deleted using Windows Explorer no problem.I 've tried saving all temp files in a different folder and changing how they are named with no change in behavior . Running ProcDump to track the application has not caught anything , it simply reports : I 've also subscribed to the unhandled exception event : That handler is also never called.I 've never seen a program exit like this with no explanation . It seems that Windows itself might be killing the process due to some violation , but I ca n't tell what since all of the temp files are basically the same and it is able to delete the first two with no problem.Anyone seen this type of behavior before ? private string TempFolder = Path.GetTempPath ( ) ; private void EraseTempFiles ( ) { // For each temp file : foreach ( string tempFile in TempFiles ) { if ( File.Exists ( tempFile ) ) { File.Delete ( tempFile ) ; } } } [ 23:54:52 ] The process has exited . [ 23:54:52 ] Dump count not reached . AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler ( UnhandledExceptionHandler ) ; private void UnhandledExceptionHandler ( object sender , UnhandledExceptionEventArgs e ) { System.Windows.Forms.MessageBox.Show ( ( ( Exception ) e.ExceptionObject ) .Message ) ; throw new NotImplementedException ( ) ; }",C # app exits without exception when deleting a temp file "C_sharp : I have a WCF method which returns me an array of custom objects like `` users '' , `` roles '' , or something else , and it has page output . WCF method has out parameter , stored procedure select rows and return total records of all rows ( not only selected ) , than i read return value in out parameter . But there is one problem i call WCF-method in lambda expression : what better solution for my example ? var client = MySvcRef.MySvcClient ( ) ; var assistant = FormsAuthenticationAssistant ( ) ; var result = assistant.Execute < MySvcRef.UserClass [ ] > ( ( ) = > client.GetAllUsers ( out totalRecords , pageIndex , pageSize ) , client.InnerChannel ) ;",.net lambda expression and out parameter "C_sharp : I want to get the most common string from a model list using Linq , but I do n't really know how.Here is some example code : Imagine a huge listof ModelClass is stored in the databaseHow would I find the most common name from this list using linq ? public ModelClass { public string name { get ; set ; } public int num { get ; set ; } } // in some controllervar model = from s in _db.SomeClass select s ; string mostCommonName = ? ? ? ? ? ? ?",C # - Get most common string in a Model list "C_sharp : I have a data structure which looks something like this : foo 1 : * bar 1 : * bazIt could look something like this when passed to the client : In my UI , this is represented by a tree structure , where the user can update/add/remove items on all levels.My question is , when the user has made modifications and I 'm sending the altered data back to the server , how should I perform the EF database update ? My initial thought was to implement dirty tracking on the client side , and make use of the dirty flag on the server in order to know what to update . Or maybe EF can be smart enough to do an incremental update itself ? { id : 1 , bar : [ { id : 1 , baz : [ ] } , { id : 2 , baz : [ { id : 1 } ] } ] }",Updating EF entities based on deep JSON data "C_sharp : I 'm currently working on a trivia game . I have written a Team class , a Question class and a Round class.This is my Team class ( I wont post properties , constructors , and methods since they are not relevant to my question ) .And this is my Round class : The problem I 'm having is what to do in case of a tie . There are 8 teams . Two winners from each of the first two Rounds ( 4 teams each ) will qualify for the 3rd and final round.So in case something like this happens : As you can see there 's a tie for the 2nd place . I know I can check for repeats , but what if the teams have scores like500 , 400 , 200 , 200or500 , 500 , 200 , 100In this case there is no need for a tie break , since only the top two teams advance to the next round.So i was wondering if anyone can help me come up with an algorithm that can help determine if I need a tie-Breaker round or not . And if I do , which teams should we pick and finally what are the top two teams from each round.Thanks for reading ! public class Team { private int _teamNumber = 0 ; private int _score = 0 ; } public class Round { Team [ ] _teams = new Team [ 4 ] ; Question [ ] _questions = new Clue [ 30 ] ; bool _done = true ; } currentRound.Teams [ 0 ] .Score = 300 ; currentRound.Teams [ 1 ] .Score = 300 ; currentRound.Teams [ 2 ] .Score = 100 ; currentRound.Teams [ 3 ] .Score = 350 ;",C # trivia game : What to do in case of a tie ? "C_sharp : I am working now on some stuff regarding registry.I checked the enum RegistryRights in System.Security.AccessControl.This enum is a bitwise , And I know that enums can contains duplicate values.I was trying to iterate through the enum by this code : also Enum.GetName ( typeof ( RegistryRights ) , regItem ) return the same key name.and the output I got is : Can someone please tell me why do I get duplicate keys ? ( `` ReadKey '' instead of `` ExecuteKey '' ) How can I force it to cast the int to the second key of the value ? and why ToString does not return the real key value ? public enum RegistryRights { QueryValues = 1 , SetValue = 2 , CreateSubKey = 4 , EnumerateSubKeys = 8 , Notify = 16 , CreateLink = 32 , Delete = 65536 , ReadPermissions = 131072 , WriteKey = 131078 , ExecuteKey = 131097 , ReadKey = 131097 , ChangePermissions = 262144 , TakeOwnership = 524288 , FullControl = 983103 , } foreach ( System.Security.AccessControl.RegistryRights regItem in Enum.GetValues ( typeof ( System.Security.AccessControl.RegistryRights ) ) ) { System.Diagnostics.Debug.WriteLine ( regItem.ToString ( ) + `` `` + ( ( int ) regItem ) .ToString ( ) ) ; } QueryValues 1SetValue 2CreateSubKey 4EnumerateSubKeys 8Notify 16CreateLink 32Delete 65536ReadPermissions 131072WriteKey 131078ReadKey 131097ReadKey 131097ChangePermissions 262144TakeOwnership 524288FullControl 983103",Why Iterating through the enum return duplicate keys ? "C_sharp : Lets say I have an observableCollection of classes : When I will remove items from a collection , do i need manually unsubscribe from events ( OnSomeEvent ) or should I leave it for a GC ? And what is the best way to unsubscribe ? CustomClassName testClass = new CustomClassName ( ) ; ObservableCollection < CustomClassName > collection = new ObservableCollection < CustomClassName > ( ) ; testClass.SomeEvent += OnSomeEvent ; collection.add ( testClass ) ;",Unsubscribe from events in observableCollection C_sharp : When you create credentials on Google Developer console You can create several different types of credentials depending upon which type is created you could have any of the followingPublic API keyClient IDClient SecretService account email addressThey all have different formats . I have deleted the ones I am posting.Public API key : AIzaSyAcMvMr_bk91qRKZ5SGYEvF5HWjXVE7XkkClient Id : 1046123799103-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.comClient secret : G5QtTuBDp6ejKraR0XodNwaWService account email address : 1046123799103-6v9cj8jbub068jgmss54m9gkuk4q2qu8 @ developer.gserviceaccount.comIs there any way to validate these in my application . What kind of keys are they ? I am using C # but any info on what kind of keys the are would be of help.I could probably come up with some kind of RegEx check for client id and service account email . But there must be a way of validating them better then that.Update : Google lets you validate the access token why is there no way to validate the credentials TokenInfo validationNot working . Convert.FromBase64String ( `` AIzaSyAcMvMr_bk91qRKZ5SGYEvF5HWjXVE7Xkk '' ) ;,Validating Google credentials "C_sharp : I have created an ASP.NET MVC5 sample project . I created my entities and from that , scaffolded the controllers for CRUD operations . I can only edit the POD members with the scaffolded code . I want to be able to add/remove related entities.With my current code , when I click save there is no error but no related entities are modified ( POD data is modified though ) . For example , if I wanted to remove all players from the account , they are n't removed . What am I doing wrong ? How can I remove/add related entities and push those changes to the database ? Here is the form : Here is the action to update the entity : Here are the models : I 'm basically lost . I ca n't find any examples in how to update related data . Could someone point me in the right direction ? I come from Symfony ( PHP Framework ) background . I thought it would be easier but I have been having problems . public async Task < ActionResult > Edit ( [ Bind ( Include = `` Account , Account.AccountModelId , Account.Name , Account.CreatedDate , SelectedPlayers '' ) ] AccountViewModel_Form vm ) { if ( ModelState.IsValid ) { if ( vm.SelectedPlayers ! = null ) { vm.Account.PlayerModels = db.PlayerModels.Where ( p = > p.AccountModel.AccountModelId == vm.Account.AccountModelId ) .ToList ( ) ; foreach ( var player in vm.Account.PlayerModels ) { player.AccountModel = null ; db.Entry ( player ) .State = EntityState.Modified ; } vm.Account.PlayerModels.Clear ( ) ; foreach ( var player_id in vm.SelectedPlayers ) { var player = db.PlayerModels.Where ( p = > p.PlayerModelId == player_id ) .First ( ) ; vm.Account.PlayerModels.Add ( player ) ; db.Entry ( player ) .State = EntityState.Modified ; } } db.Entry ( vm.Account ) .State = EntityState.Modified ; await db.SaveChangesAsync ( ) ; return RedirectToAction ( `` Index '' ) ; } return View ( vm ) ; } public class AccountViewModel_Form { public AccountModel Account { get ; set ; } public HashSet < Int32 > SelectedPlayers { get ; set ; } public virtual List < PlayerModel > PlayersList { get ; set ; } } public class AccountModel { public AccountModel ( ) { PlayerModels = new HashSet < PlayerModel > ( ) ; } public Int32 AccountModelId { get ; set ; } public string Name { get ; set ; } public DateTime CreatedDate { get ; set ; } public virtual ICollection < PlayerModel > PlayerModels { get ; set ; } } public class PlayerModel { public Int32 PlayerModelId { get ; set ; } public float Gold { get ; set ; } public string Name { get ; set ; } public virtual AccountModel AccountModel { get ; set ; } }",How to update a collection inside an entity within a post action in ASP.NET MVC5 ? "C_sharp : Sometimes when I am trying to create blurred bitmap I am getting `` Null Pointer Exception '' .Happens in this block of code ( I recently started catching the exception so at least it does n't crash the app ) : Please refer to these pictures for more details about parameters I am passing into the `` CreateBitmap '' method : Here is the expanded parameters : Full exception : exception { Java.Lang.NullPointerException : Exception of type 'Java.Lang.NullPointerException ' was thrown . at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) [ 0x0000b ] in /Users/builder/data/lanes/2058/58099c53/source/mono/mcs/class/corlib/System.Runtime.ExceptionServices/ExceptionDispatchInfo.cs:61 at Android.Runtime.JNIEnv.CallStaticObjectMethod ( IntPtr jclass , IntPtr jmethod , Android.Runtime.JValue* parms ) [ 0x00064 ] in /Users/builder/data/lanes/2058/58099c53/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:1301 at Android.Graphics.Bitmap.CreateBitmap ( System.Int32 [ ] colors , Int32 width , Int32 height , Android.Graphics.Config config ) [ 0x00088 ] in /Users/builder/data/lanes/2058/58099c53/source/monodroid/src/Mono.Android/platforms/android-22/src/generated/Android.Graphics.Bitmap.cs:735 at Psonar.Apps.Droid.PayPerPlay.StackBlur.GetBlurredBitmap ( Android.Graphics.Bitmap original , Int32 radius ) [ 0x00375 ] in d : \Dev\psonar\Source\Psonar.Apps\Psonar.Apps.Droid\Psonar.Apps.Droid.PayPerPlay\Utilities\StackBlur.cs:123 -- - End of managed exception stack trace -- - java.lang.NullPointerException at android.graphics.Bitmap.createBitmap ( Bitmap.java:687 ) at android.graphics.Bitmap.createBitmap ( Bitmap.java:707 ) at dalvik.system.NativeStart.run ( Native Method ) } Java.Lang.NullPointerExceptionNot sure if this could be a bug in Xamarin or the passed parameters are wrong . try { using ( Bitmap.Config config = Bitmap.Config.Rgb565 ) { return Bitmap.CreateBitmap ( blurredBitmap , width , height , config ) ; } } catch ( Java.Lang.Exception exception ) { Util.Log ( exception.ToString ( ) ) ; }",Android - Bitmap.CreateBitmap - null pointer exception "C_sharp : I am implementing HotChocolate as part of my ASP.NET API . I 'm trying to add subscriptions to the chat portion on my app , however , the documentation on the HotChocolate site is not implemented yet . From what I can tell from other sites/frameworks , I can use the C # IObservable < Chat > as the return type for the subscription method . Can anyone give me an example of a query method or point me towards another resource ? However , how does this work from a query standpoint ? How do we trigger an event to update this ? Thanks . public async Task < IObservable < Message > > GetMessages ( Guid chatId ) { var messages = ..Get chats ; return messages ; }",How do I implement subscriptions in GraphQL HotChocolate ? "C_sharp : I 've been trying to figure out how this works on a low-level : Basically , the above code snippet seems to intercept calls to the Index method , perform an authorization check , and throw and exception if not authorized . The exception prevents the code within the Index method from ever being invoked . This seems very AOP-like , and is not something easily done in C # . If I were to implement my own class that extended System.Attribute , I would not have any interface to hook into pre or post invocation of the method my attribute decorates . So how does the MVC Authorize attribute do it , and how could I do it on my own ? PostSharp is a library that accomplishes the same thing using IL Weaving . Basically , at compile time , PostSharp scans the assembly for methods decorated with certain attributes , and then re-writes your code to wrap your method calls with other method calls . Does the MVC framework also perform some kind of IL Weaving at compile time ? Is it possible for me to perform my own IL Weaving ? Or are there other techniques for applying the same AOP principles without complex IL Weaving ? I 've tried to find information on IL Weaving but all I find are articles about PostSharp . I would prefer to stay away from PostSharp because of the Licensing hassles , but moreover , I just want to know how the heck they did it for my own growth as a developer . It 's quite fascinating . [ Authorize ] public ActionResult Index ( ) { return View ( ) ; }",Explain HOW the MVC Authorize Attribute performs AOP-like actions "C_sharp : I am working on a Web API endpoint which will accept multipart/mixed messages as a POST . The issue I am facing is how to mock up such a request in a unit test ? The core of the API method is : I know that I have to create the request object and seed my test conditions into it , and the controller , before calling post in my test . What I am having trouble sorting out is the correct way to get the multipart content into the correct form for the ReadAsMultipartAsync ( ) call . I pieced this method together , and the request it creates is accepted and parsed correctly when fed into the above controller . However , setting a break point and inspecting the request object looks very different when built by this test vs. generated by something like fiddler and coming in through the pipeline . The pipeline has content of the type System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent while the test debug is System.Net.Http.MultipartContent.I guess I am worried that this technique will lead to a false sense of security because the test is not feeding things to the controller in the same format as the pipeline will when this goes live . Is there a better way to build the requests for my tests ? Or am I being overly paranoid , and this is a viable option for my scenario ? EDIT : We have reached the point where we are trying to test this endpoint from external code and we are seeing significant performance differences between the LazyStream and Multipart . The external code commonly gets timeouts when submitting the same data as the internal tests . public HttpResponseMessage Post ( ) { var parsedContent=Request.Content.ReadAsMultipartAsync ( ) .Result ; foreach ( var item in parsedContent.Contents ) { switch ( item.Headers.ContentType.MediaType ) { case `` application/json '' : doSomething ( item ) ; break ; case `` text/plain '' : doSomethingElse ( item ) ; break ; case `` application/pdf '' : doAnotherThing ( item ) ; break ; case `` image/png '' : doYetAnotherThing ( item ) ; break ; } } //return status message based on results of previous calls ... } public static HttpRequestMessage CreateMixedPostRequest ( string url , IEnumerable < HttpContent > contentItems ) { var request=new HttpRequestMessage ( HttpMethod.Post , url ) ; var content=new MultipartContent ( `` mixed '' ) ; foreach ( var item in contentItems ) { content.Add ( item ) ; } request.Content=content ; return request ; }",Creating a mulitpart/mixed form request in unit test C_sharp : While performing a check if there 's a camera present and enabled on my windows mobile unit I encountered something I do n't understand.The code looks like this : When I call CameraPresent2 ( ) it return false ( there is no camera present ) . But when I call CameraPresent1 ( ) i recieve a MissingMethodException with comment `` Could not find method : get_CameraEnabled Microsoft.WindowsMobile.Status.SystemState . `` Is the second term evaluated in CameraPresent1 just because they both are property ( at language level ) ? Is there anything else that explains the difference in behaviour ? public static bool CameraP ( ) { return Microsoft.WindowsMobile.Status.SystemState.CameraPresent ; } public static bool CameraE ( ) { return Microsoft.WindowsMobile.Status.SystemState.CameraEnabled ; } public static bool CameraPresent1 ( ) { return Microsoft.WindowsMobile.Status.SystemState.CameraPresent & & Microsoft.WindowsMobile.Status.SystemState.CameraEnabled ; } public static bool CameraPresent2 ( ) { return CameraP ( ) & & CameraE ( ) ; },Why does short-circuiting not prevent MissingMethodException related to unreachable branch of logical AND ( & & ) ? C_sharp : in my code i have : now i want to evaluate if i have a list of vehicles . something like : how can i do this ? the is-operator on the generic list does not work . is there another way ? interface IVehicle { void DoSth ( ) ; } class VW : IVehicle { public virtual void DoSth ( ) { ... } } class Golf : VW { } class Lupo : VW { public override void DoSth ( ) { base.DoSth ( ) ; ... } } List < VW > myCars = new List < VW > ( ) ; myCars.Add ( new Golf ( ) ) ; myCars.Add ( new Lupo ( ) ) ; if ( myCars is List < IVehicle > ) { foreach ( IVehicle v in myCars ) v.DoSth ( ) ; },is-operator on generic list "C_sharp : My ChildWindow has CloseButton and handler assigned to Click event . Code ( only for example ) : Declaring close button : Private counter ( for diagnostics problem ) : Close event handler : After fast clicking program can output `` 1 '' , `` 2 '' , `` 3 '' , and so on ... As i know after setting DialogResult = true ( or false ) , ChildWindow should be closed and there should not be any way to raise the CloseButton 's Click event second time.Can anyone help me to figure out cause of the problem and help to solve it without bool flags ( executed/ ! executed ) ? < Button x : Name= '' CloseButton '' Click= '' OnCloseButtonClick '' / > private uint _i ; OnCloseButtonClick ( object sender , RoutedEventArgs e ) { DialogResult = true ; System.Diagnostics.Debug ( _i++ ) ; }",ChildWindow Close button event handler executes multiple times if it fast clicked many times "C_sharp : The following simple program will find the last letter in a string that a user enters and then remove everything after that point . So , if a person enters one string ... . everything after the g should be removed . I 've got the following as a little program : I 've tried numerous variations of this and none of them getting it exactly write . This particular program with an input of string ... . the output of the program is strin.. So somehow it 's leaving on what it should be taking away and it 's actually taking away letters that it should n't . Can anyone give an indication as to why this is happening ? The desired output , again should be string . class Program { static void Main ( string [ ] args ) { Console.Write ( `` Enter in the value of the string : `` ) ; List < char > charList = Console.ReadLine ( ) .Trim ( ) .ToList ( ) ; int x = charList.LastIndexOf ( charList.Last ( char.IsLetter ) ) ; Console.WriteLine ( `` this is the last letter { 0 } '' , x ) ; Console.WriteLine ( `` This is the length of the string { 0 } '' , charList.Count ) ; Console.WriteLine ( `` We should have the last { 0 } characters removed '' , charList.Count - x ) ; for ( int i = x ; i < charList.Count ; i++ ) { charList.Remove ( charList [ i ] ) ; } foreach ( char c in charList ) { Console.Write ( c ) ; } Console.ReadLine ( ) ; } }",Remove all characters after the last letter C_sharp : I am writing a simple method that will calculate the number of decimal places in a decimal value . The method looks like this : I have run it against some test values to make sure that everything is working fine but am getting some really weird behavior back on the last one : Tests 1-5 work fine but test6 returns 23 . I know that the value being passed in exceeds the maximum decimal precision but why 23 ? The other thing I found odd is when I put a breakpoint inside the GetDecimalPlaces method following my call from test6 the value of decimalNumber inside the method comes through as the same value that would have come from test5 ( 20 decimal places ) yet even though the value passed in has 20 decimal places 23 is returned.Maybe its just because I 'm passing in a number that has way too many decimal places and things go wonky but I want to make sure that I 'm not missing something fundamentally wrong here that might throw off calculations for the other values later down the road . public int GetDecimalPlaces ( decimal decimalNumber ) { try { int decimalPlaces = 1 ; double powers = 10.0 ; if ( decimalNumber > 0.0m ) { while ( ( ( double ) decimalNumber * powers ) % 1 ! = 0.0 ) { powers *= 10.0 ; ++decimalPlaces ; } } return decimalPlaces ; int test = GetDecimalPlaces ( 0.1m ) ; int test2 = GetDecimalPlaces ( 0.01m ) ; int test3 = GetDecimalPlaces ( 0.001m ) ; int test4 = GetDecimalPlaces ( 0.0000000001m ) ; int test5 = GetDecimalPlaces ( 0.00000000010000000001m ) ; int test6 = GetDecimalPlaces ( 0.0000000001000000000100000000010000000001000000000100000000010000000001000000000100000000010000000001m ) ;,custom method for returning decimal places shows odd behavior C_sharp : I have a DataGrid where the ItemsSource is bound to an ObservableCollection < LogEntry > . On a click on a Button the user can scroll to a specific LogEntry . Therefor I use the following code : This just works fine . But what I do n't like is : If the LogEntry already is in view then the DataGrid flickers shortly . My question now is : Is there a possibility to check on the DataGrid if the given LogEntry already is in view ? private void BringSelectedItemIntoView ( LogEntry logEntry ) { if ( logEntry ! = null ) { ContentDataGrid.ScrollIntoView ( logEntry ) ; } },Check if Item in a DataGrid is already in view "C_sharp : Jon Galloway has an overview - http : //weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx - of the new membership features in ASP.NET MVC 4 . The Internet project template moves away from the core membership providers of ASP.NET and into the world of SimpleMembershipProvider and OAuth . Refering to simplemembership , does anyone know if its possible to extend it using open source http : //aspnetwebstack.codeplex.com/ in order to be able to allow anonymous users stored in database - probably in userprofile table ? I checked the http : //msdn.microsoft.com/en-us/library/webmatrix.webdata.simplemembershipprovider simplemembership provider class but its methods have no reference to anonymous identifications . If its not possible , does anyone have information about building an ExtendedMembershipProvider to do that ? .brgds ! UPDATED INFO : from pro.asp.netmvc3 book . regarding authentication authorization-Enabling Anonymous Profiles : By default , profile data is available only for authenticated users , and an exception will be thrown if we attempt to write profile properties when the current user hasn ’ t logged in . We can change this by enabling support for anonymous profiles , as shown in Listing 22-17.When anonymous identification is enabled , the ASP.NET framework will track anonymous users by giving them a cookie called .ASPXANONYMOUS that expires after 10,000 minutes ( that ’ s around 70 days ) . Wecan enable anonymous support for profile properties by setting the allowAnonymous attribute to true ; in the listing we have enabled anonymous support for the Name and City properties.Enabling anonymous profiles makes it possible to read and write profile data for unauthenticatedusers , but beware , every unauthenticated visitor will automatically create a user account in the profile database.I Would like to replicate this in simplemembership . I dont want to use old profile system bbecause its store values in blob . brgds ! . **Update : listing 22-17 : Listing 22-17 . Enabling Support for Anonymous ProfilesWhen anonymous identification is enabled , the ASP.NET framework will track anonymous users bygiving them a cookie called .ASPXANONYMOUS that expires after 10,000 minutes ( that ’ s around 70 days ) . Wecan enable anonymous support for profile properties by setting the allowAnonymous attribute to true ; inthe listing we have enabled anonymous support for the Name and City properties . ** < configuration > < system.web > < anonymousIdentification enabled= '' true '' / > < profile > < providers > < clear/ > < add name= '' AspNetSqlProfileProvider '' type= '' System.Web.Profile.SqlProfileProvider '' connectionStringName= '' ApplicationServices '' applicationName= '' / '' / > < /providers > < properties > < add name= '' Name '' type= '' String '' allowAnonymous= '' true '' / > < group name= '' Address '' > < add name= '' Street '' type= '' String '' / > < add name= '' City '' type= '' String '' allowAnonymous= '' true '' / > < add name= '' ZipCode '' type= '' String '' / > < add name= '' State '' type= '' String '' / > < /group > < /properties > < /profile > < /system.web > < /configuration >",Simplemembership implementing anonymous users method "C_sharp : I have the following lines in my code . They are taking more place than they should . Any suggestions for a smaller code . I know , not a really important question , but this is taking 2/3 of the entire method and not the important stuff . string longestString ; string shortestString ; if ( string1.Length > string2.Length ) { longestString = string1 ; shortestString = string2 ; } else { longestString = string2 ; shortestString = string1 ; }",Get longest and shortest string in a esthetical way "C_sharp : I 've wondered about this , so I figure I 'll ask it.Most places you 'll see use the same semantic logic for overriding Equals as GetHashCode for memberwise equality ... however they usually use different implementations : If you 're implementing memberwise equality for your type ( lets say for storing in a dictionary ) , why not just override GetHashCode then do something like this for Equals : public override bool Equals ( object obj ) { if ( obj == null || GetType ( ) ! = obj.GetType ( ) ) { return false ; } var other = ( MyType ) obj ; if ( other.Prop1 ! = Prop1 ) { return false ; } return true ; } public override int GetHashCode ( ) { int hash = -657803396 ; num ^= Prop1.GetHashCode ( ) ; return num ; } public override bool Equals ( object obj ) { return this.HashEqualsAndIsSameType ( obj ) ; } public static bool HashEquals ( this object source , object obj ) { if ( source ! = null & & obj ! = null ) { return source.GetHashCode ( ) == obj.GetHashCode ( ) ; } if ( source ! = null || obj ! = null ) { return false ; } return true ; } public static bool HashEqualsAndIsSameType < T > ( this T source , object obj ) { return ( obj == null || obj.GetType ( ) == typeof ( T ) ) & & source.HashEquals ( obj ) ; }",GetHashCode Equality "C_sharp : I have a very complicated problem . I have tried to check everything and I have worked for near-about 6 hours on this problem . But I am not successful to solve this problem . So , here is the question.Problem : Initially when program loads up : When I click on edit button on any row : When I save that row : When I click on edit button on another row having different Parent Group : XAML looks like below : Here is the code-Behind : At Last here is the code for ViewModel : I am not sure where the problem lies , so , I posted almost all the code here.I have created a sample project that can be downloaded from the link below : Project : https : //drive.google.com/file/d/0B5WyqSALui0bTTNsMm5ISHV3VEk/view ? usp=sharingDataBase : https : //drive.google.com/file/d/0B5WyqSALui0bTXVJanp4TE9iSGs/view ? usp=sharingEdit 1 : The original problem ( as shown in the images ) is solved To solve the problem I removed CollectionViewSource and bound the ComboBox directly to the ViewModel Property . Now I get another error : When I see InnerException : I have searched the net for this error but then everywhere I can see that if I insert NULL value into the foreign Key column then I get this error . But my column is Nullable and I need nulls to be inserted.edit 2 : I have solved the error mentioned in edit 1.Added a new record as first record in the table called Primary . And removed all the coding related to Primary Group . Replaced NULLs in database with the primary group.Now the only problem left is using a CollectionViewSource as the source of combobox to sort the data instead of Binding the combobox directly to the Property inside ViewModel . Can anybody answer this question ? ? ? ? < CollectionViewSource x : Key= '' GroupsViewSource '' Source= '' { Binding Groups , UpdateSourceTrigger=PropertyChanged } '' > < CollectionViewSource.SortDescriptions > < scm : SortDescription PropertyName= '' GroupName '' / > < /CollectionViewSource.SortDescriptions > < /CollectionViewSource > < CollectionViewSource x : Key= '' ParentGroupsViewSource '' Source= '' { Binding ParentGroups } '' > < CollectionViewSource.SortDescriptions > < scm : SortDescription PropertyName= '' GroupName '' / > < /CollectionViewSource.SortDescriptions > < /CollectionViewSource > < DataGrid Grid.Row= '' 0 '' Grid.Column= '' 0 '' ItemsSource= '' { Binding Source= { StaticResource GroupsViewSource } } '' SelectedItem= '' { Binding SelectedGroup } '' x : Name= '' dataGrid '' AutoGenerateColumns= '' False '' CanUserAddRows= '' False '' SelectionMode= '' Single '' SelectionUnit= '' FullRow '' IsSynchronizedWithCurrentItem= '' True '' EnableRowVirtualization= '' False '' VirtualizingPanel.IsContainerVirtualizable= '' False '' RowEditEnding= '' DataGrid_RowEditEnding '' > < DataGrid.Resources > < Style TargetType= '' { x : Type DataGridCell } '' BasedOn= '' { StaticResource { x : Type DataGridCell } } '' > < EventSetter Event= '' PreviewMouseLeftButtonDown '' Handler= '' DataGridCell_PreviewMouseLeftButtonDown '' / > < /Style > < /DataGrid.Resources > < i : Interaction.Triggers > < i : EventTrigger EventName= '' RowEditEnding '' > < i : InvokeCommandAction Command= '' { Binding DataGridRowEditEndingCommand } '' / > < /i : EventTrigger > < /i : Interaction.Triggers > < DataGrid.Columns > < DataGridTemplateColumn Header= '' Group Name '' Width= '' * '' SortMemberPath= '' GroupName '' > < DataGridTemplateColumn.HeaderTemplate > < DataTemplate > < Grid IsHitTestVisible= '' True '' > < Grid.ColumnDefinitions > < ColumnDefinition/ > < ColumnDefinition/ > < /Grid.ColumnDefinitions > < TextBlock Grid.Column= '' 0 '' Text= '' { TemplateBinding Content } '' / > < ! -- FILTER EXPANDER -- > < Expander Grid.Column= '' 1 '' IsHitTestVisible= '' True '' VerticalAlignment= '' Top '' Margin= '' 30 0 0 0 '' ToolTip= '' Filter '' > < Border IsHitTestVisible= '' True '' BorderThickness= '' 1 '' Margin= '' -160 5 0 0 '' MinWidth= '' 200 '' Height= '' 31 '' > < TextBox Text= '' { Binding DataContext.SearchGroupName , ElementName=uc , UpdateSourceTrigger=PropertyChanged } '' TextChanged= '' SearchTextBox_TextChanged '' ToolTip= '' Enter Group Name to search '' FontSize= '' 16 '' BorderThickness= '' 1 '' / > < /Border > < /Expander > < /Grid > < /DataTemplate > < /DataGridTemplateColumn.HeaderTemplate > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < TextBlock Text= '' { Binding GroupName } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < TextBox Text= '' { Binding GroupName } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < /DataGridTemplateColumn > < DataGridTemplateColumn Header= '' Parent Group '' Width= '' * '' SortMemberPath= '' ParentID '' > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < TextBlock Text= '' { Binding ParentID , Converter= { StaticResource parentIDToGroupNameConverter } } '' / > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < DataGridTemplateColumn.CellEditingTemplate > < DataTemplate > < ComboBox ItemsSource= '' { Binding Source= { StaticResource ParentGroupsViewSource } } '' DisplayMemberPath= '' GroupName '' SelectedValue= '' { Binding ParentID , Converter= { StaticResource parentIDToGroupNameConverter } } '' SelectedValuePath= '' GroupName '' / > < /DataTemplate > < /DataGridTemplateColumn.CellEditingTemplate > < /DataGridTemplateColumn > < DataGridTemplateColumn Header= '' Edit '' Width= '' 50 '' IsReadOnly= '' True '' > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' Auto '' / > < /Grid.RowDefinitions > < Button x : Name= '' btnEdit '' Style= '' { StaticResource ResourceKey=EditButton } '' Height= '' 35 '' Width= '' 35 '' Visibility= '' { Binding DataContext.IsInEdit , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } , Converter= { StaticResource boolToVisibilityInverseConverter } } '' Click= '' EditButton_Click '' Command= '' { Binding DataContext.EditCommand , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } } '' / > < Button x : Name= '' btnSave '' Grid.Row= '' 1 '' Style= '' { StaticResource ResourceKey=SaveButton } '' Height= '' 35 '' Width= '' 35 '' Visibility= '' { Binding DataContext.IsInEdit , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } , Converter= { StaticResource boolToVisibilityConverter } } '' Click= '' SaveButton_Click '' Command= '' { Binding DataContext.SaveCommand , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } } '' / > < /Grid > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < /DataGridTemplateColumn > < DataGridTemplateColumn Header= '' Delete '' Width= '' 70 '' IsReadOnly= '' True '' > < DataGridTemplateColumn.CellTemplate > < DataTemplate > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' Auto '' / > < /Grid.RowDefinitions > < Button x : Name= '' btnDelete '' Style= '' { StaticResource ResourceKey=DeleteButton } '' Height= '' 35 '' Width= '' 35 '' Visibility= '' { Binding DataContext.IsInEdit , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } , Converter= { StaticResource boolToVisibilityInverseConverter } } '' Command= '' { Binding DataContext.DeleteCommand , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } } '' / > < Button x : Name= '' btnCancel '' Grid.Row= '' 1 '' Style= '' { StaticResource ResourceKey=CancelButton } '' Height= '' 35 '' Width= '' 35 '' Visibility= '' { Binding DataContext.IsInEdit , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } , Converter= { StaticResource boolToVisibilityConverter } } '' Command= '' { Binding DataContext.CancelCommand , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type UserControl } } } '' Click= '' CancelButton_Click '' / > < /Grid > < /DataTemplate > < /DataGridTemplateColumn.CellTemplate > < /DataGridTemplateColumn > < /DataGrid.Columns > < /DataGrid > public partial class ListView : UserControl { ERPLiteDBContext db = new ERPLiteDBContext ( ) ; public ListView ( ) { InitializeComponent ( ) ; } private void DataGridCell_PreviewMouseLeftButtonDown ( object sender , MouseButtonEventArgs e ) { DependencyObject dep = ( DependencyObject ) e.OriginalSource ; if ( dep == null ) return ; while ( dep ! = null & & ! ( dep is DataGridCell ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; if ( dep is DataGridCell ) { if ( ! ( ( DataGridCell ) dep ) .IsReadOnly ) { if ( ! ( ( DataGridCell ) dep ) .IsEditing ) e.Handled = true ; } } while ( dep ! = null & & ! ( dep is DataGridRow ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; if ( dep is DataGridRow ) { ( ( DataGridRow ) dep ) .IsSelected = true ; } while ( dep ! = null & & ! ( dep is DataGrid ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; if ( dep is DataGrid ) { ( ( DataGrid ) dep ) .Focus ( ) ; } } private void EditButton_Click ( object sender , RoutedEventArgs e ) { int rowIndex = 0 ; DependencyObject dep = ( DependencyObject ) e.OriginalSource ; while ( dep ! = null & & ! ( dep is DataGridCell ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; DataGridRow row = null ; if ( dep is DataGridCell ) { while ( dep ! = null & & ! ( dep is DataGridRow ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } row = ( DataGridRow ) dep ; rowIndex = FindRowIndex ( row ) ; } while ( dep ! = null & & ! ( dep is DataGrid ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; DataGrid dg = ( DataGrid ) dep ; dg.CurrentCell = new DataGridCellInfo ( dg.Items [ rowIndex ] , dg.Columns [ 0 ] ) ; dg.BeginEdit ( ) ; for ( int column = 0 ; column < = dg.Columns.Count - 1 ; column++ ) { if ( ! ( GetDataGridCell ( new DataGridCellInfo ( dg.Items [ rowIndex ] , dg.Columns [ column ] ) ) .IsReadOnly ) ) { GetDataGridCell ( new DataGridCellInfo ( dg.Items [ rowIndex ] , dg.Columns [ column ] ) ) .IsEditing = true ; } } var rows = GetDataGridRows ( dg ) ; foreach ( DataGridRow r in rows ) { if ( ! ( r.IsEditing ) ) { r.IsEnabled = false ; } } } private void SaveButton_Click ( object sender , RoutedEventArgs e ) { int rowIndex = 0 ; DependencyObject dep = ( DependencyObject ) e.OriginalSource ; while ( dep ! = null & & ! ( dep is DataGridCell ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; DataGridRow row = null ; if ( dep is DataGridCell ) { while ( dep ! = null & & ! ( dep is DataGridRow ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } row = ( DataGridRow ) dep ; rowIndex = FindRowIndex ( row ) ; } while ( dep ! = null & & ! ( dep is DataGrid ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; DataGrid dg = ( DataGrid ) dep ; dg.CommitEdit ( DataGridEditingUnit.Row , true ) ; for ( int column = 0 ; column < = dg.Columns.Count - 1 ; column++ ) { if ( ! ( GetDataGridCell ( new DataGridCellInfo ( dg.Items [ rowIndex ] , dg.Columns [ column ] ) ) .IsReadOnly ) ) { GetDataGridCell ( new DataGridCellInfo ( dg.Items [ rowIndex ] , dg.Columns [ column ] ) ) .IsEditing = false ; } } var rows = GetDataGridRows ( dg ) ; foreach ( DataGridRow r in rows ) { r.IsEnabled = true ; } } private void CancelButton_Click ( object sender , RoutedEventArgs e ) { DependencyObject dep = ( DependencyObject ) e.OriginalSource ; int rowIndex = 0 ; DataGridRow row = null ; while ( dep ! = null & & ! ( dep is DataGridRow ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } row = ( DataGridRow ) dep ; rowIndex = FindRowIndex ( row ) ; while ( dep ! = null & & ! ( dep is DataGrid ) ) { dep = VisualTreeHelper.GetParent ( dep ) ; } if ( dep == null ) return ; DataGrid dg = ( DataGrid ) dep ; var rows = GetDataGridRows ( dg ) ; dg.CancelEdit ( DataGridEditingUnit.Row ) ; for ( int column = 0 ; column < = dg.Columns.Count - 1 ; column++ ) { if ( ! ( GetDataGridCell ( new DataGridCellInfo ( dg.Items [ rowIndex ] , dg.Columns [ column ] ) ) .IsReadOnly ) ) { GetDataGridCell ( new DataGridCellInfo ( dg.Items [ rowIndex ] , dg.Columns [ column ] ) ) .IsEditing = false ; } } foreach ( DataGridRow r in rows ) { r.IsEnabled = true ; } } private void DataGrid_RowEditEnding ( object sender , DataGridRowEditEndingEventArgs e ) { DataGrid dg = ( DataGrid ) sender ; foreach ( DataGridRow row in GetDataGridRows ( dg ) ) { row.IsEnabled = true ; } } private void SearchTextBox_TextChanged ( object sender , TextChangedEventArgs e ) { if ( dataGrid.SelectedItem ! = null ) { dataGrid.ScrollIntoView ( dataGrid.SelectedItem ) ; } } public DataGridCell GetDataGridCell ( DataGridCellInfo cellInfo ) { var cellContent = cellInfo.Column.GetCellContent ( cellInfo.Item ) ; if ( cellContent ! = null ) return ( DataGridCell ) cellContent.Parent ; return null ; } private int FindRowIndex ( DataGridRow row ) { DataGrid dataGrid = ItemsControl.ItemsControlFromItemContainer ( row ) as DataGrid ; int index = dataGrid.ItemContainerGenerator.IndexFromContainer ( row ) ; return index ; } public IEnumerable < DataGridRow > GetDataGridRows ( DataGrid grid ) { var itemsSource = grid.ItemsSource as IEnumerable ; if ( null == itemsSource ) yield return null ; foreach ( var item in itemsSource ) { var row = grid.ItemContainerGenerator.ContainerFromItem ( item ) as DataGridRow ; if ( null ! = row ) yield return row ; } } } public class ListViewModel : ViewModelBase { ERPLiteDBContext db = new ERPLiteDBContext ( ) ; public ListViewModel ( ) { Groups = new ObservableCollection < Group > ( db.Groups ) ; ParentGroups = new ObservableCollection < Group > ( db.Groups ) ; EditCommand = new RelayCommand ( Edit ) ; SaveCommand = new RelayCommand ( Save ) ; DeleteCommand = new RelayCommand ( Delete ) ; CancelCommand = new RelayCommand ( Cancel ) ; DataGridRowEditEndingCommand = new RelayCommand ( DataGridRowEditEnding ) ; SearchGroupName = `` '' ; IsInEdit = false ; } public RelayCommand EditCommand { get ; set ; } public RelayCommand SaveCommand { get ; set ; } public RelayCommand DeleteCommand { get ; set ; } public RelayCommand CancelCommand { get ; set ; } public RelayCommand DataGridRowEditEndingCommand { get ; set ; } private string _searchGroupName ; public string SearchGroupName { get { return _searchGroupName ; } set { if ( value == null ) { SearchGroupName = `` '' ; } else { _searchGroupName = value ; } OnPropertyChanged ( `` SearchGroupName '' ) ; SelectedGroup = db.Groups.AsEnumerable ( ) .OrderBy ( x = > x.GroupName ) .Where ( x = > x.GroupName.StartsWith ( SearchGroupName , StringComparison.OrdinalIgnoreCase ) ) .FirstOrDefault ( ) ; if ( SelectedGroup == null ) { SelectedGroup = db.Groups.AsEnumerable ( ) .OrderBy ( x = > x.GroupName ) .Where ( x = > x.GroupName.Contains ( SearchGroupName , StringComparison.OrdinalIgnoreCase ) ) .FirstOrDefault ( ) ; } } } private ObservableCollection < Group > _groups ; public ObservableCollection < Group > Groups { get { return _groups ; } set { _groups = value ; OnPropertyChanged ( `` Groups '' ) ; } } private Group _selectedGroup ; public Group SelectedGroup { get { return _selectedGroup ; } set { _selectedGroup = value ; OnPropertyChanged ( `` SelectedGroup '' ) ; if ( value ! = null ) { ParentGroups = new ObservableCollection < Group > ( db.Groups.Where ( x = > x.GroupID ! = value.GroupID ) ) ; ParentGroups.Add ( new Group { GroupID = -1 , GroupName = `` Primary '' } ) ; } } } private ObservableCollection < Group > _parentGroups ; public ObservableCollection < Group > ParentGroups { get { return _parentGroups ; } set { _parentGroups = value ; OnPropertyChanged ( `` ParentGroups '' ) ; } } private Group _selectedParentGroup ; public Group SelectedParentGroup { get { return _selectedParentGroup ; } set { _selectedParentGroup = value ; OnPropertyChanged ( `` SelectedParentGroup '' ) ; } } private bool _isInEdit ; public bool IsInEdit { get { return _isInEdit ; } set { _isInEdit = value ; OnPropertyChanged ( `` IsInEdit '' ) ; } } private void Edit ( object obj ) { IsInEdit = true ; } private void Save ( object obj ) { IsInEdit = false ; SaveToDataBase ( ) ; } private void Delete ( object obj ) { } private void Cancel ( object obj ) { IsInEdit = false ; } private void DataGridRowEditEnding ( object obj ) { IsInEdit = false ; } public void SaveToDataBase ( ) { Group currentGroup = db.Groups.Where ( x = > x.GroupID == SelectedGroup.GroupID ) .FirstOrDefault ( ) ; if ( currentGroup ! = null ) { currentGroup.GroupName = SelectedGroup.GroupName ; if ( SelectedGroup.ParentID == -1 ) { currentGroup.ParentID = null ; } else { currentGroup.ParentID = SelectedGroup.ParentID ; } db.SaveChanges ( ) ; } } }",Unexpected behavior of DataGrid "C_sharp : The next code shows wrong local time if current location is Moscow : Output : It should be 13:00 and 14:00 . How to fix it ? P.S . OS - Windows 7 Enterprise . DateTime dt = new DateTime ( 2010 , 1 , 1 , 10 , 0 , 0 , 0 , DateTimeKind.Utc ) ; Console.WriteLine ( dt + `` - `` + dt.ToLocalTime ( ) ) ; dt = new DateTime ( 2010 , 7 , 1 , 10 , 0 , 0 , 0 , DateTimeKind.Utc ) ; Console.WriteLine ( dt + `` - `` + dt.ToLocalTime ( ) ) ; 01.01.2010 10:00:00 - 01.01.2010 14:00:0001.07.2010 10:00:00 - 01.07.2010 15:00:00",Wrong conversion of Moscow time to UTC "C_sharp : Suppose I had this in C # : Of course , this does not compile , because the line CallWithDelegate ( SomeOverloadedMethod ) ; is ambiguous.Now , suppose there was only one CallWithDelegate ( SomeDelegateWithoutParameter del ) function ( no overloads ) . In this case , there would be no ambiguity , because , from what seems to be happening , the compiler can look at the parameter type and discard SomeOverloadedMethod ( int n ) from the candidate list ( since it can only take a SomeDelegateWithoutParameters ) , and so it compiles.I do n't intend to write code like this ; this is just out of curiosity , from a compiler writer point-of-view . I could n't find an answer about this , since it is quite confusing to put into words.I 'd like to know if there is any way in C # to disambiguate that call in Main ( ) in the example given , so that it would compile . How can you specify it so that it resolves into CallWithDelegate ( SomeDelegateWithoutParameters del ) being passed SomeOverloadedMethod ( ) , or CallWithDelegate ( SomeDelegateWithParameter del ) being passed SomeOverloadedMethod ( int n ) ? class OverloadTest { void Main ( ) { CallWithDelegate ( SomeOverloadedMethod ) ; } delegate void SomeDelegateWithoutParameters ( ) ; delegate void SomeDelegateWithParameter ( int n ) ; void CallWithDelegate ( SomeDelegateWithoutParameters del ) { } void CallWithDelegate ( SomeDelegateWithParameter del ) { } void SomeOverloadedMethod ( ) { } void SomeOverloadedMethod ( int n ) { } }",Disambiguating between overloaded methods passed as delegates in an overloaded call "C_sharp : I have to work with ( i.e . I have no control over ) csv files where `` N/A '' is a possible value for fields that `` should '' be ints , and I have been trying to figure out how to `` roll my own '' TypeConversion class to handle this , but have not been able to find examples . Josh 's examples page is conspicuously lacking in this particular area and the closest stackoverflow question I 've been able to find is this one from 2013.Then I found references to the NullValuesAttribute , which seems like exactly what I needed but then could n't figure out how to use it . VisualStudio 's Intellisense was no help either . : ) Ideally I 'd like the `` N/A '' s to convert to 0 ( zero ) . Can someone help ? Before people tell me `` Well , it 's obvious ... '' I should say that this is my first ( literally , aside from tutorials ) C # program and there is also a time factor - or I 'd quite happily explore on my own . [ Update : tried top adapt solution at CsvHelper Parsing boolean from String ] So , taking solution for the above question as a starting point , I did this : My thinking was that specifying the NullValues would get the TypeConverter to convert `` N/A '' into a null ( since there does n't appear to be an Int32 equivalent of the `` BooleanValues '' method.Unfortunately , this still threw an exception : So , looks like I 'm going to have to extend Int32Converter . Yes ? static void Main ( ) { var rows = new List < Job > ( ) ; using ( var reader = new StreamReader ( `` mydatafile.csv '' ) using ( var csv = new CsvReader ( reader ) ) { csv.Configuration.RegisterClassMap < JobMap > ( ) ; while ( csv.Read ( ) ) { var record = new Job { JobId = csv.GetField < int > ( `` Job ID '' ) , ItemCount = csv.GetField < int > ( `` Item Count '' ) } ; rows.Add ( record ) ; } } } public class Job { public int JobId { get ; set ; } public int ItemCount { get ; set ; } } public sealed class JobMap : ClassMap < Job > { Map ( m = > m.JobId ) ; Map ( m = > m.ItemCount ) .TypeConverterOption.NullValues ( `` N/A '' ) ; } CsvHelper.TypeConversion.TypeConverterException : 'The conversion can not be performed.Text : ' N/A'MemberType : TypeConverter : 'CsvHelper.TypeConversion.Int32Converter ''",`` N/A '' as null value of int field "C_sharp : Possible Duplicate : Catching specific vs. generic exceptions in c # Here 's an example method I would like to know what exception clause to use apart from just Exception and if there is an advantage in using more specific catch clauses.Edit : O.k thanks everyone private static void outputDictionaryContentsByDescending ( Dictionary < string , int > list ) { try { //Outputs entire list in descending order foreach ( KeyValuePair < string , int > pair in list.OrderByDescending ( key = > key.Value ) ) { Console.WriteLine ( `` { 0 } , { 1 } '' , pair.Key , pair.Value ) ; } } catch ( Exception e ) { MessageBox.Show ( e.Message , `` Error detected '' , MessageBoxButtons.OK , MessageBoxIcon.Error ) ; } }","C # exception handling , which catch clause to use ?" "C_sharp : I have multiple grids that display data based on a given filter ( in a web application using a REST Api ) . The data structure displayed is always the same ( to simplify the problem ) , but depending on the screen on which the user is , the displayed results are different.In addition , and this is the issue , some results must be disabled so that the user can not select them.Example : A Foo has N Bars . If I want to add a new child ( bar ) to the father ( foo ) , I go to the search screen , but I want the filtered grid shows as disabled children which are already related to the father.Currently I 'm controlling this issue on the server ( database querys ) by doing specifics joins depending on the scenario and `` disabling '' results I do n't want . But this approach causes I can not reuse queries ( due to specifics joins . Maybe I need to search Bars int order relate them with other father Baz , and I want disable Bars that are already related with current father ... ) Another approach could be the following : Save the children ( only ids ) related to the father in an array in memory ( javascript ) In the `` prerender '' grid event ( or similar ) check for each element whether it is contained in the previous array or not ( search by id ) . If so , mark it as disabled ( for example ) .This is a reusable solution in client-side and I can always reuse the same query in server side.Before starting to implement this solution I would like to know if there is any better option.I 'm sure this is a recurring problem and I do n't want to reinvent the wheel.Any strategy or suggestion ? Edit : show example : Assuming this model : I have two different screens : one showing items belongs to one category and another showing items belongs to one sales promotion . In each screen I can search for items and add them to the Category or SalesPromotion . But when I 'm searching items , I want items that already belongs to Category/SalesPromotion to show as disabled ( or not shown , for simplicity in this example ) .I can do this in server , doing queries like these : You can imagine what happens if I had more and more scenarios like these ( with more complex model and queries of course ) .One alternative could be : Store items that already belongs to current Category/SalesPromotion in memory ( javascript , clientside ) .On grid prerender event ( or equivalent ) in clientside determine what items must be disabled ( by searching each row in stored items ) .So , my question is wheter this approach is a good solution or is there a well-known solution for this issue ( I think so ) . Category N : M ItemSalesPromotion N : M Item -- Query for search Items in Category screenSELECT * FROM ITEMS iLEFT JOIN ItemsCategories ic on ic.ItemId = i.ItemIdWHERE ic.CategoryId IS NULL OR ic.CategoryId < > @ CurrentCategoryId -- Query for search Items in SalesPromotion screenSELECT * FROM ITEMS iLEFT JOIN ItemsSalesPromotions isp on isp.ItemId= i.ItemIdWHERE isp.PromotionId IS NULL OR isp.PromotionId < > @ CurrentPromotionId",How to disable elements in a grid "C_sharp : I 'm working on adding logging to a project using Windsor Logging Facility and the NLog integration.Rather than following the Windsor documentation 's recommended practice of adding a Log property to every class for which I want to support logging , I 've decided to try to go the route of using dynamic interception to do it . So far the interceptor 's fairly basic ; it just uses constructor injection to get an instance of ILogger : Beyond that , all I 've done is the minimum for registering the interceptor and applying it to a component , and the logging facility takes care of the rest.So far so good - sort of . The logger I get follows NLog 's recommended practice of one logger per class . I do n't think that 's a very good choice in this case . It means that every single message is going to a log named `` MyApplication.Interceptors.LoggingInterceptor '' , which is n't terribly useful.I 'd prefer to have logs named after the abstraction the logger has been applied to . For example , if the logger has been applied to an implementation of IEmployeeRepository then the log should be named EmployeeRepository . Is this doable ? Edit : I 've tried implementing a custom ILoggerFactory and instructing the container to use it instead . However I quickly hit a roadblock : When Windsor calls into the factory , the only information supplied is the type of the object for which the logger is being acquired . No other information about the object is supplied , so the ILoggerFactory has no way of finding out about the abstraction the interceptor has been applied to.I notice that there are two overloads of ILoggerFactory.Create ( ) that accept strings as arguments . Windsor does n't seem to be using either of them directly , but one would assume that they have to be there for a reason . Is there anything in the fluent registration API that can be used to specify that a particular string be used ? class LoggingInterceptor : IInterceptor { private readonly ILogger _logger ; public LoggingInterceptor ( ILogger logger ) { if ( logger == null ) throw new ArgumentNullException ( `` logger '' ) ; _logger = logger ; } public void Intercept ( IInvocation invocation ) { // just a placeholder implementation , I 'm not actually planning to do this ; ) _logger.Info ( invocation.Method.Name ) ; invocation.Proceed ( ) ; } } container.Register ( Component.For < LoggingInterceptor > ( ) .LifeStyle.Transient ) ; container.Register ( Component.For < IEmployeeRepository > ( ) .ImplementedBy < EmployeeRepository > ( ) .Interceptors ( InterceptorReference.ForType < LoggingInterceptor > ( ) ) .First ) ;",Windsor Logging Facility : Control log name "C_sharp : I 've read the advice many times from people smarter than me , and it has few caveats : Always use ConfigureAwait ( false ) inside library code . So I 'm fairly certain I know the the answer , but I want to be 100 % . The scenario is I have a library that thinly wraps some other asynchronous library.Library code : Application code : public async Task DoThingAsyc ( ) { // do some setup return await otherLib.DoThingAsync ( ) .ConfigureAwait ( false ) ; } // need to preserve my synchronization contextawait myLib.DoThingAync ( ) ; // do I have my context here or did my lib lose it ?",Can ConfigureAwait ( false ) in a library lose the synchronization context for the calling application ? C_sharp : I want to do something like < DataTrigger Binding= '' { Binding Something } '' ValueIsNot= '' { x : Null } '' >,What 's the easiest way to do negation in triggers ? "C_sharp : I have a MediatR pipeline behavior like this : And MediatR commands like this : The validators are registered on Startup.cs like this : This works nice for the MyUseCase.Validator , it is injected on the pipeline and is executed , validating the MyUseCase.Command.But it 's a large application , and many commands have common properties , i.e . every order operation receives an OrderId and I have to check if the Id is valid , if the entity exists in database , if the authenticated user is the owner of the order being modified , etc.So I tried to create the following interface and validator : Finally I changed the command to this : The problem is that the IOrderValidator is not injected in the pipeline , only the MyUseCase.Validator is.Am I missing something here or is it even possible to inject multiple validators in the pipeline ? public class FailFastRequestBehavior < TRequest , TResponse > : IPipelineBehavior < TRequest , TResponse > { private readonly IEnumerable < IValidator > _validators ; public FailFastRequestBehavior ( IEnumerable < IValidator < TRequest > > validators ) { _validators = validators ; } public Task < TResponse > Handle ( TRequest request , CancellationToken cancellationToken , RequestHandlerDelegate < TResponse > next ) { var failures = _validators .Select ( async v = > await v.ValidateAsync ( request ) ) .SelectMany ( result = > result.Result.Errors ) .Where ( f = > f ! = null ) ; return failures.Any ( ) ? Errors ( failures ) : next ( ) ; } ... } public class MyUseCase { public class Command : IRequest < CommandResponse > { ... } public class Validator : AbstractValidator < Command > { ... } public class Handler < T > : IRequestHandler < T , CommandResponse > { ... } } AssemblyScanner .FindValidatorsInAssembly ( Assembly.GetAssembly ( typeof ( MyUseCase ) ) ) .ForEach ( result = > services.AddScoped ( result.InterfaceType , result.ValidatorType ) ) ; public interface IOrder { string OrderId { get ; set ; } } public class IOrderValidator : AbstractValidator < IOrder > { public IOrderValidator ( ) { CascadeMode = CascadeMode.StopOnFirstFailure ; RuleFor ( x = > x.OrderId ) .Rule1 ( ) .Rule2 ( ) .Rule3 ( ) .RuleN ( ) } } public class MyUseCase { public class Command : IRequest < CommandResponse > : IOrder { ... } public class Validator : AbstractValidator < Command > { ... } public class Handler < T > : IRequestHandler < T , CommandResponse > { ... } }",Using multiple FluentValidators on MediatR pipeline "C_sharp : In .NET 4.0 , have a built-in delegate method : It is used in LINQ extesion methods , example : I do n't understand clearly about Func delegate , why does the following lambda expression match it : public delegate TResult Func < in T , out TResult > ( T arg ) ; IEnumerable < TSource > Where < TSource > ( this IEnumerable < TSource > source , Func < TSource , bool > predicate ) ; // p is a XElement objectp= > p.Element ( `` firstname '' ) .Value.StartsWith ( `` Q '' )",Please explain about Func delegate in .NET 4.0 "C_sharp : i 'm using Directory.GetFiles to give me mp3 files , and i 'd like to fill a ListBox with the results , but instead of stopping the program while it goes through the method , can i get it to search and fill the ListBox up as it gets the mp3 files ? so what i 'm using is as follows ( and it is failing to add them one at at time , it is adding them all at once when it is done ) i did add _AddMP3ToListbox = AddMP3ToListboxit does indeed add the mp3 's to the listbox , but it does so all at once , not as soon as it finds it . how can i fix this ? private List < string > Getmp3sFromFolders ( string folder ) { List < string > fileArray = new List < string > ( ) ; try { DirectoryInfo dir = new DirectoryInfo ( folder ) ; var files = dir.EnumerateFiles ( `` *.mp3 '' ) ; foreach ( var file in files ) { fileArray.Add ( file.FullName ) ; Dispatcher.BeginInvoke ( _AddMP3ToListbox , file.Name ) ; } var directories = dir.EnumerateDirectories ( ) ; foreach ( var subdir in directories ) { fileArray.AddRange ( Getmp3sFromFolders ( subdir.FullName ) ) ; } // lblFolderSearching.Content = folder.ToString ( ) ; } catch { } return fileArray ; }","directory.GetFiles , how do i get it to spit out items as it finds them ?" "C_sharp : Got some simple codeThis takes ~3 seconds on my core 2 duo . If I change the index in t1 to tmpInt [ 4 ] , it takes ~5.5 seconds.Anyway , the first cache line ends at index 4 . Being that a cache line is 64bytes and 5 int32s are only 20 bytes , that means there are 44 bytes of metadata and/or padding before the actual array.Another set of values that I tested where 5 and 21 . 5 and 21 take ~3 seconds , but 5 and 20 takes ~5.5 seconds , but that 's because index 20 shares the same cache line as index 5 as they 're spaced within the same 64 bytes.So my question is , how much data does .Net reserve before an array and does this amount change between 32bit and 64bit systems ? Thanks : - ) Int32 [ ] tmpInt = new Int32 [ 32 ] ; long lStart = DateTime.Now.Ticks ; Thread t1 = new Thread ( new ThreadStart ( delegate ( ) { for ( Int32 i = 0 ; i < 100000000 ; i++ ) Interlocked.Increment ( ref tmpInt [ 5 ] ) ; } ) ) ; Thread t2 = new Thread ( new ThreadStart ( delegate ( ) { for ( Int32 i = 0 ; i < 100000000 ; i++ ) Interlocked.Increment ( ref tmpInt [ 20 ] ) ; } ) ) ; t1.Start ( ) ; t2.Start ( ) ; t1.Join ( ) ; t2.Join ( ) ; Console.WriteLine ( ( ( DateTime.Now.Ticks - lStart ) /10000 ) .ToString ( ) ) ;",Array meta data question ( cache lines ) "C_sharp : I want to use LogicalThreadContext to pass some context information in my WCF service . I need to pass different properties . In C # I has codeIn log4net config I have And in log I gotI do n't want to have system properties log4net : Identity , log4net : UserName and log4net : HostName in log . How to do this ? I can write config like this But I have several properties in code and I want to see only properties that I added . Codedoes n't work . LogicalThreadContext.Properties [ `` MyProperty '' ] = 1 ; < log4net > < appender name= '' RollingLogFileAppenderSize '' type= '' log4net.Appender.RollingFileAppender '' > < file value= '' Logs\Log.log '' / > < lockingModel type= '' log4net.Appender.FileAppender+MinimalLock '' / > < appendToFile value= '' true '' / > < rollingStyle value= '' Composite '' / > < datePattern value= '' yyyyMMdd '' / > < maxSizeRollBackups value= '' 3 '' / > < maximumFileSize value= '' 5MB '' / > < layout type= '' log4net.Layout.PatternLayout '' > < conversionPattern value= '' % d [ % 2t ] [ % property ] % level % m % n '' / > < /layout > < /appender > < root > < level value= '' INFO '' / > < appender-ref ref= '' RollingLogFileAppenderSize '' / > < /root > < /log4net > 2015-11-03 16:24:36,313 [ 10 ] [ { MyProperty=1 , log4net : Identity= , log4net : UserName=User , log4net : HostName=User } ] INFO - Info conversionPattern value= '' % d [ % 2t ] [ % property { MyProperty } ] % level % m % n '' LogicalThreadContext.Properties.Remove ( `` log4net : UserName '' ) ;",Remove log4net system properties from output "C_sharp : I 've got code like this that 's executed from many threads simultaneously ( over shared a and b objects of type Dictionary < int , double > ) : The dictionaries do n't change during the lifetime of the threads . Is this safe ? So far , it seems OK , but I wanted to be sure . foreach ( var key in a.Keys.Union ( b.Keys ) ) { dist += Math.Pow ( b [ key ] - a [ key ] , 2 ) ; }",Is it safe to iterate over an unchanging dictionary from multiple threads ? "C_sharp : In this scenario , system A needs to send a message to system B . The following code shows a sample of how this was accomplished : For reasons out of scope of this question we decided to switch from Wcf to using raw http streams , but we needed both side by side to gather metrics and test it out . So I created a new IExecutionStrategy implementation to handle this : Essentially , the only way I could get this to be asynchronous was to wrap it in a Task.Run ( ) so the web request was none blocking . ( Note : due to unique stream manipulation requirements on both sending and receiving it is not straight forward to implement this is in HttpClient , and even if it 's possible this fact is out of scope for this question ) .We thought this was fine until we read Stephen Cleary 's multiple blog posts about how Task.Run ( ) is bad , both in library code and in Asp.Net applications . This makes perfect sense to me.What does n't make sense is how you actually implement a naturally asynchronous call if the third party library does not support an asynchronous movement . For example , if you were to use HttpClient.GetStreamAsync ( ) what does that do that makes it better for asynchronous operations than Task.Run ( ( ) = > HttpClient.GetStream ( ) ) , and is there any way to remedy this for non-async third party libraries ? public interface IExecutionStrategy { Task < Result > ExecuteMessage ( Message message ) ; } public class WcfExecutionStrategy { public async Task < Result > ExecuteMessage ( Message message ) { using ( var client = new Client ( ) ) { return await client.RunMessageOnServer ( message ) ; } } } public class MessageExecutor { private readonly IExecutionStrategy _strategy ; public MessageExecutor ( IExecutionStrategy strategy ) { _strategy = strategy ; } public Task < Result > ExecuteMessage ( Message msg ) { // ... . // Do some common checks and code here // ... . var result = await _strategy.ExecuteMessage ( msg ) ; // ... . // Do some common cleanup and logging here // ... .. return result ; } } public class HttpclientExecutionStrategy { public async Task < Result > ExecuteMessage ( Message message ) { var request = CreateWebRequestmessage var responseStream = await Task.Run ( ( ) = > { var webResponse = ( HttpWebResponse ) webRequest.GetResponse ( ) ; return webResponse.GetResponseStream ( ) ; } return MessageStreamer.ReadResultFromStream ( responseStream ) ; } }",How do I create a naturally asynchronous method when inside calls are not naturally asynchronous ? "C_sharp : I 've been involved with building an internal-use application through which users may upload files , to be stored within Google Drive . As it is recommended not to use service accounts as file owners , I wanted to have the application upload on behalf of a designated user account , to which the company sysadmin has access.I have created the application , along with a service account . There are two keys created for the service account , as I have tried both the JSON and PKCS12 formats trying to achieve this : I have downloaded the OAuth 2.0 client ID details , and also have the .json and .p12 files for the service account keys ( in that order as displayed above ) : I had my sysadmin go through the steps detailed here to delegate authority for Drive API access to the service account : https : //developers.google.com/drive/v2/web/delegation # delegate_domain-wide_authority_to_your_service_accountWe found that the only thing that worked for the `` Client name '' in step 4 was the `` Client ID '' listed for the Web application ( ending .apps.googleusercontent.com ) . The long hexadecimal IDs listed for the Service account keys were not what it required ( see below ) : Previously to the above , I had code which would create a DriveService instance that could upload directly to the service account , referencing the .json file for the service account keys : That works for listing and uploading , though of course there 's no web UI for access to the files , and it seems as though it does n't handle things like permissions metadata or generation of thumbnails for e.g . PDFs . This is why I 'm trying to use a standard account for the uploads.Once the delegation was apparently sorted , I then attempted to adapt the code shown in the delegation reference linked above , combining with code from elsewhere for extracting the necessary details from the .json key file . With this code , as soon as I try to execute any API command , even as simple as : I receive an error : Exception Details : Google.Apis.Auth.OAuth2.Responses.TokenResponseException : Error : '' unauthorized_client '' , Description : '' Unauthorized client or scope in request . `` , Uri : '' '' The code for that effort is : Finally , I created the second service account key to save a .p12 file in order to more closely match the code in the authority delegation documentation , but which results in the same exception : The minimial relevant class where this method lives is : And that 's used in this fashion : The exception occurs on that last line.I do not understand why my service account can not act on behalf of the designated user , which is part of the domain for which the application 's service account should have delegated authority . What is it that I 've misunderstood here ? private DriveService GetServiceA ( ) { var settings = SettingsProvider.GetInstance ( ) ; string keyFilePath = HostingEnvironment.MapPath ( `` ~/App_Data/keyfile.json '' ) ; var scopes = new string [ ] { DriveService.Scope.Drive } ; var stream = new IO.FileStream ( keyFilePath , IO.FileMode.Open , IO.FileAccess.Read ) ; var credential = GoogleCredential.FromStream ( stream ) ; credential = credential.CreateScoped ( scopes ) ; var service = new DriveService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = `` MyAppName '' } ) ; return service ; } FileList fileList = service.FileList ( ) .Execute ( ) ; private DriveService GetServiceB ( ) { var settings = SettingsProvider.GetInstance ( ) ; string keyFilePath = HostingEnvironment.MapPath ( `` ~/App_Data/keyfile.json '' ) ; string serviceAccountEmail = `` < account-email > @ < project-id > .iam.gserviceaccount.com '' ; var scopes = new string [ ] { DriveService.Scope.Drive } ; var stream = new IO.FileStream ( keyFilePath , IO.FileMode.Open , IO.FileAccess.Read ) ; var reader = new IO.StreamReader ( stream ) ; string jsonCreds = reader.ReadToEnd ( ) ; var o = JObject.Parse ( jsonCreds ) ; string privateKey = o [ `` private_key '' ] .ToString ( ) ; var credential = new ServiceAccountCredential ( new ServiceAccountCredential.Initializer ( serviceAccountEmail ) { Scopes = scopes , User = `` designated.user @ sameappsdomain.com '' } .FromPrivateKey ( privateKey ) ) ; var service = new DriveService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = `` MyAppName '' } ) ; return service ; } private DriveService GetServiceC ( ) { var settings = SettingsProvider.GetInstance ( ) ; string p12KeyFilePath = HostingEnvironment.MapPath ( `` ~/App_Data/keyfile.p12 '' ) ; string serviceAccountEmail = `` < account-email > @ < project-id > .iam.gserviceaccount.com '' ; var scopes = new string [ ] { DriveService.Scope.Drive } ; // Full access X509Certificate2 certificate = new X509Certificate2 ( p12KeyFilePath , `` notasecret '' , X509KeyStorageFlags.Exportable ) ; var credential = new ServiceAccountCredential ( new ServiceAccountCredential.Initializer ( serviceAccountEmail ) { Scopes = scopes , User = `` designated.user @ sameappsdomain.com '' } .FromCertificate ( certificate ) ) ; var service = new DriveService ( new BaseClientService.Initializer ( ) { HttpClientInitializer = credential , ApplicationName = `` MyAppName '' } ) ; return service ; } public class GoogleDrive { public DriveService Service { get ; private set ; } public GoogleDrive ( ) { this.Service = this.GetService ( ) ; } private DriveService GetService ( ) { // Code from either A , B or C } public FilesResource.ListRequest FileList ( ) { return this.Service.Files.List ( ) ; } } var service = new GoogleDrive ( ) ; FilesResource.ListRequest listRequest = service.FileList ( ) ; FileList fileList = listRequest.Execute ( ) ;",Failure of delegation of Google Drive access to a service account "C_sharp : I have a terrible feeling this may reduce itself to a dummy-on-me , forest-for-trees situation , and if that 's the case , mea culpa in advance . But for the life of me I 'm just not understanding why the following line will not compile in C # , assuming myRegEx is a RegEx object and myString is the target for a call to the Match method , as follows : The .Captures reference should get me to the CaptureCollection , which implements IEnumerable , and IEnumerable offers an extension method Select for a transform as I 've attempted here , snagging the Value property for each item in the collection and pushing it into a string array . However , the compiler barks at me with 'System.Text.RegularExpressions.CaptureCollection does not contain a definition for 'Select ' and no extension method 'Select ' accepting a first argument of type System.Text.RegularExpression.CaptureCollection ' could be found.I can overcome this by calling the .Cast < Capture > ( ) method from the Captures object , and then call select with a transform that , in turn , accesses the Value property , but that seems a little silly considering the objects already are Capture objects.What am I doing wrong ? Many thanks in advance for pointing out what must be a painfully obvious oversight on my part . String [ ] results = myRegEx.Matches ( myString ) [ 0 ] .Groups [ `` Group1 '' ] .Captures.Select ( x = > x.Value ) .ToArray < String > ( ) ;",Why can I not call Select ( ) from a CaptureCollection object ? "C_sharp : I have a class that has a property which is a List , I will name this class A . Then I have a List < A > .I need a LINQ for objects to get all the objects B that are present on ALL the items on the List < A > .Example to clarify : The query must return the objects B3 and B4 because are the only ones contained on all the List < A > objects . var list = new List < A > { new A { B = new List < B > { B1 , B2 , B3 , B4 } } new A { B = new List < B > { B3 , B4 , B5 , B6 } } new A { B = new List < B > { B2 , B3 , B4 , B5 , B6 } } } ;",Linq query to get shared items in a sublist "C_sharp : I am writing a library , and I have a method which takes in a Dictionary . The value of the dictionary is untrusted/insecure , but the key is trusted and if an end-user were given the ability to enter an arbitrary key name then `` bad things '' could happen . So when other developers use this library function , I want to force them to know the key name at compile time . So something like this would be allowed : Because `` MyKey '' is a string literal , known at compile time . But something like this would either raise a compile or runtime exception : Because user input was used for the key ( userKey ) and thus it was unknown at compile time . I 've looked in GetType ( ) and there is nothing that really distinguishes between a literal string and a string created at runtime . string userInput = Console.ReadLine ( ) ; Dictionary < string , string > something = new Dictionary < string , string > ( ) ; something.Add ( `` MyKey '' , userInput ) ; string userInput = Console.ReadLine ( ) ; string userKey = Console.ReadLine ( ) ; Dictionary < string , string > something = new Dictionary < string , string > ( ) ; something.Add ( userKey , userInput ) ;",Check if a string is a literal string known at compile time ? "C_sharp : So I was taking an online test where i had to implement a piece of code to simply check if the value was in the array . I wrote the following code : Now i did n't see any problems here because the code works fine but somehow i still failed the test because this is `` not fast enough '' once the array contains a million values.The only code i wrote myself is : The other code i was given to work with.Is there a way to speed up this process ? Thanks in advance.EDIT : I came across a page where someone apparently took the same test as i took and it seems to come down to saving CPU cycles.Reference : How to save CPU cycles when searching for a value in a sorted list ? Now his solution within the method is : Now i see how this code works but it 's not clear to me why this is supposed to be faster . Would be nice if someone could elaborate . using System ; using System.IO ; using System.Linq ; public class Check { public static bool ExistsInArray ( int [ ] ints , int val ) { if ( ints.Contains ( val ) ) return true ; else return false ; } } if ( ints.Contains ( val ) ) return true ; else return false ; var lower = 0 ; var upper = ints.Length - 1 ; if ( k < ints [ lower ] || k > ints [ upper ] ) return false ; if ( k == ints [ lower ] ) return true ; if ( k == ints [ upper ] ) return true ; do { var middle = lower + ( upper - lower ) / 2 ; if ( ints [ middle ] == k ) return true ; if ( lower == upper ) return false ; if ( k < ints [ middle ] ) upper = Math.Max ( lower , middle - 1 ) ; else lower = Math.Min ( upper , middle + 1 ) ; } while ( true ) ;",How to speed up the process of looping a million values array ? "C_sharp : I created a project on Visual Studio Code on Mac and wanted to set my default page . I wrote the code on the `` Startup.cs '' , but it 's not working . When I run the project and open the browser it shows that is not finding the controller.Follow the Startup.cs code : using System ; using System.Collections.Generic ; using System.Linq ; using System.Threading.Tasks ; using Microsoft.AspNetCore.Builder ; using Microsoft.AspNetCore.Hosting ; using Microsoft.Extensions.Configuration ; using Microsoft.Extensions.DependencyInjection ; namespace ProblemsV4 { public class Startup { public Startup ( IConfiguration configuration ) { Configuration = configuration ; } public IConfiguration Configuration { get ; } // This method gets called by the runtime . Use this method to add services to the container . public void ConfigureServices ( IServiceCollection services ) { services.AddMvc ( ) ; } // This method gets called by the runtime . Use this method to configure the HTTP request pipeline . public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; } else { app.UseExceptionHandler ( `` /Home/Error '' ) ; } app.UseStaticFiles ( ) ; app.UseMvc ( routes = > { routes.MapRoute ( name : `` default '' , template : `` { controller=Problem } / { action=Index } '' ) ; } ) ; } } }",How to define initial url on web api project ? "C_sharp : I have Viewport3D in the Window . it will change the size when the window size changed . Now I want the image show on like it 's the original 2d window ( look like nothing changed , but actually the image is 3d ) . But problem is If I want it looking same as the same as WPF original look at , I must change some Camera settings , like PerspectiveCamera.Position or MeshGeometry3D.Position . because the Viewport3D will change the size dynamically when the window change size , I must dynamically calculate the Viewport3D settings . Is there anyway to do ? I 've already tried this , but ca n't calculate correctly : WPF 3D : Fitting entire image to view with PerspectiveCamera < Window > < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' 100 '' / > < RowDefinition/ > < Grid.RowDefinitions > < Label Grid.Row= '' 0 '' Content= '' top label '' / > < Viewport3D Grid.Row= '' 1 '' x : Name= '' vp3D '' > < Viewport3D.Camera > < PerspectiveCamera x : Name= '' pCamera '' LookDirection= '' 0 0 -1 '' UpDirection= '' 0 1 0 '' / > < /Viewport3D.Camera > < Viewport2DVisual3D x : Name= '' v2dv3d '' > < Viewport2DVisual3D.Geometry > < MeshGeometry3D x : Name= '' mg3d '' TextureCoordinates= '' 0,0 0,1 1,1 1,0 '' TriangleIndices= '' 0 1 2 0 2 3 '' / > < /Viewport2DVisual3D.Geometry > < Viewport2DVisual3D.Material > < DiffuseMaterial Viewport2DVisual3D.IsVisualHostMaterial= '' True '' Brush= '' White '' / > < /Viewport2DVisual3D.Material > < Image Height= '' { Binding ElementName=vp3D , Path=ActualHeight } '' Width= '' { Binding ElementName=vp3D , Path=ActualWidth } '' Stretch= '' Fill '' / > < /Viewport2DVisual3D > < ModelVisual3D > < ModelVisual3D.Content > < DirectionalLight Color= '' # FFFFFFFF '' Direction= '' 0,0 , -1 '' / > < /ModelVisual3D.Content > < /ModelVisual3D > < /Viewport3D > < /Grid > < /Window",How do I calculate WPF all camera setting dynamically in the code ? "C_sharp : In my code I frequently have the sequences like : In Python , I can write it asIs there a compact way to write it in C # ? List < type1 > list1 = ... ; List < type2 > list2 = new List < type2 > ( ) ; foreach ( type1 l1 in list1 ) { list2.Add ( myTransformFunc ( l1 ) ) ; } list2 = [ myTransformFunc ( l1 ) for l1 in list1 ]",How to do lists comprehension ( compact way to transform a list into another list ) in c # ? C_sharp : Is there any difference in following two lines of code that compares the string values.and in the first line I am calling the equals method on string variable to compare it with string literal . The second line is vice versa . Is it just the difference of coding style or there is a difference in the way these two statements are processed by the compiler . string str = `` abc '' ; if ( str.Equals ( `` abc '' ) ) if ( `` abc '' .Equals ( str ) ),What is the difference in string.Equals ( `` string '' ) and `` String '' .Equals ( string ) ? "C_sharp : The current documentation says : Defines if closing for non closed nodes must be done at the end or directly in the document . Setting this to true can actually change how browsers render the page . Default is false.Sorry , I have to admit I do not understand this paragraph . Specifically `` at the end '' of what ? And what does `` in the document '' mean exactly ? The phrase before the last one sounds ominous . If the option is set to true and if the html is formatted properly is this still going to affect the document ? I looked in the source code but I did not understand what 's happening - the code reacts to the property not being set to true . See HtmlNode.cs , and search for OptionAutoCloseOnEnd - line 1707 . I also found some funky code in HtmlWeb.cs at lines 1113 and 1154 . Too bad the source code browser does n't show line numbers but search for OptionAutoCloseOnEnd in the page . Could you please illustrate with an example what this option does ? I am using the HtmlAgilityPack to fix some bad html and to export the page content to xml.I came across some badly formatted html - overlapping tags . Here is the snippet : Note that the first p tag is not closed and note the overlapping STRONG tag.If I set OptionAutoCloseOnEnd this gets somehow fixed . I am trying to understand what exactly is the effect of setting this property to true in general in the structure of the document.Here is the C # code that I am using : Thank you ! < p > Blah bah < P > < STRONG > Some Text < /STRONG > < STRONG > < /p > < UL > < LI > < /STRONG > Item 1. < /LI > < LI > Item 2 < /LI > < LI > Item 3 < /LI > < /UL > HtmlDocument doc = new HtmlDocument ( ) ; doc.OptionOutputAsXml = true ; doc.OptionFixNestedTags = true ; // doc.OptionAutoCloseOnEnd = true ; doc.LoadHtml ( htmlText ) ;",HtmlAgilityPack : Could someone please explain exactly what is the effect of setting the HtmlDocument OptionAutoCloseOnEnd to true ? "C_sharp : what 's expected in this case , is that if the user cancels the task by hitting enter , the other task hooked by ContinueWith will run , but it 's not the case , as per an AggregateException keeps thrown despite the explicit handling in the ContinueWith which is apparently not being executed.any clarification on the below please ? class Program { static void Main ( string [ ] args ) { CancellationTokenSource tokensource = new CancellationTokenSource ( ) ; CancellationToken token = tokensource.Token ; Task task = Task.Run ( ( ) = > { while ( ! token.IsCancellationRequested ) { Console.Write ( `` * '' ) ; Thread.Sleep ( 1000 ) ; } } , token ) .ContinueWith ( ( t ) = > { t.Exception.Handle ( ( e ) = > true ) ; Console.WriteLine ( `` You have canceled the task '' ) ; } , TaskContinuationOptions.OnlyOnCanceled ) ; Console.WriteLine ( `` Press any key to cancel '' ) ; Console.ReadLine ( ) ; tokensource.Cancel ( ) ; task.Wait ( ) ; } }",CancellationTokenSource not behaving as expected "C_sharp : I have a class , Container < T > , which has a ContainerContents < T > . The Container actually takes two type constraint parameters Container < TContainer , TContents > - TContainer being the type of the container , and TContents being the type of contents it accepts . I want to ensure that if TContainer is X or derived from X , then TContents will also be X or derived from X , but that TContents does not have to equal TContainer.I 'm trying to express the following kinds of things.Things that can be carried around ( Swag ) , like a pencil.Things that can not be carried ( BaseObject ) , like a tree.Things that can hold other things ( Container ) Containers that can not be carried , like a bank vault.Carriable Containers ( like a backpack ) .If a container can be carried , then its contents must be carriable too . But , just because the Container is a backpack does n't mean it can only carry backpacks.I want to be able to code : var ringWorld = new Container < BigRing , CivicWork > ( ) ; var pickleKnox = new Container < BankVault , Pickle > ( ) ; var swagBag = new Container < ToteBag , Swag > ( ) ; var tomeBag = new Container < ToteBag , Book > ( ) ; but not var treeBag = new Container < Bag , Tree > ( ) ; Here 's my skeletal setup . public abstract class BaseObject { private readonly string _name ; protected BaseObject ( string name ) { _name = name ; } public string Name { get { return _name ; } } } public class Swag : BaseObject { private readonly int _weight ; public Swag ( string name , int weight ) : base ( name ) { _weight = weight ; } public int Weight { get { return _weight ; } } } /* I like the flexibility of i.e . : Container < BankVault , Pickles > but if the container itself is carriable ( Swag ) , then its contents are by nature also carriable . */public class Container < TContainer , TContents > : BaseObject where TContainer : BaseObject where TContents : BaseObject , or Swag if TContainer : ( Swag or derived from Swag ) { ContainerContents < TContents > _contents ; public Container ( string name , int maxItems ) : base ( name ) { /* if ( TContainer is derived from Swag ) { TContents must be too } */ _contents = new ContainerContents < TContents > ( maxItems ) ; } } public class ContainerContents < T > : List < T > where T : BaseObject { int _maxItems ; public ContainerContents ( int maxItems ) { _maxItems = maxItems ; } }",Conditional type constraint parameter "C_sharp : If I have an interface : And an implementing class : Is DoSomething a candidate for inlining ? I 'd expect `` no '' because if it 's an interface then the object may be cast as a IMyInterface , so the actual method being called is unknown . But then the fact that it 's not marked as virtual implies it may not be on the vtable , so if the object is cast as MyClass , then maybe it could be inlined ? interface IMyInterface { void DoSomething ( ) ; } class MyClass : IMyInterface { public void DoSomething ( ) { } }",Will C # inline methods that are declared in interfaces ? "C_sharp : I recently started working with Data Flow Analysis APIs provided by Roslyn and find values presented in WrittenInside field and Locations field a bit ambiguous.Consider below code snippet in Main methodIf I perform DFA on for loop node , resulting Data Flow Analysis object never shows lcolSample [ ] in WrittenInside field as symbol that is written inside for loop . Reason being it is declared outside the node on which Dataflow analysis is performed . But , ReadInside field shows this symbol . Is there any way to know all the symbols that are modified/written inside a given node even though they are declared outside the node on which DFA is performed ? Variable lintCount1 is written twice ( statement 2 and 7 ) and read twice . Locations property on lintCount1 shows only the place where it is declared ( statement 2 ) . Is there a way to find all the locations in which lintCount1 is written ? Find all references of that symbol would give all the locations where the symbol is used , but I require the locations where it is written but not read.This is my first question on this forum . Please ask for any other details if information provided above is not sufficient . Thanks in advance.. 1. int [ ] lcolSample = new int [ 10 ] { 0 , 1 , 2 , 3 , 4 , 0 , 1 , 2 , 3 , 4 } ; 2. for ( int lintCount1 = 0 ; lintCount1 < 10 ; lintCount1++ ) 3 . { 4 . Prog1 ( lintCount1 ) ; 5. int [ ] lcolSample1 = new int [ 10 ] { 0 , 1 , 2 , 3 , 4 , 0 , 1 , 2 , 3 , 4 } ; 6. lintCount3 = lintCount3 + 100 ; 7. lintCount1 = lintCount1 + 2 ; 8. lcolSample [ lintCount1-1 ] = lcolSample1 [ lintCount1 ] + 100 ; 9 . }",Roslyn Data flow analysis - ambiguous values for WrittenInside and Locations fields "C_sharp : I 'm currently working on a project , where I have to manage an application via a wcf client . The problem I 'm facing is that after making a call to the server I need the client to wait for the callback to be made . Here is the scenario : I make a call to the service which shows a window and then the server app is idle . When i click a button on the window , it makes a callback to the client . during the time , the client UI has to be disabled - it has to wait for the callback . Could you please tell me how I can achieve this ? Does it have something to do with Concurrency Mode or the Operation Contract attribute ? This is my code for the ServiceContract and the CallbackContract : [ ServiceContract ( CallbackContract = typeof ( IWCFServiceCallback ) ) ] public interface IWCFService { [ OperationContract ] void OpenWindow ( ) ; } public interface IWCFServiceCallback { [ OperationContract ( IsOneWay = true ) ] void ReturnValue ( object [ ] value ) ; }",Make wcf client wait for the callback "C_sharp : I have a text file that looks like this : I need to be able to find the balance for a client on a given date.I 'm wondering if I should : A . Start from the end and read each line into an Array , one at a time . Check the last name index to see if it is the client we 're looking for . Then , display the balance index of the first match.orB . Use RegEx to find a match and display it . I do n't have much experience with RegEx , but I 'll learn it if it 's a no brainer in a situation like this . 1 , Smith , 249.24 , 6/10/20102 , Johnson , 1332.23 , 6/11/20103 , Woods , 2214.22 , 6/11/20101 , Smith , 219.24 , 6/11/2010",Parsing a CSV formatted text file "C_sharp : When I was looking at String.Join method implementation , I saw a for loop like this : Here , second if statement seems redundant to me.I thought if values [ index ] ! = null is true then how could be values [ index ] .ToString ( ) == null true ? As far as I know ToString always has to be return something , right ? Even if the type does n't override ToString method it should return Type 's fully qualified name ( Namespace + Class name ) .So when I see it in .NET Framework source code , I thought maybe there is a reason and I 'm missing something.If there is a reason , what is it ? public static string Join ( string separator , params object [ ] values ) { ... for ( int index = 1 ; index < values.Length ; ++index ) { sb.Append ( separator ) ; if ( values [ index ] ! = null ) // first if statement { string str2 = values [ index ] .ToString ( ) ; if ( str2 ! = null ) // second if statement sb.Append ( str2 ) ; } } ... }",Is this if statement redundant or not ? "C_sharp : I 'm really confused by the various configuration options for .Net configuration of dll 's , ASP.net websites etc in .Net v2 - especially when considering the impact of a config file at the UI / end-user end of the chain.So , for example , some of the applications I work with use settings which we access with : Now , this option seems cool because the members are stongly typed , and I wo n't be able to type in a property name that does n't exist in the Visual Studio 2005 IDE . We end up with lines like this in the App.Config of a command-line executable project : ( If we do n't have the second setting , someone releasing a debug dll to the live box could have built with the debug connection string embedded in it - eek ) We also have settings accessed like this : Now , these seem cool because we can access the setting from the dll code , or the exe / aspx code , and all we need in the Web or App.config is : However , the value of course may not be set in the config files , or the string name may be mistyped , and so we have a different set of problems.So ... if my understanding is correct , the former methods give strong typing but bad sharing of values between the dll and other projects . The latter provides better sharing , but weaker typing.I feel like I must be missing something . For the moment , I 'm not even concerned with the application being able to write-back values to the configuration files , encryption or anything like that . Also , I had decided that the best way to store any non-connection strings was in the DB ... and then the very next thing that I have to do is store phone numbers to text people in case of DB connection issues , so they must be stored outside the DB ! string blah = AppLib.Properties.Settings.Default.TemplatePath ; < connectionStrings > < add name= '' AppConnectionString '' connectionString= '' XXXX '' / > < add name= '' AppLib.Properties.Settings.AppConnectionString '' connectionString= '' XXXX '' / > < /connectionStrings > string blah = System.Configuration.ConfigurationManager.AppSettings [ `` TemplatePath_PDF '' ] ; < appSettings > < add key= '' TemplatePath_PDF '' value= '' xxx '' / > < /appSettings >",Understanding .Net Configuration Options "C_sharp : I am trying to capture the output from tail in follow mode , where it outputs the text as it detects changes in the file length - particularly useful for following log files as lines are added . For some reason , my call to StandardOutput.Read ( ) is blocking until tail.exe exits completely.Relevant code sample : I have also tried using the support for the OutputDataReceived event handler which exhibits the same blocking behavior : I do have a little bit more code around the call to StandardOutput.Read ( ) , but this simplifies the example and still exhibits the undesirable blocking behavior . Is there something else I can do to allow my code to react to the availability of data in the StandardOutput stream prior to the child application exiting ? Is this just perhaps a quirk of how tail.exe runs ? I am using version 2.0 compiled as part of the UnxUtils package.Update : this does appear to be at least partially related to quirks in tail.exe . I grabbed the binary from the GnuWin32 project as part of the CoreUtils package and the version bumped up to 5.3.0 . If I use the -f option to follow without retries , I get the dreaded `` bad file descriptor '' issue on STDERR ( easy to ignore ) and the process terminates immediately . If I use the -F option to include retries it seems to work properly after the bad file descriptor message has come by and it attempts to open the file a second time.Is there perhaps a more recent win32 build from the coreutils git repository I could try ? var p = new Process ( ) { StartInfo = new ProcessStartInfo ( `` tail.exe '' ) { UseShellExecute = false , RedirectStandardOutput = true , Arguments = `` -f c : \\test.log '' } } ; p.Start ( ) ; // the following thread blocks until the process exitsTask.Factory.StartNew ( ( ) = > p.StandardOutput.Read ( ) ) ; // main thread wait until child process exitsp.WaitForExit ( ) ; p.OutputDataReceived += ( proc , data ) = > { if ( data ! = null & & data.Data ! = null ) { Console.WriteLine ( data.Data ) ; } } ; p.BeginOutputReadLine ( ) ;",Capturing standard out from tail -f `` follow '' "C_sharp : I have a simple linq query where I need to filter stores within a certain distance and also order by the distance calculation result , you get the idea.So , I ended up calling GetDistance method twice for now . How can I optimize code to call it only once per store ? double distance = 50 ; var result = stores.Where < MyStore > ( s = > Helper.GetDistance ( lat , lon , s.Lat , s.Lon ) < = distance ) .OrderBy ( s = > Helper.GetDistance ( lat , lon , s.Lat , s.Lon ) ) .ToList ( ) ;",Linq : calling the same method for Where and OrderBy only once instead of twice ? C_sharp : I have a class named A . What the difference between these two statements ? A a = new A ( ) ; A a = default ( A ) ;,what 's the difference between the default and default constructor "C_sharp : I have a class and it has 11 properties ( most are inherited ) . I do n't quite like passing in 11 parameters . I know I could create a ModelBuilder class and do the following : new ModelBuilder ( ) .WithProp1 ( prop1 ) .WithProp2 ( prop2 ) .Build ( ) ; But I was thinking of only one method generic enough to accept a Func which you can then specify the prop to assign : Usage : This seems to work . My question : is there anything I 'm missing here in terms of implementation ( barring the obvious - dragging this method to an interface or helper class ) ? Are there any gotchas that may surface with this implementation that I am overlooking ? public Car With < TOut > ( Func < Car , TOut > lambda ) { lambda.Invoke ( this ) ; return this ; } var car = new Car ( ) .With ( x = > x.VehicleType = `` Sedan '' ) .With ( x = > x.Wheels = 4 ) .With ( x = > x.Colour = `` Pink '' ) .With ( x = > x.Model = `` fancyModelName '' ) .With ( x = > x.Year = `` 2007 '' ) .With ( x = > x.Engine = `` Large '' ) .With ( x = > x.WeightKg = 2105 ) .With ( x = > x.InvoiceNumber = `` 1234564 '' ) .With ( x = > x.ServicePlanActive = true ) .With ( x = > x.PassedQA = false ) .With ( x = > x.Vin = `` blabla '' ) ;",C # Lambda Builder Pattern "C_sharp : I am just reading the Microsoft REST API Guidlines ( https : //github.com/Microsoft/api-guidelines/blob/master/Guidelines.md ) and there are query parameters described beginning with a dollar sign , e.g . $ orderBy . 9.6 Sorting collections The results of a collection query MAY be sorted based on property values . The property is determined by the value of the $ orderBy query parameter.Now if I try to define a method parameter like $ orderBy in an action method then it is not syntactically correct ( $ orderBy is not a valid identifier ) .How can I access a query parameter beginning with a dollar sign in an action method of ASP.NET Core ? public class ExampleController : Controller { // this is syntactically not correct public IActionResult Collection ( ... . , string $ orderBy = null ) { ... } }",How to access query parameters like $ orderBy in controller actions ? C_sharp : Is it possible to apply a Trim ( ) to a string without assignment to a new or existing variable ? Instead of having to assign it to a new variable or itself ? var myString = `` my string `` ; myString.Trim ( ) ; // myString is now value `` my string '' var myString = `` my string `` ; myString = myString.Trim ( ) ; // myString is now value `` my string '',Apply Trim ( ) to string without assignment to variable "C_sharp : I have this code in a Windows 10 UWP application : The ManipulationCompleted event does n't work on phone in ListView . The code inside the handler never gets called.It 's working fine on PC , but does n't work on phone . I do n't understand why . MyListView.ManipulationMode = ManipulationModes.TranslateX ; MyListView.ManipulationStarted += ( s , e ) = > x1 = ( int ) e.Position.X ; MyListView.ManipulationCompleted += ( s , e ) = > { x2 = ( int ) e.Position.X ; if ( x1 > x2 ) { DataController.PaneOpen ( false ) ; } ; if ( x1 < x2 ) { DataController.PaneOpen ( true ) ; } ; } ;",ListView ManipulationCompleted event does n't work on phone "C_sharp : I 'm having a hard time describing this problem . Maybe that 's why I 'm having a hard time finding a good solution ( the words just are n't cooperating ) . Let me explain via code : Now pretend years of development go by with these three types . Different flavors of the above logic propagate throughout stored procedures , SSIS packages , windows apps , web apps , java apps , perl scripts and etc ... .Finally : Most of the time , the `` system '' runs fine until Grapes are used . Then parts of the system act inappropriately , pealing and/or coring grapes when it 's not needed or desired.What kind of guidelines do you adhere to so these messes are avoided ? My preference is for old code to throw an exception if it has n't been refactored to consider new enumerations.I 've come up with a shot in the dark : # 1 Avoid `` Not In Logic '' such as this # 2 Use carefully constructed NotIn ( ) methods when neededNow , I can safely , use code like this : If this code gets propagated throughout the system , exceptions will be thrown when the Grape comes rolling into town ( qa will catch 'em all ) .That 's the plan anyway . The problem seems like it should be very common , but I ca n't seem to find anything on google ( probably my own fault ) .How are you all handling this ? UPDATE : I feel the answer to this problem is create a `` catch everything else '' mechanism that halts processing and alerts testers and developers to that fact that the new enumeration needs consideration . `` switch ... default '' is great if you have it.If C # did n't have switch ... default , we might right the above code like this : DISCLAIMER : You really should n't use any of the above pseudo code . It may ( ? ) compile or even work , but it 's horrible code , really . I saw a lot of nice solutions in this thread if you 're looking for an OOP-based approach . A good solution , of course , places all the switching and checking in a centralized method ( a factory method is what strikes me ) . Peer code review on top of that will also be required . // original codeenum Fruit { Apple , Orange , Banana , } ... Fruit fruit = acquireFruit ( ) ; if ( fruit ! = Fruit.Orange & & fruit ! = Fruit.Banana ) coreFruit ( ) ; else pealFruit ( ) ; eatFruit ( ) ; // new codeenum Fruit { Apple , Orange , Banana , Grape , } // select fruit that needs to be coredselect Fruit from FruitBasket where FruitType not in ( Orange , Banana ) internal static class EnumSafetyExtensions { /* By adding enums to these methods , you certify that 1 . ) ALL the logic inside this assembly is aware of the * new enum value and 2 . ) ALL the new scenarios introduced with this new enum have been accounted for . * Adding new enums to an IsNot ( ) method without without carefully examining every reference will result in failure . */ public static bool IsNot ( this SalesOrderType target , params SalesOrderType [ ] setb ) { // SetA = known values - SetB List < SalesOrderType > seta = new List < SalesOrderType > { SalesOrderType.Allowance , SalesOrderType.NonAllowance , SalesOrderType.CompanyOrder , SalesOrderType.PersonalPurchase , SalesOrderType.Allotment , } ; setb.ForEach ( o = > seta.Remove ( o ) ) ; // if target is in SetA , target is not in SetB if ( seta.Contains ( target ) ) return true ; // if target is in SetB , target is not not in SetB if ( setb.Contains ( target ) ) return false ; // if the target is not in seta ( the considered values minus the query values ) and the target is n't in setb // ( the query values ) , then we 've got a problem . We 've encountered a value that this assembly does not support . throw new InvalidOperationException ( `` Unconsidered Value detected : SalesOrderType . '' + target.ToString ( ) ) ; } } bool needsCoring = fruit.IsNot ( Fruit.Orange , Fruit.Banana ) ; Fruit fruit = acquireFruit ( ) ; if ( fruit ! = Fruit.Orange & & fruit ! = Fruit.Banana ) coreFruit ( ) ; else if ( fruit == Fruit.Apple ) pealFruit ( ) ; else throw new NotSupportedException ( `` Unknown Fruit : '' + fruit ) eatFruit ( ) ;",How do you write code whose logic is protected against future additional enumerations ? "C_sharp : I have following component composition : As you can see , there 's Logger property all around . Thing is , that I need to pass that property value during resolving ( different jobs are requiring different configuration loggers ) .So if only top component would need this , it would be as simple as But I need to pass childLogger down the tree and that tree is quite complex , I do n't wish to manually pass logger instance to each component , which needs it , wondering if Windsor could help me at this ? Update : May be this will help better understand problem : In wiki there 's notice : Inline dependencies do n't get propagated Whatever arguments you pass to Resolve method will only be available to the root component you 're trying to resolve , and its Interceptors . All the components further down ( root 's dependencies , and their dependencies and so on ) will not have access to them.Why is it like so and is there any workaround ? Update 2 : May be it will help , if I 'll add real situation.So , we have Application , which sends/receives data from/to various sales channels . Each sales channel has corresponding collection of jobs , like send updated product information , receive orders , etc ( each job may contain smaller jobs inside ) . So it is logical , that we need to keep each channel 's log information separate from other channel 's , but single channel 's jobs logs should go to single listener , that we could see sequence of what is happening ( if each job and subjob would have own logging listener , we would need to merge logs by time to understand what is going on ) . Some channels and their job sets are not known at compile time ( let 's say there 's channel A , we can start separate channel for a specific country by simple adding that country to DB , depending on load we can switch synchronization method , etc. ) . What all that means , that we may have UpdateProductsForChannelAJob , which will be used in two different channels ( ChannelA US and ChannelA UK ) , so it 's logger will depend on which channel it depends to.So what we are doing now , is we create child logger for each channel and we pass it when resolving Job instance as a parameter . That works , but has one annoying thing - we have to pass logger instance manually inside job to each dependency ( and dependencies dependency ) , that may be logging something.Update 3 : I 've found in Windsor documentation feature , that sounds like what I need : There are times where you need to supply a dependency , which will not be known until the creation time of the component . For example , say you need a creation timestamp for your service . You know how to obtain it at the time of registration , but you do n't know what its specific value will be ( and indeed it will be different each time you create a new instance ) . In this scenarios you use DynamicParameters method.And you get two parameters in DynamicParameters delegate , one of them is dictionary and It is that dictionary that you can now populate with dependencies which will be passed further to the resolution pipelineGiven that , I thought this will work : But it does not . public interface IJob { ILogger Logger { get ; set ; } } public class JobC : IJob { public ILogger Logger { get ; set ; } private ServiceA serviceA ; private ServiceB serviceB ; public JobC ( ServiceA serviceA , ServiceB serviceB ) { this.serviceA = serviceA ; this.serviceB = serviceB ; } } public class ServiceB { public ILogger Logger { get ; set ; } } public class ServiceA { public ILogger Logger { get ; set ; } } var childLogger = Logger.CreateChildLogger ( jobGroupName ) ; var job = windsorContainer.Resolve ( jobType ) ; job.Logger = childLogger ; public interface IService { } public class ServiceWithLogger : IService { public ILogger Logger { get ; set ; } } public class ServiceComposition { public ILogger Logger { get ; set ; } public IService Service { get ; set ; } public ServiceComposition ( IService service ) { Service = service ; } } public class NameService { public NameService ( string name ) { Name = name ; } public string Name { get ; set ; } } public class NameServiceConsumer { public NameService NameService { get ; set ; } } public class NameServiceConsumerComposition { public NameService NameService { get ; set ; } public NameServiceConsumer NameServiceConsumer { get ; set ; } } [ TestFixture ] public class Tests { [ Test ] public void GivenDynamicParamtersConfigurationContainerShouldPassLoggerDownTheTree ( ) { var container = new WindsorContainer ( ) ; container.AddFacility < LoggingFacility > ( ) ; container.Register ( Component.For < IService > ( ) .ImplementedBy < ServiceWithLogger > ( ) .LifestyleTransient ( ) , Component.For < ServiceComposition > ( ) .DynamicParameters ( ( k , d ) = > { d [ `` Logger '' ] = k.Resolve < ILogger > ( ) .CreateChildLogger ( d [ `` name '' ] .ToString ( ) ) ; } ) .LifestyleTransient ( ) ) ; var service = container.Resolve < ServiceComposition > ( new { name = `` my child '' } ) ; var childLogger = ( ( ServiceWithLogger ) service.Service ) .Logger ; Assert.IsTrue ( ( ( ConsoleLogger ) childLogger ) .Name.Contains ( `` my child '' ) ) ; } [ Test ] public void GivenDynamicParamtersConfigurationContainerShouldPassNameDownTheTree ( ) { var container = new WindsorContainer ( ) ; container.AddFacility < LoggingFacility > ( ) ; container.Register ( Component.For < NameService > ( ) .LifestyleTransient ( ) .DependsOn ( new { name = `` default '' } ) , Component.For < NameServiceConsumer > ( ) .LifestyleTransient ( ) , Component.For < NameServiceConsumerComposition > ( ) .DynamicParameters ( ( k , d ) = > { d [ `` nameService '' ] = k.Resolve < NameService > ( d [ `` nameParam '' ] ) ; } ) .LifestyleTransient ( ) ) ; var service = container.Resolve < NameServiceConsumerComposition > ( new { nameParam = `` my child '' } ) ; Console.WriteLine ( service.NameServiceConsumer.NameService.Name ) ; Assert.IsTrue ( service.NameServiceConsumer.NameService.Name.Contains ( `` my child '' ) ) ; } }",How to configure windsor for passing dependency as argument through dependency tree ? "C_sharp : I am using entity framework 6 with oracle and Sql . Timespan datatype is not working with oracle . so i changed datatype to datetime . now i want to compare only time in datetime with Linq query . ex . in above example e.ExecutionTime is datetime and viewmodel.ExecutionTime is timespan . i am using timeofday function to convert it to timespan above query failed to execute so i used DbFunctions.CreateTime ( ) functionabove ex exetime is timespan.still i am getting below error var db0010016 = _idb0010016Rep.GetAll ( ) .Where ( e = > e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime ) .FirstOrDefault ( ) ; var db0010016 = _idb0010016Rep.FindBy ( e = > DbFunctions.CreateTime ( e.ExecutionTime.Hour , e.ExecutionTime.Minute , e.ExecutionTime.Second ) == exetime ) .FirstOrDefault ( ) ; { `` Invalid parameter binding\r\nParameter name : ParameterName '' }",Compare only time from datetime in entity framework 6 with odp.net Oracle 12c "C_sharp : In C # it is possible to alias classes using the following : Is this possible with classes that depend on generics , i have tried a similar approach but it does not seem to compile.andIs this even possible using generics in C # ? If so , what is it that I am missing ? using Str = System.String ; using IE < T > = System.Collections.Generic.IEnumerable < T > ; using IE = System.Collections.Generic.IEnumerable ;",using Alias = Class ; with generics C_sharp : I have this code in a class : Will it keep the lock on _locker ? private static MyObject _locker = new MyObject ( ) ; ... lock ( _locker ) { ... _locker = new MyObject ( ) ; ... },C # Locking an object that is reassigned in lock block "C_sharp : I came across a situation where i need some knowledge.Below is the code : My understanding of Action used to be that it should match a delegate that accepts no parameter and returns nothing.And for Func < int > that it should match a delegate that accepts no parameter and returns an int.DoSomething method returns an integer , hence my question : ( ) = > DoSomething ( ) is a delegate that returns an int . Func works as expected , but Action does n't . Why ? What am i failing to understand here ? The code compiles and runs properly , both output i am called . What i want to know is that why Action action = ( ) = > DoSomething ( ) ; is not a compile time error ? // A function to match the delegatepublic static int DoSomething ( ) { Console.WriteLine ( `` i am called '' ) ; return 1 ; } // UsageAction action = ( ) = > DoSomething ( ) ; Func < int > func = ( ) = > DoSomething ( ) ; action ( ) ; func ( ) ;",Action same as Func < TResult > ? "C_sharp : Array.Sort in C # is really fast if you sort floats , I need some extra data to go along with those floats so I made a simple class and extended the IComparable interface . Now all of a sudden Array.Sort is around 3-4 times slower , why is this and how can I improve the performance ? Demo code : Demo output : Edit : I updated the code to also sort using a struct and a delegate , as suggested below , there is no difference.New demo output : Edit 2 : I have updated my code with some of the suggestions below , making it a struct either has no effect on my pc or I am doing something horribly wrong . I also added some sanity checks.New demo output ( do n't let the `` atleast once '' fool you , it is misphrased ) : Edit 3 : I have updated the demo code once again with a fix to the overloaded method of Array.Sort . Note that I create and fill test [ ] outside the Stopwatch because in my case I already have that array available . arraySortOverload is faster in debug mode , and about as fast as the struct method in release mode.New demo output ( RELEASE ) : using System ; using System.Diagnostics ; using System.Linq ; namespace SortTest { class Program { static void Main ( string [ ] args ) { int arraySize = 10000 ; int loops = 500 ; double normalFloatTime = 0 ; double floatWithIDTime = 0 ; double structTime = 0 ; double arraySortOverloadTime = 0 ; bool floatWithIDCorrect = true ; bool structCorrect = true ; bool arraySortOverloadCorrect = true ; //just so we know the program is busy Console.WriteLine ( `` Sorting random arrays , this will take some time ... '' ) ; Random random = new Random ( ) ; Stopwatch sw = new Stopwatch ( ) ; for ( int i = 0 ; i < loops ; i++ ) { float [ ] normalFloatArray = new float [ arraySize ] ; SortTest [ ] floatWithIDArray = new SortTest [ arraySize ] ; SortStruct [ ] structArray = new SortStruct [ arraySize ] ; SortTest [ ] arraySortOverloadArray = new SortTest [ arraySize ] ; //fill the arrays for ( int j = 0 ; j < arraySize ; j++ ) { normalFloatArray [ j ] = NextFloat ( random ) ; floatWithIDArray [ j ] = new SortTest ( normalFloatArray [ j ] , j ) ; structArray [ j ] = new SortStruct ( normalFloatArray [ j ] , j ) ; arraySortOverloadArray [ j ] = new SortTest ( normalFloatArray [ j ] , j ) ; } //Reset stopwatch from any previous state sw.Reset ( ) ; sw.Start ( ) ; Array.Sort ( normalFloatArray ) ; sw.Stop ( ) ; normalFloatTime += sw.ElapsedTicks ; //Reset stopwatch from any previous state sw.Reset ( ) ; sw.Start ( ) ; Array.Sort ( floatWithIDArray ) ; sw.Stop ( ) ; floatWithIDTime += sw.ElapsedTicks ; //Reset stopwatch from any previous state sw.Reset ( ) ; sw.Start ( ) ; Array.Sort ( structArray ) ; sw.Stop ( ) ; structTime += sw.ElapsedTicks ; //Reset stopwatch from any previous state sw.Reset ( ) ; sw.Start ( ) ; Array.Sort ( arraySortOverloadArray.Select ( k = > k.ID ) .ToArray ( ) , arraySortOverloadArray ) ; sw.Stop ( ) ; arraySortOverloadTime += sw.ElapsedTicks ; for ( int k = 0 ; k < normalFloatArray.Length ; k++ ) { if ( normalFloatArray [ k ] ! = floatWithIDArray [ k ] .SomeFloat ) { floatWithIDCorrect = false ; } if ( normalFloatArray [ k ] ! = structArray [ k ] .SomeFloat ) { structCorrect = false ; } if ( normalFloatArray [ k ] ! = arraySortOverloadArray [ k ] .SomeFloat ) { arraySortOverloadCorrect = false ; } } } //calculate averages double normalFloatAverage = normalFloatTime / loops ; double floatWithIDAverage = floatWithIDTime / loops ; double structAverage = structTime / loops ; double arraySortOverloadAverage = arraySortOverloadTime / loops ; //print averages Console.WriteLine ( `` normalFloatAverage : { 0 } ticks.\nfloatWithIDAverage : { 1 } ticks.\nstructAverage : { 2 } ticks.\narraySortOverloadAverage : { 3 } ticks . `` , normalFloatAverage , floatWithIDAverage , structAverage , arraySortOverloadAverage ) ; Console.WriteLine ( `` floatWithIDArray has `` + ( floatWithIDCorrect ? `` '' : `` NOT `` ) + `` been sorted correctly atleast once . `` ) ; Console.WriteLine ( `` structArray has `` + ( structCorrect ? `` '' : `` NOT `` ) + `` been sorted correctly atleast once . `` ) ; Console.WriteLine ( `` arraySortOverloadArray has `` + ( arraySortOverloadCorrect ? `` '' : `` NOT `` ) + `` been sorted correctly atleast once . `` ) ; Console.WriteLine ( `` Press enter to exit . `` ) ; //pause so we can see the console Console.ReadLine ( ) ; } static float NextFloat ( Random random ) { double mantissa = ( random.NextDouble ( ) * 2.0 ) - 1.0 ; double exponent = Math.Pow ( 2.0 , random.Next ( -126 , 128 ) ) ; return ( float ) ( mantissa * exponent ) ; } } class SortTest : IComparable < SortTest > { public float SomeFloat ; public int ID ; public SortTest ( float f , int id ) { SomeFloat = f ; ID = id ; } public int CompareTo ( SortTest other ) { float f = other.SomeFloat ; if ( SomeFloat < f ) return -1 ; else if ( SomeFloat > f ) return 1 ; else return 0 ; } } struct SortStruct : IComparable < SortStruct > { public float SomeFloat ; public int ID ; public SortStruct ( float f , int id ) { SomeFloat = f ; ID = id ; } public int CompareTo ( SortStruct other ) { float f = other.SomeFloat ; if ( SomeFloat < f ) return -1 ; else if ( SomeFloat > f ) return 1 ; else return 0 ; } } } Sorting random arrays , this will take some time ... normalFloatAverage : 3840,998 ticks.floatWithIDAverage : 12850.672 ticks.Press enter to exit . Sorting random arrays , this will take some time ... normalFloatAverage : 3629.092 ticks.floatWithIDAverage : 12721.622 ticks.structAverage : 12870.584 ticks.Press enter to exit . Sorting random arrays , this will take some time ... normalFloatAverage : 3679.928 ticks.floatWithIDAverage : 14084.794 ticks.structAverage : 11725.364 ticks.arraySortOverloadAverage : 2186.3 ticks.floatWithIDArray has been sorted correctly atleast once.structArray has been sorted correctly atleast once.arraySortOverloadArray has NOT been sorted correctly atleast once.Press enter to exit . Sorting random arrays , this will take some time ... normalFloatAverage : 2384.578 ticks.floatWithIDAverage : 6405.866 ticks.structAverage : 4583.992 ticks.arraySortOverloadAverage : 4551.104 ticks.floatWithIDArray has been sorted correctly all the time.structArray has been sorted correctly all the time.arraySortOverloadArray has been sorted correctly all the time.Press enter to exit .",Array.Sort ( ) performance drop when sorting class instances instead of floats "C_sharp : I 'm making an HTTP POST request with this : So far , this seems working fine but I 'm not sure if this will always work , because Encoding.UTF8 means UTF8 WITH BOM . When I create local files with StreamWriter , always use the default encoding which is the same as new UTF8Encoding ( false ) in order to write WITHOUT BOM . So wonder if the same is true for calling GetBytes ( ) method too.In this case , is n't there any difference between above and below line ? I tested several times myself but still not sure 100 % , so asking here . byte [ ] postBuffer = Encoding.UTF8.GetBytes ( postStr ) ; byte [ ] postBuffer = new UTF8Encoding ( ) .GetBytes ( postStr ) ;",Does Encoding.UTF8.GetBytes ( ) create a BOM ? "C_sharp : Like Microsoft Word , If we open multiple Word windows , then we will find that they are under one process named WINWORD with multiple tasks under it . In task manager of Window 8.1 Pro , we can right click it and end it by End Task.I success to do the end process with process name but I can not get any idea from Google search that how to do the kill certain task under certain process in this situation.Emphasize : I am not asking how to kill the process.processes [ i ] .Kill ( ) ; UpdateI success to kill the specified Word Window withBut I wonder how can I kill the oldest Word Window in this case ? If process can sort the StartTime to kill the oldest one ... . But I think this should be included in another question , thanks . using System ; using System.Runtime.InteropServices ; namespace CloseTask { class Program { [ DllImport ( `` user32.dll '' ) ] public static extern int FindWindow ( string lpClassName , string lpWindowName ) ; [ DllImport ( `` user32.dll '' ) ] public static extern int SendMessage ( int hWnd , uint Msg , int wParam , int lParam ) ; public const int WM_SYSCOMMAND = 0x0112 ; public const int SC_CLOSE = 0xF060 ; static void Main ( string [ ] args ) { closeWindow ( ) ; } private static void closeWindow ( ) { // retrieve the handler of the window of Word // Class name , Window Name int iHandle = FindWindow ( `` OpusApp '' , `` Document1 - Microsoft Word '' ) ; if ( iHandle > 0 ) { //close the window using API SendMessage ( iHandle , WM_SYSCOMMAND , SC_CLOSE , 0 ) ; } } } }",Kill Specified Task instead of Process in C # "C_sharp : Update : It seems that I am not being clear enough of what exactly I am asking ( and as the question developed over time I also lost track a bit ) , so here is a tl ; dr version : This means - as I understand - that the ? type modifier has lower precedence ( as it 's not an operator this might not be the best word ) than the & operator , but higher than the & & operator . Is it so ? Where is this described in the standard ? And the original question : While trying to figure out the answer to the second puzzle from Jon Skeet 's excellent blogpost , A Tale of two puzzles , I faced a problem : Here I am using an unsafe context as my actual goal requires it ( e.g . : the third line ) , but it is not necessary for reproducing the issue I raise . ( However it might have an effect , as it introduces the address-of operator as an alternative for the & symbol . ) The first line does not compile ( the others do ) , it gives the following error message : This means that in that case the compiler sees the line asWhile in the second line it sees it as : I checked operator precedence ( here ) , and the order ( from highest to lowest ) is the following : & , & & , ? : , so this alone does not explain why the first line does not compile while the second does ( Or at least not for me - maybe this is where I am wrong ... ) Edit : I understand why the second compiles , so please do n't concentrate on this in your answers.My next hunch was that somehow the precedence ( if there is such thing ) for the ? type modifier is somewhere between those two ( or in fact three ) operators ( & and & & ) . Can it be so ? If not could someone please explain the exact behavior that I am experiencing ? Is the evaluating order of ? type modifier clearly described somewhere in the standard ? Edit : I am also aware that there is an unary address-of operator ( actually that 's the trick I am trying to use for the solution ... ) , which plays a role here , but my question still stays the same.In the same unsafe context those happily compile : So I think it must be related to the ? modifier/operator , and not solely to the address-of operator taking precedence ( otherwise the two test1 lines would not compile ) .P.S . : I know that I can add parentheses to my code , so it will compile , but I want to avoid that : Update : I experimented with Roslyn a little , and I thought it might be a good idea to attach the ASTs for the various statements : I want to emphasise that I am not looking for a solution for the original problem in the linked article ( of course I am looking for one , but I ask you not to give an answer here please , as I would like to find that out on my own . ) Also , please do n't comment if I am on a completely wrong track in finding the solution , I only mentioned the puzzle to give some context for my specific problem , and to provide a good-enough excuse for writing code like this . var test1 = a is byte & b ; // compilesvar test2 = a is byte ? & b ; // does not compilevar test3 = a is byte ? & & b ; // compiles unsafe private void Test < T > ( T a , bool b ) { var test1 = a is byte ? & b ; // does not compile var test2 = a is byte ? & & b ; // compiles var test3 = a is byte ? & b : & b ; // compiles } Syntax error , ' : ' expected var test1 = ( a is byte ) ? & b [ : missing part that it complains about ] ; var test2 = ( a is byte ? ) & & ( b ) ; var test1 = true & b ; var test2 = true & & b ; // orvar test1 = a is byte & b ; var test2 = a is byte & & b ; var test = ( a is byte ? ) & b ; // compiles var test1 = a is byte & b ; var test2 = a is byte ? & b ; var test3 = a is byte ? & & b ;",`` ? '' type modifer precedence vs logical and operator ( & ) vs address-of operator ( & ) "C_sharp : Consider the code below : Running it , I get the exception below : System.Linq.Dynamic.ParseException was unhandled by user code Message=Operator '+ ' incompatible with operand types 'Vector2 ' and 'Vector2 ' Source=DynamicLINQ Position=6How do I get the parser to 'see ' the + operator overload on the Vector2 type ? EDIT : I also get the same issue with the = operator.Looking at the source I can see why , it looks at a special interface that lists loads of methods , for simple types and if it ca n't find it , then it raises the exception . Trouble is , my type ( Vector2 ) is n't in that list , so it wo n't ever find the operator methods . var vectorTest = new Vector2 ( 1 , 2 ) + new Vector2 ( 3 , 4 ) ; // Worksvar x = Expression.Parameter ( typeof ( Vector2 ) , `` x '' ) ; var test = System.Linq.Dynamic .DynamicExpression.ParseLambda ( new [ ] { x } , null , `` x = x + x '' ) ;",Dynamic linq and operator overloads "C_sharp : I need a spell checker with the following specification : Very scalable.To be able to set a maximum edit distance for the suggested words.To get suggestion based on provided words frequencies ( most common word first ) .I took a look at Hunspell : I found the parameter MAXDIFF in the man but does n't seem to work as expected . Maybe I 'm using it the wrong wayfile t.aff : file dico.dic : - returns the same thing t.aff being empty or not : MAXDIFF 1 5 rouge vert bleu bleue orange NHunspell.Hunspell h = new NHunspell.Hunspell ( `` t.aff '' , `` dico.dic '' ) ; List < string > s = h.Suggest ( `` bleuue '' ) ; bleuebleu",Max edit distance and suggestion based on word frequency "C_sharp : I have a requirement that I think I have a solution for , but I would appreciate input in case I 'm missing something or setting myself up for failure down the road.The Requirement Implement some new business logic in a new library ( using C # ) that reports back its status through events . The library will be invoked from an existing VBA solution ( ca n't change that - yet ) . The library is exposed to VBA via COM Interop - no issues here.In addition to the `` base '' functionality exposed by this new library , I need to allow for the base functionality to be replaced by `` custom '' functionality down the road.Both the base and custom functionality will implement the same Interface , but the internal private methods of each will be different for a variety of reasons.In VBAI need to be able to invoke either the base library or custom library ( and perhaps other custom libraries that implement the same Interface in the future ) . If it were n't for the requirement to respond to and display messages from the libraries I could just use Late Binding to instantiate the object at runtime . However , since I need to respond to the events that are raised by the libraries I need to use the WithEvents keyword when declaring the variable in VBA.If I only had to support the base library I could do something like the following : Since I have to support custom implementations of this library ( some of which I know about now , others that I do n't yet know about ) I would like to use late binding to handle this scenario . However , WithEvents can not be used with Late Binding , though I may have stumbled upon a workaround.In my scenario , I will always have a reference to the base implementation . It will only be under specific , configured circumstances where the base functionality will be replaced by a custom implementation.Since the base and custom library ( ies ) share the same Interface , I have the following code working in a proof of concept : This implementation works without errors ( both at compile and runtime ) , but I am a bit hesitant about using this solution going forward because I do n't feel like I have a solid understanding of how \ why this actually works . My suspicion is that it works because both the base and custom libraries share the same interface , so COM is `` happy '' with late binding via the CreateObject statement , but I 'm afraid of what I might be missing here that will potentially cause me grief down the road . My QuestionIs it `` safe '' to rely upon this workaround for late binding using WithEvents , and if so , why ? If not , are there any alternatives that I could look to implement ( beyond not using VBA , which I do n't have a choice of in this scenario ) ? Private WithEvents Processor As MyDefault.RuleEnginePublic Sub Execute ( StartDate As Date , EndDate As Date , SomeOtherParms As String ) Set Processor = New MyDefault.RuleEngineProcessor.Execute StartDate , EndDate , SomeOtherParmsEnd SubPrivate Sub Processor_OnProgressUpdate ( ByVal percentComplete As Double ) 'Show the progress on the UI to the userEnd Sub Private WithEvents Processor As MyDefault.RuleEnginePublic Sub Execute ( StartDate As Date , EndDate As Date , SomeOtherParms As String ) If CustomConditionIsMet Then 'In real-life we 'll look this info up from a table or config file Set Processor = CreateObject ( `` MyCustom.RuleEngine '' ) Else Set Processor = New MyDefault.RuleEngineEnd IfProcessor.Execute StartDate , EndDate , SomeOtherParmsEnd SubPrivate Sub Processor_OnProgressUpdate ( ByVal percentComplete As Double ) 'Show the progress on the UI to the userEnd Sub",Late Binding and WithEvents using VBA "C_sharp : As the title says , i got a WCF Server having this service behavior defined : I ' using a named pipe binding and my clients are connecting in this way : Every client I start executes the code above , and for every client the CPU usage raises by 25 % ( actually not for the 5. client , but at this point the service execteable is covering nearly a 100 % of the whole CPU capacity ) . What I 'm searching for is a kind of resource ( website/list or just YOUR powerful knowledge ) telling me what a CreateChannel actually does ( regarding in resource allocation issues ) .hint : the CPU usage increases even if no communication is actually done , just the Channel is created . [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.Single , ConcurrencyMode = ConcurrencyMode.Multiple ) ] NetNamedPipeBinding binding = new NetNamedPipeBinding ( ) ; const int maxValue = 0x40000000 ; // 1GBbinding.MaxBufferSize = maxValue ; binding.MaxReceivedMessageSize = maxValue ; binding.ReaderQuotas.MaxArrayLength = maxValue ; binding.ReaderQuotas.MaxBytesPerRead = maxValue ; binding.ReaderQuotas.MaxStringContentLength = maxValue ; // receive timeout acts like a general timeoutbinding.ReceiveTimeout = TimeSpan.MaxValue ; binding.SendTimeout = TimeSpan.MaxValue ; ChannelFactory < IDatabaseSession > pipeFactory = new ChannelFactory < IDatabaseSession > ( binding , new EndpointAddress ( `` net.pipe : //localhost/DatabaseService '' ) ) ; IDatabaseSession dbSession = pipeFactory.CreateChannel ( )",WCF CPU usage increase by 25 % for each client "C_sharp : Is there any way to do something like this in C # ? public void DoSomething ( string parameterA , int parameterB ) { } var parameters = ( `` someValue '' , 5 ) ; DoSomething ( parameters ) ;",Is there any way to do something like this in C # ? "C_sharp : In my code I retrieve frames from a camera with a pointer to an unmanaged object , make some calculations on it and then I make it visualized on a picturebox control.Before I go further in this application with all the details , I want to be sure that the base code for this process is good.In particular I would like to : - keep execution time minimal and avoid unnecessary operations , such as copying more images than necessary . I want to keep only essential operations - understand if a delay in the calculation process on every frame could have detrimental effects on the way images are shown ( i.e . if it is not printed what I expect ) or some image is skipped - prevent more serious errors , such as ones due to memory or thread management , or to image display.For this purpose , I set up a few experimental lines of code ( below ) , but I ’ m not able to explain the results of what I found . If you have the executables of OpenCv you can make a try by yourself . results [ dual core 2 Duo T6600 2.2 GHz ] : A. buffercopy = false ; copyBitmap = false ; refresh = false ; This is the simpler configuration . Each frame is retrieved in turn , operations are made ( in the reality they are based on the same frame , here just calculations ) , then the result of the calculations is printed on top of the image and finally it is displayed on a picturebox.OpenCv documentation says : OpenCV 1.x functions cvRetrieveFrame and cv.RetrieveFrame return image stored inside the video capturing structure . It is not allowed to modify or release the image ! You can copy the frame using cvCloneImage ( ) and then do whatever you want with the copy . But this doesn ’ t prevent us from doing experiments.If the calculation are not intense ( low number of iterations , N ) , everything is just ok and the fact that we manipulate the image buffer own by the unmanaged frame retriever doesn ’ t pose a problem here.The reason is that probably they advise to leave untouched the buffer , in case people would modify its structure ( not its values ) or do operations asynchronously without realizing it . Now we retrieve frames and modify their content in turn.If N is increased ( N=1000000 or more ) , when the number of frames per second is not high , for example with artificial light and low exposure , everything seems ok , but after a while the video is lagged and the graphics impressed on it are blinking . With a higher frame rate the blinking appears from the beginning , even when the video is still fluid.Is this because the mechanism of displaying images on the control ( or refreshing or whatever else ) is somehow asynchronous and when the picturebox is fetching its buffer of data it is modified in the meanwhile by the camera , deleting the graphics ? Or is there some other reason ? Why is the image lagged in that way , i.e . I would expect that the delay due to calculations only had the effect of skipping the frames received by the camera when the calculation are not done yet , and de facto only reducing the frame rate ; or alternatively that all frames are received and the delay due to calculations brings the system to process images gotten minutes before , because the queue of images to process rises over time.Instead , the observed behavior seems hybrid between the two : there is a delay of a few seconds , but this seems not increased much as the capturing process goes on . B. buffercopy = true ; copyBitmap = false ; refresh = false ; Here I make a deep copy of the buffer into a second buffer , following the advice of the OpenCv documentation.Nothing changes . The second buffer doesn ’ t change its address in memory during the run . C. buffercopy = false ; copyBitmap = true ; refresh = false ; Now the ( deep ) copy of the bitmap is made allocating every time a new space in memory.The blinking effect has gone , but the lagging keep arising after a certain time . D. buffercopy = false ; copyBitmap = false ; refresh = true ; As before . Please help me explain these results ! using System ; using System.Drawing ; using System.Drawing.Imaging ; using System.Windows.Forms ; using System.Runtime.InteropServices ; using System.Threading ; public partial class FormX : Form { private delegate void setImageCallback ( ) ; Bitmap _bmp ; Bitmap _bmp_draw ; bool _exit ; double _x ; IntPtr _ImgBuffer ; bool buffercopy ; bool copyBitmap ; bool refresh ; public FormX ( ) { InitializeComponent ( ) ; _x = 10.1 ; // set experimemental parameters buffercopy = false ; copyBitmap = false ; refresh = true ; } private void buttonStart_Click ( object sender , EventArgs e ) { Thread camThread = new Thread ( new ThreadStart ( Cycle ) ) ; camThread.Start ( ) ; } private void buttonStop_Click ( object sender , EventArgs e ) { _exit = true ; } private void Cycle ( ) { _ImgBuffer = IntPtr.Zero ; _exit = false ; IntPtr vcap = cvCreateCameraCapture ( 0 ) ; while ( ! _exit ) { IntPtr frame = cvQueryFrame ( vcap ) ; if ( buffercopy ) { UnmanageCopy ( frame ) ; _bmp = SharedBitmap ( _ImgBuffer ) ; } else { _bmp = SharedBitmap ( frame ) ; } // make calculations int N = 1000000 ; /*1000000*/ for ( int i = 0 ; i < N ; i++ ) _x = Math.Sin ( 0.999999 * _x ) ; ShowFrame ( ) ; } cvReleaseImage ( ref _ImgBuffer ) ; cvReleaseCapture ( ref vcap ) ; } private void ShowFrame ( ) { if ( pbCam.InvokeRequired ) { this.Invoke ( new setImageCallback ( ShowFrame ) ) ; } else { Pen RectangleDtPen = new Pen ( Color.Azure , 3 ) ; if ( copyBitmap ) { if ( _bmp_draw ! = null ) _bmp_draw.Dispose ( ) ; //_bmp_draw = new Bitmap ( _bmp ) ; // deep copy _bmp_draw = _bmp.Clone ( new Rectangle ( 0 , 0 , _bmp.Width , _bmp.Height ) , _bmp.PixelFormat ) ; } else { _bmp_draw = _bmp ; // add reference to the same object } Graphics g = Graphics.FromImage ( _bmp_draw ) ; String drawString = _x.ToString ( ) ; Font drawFont = new Font ( `` Arial '' , 56 ) ; SolidBrush drawBrush = new SolidBrush ( Color.Red ) ; PointF drawPoint = new PointF ( 10.0F , 10.0F ) ; g.DrawString ( drawString , drawFont , drawBrush , drawPoint ) ; drawPoint = new PointF ( 10.0F , 300.0F ) ; g.DrawString ( drawString , drawFont , drawBrush , drawPoint ) ; g.DrawRectangle ( RectangleDtPen , 12 , 12 , 200 , 400 ) ; g.Dispose ( ) ; pbCam.Image = _bmp_draw ; if ( refresh ) pbCam.Refresh ( ) ; } } public void UnmanageCopy ( IntPtr f ) { if ( _ImgBuffer == IntPtr.Zero ) _ImgBuffer = cvCloneImage ( f ) ; else cvCopy ( f , _ImgBuffer , IntPtr.Zero ) ; } // only works with 3 channel images from camera ! ( to keep code minimal ) public Bitmap SharedBitmap ( IntPtr ipl ) { // gets unmanaged data from pointer to IplImage : IntPtr scan0 ; int step ; Size size ; OpenCvCall.cvGetRawData ( ipl , out scan0 , out step , out size ) ; return new Bitmap ( size.Width , size.Height , step , PixelFormat.Format24bppRgb , scan0 ) ; } // based on older version of OpenCv . Change dll name if different [ DllImport ( `` opencv_highgui246 '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern IntPtr cvCreateCameraCapture ( int index ) ; [ DllImport ( `` opencv_highgui246 '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern void cvReleaseCapture ( ref IntPtr capture ) ; [ DllImport ( `` opencv_highgui246 '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern IntPtr cvQueryFrame ( IntPtr capture ) ; [ DllImport ( `` opencv_core246 '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern void cvGetRawData ( IntPtr arr , out IntPtr data , out int step , out Size roiSize ) ; [ DllImport ( `` opencv_core246 '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern void cvCopy ( IntPtr src , IntPtr dst , IntPtr mask ) ; [ DllImport ( `` opencv_core246 '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern IntPtr cvCloneImage ( IntPtr src ) ; [ DllImport ( `` opencv_core246 '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern void cvReleaseImage ( ref IntPtr image ) ; }",Experiment on displaying a Bitmap retrieved from a camera on a Picturebox "C_sharp : I 'm trying to write a markupextension like this : To be used like this : Errs with : The TypeConverter for type `` Length '' does not support converting from string.The TypeConverter works if I : Put it on the Valueproperty and have a default ctor.Decorate the Length type with the attribute.While this may be x/y I do n't want any of those solutions.Here is the code for the converter : [ MarkupExtensionReturnType ( typeof ( Length ) ) ] public class LengthExtension : MarkupExtension { // adding the attribute like this compiles but does nothing . public LengthExtension ( [ TypeConverter ( typeof ( LengthTypeConverter ) ) ] Length value ) { this.Value = value ; } [ ConstructorArgument ( `` value '' ) ] public Length Value { get ; set ; } public override object ProvideValue ( IServiceProvider serviceProvider ) { return this.Value ; } } < Label Content= '' { units : Length 1 mm } '' / > public class LengthTypeConverter : TypeConverter { public override bool CanConvertFrom ( ITypeDescriptorContext context , Type sourceType ) { if ( sourceType == typeof ( string ) ) { return true ; } return base.CanConvertFrom ( context , sourceType ) ; } public override bool CanConvertTo ( ITypeDescriptorContext context , Type destinationType ) { if ( destinationType == typeof ( InstanceDescriptor ) || destinationType == typeof ( string ) ) { return true ; } return base.CanConvertTo ( context , destinationType ) ; } public override object ConvertFrom ( ITypeDescriptorContext context , CultureInfo culture , object value ) { var text = value as string ; if ( text ! = null ) { return Length.Parse ( text , culture ) ; } return base.ConvertFrom ( context , culture , value ) ; } public override object ConvertTo ( ITypeDescriptorContext context , CultureInfo culture , object value , Type destinationType ) { if ( value is Length & & destinationType ! = null ) { var length = ( Length ) value ; if ( destinationType == typeof ( string ) ) { return length.ToString ( culture ) ; } else if ( destinationType == typeof ( InstanceDescriptor ) ) { var factoryMethod = typeof ( Length ) .GetMethod ( nameof ( Length.FromMetres ) , BindingFlags.Public | BindingFlags.Static , null , new Type [ ] { typeof ( double ) } , null ) ; if ( factoryMethod ! = null ) { var args = new object [ ] { length.metres } ; return new InstanceDescriptor ( factoryMethod , args ) ; } } } return base.ConvertTo ( context , culture , value , destinationType ) ; } }",Can a TypeConverter be used for constructor argument "C_sharp : In a previous question today these two different approaches was given to a question as answers . We have an object that might or might not implement IDisposable . If it does , we want to dispose it , if not we do nothing . The two different approaches are these:1 ) 2 ) Mainly , from the comments it sounds like the consensus was that 2 ) was the best approach.But looking at the differences , we come down to this:1 ) Perform a cast twice on toDispose.2 ) Only perform the cast once , but create a new intermediate object.I would guess that 2 will be marginally slower because it has to allocate a new local variable , so why is this regarded as the best solution in this case ? It is solely because of readability issues ? if ( toDispose is IDisposable ) ( toDispose as IDisposable ) .Dispose ( ) ; IDisposable disposable = toDispose as IDisposable ; if ( disposable ! = null ) disposable.Dispose ( ) ;","Cast using is twice , or use as once and create a new variable" "C_sharp : I am building an export to excel functionality using EP plus and c # application . I am currently getting the error . 'Table range collides with table tblAllocations29'In my code logic below , I am looping through a data structure that contains key and collection as a value.I looping across each key and once again loop through each collection belonging to that key.I basically need to print tabular information for each collection along with its totals.In the current scenario , I am getting the error when it is trying to printthree arraysThe first array has 17 recordsThe second array has 29 recordsThe third array has 6 recordsI have taken a note of the ranges it is creating while debuggingThe ranges are controller I have written the following utility that will try and export . It works sometimes when there are two array collections and it failed when processing three . Could somebody tell me what the problems areFundsAllocationsPrinter.csThis is how the data looks when it is displayed successfully A1 G18A20 G50A51 G58 [ HttpGet ] [ SkipTokenAuthorization ] public HttpResponseMessage DownloadFundAllocationDetails ( int id , DateTime date ) { var ms = GetStrategy ( id ) ; DateTime d = new DateTime ( date.Year , date.Month , 1 ) .AddMonths ( 1 ) .AddDays ( -1 ) ; if ( ms.FIRM_ID ! = null ) { var firm = GetService < FIRM > ( ) .Get ( ms.FIRM_ID.Value ) ; IEnumerable < FIRMWIDE_MANAGER_ALLOCATION > allocationsGroup = null ; var allocationsGrouped = GetAllocationsGrouped ( EntityType.Firm , firm.ID , d ) ; string fileName = string.Format ( `` { 0 } as of { 1 } .xlsx '' , `` test '' , date.ToString ( `` MMM , yyyy '' ) ) ; byte [ ] fileContents ; var newFile = new FileInfo ( fileName ) ; using ( var package = new OfficeOpenXml.ExcelPackage ( newFile ) ) { FundAllocationsPrinter.Print ( package , allocationsGrouped ) ; fileContents = package.GetAsByteArray ( ) ; } var result = new HttpResponseMessage ( HttpStatusCode.OK ) { Content = new ByteArrayContent ( fileContents ) } ; result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue ( `` attachment '' ) { FileName = fileName } ; result.Content.Headers.ContentType = new MediaTypeHeaderValue ( `` application/vnd.openxmlformats-officedocument.spreadsheetml.sheet '' ) ; return result ; } return null ; # endregion } public class FundAllocationsPrinter { public static void Print ( ExcelPackage package , ILookup < string , FIRMWIDE_MANAGER_ALLOCATION > allocation ) { ExcelWorksheet wsSheet1 = package.Workbook.Worksheets.Add ( `` Sheet1 '' ) ; wsSheet1.Protection.IsProtected = false ; int count = 0 ; int previouscount = 0 ; var position = 2 ; int startposition = 1 ; IEnumerable < FIRMWIDE_MANAGER_ALLOCATION > allocationGroup = null ; foreach ( var ag in allocation ) { allocationGroup = ag.Select ( a = > a ) ; var allocationList = allocationGroup.ToList ( ) ; count = allocationList.Count ( ) ; using ( ExcelRange Rng = wsSheet1.Cells [ `` A '' + startposition + `` : G '' + ( count + previouscount + 1 ) ] ) { ExcelTableCollection tblcollection = wsSheet1.Tables ; ExcelTable table = tblcollection.Add ( Rng , `` tblAllocations '' + count ) ; //Set Columns position & name table.Columns [ 0 ] .Name = `` Manager Strategy '' ; table.Columns [ 1 ] .Name = `` Fund '' ; table.Columns [ 2 ] .Name = `` Portfolio '' ; table.Columns [ 3 ] .Name = `` As Of '' ; table.Columns [ 4 ] .Name = `` EMV ( USD ) '' ; table.Columns [ 5 ] .Name = `` Percent '' ; table.Columns [ 6 ] .Name = `` Allocations '' ; wsSheet1.Column ( 1 ) .Width = 45 ; wsSheet1.Column ( 2 ) .Width = 45 ; wsSheet1.Column ( 3 ) .Width = 55 ; wsSheet1.Column ( 4 ) .Width = 15 ; wsSheet1.Column ( 5 ) .Width = 25 ; wsSheet1.Column ( 6 ) .Width = 20 ; wsSheet1.Column ( 7 ) .Width = 20 ; // table.ShowHeader = true ; table.ShowFilter = true ; table.ShowTotal = true ; //Add TotalsRowFormula into Excel table Columns table.Columns [ 0 ] .TotalsRowLabel = `` Total Rows '' ; table.Columns [ 4 ] .TotalsRowFormula = `` SUBTOTAL ( 109 , [ EMV ( USD ) ] ) '' ; table.Columns [ 5 ] .TotalsRowFormula = `` SUBTOTAL ( 109 , [ Percent ] ) '' ; table.Columns [ 6 ] .TotalsRowFormula = `` SUBTOTAL ( 109 , Allocations ] ) '' ; table.TableStyle = TableStyles.Dark10 ; } foreach ( var ac in allocationGroup ) { wsSheet1.Cells [ `` A '' + position ] .Value = ac.MANAGER_STRATEGY_NAME ; wsSheet1.Cells [ `` B '' + position ] .Value = ac.MANAGER_FUND_NAME ; wsSheet1.Cells [ `` C '' + position ] .Value = ac.PRODUCT_NAME ; wsSheet1.Cells [ `` D '' + position ] .Value = ac.EVAL_DATE.ToString ( `` dd MMM , yyyy '' ) ; wsSheet1.Cells [ `` E '' + position ] .Value = ac.UsdEmv ; wsSheet1.Cells [ `` F '' + position ] .Value = Math.Round ( ac.GroupPercent,2 ) ; wsSheet1.Cells [ `` G '' + position ] .Value = Math.Round ( ac.WEIGHT_WITH_EQ,2 ) ; position++ ; } position++ ; previouscount = position ; // position = position + 1 ; startposition = position ; position++ ; } } }",EP Plus - Error Table range collides with table "C_sharp : I have many methods like the one below : As you can see , I check if nodesWithRules has any items and exit the method before conducting the foreach statement , but is this unecessary code ? void ValidateBuyerRules ( ) { var nodesWithRules = ActiveNodes.Where ( x = > x.RuleClass.IsNotNullOrEmpty ( ) ) ; **if ( ! nodesWithRules.Any ( ) ) return ; ** foreach ( var ruleClass in nodesWithRules ) { // Do something here } }",Is there any benefit to calling .Any ( ) before .ForEach ( ) when using linq ? "C_sharp : The following code causes the compiler to throw error CS1605 ( `` Can not pass 'var ' as a ref or out argument because it is read-only '' ) in the first line of the property getter.Removing the readonly from the public readonly struct MyStruct line makes the code work , but for performance reasons , I would really like the struct to be readonly . It makes the code so much more cleaner than having to pass the struct as ref all the time.Is there a way to get a ReadOnlySpan < byte > from a readonly struct ? Edit : ... without creating an implicit or explicit copy of the structure ? [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public readonly struct MyStruct { public readonly int Field1 ; public readonly int Field2 ; public MyStruct ( int field1 , int field2 ) = > ( Field1 , Field2 ) = ( field1 , field2 ) ; public ReadOnlySpan < byte > Span { get { // This code only works when MyStruct is not read only ReadOnlySpan < MyStruct > temp = MemoryMarshal.CreateReadOnlySpan ( ref this , 1 ) ; return MemoryMarshal.Cast < MyStruct , byte > ( temp ) ; } } }",How to get a ReadOnlySpan < byte > from a readonly struct ? "C_sharp : Importing a basic type library using the tlbimp.exe tool allways creates an interface for each coclass . For example this IDL-descriptionresults in : an interface IFoo as a representation of the COM interface , a class BarClass as a representation of the COM coclass andan interface Bar , annotated with the CoClassAttribute.Where the GUIDs of Bar and IFoo are equal . The MSDN states on this topic : This interface has the same IID as the default interface for the coclass . With this interface , clients can always register as event sinks.That 's the only thing I found on this topic . I know that , due the CoClassAttribute , I can use the interface to create instances of the actual class . I also know that ( practically ) I can simply use BarClass to create a new instance of the class . What I do n't understand is , why the import process generates the Bar interface , even if the coclass does not define an event source and thus no event sink can be connected to it . Would it be possible to remove the Bar interface 1 in this example or are there some other risks , I have not yet considered ? 1 For example by disassembling the interop assembly . interface IFoo : IUnknown { HRESULT DoSomething ( ) ; } coclass Bar { [ default ] interface IFoo ; }",What are the CoClass interfaces in imported assemblies exactly for ? "C_sharp : I have just implemented a WeakEventDelegate class in .NET.I had seen other articles to the effect of implementing such a thing in http : //code.logos.com/blog/2008/08/event_subscription_using_weak_references.html and http : //blogs.msdn.com/b/greg_schechter/archive/2004/05/27/143605.aspxHowever , the implementation I arrived at is less complicated ( though less flexible ) , and seems to do the job , so I was wondering whether there was something I had missed.Is there any problem with the following implementation , except for its relative lack of flexibility ? EDIT : My only intent in writing that class was to prevent the implicit reference from the publisher to the delegate to prevent garbage collecting of the subscriber.Meaning that , instead of writing : I would write : The main use-case I have in mind for that class is for a few collection classes ( subscribers ) that have a lifetime that I can only barely control . ( However one of these cases happen in WPF data binding so it would be a perfect candidate for using the recommended Weak Event infrastructure ) . public class WeakEventDelegate < TEventArgs > where TEventArgs : EventArgs { private readonly WeakReference handlerReference ; public WeakEventDelegate ( Action < object , TEventArgs > handler ) { handlerReference = new WeakReference ( handler ) ; } public void Handle ( object source , TEventArgs e ) { Action < object , TEventArgs > unwrappedHandler = ( Action < object , TEventArgs > ) handlerReference.Target ; if ( unwrappedHandler ! = null ) { unwrappedHandler.Invoke ( source , e ) ; } } } void subscribe ( ) { publisher.RaiseCustomEvent += this.HandleCustomEvent ; } private readonly WeakDelegate < CustomEventArgs > _customHandler = new WeakDelegate < CustomEventArgs > ( this.HandleCustomEvent ) ; void subscribe ( ) { publisher.RaiseCustomEvent += _customHandler.Handle ; }",WeakEventDelegate implementation - feedback request "C_sharp : I 'm trying to use a native library to modify the contents of a byte array ( actually uint16 array ) . I have the array in Unity ( C # ) and a native library in C++.I 've tried a couple of things , the best I could manage is successfully calling into the native code and being able to return a boolean back to C # . The problem comes when I pass an array and mutate it in C++ . No matter what I do , the array appears unmodified in C # .Here is what I have on the Unity side : The Unity project has a postprocessing.aar in Plugins/Android and is enabled for the Android build platform.I have a JNI layer in Java ( which is called successfully ) : The Java code above calls this code in C++.The core C++ function PostprocessNative seems to also be called successfully ( verified by the return value ) , but all modifications to the data_out are not reflected back in Unity.I expect all values of the short [ ] to be 10 , but they are whatever they were before calling JNI.Is this a correct way to pass a Unity array of shorts into C++ for modification ? // In Update ( ) .using ( AndroidJavaClass processingClass = new AndroidJavaClass ( `` com.postprocessing.PostprocessingJniHelper '' ) ) { if ( postprocessingClass == null ) { Debug.LogError ( `` Could not find the postprocessing class . `` ) ; return ; } short [ ] dataShortIn = ... ; // My original data . short [ ] dataShortOut = new short [ dataShortIn.Length ] ; Buffer.BlockCopy ( dataShortIn , 0 , dataShortOut , 0 , dataShortIn.Length ) ; bool success = postprocessingClass.CallStatic < bool > ( `` postprocess '' , TextureSize.x , TextureSize.y , dataShortIn , dataShortOut ) ; Debug.Log ( `` Processed successfully : `` + success ) ; } public final class PostprocessingJniHelper { // Load JNI methods static { System.loadLibrary ( `` postprocessing_jni '' ) ; } public static native boolean postprocess ( int width , int height , short [ ] inData , short [ ] outData ) ; private PostprocessingJniHelper ( ) { } } extern `` C '' { JNIEXPORT jboolean JNICALL POSTPROCESSING_JNI_METHOD_HELPER ( postprocess ) ( JNIEnv *env , jclass thiz , jint width , jint height , jshortArray inData , jshortArray outData ) { jshort *inPtr = env- > GetShortArrayElements ( inData , nullptr ) ; jshort *outPtr = env- > GetShortArrayElements ( outData , nullptr ) ; jboolean status = false ; if ( inPtr ! = nullptr & & outPtr ! = nullptr ) { status = PostprocessNative ( reinterpret_cast < const uint16_t * > ( inPtr ) , width , height , reinterpret_cast < uint16_t * > ( outPtr ) ) ; } env- > ReleaseShortArrayElements ( inData , inPtr , JNI_ABORT ) ; env- > ReleaseShortArrayElements ( outData , outPtr , 0 ) ; return status ; } bool PostprocessNative ( const uint16_t* data_in , int width , int height , uint16_t* data_out ) { for ( int y = 0 ; y < height ; ++y ) { for ( int x = 0 ; x < width ; ++x ) { data_out [ x + y * width ] = 10 ; } } // Changing the return value here is correctly reflected in C # . return false ; }",Passing byte array from Unity to Android ( C++ ) for modification "C_sharp : Here are two IEnumerable.I want to check whether a value in existedThings exist in thingsToSave.O.K . I can do that with 3 line code.But , It looks dirty.I just want to know if there is better solution . IEnumerable < String > existedThings = from mdinfo in mdInfoTotal select mdinfo.ItemNo ; IEnumerable < String > thingsToSave = from item in lbXReadSuccess.Items.Cast < ListItem > ( ) select item.Value ; bool hasItemNo ; foreach ( string itemNo in existedThings ) hasItemNo= thingsToSave.Contains ( itemNo ) ;",check existense between two IEnumerable "C_sharp : Suppose you have an array of 1000 random integer numbers and you need to loop over it to find the number 68 for example.Using the new Parallel.For on a quad core CPU would improve speed considerably , making each core to work only 250 array items.The question is : is it possible to interrupt the Parallel.For loop when the following condition is met ? Thanks . if ( integerArray [ i ] == 68 ) break ;",Parallel.For interruption "C_sharp : I want to find usages of a method with Roslyn . I managed to do this for usages by code in the .cs files . Additionally I want to analyze JavaScript files included in the solution . I know that Roslyn can not analyze syntax or sematics of JavaScript , so I only want to search for textural occurrencies of my method 's name in all .js files.I retrieve all files ( documents ) like this : But Documents only contains .cs files . Is there a way to get also .js files or do I have to get the folder with project.FilePath and get the files with the old File API , which could cause problems because not necessarily all files in the folder must have been added to the project etc . ? Edit : Also AdditionalFiles does not hold any file . foreach ( Project pr in solution.Projects ) { foreach ( Document doc in pr.Documents ) { // my js-file is not included } }",Get other files than .cs with Roslyn "C_sharp : Does anyone know of an appropriate replacement for this handmade if/then/else operator for reactive extensions ( .Net / C # ) ? Usage example ( assuming numbers is of type IObservable < int > : public static IObservable < TResult > If < TSource , TResult > ( this IObservable < TSource > source , Func < TSource , bool > predicate , Func < TSource , IObservable < TResult > > thenSource , Func < TSource , IObservable < TResult > > elseSource ) { return source .SelectMany ( value = > predicate ( value ) ? thenSource ( value ) : elseSource ( value ) ) ; } numbers.If ( predicate : i = > i % 2 == 0 , thenSource : i = > Observable .Return ( i ) .Do ( _ = > { /* some side effects */ } ) .Delay ( TimeSpan.FromSeconds ( 1 ) ) , // some other operations elseSource : i = > Observable .Return ( i ) .Do ( _ = > { /* some other side effects */ } ) ) ;",Is there an if/then/else operator for observables in c # available ? "C_sharp : In my user control I have this property : And since another window , I´m trying to set a value for the last user control : And that window in load contains : But in XAML code , binding it is n't working . Do n't pass the data . What am I wrong ? public static DependencyProperty FooListProperty = DependencyProperty.Register ( `` FooList '' , typeof ( List < Problem > ) , typeof ( ProblemView ) ) ; public List < Problem > FooList { get { return ( List < Problem > ) GetValue ( FooListProperty ) ; } set { SetValue ( FooListProperty , value ) ; } } protected override void OnPropertyChanged ( DependencyPropertyChangedEventArgs e ) { base.OnPropertyChanged ( e ) ; if ( e.Property == FooListProperty ) { // Do something } } < local : ProblemView HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' FooList= '' { Binding list } '' / > public List < Problem > list ; private void Window_Loaded ( object sender , RoutedEventArgs e ) { // Some processes and it sets to list field list = a ; }",How can I bind a field to a user control "C_sharp : I am trying to sort a list of items according to the following ( simplified ) rules : I 'll each item has the following properties : ParentID is a self-join ForeignKey to Id . If an item has a ParentId , then the parent will also exist in the list.I need to sort the list so that all items which have a parent , appear immediately after their parent . Then all items will be sorted by Name.So if I had the following : Then I would want them sorted as follows : Ids : 2 , 21 , 22 , 1 , 12 , 11At the moment the best I can come up with is to sort by Name first , and then Group by ParentId as follows : My starting plan was then as follows : ( in non functioning code ) However , parentGroup is not so this does not work.I feel there is an simpler , more concise way of achieving this , but currently it 's eluding me - can anyone help ? Id ( int ) , ParentId ( int ? ) , Name ( string ) Id : 1 , ParentId : null , Name : Pi Id : 2 , ParentId : null , Name : Gamma Id : 11 , ParentId : 1 , Name : Charlie Id : 12 , ParentId : 1 , Name : Beta Id : 21 , ParentId : 2 , Name : Alpha Id : 22 , ParentId : 2 , Name : Omega var sortedItems = itemsToSort.OrderBy ( x= > x.Name ) .GroupBy ( x= > x.ParentId ) ; var finalCollection = new List < Item > var parentGroup = sortedItems.Where ( si = > si.Key == null ) ; foreach ( parent in parentGroup ) { finalCollection.Add ( parent ) ; foreach ( child in sortedItems.Where ( si = > si.Key == parent.Id ) { finalCollection.Add ( child ) ; } } IEnumerable < Item >",Complex LINQ sorting with groups "C_sharp : I have a scenario where I have 3 types of products in a database and all products have their own separate tables ( e.g . Product1 , Product2 and Product3 ) . Almost all of the product tables have the same schema . I have the requirement to get separate types of products in different tables.I currently have 3 methods to get the products , one for each product type : While calling products I have a WebApi method which accepts product type and calls the respective methods : Does Entity Framework have any way that I can select a table with only one method ? public List < Product1 > GetProduct1Data ( ) { // ... . context.Product1.Where ( .. ) .Tolist ( ) ; } public List < Product2 > GetProduct2Data ( ) { // ... . context.Product2.Where ( .. ) .Tolist ( ) ; } public List < Product3 > GetProduct3Data ( ) { // ... . context.Product3.Where ( .. ) .Tolist ( ) ; } public IHttpActionResult GetProducts ( ProductType product ) { /// ... . // Ii have to call repositories according to product parameter }",Common query for multiple similar entity types in Entity Framework "C_sharp : I am using the Umbraco WYSIWYG datatype , and I noticed when using the HTML window to input HTML , that an A tagWill end up being : This also happens if the link is just www.something.com and not Http : // . It will also start with a ( / ) .As a bonus side affect , if it does have http : // in the link , the forward slash will change this link fromtoThe WYSIWYG is the TinyMCE WYSIWYG . Why does it do this , and what can I do to change it ? < a href= '' http : //www.someurl.com '' > link < /a > < a href= '' /http ... .. > link < /a > http : // /http : / ( single forward slash like its a path )",Why does Umbraco WYSIWYG place forward slash in front of a tag link ? C_sharp : So i have the following c # code snippet : If you notice carefully you will notice i am missing `` ; `` Here is what happens when i hover over the little red squiggly line : My question is : How can i show the `` ; expected `` by using the keyboard and without hovering over the squiggly line with the cursor ? Thanks ! var accountModel = new AccountModel { Email = `` iDontExist @ gmail.com '' },visual studio keyboard shortcut for error description "C_sharp : SituationWell , as you can see below , I have a main App , creating a thread , which creates a bunch of background workers . When the RunWorkerCompleted is fired on some BG worker , I sometimes end up dropping an Unhandled Exception , ( for a reason I have clearly pinpointed , but this is not the matter ) .So the Logs clearly show that my UnhandledException handler is entered and reports the exception.I know I am deliberately misusing the OnUnhandledException by stopping the App from exiting , using a Console.Read ( ) . I did it on purpose because I want a human intervention/check before terminating the app.However , what was supposed just to be a `` pause '' before manual exit turned out to keep the App alive , ie , the Thread is still generating workers , and running as if nothing happened.Even Weirder : The UnhandledException is still being dropped from time to time when it happens again . And it is logged each time , behaving just as if it was a plain ol ' try catch . ( This was the default behaviour before .Net 3.0 ) QuestionSo , why is everything happening as if the UnhandledException was not thrown , and the thread and BG 's keeping running as if nothing happened ? My guess is that as long as the OnUnhandledException handler is not done , and the App is still alive , all running threads that are still alive keep on living in a free world and doing their job.This gives me a bad temptation , which is to keep this design , as a try/catch to unHandled Exception . I know this is not a tidy idea , as you never know if the exception is serious or something that could be skipped . However , I would really prefer my program to keep running all day and watch the log report / mail alerts and decide for myself if it needs to be restarted or not.As this is a server application that needs to be running 24/7 I wanted to avoid ill-timed and repetitive interruptions due to minor still unhandled exceptions.The biggest advantage to that being that the server program keeps running while we are tracking down unhandled exceptions one by one and deliver patches to handle them as they occur.Thank you for your patience , and please feel free to give feedback.PS : No , I did not smoke pot . public static void OnUnhandledException ( object sender , UnhandledExceptionEventArgs e ) { Logger.log ( `` UNHANDLED EXCEPTION : `` + e.ExceptionObject.ToString ( ) ) ; Mail.Sendmail ( `` ADMIN ALERT : `` + e.ExceptionObject.ToString ( ) ) ; Console.Read ( ) ; // Yes , this is an ungraceful trick , I confess . }",Hijacking UnhandledException to keep Multi-Threaded Application Running "C_sharp : I am puzzled by the following behavior of Nullable types : Now , Nullable.GetUnderlyingType ( test.value ) returns the underlying Nullable type , which is int.However , if I try to obtain the field type like thisand I invokeit returns a System.Nullable [ System.Int32 ] type . So that means the method Nullable.GetUnderlyingType ( ) has a different behavior depending on how you obtain the member type . Why is that so ? If I simply use test.value how can I tell that it 's Nullable without using reflection ? class TestClass { public int ? value = 0 ; } TestClass test = new TestClass ( ) ; FieldInfo field = typeof ( TestClass ) .GetFields ( BindingFlags.Instance | BindingFlags.Public ) [ 0 ] ; Nullable.GetUnderlyingType ( field.FieldType ) .ToString ( )",Nullable properties vs. Nullable local variables "C_sharp : I have declared datatable inside using block which calls the Dispose method at the end of the scope.But in reflector , datatable doesnt seens to have Dispose functionHow is that ? using ( DataTable dt = Admin_User_Functions.Admin_KitItems_GetItems ( ) ) { ... }",Datatable inside using ? "C_sharp : I am working on debugging an application that seems to leak memory like crazy ; most of it seems due to fragmentation from pinned objects ( downloaded image data in a WriteableBitmap ) . However , I am not intentionally using GC.Handle or anything like it . All I do is store the data in a MemoryStream , and reference it like that . What operations pin data in memory , that do n't explicitly say so ? Also , how can I find what pinned it using WinDbg ? EDIT : Per request , here is a ( slightly sanitized ) output of one of a ! GCRoot on a System.Int32 array adjacent to a large block of free memory . This is representative of all of the large free blocks.EDIT 2 : After spending time with my new friends WinDbg and SOS , I found that WriteableBitmaps AND MemoryStream objects , are both 'pinned ' , and should be allocated carefully to prevent memory fragmentation . Read the article from the accepted answer for an explanation as to why that needs to be done . DOMAIN ( 1AC72358 ) : HANDLE ( Pinned ) :72c12f8 : Root : 174c5e20 ( System.Object [ ] ) - > 16533060 ( Project.ProjectParts.PartContainer ) - > 167fe554 ( Project.ProjectParts.Part.PartActivity ) - > 167d21d8 ( Project.ProjectParts.Sprites.Graphic ) - > 16770f28 ( System.Windows.Controls.Canvas ) - > 16770e1c ( System.Windows.Controls.Canvas ) - > 16770ee4 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 1680e778 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 16770f9c ( System.Windows.Controls.Canvas ) - > 16819114 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 16819160 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 16818df4 ( System.Windows.Controls.Canvas ) - > 16818e58 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 16819f10 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 168194c4 ( System.Windows.Controls.Canvas ) - > 16819528 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 16819574 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 16819370 ( System.Windows.Controls.Image ) - > 21c82138 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 21c82184 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 168195dc ( System.Windows.Media.Imaging.WriteableBitmap ) - > 21c7ce2c ( System.Int32 [ ] ) DOMAIN ( 1AC72358 ) : HANDLE ( AsyncPinned ) :72c1dfc : Root : 166bae48 ( System.Threading.OverlappedData ) - > 1654d448 ( System.Threading.IOCompletionCallback ) - > 1654c29c ( System.Net.Sockets.SocketAsyncEventArgs ) - > 1654bad4 ( System.Net.Sockets.Socket+StaticConnectAsyncState ) - > 1654ba40 ( System.Net.Sockets.SocketAsyncEventArgs ) - > 1654b684 ( System.ServiceModel.Channels.SocketConnectionInitiator+ConnectAsyncResult ) - > 1654b414 ( System.ServiceModel.Channels.ConnectionPoolHelper+EstablishConnectionAsyncResult ) - > 1654b3b0 ( System.ServiceModel.Channels.ClientFramingDuplexSessionChannel+OpenAsyncResult ) - > 1654b380 ( System.ServiceModel.Channels.CommunicationObject+OpenAsyncResult ) - > 1654b330 ( System.ServiceModel.Channels.CommunicationObject+OpenAsyncResult ) - > 1654b0f4 ( System.ServiceModel.Channels.ServiceChannel+SendAsyncResult ) - > 1654b070 ( System.ServiceModel.ClientBase ` 1+AsyncOperationContext [ [ Cassandra.Common.WCF.IAsyncWcfRequestProcessor , Cassandra.Common.Silverlight ] ] ) - > 1654b05c ( System.ComponentModel.AsyncOperation ) - > 1654b04c ( Project.Common.IoC.InvokeAsyncCompletedEventRequestsArgs ) - > 1654afec ( System.Action ` 1 [ [ Project.Common.IoC.ProcessRequestsAsyncCompletedArgsEx , Project.Common.SL ] ] ) - > 1654afc8 ( Project.Common.IoC.AsyncRequestDispatcherEx+ < > c__DisplayClass1 ) - > 1654afa0 ( Project.Common.IoC.NetResponseReceiver ) - > 1653408c ( System.Action ` 2 [ [ Cassandra.Common.ExceptionInfo , Cassandra.Common.Silverlight ] , [ Cassandra.Common.ExceptionType , Cassandra.Common.Silverlight ] ] ) - > 16533ffc ( Project.ProjectParts.ILE.Services.EngineProxyService+ < > c__DisplayClass5 ) - > 16533fdc ( System.Action ` 1 [ [ Cassandra.Common.ReceivedResponses , Cassandra.Common.Silverlight ] ] ) - > 16533fbc ( Project.ProjectParts.ILE.Services.IEngineProxyExtensions+ < > c__DisplayClass1 ` 2 [ [ Project.Services.RequestsAndResponses.ListMediaServersByTokenRequest , Project.Services.RequestsAndResponses.Silverlight ] , [ Project.Services.RequestsAndResponses.ListInstitutionMediaServersResponse , Project.Services.RequestsAndResponses.Silverlight ] ] ) - > 16533f9c ( System.Action ` 1 [ [ Project.Services.RequestsAndResponses.ListInstitutionMediaServersResponse , Project.Services.RequestsAndResponses.Silverlight ] ] ) - > 1650a2a0 ( Project.ProjectParts.ILE.MainPage ) - > 1674ea0c ( Project.ProjectParts.ActivityTimer ) - > 165330a4 ( Project.ProjectParts.PauseManager ) - > 165330bc ( System.Collections.Generic.List ` 1 [ [ Project.ProjectParts.IPausable , ActivityFramework ] ] ) - > 166a8610 ( System.Object [ ] ) - > 167ca858 ( Project.ProjectParts.ActivityTimer ) - > 167ca838 ( Project.ProjectParts.ActivityTimerEventHandler ) - > 16533060 ( Project.ProjectParts.PartContainer ) - > 167fe554 ( Project.ProjectParts.Part.PartActivity ) - > 167d21d8 ( Project.ProjectParts.Sprites.Graphic ) - > 16770f28 ( System.Windows.Controls.Canvas ) - > 16770e1c ( System.Windows.Controls.Canvas ) - > 16770ee4 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 1680e778 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 16770f9c ( System.Windows.Controls.Canvas ) - > 16819114 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 16819160 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 16818df4 ( System.Windows.Controls.Canvas ) - > 16818e58 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 16819f10 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 168194c4 ( System.Windows.Controls.Canvas ) - > 16819528 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 16819574 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 16819370 ( System.Windows.Controls.Image ) - > 21c82138 ( System.Collections.Generic.Dictionary ` 2 [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] ) - > 21c82184 ( System.Collections.Generic.Dictionary ` 2+Entry [ [ MS.Internal.IManagedPeerBase , System.Windows ] , [ System.Object , mscorlib ] ] [ ] ) - > 168195dc ( System.Windows.Media.Imaging.WriteableBitmap ) - > 21c7ce2c ( System.Int32 [ ] ) DOMAIN ( 1AC72358 ) : HANDLE ( Pinned ) :72c2b18 : Root : 21c7ce2c ( System.Int32 [ ] )",What can `` Pin '' an object in memory in Silverlight ? "C_sharp : I am following the documentation here Setting Up for Microsoft C # Development and at this step Building the C # vSphere DLLs I get the following in Developer Command Prompt : Looking at build.bat it looks like it is failing on this line : If I run csc /t : library /out : Vim25Service.dll VimService.cs VimServiceSerializers.cs manually i get the following : I also tried with VS2017 : A behavior to note , on VimServiceSerializers.cs ( # # # # # , # # ) the line and column are different every time.Googling error CS8078 , found it is an issue with the compiler running out of stack space . https : //stackoverflow.com/a/8160109/6656422How do I successfully compile VmWare 's code ? C : \Users\user\Downloads\VMware-vSphereSDK-6.5.0-4571253\SDK\vsphere-ws\dotnet\bin > build.bat 1 file ( s ) copied.Fixing HttpNfcLeaseInfo type , adding missing leaseState propertyGenerating VimService.csMicrosoft ( R ) Service Model Metadata Tool [ Microsoft ( R ) Windows ( R ) Communication Foundation , Version 4.6.1055.0 ] Copyright ( c ) Microsoft Corporation . All rights reserved.Generating files ... C : \Users\user\Downloads\VMware-vSphereSDK-6.5.0-4571253\SDK\vsphere-ws\dotnet\bin\VimService.csCompiling original VimService.dllMicrosoft ( R ) Service Model Metadata Tool [ Microsoft ( R ) Windows ( R ) Communication Foundation , Version 4.6.1055.0 ] Copyright ( c ) Microsoft Corporation . All rights reserved.Generating XML serializers ... C : \Users\user\Downloads\VMware-vSphereSDK-6.5.0-4571253\SDK\vsphere-ws\dotnet\bin\VimServiceSerializers.cs 1 file ( s ) copied.Optimizing VimService.cs by stripping serializer hint attributes.Compiling optimized VimService.dllFAILED echo Compiling optimized VimService.dllcsc /t : library /out : Vim25Service.dll VimService.cs VimServiceSerializers.cs > nul || goto ERROR C : \Users\user\Downloads\VMware-vSphereSDK-6.5.0-4571253\SDK\vsphere-ws\dotnet\bin > csc /t : library /out : Vim25Service.dll VimService.cs VimServiceSerializers.csMicrosoft ( R ) Visual C # Compiler version 1.3.1.60616Copyright ( C ) Microsoft Corporation . All rights reserved.VimServiceSerializers.cs ( 32548,98 ) : error CS8078 : An expression is too long or complex to compile C : \Users\user\Downloads\VMware-vSphereSDK-6.5.0-4571253\SDK\vsphere-ws\dotnet\bin > csc /t : library /out : Vim25Service.dll VimService.cs VimServiceSerializers.csMicrosoft ( R ) Visual C # Compiler version 2.0.0.61213Copyright ( C ) Microsoft Corporation . All rights reserved.VimServiceSerializers.cs ( 31372,109 ) : error CS8078 : An expression is too long or complex to compile",Building vSphere DLLs fails with CS8078 : An expression is too long or complex to compile C_sharp : I have the following class : I am trying to specialize the Convert method with concreate types.Currently it just loops recursively in Convert < T > ( ) until a stack overflow occurs . class CrmToRealTypeConverter : IConverter { # region IConverter Members public object Convert < T > ( T obj ) { return Convert ( obj ) ; } # endregion private DateTime ? Convert ( CrmDateTime obj ) { return obj.IsNull == false ? ( DateTime ? ) obj.UserTime : null ; } private int ? Convert ( CrmNumber obj ) { return obj.IsNull == false ? ( int ? ) obj.Value : null ; } private decimal ? Convert ( CrmDecimal obj ) { return obj.IsNull == false ? ( decimal ? ) obj.Value : null ; } private double ? Convert ( CrmDouble obj ) { return obj.IsNull == false ? ( double ? ) obj.Value : null ; } private float ? Convert ( CrmFloat obj ) { return obj.IsNull == false ? ( float ? ) obj.Value : null ; } private decimal ? Convert ( CrmMoney obj ) { return obj.IsNull == false ? ( decimal ? ) obj.Value : null ; } private bool ? Convert ( CrmBoolean obj ) { return obj.IsNull == false ? ( bool ? ) obj.Value : null ; } },Why overloading does not occur ? "C_sharp : Let us start with a class definition for the sake of example : Now let 's assume I have a List < Person > called people containing 3 objects : What I am looking for is some way to retrieve the following single Person object : where fields which are the same in all objects retain their value while fields which have multiple values are replaced with some invalid value.My first thought consisted of : Unfortunately , the real business object has many more members than four and this is both tedious to write and overwhelming for someone else to see for the first time.I also considered somehow making use of reflection to put these repetitive checks and assignments in a loop : where **member** would be however reflection would allow the retrieval and storage of that particular member ( assuming it is possible ) .While the first solution would work , and the second I am assuming would work , does anyone have a better alternative solution to this problem ? If not , would using reflection as described above be feasible ? public class Person { public string FirstName ; public string LastName ; public int Age ; public int Grade ; } { `` Robby '' , `` Goki '' , 12 , 8 } { `` Bobby '' , `` Goki '' , 10 , 8 } { `` Sobby '' , `` Goki '' , 10 , 8 } { null , `` Goki '' , -1 , 8 } Person unionMan = new Person ( ) ; if ( people.Select ( p = > p.FirstName ) .Distinct ( ) .Count ( ) == 1 ) unionMan.FirstName = people [ 0 ] .FirstName ; if ( people.Select ( p = > p.LastName ) .Distinct ( ) .Count ( ) == 1 ) unionMan.LastName = people [ 0 ] .LastName ; if ( people.Select ( p = > p.Age ) .Distinct ( ) .Count ( ) == 1 ) unionMan.Age = people [ 0 ] .Age ; if ( people.Select ( p = > p.Grade ) .Distinct ( ) .Count ( ) == 1 ) unionMan.Grade = people [ 0 ] .Grade ; string [ ] members = new string [ ] { `` FirstName '' , `` LastName '' , `` Age '' , `` Grade '' } ; foreach ( string member in members ) { if ( people.Select ( p = > p.**member** ) .Distinct ( ) .Count ( ) == 1 ) unionMan . **member** = people [ 0 ] . **member** ; }",Union of Two Objects Based on Equality of Their Members "C_sharp : I 'm populating a TreeView with nodes based on an XML document . However , it seems that when I go to put an attribute 's value into a textbox , it loses it 's newlines/carriage returns/tabs.I start by adding a bunch of nodes with `` task names '' . Each task has one or more queries in the XML document . Like so : < Tasks > < Task name= '' aTaskName '' > < Queries > < add Query= '' a long string with tabs and newlines and such '' / > < /Queries > < /Task > ... < /Tasks > Later in a node click event : The Query attribute value contains a long SQL query with newlines , tabs , etc . But none of that seems to show up in the ( multiline ) text box , despite all my shouting at Visual Studio . What am I doing wrong ? Also , var doc = XDocument.Load ( filename , LoadOptions.PreserveWhitespace ) ; does n't seem to work either . void PopulateQueries ( XDocument doc , TreeView tree ) { foreach ( TreeNode node in tree.Nodes ) { var taskName = node.Text ; var queriesNode = node.Nodes.Add ( `` Queries '' ) ; var queries = doc.Descendants ( `` Tasks '' ) .Descendants ( `` Task '' ) .Where ( d = > d.Attribute ( `` name '' ) .Value == taskName ) .Descendants ( `` Queries '' ) .Descendants ( `` add '' ) .ToList ( ) ; for ( int i = 0 ; i < queries.Count ; i++ ) { queriesNode.Nodes.Add ( queries [ i ] .Attribute ( `` Query '' ) .Value , `` query '' + i ) ; } } } void treeView1_NodeMouseClick ( object sender , TreeNodeMouseClickEventArgs e ) { textBoxRaw.Text = string.Empty ; if ( e.Node.Text.StartsWith ( `` query '' ) ) { textBoxRaw.Text = e.Node.Name ; } }",Losing newlines with XDocument "C_sharp : TL ; DR ? Screencast explaining problem : https : //youtu.be/B-Q3T5KpiYkProblemWhen flowing a transaction from a client to a service Transaction.Current becomes null after awaiting a service to service call.Unless of course you create a new TransactionScope in your service method as follows : Why TransactionScopeAsyncFlowOption is n't enabled by default I do n't know , but I do n't like to repeat myself so I figured I 'd always create an inner transactionscope with that option using a custom behavior.Problem UPDATEIt does n't even have to be a service to service call , an await to a local async method also nulls Transaction.Current . To clearify with an exampleAttempted SolutionI created a Message Inspector , implementing IDispatchMessageInspector and attached it as a service behavior , code executes and everyting no problem there , but it does n't have the same effect as declaring the transactionscope in the service method.by looking at the identifiers when debugging I can see that it in fact is the same transaction in the message inspector as in the service butafter the first call , i.e.Transaction.Current becomes null . Same thing if not getting the current transaction from OperationContext.Current in the message inspector as well so it 's unlikely that is the problem.QuestionIs it even possible to accomplish this ? It appears like the only way is to declare a TransactionScope in the service method , that is : with the following service contract it 's obvious that we get an exception on the second service call if transaction.current became null inbetween [ OperationBehavior ( TransactionScopeRequired = true ) ] public async Task CallAsync ( ) { using ( var scope = new TransactionScope ( TransactionScopeAsyncFlowOption.Enabled ) ) { await _service.WriteAsync ( ) ; await _service.WriteAsync ( ) ; scope.Complete ( ) ; } } [ OperationBehavior ( TransactionScopeRequired = true ) ] public async Task CallAsync ( ) { await WriteAsync ( ) ; // Transaction.Current is now null await WriteAsync ( ) ; } public class TransactionScopeMessageInspector : IDispatchMessageInspector { public object AfterReceiveRequest ( ref Message request , IClientChannel channel , InstanceContext instanceContext ) { var transactionMessage = ( TransactionMessageProperty ) OperationContext.Current.IncomingMessageProperties [ `` TransactionMessageProperty '' ] ; var scope = new TransactionScope ( transactionMessage.Transaction , TransactionScopeAsyncFlowOption.Enabled ) ; return scope ; } public void BeforeSendReply ( ref Message reply , object correlationState ) { var transaction = correlationState as TransactionScope ; if ( transaction ! = null ) { transaction.Complete ( ) ; transaction.Dispose ( ) ; } } } await _service_WriteAsync ( ) ; public async Task CallAsync ( ) { var scope = new TransactionScope ( TransactionScopeAsyncFlowOption.Enabled ) ; await _service.WriteAsync ( ) ; await _service.WriteAsync ( ) ; scope.Complete ( ) ; } [ OperationContract , TransactionFlow ( TransactionFlowOption.Mandatory ) ] Task WriteAsync ( ) ;","Is it possible to create a TransactionScope in a Custom WCF Service Behavior ? ( async , await , TransactionScopeAsyncFlowOption.Enabled )" "C_sharp : To simply illustrate my dilemma , let say that I have the following code : In order to perform its duty , class B have to react on A 's PropertyChanged event but also is capable of alternating that property by itself in certain circumstances . Unfortunately , also other objects can interact with the Property.I need a solution for a sequential flow . Maybe I could just use a variable in order to disable an action : Are there a better approaches ? Additional considerationsWe are unable to change A.A is sealed.There are also other parties connected to the PropertyChanged event and I do n't know who their are . But when I update the Property from B , they should n't be also notified . But I 'm unable to disconnect them from the event because I do n't know them.What if also more threads can interact with the Property in the mean time ? The more bullets solved , the better.Original problemMy original problem is a TextBox ( WPF ) that I want to complement depending on its content and focus . So I need to react on TextChanged event and I also need to omit that event if its origin is derived from my complements . In some cases , other listeners of a TextChanged event should n't be notified . Some strings in certain state and style are invisible to others . class A { // May be set by a code or by an user . public string Property { set { PropertyChanged ( this , EventArgs.Empty ) ; } } public EventHandler PropertyChanged ; } class B { private A _a ; public B ( A a ) { _a = a ; _a.PropertyChanged += Handler ; } void Handler ( object s , EventArgs e ) { // Who changed the Property ? } public void MakeProblem ( ) { _a.Property = `` make a problem '' ; } } bool _dontDoThis ; void Handler ( object s , EventArgs e ) { if ( _dontDoThis ) return ; // Do this ! } public void MakeProblem ( ) { _dontDoThis = true ; _a.Property = `` make a problem '' ; _dontDoThis = false ; }",A design pattern to disable event handling C_sharp : I have the following setup and it seems that my object can not be converted to the generic type . While it is actually the base class . Why does n't this work ? It seems so logical to me . public class AList < T > where T : A { void DoStuff ( T foo ) { } void CallDoStuff ( ) { DoStuff ( new A ( ) ) ; // ERROR : Can not convert A to T } } public class A { },Call generics with base class gives can not convert from base class to T "C_sharp : I tried to run a simple example on the cancellation of a task like the one belowI expected that Console.WriteLine ( `` Task 2 cancelled ? { 0 } '' , task2.IsCanceled ) ; would print ** '' Task 2 cancelled ? True '' ** , but it printed `` False '' .Do you know what happened ? Is that the expected behaviour ? Thanks.EDIT : to ensure that the task has n't completed before the cancellation request is called . I added the Console.ReadLine ( ) . CancellationTokenSource tokenSource2 = new CancellationTokenSource ( ) ; CancellationToken token2 = tokenSource2.Token ; Task task2 = new Task ( ( ) = > { for ( int i = 0 ; i < int.MaxValue ; i++ ) { token2.ThrowIfCancellationRequested ( ) ; Thread.Sleep ( 100 ) ; Console.WriteLine ( `` Task 2 - Int value { 0 } '' , i ) ; } } , token2 ) ; task2.Start ( ) ; Console.WriteLine ( `` Press any key to cancel the task '' ) ; Console.ReadLine ( ) ; tokenSource2.Cancel ( ) ; Console.WriteLine ( `` Task 2 cancelled ? { 0 } '' , task2.IsCanceled ) ;",Cancellation of a task "C_sharp : I´m writing a C # ( .NET 4.5 ) application that is used to aggregate time based events for reporting purposes . To make my query logic reusable for both realtime and historical data I make use of the Reactive Extensions ( 2.0 ) and their IScheduler infrastructure ( HistoricalScheduler and friends ) .For example , assume we create a list of events ( sorted chronologically , but they may coincide ! ) whose only payload ist their timestamp and want to know their distribution across buffers of a fixed duration : Running this code results in a System.StackOverflowException with the following stack trace ( it´s the last 3 lines all the way down ) : Ok , the problem seems to come from my use of Observable.Generate ( ) , depending on the list size ( num ) and regardless of the choice of scheduler.What am I doing wrong ? Or more generally , what would be the preferred way to create an IObservable from an IEnumerable of events that provide their own timestamps ? const int num = 100000 ; const int dist = 10 ; var events = new List < DateTimeOffset > ( ) ; var curr = DateTimeOffset.Now ; var gap = new Random ( ) ; var time = new HistoricalScheduler ( curr ) ; for ( int i = 0 ; i < num ; i++ ) { events.Add ( curr ) ; curr += TimeSpan.FromMilliseconds ( gap.Next ( dist ) ) ; } var stream = Observable.Generate < int , DateTimeOffset > ( 0 , s = > s < events.Count , s = > s + 1 , s = > events [ s ] , s = > events [ s ] , time ) ; stream.Buffer ( TimeSpan.FromMilliseconds ( num ) , time ) .Subscribe ( l = > Console.WriteLine ( time.Now + `` : `` + l.Count ) ) ; time.AdvanceBy ( TimeSpan.FromMilliseconds ( num * dist ) ) ; mscorlib.dll ! System.Threading.Interlocked.Exchange < System.IDisposable > ( ref System.IDisposable location1 , System.IDisposable value ) + 0x3d bytes System.Reactive.Core.dll ! System.Reactive.Disposables.SingleAssignmentDisposable.Dispose ( ) + 0x37 bytes System.Reactive.Core.dll ! System.Reactive.Concurrency.ScheduledItem < System.DateTimeOffset > .Cancel ( ) + 0x23 bytes ... System.Reactive.Core.dll ! System.Reactive.Disposables.AnonymousDisposable.Dispose ( ) + 0x4d bytes System.Reactive.Core.dll ! System.Reactive.Disposables.SingleAssignmentDisposable.Dispose ( ) + 0x4f bytes System.Reactive.Core.dll ! System.Reactive.Concurrency.ScheduledItem < System.DateTimeOffset > .Cancel ( ) + 0x23 bytes ...",Why does Observable.Generate ( ) throw System.StackOverflowException ? "C_sharp : The MSDN gives this code example in the article on the Func Generic Delegate : I understand what all this is doing . What I do n't understand is thebit . Surely that 's not needed ? If you leave it out and just havethen you still get an IEnumerable back that contains the same results , and the code prints the same thing.Am I missing something , or is the example misleading ? Func < String , int , bool > predicate = ( str , index ) = > str.Length == index ; String [ ] words = { `` orange '' , `` apple '' , `` Article '' , `` elephant '' , `` star '' , `` and '' } ; IEnumerable < String > aWords = words.Where ( predicate ) .Select ( str = > str ) ; foreach ( String word in aWords ) Console.WriteLine ( word ) ; Select ( str = > str ) IEnumerable < String > aWords = words.Where ( predicate ) ;",Why does this MSDN example for Func < > delegate have a superfluous Select ( ) call ? "C_sharp : I have a question . Is it possible to force Entity Framework to make one instance of class instead of ( for example ) IEnumerable ? In my database , i want to have only one Farm instead of Farms . My Farm have all other List in it that i mentioned in my DBContext : And my Farm class , that is a Singleton ( class with private constructor only with GetInstance ( ) method ) : So how to make one Farm in whole database in Code First EntityFramework Core ? EDITMaybe i wont 100 % accurate with my question . How to get single instance of Farm every time , i call a context ? For example , i have a GET function : Can i call my Farm.GetFarm ( ) = > this.farm from DBContext ? public class FarmDbContext : DbContext { public FarmDbContext ( DbContextOptions < FarmDbContext > options ) : base ( options ) { } public DbSet < Farm > Farms { get ; set ; } //i want to have one instance of farm public DbSet < Machine > Machines { get ; set ; } public DbSet < Stable > Stables { get ; set ; } public DbSet < Worker > Workers { get ; set ; } public DbSet < Cultivation > Cultivations { get ; set ; } } public class Farm { [ Key ] public int Id { get ; set ; } public string Name { get ; set ; } public virtual List < Stable > Stables { get ; set ; } public virtual List < Machine > Machines { get ; set ; } public virtual List < Worker > Workers { get ; set ; } public virtual List < Cultivation > Cultivations { get ; set ; } public Farm GetFarm ( ) = > farm ; private Farm farm ; private Farm ( ) { } } private readonly FarmDbContext _context ; public FarmController ( FarmDbContext context ) = > _context = context ; // GET : api/Farm [ HttpGet ] public IActionResult GetFarms ( ) = > Ok ( _context.Farms.SingleOrDefault ( ) ) ;",Entity Framework Core single object instead of List C_sharp : I want to figure out about singleton pattern designs . I want to create seperated instances for per thread from my singleton class . So I provided two designs below.It is WorkingIt is not working ( Throwing NullReferenceException and instance is not being created . ) I am really wondering why an instance is not created for second design . Can anybody explain that please ? class Program { static void Main ( string [ ] args ) { Task.Factory.StartNew ( ( ) = > Console.WriteLine ( SingletonClass.Instance.GetHashCode ( ) ) ) ; Task.Factory.StartNew ( ( ) = > Console.WriteLine ( SingletonClass.Instance.GetHashCode ( ) ) ) ; Console.ReadLine ( ) ; } } public sealed class SingletonClass { [ ThreadStatic ] private static SingletonClass _instance ; public static SingletonClass Instance { get { if ( _instance == null ) { _instance = new SingletonClass ( ) ; } return _instance ; } } private SingletonClass ( ) { } } class Program { static void Main ( string [ ] args ) { Task.Factory.StartNew ( ( ) = > Console.WriteLine ( SingletonClass.Instance.GetHashCode ( ) ) ) ; Task.Factory.StartNew ( ( ) = > Console.WriteLine ( SingletonClass.Instance.GetHashCode ( ) ) ) ; Console.ReadLine ( ) ; } } public sealed class SingletonClass { [ ThreadStatic ] private static SingletonClass _instance = new SingletonClass ( ) ; public static SingletonClass Instance { get { return _instance ; } } private SingletonClass ( ) { } },C # Singleton Pattern Designs for ThreadStatic "C_sharp : where param1 is Type1 and param2 is Type2It seems to me this is exactly the same asBut the first version is not allowed by the C # compiler . Why ? Is this another one of those time vs effort/payback things ? Is n't this just plain inconsistent ? ( [ MyCustomAttribute ( ... ) ] param1 , param2 ) = > { ... private void method blah ( [ MyCustomAttribute ( ... ) ] Type1 param1 , Type2 param2 ) { ...",Custom attribute on parameter of an anonymous lambda "C_sharp : [ Edit - Added analysis from fiddler , added more code to copy over authentication header ] [ Edit - now use FormUrlEncodedContent ] I have a page here : https : //www.cdc.co.nz/products/list.html ? cat=5201 that is password protected via login over here : https : //www.cdc.co.nz/login/The code below allows me to login successfully . However , despite using the same client , I am unable to make a call to the page mentioned above ( 401 Unauthorized ) Fiddler for browser environment : Result : 302Protocol : HTTPSHost : www.cdc.co.nzURL : /login/Raw Request Header Browser Environment : Response Raw Header ( Set-Cookie : PHPSESSID=oh7in7n5pjbkrkng4qwwwn22uaq951 is what I am interested ) in browser environment : Fiddler for HttpClient : Result : 200Protocol : HTTPSHost : www.cdc.co.nzURL : /login/Raw Header in HttpClient environment : Raw Response Header in HttpClient environment ( notice how there is no Set-Cookie header / value here ? ) : AnswerAdding the extra KV pairs ( without even the specification of other unnecessary details ) has now got the code working : ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls ; var baseAddress = new Uri ( `` https : //www.cdc.co.nz '' ) ; var cookieContainer = new CookieContainer ( ) ; using ( var handler = new HttpClientHandler ( ) { CookieContainer = cookieContainer , UseCookies = true } ) using ( HttpClient client = new HttpClient ( handler ) { BaseAddress = baseAddress } ) { HttpResponseMessage response = null ; //Let 's visit the homepage to set initial cookie values Task.Run ( async ( ) = > response = await client.GetAsync ( `` / '' ) ) .GetAwaiter ( ) .GetResult ( ) ; //200 string urlToPost = `` /login/ '' ; var postData = new List < KeyValuePair < string , string > > ( ) ; postData.Add ( new KeyValuePair < string , string > ( `` username '' , `` username '' ) ) ; postData.Add ( new KeyValuePair < string , string > ( `` password '' , `` password '' ) ) ; HttpContent stringContent = new FormUrlEncodedContent ( postData ) ; client.DefaultRequestHeaders.Add ( `` Accept '' , `` text/html , application/xhtml+xml , application/xml ; q=0.9 , image/webp , image/apng , */* ; q=0.8 '' ) ; client.DefaultRequestHeaders.Add ( `` Accept-Encoding '' , `` gzip , deflate , br '' ) ; client.DefaultRequestHeaders.Add ( `` Accept-Language '' , `` en-GB , en-US ; q=0.9 , en ; q=0.8 '' ) ; client.DefaultRequestHeaders.Add ( `` User-Agent '' , `` Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/67.0.3396.99 Safari/537.36 '' ) ; client.DefaultRequestHeaders.Add ( `` Origin '' , `` https : //www.cdc.co.nz '' ) ; client.DefaultRequestHeaders.Add ( `` Upgrade-Insecure-Requests '' , `` 1 '' ) ; client.DefaultRequestHeaders.Add ( `` Connection '' , `` keep-alive '' ) ; client.DefaultRequestHeaders.Add ( `` Host '' , `` www.cdc.co.nz '' ) ; client.DefaultRequestHeaders.Add ( `` Referer '' , `` https : //www.cdc.co.nz/login/ '' ) ; cookieContainer.Add ( baseAddress , new Cookie ( `` _ga '' , `` GA1.3.720299450.1533761418 '' ) ) ; cookieContainer.Add ( baseAddress , new Cookie ( `` _gat_oldTracker '' , `` 1 '' ) ) ; cookieContainer.Add ( baseAddress , new Cookie ( `` _gat '' , `` 1 '' ) ) ; cookieContainer.Add ( baseAddress , new Cookie ( `` _gid '' , `` GA1.3.1011102476.1533761418 '' ) ) ; //Tyler 's suggestion here works ! //cookieContainer.Add ( baseAddress , new Cookie ( `` PHPSESSID '' , `` value from browser login response header '' ) ) ; //Receiving 200 response for the nextline , though it returns a 302 in a browser environment Task.Run ( async ( ) = > response = await client.PostAsync ( urlToPost , stringContent ) ) .GetAwaiter ( ) .GetResult ( ) ; //401 response for the next line Task.Run ( async ( ) = > response = await client.GetAsync ( `` /products/list.html ? cat=5201 '' ) ) .GetAwaiter ( ) .GetResult ( ) ; } POST /login/ HTTP/1.1Host : www.cdc.co.nzConnection : keep-aliveContent-Length : 69Cache-Control : max-age=0Origin : https : //www.cdc.co.nzUpgrade-Insecure-Requests : 1Content-Type : application/x-www-form-urlencodedUser-Agent : Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/67.0.3396.99 Safari/537.36Accept : text/html , application/xhtml+xml , application/xml ; q=0.9 , image/webp , image/apng , */* ; q=0.8Referer : https : //www.cdc.co.nz/login/Accept-Encoding : gzip , deflate , brAccept-Language : en-GB , en-US ; q=0.9 , en ; q=0.8Cookie : _ga=GA1.3.720299450.1533761418 ; _gid=GA1.3.1011102476.1533761418 ; PHPSESSID=p3jn5qqhcul59blum597mp2o41 ; _gat=1 ; _gat_oldTracker=1 HTTP/1.1 302 FoundDate : Thu , 09 Aug 2018 00:51:11 GMTServer : Apache/2.4.7 ( Ubuntu ) X-Powered-By : PHP/5.5.9-1ubuntu4.25Expires : Thu , 19 Nov 1981 08:52:00 GMTCache-Control : no-store , no-cache , must-revalidate , post-check=0 , pre-check=0Pragma : no-cacheSet-Cookie : PHPSESSID=oh7in7n5pjbkrkng4qwwwn22uaq951 < -- -- -- -- Needed in subsequent Request headers to not 401.Location : https : //www.cdc.co.nz/home/news.htmlContent-Length : 0Keep-Alive : timeout=5 , max=100Connection : Keep-AliveContent-Type : text/html GET /login/ HTTP/1.1 Host : www.cdc.co.nz Connection : keep-alive Upgrade-Insecure-Requests : 1 User-Agent : Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/67.0.3396.99 Safari/537.36 Accept : text/html , application/xhtml+xml , application/xml ; q=0.9 , image/webp , image/apng , */* ; q=0.8 Referer : https : //www.cdc.co.nz/home/my-account/ Accept-Encoding : gzip , deflate , br Accept-Language : en-GB , en-US ; q=0.9 , en ; q=0.8 Cookie : _ga=GA1.3.720299450.1533761418 ; _gid=GA1.3.1011102476.1533761418 ; _gat=1 ; _gat_oldTracker=1 ; PHPSESSID=sdjm7r2jge751jo39mkesqnfl6 HTTP/1.1 200 OKDate : Thu , 09 Aug 2018 01:11:14 GMTServer : Apache/2.4.7 ( Ubuntu ) X-Powered-By : PHP/5.5.9-1ubuntu4.25Expires : Thu , 19 Nov 1981 08:52:00 GMTCache-Control : no-store , no-cache , must-revalidate , post-check=0 , pre-check=0Pragma : no-cacheVary : Accept-EncodingKeep-Alive : timeout=5 , max=98Connection : Keep-AliveContent-Type : text/html ; charset=UTF-8Content-Length : 5668 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls ; var baseAddress = new Uri ( `` https : //www.cdc.co.nz '' ) ; using ( HttpClient client = new HttpClient ( ) { BaseAddress = baseAddress } ) { HttpResponseMessage response = null ; //Let 's visit the homepage to set initial cookie values Task.Run ( async ( ) = > response = await client.GetAsync ( `` / '' ) ) .GetAwaiter ( ) .GetResult ( ) ; //200 string urlToPost = `` /login/ '' ; var postData = new List < KeyValuePair < string , string > > ( ) ; postData.Add ( new KeyValuePair < string , string > ( `` username '' , `` username '' ) ) ; postData.Add ( new KeyValuePair < string , string > ( `` password '' , `` password '' ) ) ; postData.Add ( new KeyValuePair < string , string > ( `` returnUrl '' , `` /login/ '' ) ) ; < -- -- - To simulate the browser postData.Add ( new KeyValuePair < string , string > ( `` service '' , `` login '' ) ) ; < -- -- - To simulate the browser HttpContent stringContent = new FormUrlEncodedContent ( postData ) ; //Receiving 200 response for the nextline , though it returns a 302 in a browser environment Task.Run ( async ( ) = > response = await client.PostAsync ( urlToPost , stringContent ) ) .GetAwaiter ( ) .GetResult ( ) ; //200 response now Task.Run ( async ( ) = > response = await client.GetAsync ( `` /products/list.html ? cat=5201 '' ) ) .GetAwaiter ( ) .GetResult ( ) ; }",HttpClient not able to access a page behind a login page C_sharp : Here is part of my modelName is some text filed who is have maximum length of 40 symbols . And in this text field is possible to have few words . My question is is it possible to set maximum length of word in Name property ? For Example is have : `` Motion Detector '' . And I want the word to be maximum 8 symbols . This mean Motion and Detector is need to be less of 8 symbols length . The user ca n't write like `` MotionDetector '' whose length is 12 symbols . public class Sensor { public int Id { get ; set ; } [ Required ] [ MaxLength ( 40 ) ] public string Name { get ; set ; } },How to set maximum length of separated word of string property C # EF "C_sharp : I have 5 to 6 projects . Project A and B use a same file via Linked File . Now , if I use this class in Razor I will get , Because Razor views reference all the dlls in bin . It is referencing the same class from Project A and B . How to tell the Razor during compilation use Project A and not Project B ? The call is ambiguous between the following methods or properties :",Ambiguous class Reference when using Linked File in Different Projects in Razor ? "C_sharp : Let 's say I want to enforce a rule : Everytime you call `` StartJumping ( ) '' in your function , you must call `` EndJumping ( ) '' before you return.When a developer is writing their code , they may simply forget to call EndSomething - so I want to make it easy to remember.I can think of only one way to do this : and it abuses the `` using '' keyword : Is there a better way to do this ? class Jumper : IDisposable { public Jumper ( ) { Jumper.StartJumping ( ) ; } public void Dispose ( ) { Jumper.EndJumping ( ) ; } public static void StartJumping ( ) { ... } public static void EndJumping ( ) { ... } } public bool SomeFunction ( ) { // do some stuff // start jumping ... using ( new Jumper ( ) ) { // do more stuff // while jumping } // end jumping }",Enforcing an `` end '' call whenever there is a corresponding `` start '' call "C_sharp : I have next code : Assert is false . And dates are different for some reason on milliseconds . Why ? ? ? endTime : row [ `` endTime '' ] : WHY ? ? ? DateTime endTime = DateTime.Now.AddDays ( 30 ) ; InsertIntoDatabase ( endTime ) ; var row = Db.SelectRow ( `` select endTime from MyTable Where @ column=myval '' , columnValue ) ; Assert.Equal ( row [ `` endTime '' ] , endTime ) ; // This is false ! Why ? Date { 7/17/2015 12:00:00 AM } System.DateTime Day 17 int DayOfWeek Friday System.DayOfWeek DayOfYear 198 int Hour 1 int Kind Unspecified System.DateTimeKind Millisecond 370 int Minute 21 int Month 7 int Second 27 int Ticks 635726928873700000 long+ TimeOfDay { 01:21:27.3700000 } System.TimeSpan Year 2015 int Date { 7/17/2015 12:00:00 AM } System.DateTime Day 17 int DayOfWeek Friday System.DayOfWeek DayOfYear 198 int Hour 1 int Kind Local System.DateTimeKind Millisecond 371 int Minute 21 int Month 7 int Second 27 int Ticks 635726928873716049 long+ TimeOfDay { 01:21:27.3716049 } System.TimeSpan Year 2015 int",DateTime is not equal "C_sharp : I needed a function that simply checks if a string can be converted to a valid integer ( for form validation ) .After searching around , I ended up using a function I had from 2002 which works using C # 1 ( below ) .However , it just seems to me that although the code below works , it is a misuse of try/catch to use it not to catch an error but to determine a value.Is there a better way to do this in C # 3 ? Answer : John 's answer below helped me build the function I was after without the try/catch . In this case , a blank textbox is also considered a valid `` whole number '' in my form : public static bool IsAValidInteger ( string strWholeNumber ) { try { int wholeNumber = Convert.ToInt32 ( strWholeNumber ) ; return true ; } catch { return false ; } } public static bool IsAValidWholeNumber ( string questionalWholeNumber ) { int result ; if ( questionalWholeNumber.Trim ( ) == `` '' || int.TryParse ( questionalWholeNumber , out result ) ) { return true ; } else { return false ; } }",Is there a better way to determine if a string can be an integer other than try/catch ? "C_sharp : Hi I am using an IoC container and I would like to initialize a service ( part of which involves 'heavy work ' talking to a database ) within the constructor.This particular service stores information that is found by a injected IPluginToServiceProviderBridge service , this information is saved in the database via a UnitOfWork.Once everything is boot-strapped , controllers with commands , and services with handlers , are used for all other interaction . All commands are wrapped within a lifetime scope so saving and disposing of the UnitOfWork is done by the handler and not the service ( this is great for clean code ) .The same neatness and separation of concerns for saving and transactions does not apply for the Initializer within the service as everything takes place in the constructor : A couple of points : Ideally I want to avoid using a factory as it complicates handling of scope lifetimes , I would be happy to refactor for better separation if i knew how.I really want to avoid having a separate Init ( ) method for the service , whilst it would allow for transaction and saving via command/handler , lots of checking code would be required and I believe this would also introduce temporal issues.Given the above , is it acceptable to call UnitOfWork.Save ( ) within my constructor or could I refactor for cleaner code and better separation ? public PluginManagerService ( IPluginToServiceProviderBridge serviceProvider , IUnitOfWork unitOfWork ) { this.unitOfWork = unitOfWork ; this.serviceProvider = serviceProvider ; lock ( threadLock ) { if ( initialised == false ) { LinkPluginsWithDatabase ( ) ; initialised = true ; } // I do n't like this next line , but // not sure what else to do this.UnitOfWork.Save ( ) ; } } protected void LinkPluginsWithDatabase ( ) { var plugins = this.serviceProvider.GetAllPlugins ( ) ; foreach ( var plugin in plugins ) { var db = new PluginRecord { interfaceType = plugin.InterfaceType ; var id = plugin.Id ; var version = plugin.Version ; } // store in db via unit of work repository this.unitOfWork.PluginsRepository.Add ( db ) ; } }",IoC Initialize Service with heavy-work in constructor but avoiding a temporal Init ( ) method "C_sharp : Using linqtoexcel to read a server generated spreadsheet . Only problem is that there is a dot in one of the headers and it refuses to pull . Manufacturer is abbreviated to Mfg . I used the following code per the example on their pagebut Manufacturer comes up empty in all the objects . I am very new to Linq so not sure what options I might have to make this work . I imagine it is confused by the dot when it tries to map to a Part object ... ExcelQueryFactory excel = new ExcelQueryFactory ( ) ; excel.FileName = myXLFile ; excel.AddMapping < Part > ( x = > x.Manufacturer , `` Mfg . `` ) ; var parts = from x in excel.Worksheet < Part > ( 0 ) select x ;",LinqToExcel dot in header C_sharp : I have the following code : which is giving me the following StyleCop ReSharper warning : The variable name 'fxRate ' begins with a prefix that looks like Hungarian notation.I have tried copying the Settings.StyleCop file to my solution folder and adding an entry for fx : I 've restarted VS but I still get the same warning.I am using the StyleCop ReSharper extension in VS2017.How do I ensure 'fx ' is a valid prefix in the solution ( for all team members ) ? var fxRate = new FxRate ( ) ; < Analyzers > < Analyzer AnalyzerId= '' StyleCop.CSharp.NamingRules '' > < AnalyzerSettings > < CollectionProperty Name= '' Hungarian '' > ... < Value > fx < /Value > ...,How do I prevent StyleCop warning of a Hungarian notation when prefix is valid "C_sharp : Is there a way to get the total number of allocations ( note - number of allocations , not bytes allocated ) ? It can be either for the current thread , or globally , whichever is easier.I want to check how many objects a particular function allocates , and while I know about the Debug - > Performance Profiler ( Alt+F2 ) , I would like to be able to do it programmatically from inside my program.Also , do I need to pause garbage collection to get accurate data , and can I do that ? Do I need to use the CLR Profiling API to achieve that ? // pseudocodeint GetTotalAllocations ( ) { ... ; } class Foo { string bar ; string baz ; } public static void Main ( ) { int allocationsBefore = GetTotalAllocations ( ) ; PauseGarbageCollector ( ) ; // do I need this ? I do n't want the GC to run during the function and skew the number of allocations // Some code that makes allocations . var foo = new Foo ( ) { bar = `` bar '' , baz = `` baz '' } ; ResumeGarbageCollector ( ) ; int allocationsAfter = GetTotalAllocations ( ) ; Console.WriteLine ( allocationsAfter - allocationsBefore ) ; // Should print 3 allocations - one for Foo , and 2 for its fields . }",Get total number of allocations in C # "C_sharp : I have a few inequalities regarding { x , y } , that satisfies the following equations : Note that x and y must be integer.Graphically it can be represented as follows , the blue region is the region that satisfies the above inequalities : The question now is , is there any function in Matlab that finds every admissible pair of { x , y } ? If there is an algorithm to do this kind of thing I would be glad to hear about it as well . Of course , one approach we can always use is brute force approach where we test every possible combination of { x , y } to see whether the inequalities are satisfied . But this is the last resort , because it 's time consuming . I 'm looking for a clever algorithm that does this , or in the best case , an existing library that I can use straight-away . The x^2+y^2 > =100 and x^2+y^2 < =200 are just examples ; in reality f and g can be any polynomial functions of any degree . Edit : C # code are welcomed as well . x > =0y > =0f ( x , y ) =x^2+y^2 > =100g ( x , y ) =x^2+y^2 < =200","Find the Discrete Pair of { x , y } that Satisfy Inequality Constriants" "C_sharp : Say I have a Task that generates an int , and a callback that accepts an int : Now I want to set it up so that once the task has completed and returned its integer result , the callfack f will be called with that integer – without requiring the main thread to wait for the task to complete : As I understand it , the typical solution for this is the Task.ContinueWith method : However , one could also get a TaskAwaiter for the task , and use its event-like interface : Now , I realize that TaskAwaiter is not intended for common use in application code , and mainly exists to be used internally by the await keyword.But in order to deepen my understanding of the TPL , I 'm wondering : Is there any practical difference between solutions ( 1 ) and ( 2 ) ? For example , ... regarding on which thread the callback will be invoked ? ... regarding what happens when an exception is thrown in the task or callback ? ... any other side-effects ? Task < int > task = ... ; Action < int > f = ... ; task.ContinueWith ( t = > f ( t.Result ) ) ; TaskAwaiter < int > awaiter = task.GetAwaiter ( ) ; awaiter.OnCompleted ( ( ) = > f ( awaiter.GetResult ( ) ) ) ;",Reacting to Task completion : ` .ContinueWith ( ) ` vs ` GetAwaiter ( ) .OnCompleted ( ) ` "C_sharp : Is it possible to call functions from C # , to an unmanaged function in a struct ( via VTable ) .For example , I am in-process hooking an application , and I am re-creating the structs for each class ( of the application ) .Then , I usually do : And I wish to call a function from the VTable of the structure in either of the following waysOrFurthermore , could this be done efficiently ( as these vtable funcs could be called numerous times ) ? Perhaps via Reflection Emit ? From what I know , marshalling has to create the delegate function every time I call the Invoke < > func . public struct SomeStruct { [ FieldOffset ( 0x00 ) ] public IntPtr * VTable ; [ FieldOffset ( 0x10 ) ] public uint SomeValue ; } var * data = ( SomeStruct* ) ( Address ) ; Invoke < delegate > ( data- > VTable [ 0x3C ] ) ( delegateArguments ) var eax = Invoke < Func < uint , uint > ( data- > VTable [ 0x3C ] ) ( arg1 , arg2 )",Call unmanaged function in struct from VTable "C_sharp : I am going to make a GUI that will have dynamically created sets of controls with events assigned to them . I will need to add and remove those controls at runtime . It will look like this : I have heard that assigning event handlers with += can cause memory leaks ( more specificly , memory will not be freed until application has exited ) . I want to avoid this . I know i can write some functions like here How to remove all event handlers from a control to find all event handlers and remove them but it looks very complex . Is there another way ? Does calling Dispose help remove those event handlers ? Can you destroy objects to force their memory to be freed like in C/C++ ? Thanks ! PS : Problem is , i dont know what event to detach . I will create lots of labels and add different kinds of onclick events to them . When its time to clean the flow layout panel , there is no way to know what event handler was attached to which label.This is the example code ( _flowLP is a FlowLayoutPanel ) - this Refresh ( ) function is ran multiple times before the application exits . FlowLayoutPanel.Controls.Clear ( ) ; < < add new controls , assigning Click events with += > > private void Refresh ( ) { Label l ; Random rnd = new Random ( ) ; // What code should i add here to prevent memory leaks _flowLP.Controls.Clear ( ) ; l = new Label ( ) ; l.Text = `` 1 '' ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method1 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method2 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method3 ; _flowLP.Controls.Add ( l ) ; l = new Label ( ) ; l.Text = `` 2 '' ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method1 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method2 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method3 ; _flowLP.Controls.Add ( l ) ; l = new Label ( ) ; l.Text = `` 3 '' ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method1 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method2 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method3 ; _flowLP.Controls.Add ( l ) ; l = new Label ( ) ; l.Text = `` 4 '' ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method1 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method2 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method3 ; _flowLP.Controls.Add ( l ) ; l = new Label ( ) ; l.Text = `` 5 '' ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method1 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method2 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method3 ; _flowLP.Controls.Add ( l ) ; l = new Label ( ) ; l.Text = `` 6 '' ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method1 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method2 ; if ( rnd.Next ( 3 ) == 0 ) l.Click += Method3 ; _flowLP.Controls.Add ( l ) ; }",precautions to take to prevent memory leaks due to added event handles "C_sharp : Hi i need to develop an addin for creating diagram objects in visio.I am able to create the top shape but not its derived types . for EG i am able to creat Start event in visio using c # , but could n't create Start Event of message type or othersIn the above picture i have 3 start event , well the BPMN Start Event was added and its property Trigger/Result option was changedStart Event - MultipleStart Event - MessageStart Event - Nonebut all the above 3 shapes are from Start Event . How to create the Message start event or Multiple start evet etc.I am creating shapes in visio usingbut this only creates Start Event , how to create Message Start EVent , Multiple Start Event etc Visio.Master shapetodrop = Masters.get_ItemU ( @ '' Start Event '' ) ; Visio.Shape DropShape = ActivePage.Drop ( shapetodrop , x , y ) ; DropShape.Name = name ; DropShape.Text = name ;",Creating Shapes in visio using c # "C_sharp : Today I noticed an interesting sorting behavior in C # . I have two lists and I sort them : The two lists now contain : Why is the AA put in the end ? Here is a demonstration : http : //ideone.com/QCeUjx var list1 = new List < string > { `` A '' , `` B '' , `` C '' } ; var list2 = new List < string > { `` AA '' , `` BB '' , `` CC '' } ; list1.Sort ( ) ; list2.Sort ( ) ; > > list1 [ 0 ] : `` A '' [ 1 ] : `` B '' [ 2 ] : `` C '' > > list2 [ 0 ] : `` BB '' [ 1 ] : `` CC '' [ 2 ] : `` AA ''",Sorting while using specific culture - `` BB '' may come first before `` AA '' in Danish and Norwegian "C_sharp : I clearly understand `` Pattern-based '' approach that uses C # compiler when it dealing with the foreach statement.And from C # Language Specification ( section 8.8.4 ) it is clear that first of all C # compiler tries to find GetEnumerator method and only then tries to find IEnumerable < T > and IEnumerable interfaces.But its unclear for me , why C # compiler treats string separately ( because the String class contains a method GetEnumerator that returns CharEnumerator and it also implements IEnumerable < char > and IEnumerable interfces ) : converts toBut I ca n't find any exceptions in Language Specification regarding the String class . Could someone give some insights about this solution ? I tried with the C # 4 compiler . Here is the IL code for the previous code snippet : string s = `` 1234 '' ; foreach ( char c in s ) Console.WriteLine ( c ) ; string s = `` 1234 '' ; for ( int i = 0 ; i < s.Length ; i++ ) Console.WriteLine ( s [ i ] ) ; IL_0000 : ldstr `` 1234 '' IL_0005 : stloc.0 IL_0006 : ldloc.0 IL_0007 : stloc.2 IL_0008 : ldc.i4.0 IL_0009 : stloc.3 IL_000A : br.s IL_001EIL_000C : ldloc.2 IL_000D : ldloc.3 IL_000E : callvirt System.String.get_CharsIL_0013 : stloc.1 IL_0014 : ldloc.1 IL_0015 : call System.Console.WriteLineIL_001A : ldloc.3 IL_001B : ldc.i4.1 IL_001C : add IL_001D : stloc.3 IL_001E : ldloc.3 IL_001F : ldloc.2 IL_0020 : callvirt System.String.get_LengthIL_0025 : blt.s IL_000C",Why C # compiler treated string class separately with foreach statement "C_sharp : Let 's say I have the following in my config : If I want to get either section , I can get them by name pretty easily : However , this relies on my code knowing how the section is named in the config - and it could be named anything . What I 'd prefer is the ability to pull all sections of type InterestingThingsSection from the config , regardless of name . How can I go about this in a flexible way ( so , supports both app configs and web configs ) ? EDIT : If you have the Configuration already , getting the actual sections is n't too difficult : However , how do I get the Configuration instance in a generally-applicable way ? Or , how do I know if I should use ConfigurationManager or WebConfigurationManager ? < configSections > < section name= '' interestingThings '' type= '' Test.InterestingThingsSection , Test '' / > < section name= '' moreInterestingThings '' type= '' Test.InterestingThingsSection , Test '' / > < /configSections > < interestingThings > < add name= '' Thing1 '' value= '' Seuss '' / > < /interestingThings > < moreInterestingThings > < add name= '' Thing2 '' value= '' Seuss '' / > < /moreInterestingThings > InterestingThingsSection interesting = ( InterestingThingsSection ) ConfigurationManager.GetSection ( `` interestingThings '' ) ; InterestingThingsSection more = ( InterestingThingsSection ) ConfigurationManager.GetSection ( `` moreInterestingThings '' ) ; public static IEnumerable < T > SectionsOfType < T > ( this Configuration configuration ) where T : ConfigurationSection { return configuration.Sections.OfType < T > ( ) .Union ( configuration.SectionGroups.SectionsOfType < T > ( ) ) ; } public static IEnumerable < T > SectionsOfType < T > ( this ConfigurationSectionGroupCollection collection ) where T : ConfigurationSection { var sections = new List < T > ( ) ; foreach ( ConfigurationSectionGroup group in collection ) { sections.AddRange ( group.Sections.OfType < T > ( ) ) ; sections.AddRange ( group.SectionGroups.SectionsOfType < T > ( ) ) ; } return sections ; }",How to get all sections of a specific type C_sharp : In the Method below on the last line I 'm always getting an exception : I ca n't really explain why because I 'm checking explicitly for that : System.OverflowException : Value was either too large or too small for an Int32 . private Int32 ConvertValue ( double value ) { if ( value > Int32.MaxValue ) { Console.WriteLine ( `` Could n't convert value `` + value + `` to Int32 '' ) ; return Int32.MaxValue ; } else if ( value < Int32.MinValue ) { Console.WriteLine ( `` Could n't convert value `` + value + `` to Int32 '' ) ; return Int32.MinValue ; } else { return Convert.ToInt32 ( value ) ; } },Got hit by an OverflowException C_sharp : Possible Duplicate : C # : Passing null to overloaded method - which method is called ? Here is a test caseThe question is why CLR decides that null is interpreted as string in first case ? It appears that this question was already answered hereHere is another similar case . None of these ifs are triggered object a = null ; var b = Convert.ToString ( null ) ; var c = Convert.ToString ( a ) ; string d = Convert.ToString ( null ) ; // CLR chooses Convert.ToString ( string value ) string e = Convert.ToString ( a ) ; // CLR chooses Convert.ToString ( object value ) object x = null ; if ( x is object ) { Console.Write ( `` x is object '' ) ; } if ( x is string ) { Console.Write ( `` x is string '' ) ; } if ( null is object ) { Console.Write ( `` null is object '' ) ; } if ( null is string ) { Console.Write ( `` null is string '' ) ; },CLR question . Why method overloading in C # decides that null is a string ? "C_sharp : I need to know if i need to add a sort-column to my custom table-type which i could then use to sort or if i can trust that the order of parameters remains the same even without such a column.This is my type : and this is one of the sql where is use it : as you can see i 'm using ROW_NUMBER to get the sort-column value . Do i need to add also a sort-column to the table-type or is it guaranteed ( documented ) that it remains the same ? It seems to work.This is the ADO.NET code where i use it : GetVwdCodeRecords returns IEnumerable < SqlDataRecord > for an IEnumerable < string > .Thanks all . If a future reader is interested to know how i 've guaranteed the sort-order . I 've modifed the table-type as suggested by adding another column : The insert-sql is even simpler because the sort-column is passed in and not calculated : For the sake of completeness , here is the method that returns the IEnumerable < SqlDataRecord > used as value for the table-valued-parameter ( omitted error-handling ) : CREATE TYPE [ dbo ] . [ VwdCodeList ] AS TABLE ( [ VwdCode ] [ varchar ] ( 50 ) NOT NULL ) /// < summary > /// Inserts all new WatchListCodes for a given watchlist/// < /summary > public const string InsertWatchListCodes = @ '' INSERT INTO [ dbo ] . [ WatchListCodes ] ( [ WatchListID ] , [ VwdCode ] , [ Sort ] ) SELECT @ WatchListID , VwdCode , ROW_NUMBER ( ) OVER ( ORDER BY ( SELECT 1 ) ) FROM @ VwdCodeList ; '' ; SqlParameter vwdCodeListParameter = insertWatchListCodeCommand.Parameters.Add ( `` @ VwdCodeList '' , SqlDbType.Structured ) ; vwdCodeListParameter.TypeName = `` [ dbo ] . [ VwdCodeList ] '' ; vwdCodeListParameter.Value = WatchListSql.GetVwdCodeRecords ( newVwdCodes , true ) ; int inserted = insertWatchListCodeCommand.ExecuteNonQuery ( ) ; CREATE TYPE [ dbo ] . [ VwdCodeList ] AS TABLE ( [ VwdCode ] [ varchar ] ( 50 ) NOT NULL , [ Sort ] [ smallint ] NOT NULL ) public const string InsertWatchListCodes = @ '' INSERT INTO [ dbo ] . [ WatchListCodes ] ( [ WatchListID ] , [ VwdCode ] , [ Sort ] ) SELECT @ WatchListID , cl.VwdCode , cl.Sort FROM @ VwdCodeList cl ; '' ; public static IEnumerable < SqlDataRecord > GetVwdCodeRecords ( IEnumerable < string > vwdCodes , bool trimCode = true ) { short currentSort = 0 ; foreach ( string vwdCode in vwdCodes ) { var record = new SqlDataRecord ( new SqlMetaData ( `` VwdCode '' , SqlDbType.VarChar , 50 ) , new SqlMetaData ( `` Sort '' , SqlDbType.SmallInt ) ) ; record.SetString ( 0 , trimCode ? vwdCode.Trim ( ) : vwdCode ) ; record.SetInt16 ( 1 , ++currentSort ) ; yield return record ; } }",Is the sort-order of table-valued-parameters guaranteed to remain the same ? "C_sharp : Hi.How can I click on 'Allow ' button ? I really ca n't find any solution in the internet . I do n't want to use c++ hooks or simulate mouse clicks by coordinates . Is there any good way to allow this notification ? does n't help new ChromeOptions.AddUserProfilePreference ( `` profile.default_content_setting_values.automatic_downloads '' , 2 ) ;",C # selenium chromedriver click on Allow store files on this device "C_sharp : Why the following two code samples produce different output ? Case 1Output : Case 2Output : I am puzzled . Does it mean that Func ( EnumType ) hides Func ( int ) declared in the base ? If this is the case then why literal 0 is implicitly casted to EnumType in the second case without a warning ? EDIT : There is even more interesting behavior when I tryWhat is your guess the output should look like ? here it is : Any ideas why 0 and 1 are treated differently ? EDIT 2 : It turns out that literal 0 indeed has special meaning in C # .Here and here I found an excellent description of this behavior ( see the accepted answers ) . enum EnumType { First , Second , Third } class ClassB { public string Func ( int index ) { return `` Func ( int ) '' ; } public string Func ( EnumType type ) { return `` Func ( EnumType ) '' ; } } class Program { static void Main ( string [ ] args ) { ClassB b = new ClassB ( ) ; Console.WriteLine ( b.Func ( 0 ) ) ; Console.WriteLine ( b.Func ( EnumType.First ) ) ; Console.ReadLine ( ) ; } } Func ( int ) Func ( EnumType ) enum EnumType { First , Second , Third } class ClassA { public string Func ( int index ) { return `` Func ( int ) '' ; } } class ClassB : ClassA { public string Func ( EnumType enumType ) { return `` Func ( EnumType ) '' ; } } class Program { static void Main ( string [ ] args ) { ClassB b = new ClassB ( ) ; Console.WriteLine ( b.Func ( 0 ) ) ; Console.WriteLine ( b.Func ( EnumType.First ) ) ; Console.ReadLine ( ) ; } } Func ( EnumType ) Func ( EnumType ) Console.WriteLine ( b.Func ( 0 ) ) ; Console.WriteLine ( b.Func ( 1 ) ) ; Console.WriteLine ( b.Func ( EnumType.First ) ) ; Func ( EnumType ) Func ( int ) Func ( EnumType )",Overloading a method in subclass ( Enum vs int ) "C_sharp : I need to pass structs as value types in a list.Suppose I have a struct which derives from an interface : I know if I did it like so : IFoo foo = new Foo1 ( ) , it would turn the value into a reference ( boxing ) .Would the structs not be passed as a reference if I added Foo1 or Foo2 to List < IFoo > ? If not , is it safe to do List < object > and only add in these structs , or would it be better to do MemberwiseClone on a class ? I 'm also looking for efficiency , as this will be for collision detection in a tile map . interface IFoo { ... } struct Foo1 : IFoo { ... } struct Foo2 : IFoo { ... } //Some other class which contains this : List < IFoo > listOfFoo ;",Adding Struct : Interface to a List < Interface > "C_sharp : I 'm reading a book about ASP.NET MVC 4 and I 've got a little question.Here is the view modelThe book 's author suggests to create object of this type to call a view from the controller.The view itself is strongly typedI just wonder was this really necessary to create object of the view model when calling the view ? In fact , I tried to pass null as model object and everything worked perfectly . I guess the MVC Framework has created the model object itself.If this is ok , then is it considered as a good practice ? public class SignupViewModel { public string Username { get ; set ; } public string Password { get ; set ; } public string Password2 { get ; set ; } public string Email { get ; set ; } } public ActionResult Index ( ) { if ( ! Security.IsAuthneticated ) { return View ( `` SignupPge '' , new SignupViewModel ( ) ) ; } } @ model SignupViewModel < p > @ using ( var signupForm = Html.BeginForm ( `` Signup '' , `` Account '' ) ) { @ Html.TextBoxFor ( m = > m.Email , new { placeholder = `` Email '' } ) @ Html.TextBoxFor ( m = > m.Username , new { placeholder = `` Username '' } ) @ Html.PasswordFor ( m = > m.Password , new { placeholder = `` Password '' } ) @ Html.PasswordFor ( m = > m.Password2 , new { placeholder = `` Confirm Password '' } ) < input type= '' submit '' value= '' Create Account '' / > } < /p > }",Should I always initialize view model object ? C_sharp : I 've written code like thisAnd i have been blamed for this code and have told to write like this But I am wondering would not I get an exception if totals count would be 0 ? Do I need also check this with .Any ( ) or .Count ( ) ? TotalCashIn = totals ! = null & & totals.Any ( ) ? totals.First ( ) .TotalCashIn : null ; TotalCashIn = totals ! = null ? totals.FirstOrDefault ( ) .TotalCashIn : null ;,LINQ ANY ( ) with First ( ) And FirstOrDefault ( ) "C_sharp : I am trying to make a class that when it starts it starts a stopwatch and all the time the elapsed time is written to a local variable Elapsed which I have a Listview that databinds to . But when I use this code the Listview just displays 00:00:00.00000001 and never changes.The class ' code is : Now it works using Timers instead } namespace project23 { public class ActiveEmployee { public int EmpID { get ; set ; } public string EmpName { get ; set ; } private DateTime date ; private BackgroundWorker worker ; public Stopwatch sw ; public ActiveEmployee ( int empID , string empName ) { date = DateTime.Now ; worker = new BackgroundWorker ( ) ; worker.DoWork += BackgroundWork ; worker.WorkerReportsProgress = true ; worker.RunWorkerAsync ( ) ; } private TimeSpan elapsed ; public TimeSpan Elapsed { get { return elapsed ; } set { elapsed = value ; NotifyPropertyChanged ( `` Elapsed '' ) ; } } private void BackgroundWork ( object sender , DoWorkEventArgs args ) { sw = new Stopwatch ( ) ; sw.Start ( ) ; if ( true ) { Elapsed = sw.Elapsed ; } } public event PropertyChangedEventHandler PropertyChanged ; private void NotifyPropertyChanged ( String info ) { if ( PropertyChanged ! = null ) { PropertyChanged ( this , new PropertyChangedEventArgs ( info ) ) ; } } } } using System ; using System.ComponentModel ; using System.Timers ; namespace Eksamen_Januar_2011 { public class ActiveEmployee : INotifyPropertyChanged { public int EmpID { get ; set ; } public string EmpName { get ; set ; } private DateTime startDate ; private BackgroundWorker worker ; private Timer timer ; public ActiveEmployee ( int empID , string empName ) { startDate = DateTime.Now ; worker = new BackgroundWorker ( ) ; worker.DoWork += BackgroundWork ; timer = new Timer ( 1000 ) ; timer.Elapsed += TimerElapsed ; worker.RunWorkerAsync ( ) ; } private TimeSpan elapsed ; public TimeSpan Elapsed { get { return elapsed ; } set { elapsed = value ; NotifyPropertyChanged ( `` Elapsed '' ) ; } } private void BackgroundWork ( object sender , DoWorkEventArgs args ) { timer.Start ( ) ; } private void TimerElapsed ( object sender , ElapsedEventArgs e ) { Elapsed = DateTime.Now - startDate ; } public event PropertyChangedEventHandler PropertyChanged ; private void NotifyPropertyChanged ( String info ) { if ( PropertyChanged ! = null ) { PropertyChanged ( this , new PropertyChangedEventArgs ( info ) ) ; } } }",Databinding issue with stopwatched elapsed "C_sharp : I have this REGEX almost perfect ... It seems to handle everything except a number that leads with a negative sign and then a decimal . So if I enter : I get an error - Here is my Regex -- everything else I 've tested works perfectly ... This allows for : a number up to 11 digits ( 99 Billion ) positive or negative number up to 4 decimal places ( optional ) leading 0 before decimal point is optional - for positive numbers onlyThese all work : These do not work : -.2 ^ ( \+|- ) ? [ 0-9 ] { 1,11 } ? ( ? : \ . [ 0-9 ] { 1,4 } ) ? $ -0.2345-1012.1250.12455.55525000000000 ( aka 25 Billion ) 25000000000.25 -.2-.421",Regular Expression almost perfect for a Numeric Value "C_sharp : I have application that launches sub process and processes its stdout asynchronously . The problem is that the async operation takes some time and I want method responsible for process execution to end after all async IO operations are done.I have code like this : Now I 'm looking for a way how to tell the program to wait until all IO ( OnRecvStdOut ) operations are done.I though about using one of System.Threading classes , but I 'm not sure which class is the best for this and how to do this after all , the best way would probably be : And in main function : Note : I 'd like to allow both StdErr and StdOut to be processed in parallel . Something ca n't rely that Wait will be called as much as Signal , because Increase ( ) and DecreaseAndSignal ( ) pairs will be called many times before Wait occurs.The second thing that came to mind was something that would be able to signal many times ( without requirement to process signals ) and use loop in main function like : Edit : Current working solution : I came up with this what seems to be working : But I 'd appreciate any notes how to do this `` good practice way '' or what are possible risks of implementation I though of . using System.Diagnostics ; Process process = new Process ( ) ; // ... process.OutputDataReceived += new DataReceivedEventHandler ( this.OnRecvStdOut ) ; process.ErrorDataReceived += new DataReceivedEventHandler ( this.OnRecvStdErr ) ; // ... process.Start ( ) ; process.BeginOutputReadLine ( ) ; process.BeginErrorReadLine ( ) ; // ... process.WaitForExit ( ) ; public void OnRecvStdOut ( ... ) { something.Increase ( ) ; // the stuff that takes so long something.DecreaseAndSignal ( ) ; } something.WaitUntilZero ( ) ; while ( ioOperations > 0 ) { something.WaitForSignal ( 500 ) ; } using System.Threading ; protected int IOCount = 0 ; protected AutoResetEvent _IOSyncEvent = new AutoResetEvent ( false ) ; public void OnRecvStdOut ( ... ) { Interlocked.Increase ( ref IOCount ) ; // the stuff that takes so long Interlocked.Decrease ( ref IOCount ) ; IOSyncEvent.Set ( ) ; } // After process.WaitForExit ( ) while ( IOCount > 0 ) { // 250 for a case that signal occurs after condition and before wait IOSyncEvent.WaitOne ( 250 ) ; }",Synchronization of asynchronous reading from stdout of child process "C_sharp : I feel like I should know the answer to this , but I do n't . What is the type character on a numeric literal called ? I wanted to find a complete list of them today , but could n't come up with what to ask Google to search for . EDITFound a decent list if anyone is interestedhttp : //www.undermyhat.org/blog/2009/08/secrets-and-lies-of-type-suffixes-in-c-and-vb-net/ double myDouble = 12d ; float myFloat = 10f ;",What is the 'd ' in the literal 12d called ? "C_sharp : I need to delete a remote branch , and found this technique : git push origin : the_remote_branchI tried passing it to Networks Push method in the following forms , but nothing seems to work ( options is my login credentials ) : And a few other options . I can not get it to work at all , it returns errors such as ( for the `` : NewBranchForDeletion '' method ) : Not a valid reference `` NewBranchForDeletion '' Update : Thanks to @ Rob for finding me this comment on LibGit2Sharp 's repo : https : //github.com/libgit2/libgit2sharp/issues/466 # issuecomment-21076975The first option fails with a NullReferenceException on objectish , and using string.Empty for objectish results in the error mentioned above . The second option is what I am trying , except I am using the version with HTTPS validation : _repo.Network.Push ( _repo.Network.Remotes [ `` origin '' ] , `` origin/ : NewBranchForDeletion '' , options ) _repo.Network.Push ( _repo.Network.Remotes [ `` origin '' ] , `` : NewBranchForDeletion '' , options ) _repo.Network.Push ( _repo.Network.Remotes [ `` origin '' ] , `` : origin/NewBranchForDeletion '' , options ) _repo.Network.Push ( _repo.Network.Remotes [ `` origin '' ] , `` : refs/remotes/ : origin/NewBranchForDeletion '' , options ) _repo.Network.Push ( _repo.Network.Remotes [ `` origin '' ] , `` : refs/remotes/origin/NewBranchForDeletion '' , options ) _repo.Network.Push ( _repo.Network.Remotes [ `` origin '' ] , `` refs/heads/ : origin/NewBranchForDeletion '' , options ) _repo.Network.Push ( _repo.Network.Remotes [ `` origin '' ] , `` refs/heads/ : NewBranchForDeletion '' , options ) repo.Network.Push ( repo.Remotes [ `` my-remote '' ] , objectish : null , destinationSpec : `` my-branch '' ) ; // Or using a refspec , like you would use with git push ... repo.Network.Push ( repo.Remotes [ `` my-remote '' ] , pushRefSpec : `` : my-branch '' ) ;",Delete Remote Branch "C_sharp : I have a boolean property in my ViewModel , named lets say IsNotSupported that is used to show some warning information if a sensor is not supported . Therefore I use a BooleanToVisibilityConverter , that is added in the ressources : and bind it to the stackpanel containing the warning : That works all quite well , but when loading the page , and the sensor is supported , the warning appears for just a fraction of a second and disappears afterwards . I know that this flickering is caused by the binding not having happened yet and therefore defaulting to visible . That flicker it is annoying as hell ... It should rather default to collapsed and be made visible only after it is clear that the warning should be shown . Also , this would avoid a second layouting pass after the binding and could therefore have positive performance impacts.I had this problem over and over , and found nothing about it in the internet until I found this SO question , that is closely related , but is not found if searched for windows phone instead of silverlight . Both the problem and the solution might seem simple , but I really bugged me quite a long time , so I thought it might be a good idea to write a Q & A-style question about it to help others that are facing the same issue . < phone : PhoneApplicationPage.Resources > < local : BooleanToVisibilityConverter x : Key= '' BooleanToVisibilityConverter '' / > < /phone : PhoneApplicationPage.Resources > < StackPanel x : Name= '' NotSupportedWarning '' Visibility= '' { Binding IsNotSupported , Converter= { StaticResource BooleanToVisibilityConverter } } '' >",How can I prevent flickering when binding a boolean to the visibility of a control "C_sharp : I have found code on a website which is as follows.Here , what is the purpose of casting into object type again since a , b , d are itself the objects of string ? string a = `` xx '' ; string b = `` xx '' ; string c = `` x '' ; string d = String.Intern ( c + c ) ; Console.WriteLine ( ( object ) a == ( object ) b ) ; // True Console.WriteLine ( ( object ) a == ( object ) d ) ; // True",What is the purpose of casting into `` object '' type ? "C_sharp : We have a database of images where I have calculated the PHASH using Dr. Neal Krawetz 's method as implemented by David Oftedal.Part of the sample code calculates the difference between these longs is here : The challenge is that I only know one of these hashes and I want to query SOLR to find other hashes in order of similarity.A few notes : Using SOLR here ( only alternative I have is HBASE ) Want to avoid installing any custom java into solr ( happy to install an existing plugin ) Happy to do lots of pre-processing in C # Happy to use multiple fields to store data as a bit string , long , etcUsing SOLRNet as a clientEdit , some extra information ( apologies I am caught up in the problem and started assuming it was a widely known area ) . Here is a direct download to the C # console / sample app : http : //01101001.net/Imghash.zipAn example output of this console app would be : 004143737f7f7f7f phash-test-001.jpg0041417f7f7f7f7f phash-test-002.jpgSimilarity : 95.3125 % ulong hash1 = AverageHash ( theImage ) ; ulong hash2 = AverageHash ( theOtherImage ) ; uint BitCount ( ulong theNumber ) { uint count = 0 ; for ( ; theNumber > 0 ; theNumber > > = 8 ) { count += bitCounts [ ( theNumber & 0xFF ) ] ; } return count ; } Console.WriteLine ( `` Similarity : `` + ( ( 64 - BitCount ( hash1 ^ hash2 ) ) * 100.0 ) / 64.0 + `` % '' ) ;",Using SOLR to calculate `` similarity '' / '' bitcount '' between two ulongs "C_sharp : I am trying to filter a List of strings based on the number of words in each string . I am assuming that you would trim any white-space at the ends of the string , and then count the number of spaces left in the string , so that WordCount = NumberOfSpaces + 1 . Is that the most efficient way to do this ? I know that for filtering based on character count the following is working fine ... just cant figure out how to write it succinctly using C # /LINQ.Any ideas of for counting words ? UPDATE : This Worked like a charm ... Thanks Mathew : if ( checkBox_MinMaxChars.Checked ) { int minChar = int.Parse ( numeric_MinChars.Text ) ; int maxChar = int.Parse ( numeric_MaxChars.Text ) ; myList = myList.Where ( x = > x.Length > = minChar & & x.Length < = maxChar ) .ToList ( ) ; } int minWords = int.Parse ( numeric_MinWords.Text ) ; int maxWords = int.Parse ( numeric_MaxWords.Text ) ; sortBox1 = sortBox1.Where ( x = > x.Trim ( ) .Split ( new char [ ] { ' ' } , StringSplitOptions.RemoveEmptyEntries ) .Count ( ) > = minWords & & x.Trim ( ) .Split ( new char [ ] { ' ' } , StringSplitOptions.RemoveEmptyEntries ) .Count ( ) < = maxWords ) .ToList ( ) ;",Filtering a String based on word count "C_sharp : I have a weird case and I wanted your enlightenment.I have two controllers . One Person Controller for general Person use action methods and one Candidate Controller for more specific action methods related to Candidate . I use one partial view that is located under the Person folder in order to be used as generic in case I want to use it in the future for other types of Person.For the time being this partial view uses an Ajax.BeginForm targeting the Candidate Controller . The syntax I am using isThis type of Ajax.BeginForm works correctly despite of the fact that it targets an action in a different controller.Now for my form validation I had to put some more arguments to my Ajax.BeginForm . My new syntax is like that : For some reason this way ca n't find the Action method . If I put my action inside the Person Controller it works correctly again . However I was wondering why is that case . I did some digging but I did n't manage to get an answer about that . From firebug I see that the url the browser tries to post is for some reason http : // { ProjectName } /Person/SaveCandidateLanguage ? Length=9 instead ofhttp : // { ProjectName } /Candidate/SaveCandidateLanguage ? Length=9and naturally I get a 404 Not found response . I was also wondering what is the variable ? Length=9 that I see at the end of the url and where does it come from . @ using ( Ajax.BeginForm ( `` SaveCandidateLanguage '' , `` Candidate '' , new AjaxOptions { HttpMethod = `` Post '' , OnBegin = `` onBeginFormValidation '' , OnSuccess = `` onSaveCandidateLanguageSuccess '' } ) ) { // form input elements } @ using ( Ajax.BeginForm ( `` SaveCandidateLanguage '' , `` Candidate '' , new AjaxOptions { HttpMethod = `` Post '' , OnBegin = `` onBeginFormValidation '' , OnSuccess = `` onSaveCandidateLanguageSuccess '' } , new { id = `` addEditCandidateLanguageForm '' , novalidate = `` novalidate '' } ) ) { // form input elements }",Ajax.BeginForm with 4 arguments not finding the action method "C_sharp : It 's often said that you should n't use exceptions for regular error handling because of bad performance . My guess is that that bad performance is caused by having to instantiate a new exception object , generate a stack trace , etc . So why not have lightweight exceptions ? Code like this is logically sound : And yet we 're recommended to use TryParse instead to avoid the overhead of the exception . But if the exception were just a static object that got initialized when the thread started , all the code throwing the exception would need to do is set an error code number and maybe an error string . No stack trace , no new object instantiation . It would be a `` lightweight exception '' , and so the overhead for using exceptions would be greatly reduced . Why do n't we have such lightweight exceptions ? string ageDescription = `` Five years old '' ; try { int age = int.Parse ( ageDescription ) ; } catch ( Exception ) { // Could n't parse age ; handle parse failure }",Why does n't C # have lightweight exceptions ? C_sharp : What would the folowing VB.NET enum definition look like in C # ? Public Enum SomeEnum As Integer < Description ( `` Name One '' ) > NameOne = 1End Enum,Defining C # enums with descriptions "C_sharp : I have a main entity Profile that has a property Name that is a value object . The Name object has two properties First and Last . When I use the Fluent API to map the Name objects properties to columns within the Profile table I specify that they are required . When I create the migration it says nullable is true . I assume it has to do with the fact that in EF Core 3.0 owned entities are now optional but how do I tell EF that they are actually required ? Any help you can provide would be great . public class Profile { public Name Name { get ; private set ; } ... } public class Name { public string First { get ; } public string Last { get ; } ... } public override void Configure ( EntityTypeBuilder < Profile > builder ) { base.Configure ( builder ) ; builder.OwnsOne ( navigationExpression : p = > p.Name , buildAction : n = > { n.Property ( n = > n.First ) .HasColumnName ( `` NameFirst '' ) .HasMaxLength ( 25 ) .IsRequired ( ) ; n.Property ( n = > n.Last ) .HasColumnName ( `` NameLast '' ) .HasMaxLength ( 25 ) .IsRequired ( ) ; } ) ; }",How to make an OwnsOne property in EF Core 3.0 required when mapping to SQL Server columns ? "C_sharp : I have two very similar specs for two very similar controller actions : VoteUp ( int id ) and VoteDown ( int id ) . These methods allow a user to vote a post up or down ; kinda like the vote up/down functionality for StackOverflow questions . The specs are : VoteDown : VoteUp : So I have two questions : How should I go about DRY-ing these two specs ? Is it even advisable or should I actually have one spec per controller action ? I know I Normally should , but this feels like repeating myself a lot.Is there any way to implement the second It within the same spec ? Note that the It should_not_let_the_user_vote_more_than_once ; requires me the spec to call controller.VoteDown ( 1 ) twice . I know the easiest would be to create a separate spec for it too , but it 'd be copying and pasting the same code yet again ... I 'm still getting the hang of BDD ( and MSpec ) and many times it is not clear which way I should go , or what the best practices or guidelines for BDD are . Any help would be appreciated . [ Subject ( typeof ( SomeController ) ) ] public class When_user_clicks_the_vote_down_button_on_a_post : SomeControllerContext { Establish context = ( ) = > { post = PostFakes.VanillaPost ( ) ; post.Votes = 10 ; session.Setup ( s = > s.Single ( Moq.It.IsAny < Expression < Func < Post , bool > > > ( ) ) ) .Returns ( post ) ; session.Setup ( s = > s.CommitChanges ( ) ) ; } ; Because of = ( ) = > result = controller.VoteDown ( 1 ) ; It should_decrement_the_votes_of_the_post_by_1 = ( ) = > suggestion.Votes.ShouldEqual ( 9 ) ; It should_not_let_the_user_vote_more_than_once ; } [ Subject ( typeof ( SomeController ) ) ] public class When_user_clicks_the_vote_down_button_on_a_post : SomeControllerContext { Establish context = ( ) = > { post = PostFakes.VanillaPost ( ) ; post.Votes = 0 ; session.Setup ( s = > s.Single ( Moq.It.IsAny < Expression < Func < Post , bool > > > ( ) ) ) .Returns ( post ) ; session.Setup ( s = > s.CommitChanges ( ) ) ; } ; Because of = ( ) = > result = controller.VoteUp ( 1 ) ; It should_increment_the_votes_of_the_post_by_1 = ( ) = > suggestion.Votes.ShouldEqual ( 1 ) ; It should_not_let_the_user_vote_more_than_once ; }",DRY-ing very similar specs for ASP.NET MVC controller action with MSpec ( BDD guidelines ) "C_sharp : In my factory method I use Switch statement to create concrete objects . This results in very high cyclomatic complexity . Here is a sample code : How can I refactor this to reduce cyclomatic complexity ? If I use reflection to create objects or something else to build objects is it better than above method ? private static UnitDescriptor createUnitDescriptor ( string code ) { switch ( code ) { case UnitCode.DEG_C : return new UnitDescriptorDegC ( ) ; case UnitCode.DEG_F : return new UnitDescriptorDegF ( ) ; : : default : throw new SystemException ( string.format ( `` unknown code : { o } '' , code ) ; } }",Unable to reduce cyclomatic complexity in a Factory method without using reflection "C_sharp : Let 's say I have a class A which can fire an event called X . Now I have a class B and in a method I get an instance to A and bind the event to a handler in B : I have three questions about this.Is it true that when I now set the reference to the B instance to null , it wo n't be garbage collected since the garbage collector thinks it 's still in use ( thus keeping a useless and potentially interfering copy of B in memory ) .What about when I have another object c ( of class C ) in which I have a reference to A called a ( `` this.a = new A ( ) '' ) . Then I call `` b.BindEvent ( this.a ) '' , and in c I set the reference to a to null ( `` this.a = null '' ) . Will this keep the copy of A in memory because it 's referenced through the event in b ? If either or both are true of the above , how can I best circumvent these issues ? If I have a whole list of event handlers ( say 10 lines like `` a.SomeEvent += SomeMethod '' ) should I clean them all up again ( `` a.SomeEvent -= SomeMethod '' ) . At which time or place in the code should I do these things ? Well it 's gotten a bit fuzzy but I 'm not sure how to explain in a better way . Please leave a comment if I need to explain something more detailed . public void BindEvent ( A a ) { a.X += AEventHandler ; }",How to get rid of event handlers safely ? "C_sharp : I am generating .cs files from .xsd files using xsd.exe . But when I am adding the files to windows 10 universal blank app , I was getting error as `` missing an assembly reference '' for System.SerializableAttribute ( ) and System.ComponentModel.DesignerCategoryAttribute ( ‌​ '' ‌​code '' ) . I fixed this by @ t.ouvre 's trick . Then there were no errors in any of the particular line of the code but when i am building the code i am getting an error saying that `` Can not find type System.ComponentModel.MarshalByValueComponent in module System.dll '' and it does n't specify exactly where the error is . How can I use the file generated by xsd.exe in windows 10 universal app ? What are all the things that I need to do with the file to use it for serialization and deserialization ( using DataContractSerializer in UWP ) /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` xsd '' , `` 4.6.81.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( AnonymousType = true ) ] [ System.Xml.Serialization.XmlRootAttribute ( Namespace = `` '' , IsNullable = false ) ] public partial class request { private usertype userField ; private string versionField ; /// < remarks/ > [ System.Xml.Serialization.XmlElementAttribute ( Form = System.Xml.Schema.XmlSchemaForm.Unqualified ) ] public usertype user { get { return this.userField ; } set { this.userField = value ; } } /// < remarks/ > [ System.Xml.Serialization.XmlAttributeAttribute ( ) ] public string version { get { return this.versionField ; } set { this.versionField = value ; } } } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` xsd '' , `` 4.6.81.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] public partial class usertype { private string emailField ; private string passwordField ; /// < remarks/ > [ System.Xml.Serialization.XmlElementAttribute ( Form = System.Xml.Schema.XmlSchemaForm.Unqualified ) ] public string email { get { return this.emailField ; } set { this.emailField = value ; } } /// < remarks/ > [ System.Xml.Serialization.XmlElementAttribute ( Form = System.Xml.Schema.XmlSchemaForm.Unqualified ) ] public string password { get { return this.passwordField ; } set { this.passwordField = value ; } } } /// < remarks/ > [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` xsd '' , `` 4.6.81.0 '' ) ] [ System.SerializableAttribute ( ) ] [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.ComponentModel.DesignerCategoryAttribute ( `` code '' ) ] [ System.Xml.Serialization.XmlTypeAttribute ( AnonymousType = true ) ] [ System.Xml.Serialization.XmlRootAttribute ( Namespace = `` '' , IsNullable = false ) ] public partial class NewDataSet { private request [ ] itemsField ; /// < remarks/ > [ System.Xml.Serialization.XmlElementAttribute ( `` request '' ) ] public request [ ] Items { get { return this.itemsField ; } set { this.itemsField = value ; } } }",how can i use the file that is generated by xsd.exe in windows 10 universal app "C_sharp : I am uploading a file in my ASP.NET MVC application using Uploadify . Controller : Uploadify code ( in a .ascx file ) : The 'file ' in the controller action is always returning NULL . What am I missing ? public ActionResult Upload ( HttpPostedFileBase file ) { List < string > validIDs , invalidIDs ; if ( file.ContentLength > 0 ) { //do something } } $ ( document ) .ready ( function ( ) { $ ( `` # file_upload '' ) .uploadify ( { 'uploader ' : '/Scripts/uploadify/uploadify.swf ' , 'script ' : '/XYZ/Upload ' , 'cancelImg ' : '/Scripts/uploadify/cancel.png ' , 'fileExt ' : '*.jpg ; *.gif ; *.png ; *.bmp ; *.htm ; *.html ; *.zip ' , 'fileDesc ' : '*.jpg ; *.gif ; *.png ; *.bmp ; *.htm ; *.html ; *.zip ' , 'auto ' : true , 'multi ' : false , 'sizeLimit ' : 1048576 , //1 MB 'buttonText ' : 'Upload Files ' } } ) ; } ) ;",File upload returns null "C_sharp : I have some basic Azure tables that I 've been querying serially : To speed this up , I parallelized this like so : This produces significant speedup , but the results tend to be slightly different between runs ( i.e. , some of the entities differ occasionally , though the number of entities returned is exactly the same ) .From this and some web searching , I conclude that the enumerator above is not always thread-safe . The documentation appears to suggest that thread safety is guaranteed only if the table objects are public static , but that has n't made a difference for me.Could someone suggest how to resolve this ? Is there a standard pattern for parallelizing Azure table queries ? var query = new TableQuery < DynamicTableEntity > ( ) .Where ( TableQuery.GenerateFilterCondition ( `` PartitionKey '' , QueryComparisons.Equal , myPartitionKey ) ) ; foreach ( DynamicTableEntity entity in myTable.ExecuteQuery ( query ) ) { // Process entity here . } Parallel.ForEach ( myTable.ExecuteQuery ( query ) , ( entity , loopState ) = > { // Process entity here in a thread-safe manner . // Edited to add : Details of the loop body below : // This is the essence of the fixed loop body : lock ( myLock ) { DataRow myRow = myDataTable.NewRow ( ) ; // [ Add entity data to myRow . ] myDataTable.Rows.Add ( myRow ) ; } // Old code ( apparently not thread-safe , though NewRow ( ) is supposed to create // a DataRow based on the table 's schema without changing the table state ) : /* DataRow myRow = myDataTable.NewRow ( ) ; lock ( myLock ) { // [ Add entity data to myRow . ] myDataTable.Rows.Add ( myRow ) ; } */ } ) ;",Azure TableQuery thread safety with Parallel.ForEach "C_sharp : I want to implement paging on a list of data . The list has some fake items in itself as flag items for doing some specific work on the data . A simplified version of what I have done is as below : But my problem with this way is that the fake items will be counted in the Skip and Take methods of the Linq.I want to know if it is possible to ignore those fake items in the Skip method then apply Skip on the list , including fake items by some changes in the Take method for example or something similar.Edit : The first list is ordered before doing paging and those fake items are in ordered places also . You should know the order of the list is important for me . List < Model > list = _myServiceContract.MyServiceMethod ( MySearchModel ) ; pagedData = list.Skip ( ( page - 1 ) * pageSize ) .Take ( pageSize ) ;",Is it possible to ignore a list item with skip method of linq then apply skip on a list without losing that item from the list "C_sharp : EDIT : I do n't want to use Consul or ZooKeeper . I want to find the address of a web service on a local network.What are the gRPC equivalents of service discovery classes in WCF , like : ServiceDiscoveryBehavior and UdpDiscoveryEndpoint and DiscoveryClient used in this example : Service : Client : using ( ServiceHost serviceHost = new ServiceHost ( typeof ( CalculatorService ) , baseAddress ) ) { // Add calculator endpoint serviceHost.AddServiceEndpoint ( typeof ( ICalculator ) , new WSHttpBinding ( ) , string.Empty ) ; // ** DISCOVERY ** // // Make the service discoverable by adding the discovery behavior ServiceDiscoveryBehavior discoveryBehavior = new ServiceDiscoveryBehavior ( ) ; serviceHost.Description.Behaviors.Add ( discoveryBehavior ) ; // Send announcements on UDP multicast transport discoveryBehavior.AnnouncementEndpoints.Add ( new UdpAnnouncementEndpoint ( ) ) ; // ** DISCOVERY ** // // Add the discovery endpoint that specifies where to publish the services serviceHost.Description.Endpoints.Add ( new UdpDiscoveryEndpoint ( ) ) ; // Open the ServiceHost to create listeners and start listening for messages . serviceHost.Open ( ) ; } { DiscoveryClient discoveryClient = new DiscoveryClient ( new UdpDiscoveryEndpoint ( ) ) ; Collection < EndpointDiscoveryMetadata > calculatorServices = ( Collection < EndpointDiscoveryMetadata > ) discoveryClient.Find ( new FindCriteria ( typeof ( ICalculator ) ) ) .Endpoints ; discoveryClient.Close ( ) ; CalculatorClient client = new CalculatorClient ( ) ; client.Endpoint.Address = calculatorServices [ 0 ] .Address ; }",gRPC equivalent of WCF service discovery "C_sharp : This might get downvoted , but this question has been bothering me since yesterday.. until I found a link then I knew I was n't really crazy lol : Enum as instance variablesI 'm basically asking the opposite of the OP 's question . Given : Although this is Java and enums do differ somewhat in both languages how is it that I ca n't do coffee.BIG or coffee.BIG.SMALL ( though it makes little sense when reading it , it should be possible considering coffee is of type Coffee ) in C # ? enum Coffee { BIG , SMALL } public class MyClass { private Coffee coffee ; // Constructor etc . }",Why ca n't we access enum values from an enum instance in C # ? "C_sharp : For example , in the below code an 'image'object will be created and then garbage collected at some unknown point in the futureWhat aboutIn this case is the object garbage collected once it moves out of scope i.e . After the end of MyFunction . If not is there somewhere to enforce this ? void MyFunction ( ) { Bitmap image = RetrieveImage ( ) ; DoSomething ( image ) ; } void MyFunction ( ) { DoSomething ( RetrieveImage ( ) ) ; }",Is it possible to write C # so that objects are garbage collected when they fall out of scope ? "C_sharp : With code like this : Quite a lot of information can be fetched about the schema , but the metadata version ( ie : GetSchema ( ) ) does n't return anything about synonyms.We use Synonyms quite heavily in our environment . Can I get Schema information about them using GetSchema , or do I need another method ? DataTable schema = conn.GetSchema ( ) ; DataTable tables = conn.GetSchema ( `` Tables '' ) ; DataTable columns = conn.GetSchema ( `` Columns '' ) ;",How can I use SqlConnection.GetSchema to get synonym information ? "C_sharp : Not sure if this is possible or not , but here 's my scenario : In about 10 of our aspx files we have the same javaScript function , I want remove this from all these pages and put it in the main javaScript file ( main.js ) which is global to all pages , so it 's easier to maintain . the javaScript code in the current aspx pages looks something like this : Not sure how to get the server side values for those variables in main.js.also this may also be relevant : '' regEx '' inside < % = regEx [ `` regEx_gaid '' ] % > is a dictionary collection on the server side and `` regEx_gain '' is key to access the value of the regEx dictionary . Thanks . var regEx_gaid = < % = regEx [ `` regEx_gaid '' ] % > ; var regEx_wCard = < % = regEx [ `` regEx_wildCard '' ] % > ; var regEx_fCss = < % = regEx [ `` regEx_flattenCss '' ] % > ; var regEx_iCss = < % = regEx [ `` regEx_inlineCss '' ] % > ; ... function doSomething ( ) { // do something with those variables declared above . }",Executing serverside code from javaScript "C_sharp : I 'm using telerik RadGridView in my WPF application . One of the column has the following functionality , When the user changes the value of the column a command is fired as a event and a pop is shown . Using the pop up result ( Yes or No ) i 'm updating the collection.Now i 'm facing an issue here.Issue : The user is changing the value of that column in one of the row and before the alert appears he is changing in another row of same column . So the application works in a different way and functionality collapses.Work Tried : I tried to disable the grid once the event fires and enable after the function is complete . But still the user is very fast even before the event triggers he is changing the value.XAML : Command : ViewModel : I just need something like restricting the user not to change the second value until the event triggers and he selects something ( Yes/No ) from the popup.Can someone help me with this ? < telerik : GridViewDataColumn Name= '' grdItemBuildColumn '' DataMemberBinding= '' { Binding Build , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' IsReadOnlyBinding= '' { Binding IsEnable , Mode=OneWay , UpdateSourceTrigger= PropertyChanged } '' > < telerik : GridViewDataColumn.CellEditTemplate > < DataTemplate > < telerik : RadMaskedNumericInput Value= '' { Binding Build , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' Mask= '' # 1.0 '' Placeholder= '' `` TextMode= '' PlainText '' AllowInvalidValues= '' False '' IsClearButtonVisible= '' False '' AutoFillNumberGroupSeparators= '' False '' ext : MaskedInputExtensions.Minimum= '' 0 '' SelectionOnFocus= '' SelectAll '' AcceptsReturn= '' False '' > < i : Interaction.Triggers > < i : EventTrigger EventName= '' ValueChanged '' > < i : InvokeCommandAction Command= '' { Binding BuidValueChangedCommand , Source= { StaticResource MarketSeriesViewModel } } '' / > < /i : EventTrigger > < /i : Interaction.Triggers > < /telerik : RadMaskedNumericInput > < /DataTemplate > < /telerik : GridViewDataColumn.CellEditTemplate > < /telerik : GridViewDataColumn > public ICommand BuidValueChangedCommand { get { return new RelayCommand ( BuildValueChanged ) ; } } private void BuildValueChanged ( ) { // Ask confirmation for delete . if ( ShowMessages.MessageBox ( `` This will be removed from the collection '' , `` Application '' ) ) { DeleteItem ( SelectedItem.Id ) } else { Item bo = RestoreBuild ( SelectedItem ) ; SelectedItem = bo ; } }",Disable grid before event fire WPF "C_sharp : According to the language specification lock ( obj ) statement ; would be compiled as : However , it is compiled as : That seems to be a lot more complicated than necessary . So the question is , what 's the advantage of that implementation ? object lockObj = obj ; // ( the langspec does n't mention this var , but it would n't be safe without it ) Monitor.Enter ( lockObj ) ; try { statement ; } finally { Monitor.Exit ( lockObj ) ; } try { object lockObj = obj ; bool lockTaken = false ; Monitor.Enter ( lockObj , ref lockTaken ) ; statement ; } finally { if ( lockTaken ) Monitor.Exit ( lockObj ) ; }","What 's the advantage of Monitor.Enter ( object , ref bool ) over Monitor.Enter ( object ) ?" "C_sharp : I 'm creating an application which displays rows of tables according to a map config file . Right now , I have XAML that displays the outer bound of the rectangle in the correct location , but I ca n't find any information on drawing subdividing lines , which are held in the data source as numTablesWide and numTablesTall.Here 's the XAML that draws the box in the correct locationThanks ! < ListBox.ItemContainerStyle > < Style TargetType= '' ListBoxItem '' > < Setter Property= '' Template '' > < ! -- Selection stuff -- > < /Setter > < Setter Property= '' Canvas.Top '' Value= '' { Binding y } '' / > < Setter Property= '' Canvas.Left '' Value= '' { Binding x } '' / > < Setter Property= '' VerticalContentAlignment '' Value= '' Stretch '' / > < Setter Property= '' HorizontalContentAlignment '' Value= '' Stretch '' / > < Setter Property= '' Padding '' Value= '' 5 '' / > < Setter Property= '' Panel.ZIndex '' Value= '' { Binding z } '' / > < Setter Property= '' ContentTemplate '' > < Setter.Value > < DataTemplate > < Grid > < Path Data= '' { Binding data } '' Stroke= '' { Binding brush } '' StrokeThickness= '' 2 '' Stretch= '' Fill '' / > < TextBlock Text= '' { Binding i } '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /Grid > < /DataTemplate > < /Setter.Value > < /Setter > < Style.Triggers > < DataTrigger Binding= '' { Binding type } '' Value= '' tableBlock '' > < Setter Property= '' ContentTemplate '' > < Setter.Value > < DataTemplate > < Grid > < Rectangle Fill= '' { Binding fill } '' Stroke= '' Black '' StrokeThickness= '' 5 '' Width= '' { Binding width } '' Height= '' { Binding height } '' Panel.ZIndex= '' 50 '' / > < TextBlock Text= '' { Binding id } '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /Grid > < /DataTemplate > < /Setter.Value > < /Setter > < /DataTrigger > < /Style.Triggers > < /Style > < /ListBox.ItemContainerStyle >",How can I draw subdivide a databound rectangle in the XAML ? "C_sharp : I am trying to auto-map a Superhero model to a a Supervillan model , each has a similar dictionary declaration : Superhero : Supervillan : I tried following the advice in other similar threads , but have n't been successful . Here is my latest attempt , that fails on execution : How can I map my Superhero SuperNumber dictionary to my Supervillan SuperNumber dictionary ? Note : the SomeHero/SomeVillan models will have unique properties , but I 'm not concerned with them for this question . public class Superheroes { public Dictionary < string , SomeHero > > SuperNumber { get ; set ; } } public class SomeHero { // unique properties } public class Supervillans { public Dictionary < string , SomeVillan > > SuperNumber { get ; set ; } } public class SomeVillan { // unique properties } CreateMap < KeyValuePair < string , Superheroes > , KeyValuePair < string , Supervillans > > ( ) ;",c # automapper dictionary to dictionary "C_sharp : I wrote a method to get Attribute Value By Property : For Example : I have Attribute [ Map ( Name = `` MenuItem , Availability '' ) ] I call GetAttributeValueByNameAttributeAndProperty ( codeclass , `` Map '' , `` Name '' ) After that method get CodeAttribute.Value and return string : Name = `` MenuItem , Availability '' After I remove `` Name = `` and extra characters and Split by `` , '' But my Senior Programmer told me that this method is inflexible and I need to find a more convenient way get inner data in CodeAttribute.Value.Do you have any ideas / examples ? public string GetAttributeValueByNameAttributeAndProperty ( CodeClass cc , string nameAttribute , string nameProperty ) { var value = `` '' ; foreach ( CodeAttribute ca in cc.Attributes ) { if ( ca.Name.Contains ( nameAttribute ) & & ca.Value.Contains ( nameProperty ) ) { value = ca.Value.Remove ( 0 , ca.Value.IndexOf ( nameProperty ) ) ; value = value.Replace ( `` `` , '' '' ) ; if ( value.Contains ( `` , '' ) ) value = value.Remove ( ca.Value.IndexOf ( `` , '' ) ) ; } } return value ; }",How get Attribute Value in CodeAttribute "C_sharp : Both of these are accepted by the compiler : Is one way preferable to the other ? ToString ( ) or not ToString ( ) , that is the question . ssMinnow = listStrLineElements [ VESSEL_TO_AVOID ] .ToString ( ) ; ssMinnow = listStrLineElements [ VESSEL_TO_AVOID ] ;","Is ToString ( ) here good , bad , or simply redundant ?" "C_sharp : i have a pop up and i want to close it when i tap anywhere outside the pop up . i searched and everyone advised me to use the property IsLightDismissEnabled ; however if i touch outside , it will only remove the pop oup leaving everything inactive with a grey like screen as if it doesnt close the pop up completelythis is my code snippet : this is my code for the eventsAm I missing anything ? thank you in advance < Popup x : Name= '' logincontroler '' IsOpen= '' False '' Margin= '' 0,190,896,276 '' IsLightDismissEnabled= '' True '' > < StackPanel Height= '' 300 '' Width= '' 470 '' x : Name= '' popup '' FlowDirection= '' RightToLeft '' > < Grid Width= '' 470 '' Background= '' White '' > < Grid.RowDefinitions > < RowDefinition Height= '' 70 '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < RichEditBox Grid.Row= '' 1 '' Height= '' 250 '' TextWrapping= '' Wrap '' FontSize= '' 20 '' Name= '' notesPopupTextBox '' FlowDirection= '' LeftToRight '' / > < StackPanel Grid.Row= '' 0 '' Orientation= '' Horizontal '' Background= '' # FFE3E3E5 '' > < Button Name= '' CanclePopupButton '' Content= '' Cancel '' Width= '' 64 '' Height= '' 64 '' Click= '' CanclePopupButton_Click '' / > < Button Name= '' ClearNotePopupButton '' Content= '' Clear '' Width= '' 64 '' Height= '' 64 '' Click= '' ClearNotePopupButton_Click '' / > < Button Name= '' saveNoteButton '' Content= '' Save '' Width= '' 64 '' Height= '' 64 '' Click= '' saveNoteButton_Click '' / > < TextBlock FontWeight= '' Medium '' FontSize= '' 40 '' Foreground= '' # 2a2a86 '' Margin= '' 170 12 0 0 '' > Note < /TextBlock > < /StackPanel > < /Grid > < /StackPanel > < /Popup > private void ShowButton_Click ( object sender , RoutedEventArgs e ) { logincontroler.IsOpen = true ; flipView1.IsEnabled = false ; } private void CanclePopupButton_Click ( object sender , RoutedEventArgs e ) { logincontroler.IsOpen = false ; flipView1.IsEnabled = true ; }",IsLightDismissEnabled= '' True '' is not actually dismissing the popup "C_sharp : I am using the Logical CallContext to flow information back across a series of awaits . Interestingly , in my test console app , everything works fine . However , when running my unit test in the context of a VS UnitTest , the call context does not seems to flow across the awaits.Inside of the method : SendRequestAsyncImpl the call context is being set , and when I query the logical call context from a breakpoint at the moment the method returns , the call context is set just fine.However , after the await returns in the below line : The logical call context is empty . I thought maybe the problem would be fixed by setting ConfigureAwait ( true ) rather than false . But that does not fix the issue.It does n't matter what I try to flow , even setting a simple value type inside of SendRequestAsyncImpl like : is not retrievable after the await.Why is this working from my console app ? But not from my unit test ? What 's different ? ( I 've seen some other stack overflow questions that refer to AppDomain issues . But I ca n't even marshal a bool across the await . The ability to marshal the data does n't appear to be the issue here . ) Message response = await SendRequestAsyncImpl ( m , true ) .ConfigureAwait ( false ) ; System.Runtime.Remoting.Messaging.CallContext.LogicalSetData ( `` flag '' , true ) ;",LogicalCallContext flows across await in Console App but not VS UnitTest "C_sharp : I 'm trying the new Azure Mobile App . Created the instance in Azure , and then downloaded the Visual Studio package . Updated all components via Nuget . And now when I run it , am getting following error : Found another post that recommends to upgrade Windows Azure Mobile Services , which I have done so.Am running Razor Engine 3.7.0 < Error > < Message > An error has occurred. < /Message > < ExceptionMessage > Method not found : 'System.String RazorEngine.Templating.ITemplate.Run ( RazorEngine.Templating.ExecuteContext ) '. < /ExceptionMessage > < ExceptionType > System.MissingMethodException < /ExceptionType > < StackTrace > at Microsoft.Azure.Mobile.Server.Content.HtmlActionResult.ExecuteAsync ( CancellationToken cancellationToken ) at System.Web.Http.Controllers.ApiControllerActionInvoker. < InvokeActionAsyncCore > d__0.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Web.Http.Controllers.ActionFilterResult. < ExecuteAsync > d__2.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Web.Http.Filters.AuthorizationFilterAttribute. < ExecuteAuthorizationFilterAsyncCore > d__2.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Web.Http.Controllers.AuthenticationFilterResult. < ExecuteAsync > d__0.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Web.Http.Controllers.ExceptionFilterResult. < ExecuteAsync > d__0.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Web.Http.Controllers.ExceptionFilterResult. < ExecuteAsync > d__0.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- -at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Web.Http.Dispatcher.HttpControllerDispatcher. < SendAsync > d__1.MoveNext ( ) < /StackTrace > < /Error >",Method not found : 'System.String RazorEngine.Templating.ITemplate.Run "C_sharp : I was surprised recently to discover that the compiler is apparently not strict about comparing interface references and am wondering why it works this way.Consider this code : The compiler says that I ca n't compare c1 == c2 , which follows . The types are totally unrelated . Yet , it does permit me to compare i1 == i2 . I would expect it to error here with a compile-time failure but I was surprised to find out that you can compare any interface to any other and the compiler will never complain . I could compare , for example ( I1 ) null == ( IDisposable ) null and no problem.Are interfaces not objects ? Are they a special type of reference ? My expectation would be that a == would result in either a straight reference compare or a call into the concrete class 's virtual Equals.What am I missing ? class Program { interface I1 { } interface I2 { } class C1 : I1 { } class C2 : I2 { } static void Main ( string [ ] args ) { C1 c1 = new C1 ( ) ; C2 c2 = new C2 ( ) ; I1 i1 = c1 ; I2 i2 = c2 ; bool x = c1 == c2 ; bool y = i1 == i2 ; } }",Why can unrelated c # interface references be compared without compiler error ? "C_sharp : I have code that looks something like this : Should n't the Any check account for index 0 ? Am I doing something wrong , or does CodeContracts just not recognize this case ? public class Foo < T > : ObservableCollection < T > { private T bar ; public Foo ( IEnumerable < T > items ) : base ( items.ToList ( ) ) { Contract.Requires ( items ! = null ) ; if ( this.Any ( ) ) this.bar = this [ 0 ] ; // gives 'requires unproven : index < @ this.Count ' } }",Why does CodeContracts warn me that `` requires unproven : index < @ this.Count '' even though I have already checked the count ? "C_sharp : We are trying to use an objectanimator proxy to animate the TopMargin property in Android ( Xamarin ) .However , we get this error : [ PropertyValuesHolder ] Could n't find setter/getter for property TopMargin with value type floatNote : we tried TopMargin , topMargin , GetTopMargin , getTopMargin , etc. , thinking that it might be an issue of casing conversion betwen Java and C # , but it does n't look to be the case.Our code in the Activity starting the animation : Our proxy class : Any advise ? a pointer to a working Xamarin sample using a proxy would be helpful.thanks . translation = new int [ ] { 0 , 300 } ; var anim2 = ObjectAnimator.OfInt ( new MarginProxyAnimator ( myview ) , `` TopMargin '' , translation ) ; anim2.SetDuration ( 500 ) ; anim2.Start ( ) ; public class MarginProxyAnimator : Java.Lang.Object { /// ... other code ... public int getTopMargin ( ) { var lp = ( ViewGroup.MarginLayoutParams ) mView.LayoutParameters ; return lp.TopMargin ; } public void setTopMargin ( int margin ) { var lp = ( ViewGroup.MarginLayoutParams ) mView.LayoutParameters ; lp.SetMargins ( lp.LeftMargin , margin , lp.RightMargin , lp.BottomMargin ) ; mView.RequestLayout ( ) ; } }",ObjectAnimator Proxy to Animate TopMargin ca n't find setting/getter "C_sharp : I noticed something curious when messing around with nested classes and outputting the name of the type to a console window . I was wondering if someone could explain it a bit for me . When calling GetType ( ) on the main class , it returns what I would expect , which was the name of the class after the relevant namespaces . i.e . Namespace.Namespace.ClassnameHowever , when I call a function from within the enclosing class to return the type of the nested class I get the value returned as this : Why is it not simply returned as dot notation . Why the + symbol ? I am just curious as to what is going on in the background that causes this notation . Namespace.Namespace.ClassNameEnclosing + ClassNameNested .",Nested Class .GetType ( ) "C_sharp : Prob something im overlooking but this problem has annoyed me greatly.im trying to get a value from a dataset and then use it to do some calculations.in the dataset its seen as an object , so i need to cast it to an int or double.For some reason im getting a stupid error thats getting on my nerves . heres the code.Thrown : `` Specified cast is not valid . '' ( System.InvalidCastException ) when casting form a number , must be less than inifnite . This is the annoying error im getting . now i get the data from my dataset , which gets its data from a stored procedure.I believe the `` Qty '' field type is currency ( yeh , why is qty currency haha , not my tables ! ) . in my datagrid view it looks like 1.000 , is this due to a type conversion ? how would i rectify this ? Many Thanks in Advance ! private void SpendsAnalysis ( ) { float tempQty = 0 ; float tempPrice = 0 ; double tempTot = 0 ; double total = 0 ; foreach ( DataGridViewRow row in dataGridView1.Rows ) { tempQty = ( float ) row.Cells [ `` Qty '' ] .Value ; tempPrice = ( float ) row.Cells [ `` Unit '' ] .Value ; tempTot = tempQty * tempPrice ; total += tempTot ; } textBox7.Text = total.ToString ( ) ; }",c # cast error ( infinte value ... .what ? ) "C_sharp : The most basic way of representing a quadrile plane ( a bunch of squares ) is to use a two-dimensional array.In C # we declare this as int [ , ] and can make our plane as big as we want : To `` move '' an item on the plane , we would just asign it toa new `` position '' So , how would you represent a hexagonal plane ( a bunch of hexagons ) and how would movement from one position to the next be handled ? Note : This is not purely theoretical , as I have an idea for a little game in my head which would require this kind of movement , but I ca n't wrap my head around how it would be done . I 've looked through some of the other questions here , but ca n't really find a good match ... string [ 3,3 ] = > tic-tac-toe board ( or similar ) string [ 8,8 ] = > chess or checkers board //using our tic-tac-toe board : string [ 0,0 ] = `` x '' ; //top-leftstring [ 1,1 ] = `` o '' ; //middle-middle//to movestring [ 0,1 ] = bN ; //Black Knight 's starting positonstring [ 2,2 ] = bN ; //Black Knight movesstring [ 0,1 ] = String.Empty ;",Form and movement representation of a hexagonal plane "C_sharp : I run the following websocket client code on windows and everything works fine - like expected . But if the code is published for linux-arm and copied to a RaspberryPi3 ( runs under Raspian ) it will end up in an AuthenticationException.csproj file content : The connection attempt : ( the point where the exception is thrown ) Exception stack : The target websocket server is running behind a nginx proxy on Ubuntu . I think the problem relies on the client because if the code is executed on windows everything works fine.I tried also importing the CA certifacte into Raspians `` certificate store '' . With no luck.UPDATE : A http connection ( ws : // ) works also on linux . It seems , the WebSocketClient did n't trust my LetsEncrypt cert ? < PropertyGroup > < OutputType > Exe < /OutputType > < TargetFramework > netcoreapp2.0 < /TargetFramework > < /PropertyGroup > < ItemGroup > < PackageReference Include= '' Newtonsoft.Json '' Version= '' 10.0.3 '' / > < PackageReference Include= '' System.Net.WebSockets.Client '' Version= '' 4.3.1 '' / > < /ItemGroup > private readonly ClientWebSocket _socket ; public ApiConnection ( ) { _socket = new ClientWebSocket ( ) ; } public async Task Connect ( ) { // the uri is like : wss : //example.com/ws await _socket.ConnectAsync ( new Uri ( _settings.WebSocketUrl ) , CancellationToken.None ) ; if ( _socket.State == WebSocketState.Open ) Console.WriteLine ( `` connected . `` ) ; } System.Net.WebSockets.WebSocketException ( 0x80004005 ) : Unable to connect to the remote server -- - > System.Security.Authentication.AuthenticationException : The remote certificate is invalid according to the validation procedure . at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Net.Security.SslState.StartSendAuthResetSignal ( ProtocolToken message , AsyncProtocolRequest asyncRequest , ExceptionDispatchInfo exception ) at System.Net.Security.SslState.CheckCompletionBeforeNextReceive ( ProtocolToken message , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartSendBlob ( Byte [ ] incoming , Int32 count , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.ProcessReceivedBlob ( Byte [ ] buffer , Int32 count , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartReadFrame ( Byte [ ] buffer , Int32 readBytes , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartReceiveBlob ( Byte [ ] buffer , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.CheckCompletionBeforeNextReceive ( ProtocolToken message , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartSendBlob ( Byte [ ] incoming , Int32 count , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.ProcessReceivedBlob ( Byte [ ] buffer , Int32 count , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartReadFrame ( Byte [ ] buffer , Int32 readBytes , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartReceiveBlob ( Byte [ ] buffer , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.CheckCompletionBeforeNextReceive ( ProtocolToken message , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartSendBlob ( Byte [ ] incoming , Int32 count , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.ProcessReceivedBlob ( Byte [ ] buffer , Int32 count , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.StartReadFrame ( Byte [ ] buffer , Int32 readBytes , AsyncProtocolRequest asyncRequest ) at System.Net.Security.SslState.PartialFrameCallback ( AsyncProtocolRequest asyncRequest ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Net.Security.SslState.InternalEndProcessAuthentication ( LazyAsyncResult lazyResult ) at System.Net.Security.SslState.EndProcessAuthentication ( IAsyncResult result ) at System.Net.Security.SslStream.EndAuthenticateAsClient ( IAsyncResult asyncResult ) at System.Threading.Tasks.TaskFactory ` 1.FromAsyncCoreLogic ( IAsyncResult iar , Func ` 2 endFunction , Action ` 1 endAction , Task ` 1 promise , Boolean requiresSynchronization ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Net.WebSockets.WebSocketHandle. < ConnectAsyncCore > d__24.MoveNext ( ) at System.Net.WebSockets.WebSocketHandle. < ConnectAsyncCore > d__24.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Net.WebSockets.ClientWebSocket. < ConnectAsyncCore > d__16.MoveNext ( ) -- - End of stack trace from previous location where exception was thrown -- - at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) at System.Runtime.CompilerServices.TaskAwaiter.GetResult ( )",ClientWebSocket on Linux throws AuthenticationException ( SSL ) "C_sharp : In a code review a co-worker changed my code to pass in a Stream as a parameter . He said this was to ensure that the responsibility to dispose of the object is clear to the caller . In a sense I can empathize . I would prefer the object creator to also be responsible for cleanup.On the other other hand , neither method makes the need for a using any more clear . I prefer the simpler method call as well.TakeVSIs there any technical reason to add the extra param ? public static TextReader Serialize < T > ( T obj ) where T : new ( ) { if ( obj == null ) throw new ArgumentNullException ( `` obj '' ) ; return Serialize < T > ( obj , null ) ; } public static void Serialize < T > ( T obj , TextWriter outbound ) where T : new ( ) { if ( obj == null ) throw new ArgumentNullException ( `` obj '' ) ; Serialize < T > ( obj , outbound , null ) ; }",Should disposable objects be passed in ? "C_sharp : I have an NHibernate Linq query which is n't working how I would expect.The problem seems to come from using a nullable int column from a left joined table in the where clause . This is causing the join to act like an inner join.The SQL produced by this looks like ( from the join onwards - you do n't need to see all the selects ) So the part that is causing the problem is line 5 of the snippet above . As you can see , NHibernate is trying to do an 'old-school ' join on my WorkflowCaseView View . This causes the query to exclude otherwise valid actions which do not have a CaseId in the WorkflowAction table.Could anyone explain why NHibernate is writing this SQL , and how I might encourage it to produce a better query ? Thanks ! Important bits from WorkflowActionMapImportant bits from WorkflowCaseViewMapLooking at this , I wonder if I should have a HasMany going back the other way ... EDIT . Does n't seem to help var list = this.WorkflowDiaryManager.WorkflowActionRepository.All .Fetch ( x = > x.CaseView ) .Fetch ( x = > x.WorkflowActionType ) .ThenFetchMany ( x = > x.WorkflowActionPriorityList ) .Where ( x = > x.AssignedUser.Id == userId || x.CaseView.MooseUserId == userId ) from Kctc.WorkflowAction workflowac0_ left outer join Kctc.WorkflowCaseView workflowca1_ on workflowac0_.CaseId=workflowca1_.CaseId left outer join Kctc.WorkflowActionType workflowac2_ on workflowac0_.WorkflowActionTypeId=workflowac2_.WorkflowActionTypeId left outer join Kctc.WorkflowActionPriority workflowac3_ on workflowac2_.WorkflowActionTypeId=workflowac3_.WorkflowActionTypeId , Kctc.WorkflowCaseView workflowca4_ where workflowac0_.CaseId=workflowca4_.CaseId and ( workflowac0_.AssignedUser= @ p0 or workflowca4_ . [ MooseUserId ] = @ p1 ) ; @ p0 = 1087 [ Type : Int32 ( 0 ) ] , @ p1 = 1087 [ Type : Int32 ( 0 ) ] Table ( `` Kctc.WorkflowAction '' ) ; Id ( x = > x.Id ) .GeneratedBy.Identity ( ) .Column ( `` WorkflowActionId '' ) ; References ( x = > x.WorkflowActionType ) .Column ( `` WorkflowActionTypeId '' ) .Unique ( ) ; References ( x = > x.CompletedBy ) .Column ( `` CompletedBy '' ) ; References ( x = > x.CaseView ) .Column ( `` CaseId '' ) .Not.Update ( ) .Unique ( ) ; References ( x = > x.AssignedUser ) .Column ( `` AssignedUser '' ) ; Table ( `` Kctc.WorkflowCaseView '' ) ; Id ( x = > x.Id ) .Column ( `` CaseId '' ) ; Map ( x = > x.MooseUserId ) .Nullable ( ) ;",NHibernate is producing SQL with a bad join "C_sharp : I have a simple program . It runs .NET 4.5 and is built in Visual Studio 2013.D : \\MyDir is full of .xlsx files and no .xls files . When I run the program on Windows 8.1 x64 , the filter for *.xls returns no results . When I run the same program , with the same .NET version on Windows 7 x86 , the *.xls filter returns the same results as the *.xlsx filter.The test folders on both systems definitely contain the same data.Am I missing something , or is this a bug in .NET and/or Windows ? The respective code : Edit 1When I navigate to the directory using the command prompt in Windows 8.1 x64 : dir *.xlsx returns all files as expecteddir *.xls returns 'File Not Found'Windows 7 returns the expected files on both of the above commands.My guess is that .NET uses this command under the hood , thus the above results ? using System ; using System.Collections.Generic ; using System.IO ; using System.Linq ; using System.Text ; using System.Threading ; using System.Threading.Tasks ; namespace throw_test { static class Program { static void Main ( ) { int fileCount1 = Directory.GetFiles ( `` D : \\MyDir '' , `` *.xlsx '' ) .Length ; int fileCount2 = Directory.GetFiles ( `` D : \\MyDir '' , `` *.xls '' ) .Length ; Console.WriteLine ( `` File Count 1 : `` + fileCount1 ) ; Console.WriteLine ( `` File Count 2 : `` + fileCount2 ) ; Console.Read ( ) ; } } }",Directory.GetFiles - different output dependent on OS "C_sharp : I just saw this codeMSDN article is not helping much . What is the usage of this line ? # pragma warning disable 659 , 660 , 661",What is the use of # pragma warning in C # ? "C_sharp : I 'd been programming in C # , but was frustrated by the limitations of its type system . One of the first things , I learned about Scala was that Scala has higher kinded generics . But even after I 'd looked at a number of articles , blog entries and questions I still was n't sure what higher kinded generics were . Anyway I 'd written some Scala code which compiled fine , Does this snippet use higher kinds ? And then I thought maybe I 'm already using higher kinded generics . As I understand it I was , but then as I now I understand it I had already been happily using higher kinded types in C # before I 'd even heard of Scala . Does this snipet use higher kinded type ? So to avert further confusion I thought it would be useful to clarify for each of Java , C # and Scala what they allow in terms of Higher kinded types , wild cards and the use of open / partially open types . As the key difference between C # and Scala seems to be that Scala allows wild cards and open types , where as C # has no wild card and requires all generic types to be closed before use . I know they are some what different but I think it would be useful to relate the existence of these features to their equivalent in C++ Templates.So is the following correct ? This table has been corrected for Alexey 's answer abstract class Descrip [ T < : DTypes , GeomT [ _ < : DTypes ] < : GeomBase [ _ ] ] ( newGeom : NewGeom [ GeomT ] ) { type GeomType = GeomT [ T ] val geomM : GeomT [ T ] = newGeom.apply [ T ] ( ) } namespace ConsoleApplication3 { class Class1 < T > { List < List < T > > listlist ; } } Lang : Higher-kind Wild-card Open-typesScala yes yes yesC # no no noJava no yes noC++ yes yes yes","Scala : Higher kinded , open-type and wild card generics in Java , C # , Scala and C++" C_sharp : This code returns fields that I created but also some system fields ( I 'm in WPF app ) I did n't create myself : How to exclude the system fields and keep only my own ? Update : these fields are not fields I inherited from my own class either . FieldInfo [ ] fieldInfos ; fieldInfos = this.GetType ( ) .GetFields ( BindingFlags.NonPublic | BindingFlags.Instance ) ;,C # Reflection why GetFields list fields that I have n't created ? How to exclude them ? "C_sharp : Within a string , I 'm trying to update multiple instances of the same word with different values . This is an overly simplified example , but given the following string : The first instance of the word color I want to replace with `` red '' , the second instance should be `` green '' and the third instance should be `` blue '' . What I thought to try was a regex pattern to find boundried words , interate through a loop and replace them one at a time . See the example code below.However , the word `` color '' never gets replaced with the appropriate color name . I ca n't find what I 've been doing wrong . `` The first car I saw was color , the second car was color and the third car was color '' var colors = new List < string > { `` reg '' , `` green '' , `` blue '' } ; var sentence = `` The first car I saw was color , the second car was color and the third car was color '' ; foreach ( var color in colors ) { var regex = new Regex ( `` ( \b [ color ] +\b ) '' ) ; sentence = regex.Replace ( sentence , color , 1 ) ; }",Replacing each instance of a word in a string with a unique value "C_sharp : I saw this piece of C # code in one of the msdn articles : I am fairly new to pointers . I understand most of this code , but it would be great if someone can help me understand this line in the above code in more detail : using System ; class Test { public static unsafe void Main ( ) { int* fib = stackalloc int [ 100 ] ; int* p = fib ; *p++ = *p++ = 1 ; for ( int i=2 ; i < 100 ; ++i , ++p ) *p = p [ -1 ] + p [ -2 ] ; for ( int i=0 ; i < 10 ; ++i ) Console.WriteLine ( fib [ i ] ) ; } } *p++ = *p++ = 1",Pointer increment and chaining precedence in C # "C_sharp : I am using a Castle Windsor Typed Factory . In our registration code it is set up so it can create a Transient component : From my understanding of the Castle Windsor Typed Factory documentation I thought that a Transient object must be released by a Typed Factory method , otherwise the Typed Factory would keep a reference to the object . I tried to prove this by writing a test that used the method explained in this StackOverflow article.But to my surprise it does n't actually fail , implying that although I have not released the transient object back to the factory , it can still be reclaimed by the GC . I 'm concerned that perhaps my test is misleading and there really is a leak.So my question is : is my test wrong , or is the documentation wrong ? Here 's the test : container.AddFacility < TypedFactoryFacility > ( ) ; container.Register ( Component.For < IThingFactory > ( ) .AsFactory ( ) ) ; container.Register ( Component.For < IThing > ( ) .ImplementedBy < TransientObject > ( ) .Named ( `` TransientObject '' ) .LifeStyle.Transient ) ; var factory = container.Resolve < IThingFactory > ( ) ; WeakReference reference = null ; new Action ( ( ) = > { var service = factory.GetTransientObject ( ) ; reference = new WeakReference ( service , true ) ; } ) ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Assert.That ( reference.Target , Is.Null , `` reference should be null '' ) ;",Castle Windsor Typed Factory without release does not leak "C_sharp : I discovered that iterator methods in value types are allowed to modify this.However , due to limitations in the CLR , the modifications are not seen by the calling method . ( this is passed by value ) Therefore , identical code in an iterator and a non-iterator produce different results : Output : Why is n't it a compiler error ( or at least warning ) to mutate a struct in an iterator ? This behavior is a subtle trap which is not easily understood.Anonymous methods , which share the same limitation , can not use this at all.Note : mutable structs are evil ; this should never come up in practice . static void Main ( ) { Mutable m1 = new Mutable ( ) ; m1.MutateWrong ( ) .ToArray ( ) ; //Force the iterator to execute Console.WriteLine ( `` After MutateWrong ( ) : `` + m1.Value ) ; Console.WriteLine ( ) ; Mutable m2 = new Mutable ( ) ; m2.MutateRight ( ) ; Console.WriteLine ( `` After MutateRight ( ) : `` + m2.Value ) ; } struct Mutable { public int Value ; public IEnumerable < int > MutateWrong ( ) { Value = 7 ; Console.WriteLine ( `` Inside MutateWrong ( ) : `` + Value ) ; yield break ; } public IEnumerable < int > MutateRight ( ) { Value = 7 ; Console.WriteLine ( `` Inside MutateRight ( ) : `` + Value ) ; return new int [ 0 ] ; } } Inside MutateWrong ( ) : 7After MutateWrong ( ) : 0Inside MutateRight ( ) : 7After MutateRight ( ) : 7",Why can iterators in structs modify this ? "C_sharp : Let us assume the code I use to iterate through a node list in this case does the expression node.SelectNodes ( `` Property '' ) , get evaluated during each iteration of for each or once ? foreach ( XmlNode nodeP in node.SelectNodes ( `` Property '' ) ) { propsList.Add ( nodeP.Attributes [ `` name '' ] .Value , true ) ; }",for each loop iteration "C_sharp : Building off of my marshalling helloworld question , I 'm running into issues marshalling an array allocated in C to C # . I 've spent hours researching where I might be going wrong , but everything I 've tried ends up with errors such as AccessViolationException.The function that handles creating an array in C is below.The C # code : The first human struct gets marshalled fine . I get the access violation exceptions after the first one . I feel like I 'm missing something with marshalling structs with struct pointers inside them . I hope I have some simple mistake I 'm overlooking . Do you see anything wrong with this code ? See this GitHub gist for full source . __declspec ( dllexport ) int __cdecl import_csv ( char *path , struct human ***persons , int *numPersons ) { int res ; FILE *csv ; char line [ 1024 ] ; struct human **humans ; csv = fopen ( path , `` r '' ) ; if ( csv == NULL ) { return errno ; } *numPersons = 0 ; // init to sane value /* * All I 'm trying to do for now is get more than one working . * Starting with 2 seems reasonable . My test CSV file only has 2 lines . */ humans = calloc ( 2 , sizeof ( struct human * ) ) ; if ( humans == NULL ) return ENOMEM ; while ( fgets ( line , 1024 , csv ) ) { char *tmp = strdup ( line ) ; struct human *person ; humans [ *numPersons ] = calloc ( 1 , sizeof ( *person ) ) ; person = humans [ *numPersons ] ; // easier to work with if ( person == NULL ) { return ENOMEM ; } person- > contact = calloc ( 1 , sizeof ( * ( person- > contact ) ) ) ; if ( person- > contact == NULL ) { return ENOMEM ; } res = parse_human ( line , person ) ; if ( res ! = 0 ) { return res ; } ( *numPersons ) ++ ; } ( *persons ) = humans ; fclose ( csv ) ; return 0 ; } IntPtr humansPtr = IntPtr.Zero ; int numHumans = 0 ; HelloLibrary.import_csv ( args [ 0 ] , ref humansPtr , ref numHumans ) ; HelloLibrary.human [ ] humans = new HelloLibrary.human [ numHumans ] ; IntPtr [ ] ptrs = new IntPtr [ numHumans ] ; IntPtr aIndex = ( IntPtr ) Marshal.PtrToStructure ( humansPtr , typeof ( IntPtr ) ) ; // Populate the array of IntPtrfor ( int i = 0 ; i < numHumans ; i++ ) { ptrs [ i ] = new IntPtr ( aIndex.ToInt64 ( ) + ( Marshal.SizeOf ( typeof ( IntPtr ) ) * i ) ) ; } // Marshal the array of human structsfor ( int i = 0 ; i < numHumans ; i++ ) { humans [ i ] = ( HelloLibrary.human ) Marshal.PtrToStructure ( ptrs [ i ] , typeof ( HelloLibrary.human ) ) ; } // Use the marshalled dataforeach ( HelloLibrary.human human in humans ) { Console.WriteLine ( `` first : ' { 0 } ' '' , human.first ) ; Console.WriteLine ( `` last : ' { 0 } ' '' , human.last ) ; HelloLibrary.contact_info contact = ( HelloLibrary.contact_info ) Marshal . PtrToStructure ( human.contact , typeof ( HelloLibrary.contact_info ) ) ; Console.WriteLine ( `` cell : ' { 0 } ' '' , contact.cell ) ; Console.WriteLine ( `` home : ' { 0 } ' '' , contact.home ) ; }",Marshalling C array in C # - Simple HelloWorld "C_sharp : This is purely to improve my skill . My solution works fine for the primary task , but it 's not `` neat '' . I 'm currently working on a .NET MVC with Entity framework project . I know only basic singular LINQ functions which have sufficed over the years . Now I 'd like to learn how to fancy.So I have two modelsIn one of my view models I was asked to provide a dropdown list for selecting a server when creating a new user . The drop down list populated with text and value Id as an IEnumerableHere 's my original property for dropdown list of serversUpdate on requirements , now I need to display how many users are related to each server selection . Ok no problem . Here 's what I wrote off the top of my head.This gets my result lets say `` localhost @ rvrmt1u ( 8 Users ) '' but thats it..What if I want to sort this dropdown list by user count . All I 'm doing is another variable in the string.TLDR ... I 'm sure that someone somewhere can teach me a thing or two about converting this to a LINQ Query and making it look nicer . Also bonus points for knowing how I could sort the list to show servers with the most users on it first . public class Server { [ Key ] public int Id { get ; set ; } public string InstanceCode { get ; set ; } public string ServerName { get ; set ; } } public class Users { [ Key ] public int Id { get ; set ; } public string Name { get ; set ; } public int ServerId { get ; set ; } //foreign key relationship } public IEnumerable < SelectListItem > ServerItems { get { Servers.ToList ( ) .Select ( s = > new selectListItem { Value = x.Id.ToString ( ) , Text = $ '' { s.InstanceCode } @ { s.ServerName } '' } ) ; } } public IEnumerable < SelectListItem > ServerItems { get { var items = new List < SelectListItem > ( ) ; Servers.ToList ( ) .ForEach ( x = > { var count = Users.ToList ( ) .Where ( t = > t.ServerId == x.Id ) .Count ( ) ; items.Add ( new SelectListItem { Value = x.Id.ToString ( ) , Text = $ '' { x.InstanceCode } @ { x.ServerName } ( { count } users on ) '' } ) ; } ) ; return items ; } }",More Elegant LINQ Alternative to Foreach Extension "C_sharp : I 'm trying to re-arrange a list of objects in different ways . Here I 'll use integers but could be anything in this list.The example code below sorts 1,2,3,4,5,6,7,8 into the following order:1,8,2,7,3,6,4,5So first . last . second . Second to last etc . It may be a bit clunky but it works.Now what I 'm trying to do now is to output the list in another order , so that it keeps dividing in two . I think this may be called Divide and Conquer but after trying / looking at some recursive sorting code etc . I 'm not too clear on how to implement that here.I hope to get the numbers ordered like this.First , last , halfway , 1st half halfway , 2nd half halfway etc.So in other words what I 'm trying to do is to split the set of numbers in half ... Then for each half in turn split those in half . And so on : If anyone could anyone show me how to do this , with this simple example , that 'd be really great.Some more sample ranges and output , to be read left-to-right , top-to-bottom : 1,8,4,2,6,3,5,7 1 2 3 4 5 6 7 81 ( first item ) 8 ( last item ) 4 ( mid item ) 2 ( mid of first half ) 6 ( mid of second half ) 3 ( mid of 1st chunk ) 5 ( mid of 2nd chunk ) 7 ( mid of 3rd chunk ) static void Main ( string [ ] args ) { List < int > numberlist = new List < int > ( ) ; numberlist.Add ( 1 ) ; numberlist.Add ( 2 ) ; numberlist.Add ( 3 ) ; numberlist.Add ( 4 ) ; numberlist.Add ( 5 ) ; numberlist.Add ( 6 ) ; numberlist.Add ( 7 ) ; numberlist.Add ( 8 ) ; int rev = numberlist.Count-1 ; int fwd = 0 ; // order 1,8,2,7,3,6,4,5 for ( int re = 0 ; re < numberlist.Count ; re++ ) { if ( re % 2 == 0 ) { Console.WriteLine ( numberlist [ fwd ] ) ; fwd++ ; } else { Console.WriteLine ( numberlist [ rev ] ) ; rev -- ; } } Console.ReadLine ( ) ; } 1 2 3 4 5 6 71 7 4 2 5 3 61 2 3 4 5 6 7 8 9 10 11 121 12 6 3 9 2 4 7 10 5 8 111 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 16 8 4 12 2 6 10 14 3 5 7 9 11 13 15",Different Sorting Orders - divide and conquer ? "C_sharp : I 'm implementing a data link layer using a producer/consumer pattern . The data link layer has its own thread and state machine to communicate the data link protocol over the wire ( Ethernet , RS-232 ... ) . The interface to the physical layer is represented as a System.IO.Stream . Another thread writes messages to and reads messages from the data link object.The data link object has an idle state that must wait for one of four conditions : A byte is receivedA message is available from the network threadThe keep-alive timer has expiredAll communication was cancelled by the network layerI 'm having a difficult time figuring out the best way to do this without splitting up communication into a read/write thread ( thereby significantly increasing the complexity ) . Here 's how I can get 3 out of 4 : orWhat should I do to block the thread , waiting for all four conditions ? All recommendations are welcome . I 'm not set on any architecture or data structures.EDIT : ******** Thanks for the help everyone . Here 's my solution ********First I do n't think there was an asynchronous implementation of the producer/consumer queue . So I implemented something similar to this stackoverflow post.I needed an external and internal cancellation source to stop the consumer thread and cancel the intermediate tasks , respectively , similar to this article . // Read a byte from 'stream ' . Timeout after 10 sec . Monitor the cancellation token.stream.ReadTimeout = 10000 ; await stream.ReadAsync ( buf , 0 , 1 , cts.Token ) ; BlockingCollection < byte [ ] > SendQueue = new ... ; ... // Check for a message from network layer . Timeout after 10 seconds.// Monitor cancellation token.SendQueue.TryTake ( out msg , 10000 , cts.Token ) ; byte [ ] buf = new byte [ 1 ] ; using ( CancellationTokenSource internalTokenSource = new CancellationTokenSource ( ) ) { CancellationToken internalToken = internalTokenSource.Token ; CancellationToken stopToken = stopTokenSource.Token ; using ( CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource ( stopToken , internalToken ) ) { CancellationToken ct = linkedCts.Token ; Task < int > readTask = m_stream.ReadAsync ( buf , 0 , 1 , ct ) ; Task < byte [ ] > msgTask = m_sendQueue.DequeueAsync ( ct ) ; Task keepAliveTask = Task.Delay ( m_keepAliveTime , ct ) ; // Wait for at least one task to complete await Task.WhenAny ( readTask , msgTask , keepAliveTask ) ; // Next cancel the other tasks internalTokenSource.Cancel ( ) ; try { await Task.WhenAll ( readTask , msgTask , keepAliveTask ) ; } catch ( OperationCanceledException e ) { if ( e.CancellationToken == stopToken ) throw ; } if ( msgTask.IsCompleted ) // Send the network layer message else if ( readTask.IsCompleted ) // Process the byte from the physical layer else Contract.Assert ( keepAliveTask.IsCompleted ) ; // Send a keep alive message } }",C # Await Multiple Events in Producer/Consumer "C_sharp : Consider the Employee , Manager , and Assistant classes : The goal is to DISALLOW a piece of code to access a property like this : Because Manager inherits from Emp , it has a .Manager and .Assistant property.QuestionAre there any modifiers in .NET 's inheritance implementation to remove the .Manager and .Assistant properties ? UpdateThank you for your great answers , everyone . I was hoping the simplification and contrivance of Emp/Mgr would show through in this question . It 's clear that the inheritance , in this example , should be taken to another commonality ( something like Person , where the classes would share names , birthdates , etc . ) Your input is much appreciated ! public class Emp { public string Name { get ; set ; } public Manager Manager { get ; set ; } public Assistant Assistant { get ; set ; } } public class Manager : Emp { } public class Assistant : Emp { } var foo = new Manager ( ) ; var elmo = new Emp ( ) ; elmo.Manager = foo ; elmo.Manager.Manager = new Manager ( ) ; //how to disallow access to Manager.Manager ?",.NET inheritance : suppress a property from the base class "C_sharp : I have developed a push notification service for my web site . the service worker is : I have subscribed the users successfully using the following code : and All these codes are in javascript . I can successfully recieve user subscription infromarion on my server like : Also I can successfully send a push to this user using the code bellow in C # : The problem is that after a period of time ( about 20 hours or even less ) , when I want to send a push to this user I got the following errors : firefox subscription : chrome subscription : I think I missed something , that makes the subscription expires , or have to make the users to resubscribe when their subscription information is changed or expired , but I do not know how ? ! ! 'use strict ' ; self.addEventListener ( 'push ' , function ( event ) { var msg = { } ; if ( event.data ) { msg = event.data.json ( ) ; } let notificationTitle = msg.title ; const notificationOptions = { body : msg.body , //body dir : 'rtl ' , //direction icon : msg.icon , //image data : { url : msg.url , //click } , } ; event.waitUntil ( Promise.all ( [ self.registration.showNotification ( notificationTitle , notificationOptions ) , ] ) ) ; } ) ; self.addEventListener ( 'notificationclick ' , function ( event ) { event.notification.close ( ) ; let clickResponsePromise = Promise.resolve ( ) ; if ( event.notification.data & & event.notification.data.url ) { clickResponsePromise = clients.openWindow ( event.notification.data.url ) ; } const fetchOptions = { method : 'post ' } ; fetch ( 'http : //localhost:5333/usrh.ashx ? click=true ' , fetchOptions ) . then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { throw new Error ( 'Failed to send push message via web push protocol ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a Click ' , err ) ; } ) ; } ) ; self.addEventListener ( 'notificationclose ' , function ( event ) { const fetchOptions = { method : 'post ' } ; fetch ( 'http : //localhost:5333/usrh.ashx ? close=true ' , fetchOptions ) . then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { throw new Error ( 'Failed to send push message via web push protocol ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a Click ' , err ) ; } ) ; } ) ; self.addEventListener ( 'pushsubscriptionchange ' , function ( ) { const fetchOptions = { method : 'post ' , } ; fetch ( 'http : //localhost:5333/usru.ashx ' , fetchOptions ) .then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { console.log ( 'Failed web push response : ' , response , response.status ) ; throw new Error ( 'Failed to update users . ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a user ' , err ) ; } ) ; } ) ; registerServiceWorker ( ) { if ( 'serviceWorker ' in navigator ) { navigator.serviceWorker.register ( 'http : //localhost:5333/service-worker.js ' ) .catch ( ( err ) = > { this.showErrorMessage ( 'Unable to Register SW ' , 'Sorry this demo requires a service worker to work and it ' + 'failed to install - sorry : ( ' ) ; console.error ( err ) ; } ) ; } else { this.showErrorMessage ( 'Service Worker Not Supported ' , 'Sorry this demo requires service worker support in your browser . ' + 'Please try this demo in Chrome or Firefox Nightly . ' ) ; } } class PushClient { constructor ( subscriptionUpdate , appkeys ) { this._subscriptionUpdate = subscriptionUpdate ; this._publicApplicationKey = appkeys ; if ( ! ( 'serviceWorker ' in navigator ) ) { return ; } if ( ! ( 'PushManager ' in window ) ) { return ; } if ( ! ( 'showNotification ' in ServiceWorkerRegistration.prototype ) ) { return ; } navigator.serviceWorker.ready.then ( ( ) = > { this.setUpPushPermission ( ) ; } ) ; } setUpPushPermission ( ) { return navigator.serviceWorker.ready.then ( ( serviceWorkerRegistration ) = > { return serviceWorkerRegistration.pushManager.getSubscription ( ) ; } ) .then ( ( subscription ) = > { if ( ! subscription ) { return ; } this._subscriptionUpdate ( subscription ) ; } ) .catch ( ( err ) = > { console.log ( 'setUpPushPermission ( ) ' , err ) ; } ) ; } subscribeDevice ( ) { return new Promise ( ( resolve , reject ) = > { if ( Notification.permission === 'denied ' ) { sc ( 3 ) ; return reject ( new Error ( 'Push messages are blocked . ' ) ) ; } if ( Notification.permission === 'granted ' ) { sc ( 3 ) ; return resolve ( ) ; } if ( Notification.permission === 'default ' ) { Notification.requestPermission ( ( result ) = > { if ( result === 'denied ' ) { sc ( 0 ) ; } else if ( result === 'granted ' ) { sc ( 1 ) ; } else { sc ( 2 ) ; } if ( result ! == 'granted ' ) { reject ( new Error ( 'Bad permission result ' ) ) ; } resolve ( ) ; } ) ; } } ) .then ( ( ) = > { return navigator.serviceWorker.ready.then ( ( serviceWorkerRegistration ) = > { return serviceWorkerRegistration.pushManager.subscribe ( { userVisibleOnly : true , applicationServerKey : this._publicApplicationKey.publicKey , } ) ; } ) .then ( ( subscription ) = > { this._subscriptionUpdate ( subscription ) ; if ( subscription ) { this.sendPushMessage ( subscription ) ; } } ) .catch ( ( subscriptionErr ) = > { } ) ; } ) .catch ( ( ) = > { } ) ; } toBase64 ( arrayBuffer , start , end ) { start = start || 0 ; end = end || arrayBuffer.byteLength ; const partialBuffer = new Uint8Array ( arrayBuffer.slice ( start , end ) ) ; return btoa ( String.fromCharCode.apply ( null , partialBuffer ) ) ; } unsubscribeDevice ( ) { navigator.serviceWorker.ready.then ( ( serviceWorkerRegistration ) = > { return serviceWorkerRegistration.pushManager.getSubscription ( ) ; } ) .then ( ( pushSubscription ) = > { if ( ! pushSubscription ) { this._subscriptionUpdate ( null ) ; return ; } return pushSubscription.unsubscribe ( ) .then ( function ( successful ) { if ( ! successful ) { console.error ( 'We were unable to unregister from push ' ) ; } } ) ; } ) .then ( ( ) = > { this._subscriptionUpdate ( null ) ; } ) .catch ( ( err ) = > { console.error ( 'Error thrown while revoking push notifications . ' + 'Most likely because push was never registered ' , err ) ; } ) ; } sendPushMessage ( subscription ) { let payloadPromise = Promise.resolve ( null ) ; payloadPromise = JSON.parse ( JSON.stringify ( subscription ) ) ; const vapidPromise = EncryptionHelperFactory.createVapidAuthHeader ( this._publicApplicationKey , subscription.endpoint , 'http : //localhost:5333/ ' ) ; return Promise.all ( [ payloadPromise , vapidPromise , ] ) .then ( ( results ) = > { const payload = results [ 0 ] ; const vapidHeaders = results [ 1 ] ; let infoFunction = this.getWebPushInfo ; infoFunction = ( ) = > { return this.getWebPushInfo ( subscription , payload , vapidHeaders ) ; } ; const requestInfo = infoFunction ( ) ; this.sendRequestToProxyServer ( requestInfo ) ; } ) ; } getWebPushInfo ( subscription , payload , vapidHeaders ) { let body = null ; const headers = { } ; headers.TTL = 60 ; if ( payload ) { headers.Encryption = ` auth= $ { payload.keys.auth } ` ; headers [ 'Crypto-Key ' ] = ` p256dh= $ { payload.keys.p256dh } ` ; headers [ 'Content-Encoding ' ] = 'aesgcm ' ; } else { headers [ 'Content-Length ' ] = 0 ; } if ( vapidHeaders ) { headers.Authorization = ` WebPush $ { vapidHeaders.authorization } ` ; if ( headers [ 'Crypto-Key ' ] ) { headers [ 'Crypto-Key ' ] = ` $ { headers [ 'Crypto-Key ' ] } ; ` + ` p256ecdsa= $ { vapidHeaders.p256ecdsa } ` ; } else { headers [ 'Crypto-Key ' ] = ` p256ecdsa= $ { vapidHeaders.p256ecdsa } ` ; } } const response = { headers : headers , endpoint : subscription.endpoint , } ; if ( body ) { response.body = body ; } return response ; } sendRequestToProxyServer ( requestInfo ) { const fetchOptions = { method : 'post ' , } ; if ( requestInfo.body & & requestInfo.body instanceof ArrayBuffer ) { requestInfo.body = this.toBase64 ( requestInfo.body ) ; fetchOptions.body = requestInfo ; } fetchOptions.body = JSON.stringify ( requestInfo ) ; fetch ( 'http : //localhost:5333/usrh.ashx ' , fetchOptions ) .then ( function ( response ) { if ( response.status > = 400 & & response.status < 500 ) { console.log ( 'Failed web push response : ' , response , response.status ) ; throw new Error ( 'Failed to send push message via web push protocol ' ) ; } } ) .catch ( ( err ) = > { this.showErrorMessage ( 'Ooops Unable to Send a Push ' , err ) ; } ) ; } } Authorization : WebPush eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJhdWQiOiJodHRwcxxxxx Crypto-Key : p256dh=BBp90dwDWxxxxc1TfdBjFPqxxxxxwjO9fCip-K_Eebmg= ; p256ecdsa=BDd3_hVL9fZi9Yboxxxxxxoendpoint : https : //fcm.googleapis.com/fcm/send/cxxxxxxxxxxxxxxJRorOMHKLQ3gtT7Encryption : auth=9PzQZ1mut99qxxxxxxxxxxyw== Content-Encoding : aesgcm public static async Task < bool > SendNotificationByte ( string endpoint , string [ ] Keys , byte [ ] userSecret , byte [ ] data = null , int ttl = 0 , ushort padding = 0 , bool randomisePadding = false , string auth= '' '' ) { # region send HttpRequestMessage Request = new HttpRequestMessage ( HttpMethod.Post , endpoint ) ; Request.Headers.TryAddWithoutValidation ( `` Authorization '' , auth ) ; Request.Headers.Add ( `` TTL '' , ttl.ToString ( ) ) ; if ( data ! = null & & Keys [ 1 ] ! = null & & userSecret ! = null ) { EncryptionResult Package = EncryptMessage ( Decode ( Keys [ 1 ] ) , userSecret , data , padding , randomisePadding ) ; Request.Content = new ByteArrayContent ( Package.Payload ) ; Request.Content.Headers.ContentType = new MediaTypeHeaderValue ( `` application/octet-stream '' ) ; Request.Content.Headers.ContentLength = Package.Payload.Length ; Request.Content.Headers.ContentEncoding.Add ( `` aesgcm '' ) ; Request.Headers.Add ( `` Crypto-Key '' , `` dh= '' + Encode ( Package.PublicKey ) + '' ; '' +Keys [ 2 ] + '' = '' +Keys [ 3 ] ) ; Request.Headers.Add ( `` Encryption '' , `` salt= '' + Encode ( Package.Salt ) ) ; } using ( HttpClient HC = new HttpClient ( ) ) { HttpResponseMessage res = await HC.SendAsync ( Request ) .ConfigureAwait ( false ) ; if ( res.StatusCode == HttpStatusCode.Created ) return true ; else return false ; } # endregion } { StatusCode : 410 , ReasonPhrase : 'Gone ' , Version : 1.1 , Content : System.Net.Http.StreamContent , Headers : { Access-Control-Allow-Headers : content-encoding , encryption , crypto-key , ttl , encryption-key , content-type , authorization Access-Control-Allow-Methods : POST Access-Control-Allow-Origin : * Access-Control-Expose-Headers : location , www-authenticate Connection : keep-alive Cache-Control : max-age=86400 Date : Tue , 21 Feb 2017 08:19:03 GMT Server : nginx Content-Length : 179 Content-Type : application/json } } { StatusCode : 400 , ReasonPhrase : 'UnauthorizedRegistration ' , Version : 1.1 , Content : System.Net.Http.StreamContent , Headers : { X-Content-Type-Options : nosniff X-Frame-Options : SAMEORIGIN X-XSS-Protection : 1 ; mode=block Alt-Svc : quic= '' :443 '' ; ma=2592000 ; v= '' 35,34 '' Vary : Accept-Encoding Transfer-Encoding : chunked Accept-Ranges : none Cache-Control : max-age=0 , private Date : Tue , 21 Feb 2017 08:18:35 GMT Server : GSE Content-Type : text/html ; charset=UTF-8 Expires : Tue , 21 Feb 2017 08:18:35 GMT } }",Web Pushnotification 'UnauthorizedRegistration ' or 'Gone ' or 'Unauthorized'- subscription expires "C_sharp : This is mostly an understanding check , as I could n't find a complete reference on this topic.In C # , when I write readonly Foo myFoo , I 'm essentially saying myFoo is a pointer to Foo , and the pointer can not be reassigned . To guarantee that the underlying Foo ca n't be reassigned , I need a whole other class or interface ImmutableFoo.Now consider the construct List < Foo > . It 's basically a pointer to a list of pointers to Foo , i.e . similar to vector < Foo * > * in C++ . There are three places where you could put const in C++.const # 1 : You can not modify the vector ( by resizing , reassigning elements , etc . ) const # 2 : You can not modify the Foo-s pointed to inside the vectorconst # 3 : You can not modify the pointer to the vectorSo I think the equivalent of each of these is , Is this table of equivalencies correct ? const vector < const Foo * > * const List < Foo > = vector < Foo * > * // No constsReadOnlyCollection < Foo > = const vector < Foo * > * // First const toggledList < ImmutableFoo > = vector < const Foo * > * // Second const toggledreadonly List < Foo > = vector < Foo * > * const // Third const toggledreadonly ReadOnlyCollection < ImmutableFoo > = const vector < const Foo * > * const // All consts toggled",C # 's readonly vs C++ 's const - Equivalents "C_sharp : Hello WEB API developers ! I have problems when I try to return array object with my WEB API in MVC6.On the debug controller , I obtain two or more objects but the result only sends a response with one object . I do n't know what more to do for resolve this problem . Please help me ! My controller method : Response with only 1 object , but my controller debug show me more than one : [ HttpGet ] public IEnumerable < Maquina > Get ( ) { var maquinas = _cobraAppContext.Maquina .Include ( m = > m.IdMarcaMotorNavigation ) .Include ( m = > m.IdModeloNavigation ) .ToList ( ) ; return maquinas ; //Two or more object obtains : ( } [ { `` id '' : 1 , `` nombre '' : `` M1 '' , `` idModelo '' : 3 , `` serie '' : `` 123456 '' , `` idMarcaMotor '' : 3 , `` serieMotor '' : `` 123456789 '' , `` descripcion '' : `` ejemplo 123 '' , `` fechaCreacion '' : `` 2016-12-06T08:30:51.307 '' , `` idMarcaMotorNavigation '' : { `` id '' : 3 , `` nombre '' : `` DAEWO '' , `` descripcion '' : `` DAEWO '' , `` fechaCreacion '' : `` 2016-11-29T15:17:33.223 '' , `` maquina '' : [ ] } } ]",ASP.NET Core MVC/WEB API with self-referencing type does not return json array "C_sharp : In a win form application , I have an array of threads which are started like this : Now if user press STOP , the boolean value for stop will set to true , so threads exit the Job method one after another . How can I make sure all threads are exited ? NOTE : I need traditional threading for my case and TaskLibrary does n't fit my scenario . bool stop = false ; Thread [ ] threads = new Thread [ 10 ] ; for ( int i = 0 ; i < threads.Length ; i++ ) threads [ i ] = new Thread ( new ThreadStart ( Job ) ) ; // How to make sure all threads have exited , when the boolean = falsevoid Job ( ) { while ( ! stop ) // Do something }",Make sure all threads exited "C_sharp : I just spent the last hour tackling a bizarre issue with unmanaged memory in C # .First , a bit of context . I 've got a C # DLL which exports some native methods ( via this awesome project template ) which are then called by a Delphi application . One of these C # methods has to pass back a struct to Delphi , where it 's cast to a record . Already I can tell you 're feeling nauseous , so I wo n't go into any more detail . Yes , it 's ugly , but the alternative is COM ... no thanks.Here 's a simplification of the offending code : In reality there 's some other stuff going off in here , related to native resource tracking , but that 's basically it . If you already spotted the bug , well done.Essentially , the problem was that I was using WriteInt16 instead of WriteByte , due to an IntelliSense-aided typo , resulting in the final iteration writing one byte over the end of the buffer . Easy mistake to make , I guess.However , what made this such a pain in the proverbial to debug was that it failed silently within the debugger , and the remainder of the application continued to work . The memory had been allocated , and all but the last byte was zero 'd , so it worked fine . When launched outside a debugger , it caused the application to crash with an access violation . A classic Heisenbug situation - the bug disappears when you try to analyse it . Note that this crash was n't a managed exception , but rather a real CPU-level access violation.Now , this baffles me for two reasons : The exception was NOT thrown when any debugger was attached - I tried Visual Studio , CodeGear Delphi 2009 and OllyDbg . When attached , the program worked perfectly . When not attached , the program crashed . I used exactly the same executable file for all attempts . My understanding is that debugging should not change the behaviour of the application , yet it clearly did.Normally I 'd expect this operation to cause an AccessViolationException within my managed code , but instead it died with a memory access violation in ntdll.dll.Now , fair enough , my case is probably one of the most obscure ( and possibly misguided ) corner-cases in the history of C # , but I 'm lost as to how attaching any debugger prevented the crash . I 'm especially surprised that it worked under OllyDbg , which does n't interfere with the process anywhere near as much as Visual Studio would.So , what the heck happened here ? Why was the exception swallowed ( or not raised ) during debugging , yet not when outside the debugger ? And why was n't a managed access violation exception thrown when I tried to call Marshal.WriteInt16 outside the allocated memory block , as the documentation says it should ? IntPtr AllocBlock ( int bufferSize ) { IntPtr ptrToMem = Marshal.AllocHGlobal ( bufferSize ) ; // zero memory for ( int i = 0 ; i < bufferSize ; i++ ) Marshal.WriteInt16 ( ptrToMem , i , 0 ) ; return ptrToMem ; }",Strange behaviour of C # in debugger vs normal execution caused a Heisenbug "C_sharp : I do n't understand this case : Why is compilation OK when I use Invoke method and not OK when I return csharp Func < int , int > directly ? public delegate int test ( int i ) ; public test Success ( ) { Func < int , int > f = x = > x ; return f.Invoke ; // < - code successfully compiled } public test Fail ( ) { Func < int , int > f = x = > x ; return f ; // < - code does n't compile }","Why is compilation OK , when I use Invoke method , and not OK when I return Func < int , int > directly ?" "C_sharp : I have a WCF server that I can run as a service or as a windows forms application . When I run it as a Windows Forms application I can connect to it via my client application . However when I run it as a service using the same code , I can not connect to it . I have confirmed that the service is running and doing its work . Below is the server 's config file.and its hosting code , called 100 milliseconds after OnStart is called : and the client 's config file : < system.serviceModel > < services > < service name= '' Cns.TrafficCopService.ManagementService '' > < host > < baseAddresses > < add baseAddress= '' http : //localhost:8000/TrafficCop/ManagementService '' / > < /baseAddresses > < /host > < endpoint address= '' '' binding= '' wsHttpBinding '' contract= '' Cns.TrafficCopService.IManagementService '' / > < /service > < /services > < /system.serviceModel > if ( this.serviceHost ! = null ) { this.serviceHost.Close ( ) ; } this.serviceHost = new ServiceHost ( typeof ( ManagementService ) ) ; this.serviceHost.Open ( ) ; < system.serviceModel > < bindings > < wsHttpBinding > < binding name= '' WSHttpBinding_IManagementService '' / > < /wsHttpBinding > < /bindings > < client > < endpoint address= '' http : //localhost:8000/TrafficCop/ManagementService '' binding= '' wsHttpBinding '' bindingConfiguration= '' WSHttpBinding_IManagementService '' contract= '' IManagementService '' name= '' WSHttpBinding_IManagementService '' > < /endpoint > < /client > < /system.serviceModel >","WCF works as application , but not as service" "C_sharp : Given this declaration : and this declarationare there any difference in any sense between them ? Or is just a difference in coding styles ? I allways used to declared my classes like the first , but recently noticed that Microsoft uses the second . using System ; using System.Collections ; using System.Collections.Generic ; namespace AProject.Helpers { public static class AClass { namespace AProject.Helpers { using System ; using System.Collections ; using System.Collections.Generic ; public static class AClass {",What is the difference between these two declarations ? "C_sharp : I am creating Bézier curves using the code below which I got from here . I have also made a BezierPair game object which has two Bézier curves as child objects . From the respective images below and BezierPair , where points [ 0 ] ... points [ 3 ] is represented as P0 ... P3 : I want P0 of each Bézier curve always remain the same when one is moved . In other words I want them to move together always , with the option of turning this movement off.Say P1 of both curves are apart . How can I make P1 of each curve move in the same direction covering the same distance ? Say P2 of both curves are apart . How can I make P2 of one curve mirror P2 of another curve along a line joining P0 and P3 ? Note that the mirror line would be taken from the curve 1 in the example below because curve1 's P2 is moved . If curve2 's P2 is moved , then the mirror line will be taken from curve2 's P0P3.I don ’ t want to do this at run time . So a custom editor has to be used . I tried solving 1. in the code below but the position for the second curve wouldn ’ t update without my selecting BezierPair in the hierarchy windowBezier : BezierCurve : BezierCurveEditor : BezierPair : BezierPairEditor : public static class Bezier { public static Vector3 GetPoint ( Vector3 p0 , Vector3 p1 , Vector3 p2 , Vector3 p3 , float t ) { t = Mathf.Clamp01 ( t ) ; float oneMinusT = 1f - t ; return oneMinusT * oneMinusT * oneMinusT * p0 + 3f * oneMinusT * oneMinusT * t * p1 + 3f * oneMinusT * t * t * p2 + t * t * t * p3 ; } public static Vector3 GetFirstDerivative ( Vector3 p0 , Vector3 p1 , Vector3 p2 , Vector3 p3 , float t ) { t = Mathf.Clamp01 ( t ) ; float oneMinusT = 1f - t ; return 3f * oneMinusT * oneMinusT * ( p1 - p0 ) + 6f * oneMinusT * t * ( p2 - p1 ) + 3f * t * t * ( p3 - p2 ) ; } } [ RequireComponent ( typeof ( LineRenderer ) ) ] public class BezierCurve : MonoBehaviour { public Vector3 [ ] points ; LineRenderer lr ; public int numPoints = 49 ; bool controlPointsChanged = false ; bool isMoving = false ; public void Reset ( ) { points = new Vector3 [ ] { new Vector3 ( 1f , 0f , 0f ) , new Vector3 ( 2f , 0f , 0f ) , new Vector3 ( 3f , 0f , 0f ) , new Vector3 ( 4f , 0f , 0f ) } ; } void Start ( ) { lr = GetComponent < LineRenderer > ( ) ; lr.positionCount = 0 ; DrawBezierCurve ( ) ; } public Vector3 GetPoint ( float t ) { return transform.TransformPoint ( Bezier.GetPoint ( points [ 0 ] , points [ 1 ] , points [ 2 ] , points [ 3 ] , t ) ) ; } public void DrawBezierCurve ( ) { lr = GetComponent < LineRenderer > ( ) ; lr.positionCount = 1 ; lr.SetPosition ( 0 , points [ 0 ] ) ; for ( int i = 1 ; i < numPoints+1 ; i++ ) { float t = i / ( float ) numPoints ; lr.positionCount = i+1 ; lr.SetPosition ( i , GetPoint ( t ) ) ; } } public Vector3 GetVelocity ( float t ) { return transform.TransformPoint ( Bezier.GetFirstDerivative ( points [ 0 ] , points [ 1 ] , points [ 2 ] , points [ 3 ] , t ) ) - transform.position ; } public Vector3 GetDirection ( float t ) { return GetVelocity ( t ) .normalized ; } } [ CustomEditor ( typeof ( BezierCurve ) ) ] public class BezierCurveEditor : Editor { private BezierCurve curve ; private Transform handleTransform ; private Quaternion handleRotation ; private const int lineSteps = 10 ; private const float directionScale = 0.5f ; private void OnSceneGUI ( ) { curve = target as BezierCurve ; handleTransform = curve.transform ; handleRotation = Tools.pivotRotation == PivotRotation.Local ? handleTransform.rotation : Quaternion.identity ; Vector3 p0 = ShowPoint ( 0 ) ; Vector3 p1 = ShowPoint ( 1 ) ; Vector3 p2 = ShowPoint ( 2 ) ; Vector3 p3 = ShowPoint ( 3 ) ; Handles.color = Color.gray ; Handles.DrawLine ( p0 , p1 ) ; Handles.DrawLine ( p2 , p3 ) ; Handles.DrawBezier ( p0 , p3 , p1 , p2 , Color.white , null , 2f ) ; curve.DrawBezierCurve ( ) ; if ( GUI.changed ) { curve.DrawBezierCurve ( ) ; EditorUtility.SetDirty ( curve ) ; Repaint ( ) ; } } private void ShowDirections ( ) { Handles.color = Color.green ; Vector3 point = curve.GetPoint ( 0f ) ; Handles.DrawLine ( point , point + curve.GetDirection ( 0f ) * directionScale ) ; for ( int i = 1 ; i < = lineSteps ; i++ ) { point = curve.GetPoint ( i / ( float ) lineSteps ) ; Handles.DrawLine ( point , point + curve.GetDirection ( i / ( float ) lineSteps ) * directionScale ) ; } } private Vector3 ShowPoint ( int index ) { Vector3 point = handleTransform.TransformPoint ( curve.points [ index ] ) ; EditorGUI.BeginChangeCheck ( ) ; point = Handles.DoPositionHandle ( point , handleRotation ) ; if ( EditorGUI.EndChangeCheck ( ) ) { Undo.RecordObject ( curve , `` Move Point '' ) ; EditorUtility.SetDirty ( curve ) ; curve.points [ index ] = handleTransform.InverseTransformPoint ( point ) ; } return point ; } } public class BezierPair : MonoBehaviour { public GameObject bez1 ; public GameObject bez2 ; public void setupCurves ( ) { bez1 = GameObject.Find ( `` Bez1 '' ) ; bez2 = GameObject.Find ( `` Bez2 '' ) ; } } [ CustomEditor ( typeof ( BezierPair ) ) ] public class BezierPairEditor : Editor { private BezierPair bezPair ; public override void OnInspectorGUI ( ) { bezPair = target as BezierPair ; if ( bezPair.bez1.GetComponent < BezierCurve > ( ) .points [ 0 ] ! = bezPair.bez2.GetComponent < BezierCurve > ( ) .points [ 0 ] ) { Vector3 assignPoint0 = bezPair.bez1.GetComponent < BezierCurve > ( ) .points [ 0 ] ; bezPair.bez2.GetComponent < BezierCurve > ( ) .points [ 0 ] = assignPoint0 ; } if ( GUI.changed ) { EditorUtility.SetDirty ( bezPair.bez1 ) ; EditorUtility.SetDirty ( bezPair.bez2 ) ; Repaint ( ) ; } }",How to update one Bezier curve as another is moved using a custom editor C_sharp : I have the follow program : The compiler complains that it ca n't convert a Task < List > to a Task < IList > in the TestAsync method : CS0029 Can not implicitly convert type System.Threading.Tasks.Task < System.Collections.Generic.List < int > > to System.Threading.Tasks.Task < System.Collections.Generic.IList < int > > Why ca n't it figure out that my method returns an Task of IList ? async Task Main ( ) { IList < int > myList = await TestAsync ( ) ; } public Task < IList < int > > TestAsync ( ) { return Task.FromResult ( new List < int > ( ) ) ; },Why does Task.FromResult require explicit cast ? "C_sharp : Note that I 'm aware of other yield in vb.net questions here on SO.I 'm playing around with Caliburn lately . Bunch of great stuff there , including co-routines implementation.Most of the work I 'm doing is C # based , but now I 'm also creating an architecture guideline for a VB.NET only shop , based on Rob 's small MVVM framework.Everything looks very well except using co-routines from VB . Since VB 10 is used , we can try something like Bill McCarthy 's suggestion : I 'm just failing to comprehend how a little more complex co-routine method like the one below ( taken from Rob 's GameLibrary ) could be written in VB : Any idea how to achieve that , or any thoughts on using Caliburn co-routines in VB ? Edit : Marco pointed me to a right direction . After looking in Reflector - Visual Basic code of Rob 's GameLibrary , I managed to modify Bill McCarthy 's GenericIterator to become a poor man 's state machine : And we can use it like this : It definitely is n't as elegant as C # version , but it looks to be doable . We 'll see if there are any problems with this . If anyone has better idea , I 'm all ears . Public Function Lines ( ByVal rdr as TextReader ) As IEnumerable ( Of String ) Return New GenericIterator ( Of String ) ( Function ( ByRef nextItem As String ) As Boolean nextItem = rdr.ReadLine Return nextItem IsNot Nothing End Function ) End Function public IEnumerable < IResult > ExecuteSearch ( ) { var search = new SearchGames { SearchText = SearchText } .AsResult ( ) ; yield return Show.Busy ( ) ; yield return search ; var resultCount = search.Response.Count ( ) ; if ( resultCount == 0 ) SearchResults = _noResults.WithTitle ( SearchText ) ; else if ( resultCount == 1 & & search.Response.First ( ) .Title == SearchText ) { var getGame = new GetGame { Id = search.Response.First ( ) .Id } .AsResult ( ) ; yield return getGame ; yield return Show.Screen < ExploreGameViewModel > ( ) .Configured ( x = > x.WithGame ( getGame.Response ) ) ; } else SearchResults = _results.With ( search.Response ) ; yield return Show.NotBusy ( ) ; } Private _state As Integer = -1Public Function MoveNext ( ) As Boolean Implements IEnumerator.MoveNext _state += 1 Return _func ( _Current , _state ) End Function Public Function ExecuteSearch ( ) As IEnumerable ( Of String ) ' If we need some variable shared across states , define it here Dim someSharedStuff As String = String.Empty ' Notice the second lambda function parameter below - state Return New GenericIterator ( Of IResult ) ( Function ( ByRef nextItem As IResult , state As Integer ) As Boolean Select Case state Case 0 someSharedStuff = `` First state '' nextItem = Show.Busy Return True Case 1 nextItem = Show.SomeLoadingScreen ' Do some additional processing here ... Return True Case 2 ' Do something with someSharedStuff variable ... Console.WriteLine ( someSharedStuff ) nextItem = PerforSomemWebServiceCall ( ) Return True ' ... Case 6 nextItem = Show.NotBusy Return False End Select Return False End Function ) End Function",Is there a way to implement Caliburn-like co-routines in VB.NET since there 's no yield keyword "C_sharp : In C # all delegate types are incompatible with one another , even if they have the same signature . As an example : What is the reasoning behind this behaviour and language design decision . delegate void D1 ( ) ; delegate void D2 ( ) ; D1 d1 = MethodGroup ; D2 d2 = d1 ; // compile time errorD2 d2 = new D2 ( d1 ) ; // you need to do this instead",Why are all Delegate types incompatible with each other ? "C_sharp : I have a method which returns an IEnumerable < string > which of course is being handled with yield return < string > ; . I want to have multiple threads processing the result of this , of course without repeating it and being thread safe . How would I achieve this ? However this seems to be producing repeats : var result = GetFiles ( source ) ; for ( int i = 0 ; i < Environment.ProcessorCount ; i++ ) { tasks.Add ( Task.Factory.StartNew ( ( ) = > { ProcessCopy ( result ) ; } ) ) ; } Task.WaitAll ( tasks.ToArray ( ) ) ; C : \Users\esac\Pictures\2000-06\DSC_1834.JPGC : \Users\esac\Pictures\2000-06\DSC_1835.JPGC : \Users\esac\Pictures\2000-06\.picasa.iniC : \Users\esac\Pictures\2000-06\DSC_1834.JPGC : \Users\esac\Pictures\2000-06\DSC_1835.JPGC : \Users\esac\Pictures\2000-06\.picasa.iniC : \Users\esac\Pictures\2000-06\DSC_1834.JPGC : \Users\esac\Pictures\2000-06\DSC_1835.JPGC : \Users\esac\Pictures\2000-06\.picasa.iniC : \Users\esac\Pictures\2000-06\DSC_1834.JPGC : \Users\esac\Pictures\2000-06\DSC_1835.JPG",How to have multiple threads processing the same IEnumerable result ? "C_sharp : I 'm reading through the Exam Ref 70-483 : Programming in C # book and the following code sample is given : LISTING 1-19The paragraph under states this : The SleepAsyncA method uses a thread from the thread pool while sleeping . the second method , however , which has a completely different implementation , does not occupy a thread while waiting for the timer to run . The second method gives you scalability.Why is A responsive but B scalable ? public Task SleepAsyncA ( int millisecondsTimeout ) { return Task.Run ( ( ) = > thread.Sleep ( millisecondsTimeout ) ; } public Task SleepAsyncB ( int millisecondsTimeout ) { TaskCompletionSource < bool > tcs = null ; var t = new Timer ( delegate { tcs.TrySetResult ( true ) ; } , -1 , -1 ) ; tcs = new TaskCompletionSource < bool > ( t ) ; t.Change ( millisecondsTimeout , -1 ) ; return tcs.Task ; }",Scalability versus Responsiveness in .NET Async C_sharp : I want to do this : I get an `` invalid expression '' term on the lambda . Can that be fixed inline ? class Foo { static Func < string > sRunner ; Func < string > _runner ; public Foo ( Func < string > runner ) { _runner = runner ? ? sRunner ? ? ( ) = > `` Hey ! `` ; } },How to Coalesce a Lambda Delegate "C_sharp : I 'm trying to do a post request on windows phone 8 from the Unity Platform . I do not want to use the unity WWW method as this blocks rendering ( and is not thread safe ) .The following code works in the editor and on Android , but when building it for WP8 I get the following error . System.Byte [ ] System.Net.WebClient : :UploadData ( System.String , System.String , System.Byte [ ] ) ` does n't exist in target framework.The reason for this error is explained here It ’ s because Windows Phone 8 uses a different flavor of .NET called .NET for Windows Phone which is missing some of the types available on other platforms . You ’ ll have to either replace these types with different ones or implement them yourself . - http : //docs.unity3d.com/Manual/wp8-faq.htmlThis is my codeI 've also tried WebRequests , but GetResponse ( ) breaks it , and HttpClient does not exist . So , how do I post data in Unity , without using WWW , on windows phone 8 ? UPDATE AS PER COMMENT REQUEST - WebRequestsThis code , using HttpWebRequest works in the editor and on Android , but on windows phone throws the errors listed below the code.Error 1 : Error : method System.IO.Stream System.Net.HttpWebRequest : :GetRequestStream ( ) does n't exist in target framework.Error 2 : System.Net.WebResponse System.Net.HttpWebRequest : :GetResponse ( ) does n't exist in target framework.UPDATE WITH MORE DETAILS - UploadStringAsyncUsing this code to make an async request it again works great in the editor , errors are thrown on the WP8.Error 1 method System.Void System.Net.WebClient : :add_UploadDataCompleted ( System.Net.UploadDataCompletedEventHandler ) does n't exist in target framework.Error 2 Error : method System.Void System.Net.WebClient : :UploadDataAsync ( System.Uri , System.Byte [ ] ) does n't exist in target framework . Error 3 Error : type System.Net.UploadDataCompletedEventArgs does n't exist in target framework.Error 4 Error : method System.Byte [ ] System.Net.UploadDataCompletedEventArgs : :get_Result ( ) does n't exist in target framework . using ( WebClient client = new WebClient ( ) ) { client.Encoding = System.Text.Encoding.UTF8 ; client.Headers [ HttpRequestHeader.ContentType ] = `` application/json '' ; byte [ ] requestData = new byte [ 0 ] ; string jsonRequest = `` { } '' ; if ( data ! = null ) { string tempRequest = Converter.SerializeToString ( data ) ; jsonRequest = `` { \ '' Data\ '' : \ '' '' + tempRequest + `` \ '' } '' ; requestData = System.Text.Encoding.UTF8.GetBytes ( jsonRequest ) ; } // below line of code is the culprit byte [ ] returnedData = client.UploadData ( url , `` POST '' , requestData ) ; if ( returnedData.Length > 0 ) { // do stuff } } var request = ( System.Net.HttpWebRequest ) System.Net.WebRequest.Create ( url ) ; request.ContentType = `` application/json '' ; request.Method = `` POST '' ; var sw = new System.IO.StreamWriter ( request.GetRequestStream ( ) , System.Text.Encoding.UTF8 ) ; sw.Write ( jsonRequest ) ; // jsonRequest is same variable as in above code , string with json object.sw.Close ( ) ; var re = request.GetResponse ( ) ; string resultString = `` '' ; using ( var outputStream = new System.IO.StreamReader ( re.GetResponseStream ( ) , System.Text.Encoding.UTF8 ) ) { resultString = outputStream.ReadToEnd ( ) ; } if ( resultString.Length > 0 ) { } bool isCompleted = false ; byte [ ] returnedData = null ; client.UploadDataCompleted += new UploadDataCompletedEventHandler ( ( object sender , UploadDataCompletedEventArgs e ) = > { Debug.Log ( `` return event '' ) ; returnedData = e.Result ; isCompleted =true ; } ) ; Debug.Log ( `` async call start '' ) ; client.UploadDataAsync ( new Uri ( url ) , requestData ) ; while ( isCompleted == false ) { Thread.Sleep ( 100 ) ; } if ( returnedData.Length > 0 ) { }",Making a post request in Unity on Windows Phone 8 "C_sharp : I have this code : This is the method : So the FirstOrDefault ( ) does n't find a hit in the entity framework context , which is the `` ctx '' object . So the 'default ' value to be returned is null , since the target of the query is a class.The result of the first bit of code , using the ? ? , results in _localMyClass being what ? I would say it would be the new MyClass ( ) . Instead , _localMyClass ends up being null . I tried grouping the logic with various sets of parentheses , but still no luck.Odder still ; when I set a debug break point , and copy/paste the MyClassDAO.GetMyClassByID ( 123 ) ? ? new MyClass ( ) into the watch screen of Visual Studio , the result is the new MyClass ( ) instead of null.Can anybody explain why it would be working in this manner ? Why it does n't recognize the method return value as null and then instead use the new part ? MyClass _localMyClass = MyClassDAO.GetMyClassByID ( 123 ) ? ? new MyClass ( ) ; public static MyClass GetMyClassByID ( int id ) { var query = from m in ctx.MyClass where m.MyClassID == id select m ; return query.FirstOrDefault < MyClass > ( ) ; }",C # coalesce operator does n't replace a null method return value ? "C_sharp : I thought with the new fancy C # local functions I could get rid of themandatory private recursion function.Obviously this function `` should '' do some post order traverasal of a tree . So , only give the element IFF there is no left or right child available.The code compiles , it `` works '' , but the recursive calls to the local function : PostOrderRecursive ( currentNode.Left ) ; and PostOrderRecursive ( currentNode.Right ) ; are ignored when debugging . So no recursion is performed at all.What is the problem here ? Thanks in advance ! public IEnumerable < ElementType > GetSubtreeFlattenedPostOrder ( ) { return PostOrderRecursive ( this ) ; IEnumerable < ElementType > PostOrderRecursive ( BinaryTree < ElementType > currentNode ) { if ( currentNode.HasLeft ) PostOrderRecursive ( currentNode.Left ) ; if ( currentNode.HasRight ) PostOrderRecursive ( currentNode.Right ) ; yield return currentNode.element ; } }",Yield return in local recursive function C_sharp : I am trying to retrieve user contacts in Hotmail account exactly like google+ and twitter.What I tried so far is using getting verification code : wrap_scope=WL_Contacts.ViewI have traced Gogole+ and Twitter Invitations I noticed that both are using : wrap_scope=WL_Contacts.ViewFullbut every time I use this parameter I receive : How can I get the restricted Permission [ WL_Contacts.ViewFull ] . Can any one help me out by providing some info on using the restricted apis of msn and also about applying for the scopes . error_code=1017 & wrap_error_reason=ExternalConsentConnectivityProblem,How to Grab Hotmail Contact Email Addresses ? "C_sharp : Within a HttpModule , following a url rewrite , I 'm am testing user permissions to a to a virtual path situated within my application using : Where virtualCachedPath is any virtual path e.g ~/app_data/cache situated with the root of the application.http : //msdn.microsoft.com/en-us/library/system.web.security.urlauthorizationmodule.checkurlaccessforprincipal ( v=vs.110 ) .aspxThis however , will throw an ArgumentException though if tested against an external virtual directory . [ ArgumentException : Virtual path outside of the current application is not supported . Parameter name : virtualPath ] E.g.What is the correct method to check user permission to a virtual directory ? // Since we are now rewriting the path we need to check again that the // current user has access to the rewritten path.// Get the user for the current request// If the user is anonymous or authentication does n't work for this suffix // avoid a NullReferenceException in the UrlAuthorizationModule by creating // a generic identity.string virtualCachedPath = cache.GetVirtualCachedPath ( ) ; IPrincipal user = context.User ? ? new GenericPrincipal ( new GenericIdentity ( string.Empty , string.Empty ) , new string [ 0 ] ) ; // Do we have permission to call // UrlAuthorizationModule.CheckUrlAccessForPrincipal ? PermissionSet permission = new PermissionSet ( PermissionState.None ) ; permission.AddPermission ( new AspNetHostingPermission ( AspNetHostingPermissionLevel.Unrestricted ) ) ; bool hasPermission = permission.IsSubsetOf ( AppDomain.CurrentDomain.PermissionSet ) ; bool isAllowed = true ; // Run the rewritten path past the auth system again , using the result as // the default `` AllowAccess '' valueif ( hasPermission & & ! context.SkipAuthorization ) { isAllowed = UrlAuthorizationModule.CheckUrlAccessForPrincipal ( virtualCachedPath , user , `` GET '' ) ; }",How to test user permissions for virtual directory ? "C_sharp : If I register : And then retrieve via : Am I guaranteed the bindings will always be handed back in that order ? I tried it , and it seems it does , but this could be purely incidental . Bind < IWeapon > ( ) .To < Sword > ( ) ; Bind < IWeapon > ( ) .To < Knife > ( ) ; Bind < IWeapon > ( ) .To < ChuckNorris > ( ) ; IEnumerable < IWeapon > weapons = ServiceLocator.Current.GetAllInstances < IWeapon > ( ) ;",are multiple ninject bindings guaranteed to maintain their binding order "C_sharp : Compiler does n't complain about the case 2 ( see the comment ) , well , the reason is straight forward since string inherits from object . Along the same lines , why is it complaining for anonymous method types ( see the comment //case 4 : ) that Can not convert anonymous method to delegate type 'DelegateTest.Program.Srini ' because the parameter types do not match the delegate parameter typeswhere as in case of normal method it does n't ? Or am I comparing apples with oranges ? Another case is why is it accepting anonymous method without parameters ? public class Program { delegate void Srini ( string param ) ; static void Main ( string [ ] args ) { Srini sr = new Srini ( PrintHello1 ) ; sr += new Srini ( PrintHello2 ) ; //case 2 : sr += new Srini ( delegate ( string o ) { Console.WriteLine ( o ) ; } ) ; sr += new Srini ( delegate ( object o ) { Console.WriteLine ( o.ToString ( ) ) ; } ) ; //case 4 : sr += new Srini ( delegate { Console.WriteLine ( “ This line is accepted , though the method signature is not Comp ” ) ; } ) ; //case 5 sr ( `` Hello World '' ) ; Console.Read ( ) ; } static void PrintHello1 ( string param ) { Console.WriteLine ( param ) ; } static void PrintHello2 ( object param ) { Console.WriteLine ( param ) ; } }",Can ’ t assign delegate an anonymous method with less specific parameter type "C_sharp : I 'm facing issues while running my application built on ASP.NET Core using Docker in Visual Studio . My application only uses dnxcore50 framework . My project.json file is : I have tried following approaches : When my dnvm points to runtime dnx-coreclr-win-x64.1.0.0-rc1-update1 as shown in figure below.My application builds successfully . But , I get following error on running/debugging the application on docker and my application gets stuck at `` Opening site http : //192.168.99.100:5000 '' Error details : The Current runtime framework is not compatible with 'app ' The current runtime target framework : 'DNX , Version=v4.5.1 ( dnx451 ) ' Please make sure the runtime matches the framework specified in project.jsonAs the above error message suggests there is mismatch in framework , I changed the default and active runtime to dnx-coreclr-linux-x64.1.0.0-rc1-update1 by modifying default alias and executing command dnvm use default -p. Then , I restart my VS ( to make sure the changes are visible in VS ) .However , my application still builds on DNX version v4.5.1 as suggested in the build logs below : Hence , the application again fails to run with the same error as in point 1.Additionally , on changing the default runtime dnu restore stops working from command line and gives with following error : 'dnu ' is not recognized as an internal or external command , operable program or batch file.Interestingly , the 'dnu ' restore command continues to work from VS ( as suggested in VS build logs ) .I then tried to change dnvm runtime to dnx-mono.1.0.0-rc1-update1 . But it fails with following error : Can not find dnx-mono.1.0.0-rc1-update1.1.0.0-rc1-update1 , do you need to run 'dnvm install default ' ? At C : \Program Files\Microsoft DNX\Dnvm\dnvm.ps1:1659 char:9 + throw `` Can not find $ runtimeFullName , do you need to run ' $ Com ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped : ( Can not find dnx ... stall default ' ? : String ) [ ] , Run timeException + FullyQualifiedErrorId : Can not find dnx-mono.1.0.0-rc1-update1.1.0.0-rc1-update1 , do you nee d to run 'dnvm install default ' ? What runtime I need to use to run docker from VS and how I can change it ? Request your help to resolve the issue . Update I was finally able to resolve the issue by changing the docker file first line to FROM microsoft/aspnet:1.0.0-rc1-update1-coreclr FROM microsoft/aspnet:1.0.0-rc1-update1 . Thanks @ bertt for the tip . { `` version '' : `` 1.0.0-* '' , `` compilationOptions '' : { `` emitEntryPoint '' : true } , `` dependencies '' : { `` Microsoft.AspNet.IISPlatformHandler '' : `` 1.0.0-rc1-final '' , `` Microsoft.AspNet.Mvc '' : `` 6.0.0-rc1-final '' , `` Microsoft.AspNet.Server.Kestrel '' : `` 1.0.0-rc1-final '' , `` Microsoft.AspNet.StaticFiles '' : `` 1.0.0-rc1-final '' } , `` frameworks '' : { `` dnxcore50 '' : { } } , `` exclude '' : [ `` wwwroot '' , `` node_modules '' ] , `` publishExclude '' : [ `` **.user '' , `` **.vspscc '' ] , `` commands '' : { `` web '' : `` Microsoft.AspNet.Server.Kestrel '' } } 1 > Information : [ LoaderContainer ] : Load name=Microsoft.Dnx.Tooling1 > Information : [ PathBasedAssemblyLoader ] : Loaded name=Microsoft.Dnx.Tooling in 2ms1 > Information : [ Bootstrapper ] Runtime Framework : DNX , Version=v4.5.11 > Microsoft .NET Development Utility Mono-x64-1.0.0-rc1-16231",ASP.NET Core - Issues while Debugging through Docker in Visual Studio 2015 "C_sharp : We have a simple utility class in-house for our database calls ( a light wrapper around ADO.NET ) , but I am thinking of creating classes for each database/object . Would it be smart thing to do so , or would it only benefit if we were using the full MVC framework for ASP.NET ? So we have this : Thinking of doing this : or for a new record -Would this be smart , or would it be overkill ? I can see the benefit for reuse , changing database , and maintenance/readability . SQLWrapper.GetRecordset ( connstr-alias , sql-statement , parameters ) ; SQLWrapper.GetDataset ( connstr-alias , sql-statement , parameters ) ; SQLWrapper.Execute ( connstr-alias , sql-statement , parameters ) ; Person p = Person.get ( id ) ; p.fname = `` jon '' ; p.lname = `` smith '' ; p.Save ( ) ; Person p = new Person ( ) ; p.fname = `` Jon '' ; p.lname = `` Smith '' ; p.Save ( ) ; p.Delete ( ) ;",Is it better to create Model classes or stick with generic database utility class ? "C_sharp : See the following simple casting example : I understand why the last line generates an error . Unlike ints , objects do n't implement IComparable and therefore do n't expose the CompareTo method . The following also generates an error : Since there 's no inheritance between ints and strings , casting will not work here . Now , take a look at this : ( These classes come from the DirectShowNet library . ) I do n't understand this . The cast does not generate an error and throws no exceptions at runtime , so I assume that AudioRender implements IBaseFilter . However , AudioRender does not expose any of IBaseFilter 's methods , indicating that my assumption above is wrong ... If a implements b , why does n't a expose the methods of b ? Else , if a does not implement b , why can a be casted to b ? Also , can I reproduce this behaviour without the use of DirectShowNet ? int i = 1000 ; object o = ( object ) i ; // casti.CompareTo ( 1000 ) ; o.CompareTo ( 1000 ) ; // error string s = ( string ) i ; // cast error AudioRender a = new AudioRender ( ) ; IBaseFilter b = ( IBaseFilter ) a ; // casta.Run ( 1000 ) ; // errorb.Run ( 1000 ) ;",Something about .NET inheritance/casting that I do n't understand ? C_sharp : Let 's say I have this structure of projects : I 'd want to tell compiler to copy wwwroot with all items and folders inside to output folder of testsbut I 'd want it to work fine not only on Windows but also on LinuxI addedd to Tests.csproj this : but it does n't really work - AppRunner | - Apprunner.csproj | - wwwroot- Tests | - Tests.csproj | - bin | - debug | - netcoreapp2.1 | - I want copy wwwroot here < ItemGroup > < None Update= '' ..\AppRunner\wwwroot\* '' > < CopyToOutputDirectory > Always < /CopyToOutputDirectory > < /None > < /ItemGroup >,How can I tell compiler to copy wwwroot from one project to Tests proj ? "C_sharp : I used dropdown for search . The text value should different from the value . So , I created 2 types of methods : lstFunctions should come in the value field . How will I add this ? List < string > lstRoles = new List < string > ( ) ; lstRoles = _repository.GetRolesForFindJobseekers ( ) ; List < string > lstFunctions = new List < string > ( ) ; lstFunctions = _repository.GetFunctionsForRolesFindJobSeekers ( ) ; List < SelectListItem > selectListRoles = new List < SelectListItem > ( ) ; int i = 1 ; foreach ( string role in lstRoles ) { selectListRoles.Add ( new SelectListItem { Text = role , Value = role , Selected = ( i == 0 ) } ) ; i++ ; } ViewData [ `` RolesForJobSeekers '' ] = selectListRoles ;",Using foreach with two types of conditions in c # "C_sharp : Is this a bad idea ? This class is only visible as an IEnumerable ( Of T ) readonly property , and it saves me an additional class that wraps IEnumerator ( Of T ) . But somehow it just seems wrong . Is there a better way ? Private Class GH_DataStructureEnumerator ( Of Q As Types.IGH_Goo ) Implements IEnumerable ( Of Q ) Implements IEnumerator ( Of Q ) ... . ... . 'Current , MoveNext , Reset etc . ' ... . ... . Public Function GetEnumerator_Generic ( ) As IEnumerator ( Of Q ) _ Implements IEnumerable ( Of Q ) .GetEnumerator Return Me End FunctionEnd Class","IEnumerable and IEnumerator in the same class , bad idea ?" "C_sharp : I am trying to serialize an instance of a class that inherits from DynamicObject . I 've had no trouble getting the dynamic properties to serialize ( not demonstrated here for brevity ) , but `` normal '' properties do n't seem to make the trip . I experience the same problem regardless of serialization class : it 's the same for JavaScriptSerializer , JsonConvert , and XmlSerializer.Should n't MyNormalProperty show up in the serialized string ? Is there a trick , or have I misunderstood something fundamental about inheriting from DynamicObject ? public class MyDynamicClass : DynamicObject { public string MyNormalProperty { get ; set ; } } ... MyDynamicClass instance = new MyDynamicClass ( ) { MyNormalProperty = `` Hello , world ! `` } ; string json = JsonConvert.SerializeObject ( instance ) ; // the resulting string is `` { } '' , but I expected to see MyNormalProperty in there","C # How to serialize ( JSON , XML ) normal properties on a class that inherits from DynamicObject" "C_sharp : I am maintaining an application that has both VB.NET and c # components . I thought these two languages differed only in syntax , but I have found a strange feature in VB.NET that is not present in C # .In VB.NET , I have the following class : If I want to use this class in C # , I do this : However , in the VB.NET code , the class can be used like this : ShowDialog is defined in the metadata like this : So in VB.NET , it is possible to call an instance method on the class . As far as I can tell , this seems to implicitly create a new instance of the class , and then calls the method on that object . In C # , this is not possible - static methods must be called on the class , and instance methods must be called on objects.I ca n't find any information about this on the Internet . What is the feature called , and is it good practice ? The project was initially converted from VB6 - is it some weird legacy feature ? Public Class bill_staff Inherits System.Windows.Forms.Form ... .End Class using ( var frm = new bill_staff ( ) ) frm.ShowDialog ( ) ; bill_staff.ShowDialog ( ) ; Public Function ShowDialog ( ) As System.Windows.Forms.DialogResult",Objects implicitly instantiated in vb.net ? C_sharp : i have the following code to cache some expensive code.will this stay in the cache forever ? until the server reboots or runs out of memory ? private MyViewModel GetVM ( Params myParams ) { string cacheKey = myParams.runDate.ToString ( ) ; var cacheResults = HttpContext.Cache [ cacheKey ] as MyViewModel ; if ( cacheResults == null ) { cacheResults = RunExpensiveCodeToGenerateVM ( myParams ) ; HttpContext.Cache [ cacheKey ] = cacheResults ; } return cacheResults ; },"how long , by default does stuff stay in httpcache if i do n't put an explicit expiration ?" "C_sharp : I tried the following code : and it looks like in Release build the exception is not thrown so not only the call to a method marked with ConditionalAttribute is removed , but also the parameters computation is eliminated.Is such behavior guaranteed ? class Magic { [ Conditional ( `` DEBUG '' ) ] public static void DoMagic ( int stuff ) { } public static int ComputeMagic ( ) { throw new InvalidOperationException ( ) ; } } class Program { static void Main ( string [ ] args ) { Magic.DoMagic ( Magic.ComputeMagic ( ) ) ; } }",Does using ConditionalAttribute also remove arguments computation ? "C_sharp : I am trying to build a LINQ provider to a well defined web API with a well defined model . I am following these walkthroughs : Part I Part II I have been able to create the Query Provider that translates the expression to the desired URL and it works pretty good.Now here is the next step that I just can not figure out . Imagine that one of the requests returns an object defined like this : Now as you can see the SomeOtherObjectId is not decorated with the JsonProperty attribute , that is because it is not part of the returned object definition but it is needed because it is the parameter that the get request depends on . This means that an expression like the following : Is translated into something like : blablabla/someId/ ... .Now the web API searches are limited in the parameters they expect so the IsActive filter will be ignored so I figured that after the response is received I could use the same expression as a predicate in a LINQ to Objects query so the rest of the filters are taken into consideration but in order to do so I would have to recreate the expression without the ProjectId filter since it does not exist in the returned JSON that gets deserialized into the object , so it would have to become something like : So then I can do something likeI have been searching for examples of how to do this using an ExpressionVisitor but I just can not understand how to recreate the expression without the filter I want removed.Thank you for your help.UPDATE : Thank you to both Evk and MaKCbIMKo since with their combined answers I got the final solution which I am including in the hope that it might help others . [ JsonObject ] public class SomeObject { [ JsonProperty ( PropertyName = `` id '' ) ] public string Id { get ; set ; } [ JsonProperty ( PropertyName = `` name '' ) ] public string Name { get ; set ; } [ JsonProperty ( PropertyName = `` is_active '' ) ] public bool IsActive { get ; set ; } public string SomeOtherObjectId { get ; set ; } } Expression < Func < SomeObject , bool > > exp = o = > o.SomeOtherObjectId == `` someId '' & & o.IsActive ; Expression < Func < SomeObject , bool > > modifiedExp = o = > o.IsActive ; return deserializedObject.Where ( modifiedExp ) ; protected override Expression VisitBinary ( BinaryExpression node ) { if ( node.NodeType ! = ExpressionType.Equal ) return base.VisitBinary ( node ) ; if ( new [ ] { node.Left , node.Right } .Select ( child = > child as MemberExpression ) .Any ( memberEx = > memberEx ! = null & & memberEx.Member.CustomAttributes.All ( p = > p.AttributeType.Name ! = `` JsonPropertyAttribute '' ) ) ) { return Expression.Constant ( true ) ; } return base.VisitBinary ( node ) ; }",Remove a condition from an expression using an ExpressionVisitor "C_sharp : Having just installed VS2015 Update 1 , I discovered the C # Interactive window.According to the second post in that series , you should be able to import a project from your solution . When you want to fire up the C # Interactive Window you can just right click your solution and select `` Reset Interactive from Project '' However , this option is not available on my project . I 'm using a Console Application to test , and have pushed the framework up to 4.6.1 from 4.5 . However , this has not worked.Additionally , I have attempted to manually import the project . Looking at the screenshots on the website , I should be able to do this like this : # r `` ConsoleApplication7.exe '' but when I do , I get the following exception : ( 1,1 ) : error CS0006 : Metadata file 'ConsoleApplication7.exe ' could not be foundIt will pull in via the filepath , e.g : However , this is a little unwieldly . Especially since whenever you make changes to the classes , it requires a # reset and re-import.Is there a better way to import Projects into the Immediate instance ? # r `` bin\Debug\ConsoleApplication7.exe ''",Import Project to Immediate "C_sharp : I am trying to create something to hold global site-wide settings in our ASP.NET website - things such as site name , google analytics account number , facebook url etc ... The site can have multiple ‘ brands ’ or sub-sites associated with it , hence the sitguid column , we would also like to have the option to put them into groups , hence the group column – e.g . TEST and PRODUCTION ( set via web.config appsetting ) .I do not want any of the KEY ’ s to be hardcoded anywhere , but I would like to be able to reference them as simply as possible in code , e.g . SiteSetting.getSetting ( “ SiteName ” ) ( these may be used in templates ( masterpages and such ) that more junior devs will create ) I would also like to be able to administer the existing settings in our admin console and to be able to create new settings.The datatype column is for the edit form so that the correct input element can be used , e.g . checkbox for bit types , text box for varchar etc ... SiteSettings database table currently : I am part way through having this working at the moment , but I am not happy with the way I have done it and would like any advice people here have that might help find the ‘ right ’ solution ! I 'm sure people have done this before me . ( I would share what I have so far , but do not want to skew the answers in any particular way ) All i 'm looking for is an overview of how this might be best done , not looking for anyone to write it for me ; ) I ’ ve done quite a bit of searching both here and Google and have not really found what I ’ m looking for , especially the ability to add new setting ‘ definitions ’ as well as editing the settings that exist.The system runs on ASP.NET using webforms , it 's all written in c # and uses MSSQL 2008.As always , any help is very much appreciated ! EDIT : To clarify I am going to explain what I have built so far . I am dead set on storing all of this in SQL as we do n't want web.config or other xml files or another database floating around since it 'll give us more to do when we rollout the app to other customers.So far I have a SiteSettings class , this has a method GetSetting which i can call with GetSetting ( `` SettingAlias '' ) to get the value for `` SettingAlias '' in the DB . This class 's constructor fetches all the settings for the current site from the database and stores those in a dictionary , GetSetting reads from that dictionary . All of that part I am happy with so far.The part I am struggling with is generating the edit form . The previous version of this used a webservice to get/set the settings and I am trying to continue using something similar to save work , but they were all defined in the code , such as GoogleAnalyticsID , Sitename etc ... and each had a column in the database , the change I am making is to store these settings as ROWS instead ( since then it 's easier to add more , no need to change the schema & all of the sitesettings class ) Currently my SiteSettings class has a SiteSettingsEditForm method which grabs all the info from the db , creates a bunch of controls for the form elements , puts that in a temporary page and executes that , then passes the HTML generated to our management system via ajax . This feels wrong and is a bit clunky , and is the reason for posting it here , I am having trouble figuring out how to save this stuff back via the webservice , but more importantly generating a bunch of HTML by executing a page containing a load of form controls just feels like the wrong way to do it.So in summary I ( think i ) want to write a class to be able to cache & read a handful of rows from a database table , and also give me an edit form ( or give data to something else to generate the form ) that is dynamic based on the contents of the same database table ( e.g . where my type column is 'bit ' I want a checkbox , where it is 'text ' I want a text input ) [ sts_sitGuid ] [ uniqueidentifier ] NOT NULL , -- tells us which site the setting is for [ sts_group ] [ nvarchar ] ( 50 ) NOT NULL , -- used to group settings e.g . test/live [ sts_name ] [ nvarchar ] ( max ) NULL , -- the display name of the setting , for edit forms [ sts_alias ] [ nvarchar ] ( 50 ) NOT NULL , -- the name for the setting [ sts_value ] [ nvarchar ] ( max ) NOT NULL , -- the settings value [ sts_dataType ] [ nvarchar ] ( 50 ) NULL , -- indicates the control to render on edit form [ sts_ord ] [ tinyint ] NULL , -- The order they will appear in on the admin form",Managing Dynamic Website Settings Persisted in a Database "C_sharp : If I modify the copied object the original does not change.I understand from this that System.Linq.IEnumerable < T > collections will always produce new objects even though they are reference types when calling ToList ( ) /ToArray ( ) ? Am I missing something as other SO questions are insistent only references are copied . public class TestClass { public int Num { get ; set ; } public string Name { get ; set ; } } IEnumerable < TestClass > originalEnumerable = Enumerable.Range ( 1 , 1 ) . Select ( x = > new TestClass ( ) { Num = x , Name = x.ToString ( ) } ) ; List < TestClass > listFromEnumerable = originalEnumerable.ToList ( ) ; // falsebool test = ReferenceEquals ( listFromEnumerable [ 0 ] , originalEnumerable.ElementAt ( 0 ) ) ;",Why does IEnumerable.ToList produce new objects "C_sharp : I have found the following example in Jon Skeet 's `` C # in depth . 3rd edition '' : I expected that this code would deadlock , but it does not . As I see it , it works this way : Main method calls GetPageLengthAsync synchronously within the main thread . GetPageLengthAsync makes an asynchronous request and immediately returns Task < int > to Main saying `` wait for a while , I will return you an int in a second '' . Main continues execution and stumbles upon lengthTask.Result which causes the main thread to block and wait for lengthTask to finish its work.GetStringAsync completes and waits for main thread to become available to execute Length and start continuation.But it seems like I misunderstand something . Why does n't this code deadlock ? The code in this StackOverflow question about await/async deadlock seems to do the same , but deadlocks . static async Task < int > GetPageLengthAsync ( string url ) { using ( HttpClient client = new HttpClient ( ) ) { Task < string > fetchTextTask = client.GetStringAsync ( url ) ; int length = ( await fetchTextTask ) .Length ; return length ; } } public static void Main ( ) { Task < int > lengthTask = GetPageLengthAsync ( `` http : //csharpindepth.com '' ) ; Console.WriteLine ( lengthTask.Result ) ; }",Why does this async/await code NOT cause a deadlock ? "C_sharp : For example : I would like to define my own Brush class by adding a new property called Name , but there is a compiler error : error CS0534 : 'Brushes.DesignerPatternBrush ' does not implement inherited abstract member 'System.Windows.Freezable.CreateInstanceCore ( ) 'How can I add a Name property to a Brush type ? Note this related question : How do I implement a custom Brush in WPF ? It answers the question of why it is not possible to literally inherit Brush . But is there some other way ( e.g . using an attached property ) to achieve the same effect I want ? public class DesignerPatternBrush : Brush { public string Name { get ; set ; } }","How do I inherit from Brush , so I can add a Name property ?" "C_sharp : Having defined this interface : Why does the following code work : and this does n't ? : Does it have anything to do with int being a value type ? If yes , how can I circumvent this situation ? Thanks public interface IInputBoxService < out T > { bool ShowDialog ( ) ; T Result { get ; } } public class StringInputBoxService : IInputBoxService < string > { ... } ... IInputBoxService < object > service = new StringInputBoxService ( ) ; public class IntegerInputBoxService : IInputBoxService < int > { ... } ... IInputBoxService < object > service = new IntegerInputBoxService ( ) ;",Question about C # 4.0 's generics covariance "C_sharp : I 'm new to EF and struggling to implement the following scenario . I have an entity I 'd like to have a navigation property to another of the same entity . E.g.The only example I 've found so far was where the entity had a parent / child relationship , i.e . the navigation property was an ICollection of the same entity . I tried adapting this but could n't get it to work in my instance . Also , I only need it to be one way , i.e . the entity does n't have a 'PreviousStage ' property , just a 'NextStage ' one . I 'm configuring using Fluent API . Could someone advise if / how this can be achieved ? I am getting this error : Unable to determine the principal end of an association between the types 'namespace.Stage ' and 'namespace.Stage ' . The principal end of this association must be explicitly configured using either the relationship fluent API or data annotationsEditJust realised in my slightly simplified example , I did n't show that NextStageID is optional ( int ? ) . public class Stage { public int ID { get ; set ; } public int ? NextStageID { get ; set ; } public string Name { get ; set ; } public virtual Stage NextStage { get ; set ; } }",EF Code First Navigation Property to same table "C_sharp : How would you write this exact same query using the LINQ query syntax ? I though this should work but it did n't : Here 's a test program if you want to play around with it : var q2 = list.GroupBy ( x = > x.GroupId ) .Select ( g = > g .OrderByDescending ( x = > x.Date ) .FirstOrDefault ( ) ) ; var q1 = from x in list group x by x.GroupId into g from y in g orderby y.Date descending select g.FirstOrDefault ( ) ; public class MyClass { public int Id { get ; set ; } public string GroupId { get ; set ; } public DateTime Date { get ; set ; } public override bool Equals ( object obj ) { var item = obj as MyClass ; return item == null ? false : item.Id == this.Id ; } } static void Main ( string [ ] args ) { var list = new List < MyClass > { new MyClass { GroupId = `` 100 '' , Date=DateTime.Parse ( `` 01/01/2000 '' ) , Id = 1 } , new MyClass { GroupId = `` 100 '' , Date=DateTime.Parse ( `` 02/01/2000 '' ) , Id = 2 } , new MyClass { GroupId = `` 200 '' , Date=DateTime.Parse ( `` 01/01/2000 '' ) , Id = 3 } , new MyClass { GroupId = `` 200 '' , Date=DateTime.Parse ( `` 02/01/2000 '' ) , Id = 4 } , new MyClass { GroupId = `` 300 '' , Date=DateTime.Parse ( `` 01/01/2000 '' ) , Id = 5 } , new MyClass { GroupId = `` 300 '' , Date=DateTime.Parse ( `` 02/01/2000 '' ) , Id = 6 } , } ; var q1 = from x in list group x by x.GroupId into g from y in g orderby y.Date descending select g.FirstOrDefault ( ) ; var q2 = list.GroupBy ( x = > x.GroupId ) .Select ( g = > g .OrderByDescending ( x = > x.Date ) .FirstOrDefault ( ) ) ; Debug.Assert ( q1.SequenceEqual ( q2 ) ) ; }",Convert EF LINQ method syntax to query syntax "C_sharp : The application tries to do a CFind on patient level , get the studies , for a study , get the series and in the end , the images.The code is working when querying two different PACS implementation but fails on a third on study level.The part of the code that makes the patient requestAnd for the study levelIt seems that by examing the logs and also comparing the logs from a tool that there should be a list of abstract syntaxes rather than just one ? Or what is the problem ? Log from jdicom that can execute the cfind request on study levelEdit , Here is conformance statement.https : //sectramedical.blob.core.windows.net/uploads/2018/04/pacs-dicom-conformance-statement-20.1.pdfBut if CFind is not supported , what method to be used to retrieve studies and series ? I am bit lost here but I really appreciate you taking the time to give hints.Here is log ( truncated due to the max length of a post ) from the other tool that manage to list patient and studies and some screen shoots that shows that it is possible . There also a screen shot from Radiant that also can connect , display the patients and display the image . ] Log truncated hitting the post max length . var request = DicomCFindRequest.CreatePatientQuery ( patientId : _patientid , patientName : _patientname ) ; var client = new DicomClient ( ) ; client.AddRequest ( request ) ; await client.SendAsync ( destip , port , useTLS , callingAE , calledAE ) ; request = DicomCFindRequest.CreateStudyQuery ( patientId : _patientid ) ; 2019-02-24 02:32:49.1671 INFO Dicom.Log.NLogManager+NLogger.Log DICOM_STORAGE - > Association request : Calling AE Title : TEST_01 Called AE Title : DICOM_STORAGE Remote host : xxx.29.51.150Remote port : 7817Implementation Class : Implementation Class UID [ 1.3.6.1.4.1.30071.8 ] Implementation Version : fo-dicom 4.0.0Maximum PDU Length : 16384Async Ops Invoked : 1Async Ops Performed : 1Presentation Contexts : 1 Presentation Context : 1 [ Proposed ] Abstract Syntax : Study Root Query/Retrieve Information Model - FIND Transfer Syntax : Implicit VR Little Endian : Default Transfer Syntax for DICOM 2019-02-24 02:32:49.1671 INFO Dicom.Log.NLogManager+NLogger.Log DICOM_STORAGE < - Association accept : Calling AE Title : TEST_01Called AE Title : DICOM_STORAGERemote host : xxx.29.51.150Remote port : 7817Implementation Class : Unknown [ 1.2.752.24.3.3.25.7 ] Implementation Version : WISSTOSCP_20_1Maximum PDU Length : 28672Async Ops Invoked : 1Async Ops Performed : 1Presentation Contexts : 1 Presentation Context : 1 [ RejectAbstractSyntaxNotSupported ] Abstract Syntax : Study Root Query/Retrieve Information Model - FIND Transfer Syntax : Implicit VR Little Endian : Default Transfer Syntax for DICOM 2019-02-24 02:32:49.1671 INFO DicomHandler.DicomHandler+ < > c__DisplayClass8_0. < QueryRetrieveSCU > b__0 DicomCFindRequest.QueryRetrieveSCU response rp.status=Failure [ 0122 : Refused : SOP class not supported ] 2019-02-24 02:32:49.1671 INFO Dicom.Network.DicomCFindRequest.PostResponse DicomCFindRequest.QueryRetrieveSCU response return . 2019-02-24 02:32:49.1671 ERROR Dicom.Log.NLogManager+NLogger.Log No accepted presentation context found for abstract syntax : Study Root Query/Retrieve Information Model - FIND [ 1.2.840.10008.5.1.4.1.2.2.1 ] 2019-02-24 02:32:49.2288 INFO Dicom.Log.NLogManager+NLogger.Log DICOM_STORAGE - > Association release request 2019-02-24 02:32:49.2288 INFO Dicom.Log.NLogManager+NLogger.Log DICOM_STORAGE < - Association release response jdicom : *** request ***application context UID : nullcalled title : DICOM_QR_SCPcalling title : jdicommax pdu size : 32768max operation invoked : 1max operation performed : 1implementation class UID : 1.2.826.0.1.3680043.2.60.0.1implementation version Name : softlink_jdt103abstract syntax scu scp 1.2.840.10008.1.1 -1 -1 1.2.840.10008.5.1.4.1.2.1.1 -1 -1 1.2.840.10008.5.1.4.1.2.2.1 -1 -1 1.2.840.10008.5.1.4.1.2.3.1 -1 -1 1.2.840.10008.5.1.4.1.2.1.2 -1 -1 1.2.840.10008.5.1.4.1.2.2.2 -1 -1 1.2.840.10008.5.1.4.1.2.3.2 -1 -1 nr abstract syntax pcid description 0 1.2.840.10008.1.1 1 Verification SOP Class ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 1 1.2.840.10008.5.1.4.1.2.1.1 3 Patient Root Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 2 1.2.840.10008.5.1.4.1.2.2.1 5 Study Root Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 3 1.2.840.10008.5.1.4.1.2.3.1 7 Patient/Study Only Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 4 1.2.840.10008.5.1.4.1.2.1.2 9 Patient Root Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 5 1.2.840.10008.5.1.4.1.2.2.2 11 Study Root Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 6 1.2.840.10008.5.1.4.1.2.3.2 13 Patient/Study Only Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax ***************Waiting for AssociationRspASSOCIATE_ACKNOWLEDGE detectedjdicom : # 17 : DICOM_QR_SCP > > A-ASSOCIATE-AC PDUjdicom : *** acknowledge ***max pdu size : 28672max operation invoked : 1max operation performed : 1implementation class UID : 1.2.752.24.3.3.25.7implementation version name : WIQRSCP_20_1abstract syntax scu scp nr pcid result transfer syntax 0 1 accepted 1.2.840.10008.1.2 1 3 accepted 1.2.840.10008.1.2 2 5 accepted 1.2.840.10008.1.2 3 7 accepted 1.2.840.10008.1.2 4 9 accepted 1.2.840.10008.1.2 5 11 accepted 1.2.840.10008.1.2 6 13 accepted 1.2.840.10008.1.2 ******************* PatientRootLog # 14 1 PatientID ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ ] # 0 0 SeriesInstanceUID ( 0020,0011 ) IS [ ] # 0 0 SeriesNumber ( 0020,1209 ) IS [ ] # 0 0 NumberOfSeriesRelatedImagesjdicom : DICOM_QR_SCP PDU receivedjdicom : # 16 : DICOM_QR_SCP > > C-FIND-RSP Patient Root Query/Retrieve Information Model - FIND SOP Class , status # ff00H [ StatusEntry.PENDING ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.1.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 258 ] # 2 1 DataSetType ( 0000,0900 ) US [ 65280 ] # 2 1 Statusjdicom : # 16 : DICOM_QR_SCP > > Dataset ( 0008,0005 ) CS [ ISO_IR 100 ] # 10 1 SpecificCharacterSet ( 0008,0050 ) SH [ 1912121-0034201 ] # 16 1 AccessionNumber ( 0008,0052 ) CS [ SERIES ] # 6 1 QueryRetrieveLevel ( 0008,0054 ) AE [ DICOM_QR_SCP ] # 12 1 RetrieveAETitle ( 0008,0060 ) CS [ OP ] # 2 1 Modality ( 0010,0020 ) LO [ 19121212-1212 ] # 14 1 PatientID ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476159 ] # 50 1 SeriesInstanceUID ( 0020,0010 ) SH [ 1912121-0034201 ] # 16 1 StudyID ( 0020,0011 ) IS [ 1 ] # 2 1 SeriesNumber ( 0020,1209 ) IS [ 1 ] # 2 1 NumberOfSeriesRelatedImagesjdicom : DICOM_QR_SCP Waiting for PDUjdicom : DICOM_QR_SCP PDU receivedjdicom : # 16 : DICOM_QR_SCP > > C-FIND-RSP Patient Root Query/Retrieve Information Model - FIND SOP Class , status # 0000H [ Success ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.1.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 257 ] # 2 1 DataSetType ( 0000,0900 ) US [ 0 ] # 2 1 Statusjdicom : DICOM_QR_SCP Waiting for PDUjdicom : Enter _dimseSCUs.waitUntilEmpty ( jdicom : Enter _as.sendReleaseRequest ( ) jdicom : # 16 : DICOM_QR_SCP < < A-RELEASE-RQ PDUjdicom : Leave DimseExchange.releaseAssoc ( ) jdicom : DICOM_QR_SCP PDU receivedjdicom : # 16 : DICOM_QR_SCP > > A-RELEASE-RP PDUjdicom : # 16 : DICOM_QR_SCP closing socketjdicom : DICOM_QR_SCP Leave DimseExchange.run ( ) jdicom : # 17 : DICOM_QR_SCP < < A-ASSOCIATE-RQ PDUjdicom : *** request ***application context UID : nullcalled title : DICOM_QR_SCPcalling title : jdicommax pdu size : 32768max operation invoked : 1max operation performed : 1implementation class UID : 1.2.826.0.1.3680043.2.60.0.1implementation version Name : softlink_jdt103abstract syntax scu scp 1.2.840.10008.1.1 -1 -1 1.2.840.10008.5.1.4.1.2.1.1 -1 -1 1.2.840.10008.5.1.4.1.2.2.1 -1 -1 1.2.840.10008.5.1.4.1.2.3.1 -1 -1 1.2.840.10008.5.1.4.1.2.1.2 -1 -1 1.2.840.10008.5.1.4.1.2.2.2 -1 -1 1.2.840.10008.5.1.4.1.2.3.2 -1 -1 nr abstract syntax pcid description 0 1.2.840.10008.1.1 1 Verification SOP Class ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 1 1.2.840.10008.5.1.4.1.2.1.1 3 Patient Root Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 2 1.2.840.10008.5.1.4.1.2.2.1 5 Study Root Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 3 1.2.840.10008.5.1.4.1.2.3.1 7 Patient/Study Only Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 4 1.2.840.10008.5.1.4.1.2.1.2 9 Patient Root Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 5 1.2.840.10008.5.1.4.1.2.2.2 11 Study Root Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 6 1.2.840.10008.5.1.4.1.2.3.2 13 Patient/Study Only Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax ***************Waiting for AssociationRspASSOCIATE_ACKNOWLEDGE detectedjdicom : # 17 : DICOM_QR_SCP > > A-ASSOCIATE-AC PDUjdicom : *** acknowledge ***max pdu size : 28672max operation invoked : 1max operation performed : 1implementation class UID : 1.2.752.24.3.3.25.7implementation version name : WIQRSCP_20_1abstract syntax scu scp nr pcid result transfer syntax 0 1 accepted 1.2.840.10008.1.2 1 3 accepted 1.2.840.10008.1.2 2 5 accepted 1.2.840.10008.1.2 3 7 accepted 1.2.840.10008.1.2 4 9 accepted 1.2.840.10008.1.2 5 11 accepted 1.2.840.10008.1.2 6 13 accepted 1.2.840.10008.1.2 *******************jdicom : DICOM_QR_SCP Enter DimseExchange.run ( ) jdicom : # 17 : DICOM_QR_SCP < < C-FIND-RQ Patient Root Query/Retrieve Information Model - FIND SOP Classjdicom : DICOM_QR_SCP Waiting for PDU ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.1.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32 ] # 2 1 CommandField ( 0000,0110 ) US [ 1 ] # 2 1 MessageID ( 0000,0700 ) US [ 0 ] # 2 1 Priority ( 0000,0800 ) US [ 65278 ] # 2 1 DataSetTypejdicom : # 17 : DICOM_QR_SCP < < Dataset ( 0008,0018 ) UI [ ] # 0 0 SOPInstanceUID ( 0008,0052 ) CS [ IMAGE ] # 6 1 QueryRetrieveLevel ( 0010,0020 ) LO [ 19121212-1212 ] # 14 1 PatientID ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476159 ] # 50 1 SeriesInstanceUID ( 0020,0013 ) IS [ ] # 0 0 InstanceNumberjdicom : DICOM_QR_SCP PDU receivedjdicom : # 17 : DICOM_QR_SCP > > C-FIND-RSP Patient Root Query/Retrieve Information Model - FIND SOP Class , status # ff00H [ StatusEntry.PENDING ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.1.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 258 ] # 2 1 DataSetType ( 0000,0900 ) US [ 65280 ] # 2 1 Statusjdicom : # 17 : DICOM_QR_SCP > > Dataset ( 0008,0005 ) CS [ ISO_IR 100 ] # 10 1 SpecificCharacterSet ( 0008,0018 ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024575915205577 ] # 50 1 SOPInstanceUID ( 0008,0050 ) SH [ 1912121-0034201 ] # 16 1 AccessionNumber ( 0008,0052 ) CS [ IMAGE ] # 6 1 QueryRetrieveLevel ( 0008,0054 ) AE [ DICOM_QR_SCP ] # 12 1 RetrieveAETitle ( 0010,0020 ) LO [ 19121212-1212 ] # 14 1 PatientID ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476159 ] # 50 1 SeriesInstanceUID ( 0020,0010 ) SH [ 1912121-0034201 ] # 16 1 StudyID ( 0020,0013 ) IS [ 1 ] # 2 1 InstanceNumberjdicom : DICOM_QR_SCP Waiting for PDUjdicom : DICOM_QR_SCP PDU receivedjdicom : # 17 : DICOM_QR_SCP > > C-FIND-RSP Patient Root Query/Retrieve Information Model - FIND SOP Class , status # 0000H [ Success ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.1.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 257 ] # 2 1 DataSetType ( 0000,0900 ) US [ 0 ] # 2 1 Statusjdicom : DICOM_QR_SCP Waiting for PDUjdicom : Enter _dimseSCUs.waitUntilEmpty ( jdicom : Enter _as.sendReleaseRequest ( ) jdicom : # 17 : DICOM_QR_SCP < < A-RELEASE-RQ PDUjdicom : Leave DimseExchange.releaseAssoc ( ) jdicom : DICOM_QR_SCP PDU receivedjdicom : # 17 : DICOM_QR_SCP > > A-RELEASE-RP PDUjdicom : # 17 : DICOM_QR_SCP closing socketjdicom : DICOM_QR_SCP Leave DimseExchange.run ( ) Studyroot LOG : 1 Priority ( 0000,0800 ) US [ 65278 ] # 2 1 DataSetTypejdicom : # 23 : DICOM_QR_SCP < < Dataset ( 0008,0052 ) CS [ SERIES ] # 6 1 QueryRetrieveLevel ( 0008,0060 ) CS [ ] # 0 0 Modality ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ ] # 0 0 SeriesInstanceUID ( 0020,0011 ) IS [ ] # 0 0 SeriesNumber ( 0020,1209 ) IS [ ] # 0 0 NumberOfSeriesRelatedImagesjdicom : DICOM_QR_SCP PDU receivedjdicom : # 23 : DICOM_QR_SCP > > C-FIND-RSP Study Root Query/Retrieve Information Model - FIND SOP Class , status # ff00H [ StatusEntry.PENDING ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.2.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 258 ] # 2 1 DataSetType ( 0000,0900 ) US [ 65280 ] # 2 1 Statusjdicom : # 23 : DICOM_QR_SCP > > Dataset ( 0008,0005 ) CS [ ISO_IR 100 ] # 10 1 SpecificCharacterSet ( 0008,0050 ) SH [ 1912121-0034201 ] # 16 1 AccessionNumber ( 0008,0052 ) CS [ SERIES ] # 6 1 QueryRetrieveLevel ( 0008,0054 ) AE [ DICOM_QR_SCP ] # 12 1 RetrieveAETitle ( 0008,0060 ) CS [ OP ] # 2 1 Modality ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476159 ] # 50 1 SeriesInstanceUID ( 0020,0010 ) SH [ 1912121-0034201 ] # 16 1 StudyID ( 0020,0011 ) IS [ 1 ] # 2 1 SeriesNumber ( 0020,1209 ) IS [ 1 ] # 2 1 NumberOfSeriesRelatedImagesjdicom : DICOM_QR_SCP Waiting for PDUjdicom : DICOM_QR_SCP PDU receivedjdicom : # 23 : DICOM_QR_SCP > > C-FIND-RSP Study Root Query/Retrieve Information Model - FIND SOP Class , status # 0000H [ Success ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.2.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 257 ] # 2 1 DataSetType ( 0000,0900 ) US [ 0 ] # 2 1 Statusjdicom : DICOM_QR_SCP Waiting for PDUjdicom : Enter _dimseSCUs.waitUntilEmpty ( jdicom : Enter _as.sendReleaseRequest ( ) jdicom : # 23 : DICOM_QR_SCP < < A-RELEASE-RQ PDUjdicom : Leave DimseExchange.releaseAssoc ( ) jdicom : DICOM_QR_SCP PDU receivedjdicom : # 23 : DICOM_QR_SCP > > A-RELEASE-RP PDUjdicom : # 23 : DICOM_QR_SCP closing socketjdicom : DICOM_QR_SCP Leave DimseExchange.run ( ) jdicom : # 24 : DICOM_QR_SCP < < A-ASSOCIATE-RQ PDUjdicom : *** request ***application context UID : nullcalled title : DICOM_QR_SCPcalling title : jdicommax pdu size : 32768max operation invoked : 1max operation performed : 1implementation class UID : 1.2.826.0.1.3680043.2.60.0.1implementation version Name : softlink_jdt103abstract syntax scu scp 1.2.840.10008.1.1 -1 -1 1.2.840.10008.5.1.4.1.2.1.1 -1 -1 1.2.840.10008.5.1.4.1.2.2.1 -1 -1 1.2.840.10008.5.1.4.1.2.3.1 -1 -1 1.2.840.10008.5.1.4.1.2.1.2 -1 -1 1.2.840.10008.5.1.4.1.2.2.2 -1 -1 1.2.840.10008.5.1.4.1.2.3.2 -1 -1 nr abstract syntax pcid description 0 1.2.840.10008.1.1 1 Verification SOP Class ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 1 1.2.840.10008.5.1.4.1.2.1.1 3 Patient Root Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 2 1.2.840.10008.5.1.4.1.2.2.1 5 Study Root Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 3 1.2.840.10008.5.1.4.1.2.3.1 7 Patient/Study Only Query/Retrieve Information Model - FIND SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 4 1.2.840.10008.5.1.4.1.2.1.2 9 Patient Root Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 5 1.2.840.10008.5.1.4.1.2.2.2 11 Study Root Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax 6 1.2.840.10008.5.1.4.1.2.3.2 13 Patient/Study Only Query/Retrieve Information Model - MOVE SOP Cl ... ts-0 1.2.840.10008.1.2 Implicit VR Little Endian Transfer Syntax ***************Waiting for AssociationRspASSOCIATE_ACKNOWLEDGE detectedjdicom : # 24 : DICOM_QR_SCP > > A-ASSOCIATE-AC PDUjdicom : *** acknowledge ***max pdu size : 28672max operation invoked : 1max operation performed : 1implementation class UID : 1.2.752.24.3.3.25.7implementation version name : WIQRSCP_20_1abstract syntax scu scp nr pcid result transfer syntax 0 1 accepted 1.2.840.10008.1.2 1 3 accepted 1.2.840.10008.1.2 2 5 accepted 1.2.840.10008.1.2 3 7 accepted 1.2.840.10008.1.2 4 9 accepted 1.2.840.10008.1.2 5 11 accepted 1.2.840.10008.1.2 6 13 accepted 1.2.840.10008.1.2 *******************jdicom : DICOM_QR_SCP Enter DimseExchange.run ( ) jdicom : # 24 : DICOM_QR_SCP < < C-FIND-RQ Study Root Query/Retrieve Information Model - FIND SOP Classjdicom : DICOM_QR_SCP Waiting for PDU ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.2.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32 ] # 2 1 CommandField ( 0000,0110 ) US [ 1 ] # 2 1 MessageID ( 0000,0700 ) US [ 0 ] # 2 1 Priority ( 0000,0800 ) US [ 65278 ] # 2 1 DataSetTypejdicom : # 24 : DICOM_QR_SCP < < Dataset ( 0008,0018 ) UI [ ] # 0 0 SOPInstanceUID ( 0008,0052 ) CS [ IMAGE ] # 6 1 QueryRetrieveLevel ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476159 ] # 50 1 SeriesInstanceUID ( 0020,0013 ) IS [ ] # 0 0 InstanceNumberjdicom : DICOM_QR_SCP PDU receivedjdicom : # 24 : DICOM_QR_SCP > > C-FIND-RSP Study Root Query/Retrieve Information Model - FIND SOP Class , status # ff00H [ StatusEntry.PENDING ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.2.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 258 ] # 2 1 DataSetType ( 0000,0900 ) US [ 65280 ] # 2 1 Statusjdicom : # 24 : DICOM_QR_SCP > > Dataset ( 0008,0005 ) CS [ ISO_IR 100 ] # 10 1 SpecificCharacterSet ( 0008,0018 ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024575915205577 ] # 50 1 SOPInstanceUID ( 0008,0050 ) SH [ 1912121-0034201 ] # 16 1 AccessionNumber ( 0008,0052 ) CS [ IMAGE ] # 6 1 QueryRetrieveLevel ( 0008,0054 ) AE [ DICOM_QR_SCP ] # 12 1 RetrieveAETitle ( 0020,000d ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476158 ] # 50 1 StudyInstanceUID ( 0020,000e ) UI [ 1.3.6.1.4.1.30071.8.345050320220.6024574499476159 ] # 50 1 SeriesInstanceUID ( 0020,0010 ) SH [ 1912121-0034201 ] # 16 1 StudyID ( 0020,0013 ) IS [ 1 ] # 2 1 InstanceNumberjdicom : DICOM_QR_SCP Waiting for PDUjdicom : DICOM_QR_SCP PDU receivedjdicom : # 24 : DICOM_QR_SCP > > C-FIND-RSP Study Root Query/Retrieve Information Model - FIND SOP Class , status # 0000H [ Success ] ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.2.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32800 ] # 2 1 CommandField ( 0000,0120 ) US [ 1 ] # 2 1 MessageIDBeingRespondedTo ( 0000,0800 ) US [ 257 ] # 2 1 DataSetType ( 0000,0900 ) US [ 0 ] # 2 1 Statusjdicom : DICOM_QR_SCP Waiting for PDUjdicom : Enter _dimseSCUs.waitUntilEmpty ( jdicom : Enter _as.sendReleaseRequest ( ) jdicom : # 24 : DICOM_QR_SCP < < A-RELEASE-RQ PDUjdicom : Leave DimseExchange.releaseAssoc ( ) jdicom : DICOM_QR_SCP PDU receivedjdicom : # 24 : DICOM_QR_SCP > > A-RELEASE-RP PDUjdicom : # 24 : DICOM_QR_SCP closing socketjdicom : DICOM_QR_SCP Leave DimseExchange.run ( ) PatientStudyOnlyOM_QR_SCP < < C-FIND-RQ Patient/Study Only Query/Retrieve Information Model - FIND SOP Classjdicom : DICOM_QR_SCP Waiting for PDU ( 0000,0002 ) UI [ 1.2.840.10008.5.1.4.1.2.3.1 ] # 28 1 AffectedSOPClassUID ( 0000,0100 ) US [ 32 ] # 2 1 CommandField ( 0000,0110 ) US [ 1 ] # 2 1 MessageID",CFind fails on Study level - SOP Class not supported or No accepted presentation context found for abstract syntax "C_sharp : My Razor page looks like this.My Startup.cs contains the following.I placed a file called Controllers.HomeController.se.resx directly in the project 's root . The controller HomeController contains the injection.The application does n't crash but the string renedered is Index and not the value from the RESX file . I 've tried to follow the docs as closely as possible but apparently I 've missed something . I need help finding what that would be.I breakpointed and checked the value of _localizer [ `` Index '' ] in the constructor . As expected , the flag for the file not being found is set to true . Checking the value of SearchedLocation gives me Web ... Controllers.MemberController . I ca n't tell if those three dots is the correct one for the RESX file in the project 's root . I was expecting se somewhere in the name too . @ using Microsoft.AspNetCore.Mvc.Localization @ inject IViewLocalizer Localizer < h1 > @ Localizer [ `` Index '' ] < /h1 > ... public void ConfigureServices ( IServiceCollection services ) { ... services.AddLocalization ( a = > a.ResourcesPath = `` / '' ) ; services.Configure < RequestLocalizationOptions > ( a = > { CultureInfo [ ] supportedCultures = { new CultureInfo ( `` sv-SE '' ) , new CultureInfo ( `` se '' ) } ; a.DefaultRequestCulture = new RequestCulture ( `` se '' ) ; a.SupportedCultures = supportedCultures ; a.SupportedUICultures = supportedCultures ; } ) ; ... } public class HomeController : Controller { private readonly Context _context ; private readonly IStringLocalizer < HomeController > _localizer ; public HomeController ( Context context , IStringLocalizer < HomeController > localizer ) { _context = context ; _localizer = localizer ; } ... }",Localization file not effective rendering a Razor page in MVC ASP.NET Core 2.2 "C_sharp : I have these build configurations : These platform configurations : And these compiler conditionals : My solution is a huge API that consists in 20 solutions , some of those solutions consumes Async keywords and other beneffits that are available only from .NetFx 4.5.That part of the code I have it in a conditional in this way : Then , what I 'm trying to do is clear , the .NetFx 4.5 build configurations should compile the block of the NET45 conditional , and the .NetFx 4.0 build configurations should compile the block of the # Else part.The problem I found is that if I change the application target framework in the project settings , the change persist in all the other build configurations , and I would like to avoid that persistance.So how I can do this ? .Note : I marked this question with the C # tag because is a general Visual Studio environment question , but I will clarify that my solutions are written in Vb.Net , because I know there are some big differences between the C # project settings and also their compiler params so maybe a C # advanced answer could not help me . NET40NET45 # If NET45 then Sub Async ... End Sub # Else Sub ... End Sub # End If",Change the application target framework when changing build configurations in Visual Studio "C_sharp : I 'm working on a C # console application . My objective is to create an object called GroupEntity , preferably of non generic type.Inside this GroupEntity object will be a List of 'AttributeFilter ' object which contains object of Generic type which hold the attribute name on a user object in Active Directory and the possible values of those user objects . The reason I want the AttributeFilter object to take a generic type is because some attributes on user objects in AD are string , some are int32 , some are int64 etc.Here are my classes ( I 've cut out the contructorse etc to save space here ) Here is the GroupEntity class . Notice I have a field . Problem is I dont know what that T will be until I run program.cs } Now I use program.cs to initialise and test ... So how can I write my GroupEntity class without a generic parameter so I can hold various types of AttributeFilter < T > inside it . So for example , I can hold AttributeFilter < int > and AttributeFilter < string > and AttributeFilter < long > I ca n't seem to figure out this problem . public class AttributeFilter < T > : IEqualityComparer < AttributeFilter < T > > { private string _attributeName ; private T _attributeValue ; private List < T > _attributeValues { get ; set ; } public AttributeFilter ( string attributeName ) { AttributeName = attributeName ; _attributeValues = new List < T > ( ) ; } public void AddValues ( T attributeValue ) { AttributeValue = attributeValue ; if ( ! _attributeValues.Contains ( AttributeValue ) ) { _attributeValues.Add ( AttributeValue ) ; } } // Ive cut out the getter setter etc that is not relevant } List < AttributeFilter < T > > public class GroupEntity < T > { private string _groupName ; // because I want to a have a List < AttributeFilter < T > > , but I dont really want this here . because of program.cs when I initialise a new GroupEntity < > I have to tell it what type . I wont know . The type could be int32 , string , long or whatever . private List < AttributeFilter < T > > _filters ; public void AddFilters ( AttributeFilter < T > attributeFilter ) { if ( ! _filters.Contains ( attributeFilter , attributeFilter ) ) { _filters.Add ( attributeFilter ) ; } } public GroupEntity ( ) { _filters = new List < AttributeFilter < T > > ( ) ; } public GroupEntity ( string groupName ) : this ( ) { _groupName = groupName ; } class Program { static void Main ( string [ ] args ) { // Create AttributeFilter object for user attribute : EYAccountType var at1 = new AttributeFilter < string > ( `` EYAccountType '' ) ; at1.AddValues ( `` 02 '' ) ; at1.AddValues ( `` 03 '' ) ; at1.AddValues ( `` 04 '' ) ; at1.AddValues ( `` 05 '' ) ; // try adding anothr AtributeFilter with same name . var at3 = new AttributeFilter < string > ( `` EYAccountType1 '' ) ; at3.AddValues ( `` 06 '' ) ; at3.AddValues ( `` 07 '' ) ; // Create AttributeFilter object for user attribute : userAccountControl var at2 = new AttributeFilter < int > ( `` userAccountControl '' ) ; at2.AddValues ( 512 ) ; at2.AddValues ( 544 ) ; at2.AddValues ( 546 ) ; at2.AddValues ( 4096 ) ; // Now create a GroupEntity object var group1 = new GroupEntity < string > ( `` My_First_AD_Group_Name '' ) ; // Try adding the above two AttributeFilter objects we created to the GroupEntity object . group1.AddFilters ( at1 ) ; group1.AddFilters ( at3 ) ; // This is the problem . I know why this is happening . because I initialised the var group1 = new GroupEntity < string > . So it wont accept at2 because at2 is taking in int . //group1.AddFilters ( at2 ) ; }",Wrapping a Generic class inside a non Generic class C # "C_sharp : In one of my WPF project , I have integrated WPF Toolkit 's AutoCompleteBox control . I need a custom Context Menu for this control and I have added one using the ContextMenu property . Unfortunately its not showing the custom created one but showing the default one ( i.e . Cut , Copy , Paste with Cut & Copy as disabled ) . To recreate the issue , I have created a sample project and the window contains 2 controls inside a Grid.The two controls have the same ContextMenu and if I run the solution , I can see that the custom created ContextMenu is working for TextBox and not for AutoCompleteBox . Also , I set the same Context Menu to Grid ( parent control ) and set ContextMenu= '' { x : Null } '' to TextBox & AutoCompleteBox . Now the ContextMenu is inherited for TextBox but not for AutoCompleteBox . So my question is , how can I create a custom ContextMenu for AutoCompleteBox ? If it is not by design ( AutoCompleteBox ) , how can I add a ContextMenu to a custom AutoCompleteBox control which is inherited from AutoCompleteBox . Please advice . < Grid > < Grid.RowDefinitions > < RowDefinition > < /RowDefinition > < RowDefinition > < /RowDefinition > < /Grid.RowDefinitions > < toolkit : AutoCompleteBox > < toolkit : AutoCompleteBox.ContextMenu > < ContextMenu > < MenuItem Header= '' Menu Item 1 '' > < /MenuItem > < MenuItem Header= '' Menu Item 2 '' > < /MenuItem > < /ContextMenu > < /toolkit : AutoCompleteBox.ContextMenu > < /toolkit : AutoCompleteBox > < TextBox Grid.Row= '' 1 '' > < TextBox.ContextMenu > < ContextMenu > < MenuItem Header= '' Menu Item 1 '' > < /MenuItem > < MenuItem Header= '' Menu Item 2 '' > < /MenuItem > < /ContextMenu > < /TextBox.ContextMenu > < /TextBox > < /Grid >",WpfToolkit AutoCompleteBox ContextMenu not working "C_sharp : As a premise one of a key difference of FP design about reusable libraries ( for what I 'm learning ) , is that these are more data-centric that corresponding OO ( in general ) .This seems confirmed also from emerging techniques like TFD ( Type-First-Development ) , well explained by Tomas Petricek in this blog post.Nowadays language are multi-paradigm and the same Petricek in its book explains various functional techniques usable from C # .What I 'm interested here and , hence the question , is how to properly partition code.So I 've defined library data structures , using the equivalent of discriminated unions ( as shown in Petricek book ) , and I project to use them with immutable lists and/or tuples according to the domain logic of mine requirements.Where do I place operations ( methods ... functions ) that acts on data structures ? If I want define an high-order function that use a function value embodied in a standard delegates Func < T1 ... TResult > , where do I place it ? Common sense says me to group these methods in static classes , but I 'd like a confirmation from people that already wrote functional libs in C # .Assuming that this is correct and I 've an high-order function like this : If choosing vertebrated animal has N particular cases that I want to expose in the library , what 's the more correct way to expose them . orAny indication will be very appreciated.EDIT : I want to quote two phrases from T. Petricek , Real World Functional Programming foreword by Mads Torgersen : [ ... ] You can use functional programming techniques in C # to great benefit , though it is easier and more natural to do so in F # . [ ... ] Functional programming is a state of mind . [ ... ] EDIT-2 : I feel there 's a necessity to further clarify the question . The functional mentioned in the title strictly relates to Functional Programming ; I 'm not asking the more functional way of grouping methods , in the sense of more logic way or the the way that make more sense in general.This implies that the implementation will try to follow as more as possible founding concepts of FP summarized by NOOO manifesto and quoted here for convenience and clarity : Functions and Types over classes Purity over mutability Composition over inheritance Higher-order functions over method dispatch Options over nulls The question is around how to layout a C # library wrote following FP concepts , so ( for example ) it 's absolutely not an option putting methods inside data structure ; because this is a founding Object-Oriented paradigm.EDIT-3 : Also if the question got response ( and various comments ) , I do n't want give the wrong impression that there has been said that one programming paradigm is superior than another.As before I 'll mention an authority on FP , Don Syme , in its book Expert F # 3.0 ( ch.20 - Designing F # Libraries - pg.565 ) : [ ... ] It 's a common misconception that the functional and OO programming methodologies compete ; in fact , they 're largely orthogonal . [ ... ] static class AnimalTopology { IEnumerable < Animal > ListVertebrated ( Func < Skeleton , bool > selector ) { // remainder omitted } } static class VertebratedSelectorsA { // this is compatible with `` Func < Skeleton , bool > selector '' static bool Algorithm1 ( Skeleton s ) { // ... } } static class VertebratedSelectorsB { // this method creates the function for later application static Func < Skeleton , bool > CreateAlgorithm1Selector ( Skeleton s ) { // ... } }",How to properly partition code in a C # functional library ? "C_sharp : C # Hi , I 've been developing c # web applications for a couple of years and there is one issue I keep coming upagainst that I ca n't find a logical way to solve.I have a control I wish to access in code behind , this control is deep within the markup ; burried within ContentPlaceHolders , UpdatePanels , Panels , GridViews , EmptyDataTemplates , TableCells ( or whatever structure you like.. the point is it has more parents than farthers for justice ) .How can I use FindControl ( `` '' ) to access this control without doing this : Page.Form.Controls [ 1 ] .Controls [ 1 ] .Controls [ 4 ] .Controls [ 1 ] .Controls [ 13 ] .Controls [ 1 ] .Controls [ 0 ] .Controls [ 0 ] .Controls [ 4 ] .FindControl ( `` '' ) ;",Easy way to use FindControl ( `` '' ) "C_sharp : I have a project primarily written in F # that uses a component written in C # . It is building fine on Windows with Visual Studio and on Linux and OS X using Makefiles.I 'm trying to port it to .NET Core , which has its own build system , dotnet build . I 'm having difficulty replicating the nested project handling of my existing build systems under it . That is , I want it to build the C # DLL , then build and link the F # executable project to it.I tried to do without DLLs , but each project.json file can apparently only reference files in one language . If you try to add a C # file to the compileFiles list of an F # project file , dotnet build complains that it ca n't compile Foo.cs with fsc.My C # project is in a subdirectory of the F # project , named after the namespace it implements , so I created a new .NET Core C # DLL project in that directory , but now I do n't see how to tie the two projects together.The dependencies feature of the project file format does n't seem to solve this sort of problem . If the DLL project is in Foo/Bar and it implements the Foo.Bar namespace , dotnet restore fails to find it with this dependency reference : Apparently it can only search NuGet for dependencies . I do n't want to ship the component to NuGet purely so that dotnet restore can find it.I do n't want to use bin syntax to reference the built DLL because that would require a 2-pass build and a third project.json file . ( One for the F # project , one for the C # project , and one to reference the built DLL . ) Even then , I still do n't see how to tie the first project to the third.Surely there 's a simple way to have a nested build tree with dotnet build ? `` dependencies '' : { ... other stuff ... `` Foo.Bar '' : `` * '' } ,",Mixed languages and sub-projects with .NET Core "C_sharp : im a bit stuck in this : Im trying to convert a rectangle made by two OpenCvSharp.Points into a System.Drawing.Rectangle.I found an interesting Region in OpenCvSharp and i want to save this region as a new bitmap to display in a PictureBox or something.Basically in want this OpenCvSharp Rect which is drawn into the mat as a single bitmap to display in a pictureboxThis is the line where the rectangle is drawnmat.Rectangle ( new OpenCvSharp.Point ( x1 , centerY - height / 2 ) , new OpenCvSharp.Point ( centerX + width / 2 , centerY + height / 2 ) , Colors [ classes ] , 2 ) ; Can anybody help me with this ? Im very sorry for my bad english ! public static Mat Detect ( string filename ) { var cfg = `` 4000.cfg '' ; var model = `` 4000.weights '' ; //YOLOv2 544x544 var threshold = 0.3 ; var mat = Cv2.ImRead ( filename ) ; var w = mat.Width ; var h = mat.Height ; var blob = CvDnn.BlobFromImage ( mat , 1 / 255.0 , new OpenCvSharp.Size ( 416 , 416 ) , new Scalar ( ) , true , false ) ; var net = CvDnn.ReadNetFromDarknet ( Path.Combine ( System.AppDomain.CurrentDomain.BaseDirectory , cfg ) , Path.Combine ( System.AppDomain.CurrentDomain.BaseDirectory , model ) ) ; net.SetInput ( blob , `` data '' ) ; Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; var prob = net.Forward ( ) ; // Process NeuralNet sw.Stop ( ) ; Console.WriteLine ( $ '' Runtime : { sw.ElapsedMilliseconds } ms '' ) ; const int prefix = 5 ; //skip 0~4 for ( int i = 0 ; i < prob.Rows ; i++ ) { var confidence = prob.At < float > ( i , 4 ) ; if ( confidence > threshold ) { //get classes probability Cv2.MinMaxLoc ( prob.Row [ i ] .ColRange ( prefix , prob.Cols ) , out _ , out OpenCvSharp.Point max ) ; var classes = max.X ; var probability = prob.At < float > ( i , classes + prefix ) ; if ( probability > threshold ) //more accuracy { //get center and width/height var centerX = prob.At < float > ( i , 0 ) * w ; var centerY = prob.At < float > ( i , 1 ) * h ; var width = prob.At < float > ( i , 2 ) * w ; var height = prob.At < float > ( i , 3 ) * h ; //label formating var label = $ '' { Labels [ classes ] } { probability * 100:0.00 } % '' ; Console.WriteLine ( $ '' confidence { confidence * 100:0.00 } % { label } '' ) ; var x1 = ( centerX - width / 2 ) < 0 ? 0 : centerX - width / 2 ; //avoid left side over edge //draw result mat.Rectangle ( new OpenCvSharp.Point ( x1 , centerY - height / 2 ) , new OpenCvSharp.Point ( centerX + width / 2 , centerY + height / 2 ) , Colors [ classes ] , 2 ) ; var textSize = Cv2.GetTextSize ( label , HersheyFonts.HersheyTriplex , 0.5 , 1 , out var baseline ) ; Cv2.Rectangle ( mat , new Rect ( new OpenCvSharp.Point ( x1 , centerY - height / 2 - textSize.Height - baseline ) , new OpenCvSharp.Size ( textSize.Width , textSize.Height + baseline ) ) , Colors [ classes ] , Cv2.FILLED ) ; Cv2.PutText ( mat , label , new OpenCvSharp.Point ( x1 , centerY - height / 2 - baseline ) , HersheyFonts.HersheyTriplex , 0.5 , Scalar.Black ) ; } } } return mat ; }",Conversion between OpenCVSharp Coordinates and System.Drawing Coordinates C_sharp : In my application I 'm using Iron Python to provide scripting capabilities . The problem is that embedded scripts do n't see references I 've linked to the app . Only solution as I understand is to manually import them from scriptbut I 'm reading scripts from files and I do n't want to prepend a bunch of imports like this.So how do I add references from host application ? ScriptEngine / ScriptScope does n't look to have any related methods : ( import clrclr.AddReference ( ... ) from ... import ...,IronPython : adding references from host application "C_sharp : I discovered an issue with ( what might be ) over-optimization in .Net Native and structs . I 'm not sure if the compiler is too aggressive , or I 'm too blind to see what I 've done wrong . To reproduce this , follow these steps : Step 1 : Create a new Blank Universal ( win10 ) app in Visual Studio 2015 Update 2 targeting build 10586 with a min build of 10240 . Call the project NativeBug so we have the same namespace.Step 2 : Open MainPage.xaml and insert this labelStep 3 : Copy/paste the following into MainPage.xaml.csStep 4 : Run the application in Debug x64 . You should see this label : 42.5 , 42.5 = > 107.5 , 107.5Step 5 : Run the application in Release x64 . You should see this label : -7.5 , -7.5 = > 7.5 , 7.5Step 6 : Uncomment line 45 in MainPage.xaml.cs and repeat step 5 . Now you see the original label 42.5 , 42.5 = > 107.5 , 107.5By commenting out line 45 , the code will use Rectangle2D.Inflate2 ( ... ) which is exactly the same as Rectangle2D.Inflate1 ( ... ) except it creates a local copy of the computations before sending them to the constructor of Rectangle2D . In debug mode , these two function exactly the same . In release however , something is getting optimized out.This was a nasty bug in our app . The code you see here was stripped from a much larger library and I 'm afraid there might be more . Before I report this to Microsoft , I would appreciate it if you could take a look and let me know why Inflate1 does n't work in release mode . Why do we have to create local copies ? < Page x : Class= '' NativeBug.MainPage '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' mc : Ignorable= '' d '' > < Grid Background= '' { ThemeResource ApplicationPageBackgroundThemeBrush } '' > < ! -- INSERT THIS LABEL -- > < TextBlock x : Name= '' _Label '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' / > < /Grid > < /Page > using System ; using System.Collections.Generic ; namespace NativeBug { public sealed partial class MainPage { public MainPage ( ) { InitializeComponent ( ) ; var startPoint = new Point2D ( 50 , 50 ) ; var points = new [ ] { new Point2D ( 100 , 100 ) , new Point2D ( 100 , 50 ) , new Point2D ( 50 , 100 ) , } ; var bounds = ComputeBounds ( startPoint , points , 15 ) ; _Label.Text = $ '' { bounds.MinX } , { bounds.MinY } = > { bounds.MaxX } , { bounds.MaxY } '' ; } private static Rectangle2D ComputeBounds ( Point2D startPoint , IEnumerable < Point2D > points , double strokeThickness = 0 ) { var lastPoint = startPoint ; var cumulativeBounds = new Rectangle2D ( ) ; foreach ( var point in points ) { var bounds = ComputeBounds ( lastPoint , point , strokeThickness ) ; cumulativeBounds = cumulativeBounds.Union ( bounds ) ; lastPoint = point ; } return cumulativeBounds ; } private static Rectangle2D ComputeBounds ( Point2D fromPoint , Point2D toPoint , double strokeThickness ) { var bounds = new Rectangle2D ( fromPoint.X , fromPoint.Y , toPoint.X , toPoint.Y ) ; // ** Uncomment the line below to see the difference ** //return strokeThickness < = 0 ? bounds : bounds.Inflate2 ( strokeThickness ) ; return strokeThickness < = 0 ? bounds : bounds.Inflate1 ( strokeThickness ) ; } } public struct Point2D { public readonly double X ; public readonly double Y ; public Point2D ( double x , double y ) { X = x ; Y = y ; } } public struct Rectangle2D { public readonly double MinX ; public readonly double MinY ; public readonly double MaxX ; public readonly double MaxY ; private bool IsEmpty = > MinX == 0 & & MinY == 0 & & MaxX == 0 & & MaxY == 0 ; public Rectangle2D ( double x1 , double y1 , double x2 , double y2 ) { MinX = Math.Min ( x1 , x2 ) ; MinY = Math.Min ( y1 , y2 ) ; MaxX = Math.Max ( x1 , x2 ) ; MaxY = Math.Max ( y1 , y2 ) ; } public Rectangle2D Union ( Rectangle2D rectangle ) { if ( IsEmpty ) { return rectangle ; } var newMinX = Math.Min ( MinX , rectangle.MinX ) ; var newMinY = Math.Min ( MinY , rectangle.MinY ) ; var newMaxX = Math.Max ( MaxX , rectangle.MaxX ) ; var newMaxY = Math.Max ( MaxY , rectangle.MaxY ) ; return new Rectangle2D ( newMinX , newMinY , newMaxX , newMaxY ) ; } public Rectangle2D Inflate1 ( double value ) { var halfValue = value * .5 ; return new Rectangle2D ( MinX - halfValue , MinY - halfValue , MaxX + halfValue , MaxY + halfValue ) ; } public Rectangle2D Inflate2 ( double value ) { var halfValue = value * .5 ; var x1 = MinX - halfValue ; var y1 = MinY - halfValue ; var x2 = MaxX + halfValue ; var y2 = MaxY + halfValue ; return new Rectangle2D ( x1 , y1 , x2 , y2 ) ; } } }",Is this a possible bug in .Net Native compilation and optimization ? "C_sharp : If I create a Uri class instance from string that has trailing full stops - ' . ' , they are truncated from the resulting Uri object . For example in C # : returns `` /folder/ '' instead of `` /folder ... / '' .Escaping `` . '' with `` % 2E '' did not help.How do I make the Uri class to keep trailing period characters ? Uri test = new Uri ( `` http : //server/folder ... / '' ) ; test.PathAndQuery ;",System.Uri class truncates trailing ' . ' characters "C_sharp : I 'm trying to enhance my enum so I 've tried a suggestion on Display and another one on Description.I 'm annoyed because I do n't understand the difference between them . Both Description class and Display class are from framework 4.5.It 's additionally annoying since neither of them work in the code . I 'm testing the following but I only get to see the donkeys ... [ Flags ] public enum Donkeys { [ Display ( Name = `` Monkey 1 '' ) ] Donkey1 = 0 , [ Description ( `` Monkey 2 '' ) ] Donkey2 = 1 }",Difference between Display and Description attribute C_sharp : I would like to know . How can I remove the link between the blocks ? In other words . I want to get opposite of LinkTo.I want to write a logger based on tlp dataflow.I wrote this interface and want to delete a subscription for ILogListener when it needed . public interface ILogManager { void RemoveListener ( ILogListener listener ) ; },TPL Dataflow how to remove the link between the blocks "C_sharp : I 've noticed in C # I can override methods in the Form ( ) parent class , like so : I do n't understand how PaintEventArgs is generated and how/when it is passed to this function . I 've got to assume OnPaint ( ) is called every time the form needs repainting.Furthermore , when I create button press events they look like this : Once again , I do n't understand how/why these parameters are passed when a button click is activated . protected override void OnPaint ( PaintEventArgs e ) { } private void button1_Click ( object sender , EventArgs e ) { }",How is an event parameter passed ? C_sharp : Could you please show me the C # Equivalent of this VB.NET code : I am not sure where/how to add it in for C # : The code is suppose to tell the class to expect a list of tasks from the controller ... Public Partial Class Index Inherits System.Web.Mvc.Viewpage ( Of List ( Of Task ) ) End Class public partial class DirList : System.Web.Mvc.ViewPage { },VB.NET generics to C # syntax "C_sharp : ( I am talking about pure SS project , please not to be confused with MVC Razor ) How do we limit the visit to a SS Razor view with authentication ? That is , how do we call user session and auth code from SS Razor ? I wish to do something like this : @ inherits ViewPage @ Authenticate ( RedirectUrl = `` /Login '' ) < div > Hello @ UserSession.UserName < /div > < div > You are in the secured area now < /div >",ServiceStack put Authentication to Razor view C_sharp : If i have an interface : can i have this : so consumers of IBar will be able to set or get ? interface IFoo { int Offset { get ; } } interface IBar : IFoo { int Offset { set ; } },Interface inheritance "C_sharp : Suppose you have a web handler that calls an asynchronous method like such : And , due to poor coding ( no CancellationToken , no timeouts , etc ) , SomeMethod never completes . The frustrated user , in turn , presses `` stop '' on her browser and goes to the pub.Suppose this happens to a lot of users.I know that I can write a timeout to prevent it from waiting eternally , but if I do not ... what happens ? Is this a memory leak ? Does it get cleaned up eventually ? What 's the worst-case scenario ? var foo = await SomeMethod ( ) ;",What are the implications for incomplete async tasks in .NET 4.5 ? "C_sharp : I have some older software that I am maintaining . I am attempting to find out what specific reference file contains the namespace that is being brought into the project by the using directive.Is there a simple way of finding which reference file contains the namespace of a given using directive ? This seems like it should be easy , and it probably is , but all of my searching using these terms returns results related to how to implement using directives and reference classes , etc . However , I can not find an answer for how to find the reference containing the namespace in question.For some reason , the references often contain namespaces that have nothing to do with the name of the file . For example , I 've seen references like Foo.cs that contain the namespace Bar . I then seeand ca n't find an easy way to see what reference file contains the namespace.Anyway , apologies in advance if this is something stupidly simple that I 'm just not finding . using Bar ;",How do I find what reference file a namespace in a using directive is coming from ? "C_sharp : Whats the easiest way to traverse a methodinfo in c # ? I want to traverse the method body and find field-references and such and retrieves the types.In System.Reflection there is : which is kinda low-level and would require `` some '' work before I would be able to traverse the body.I know Cecil exists , but there 's a problem in loading an in memory assembly with cecil . The assembly i 'm working with is't always `` on disk '' it can be an in memory assembly compiled from eg . Boo , and I wa n't a clean solution without writing the assembly temporary to disk.What other alternatives is there out there for this ? mi.GetMethodBody ( ) .GetILAsByteArray ( )",Traverse a c # method and anazlye the method body "C_sharp : Does anyone have a more elegant solution to parsing enums ? The following just seems like a mess to me . UserType userType = ( UserType ) Enum.Parse ( typeof ( UserType ) , iUserType.ToString ( ) ) ;",Elegantly parsing C # Enums "C_sharp : In my MVC Application : In the controller I created a list of dynamic type , which is stored in the session.The view then attempts to access the objects but it throws an exception : 'object ' does not contain a definition for ' a'The code : In my viewNote At the debug time , in the watch view I can see the properties/valuesI ca n't store the list in the ViewBag in my case because I used ajax to call the methodI tried to use var , object instead of dynamic = > the same resultI think this is not related to MVC or Razor engineI tried to use a aspx view ( not the razor one ) and the same resultWhy I ca n't access the property , if the debugger can see it , and how can I solve this problem ? // Controller List < dynamic > myLists = new List < dynamic > ( ) ; for ( int i=0 ; i < 3 ; i++ ) { var ano = new { a= ' a ' , b = i } ; myLists.Add ( ano ) ; } Session [ `` rows '' ] = myLists ; // My Viewforeach ( dynamic row in ( Session [ `` rows '' ] as List < dynamic > ) ) { < div > @ row < /div > // output { a : ' a ' , b :1 } < div > @ row.a < /div > // throw the error . }",Retrieve property from a dynamic object after storing/retrieving it From the Session "C_sharp : I would like to round a number that is based on ratio of two values.The ratio will include values that are greater or less than the original value whereWhen newValue > originalValue I can round to the nearest lower factor using : For example : factor = 2 ratio = 3 NearestLowerFactor = 2When newValue < originalValue I wish to round to the nearest reciprocal of the factor . Therefore , if the factor is 2 I would like to round based on factors of 1/2 , that is 1/2 , 1/4 , 1/8 , 1/16 , etc.For example : originalValue = 8newValue = 3ratio = 0.375NearestLowerFactor = 0.25 or 1 / 4.How would I round to the closest lower factor in this case ? ratio = newValue / originalvalue double NearestLowerFactor ( float value , double factor ) { return Math.Floor ( value / factor ) * factor ; }",Round a number based on a ratio in C # C_sharp : I have the following LINQ to SQL query : Without the ToList call I get the exception below on the Sum ( ) line : The null value can not be assigned to a member with type System.Double which is a non-nullable value type.If I add a .ToList ( ) before sum ( as shown in the comment ) I do n't get the error.Why do I get the error in the first place ? ( Shipped_Qty is not null and no null data in that field exists in the db ) Why is adding ToList ( ) a fix ? The sql query executed is below ( there is more to the query than above ) : No results are returned . var inTransitStocks = orderHistories.Where ( oh = > oh.Shipped_Qty > 0 ) .Select ( oh = > oh.Shipped_Qty ) ; //.ToList ( ) ; var inTransitStock = ( int ) inTransitStocks.Sum ( ) ; SELECT [ t0 ] . [ Shipped Qty ] FROM [ dbo ] . [ Order History ] AS [ t0 ] WHERE ( [ t0 ] . [ Shipped Qty ] > @ p0 ) AND ( [ t0 ] . [ CUST_ID ] = @ p1 ) AND ( [ t0 ] . [ SHIP_TO_ID ] = @ p2 ) AND ( [ t0 ] . [ Item ] = @ p3 ) AND ( ( [ t0 ] . [ DT_LST_SHP ] > = @ p4 ) OR ( UNICODE ( [ t0 ] . [ LN_STA ] ) = @ p5 ) ),LINQ to SQL and null values "C_sharp : How can I change the source of a specific ResourceDictionary inside ResourceDictionary.MergedDictionaries based on the ResourceDictionary 's x : Name/x : Uid ? Thanks . < Application x : Class= '' CDesign.App '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : CDesign '' StartupUri= '' MainWindow.xaml '' > < Application.Resources > < ResourceDictionary x : Name= '' ThemeDictionary '' > < ResourceDictionary.MergedDictionaries > < ResourceDictionary Source= '' pack : //application : , , ,/AppStyles ; component/Resources/Icons.xaml '' / > < ResourceDictionary Source= '' pack : //application : , , ,/AppStyles ; component/Resources/IconsNonShared.xaml '' / > < ! -- MahApps.Metro resource dictionaries . Make sure that all file names are Case Sensitive ! -- > < ResourceDictionary Source= '' pack : //application : , , ,/MahApps.Metro ; component/Styles/Controls.xaml '' / > < ResourceDictionary Source= '' pack : //application : , , ,/MahApps.Metro ; component/Styles/Fonts.xaml '' / > < ResourceDictionary Source= '' pack : //application : , , ,/MahApps.Metro ; component/Styles/Colors.xaml '' / > < ! -- Accent and AppTheme setting -- > < ResourceDictionary x : Uid= '' Accents '' x : Name= '' Accents '' Source= '' pack : //application : , , ,/MahApps.Metro ; component/Styles/Accents/Blue.xaml '' / > < ResourceDictionary x : Uid= '' BaseTheme '' x : Name= '' BaseTheme '' Source= '' pack : //application : , , ,/MahApps.Metro ; component/Styles/Accents/BaseDark.xaml '' / > < /ResourceDictionary.MergedDictionaries > < /ResourceDictionary > < /Application.Resources >",XAML : How can I change the source of a specific ResourceDictionary "C_sharp : I need to execute async delete operation with user confirmation . Something like this : The problem is the MessageBox would execute asynchronously too.Which is the best pattern in ReactiveUI to ask user synchronously and then execute method asynchronously ? public ReactiveAsyncCommand DeleteCommand { get ; protected set ; } ... DeleteCommand = new ReactiveAsyncCommand ( ) ; DeleteCommand.RegisterAsyncAction ( DeleteEntity ) ; ... private void DeleteEntity ( object obj ) { if ( MessageBox.Show ( `` Do you really want to delete this entity ? `` , `` Confirm '' , MessageBoxButton.YesNo ) == MessageBoxResult.Yes ) { //some delete operations } }",Asynchronous command execution with user confirmation "C_sharp : In my indexed property I check whether the index is out of bounds or not . If it is , I throw an IndexOutOfBoundsException.When I run the Code Analyst ( in VS12 ) it complains with CA1065 : Unexpected exception in unexpected location.Referring to the description of CA1065 , onlyare allowed in an indexed getter.Throwing IndexOutOfBoundsException seems natural to me , so what is the reasoning here ? ( And yes , I know I can turn the warning off , I just want to know the reasoning ) System.InvalidOperationExceptionSystem.NotSupportedExceptionSystem.ArgumentExceptionKeyNotFoundException",IndexOutOfRangeException in indexed getter "C_sharp : I need to convert my class to JSON and I use Json.NET . But I can have different JSON structures , like : orMy C # code is : My idea was when Configuration.Type - value has n't attribute OptionalSettingsAttribute - to serialize it as type : `` simple1 '' . Otherwise - to use Configuration.Type - value as type 's value key ( type : { optional1 : { } } ) and value in Configuration.TypeAdditionalData as optional1 - value ( like 2 simple JSON above ) .I tried to create a custom Converter , like : But when I add [ JsonConverter ( typeof ( ConfigurationCustomConverter ) ) ] attribute to Configuration class : and called JsonConvert.SerializeObject ( configurationObj ) ; I received next error : Self referencing loop detected with type 'Configuration ' . Path `` .Do you have any ideas how to change my code to serialize my class to 2 different JSON structures ? Note : I wo n't use the same class to deserialize the JSON.Thank you ! { name : `` Name '' , type : `` simple1 '' , value : 100 } ; { name : `` Name '' , type : { optional1 : { setting1 : `` s1 '' , setting2 : `` s2 '' , ///etc . } , value : 100 } ; public class Configuration { [ JsonProperty ( PropertyName = `` name '' ) ] public string Name { get ; set ; } [ JsonProperty ( PropertyName = `` type '' ) ] public MyEnumTypes Type { get ; set ; } public OptionalType TypeAdditionalData { get ; set ; } [ JsonProperty ( PropertyName = `` value '' ) ] public int Value { get ; set ; } public bool ShouldSerializeType ( ) { OptionalSettingsAttribute optionalSettingsAttr = this.Type.GetAttributeOfType < OptionalSettingsAttribute > ( ) ; return optionalSettingsAttr == null ; } public bool ShouldSerializeTypeAdditionalData ( ) { OptionalSettingsAttribute optionalSettingsAttr = this.Type.GetAttributeOfType < OptionalSettingsAttribute > ( ) ; return optionalSettingsAttr ! = null ; } } public enum MyEnumTypes { [ EnumMember ( Value = `` simple1 '' ) ] Simple1 , [ EnumMember ( Value = `` simple2 '' ) ] Simple2 , [ OptionalSettingsAttribute ] [ EnumMember ( Value = `` optional1 '' ) ] Optional1 , [ EnumMember ( Value = `` optional2 '' ) ] [ OptionalSettingsAttribute ] Optional2 } public class ConfigurationCustomConverter : JsonConverter { public override bool CanConvert ( Type objectType ) { return typeof ( Configuration ) .IsAssignableFrom ( objectType ) ; } public override object ReadJson ( JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer ) { return serializer.Deserialize < Configuration > ( reader ) ; } public override void WriteJson ( JsonWriter writer , object value , JsonSerializer serializer ) { //my changes here serializer.Serialize ( writer , value ) ; } [ JsonConverter ( typeof ( ConfigurationCustomConverter ) ) ] public class Configuration","Json.NET different json structure , based on enum value" "C_sharp : How can you access the Value property of a CommandLine Parsed ? Trying to use the CommandLineParser The wiki section on Parsing says the instance of T can be access through the Value property ... If parsing succeeds , you 'll get a derived Parsed type that exposes an instance of T through its Value property.But I ca n't see any Value property on the parserResult , only a Tag ... And I know I 'm missing something as if I debug , I can see the Value property ? ? ? ParserResult < Options > parserResult = Parser.Default.ParseArguments < Options > ( args ) ; WriteLine ( parserResult.Tag ) ;",How can you access the Value property of a CommandLine Parsed < T > ? "C_sharp : I have a simple program which draws geometrical figures based on mouse data provided by user.I 've got one class which handles the mouse tracking ( it gets the List with mouse movement history ) and oneabstract class called Shape . From this class I derieve some extra Shapes , like Circle , Rectangle , etc . - and every one of them overrides the abstract Draw ( ) function.It all works nicely , but the problem comes when I want the user to be able to switch desired Shape manually . I get the mouse data and i know what shape should I draw . The problem is how to make the code to `` know '' which object should it create and pass appropiate parameters to the constructor . It is also impossible at this point to add new Shape derivatives , which is obiously wrong.I obiously do n't want to come out with code like : The code above clearly vilates the Open-Closed Principle . The problem is that I do n't have any good idea how to get over it . The main problem is that different Shapeshave constructors with different parameters , which makes it much more troublesome.I am pretty sure that this is a common problem , but I do n't know how to get past it . Do you have ay idea ? List < Shape > Shapes = new List < Shape > ( ) ; // somwhere later if ( CurrentShape == `` polyline '' ) { Shapes.Add ( new Polyline ( Points ) ) ; } else if ( CurrentShape == `` rectangle '' ) { Shapes.Add ( new Rectangle ( BeginPoint , EndPoint ) ) ; } // and so on .",Getting past Open-Closed Principle "C_sharp : I am moving a calculation engine from an Azure worker role into Azure Service Fabric . It works by listening for messages on a Service Bus that it then processes based on the message content.Currently , the calculation is working correctly but if the compute is taking longer than a minute or so the message does not get removed from the queue after completion . In the worker role , we solved this by increasing the `` AutoRenewTimeout '' . However , using the `` ServiceFabric.ServiceBus '' nuget package , I can not work out where you would set this . I have used the demo project as a reference to set up a stateless service that actually runs the compute . Below is an extract from CalculateService.cs where the Stateless Service is initialised.I did try using the < BrokeredMessage > message.Complete ( ) ; but that was throwing a message lock error . var options = new OnMessageOptions { AutoComplete = true , AutoRenewTimeout = TimeSpan.FromMinutes ( 3 ) } ; _queueClient.OnMessage ( OnMessage , options ) ; internal sealed class CalculateService : StatelessService { public CalculateService ( StatelessServiceContext context ) : base ( context ) { } /// < summary > /// Optional override to create listeners ( e.g. , TCP , HTTP ) for this service replica to handle client or user requests . /// < /summary > /// < returns > A collection of listeners. < /returns > protected override IEnumerable < ServiceInstanceListener > CreateServiceInstanceListeners ( ) { string serviceBusQueueName = CloudConfigurationManager.GetSetting ( `` QueueName '' ) ; yield return new ServiceInstanceListener ( context = > new ServiceBusQueueCommunicationListener ( new Handler ( this ) , context , serviceBusQueueName ) , `` StatelessService-ServiceBusQueueListener '' ) ; } } internal sealed class Handler : AutoCompleteServiceBusMessageReceiver { protected override Task ReceiveMessageImplAsync ( BrokeredMessage message , CancellationToken cancellationToken ) { ServiceEventSource.Current.ServiceMessage ( _service , $ '' Handling queue message { message.MessageId } '' ) ; var computeRole = new ExcelCompute ( ) ; var rMessage = new RangeMessage ( ) ; rMessage = message.GetBody < RangeMessage > ( ) ; var result = computeRole.OnMessage ( rMessage , message.MessageId ) ; //returns true if the compute was successful ( which it currently , always is ) return Task.FromResult ( result ) ; } }",Azure Service Bus/Service Fabric message not being removed from queue "C_sharp : I am setting the page title on the Navigationbar asThis page is a child page of Tabbed page where the Tab already has the Title `` Tab1 '' .Now when I open the Homework.cs page from Tab1 , The above code changing Tab title to Homework and the Navigationbar title also changes to `` Homework '' . I do n't want to change Tab title.MyTabbed page code usingSee some convenient snippetsLoginContentPage button clickParentDashboard Containing tabsFrom now I am clicking on HomewPage as I shown in starting of this question & that is not working.How can I do this ? public Homework ( ) { InitializeComponent ( ) ; Title = `` Homework '' ; } public class MyTabbedPage : TabbedPage { public MyTabbedPage ( ) { this.CurrentPageChanged +=delegate { this.Title = this.CurrentPage.Title ; } ; } } public App ( ) { InitializeComponent ( ) ; MainPage = new NavigationPage ( new LoginPage ( ) ) ; } btnLogin.Clicked +=async delegate { await Navigation.PushAsync ( new ParentDashboard ( ) , false ) ; } ; public partial class ParentDashboard : MyTabbedPage { public ParentDashboard ( ) { InitializeComponent ( ) ; Title= '' Home '' ; //upto here title working } }",How to change Navigationbar title irrespective of Tab title "C_sharp : I 'm trying to rewrite generic code like this ( C # ) : In F # : But F # constraint solving works different than C # and compiler outputs a bunch of typing errors : error FS0698 : Invalid constraint : the type used for the constraint is sealed , which means the constraint could only be satisfied by at most one solution warning FS0064 : This construct causes code to be less generic than indicated by the type annotations . The type variable 'T has been constrained to be type `` U ' . error FS0663 : This type parameter has been used in a way that constrains it to always be `` U ' error FS0013 : The static coercion from type ' U to ' U involves an indeterminate type based on information prior to this program point . Static coercions are not allowed on some types . Further type annotations are needed . error FS0661 : One or more of the explicit class or function type variables for this binding could not be generalized , because they were constrained to other typesPlease , explain me how to correctly rewrite C # code above and why F # version I 've wrote does n't compiles . U Upcast < T , U > ( T x ) where T : U { return x ; } let ucast < 'T , ' U when 'T : > ' U > ( x : 'T ) = x : > ' U",Rewrite some C # generic code into F # "C_sharp : Sometimes I expect a certain range of items and need to do some validation to ensure that I am within that range . The most obvious way to do this is to just compare the number of items in the collection with the range . Although , my understanding is that the linq Count ( ) method will evaluate the entire enumerable before returning a result . Ideally I would only cause evaluation on the minimal number of items to get my result . What would be the best way to ensure that an enumerable has less than a certain number of items without causing any unnecessary evaluation ? public static bool IsWithinRange < T > ( this IEnumerable < T > enumerable , int max ) { return enumerable.Count ( ) < = max ; }",Check if an IEnumerable has less than a certain number of items without causing any unnecessary evaluation ? "C_sharp : From this answer to the question : Do HttpClient and HttpClientHandler have to be disposed ? , I see that the best practice is not to dispose a System.Net.Http.HttpClient per HTTP request . In particular , it is stated that : standard usage of HttpClient is not to dispose of it after every request.And that is fine.My question is , does this `` pattern '' apply to Windows.Web.Http.HttpClient as well ? Or should it be disposed per HTTP request ? I think the documentation is a bit vague on this . In one of the samples , it simply states : I believe this can be read both ways , so any specific input on this is appreciated . // Once your app is done using the HttpClient object call dispose to // free up system resources ( the underlying socket and memory used for the object ) httpclient.Dispose ( ) ;",Do Windows.Web.Http.HttpClient have to be disposed per HTTP request ? "C_sharp : I 'm trying to upload video using c # to SharePoint 2013 document library , every time the code runs I get a `` file not found '' exception , it only throws errors with .mp4 files . If I upload a jpg or any other file format for that matter it will work . What am I doing wrong ? Thanks in advance for the help.UPADTECreated a library , for people to download that will work for uploading .mp4'shttps : //github.com/bikecrazyy/sharepoint-library-uploader string result = string.Empty ; try { //site url ClientContext context = new ClientContext ( `` siturl '' ) ; // The SharePoint web at the URL . Web web = context.Web ; FileCreationInformation newFile = new FileCreationInformation ( ) ; newFile.Content = System.IO.File.ReadAllBytes ( @ '' C : \test.mp4 '' ) ; newFile.Url = `` test.mp4 '' ; List docs = web.Lists.GetByTitle ( `` Learning Materials2 '' ) ; Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add ( newFile ) ; context.Load ( uploadFile ) ; context.ExecuteQuery ( ) ; } catch ( Exception Ex ) { }",SharePoint 2013 - Document Library upload c # C_sharp : I would like to catch all variants of a generic exception class and I was wondering if there is a way to do it without multiple catch blocks . For example say I have an exception class : and two derived classes : is there a way of catching both MyDerivedStringException and MyDerivedIntException in one catch block.I have tried this : but it is not very clean and means I do not have access to MyProperty.I am interested in a general solution to the problem but in my case the generic Exception is defined in a third party library which as pointed out below adds some additional constraints to the problem . public class MyException < T > : Exception { public string MyProperty { get ; } public MyException ( T prop ) : base ( prop.ToString ( ) ) { MyProperty = prop ? .ToString ( ) ; } } public class MyDerivedStringException : MyException < string > { public MyDerivedStringException ( string prop ) : base ( prop ) { } } public class MyDerivedIntException : MyException < int > { public MyDerivedIntException ( int prop ) : base ( prop ) { } } try { ... } catch ( Exception e ) when ( e is MyDerivedStringException || e is MyDerivedIntException ) { },How to catch all variants of a generic exception in C # "C_sharp : I am using the following code to display the elapsed time of a task in the status bar in my application . this.TimingLabel is a label in the statusStrip control in the footer of the winform.But I get completely different results on Windows XP vs Windows 7Windows XP : Windows 7Why is the units appearing before the time in Windows 7 ? I have checked Regional Settings both machines are set to US with same Date Time formatting . Make quite quite sure it is the same code running on both machines.This is very odd behavior in some very simple code . As a follow up : I made the following change to my code but still have the same problem : public void DisplayDuration ( TimeSpan duration ) { string formattedDuration ; if ( duration.TotalMilliseconds < 2000 ) formattedDuration = string.Format ( `` { 0 } ms '' , duration.TotalMilliseconds ) ; else if ( duration.TotalSeconds < 60 ) formattedDuration = string.Format ( `` { 0 } sec '' , duration.TotalSeconds ) ; else formattedDuration = string.Format ( `` { 0 } min '' , duration.TotalMinutes ) ; this.TimingLabel.Text = formattedDuration ; } formattedDuration = string.Format ( `` { 0 } ms '' , duration.TotalMilliseconds.ToString ( ) ) ;",String.format ( ) value in statusstrip label displayed differently on Win 7 vs Win XP "C_sharp : I have a list of dates organized like this : I am trying to find how to consolidate ranges in an efficient way ( it has to be quite fast because it is to consolidate financial data streams in realtime ) .Dates do NOT overlap.what I was thinking about is : Sort everything by From timeand then iterate through pairs to see if Pair1.To == Pair2.From to merge them , but this means several iterations.Is there a better way to do this , like in a single passHere are some examplesexpected output : In practice , it 's really about seconds and not dates , but the idea is the same . ( From , To ) ( From , To ) ... ( From , To ) ( 2019-1-10 , 2019-1-12 ) ( 2019-3-10 , 2019-3-14 ) ( 2019-1-12 , 2019-1-13 ) ( 2019-1-10 , 2019-1-12 ) + ( 2019-1-12 , 2019-1-13 ) - > ( 2019-1-10 , 2019-1-13 ) ( 2019-3-10 , 2019-3-14 ) - > ( 2019-3-10 , 2019-3-14 )",How to consolidate date ranges in a list in C # "C_sharp : Is it possible to get something drawn with default .net paint methods ( System.Drawing methods ) to a SharpDX Texture2D object so that i can display it as a texture ? Preferably with the SharpDX Toolkit.If yes , how ? edit : what i am trying so far : Bitmap b = new Bitmap ( 100,100 ) ; MemoryStream ms = new MemoryStream ( ) ; b.Save ( ms , System.Drawing.Imaging.ImageFormat.Png ) ; Texture2D tex = Texture2D.Load ( g.device , ms ) ; // crashing herems.Close ( ) ;",SharpDX - System.Drawing interoperability "C_sharp : Given my current extension method : Original State : Current Result for ring.rotate ( 10 ) ; Is there any way to get rid of this while loop and any chance to integrate the repetition into the LINQ query ? BestHenrik public static List < char > rotate ( this List < char > currentList , int periodes ) { if ( periodes ! = 1 ) { int x = currentList.Count ( ) - 1 ; return rotate ( currentList.Skip ( x ) . Concat ( currentList.Take ( x ) ) .ToList < char > ( ) , periodes - 1 ) ; } return currentList ; } ring = new List < char > ( ) { ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' , ' h ' , ' i ' , ' j ' } ; J A B C D E F G H II J A B C D E F G HH I J A B C D E F GG H I J A B C D E FF G H I J A B C D E Recursive StepsE F G H I J A B C DD E F G H I J A B CC D E F G H I J A BB C D E F G H I J A A B C D E F G H I J Result",Repeat LINQ Query "C_sharp : I found a very intersting thing——Let 's say : The result is a , why ? And if I say : The result becomes `` b '' , why ? enum Myenum { a , b , c= 0 } public class Program { static void Main ( string [ ] args ) { Myenum ma = Myenum.a ; Console.WriteLine ( ma ) ; } } enum Myenum { a , b=0 , c } public class Program { static void Main ( string [ ] args ) { Myenum ma = Myenum.a ; Console.WriteLine ( ma ) ; } }",How does C # decide which enum value as a returned one ? Any rules ? "C_sharp : I need to build about 30 different administration pages to add/edit/delete records from 30 different tables . I could obviously spend the time creating 30 unique pages , to query each table , but I 'm curious if there 's a way to simply create a single , dynamic page that queries a single , dynamic linq query . This linq query then returns all fields & records from a specified table.I 've seen examples of dynamic linq similar to this one ( http : //weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx ) , but that still requires hardcoding the table name into the query . I 'd like to do a select all similar to this , where I pass in the name of the table ( i.e . `` Products '' , `` Orders '' , etc ) , and then somehow query that table : Is something like this even possible to do ? Thanks private List < tableName > MyDynamicQuery ( string tableName ) { IEnumerable < tableName > dynamicList ; using ( MyEntities db = _conn.GetContext ( ) ) { dynamicList = ( from q in db. < tableName > select q ) .ToList ( ) ; } return dynamicList ; }",How to create a fully dynamic linq query ? "C_sharp : I am writing this program to replace the character at the nth position of a string in a text file . My text file consists of the following contents -And here is the output of the code -The above result is not what i wanted . Only one line is updated the rest are not found anymore within the file.Here 's my complete code in C # Where have i gone wrong ? Please help ! the quick brown fox jumped over the lazy dogthe quick brown fox jumped over the lazy dogthe quick brown fox jumped over the lazy dogthe quick brown fox jumped over the lazy dog thehuick brown fox jumped over the lazy dog var txtFiles = Directory.GetFiles ( @ '' E : \PROJ\replaceY\replaceY\ '' , `` *.txt '' ) ; foreach ( string currentFile in txtFiles ) { string [ ] lines = File.ReadAllLines ( currentFile ) ; foreach ( string line in lines ) { var theString = line ; var aStringBuilder = new StringBuilder ( theString ) ; aStringBuilder.Remove ( 3 , 2 ) ; aStringBuilder.Insert ( 3 , `` h '' ) ; theString = aStringBuilder.ToString ( ) ; using ( StreamWriter outfile = new StreamWriter ( currentFile ) ) { outfile.Write ( theString.ToString ( ) ) ; } Console.WriteLine ( theString ) ; Console.ReadKey ( ) ; } }",Replace a character of the nth position "C_sharp : I am building an API and using swagger to test the endpoints . I have a ProductDTO : in this DTO I want to use Price class which is used throughout my code . Price class looks like this : But since private setters are used in Price class I can not set these values using swagger ( it has readonly attribute on those ) . I really like this approach of having private setters and setting values with constructor , which by the way is public . Is there any way I could set values for Price class using swagger and still use private setters on properties ? public string ProductName { get ; set ; } ... public Price Price { get ; set ; } public class Price { public Price ( decimal amount , string currency ) { Amount = amount ; Currency = currency ; } public decimal Amount { get ; private set ; } public string Currency { get ; private set ; } }",Use constructor to set properties in swagger "C_sharp : It is a leet code contest question which I am trying to attempt after contest is over but my code always exceeds time limit . Question is Given four lists A , B , C , D of integer values , compute how many tuples ( i , j , k , l ) there are such that A [ i ] + B [ j ] + C [ k ] + D [ l ] is zero . To make problem a bit easier , all A , B , C , D have same length of N where 0 ≤ N ≤ 500 . All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.Example : My code is is there any better way ? Thanks in anticipation . Input : A = [ 1 , 2 ] B = [ -2 , -1 ] C = [ -1 , 2 ] D = [ 0 , 2 ] Output:2Explanation : The two tuples are : 1 . ( 0 , 0 , 0 , 1 ) - > A [ 0 ] + B [ 0 ] + C [ 0 ] + D [ 1 ] = 1 + ( -2 ) + ( -1 ) + 2 = 0 2 . ( 1 , 1 , 0 , 0 ) - > A [ 1 ] + B [ 1 ] + C [ 0 ] + D [ 0 ] = 2 + ( -1 ) + ( -1 ) + 0 = 0 public static int FourSumCount ( int [ ] A , int [ ] B , int [ ] C , int [ ] D ) { int count = 0 ; List < int > map1 = new List < int > ( ) ; List < int > map2 = new List < int > ( ) ; for ( int i = 0 ; i < A.Length ; i++ ) for ( int y = 0 ; y < B.Length ; y++ ) { map1.Add ( A [ i ] + B [ y ] ) ; map2.Add ( C [ i ] + D [ y ] ) ; } for ( int i = 0 ; i < map2.Count ( ) ; i++ ) { for ( int j = 0 ; j < map2.Count ( ) ; j++ ) //if ( map1.Contains ( map2 [ i ] *-1 ) ) // { // var newList = map1.FindAll ( s = > s.Equals ( map2 [ i ] * -1 ) ) ; // count = count + newList.Count ( ) ; // } if ( map1 [ i ] + map2 [ j ] == 0 ) { count++ ; } } return count ; }",How to improve the performance of Leetcode 4sum-ii challenge "C_sharp : I have implemented dependency injection in MVC 3 unity framework and following the instructions.It worked , but I have a few questions regarding this : Here is my implementation : And the classes which implement this interface are : In the bootstrapper class , Now my question is `` I want to set the service class D in the Homecontroller constructor , but according to the above code , it is setting `` class F '' in the constructor.Is there any way to do this ? any modification to the above code ? public interface ID { string MReturn ( ) ; } public class D : ID { public string MReturn ( ) { return `` Hi '' ; } } public class E : ID { public string MReturn ( ) { return `` HiE '' ; } } public class F : ID { public string MReturn ( ) { return `` Hif '' ; } } private static IUnityContainer BuildUnityContainer ( ) { var container = new UnityContainer ( ) ; container.RegisterType < ID , D > ( ) ; container.RegisterType < IController , HomeController > ( `` feedbackRepo '' ) ; container.RegisterType < ID , E > ( ) ; container.RegisterType < ID , F > ( ) ; // register all your components with the container here // it is NOT necessary to register your controllers // e.g . container.RegisterType < ITestService , TestService > ( ) ; return container ; }",Dependency injection in MVC 3 using unity framework "C_sharp : In C # 6.0 , the new syntax let us write read-only auto-properties with using an initializer : Likewise , we can write it using an expression body getter : For simple types , these two should have the same effect : a read-only auto-property that returns true.But is one of them preferred over the other ? I suspect that the former uses a backing field : Whereas the latter is turned into something like : Is that right , or is the compiler smarter than this ? public bool AllowsDuplicates { get ; } = true ; public bool AllowsDuplicates = > true ; private readonly bool _backingField = true ; public bool AllowsDuplicates { get { return _backingField ; } } public bool AllowsDuplicates { get { return true ; } }",Read-Only Auto-Property for Simple Types : Initializer VS Expression Body Getter "C_sharp : I have an observable stream created from an event pattern like seen below.What I want to do is subscribe to the stream and execute a method when there has either been 10 seconds of inactivity ( no events have occurred ) or 100 events have fired without the method having been executed . This is to avoid scenarios when events are fired every 5 seconds and the onNext method is never called . How can I accomplish this ? I know how to do the first part ( see below ) but I ca n't figure out how to do the counting logic . Note that I already know how to subscribe to the stream.Any help would be much appreciated ! Thank you . var keyspaceStream = Observable.FromEventPattern < RedisSubscriptionReceivedEventArgs > ( h = > keyspaceMonitor.KeySpaceChanged += h , h = > keyspaceMonitor.KeySpaceChanged -= h ) ; var throttledStream = keyspaceStream.Throttle ( TimeSpan.FromSeconds ( 10 ) ) ;",Use Observable.FromEventPattern to perform action after inactivity or count "C_sharp : High Level : I want to use my custom Cortana command `` Notepad '' in TEXT mode . For instance , by pressing WIN+S and typing `` appname Notepad Example sentence ! '' . ( This will open Notepad and input `` Example sentence ! '' . ) The Notepad command already works in VOICE mode : when I press WIN+C and say `` appname Notepad Example sentence ! `` , my notepad script is run with the payload `` Example sentence ! '' . The Problem : When I press WIN+S and input `` appname Notepad Example sentence ! `` , the text property of SpeechRecognitionResult is `` Notepad ... '' ( as opposed to voice where it is `` Notepad Example sentence ! `` , as expected ) . Code : VCD.xml excerptCommandHandler.csQuestion RestatedHow can the above code be changed to extract command arguments ( i.e . everything other than the app name and command name ) in text mode ? < Command Name= '' notepad '' > < Example > Notepad Example Sentence ! < /Example > < ListenFor > Notepad { wildcardArgs } < /ListenFor > < Feedback > Notepadding { wildcardArgs } < /Feedback > < Navigate/ > < /Command > < PhraseTopic Label= '' wildcardArgs '' Scenario= '' Dictation '' > < ! -- < Subject > Wildcard < /Subject > -- > < /PhraseTopic > public static CortanaCommand ProcessCommand ( SpeechRecognitionResult speechRecognitionResult , CommandDiagnostics diagnostics ) { // Get the name of the voice command and the raw text string voiceCommandName = speechRecognitionResult.RulePath [ 0 ] ; string text = speechRecognitionResult.Text ; string mode = speechRecognitionResult.SemanticInterpretation.Properties [ interpretationKey ] .FirstOrDefault ( ) ; // When mode is voice , text is `` Notepad Example sentence ! '' // When mode is text , text is `` Notepad ... '' // How can one retrieve `` Example sentence ! '' from `` ... '' ! ? // Is there some property other than speechRecognitionResult.Text that holds the raw text typed ? string argument = null ; CortanaCommand processedCommand = null ; switch ( voiceCommandName ) { // ... case CortanaCommand.Notepad : const string notepad = `` Notepad '' ; argument = CortanaCommand.StripOffCommandName ( notepad , text ) ; processedCommand = new NotepadCortanaCommand ( argument , diagnostics ) ; break ; default : Debug.WriteLine ( `` Command Name Not Found : `` + voiceCommandName ) ; break ; } return processedCommand ; }","How to extract the argument from a Cortana command with a phrase topic , activated via text ?" "C_sharp : The Fluent Api is asSo here are some classes that I have defined . They have relationships as follows : Client & Product have one to many , Client & Inquiry have one to many and Product & Inquiry have one to many . I am using Code First here . Now using fluent api I have defined the relationships , these relationships are supposed to be required ones , meaning Client & Product relationship can not be null as well as Client and Inquiry ca n't be null either.However the relationship between Client & Inquiry is being forced to be an optional one with the Code First . When i try to make them required the EF does not generate the database.Can someone tell me what is wrong with my model that it is causing the EF to not create a required relationsship between Client & Inruiry ? Is this due to cascade delete ? As I read some where the mssql can only have one cascade delete path between Client , Product and Inquiry . Any help explaination would be nice . public class Client { public Int32 ClientID { get ; set ; } public virtual ICollection < Inquiry > InquiryManufacturers { get ; set ; } public virtual ICollection < Product > Products { get ; set ; } public virtual ICollection < Inquiry > InquiryRetailers { get ; set ; } } public class Product { public Int32 ProductID { get ; set ; } public Int32 ClientID { get ; set ; } public virtual Client Client { get ; set ; } public virtual ICollection < Inquiry > Inquiries { get ; set ; } } public class Inquiry { public Int32 InquiryID { get ; set ; } public Int32 ProductID { get ; set ; } public Int32 ManufacturerID { get ; set ; } public Int32 RetailerID { get ; set ; } public virtual Product Product { get ; set ; } public virtual Client Manufacturer { get ; set ; } public virtual Client Retailer { get ; set ; } } HasRequired ( i = > i.Product ) .WithMany ( p = > p.Inquiries ) ; HasRequired ( i = > i.Manufacturer ) .WithMany ( p = > p.InquiryManufacturers ) .HasForeignKey ( p = > p.ManufacturerID ) ; HasRequired ( i = > i.Retailer ) .WithMany ( p = > p.InquiryRetailers ) .HasForeignKey ( p = > p.RetailerID ) ;",Code first causing required relation to be optional ? "C_sharp : Let 's say that I have an array.I want to join them with comma per 3 items like below.I know I can use But this gives me the result asDoes anyone have an idea ? string [ ] temp = { `` a '' , `` b '' , `` c '' , `` d '' , `` e '' , `` f '' , `` g '' , `` h '' , `` i '' , `` j '' } ; string [ ] temp2 = { `` a , b , c '' , `` d , e , f '' , `` g , h , i '' , `` j '' } ; string temp3 = string.Join ( `` , '' , temp ) ; `` a , b , c , d , e , f , g , h , i , j ''",How to join array to string with comma per 3 items in c # "C_sharp : I have a small question about structures with the LayoutKind.Explicit attribute set . I declared the struct as you can see , with a fieldTotal with 64 bits , being fieldFirst the first 32 bytes and fieldSecond the last 32 bytes . After setting both fieldfirst and fieldSecond to Int32.MaxValue , I 'd expect fieldTotal to be Int64.MaxValue , which actually does n't happen . Why is this ? I know C # does not really support C++ unions , maybe it will only read the values well when interoping , but when we try to set the values ourselves it simply wo n't handle it really well ? [ StructLayout ( LayoutKind.Explicit ) ] struct STRUCT { [ FieldOffset ( 0 ) ] public Int64 fieldTotal ; [ FieldOffset ( 0 ) ] public Int32 fieldFirst ; [ FieldOffset ( 32 ) ] public Int32 fieldSecond ; } STRUCT str = new STRUCT ( ) ; str.fieldFirst = Int32.MaxValue ; str.fieldSecond = Int32.MaxValue ; Console.WriteLine ( str.fieldTotal ) ; // < -- -- - I 'd expect both these values Console.WriteLine ( Int64.MaxValue ) ; // < -- -- - to be the same . Console.ReadKey ( ) ;",How can I simulate a C++ union in C # ? "C_sharp : Resharper warns me when parts of my code are never used ; this is very helpful.However , I have quite a few classes that are not referenced by other code directly . These classes are used in the dependency injection ( DI ) configuration only . I use spring.net for DI . The DI configuration is in xml format.Is there any way I can tell Resharper to use the DI files for the inspection of unused classes ? I know I can suppress the Resharper warning using something like : But I do n't like this very much - it 's difficult to read and I do n't really want to suppress the warning.Note : There is a less obtrusive and more readable way to suppress the warning , which I found on the jetbrains forum . When you define this custom attribute : Then you can suppress the warning : // ReSharper disable UnusedMember.Globalpublic class TheClass : IInterfaceWiredUsingSpringDI// ReSharper restore UnusedMember.Global [ MeansImplicitUse ] public class IoCAttribute : Attribute { } [ IoC ] public class TheClass : IInterfaceWiredUsingSpringDI",Tell Resharper to use spring.net DI configuration for the inspection of unused classes ? "C_sharp : tl ; dr ; What I need to be able to do is reverse engineer serial commands so that I can figure out how either the human readable values or the binary values are being serialized into raw serial commands.IE : Im working on a wrapper for an open source automation project.There is a way to send raw commands , and in theory string multiple commands together.I 've sniffed a few serial commands , and this is what they look like.What I need to be able to do is reverse engineer this so that I can make the serial calls programmatically , or better yet , figure out how either the human readable values or the binary values are being serialized into raw serial commands.Yes , I could sniff ALL the commands and store each value separately , but I 'd like to know how this has been done.Here 's my current observation.The calls are broken up into two.04 is initiated and tells the device what to look for ** tells the system which device is being controlled [ HouseCode & DeviceCode ] hex 55 is returned to tell you it 's ready06 is initiated and tells the device what to expect** tells the system the house code and command [ HouseCode & FunctionCode ] ** is optionally sent and is a value between 0 & 100 to reference a dim levelhex 55 is sent back again to tell you it 's readyThe second pair uses the first character as the alphabetic code ( HouseCode = A , B , C , etc ) and the second character is the address ( DeviceCode = 1 , 2 , 3 , etc ) with this information , my personal guess is that ... 6 must directly correspond to A e must directly correspond to BThe forth pair starts with the same HouseCode as the second pairThe forth pair ends with the FunctionCode1 = all on2 = on3 = off4 = dim5 = bright6 = all offetc..The fifth pair only shows on a bright/dim command and represents the number between 0 and 100Lastly , in the docs , each of the commands relate to Binary data , so it 's probably not a matter of converting A1 to hex , but rather the binary to hex.Does anyone know how I might go about achieving this ? if 66 = 'A1 ' or '0110 1 ' 6e = 'A2 ' or '0110 2 ' e6 = 'B1 ' or '1110 1 ' ee = 'B2 ' or '1110 2'then what is A3 or B3 , etc . [ init ] [ HouseCode | DeviceCode ] [ ready ] [ HouseCode | FunctionCode ] 04 66 06 62 // A1 ON04 6e 06 62 // A2 ON 04 62 06 62 // A3 ON04 6a 06 62 // A4 ON04 61 06 62 // A5 ON04 69 06 62 // A6 ON04 65 06 62 // A7 ON04 6d 06 62 // A8 ON04 67 06 62 // A9 ON04 6f 06 62 // A10 ON04 63 06 62 // A11 ON04 6b 06 62 // A12 ON04 60 06 62 // A13 ON04 68 06 62 // A14 ON04 64 06 62 // A15 ON04 6c 06 62 // A16 ON04 e6 06 e2 // B1 ON 04 ee 06 e2 // B2 ON 04 e2 06 e2 // B3 ON 04 ea 06 e2 // B4 ON ... .04 ec 06 e2 // B16 ON04 66 06 63 // A1 Off04 e6 06 e3 // B1 Off04 66 06 61 // All A lights On ( using A1 as the starting point ) 04 e6 06 e1 // All B lights On ( using B1 as the starting point ) 04 66 06 66 // All A lights Off ( using A1 as the starting point ) 04 e6 06 66 // All B lights Off ( using A1 as the starting point ) 04 66 06 64 2a // A1 Dim 2004 66 06 64 2c // A1 Dim 2104 66 06 64 2e // A1 Dim 2204 66 06 65 2a // A1 Bright 2004 66 06 65 69 // A1 Bright 50 HouseCode DeviceCode Binary Value A 1 0110 B 2 1110 C 3 0010 D 4 1010 E 5 0001 F 6 1001 G 7 0101 H 8 1101 I 9 0111 J 10 1111 K 11 0011 L 12 1011 M 13 0000 N 14 1000 O 15 0100 P 16 1100FunctionCode Binary ValueAll Units Off 0000All Lights On 0001On 0010Off 0011Dim 0100Bright 0101All Lights Off 0110Extended Code 0111Hail Request 1000Hail Acknowledge 1001Pre-set Dim ( 1 ) 1010Pre-set Dim ( 2 ) 1011Extended Data Transfer 1100Status On 1101 Status Off 1110Status Request 1111",Reverse Engineering Serial Commands C_sharp : I have this problem where String.Contains returns true and String.LastIndexOf returns -1 . Could someone explain to me what happened ? I am using .NET 4.5 . static void Main ( string [ ] args ) { String wikiPageUrl = @ '' http : //it.wikipedia.org/wiki/ʿAbd_Allāh_al-Sallāl '' ; if ( wikiPageUrl.Contains ( `` wikipedia.org/wiki/ '' ) ) { int i = wikiPageUrl.LastIndexOf ( `` wikipedia.org/wiki/ '' ) ; Console.WriteLine ( i ) ; } },String.Contains and String.LastIndexOf C # return different result ? "C_sharp : I have a situation which come in front of me very often but I do n't have any solution to it right now.Suppose I have a key/value pair like thisI want to bind this data to an asp label control , Right now what I do is , I bind UserID to the tooltip of the label & UserName to the text of the label , It works fine but drawback is that when user hovers the label it shows UserID as a tooltip to the user which is obvious.I want to find some better way to do this job , please help me to get a better approach here . UserID | UserName -- -- -- -- -- -- -- -- -1 | Yogi2 | Mike",What 's the best way to bind key/value pair to an asp label "C_sharp : I am upgrading a .NET Core Web API from 2.2 to 3.1 . When testing the ChangePasswordAsync function , I receive the following error message : Can not update identity column 'UserId'.I ran a SQL Profile and I can see that the Identity column is not included in the 2.2 UPDATE statement but it is in 3.1 . The line of code in question returns NULL , as opposed to success or errors , and is as follows : The implementation of the ChangePasswordAsnyc is as follows ( code truncated for brevity ) . Note : AspNetUsers extends IdentityUser.The UserId is included in the objResult , along with a lot of other fields , which is then returned at the end of the method . From what I can tell , without being able to step through the ChangePasswordAsync method , the function updates all fields that are contained in the objUser . Question : How do I suppress the identity column from being populated in the UPDATE statement that ChangePasswordAsnyc is generating ? Do I need to add an attribute in the model ? Do I need to remove the UserId from the objUser before passing it into the ChangePasswordAsync ? Or , something else ? Bounty QuestionI have created a custom user class that extends the IdentityUser class . In this custom class , there is an additional IDENTITY column . In upgrading the .NET Core 2.2 to 3.1 , the ChangePasswordAsync function no longer works because the 3.1 method is trying to UPDATE this IDENTITY column whereas this does not happen in 2.1.There was no code change other than upgrading an installing the relevant packages . The accepted answer needs to fix the problem.UPDATEMigrations are not used as this results in a forced marriage between the database and the Web API with it 's associated models . In my opinion , this violated the separation of duties between database , API , and UI . But , that 's Microsoft up to its old ways again.I have my own defined ADD , UPDATE , and DELETE methods that use EF and set the EntityState . But , when stepping through the code for ChangePasswordAsync , I do not see any of these functions called . It is as if ChangePasswordAsync uses the base methods in EF . So , I do not know how to modify this behavior . from Ivan 's answer.Note : I did post a question to try and understand how the ChangePasswordAsync method calls EF here [ Can someone please explain how the ChangePasswordAsnyc method works ? ] [ 1 ] .namespace ABC.Model.AspNetCorenamespace ABC.Model.ClientsEntitiesRepo objResult = await this.UserManager.ChangePasswordAsync ( objUser , objChangePassword.OldPassword , objChangePassword.NewPassword ) ; [ HttpPost ( `` / [ controller ] /change-password '' ) ] public async Task < IActionResult > ChangePasswordAsync ( [ FromBody ] ChangePassword objChangePassword ) { AspNetUsers objUser = null ; IdentityResult objResult = null ; // retrieve strUserId from the token . objUser = await this.UserManager.FindByIdAsync ( strUserId ) ; objResult = await this.UserManager.ChangePasswordAsync ( objUser , objChangePassword.OldPassword , objChangePassword.NewPassword ) ; if ( ! objResult.Succeeded ) { // Handle error . } return this.Ok ( new User ( objUser ) ) ; } using ABC.Common.Interfaces ; using ABC.Model.Clients ; using Microsoft.AspNetCore.Identity ; using System ; using System.ComponentModel.DataAnnotations ; using System.ComponentModel.DataAnnotations.Schema ; namespace ABC.Model.AspNetCore { // Class for AspNetUsers model public class AspNetUsers : IdentityUser { public AspNetUsers ( ) { // Construct the AspNetUsers object to have some default values here . } public AspNetUsers ( User objUser ) : this ( ) { // Populate the values of the AspNetUsers object with the values found in the objUser passed if it is not null . if ( objUser ! = null ) { this.UserId = objUser.UserId ; // This is the problem field . this.Email = objUser.Email ; this.Id = objUser.AspNetUsersId ; // Other fields . } } // All of the properties added to the IdentityUser base class that are extra fields in the AspNetUsers table . [ DatabaseGenerated ( DatabaseGeneratedOption.Identity ) ] [ Key ] public int UserId { get ; set ; } // Other fields . } } using ABC.Model.AspNetCore ; using JsonApiDotNetCore.Models ; using System ; using System.ComponentModel.DataAnnotations ; namespace ABC.Model.Clients { public class User : Identifiable { public User ( ) { // Construct the User object to have some default values show when creating a new object . } public User ( AspNetUsers objUser ) : this ( ) { // Populate the values of the User object with the values found in the objUser passed if it is not null . if ( objUser ! = null ) { this.AspNetUsersId = objUser.Id ; this.Id = objUser.UserId ; // Since the Identifiable is of type Identifiable < int > we use the UserIdas the Id value . this.Email = objUser.Email ; // Other fields . } } // Properties [ Attr ( `` asp-net-users-id '' ) ] public string AspNetUsersId { get ; set ; } [ Attr ( `` user-id '' ) ] public int UserId { get ; set ; } [ Attr ( `` email '' ) ] public string Email { get ; set ; } [ Attr ( `` user-name '' ) ] public string UserName { get ; set ; } // Other fields . } } using Microsoft.EntityFrameworkCore ; using System ; using System.Collections.Generic ; using System.Linq ; using System.Linq.Expressions ; namespace ABC.Data.Infrastructure { public abstract class EntitiesRepositoryBase < T > where T : class { # region Member Variables protected Entities m_DbContext = null ; protected DbSet < T > m_DbSet = null ; # endregion public virtual void Update ( T objEntity ) { this.m_DbSet.Attach ( objEntity ) ; this.DbContext.Entry ( objEntity ) .State = EntityState.Modified ; } } }",.NET Core 3.1 ChangePasswordAsync Inner Exception `` Can not update Identity column '' C_sharp : So I have the following code block : and in the output I have Why does it reset every 1000 ms ? I need to wait for 10 seconds and I ca n't use Thread.Sleep ( 10000 ) ; because this 3rd party library i use sleeps also and I need it to do stuff during that time . var sw = new Stopwatch ( ) ; sw.Start ( ) ; while ( sw.Elapsed.Seconds < 10 ) { System.Threading.Thread.Sleep ( 50 ) ; Console.WriteLine ( sw.Elapsed.Milliseconds.ToString ( ) + `` ms '' ) ; } sw.Stop ( ) ; 50 ms101 ms151 ms202 ms253 ms304 ms355 ms405 ms456 ms507 ms558 ms608 ms659 ms710 ms761 ms812 ms862 ms913 ms964 ms15 ms65 ms116 ms167 ms218 ms,Why is does my stopwatch keep reseting after 1 second "C_sharp : I have some code in a button click event which gets a csv string from a hidden input and writes it to the response as a CSV file.This work fine in Chrome , Firefox , ie7 , ie9 in quirks mode . However it does not work in ie8 or ie9 default . Looking at this in fiddler the csv is being written to the response but the another get request is being made immediately after and the page reloads . No file saving dialog appears . protected void btnCsvHidden_Click ( object sender , EventArgs e ) { var csv = csvString.Value ; var filename = `` Reporting '' ; Response.Clear ( ) ; Response.ClearHeaders ( ) ; Response.AddHeader ( `` Cache-Control '' , `` no-store , no-cache '' ) ; Response.AddHeader ( `` content-disposition '' , `` attachment ; filename=\ '' '' + filename + `` .csv\ '' '' ) ; Response.ContentType = `` text/csv '' ; Response.Write ( csv ) ; Response.End ( ) ; }",CSV file download ignored in ie8/9 "C_sharp : I want to redirect to a certain div of a webpage after handling some data in a controller . Is their any way to add the ' # ' to the end of the url ? Or should I handle it with javascript ? Example : = > Should redirect to /Info/id=4 # item_55 [ HttpPost ] public async Task < IActionResult > Edit ( ViewModel model ) { ... . return RedirectToAction ( `` Info '' , new { id = model.Id , `` # '' = `` item_55 '' } ) ; }",Redirect to div in page with # "C_sharp : Before you close this as a duplicate please look at the other similarly titled question , there is no answer to the problem he just marked it as answered and left.I am getting this lovely and descriptive error from the EWS manged API whenever I attempt to edit the RequiredAttendees property on an appointment.Set action is invalid for property.Looking at the exception details shows me that it is indeed the RequiredAttendees property that is causing problems but I have no idea why.The credentials I use to connect to the service are those of the meeting organizer , I have even tried impersonating the user with no luck . Scratching my head trying to figure out what went wrong here.Here are the relevant parts of the update routine that are causing problems.Request Trace : Response Trace : PropertySet props = new PropertySet ( AppointmentSchema.Start , AppointmentSchema.End , AppointmentSchema.Id , AppointmentSchema.Organizer , AppointmentSchema.Subject , AppointmentSchema.Body , AppointmentSchema.RequiredAttendees ) ; props.RequestedBodyType = BodyType.Text ; Appointment appointment = Appointment.Bind ( _service , new ItemId ( appointmentId ) , props ) ; if ( IsResource ( appointment.Organizer.Address ) & & appointment.Organizer.Address ! = resourceId ) { /* * removed for brevity , no attendee manipulation here */ } else { List < Attendee > remove = new List < Attendee > ( ) ; foreach ( var attendee in appointment.RequiredAttendees ) { if ( IsResource ( attendee.Address ) & & attendee.Address ! = resourceId ) { remove.Add ( attendee ) ; } } remove.ForEach ( a = > appointment.RequiredAttendees.Remove ( a ) ) ; if ( ! appointment.RequiredAttendees.Any ( a = > a.Address == resourceId ) ) { appointment.RequiredAttendees.Add ( resourceId ) ; } } /** removed for brevity , no attendee manipulation here*/if ( IsAvailable ( resourceId , startTime , endTime , appointmentId ) ) appointment.Update ( ConflictResolutionMode.AlwaysOverwrite , SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy ) ; else throw new RoomUnavailableException ( ) ; < Trace Tag = `` EwsRequest '' Tid= '' 14 '' Time= '' 2017-09-25 20:20:24Z '' Version= '' 15.00.0847.030 '' > < ? xml version = `` 1.0 '' encoding= '' utf-8 '' ? > < soap : Envelope xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : m= '' http : //schemas.microsoft.com/exchange/services/2006/messages '' xmlns : t= '' http : //schemas.microsoft.com/exchange/services/2006/types '' xmlns : soap= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < soap : Header > < t : RequestServerVersion Version = `` Exchange2013 '' / > < / soap : Header > < soap : Body > < m : UpdateItem ConflictResolution = `` AlwaysOverwrite '' SendMeetingInvitationsOrCancellations= '' SendToAllAndSaveCopy '' > < m : ItemChanges > < t : ItemChange > < t : ItemId Id = `` AAMkAGEwYWRjZjA3LWNlZjAtNDI2Ny05ZjQwLWUzYWZjOThhMjkzNwBGAAAAAABWdX+yf6THTpO/1LYpoG6xBwD6lEwS6u8XQbDhIlTh/X/UAAAAAAENAAD6lEwS6u8XQbDhIlTh/X/UAAAi3oSdAAA= '' ChangeKey= '' DwAAABYAAAD6lEwS6u8XQbDhIlTh/X/UAAAi3ocU '' / > < t : Updates > < t : SetItemField > < t : FieldURI FieldURI = `` calendar : RequiredAttendees '' / > < t : CalendarItem > < t : RequiredAttendees > < t : Attendee > < t : Mailbox > < t : Name > Exchange Test < /t : Name > < t : EmailAddress > etest @ supertester.com < /t : EmailAddress > < t : RoutingType > SMTP < /t : RoutingType > < t : MailboxType > Mailbox < /t : MailboxType > < /t : Mailbox > < /t : Attendee > < t : Attendee > < t : Mailbox > < t : EmailAddress > redroom @ supertester.com < /t : EmailAddress > < /t : Mailbox > < /t : Attendee > < /t : RequiredAttendees > < /t : CalendarItem > < /t : SetItemField > < /t : Updates > < /t : ItemChange > < /m : ItemChanges > < /m : UpdateItem > < /soap : Body > < /soap : Envelope > < /Trace > < Trace Tag = `` EwsResponse '' Tid= '' 14 '' Time= '' 2017-09-25 20:20:24Z '' Version= '' 15.00.0847.030 '' > < ? xml version = `` 1.0 '' encoding= '' utf-8 '' ? > < s : Envelope xmlns : s= '' http : //schemas.xmlsoap.org/soap/envelope/ '' > < s : Header > < h : ServerVersionInfo MajorVersion = `` 15 '' MinorVersion= '' 1 '' MajorBuildNumber= '' 225 '' MinorBuildNumber= '' 41 '' Version= '' V2_48 '' xmlns : h= '' http : //schemas.microsoft.com/exchange/services/2006/types '' xmlns= '' http : //schemas.microsoft.com/exchange/services/2006/types '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' / > < /s : Header > < s : Body xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : xsd= '' http : //www.w3.org/2001/XMLSchema '' > < m : UpdateItemResponse xmlns : m= '' http : //schemas.microsoft.com/exchange/services/2006/messages '' xmlns : t= '' http : //schemas.microsoft.com/exchange/services/2006/types '' > < m : ResponseMessages > < m : UpdateItemResponseMessage ResponseClass = `` Error '' > < m : MessageText > Set action is invalid for property. < /m : MessageText > < m : ResponseCode > ErrorInvalidPropertySet < /m : ResponseCode > < m : DescriptiveLinkKey > 0 < /m : DescriptiveLinkKey > < m : MessageXml > < t : FieldURI FieldURI = `` calendar : RequiredAttendees '' / > < /m : MessageXml > < m : Items / > < /m : UpdateItemResponseMessage > < /m : ResponseMessages > < /m : UpdateItemResponse > < /s : Body > < /s : Envelope > < /Trace >",EWS : 'Set action is invalid for property ' when editing RequiredAttendees "C_sharp : I am using this article to print my rdlc directly to printer but when I am trying to create Metafile object by passing stream it gives me error . ( A generic error occurred in GDI+ ) Code : It gives me error when stream size exceed or rdlc static content is more.My dataset that I use to create stream of it is : I do n't know whether static content should not affect stream size or not but it is not giving me any error if I remove some content from rdlc but when I add that it again throw error ( A generic error occurred in GDI+ ) using System ; using System.IO ; using System.Data ; using System.Text ; using System.Drawing.Imaging ; using System.Drawing.Printing ; using System.Collections.Generic ; using System.Windows.Forms ; using Microsoft.Reporting.WinForms ; public class Demo : IDisposable { private int m_currentPageIndex ; private IList < Stream > m_streams ; // Routine to provide to the report renderer , in order to // save an image for each page of the report . private Stream CreateStream ( string name , string fileNameExtension , Encoding encoding , string mimeType , bool willSeek ) { DataSet ds = new DataSet ( ) ; ds.Tables.Add ( dsData.Tables [ 0 ] .Copy ( ) ) ; using ( MemoryStream stream = new MemoryStream ( ) ) { IFormatter bf = new BinaryFormatter ( ) ; ds.RemotingFormat = SerializationFormat.Binary ; bf.Serialize ( stream , ds ) ; data = stream.ToArray ( ) ; } Stream stream1 = new MemoryStream ( data ) ; m_streams.Add ( stream1 ) ; return stream1 ; } // Export the given report as an EMF ( Enhanced Metafile ) file . private void Export ( LocalReport report ) { string deviceInfo = @ '' < DeviceInfo > < OutputFormat > EMF < /OutputFormat > < PageWidth > 8.5in < /PageWidth > < PageHeight > 11in < /PageHeight > < MarginTop > 0.25in < /MarginTop > < MarginLeft > 0.25in < /MarginLeft > < MarginRight > 0.25in < /MarginRight > < MarginBottom > 0.25in < /MarginBottom > < /DeviceInfo > '' ; Warning [ ] warnings ; m_streams = new List < Stream > ( ) ; report.Render ( `` Image '' , deviceInfo , CreateStream , out warnings ) ; foreach ( Stream stream in m_streams ) stream.Position = 0 ; } // Handler for PrintPageEvents private void PrintPage ( object sender , PrintPageEventArgs ev ) { Metafile pageImage = new Metafile ( m_streams [ m_currentPageIndex ] ) ; // Adjust rectangular area with printer margins . Rectangle adjustedRect = new Rectangle ( ev.PageBounds.Left - ( int ) ev.PageSettings.HardMarginX , ev.PageBounds.Top - ( int ) ev.PageSettings.HardMarginY , ev.PageBounds.Width , ev.PageBounds.Height ) ; // Draw a white background for the report ev.Graphics.FillRectangle ( Brushes.White , adjustedRect ) ; // Draw the report content ev.Graphics.DrawImage ( pageImage , adjustedRect ) ; // Prepare for the next page . Make sure we have n't hit the end . m_currentPageIndex++ ; ev.HasMorePages = ( m_currentPageIndex < m_streams.Count ) ; } private void Print ( ) { if ( m_streams == null || m_streams.Count == 0 ) throw new Exception ( `` Error : no stream to print . `` ) ; PrintDocument printDoc = new PrintDocument ( ) ; if ( ! printDoc.PrinterSettings.IsValid ) { throw new Exception ( `` Error : can not find the default printer . `` ) ; } else { printDoc.PrintPage += new PrintPageEventHandler ( PrintPage ) ; m_currentPageIndex = 0 ; printDoc.Print ( ) ; } } // Create a local report for Report.rdlc , load the data , // export the report to an .emf file , and print it . private void Run ( ) { LocalReport report = new LocalReport ( ) ; LocalReport report = new LocalReport ( ) ; report.ReportPath = @ '' Reports\InvoiceReportTest.rdlc '' ; report.DataSources.Add ( new ReportDataSource ( `` DataSet1 '' , dsPrintDetails ) ) ; Export ( report ) ; Print ( ) ; } public void Dispose ( ) { if ( m_streams ! = null ) { foreach ( Stream stream in m_streams ) stream.Close ( ) ; m_streams = null ; } } public static void Main ( string [ ] args ) { using ( Demo demo = new Demo ( ) ) { demo.Run ( ) ; } } }",Printing a Local Report without Preview - Stream size exceeded or A generic error occurred in GDI+ C # "C_sharp : I started writing a fluent interface and took a look at an older piece Martin Fowler wrote on fluent interfaces ( which I did n't realize he and Eric Evans coined the term ) . In the piece , Martin mentions that setters usually return an instance of the object being configured or worked on , which he says is a violation of CQS . The common convention in the curly brace world is that modifier methods are void , which I like because it follows the principle of CommandQuerySeparation . This convention does get in the way of a fluent interface , so I 'm inclined to suspend the convention for this case.So if my fluent interface does something like : Is this truly a violation of CQS ? UPDATE I broke out my sample to show logging warnings and errors as separate behaviors . myObject .useRepository ( `` Stuff '' ) .withTransactionSupport ( ) .retries ( 3 ) .logWarnings ( ) .logErrors ( ) ;",Are fluent interfaces a violation of the Command Query Separation Principle ? "C_sharp : Just looking through the LINQ tutorials on MSDN and come accross the following code : I do n't understand how an interface is being returned ? It was my understanding that an interface is simply an outline for a class , and certainly can not contain any data.I would love this to be cleared up . IEnumerable < int > numQuery1 = from num in numbers where num % 2 == 0 orderby num select num ;",LINQ returns an interface ? "C_sharp : I am looking to extract ranges from an list of integers using linq : for example I am looking to split the following list : into a list of integer ranges that will look like : ie : where the next seq is greater than 30another example : into a list of integer ranges that will look like : I have tried with for loops to find the best way possible however I don'tknow where to start trying to use a linq query to do this . List < int > numberList = new List < int > ( ) { 30 , 60 , 90 , 120 , 150 , 180 , 270 , 300 , 330 } ; { 30 , 180 } { 270 , 330 } List < int > numberList = new List < int > ( ) { 30 , 60 , 120 , 150 , 270 , 300 , 330 } ; { 30 , 60 } { 120 , 150 } { 270 , 330 }",C # Split time List into time ranges "C_sharp : I do n't understand why ' x ' below converts , but ' y ' and ' z ' do not.Does the new covariance feature simply not work on generics of generics or am I doing something wrong ? ( I 'd like to avoid using .Cast < > to make y and z work . ) var list = new List < List < int > > ( ) ; IEnumerable < List < int > > x = list ; List < IEnumerable < int > > y = list ; IEnumerable < IEnumerable < int > > z = list ;",Does C # 4 's covariance support nesting of generics ? "C_sharp : Consider the following code : But I want to be able do the following , if possible.I ca n't extend the String class with the TextType implicit operator overload , but is there any way to assign a literal string to another class ( which is handled by a method or something ) ? String is a reference type so when they developed C # they obviously had to use some way to get a string literal to the class . I just hope it 's not hardcoded into the language . public class TextType { public TextType ( String text ) { underlyingString = text ; } public static implicit operator String ( TextType text ) { return text.underlyingString ; } private String underlyingString ; } TextType text = new TextType ( `` Something '' ) ; String str = text ; // This is OK. TextType textFromStringConstant = `` SomeOtherText '' ;",Using string constants in implicit conversion "C_sharp : I need to use an external assembly that I can not modify . Suppose that I use a class from that assembly like so : Each time I call this code , it leaks unmanaged memory . ExternalWidget implements IDisposable and I have wrapped it in a using statement , but ExternalWidget does not clean up its unmanaged resources . Since I do not have access to the ExternalWidget code , I can not fix this issue the right way . Is there any other way that I can free up the memory resources used by ExternalWidget ? using ( ExternalWidget widget = new ExternalWidget ( ) ) { widget.DoSomething ( ) ; }",Handling memory leaks caused by an external assembly "C_sharp : I have an Xamarin.iOS project that uses the splat library https : //github.com/paulcbetts/splat to make System.Drawing types available in portable class library . If a parent class uses ( say ) System.Drawing.RectangleF , then by using Splat , it works just fine to subclass this class in Xamarin.IOS code . However , the same is not true of Xamarin.Mac , at least not the way I am doing it . Various types conflict with themselves -- at a minimum Point and RectangleF.I do n't know if this is related to Xamarin 's recent updates ( to Xamarin 6 ) or not.Some sample code is below , and I 'm making a full project demonstrating the problem available on Github . https : //github.com/verybadcat/splat -- macbug branch.It looks similar to the problem described here [ Splat [ 0.3.4 ] on Xamarin.iOS : issues with RectangleF and PointF.Portable Class Library project : IOS project -- this works just fine : Mac project -- does not build : How can I get the Mac project to build ? using System.Drawing ; namespace PCL { public class RectOwner { public RectangleF Rect { get ; set ; } } } using PCL ; namespace IOSApp { public class RectOwnerIOS : RectOwner { public RectOwnerIOS ( ) { this.Rect = new System.Drawing.RectangleF ( 10 , 20 , 30 , 40 ) ; } } } using PCL ; namespace MacApp { public class RectOwnerSubclass : RectOwner { public RectOwnerSubclass ( ) { this.Rect = new System.Drawing.RectangleF ( 5 , 6 , 7 , 8 ) ; // errors here : // /Users/william/Documents/splat/MacApp/RectOwnerMac.cs ( 16,16 ) : Error CS7069 : Reference to type ` System.Drawing.RectangleF ' claims it is defined assembly ` Splat , Version=1.6.2.0 , Culture=neutral , PublicKeyToken=null ' , but it could not be found ( CS7069 ) ( MacApp ) // /Users/william/Documents/splat/MacApp/RectOwnerMac.cs ( 23,23 ) : Error CS0029 : Can not implicitly convert type ` System.Drawing.RectangleF [ Xamarin.Mac , Version=0.0.0.0 , Culture=neutral , PublicKeyToken=84e04ff9cfb79065 ] ' to ` System.Drawing.RectangleF [ Splat , Version=1.6.2.0 , Culture=neutral , PublicKeyToken=null ] ' ( CS0029 ) ( MacApp ) } } }",type resolution with Splat library and Xamarin.Mac C_sharp : I just can not get the point : If '\0 ' is an empty char and if a string is a kind of array of chars why this happens ? char value = '\0 ' ; bool isEmpty = value.ToString ( ) == string.Empty ; // This returns FALSE because // '\0'.ToString ( ) returns `` \0 '' // where I expect it to be // string.empty,Why '\0'.ToString ( ) ==string.Empty returns FALSE ? "C_sharp : I 'm having some problem with finding nearest sumElement combination in list.Example : This is my list : And now I 'm dividing and I get Now I want to find closest number from listElement summs.Closest to 50031 isSo I 'm choosing 48066 , next I want to find next element but we had to skip already counted elements ( in this case I had to skip 32183 + 15883 ) So now we can use only these elements 26917,25459,22757,25236,1657 ( not counted yet ) So I 'm choosing 52376 and we doing this z ( variable ) timesWe can sum elements in this order for exmaple we ca n't addBecause this skip couple list elementsWe can sum elements in this sort , we CA N'T sort list.We ca n't do it because these numbers are lines amount from .csv file so I had to do it in this order.For now I had : It finds me the 1st element ( correctly ) but I do n't know how to loop it correctly . So I got only first element and in this example I need 3.Can anyone help me to accomplish this ? list = { 32183,15883,26917,25459,22757,25236,1657 } list.Sum = 150092 list.Sum / z z = variable ( user Input - in this example it 's 3 ) 50031 32183 + 15883 = 48066 or 32183 + 15883 + 26917 = 74983 26917 + 25459 = 52376 or 26917 + 25459 + 22757 = 75133 32183 + 15883 + 1657 for ( int i = 0 ; i < z ; i++ ) { mid = suma/z ; najbliższy = listSum.Aggregate ( ( x , y ) = > Math.Abs ( x - mid ) < Math.Abs ( y - mid ) ? x : y ) ; }",Finding nearest sumElement combination in list "C_sharp : Ok , this might be obvious for some of you but I am stumped with the behavior I 'm getting from this rather simple code : I exepcted both outputs to be the same and equal to 2 but strangely enough they are n't . Can someone explain why ? EDIT : Although the code to generate this `` weird '' behavior is admittedly contrived , it does look like a bug in the C # compiler though seemingly unimportant and the reason seems to be the inlined new as James pointed out initially . But the behavior is not limited to operations . Method calls behave exactly the same way , that is , they are called twice when they should only be called once.Consider the following repro : Sure enough , output is 2 when it should be 1 and `` sideEffect ( i ) called '' is printed out twice . public static void Main ( string [ ] args ) { int ? n = 1 ; int i = 1 ; n = ++n - -- i ; Console.WriteLine ( `` Without Nullable < int > n = { 0 } '' , n ) ; //outputs n = 2 n = 1 ; i = 1 ; n = ++n - new Nullable < int > ( -- i ) ; Console.WriteLine ( `` With Nullable < int > n = { 0 } '' , n ) ; //outputs n = 3 Console.ReadKey ( ) ; } public static void Main ( ) { int ? n = 1 ; int i = 1 ; n = n - new Nullable < int > ( sideEffect ( ref i ) ) ; Console.WriteLine ( `` With Nullable < int > n = { 0 } '' , n ) ; Console.ReadKey ( ) ; } private static int sideEffect ( ref int i ) { Console.WriteLine ( `` sideEffect ( { 0 } ) called '' , i ) ; return -- i ; }",Do n't understand pre decrement operator behavior with Nullable type "C_sharp : I have a very simple many to many table in entity framework connecting my approvals to my transactions ( shown below ) .I am trying to do a query inside the approval object to count the amount of transactions on the approval , which should be relatively easy.If I do something like this then it works super fast.However when I do this or this its exceedingly slow . I have traced the sql running on the server and it does indeed seem to be trying to load in all the transactions instead of just doing the COUNT query on the collection of Transactions.Can anyone explain to me why ? Additional : Here is how the EF model looks in regards to these two classesUPDATE : Thanks for all the responses , I believe where I was going wrong was to believe that the collections attached to the Approval object would execute as IQueryable . I 'm going to have to execute the count against the dbContext object.Thanks everyone . int count ; EntitiesContainer dbContext = new EntitiesContainer ( ) ; var aCnt = from a in dbContext.Approvals where a.id == id select a.Transactions.Count ; count = aCnt.First ( ) ; count = Transactions.Count ; count = Transactions.AsQueryable < Transaction > ( ) .Count ( ) ;",Queryable Linq Query Differences In Entity Framework "C_sharp : I 'm trying to swap the value in a unique column for two ( or more rows ) . For example : Before update : Row 1 = 1Row 2 = 2After update : Row 1 = 2Row 2 = 1I 'm using Entity Framework . These changes take place on a single commit for the same context . However , I always get a unique constrain violation when I attempt this update . Is EF not using a transaction ? For completeness , here is a snippet of my table design : I 'm trying to update the 'SortPosition ' column . The code is a bit complex to display here , but I can assure you that it is the same context with a single final commit . The error is only thrown when EF tries to write to the database.UPDATE : -Using SQL Server Profiler I can see that EF is running separate UPDATE for each affected row . Should EF not be using a single transaction for one call to SaveChanges ( ) ? -UPDATE 2 : Turns out EF is using a single transaction after all . SQL Profiler was filtering it out . [ FeeSchemeId ] UNIQUEIDENTIFIER NOT NULL , [ SortPosition ] INT NOT NULL , UNIQUE ( FeeSchemeId , SortPosition )",Can not swap unique value on two rows with EF "C_sharp : I 'm tryign to use LINQ to SQL . Everythign works great but it seems that it is not friendly to immutable objects.LINQ to SQL requires me to create a parameterless constructor for my immutable class . But I want it to be immutable , so I want to only allow people to create it with all the required parameters each time . Likewise I need to have setters on all of my members.Is there a way that I can still use LINQ 2 SQL without giving up my immutability ? Here is my code : It will throw exceptions about no setter and no default constructor with no parameters . DataContext db = new DataContext ( `` myconnectistring '' ) ; Table < MyImmutableType > myImmutableObjects = db.GetTable < MyImmutableType > ( ) ;",LINQ to SQL and immutability "C_sharp : Particularly : Is Marshal safer ? Are pointers faster ? int pixel = Marshal.ReadInt32 ( bitmapData.Scan0 , x * 4 + y * bitmapData.Stride ) ; int pixel = ( ( int* ) bitmapData.Scan0 ) [ x + y * bitmapData.Stride / 4 ] ;",How does Marshal.ReadInt32 etc . differ from unsafe context and pointers ? "C_sharp : Consider the following types : ( int , int ) → managed.struct MyStruct { public ( int , int ) Value ; } → unmanaged ! Problem : A non-generic structure MyStruct , which has a managed member ( int , int ) has been evaluated as managed type.Expected Behavior : A structure which contains a managed member , should be considered as managed , the same way the struct MyStruct { int ? Value ; } are considered as managed . It seems both types are behaving against the documentations [ 1 ] and [ 2 ] . Example 1 - unmanaged Constraint Error CS8377 The type ' ( int , int ) ' must be a non-nullable value type , along with all fields at any level of nesting , in order to use it as parameter 'T ' in the generic type or method 'Program.DoSomething ( ) 'Example 2 - pointer or sizeofUsing above structure , the behavior is the same for pointers or sizeof operator : Error CS0208 Can not take the address of , get the size of , or declare a pointer to a managed type ( ' ( int , int ) ' ) QuestionHow do a struct containing ValueTuple is considered as unmanaged and can satisfy unmanaged constraint while the ValueTuple is considered as managed ? How a struct having ValueTupple < T1 , T2 > and a struct containing Nullable < T > are treated differently ? Note 1 : IMO the issue is different from the Proposal : Unmanaged constructed types ( addressed by DavidG in comments ) , because MyStruct is not generic , on the other hand while int ? and ( int , int ) both are managed , but struct MyStruct { int ? Value ; } and struct MyStruct { ( int , int ) Value ; } evaluated differently . class Program { static void DoSomething < T > ( ) where T : unmanaged { } struct MyStruct { public ( int , int ) Value ; } static void Main ( string [ ] args ) { DoSomething < MyStruct > ( ) ; // → OK DoSomething < ( int , int ) > ( ) ; // → Shows compile-time error } } unsafe { ( int , int ) * p1 ; // → Compile-time error , MyStruct* p2 ; // → Compiles }","How is it that a struct containing ValueTuple can satisfy unmanaged constraints , but ValueTuple itself can not ?" "C_sharp : I need to call a Method of a an abstract class implementation . But the compiler always defaults to use the overloaded method from the concrete class , since the signature just requires an inherited type.Just have a look at the code : -- This is obviously a vastly simplified version of the actual code that I 'm using ; ) ^^ This results in a recursionWhat I 've tried is : ^^ does n't change anything^^ throws an error `` Can not call an abstract base member : 'AbstractClass.Do ( ModelA ) ' '' How do I call the `` public override void Do ( ModelA model ) '' method ? btw.If I change the class to thisit works . public class ModelBase { } public class ModelA : ModelBase { } public interface IInterface < in TModel > { void Do ( TModel model ) ; } public abstract class AbstractClass < TModel > : IInterface < TModel > { public abstract void Do ( TModel model ) ; } public class ConcreteClass : AbstractClass < ModelA > , IInterface < ModelBase > { public override void Do ( ModelA model ) { // I 'd like to invoke this method } public void Do ( ModelBase model ) { // how do I invoke the method above ? ? Do ( ( ModelA ) model ) ; } } ( ( IClass < ModelA > ) this ) .Do ( ( ModelA ) model ) ; base.Do ( ( ModelA ) model ) ; public class ConcreteClass : IInterface < ModelA > , IInterface < ModelBase >",Call Method overloaded from abstract class "C_sharp : I 've a C # class library with overloaded methods , and one method has a ref parameter and the other has a value parameter . I can call these methods in C # , but I ca n't get it right in C++/CLI . It 's seems compiler ca n't distinguish these two methods.Here is my C # codeand my C++/CLI codeI know in C++ I ca n't declare overload functions where the only difference in the function signature is that one takes an object and another takes reference to an object , but in C # I can.Is this a feature supported in C # but not in C++/CLI ? Is there any workaround ? namespace test { public class test { public static void foo ( int i ) { i++ ; } public static void foo ( ref int i ) { i++ ; } } } int main ( array < System : :String ^ > ^args ) { int i=0 ; test : :test : :foo ( i ) ; //error C2668 : ambiguous call to overloaded function test : :test : :foo ( % i ) ; //error C3071 : operator ' % ' can only be applied to an instance of a ref class or a value-type int % r=i ; test : :test : :foo ( r ) ; //error C2668 : ambiguous call to overloaded function Console : :WriteLine ( i ) ; return 0 ; }",How to call overloaded c # functions which the only difference is parameter passed by ref or not in c++/cli "C_sharp : I am working on a C # code analyzer and use Roslyn ( .NET Compiler API ) .And I would like to check , that a particular type is inherited from a base class type.For example , let 's assume we have a hierarchy of custom classes : TypeA - > TypeB - > TypeC - > TypeDWhere TypeA is parent class for TypeB , TypeB is parent for TypeC and TypeC is parent for TypeD.I created a method : symbol contains the type , that should be checked . But this approach does not work . Code does not get the parent type for the symbol.symbol.BaseType returns the same class type twice and then ( on the next iteration ) I get symbol.BaseType equal to null.expectedParentTypeName contains fully qualified type name : for example some.namespace.blablabla.TypeCHow can I solve this task ? UpdateAs I noted above , let 's assume we have a hierarchy : TypeA - > TypeB - > TypeC - > TypeDUpon analysis I get a property with type TypeD and I want to check , that it is inherited from TypeBUpdate # 2TypeA - > TypeB - > TypeC - > TypeD types are not existing yet when I write my code analyser . So , I ca n't use typeof and other stuff for these types.They will exist only in context the analyzer will work in.My analyzer gets a part of the source code , recognizes it as a type name and I want to check , that this recognized type name is inherited from another custom type , imported from a custom nuget package.All I have - I have source code to analyze and names of those custom types in class , property , field , etc declarations.Update # 3For the following code : propertyTypeInfo and classTypeInfo do not contain any information inside . bool InheritsFrom ( ITypeSymbol symbol , string expectedParentTypeName ) { while ( true ) { if ( symbol.ToString ( ) .Equals ( expectedParentTypeName ) ) { return true ; } if ( symbol.BaseType ! = null ) { symbol = symbol.BaseType ; continue ; } break ; } return false ; } SyntaxNodeAnalysisContext context ; // is already initialized PropertyDeclarationSyntax propertyDeclaration = ( PropertyDeclarationSyntax ) context.Node ; ClassDeclarationSyntax classDeclaration = ( ClassDeclarationSyntax ) propertyDeclaration.Parent ; TypeInfo propertyTypeInfo = context.SemanticModel.GetTypeInfo ( propertyDeclaration ) ; TypeInfo classTypeInfo = context.SemanticModel.GetTypeInfo ( classDeclaration ) ;",How to get base type for the particular type "C_sharp : So I got the Address class : And I want to get its readable version to , lets say , show in a grid column.Whats the best and concise way to implement this ? toString method inside class Address ( I personally do n't like this approach , as 'toString ' is not directly related to an Address ) class ReadableAddressFormatter ReadableAddressFormatter ( Address addressToFormat ) public String getFormatted ( ) Previous class but getFormmated would be static , receiving the Address instance and returning the stringOther ? Suggestions please.I 'm looking for a good design , focusing also in Clean Code , Decoupling and Maintainability . class Address { private String streetAddress ; private int number ; private String postalCode ; private City city ; private State state ; private Country country ; }",OO Design Advice - toString "C_sharp : In VS2012 C # text editor , when Enter is pressed inside /* */ comments , new line is added , beginning with * . Is it possible to disable this behaviour and get just an empty new line ? From Visual Studio About box , Installed products : Microsoft Visual Studio Professional 2012Microsoft Team Explorer for Visual Studio 2012Microsoft Visual Basic 2012Microsoft Visual C # 2012Microsoft Visual C++ 2012Microsoft Visual F # 2012Microsoft® Visual Studio® 2012 Code Analysis Spell CheckerNuGet Package ManagerPreEmptive Analytics Visualizer",How to prevent asterisk with Enter is pressed inside C # /* */ comments "C_sharp : I am looking for a format to use with string.Format that would print the following like { 0 : N6 } results in { 0:0. # # # # # # } results in { 0 : # .0 } results inI can not workout a format that will get me to what I need . Will I need to define my own format provider ? double d = 123456.123456D ; double d2 = 123456D ; 123,456.123456123,456 123,456.123456123,456.000000 123456.123456123456 123,456123,456",Format double - thousands separator with decimal but no trailing zeros "C_sharp : We have a controller that derives from ControllerBase with an action like this : We also have a unit test like this : But ControllerBase.Problem ( ) throws a Null Reference Exception . This is a method from the Core MVC framework , so I do n't realy know why it is throwing the error . I think it may be because HttpContext is null , but I 'm not sure.Is there a standardized way to test a test case where the controller should call Problem ( ) ? Any help is appreciated.If the answer involves mocking : we use Moq and AutoFixtrue . public async Task < ActionResult > Get ( int id ) { try { // Logic return Ok ( someReturnValue ) ; } catch { return Problem ( ) ; } } [ TestMethod ] public async Task GetCallsProblemOnInvalidId ( ) { var result = sut.Get ( someInvalidId ) ; }",How to unit test whether a Core MVC controller action calls ControllerBase.Problem ( ) "C_sharp : I have been writing .NET applications and have been impressed with the error handling included in the framework.When catching an error that has been throw by the processes or somewhere in the code I like to include the message ( ex.Message , which is usually pretty general ) but also the stacktrace ( ex.stacktrace ) which helps to trace the problem back to a specific spot.For a simple example let 's say for instance that we are recording numbers to a log in a method : Is there any way to see the method called ( in this case ExampleMethod ) with the specific number that was passed that potentially crashed the method call ? I believe you could log this perhaps in the catch block but I am interested essentially in catching the method call and parameters that caused the system to throw the exception.Any ideas ? public void ExampleMethod ( int number ) { try { int num = number ... open connection to file ... write number to file } catch ( Exception ex ) { ... . deal with exception ( ex.message , ex.stacktrace etc ... ) } finally { ... close file connection } }",.NET error handling "C_sharp : Hi guys i want to stream a video from my Azure blob via a ASP.NET MVC web application to users on desktop browsers and of course mobile browsers . What i have build so far is a ASP.NET MVC Application that serves the website and a WebApi service that would PushStreamContent . This works awesome on Chrome and Edge on the desktop . But wen i try to open it on a mobile device Chrome , Safari , Firefox it just wont play.My Code so far : The view on the MVC projectThe WebApiHelper on webAPI < video id= '' vPlayer '' class= '' video-js '' autoplay controls playsinline preload= '' auto '' data-setup= ' { `` fluid '' : true } 'poster= '' @ ImgManager.GetVideoImgUrl ( Model.ThumbnailUrl ) '' > < source src= '' //xyz.nl/api/Videos/Get ? filename=340a85a3-ccea-4a2a-bab6-74def07e416c.webm & type=video % 2Fwebm '' type= '' video/webm '' > < source src= '' //xyz.nl/api/Videos/Get ? filename=340a85a3-ccea-4a2a-bab6-74def07e416c.mp4 & type=video % 2Fmp4 '' type= '' video/mp4 '' > public HttpResponseMessage Get ( string filename , string type ) { var video = new VideoStream ( filename ) ; var response = Request.CreateResponse ( ) ; response.Content = new PushStreamContent ( video.WriteToStream , new MediaTypeHeaderValue ( type ) ) ; return response ; } public class VideoStream { private readonly string _filename ; public VideoStream ( string fileName ) { _filename = fileName ; } public async Task WriteToStream ( Stream outputStream , HttpContent content , TransportContext context ) { try { var storage = new AzureMainStorage ( `` avideo '' ) ; byte [ ] file = await storage.GetFileAsync ( _filename ) ; var buffer = new byte [ 65536 ] ; using ( var video = new MemoryStream ( file ) ) { var length = ( int ) video.Length ; var bytesRead = 1 ; while ( length > 0 & & bytesRead > 0 ) { bytesRead = video.Read ( buffer , 0 , Math.Min ( length , buffer.Length ) ) ; await outputStream.WriteAsync ( buffer , 0 , bytesRead ) ; length -= bytesRead ; } } } catch ( HttpException ex ) { Utilities.LogErrorToDb ( ex ) ; return ; } finally { outputStream.Close ( ) ; } } } }",MVC Video streaming to mobile web browsers "C_sharp : I 'm still learning about REST and , in my test , came up with this scenario I do n't know how to deal with.I have an existing sample WCF service which uses Linq-to-Sql . Its a tremendously simple database with a single table called `` Tasks '' which has four fields : Id , Description , IsCompleted , and EnteredDate . ( I mentioned this because I have no data contracts defined in the service itself , it all comes from the Context created by Linq . ) Getting data was trivial to convert to REST ... as was deleting data . However , inserting new records does n't seem as easy.My RPC-style contract operation looks like this : The Id , IsCompleted , and EnteredDate are not needed as the service implementation looks like this : The Id is an Identity and therefore handled by the database.My first thought was to decorate the Operation contract like this : But I do n't really know how to get this to work . When I try using Fiddler to add this it returns a result of 411 ( Length Required ) .What would be the proper way to do this ? Will I have to re-write the implementation to accept a whole XML document representing the new record ? [ OperationContract ] void AddTask ( string description ) ; public void AddTask ( string description ) { TaskListLinqDataContext db = new TaskListLinqDataContext ( ) ; Task task = new Task ( ) { Description = description , IsCompleted = false , EntryDate = DateTime.Now } ; db.Tasks.InsertOnSubmit ( task ) ; db.SubmitChanges ( ) ; } [ WebInvoke ( Method= '' PUT '' , UriTemplate= '' tasks/ { description } '' ) ] [ OperationContract ] void AddTask ( string description ) ;",How would I add new data via a REST service opposed to RPC style service ? "C_sharp : I 've read a lot of articles about asynchronnous programming , but I 'm not sure in one thing . I have 3rd party winrt library , written in C++ and I want to wrapp it . So now I have : According Stephen Cleary and Stephen Toub blogs , it is not good solution . But when I use the method synchronously , my UI will not be responsive and will be blocked.Is it better to expose service method synchronously and in UI use Task.Run ? public Task LoginAsync ( ) { return Task.Run ( winrtLibrary.Login ( ) ; ) }",Using Task.Run for synchronous method in service C_sharp : My colleagues tell me that table based formatting of code is bad and it is no readable and I should follow conventions . What 's that bad about table based formatting ? Why is it banned ? I 'm asking because for me it 's much more readable.Examples ( not real code ) : versusWhy I think the second one is better : I do n't need to parse the text by eyes - I see the structure of the commands at one glance.I see immediatelly that there are some ifs and assignmentsthat the enum used in conditions is ResultType and nothing morethat only the last condition is composed from two expressionsUpdate : this is not a real code . I just wanted to show some example . Consider it like it 's an old code that somebody wrote some time ago and you need to read it . Why the first formatting is preferred over the second ? if ( res == ResultType.Failure ) something = ProcessFailure ( .. ) ; if ( res == ResultType.ScheduledAndMonitored ) something = DoSomething ( ... ) & & DoSomething3 ( .. ) ; if ( res == ResultType.MoreInfoAvailable ) info = GetInfo ( .. ) ; if ( res == ResultType.OK & & someCondition ) something = DoSomething2 ( .. ) ; ... . continued if ( res == ResultType.Failure ) something = ProcessFailure ( .. ) ; if ( res == ResultType.ScheduledAndMonitored ) something = DoSomething ( ... ) & & DoSomething3 ( .. ) ; if ( res == ResultType.MoreInfoAvailable ) info = GetInfo ( .. ) ; if ( res == ResultType.OK & & someCondition ) something = DoSomething2 ( .. ) ; ... . continued,What 's the reason why table layout in code is considered bad ? "C_sharp : Have a look at the following code from here.It 's about preserving circular references in a datacontract ( object model , object graph , domain model ) when serializing in wcf.Is n't CreateDataContractSerializer generating an endless loop ( stackoverflow ) - and therefore also the preceding CreateSerializer method ? Now maybe these methods are not in use ? What am I missing here ? class ReferencePreservingDataContractSerializerOperationBehavior : DataContractSerializerOperationBehavior { public ReferencePreservingDataContractSerializerOperationBehavior ( OperationDescription operationDescription ) : base ( operationDescription ) { } public override XmlObjectSerializer CreateSerializer ( Type type , string name , string ns , IList < Type > knownTypes ) { return CreateDataContractSerializer ( type , name , ns , knownTypes ) ; } private static XmlObjectSerializer CreateDataContractSerializer ( Type type , string name , string ns , IList < Type > knownTypes ) { return CreateDataContractSerializer ( type , name , ns , knownTypes ) ; } public override XmlObjectSerializer CreateSerializer ( Type type , XmlDictionaryString name , XmlDictionaryString ns , IList < Type > knownTypes ) { return new DataContractSerializer ( type , name , ns , knownTypes , 0x7FFF /*maxItemsInObjectGraph*/ , false/*ignoreExtensionDataObject*/ , true/*preserveObjectReferences*/ , null/*dataContractSurrogate*/ ) ; } } private static XmlObjectSerializer CreateDataContractSerializer ( Type type , string name , string ns , IList < Type > knownTypes ) { return CreateDataContractSerializer ( type , name , ns , knownTypes ) ; }",Endless loop in a code sample on serialization "C_sharp : I thought that F # was meant to be faster than C # , I made a probably bad benchmark tool and C # got 16239ms while F # did way worse at 49583ms . Could somebody explain why this is ? I 'm considering leaving F # and going back to C # . Is it possible to get the same result in F # with way faster code ? Here is the code I used , I made it as equal as I possibly could.F # ( 49583ms ) C # ( 16239ms ) open Systemopen System.Diagnosticslet stopwatch = new Stopwatch ( ) stopwatch.Start ( ) let mutable isPrime = truefor i in 2 .. 100000 do for j in 2 .. i do if i < > j & & i % j = 0 then isPrime < - false if isPrime then printfn `` % i '' i isPrime < - truestopwatch.Stop ( ) printfn `` Elapsed time : % ims '' stopwatch.ElapsedMillisecondsConsole.ReadKey ( ) | > ignore using System ; using System.Diagnostics ; namespace ConsoleApp1 { class Program { static void Main ( string [ ] args ) { Stopwatch stopwatch = new Stopwatch ( ) ; stopwatch.Start ( ) ; bool isPrime = true ; for ( int i = 2 ; i < = 100000 ; i++ ) { for ( int j = 2 ; j < = i ; j++ ) { if ( i ! = j & & i % j == 0 ) { isPrime = false ; break ; } } if ( isPrime ) { Console.WriteLine ( i ) ; } isPrime = true ; } stopwatch.Stop ( ) ; Console.WriteLine ( `` Elapsed time : `` + stopwatch.ElapsedMilliseconds + `` ms '' ) ; Console.ReadKey ( ) ; } } }",Why is F # so much slower than C # ? ( prime number benchmark ) "C_sharp : I thought that in .NET strings were compared alphabetically and that they were compared from left to right . I 'd expect this ( or the both with minus at the beginning first ) : But the result is : It seems to be a mixture , either the minus sign is ignored or multiple characters are compared even if the first character was already different . Edit : I 've now tested OrdinalIgnoreCase and i get the expected order : But even if i use InvariantCultureIgnoreCase i get the unexpected order . string [ ] strings = { `` -1 '' , `` 1 '' , `` 1Foo '' , `` -1Foo '' } ; Array.Sort ( strings ) ; Console.WriteLine ( string.Join ( `` , '' , strings ) ) ; 1,1Foo , -1 , -1Foo 1 , -1,1Foo , -1Foo Array.Sort ( strings , StringComparer.OrdinalIgnoreCase ) ;",Alphabetical order does not compare from left to right ? C_sharp : Possible Duplicate : What do two question marks together mean in C # ? I 'm trying to understand what this statment does : what does `` ? ? '' mean ? is this som type if if-statment ? string cookieKey = `` SearchDisplayType '' + key ? ? `` `` ;,What does ' ? ? ' mean in C # ? "C_sharp : I am trying to automate fetching of AD reports using the Graph REST API from a .net application in C # .I have created a Service Principal ( using App Registrations ) in the new Azure Portal . This service principal has all the required information configured for OAuth 2.0 : App ID or Client Id ( auto generated ) Key or Client SecretTenant ID ( from the Azure Directory 's Directory ID ) The service principal also has permissions set appropriately for `` Microsoft Graph '' as `` Read Directory Data '' . I am able to fetch the Token using the REST API from .net application but when I am trying to use this token in my code I am getting the error : `` Unable to check Directory Read access for appId '' .My code to make the REST API call using the token is ( I have changed the GUIDs for Tenant ID etc . ) : The error I am getting is : I have checked that the credentials are not cached anywhere as indicated by some blogs . I have even run the code from a blank VM and got the same error . Any pointers to resolve this error or what could be causing this.UPDATE - 4-28-2017I got this resolved . I know the exact steps that resolve this for me . But I do n't know the underlying concept . If anyone can explain to me that and how to do this via PowerShell or GUI ( even in 2 lines ) I will accept that as an answer . The steps I take are : Create the Service Principal/App inside App RegistrationsAdd Permission for Windows Azure AD for `` Sing in and read user profile '' and `` Read directory data '' . I also added permissions for Microsoft Graph for `` Read directory data '' since I also need to make some calls to that.Add Reply URL for Postman i.e . `` https : //www.getpostman.com/oauth2/callback '' .Use Postman 's OAuth 2.0 helper to fetch the token . During the process , it provides the below screen . After I click Accept it generates the token.Now I am able to make requests using C # code.What I have tried : I have tried using `` Grant Permissions '' on the `` Required Permissions '' blade inside App Registrations , but that did not work and resulted in the same error.QUESTION : I want to understand what exactly the below dialog is doing and how can I do this via GUI or PowerShell . var client2 = new RestClient ( `` https : //graph.windows.net/a0a00aa0-aaaa-0000-0000-00000e0000aa/reports ? api-version=beta '' ) ; var request2 = new RestRequest ( Method.GET ) ; request2.AddHeader ( `` cache-control '' , `` no-cache '' ) ; request2.AddHeader ( `` authorization '' , `` Bearer `` + token ) ; request2.AddHeader ( `` content-type '' , `` application/json '' ) ; IRestResponse response2 = client2.Execute ( request2 ) ; Console.WriteLine ( response2.Content ) ; { `` error '' : { `` code '' : '' Unable to check Directory Read access for appId : 00000aa-aaaa-0a0a-0000-000000000000 '' , '' message '' : '' message : Unable to check Directory Read access for appId : 00000aa-aaaa-0a0a-0000-000000000000\n client-request-id:00aa0a0a-48bf-4bf8-ae40-a2976a3c6910 timestamp:2017-04-28 01:38:52Z '' } }",Getting error `` Unable to check Directory Read access for appId '' when trying to access Graph REST API programmatically from a .net application "C_sharp : I was reading this post here on micro ORM used on SO.The author showed this stack-trace : Then said : In the trace above you can see that 'EntityRef ' is baking a method , which is not a problem , unless it is happening 100s of times a second.Could someone explain the stack-trace in relation to what he meant by `` baking a method '' and why it would be a performance problem ? System.Reflection.Emit.DynamicMethod.CreateDelegateSystem.Data.Linq.SqlClient.ObjectReaderCompiler.CompileSystem.Data.Linq.SqlClient.SqlProvider.GetReaderFactorySystem.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.CompileSystem.Data.Linq.CommonDataServices+DeferredSourceFactory ` 1.ExecuteKeyQuerySystem.Data.Linq.CommonDataServices+DeferredSourceFactory ` 1.ExecuteSystem.Linq.Enumerable.SingleOrDefaultSystem.Data.Linq.EntityRef ` 1.get_Entity",What does baking a method means ? "C_sharp : Let 's say I wanted to just quickly make the following method run asynchronously : What would be the difference in how the following two code samples are executed/scheduled ? Compared to : I understand that the Task.Yield ( ) call will ensure that the thread immediately returns to the caller , and that Task.Run ( ) will definitely schedule the code to run somewhere on the ThreadPool , but do both of these methods effectively make the method async ? Let 's assume for this question that we are on the default SynchronizationContext . ResultType SynchronousCode ( ParamType x ) { return SomeLongRunningWebRequest ( x ) ; } async Task < ResultType > AsynchronousCode ( ParamType x ) { return await Task.Run ( ( ) = > SomeLongRunningWebRequest ( x ) ) ; } async Task < ResultType > AsynchronousCode ( ParamType x ) { await Task.Yield ( ) ; return SomeLongRunningWebRequest ( x ) ; }",Task.Yield ( ) ; SyncAction ( ) ; vs Task.Run ( ( ) = > SyncAction ( ) ) ; "C_sharp : I have a WCF service that will be using basic authentication and would like to be able identify `` who '' is trying to use the service . I know that the HttpContext.Current is NULL and in the WCF service , but do not know what the alternative is to get the username . For the website , I can use : How do I get userName in the WCF Service ? userName = HttpContext.Current.Request.ServerVariables [ `` LOGON_USER '' ] ;",How do you identify authentcated user in WCF ? "C_sharp : I am trying to determine if one path is a child of another path.I already tried with : like in How to check if one path is a child of another path ? postBut it does n't work . For example if I write `` C : \files '' and `` C : \files baaa '' the code thinks that the `` C : \files baaa '' is a child of `` C : \files '' , when it is n't , it is only of C : .The problem is really heavy when I try with long paths , with an amount of childs.I also tried with `` if contains \ '' ... but still not really working in all the chasesWhat can I do ? Thanks ! if ( Path.GetFullPath ( A ) .StartsWith ( Path.GetFullPath ( B ) ) || Path.GetFullPath ( B ) .StartsWith ( Path.GetFullPath ( A ) ) ) { /* ... do your magic ... */ }",How to check effectively if one path is a child of another path in C # ? "C_sharp : Background : We have a project with client side ( Javascript ) and server side ( C # ) . There is a calculation logic need to run in both sides , so it is written in both Javascript and C # . We have many unit tests for the C # version classes . Our goal is to share the unit tests for both C # and Javascript implementation.Current situation : We are able to run the Javascript code in an embeded JS engine ( Microsoft ClearScript ) . The code looks like this : However , writing such classes takes a lot of effort . We are looking for a way to create such classes dynamically at runtime.For exmample , we have a C # class ( also has it JS version in a JS fle ) : We want to create a dynamic class having the same methods but calling the Script engine to call the related JS code.Is it possible to do it ? public decimal Calulate ( decimal x , decimal y ) { string script = @ '' var calc = new Com.Example.FormCalculater ( ) ; var result = calc.Calculate ( { 0 } , { 1 } ) ; '' ; this.ScriptEngine.Evaluate ( string.Format ( script , x , y ) ) ; var result = this.ScriptEngine.Evaluate ( `` result '' ) ; return Convert.ToDecimal ( result ) ; } public class Calculator { public decimal Add ( decimal x , decimal y ) { ... } public decimal Substract ( decimal x , decimal y ) { ... } public decimal Multiply ( decimal x , decimal y ) { ... } public decimal Divide ( decimal x , decimal y ) { ... } }",How to create a C # class ( according to an existing class ) dynamically at runtime C_sharp : The yield keyword documentation says : The yield keyword signals to the compiler that the method in which it appears is an iterator block.I have encountered code using the yield keyword outside any iterator block . Should this be considered as a programing mistake or is it just fine ? EDIT Sorry forgot to post my code : Thanks . int yield = previousVal/actualVal ; return yield ; // Should this be allowed ! ! ! ? ? ?,Is `` yield keyword '' useful outside of an iterator block ? "C_sharp : I 've read this thread which claims with reference to msdn with idea that async/await does n't create new threads . Please look at following code : As result of this code I got different ThreadId . Why the same thread gets different ThreadId ? static class Program { static void Main ( string [ ] args ) { var task = SlowThreadAsync ( ) ; for ( int i = 0 ; i < 5 ; i++ ) { Console.WriteLine ( i * i ) ; } Console.WriteLine ( `` Slow thread result { 0 } '' , task.Result ) ; Console.WriteLine ( `` Main finished on thread { 0 } '' , Thread.CurrentThread.ManagedThreadId ) ; Console.ReadKey ( ) ; } static async Task < int > SlowThreadAsync ( ) { Console.WriteLine ( `` SlowThreadAsync started on thread { 0 } '' , Thread.CurrentThread.ManagedThreadId ) ; await Task.Delay ( 2000 ) ; Console.WriteLine ( `` SlowThreadAsync completed on thread { 0 } '' , Thread.CurrentThread.ManagedThreadId ) ; return 3443 ; } }",If async/await does n't create new thread then explain this code "C_sharp : I have found plenty of articles that pointed out to me that BundleConfig.cs is no longer a thing with MVC . Instead I am suppose to use third party tools to achieve this . At least , this is my understanding . I have spent a lot of time researching and trying to understand , but ca n't find anywhere any clear instructions on how to achieve this with bundlingconfig.json . Some of the articles by microsoft , such as this one https : //docs.microsoft.com/en-us/aspnet/core/client-side/bundling-and-minification ? view=aspnetcore-2.1 & tabs=visual-studio % 2Caspnetcore2x talk about how the default template uses it , but it does n't tell me how exactly they achieve it . Also , when I tried to create a new template with core 2.1 project , it was n't there . So I 'm quite confused as to how to get my bundleconfig.json to work.Now , I 'm a fan of starting from scratch and building things up so I get a good understanding of how they work so I can fix them if things go wrong in future . As such , I created a brand new project with nothing in it and added my controllers , views , everything I need to get a basic website . However , simply just by adding the config file on its own , it does nothing . I was hoping it was part of the mvc framework and it would pick it up and know what to do with it . But I guess that is not the case and I ca n't find anywhere instructions on what I need to add in addition to the config file for this to work.Could anyone point me in the right direction ? and then in my cshtml page I added [ { `` outputFileName '' : `` wwwroot/css/Test.css '' , `` inputFiles '' : [ `` wwwroot/css/Global.css '' ] , `` minify '' : { `` enabled '' : true , `` renameLocals '' : true } } ] < link rel= '' stylesheet '' href= '' ~/css/Test.css '' / >",Bundling & Minification with MVC Core "C_sharp : I have an ItemsControl containing dynamically changable number of DataGrids : The template for the `` SingleParameterColumn '' is defined like this : There is always one InputParameterColumn and at least one SingleParameterColumn . The InputParameterColumn has a fixed header name , whereas the header of the SingleParameterColumn can be arbitrarily long . Since I do not want to have very wide columns I have defined the MaxWidth of the TextBlock in the header template to 60 , which causes the header to be higher if the name of a column is very long . This causes the columns to have different heights depending on the length of the header name . Is there any way I can find out how tall is the tallest header in my ItemsControl and then set the same height for all the other headers so that my columns then all have the same size ? < ItemsControl ItemsSource= '' { Binding Table.Columns } '' > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < StackPanel Orientation= '' Horizontal '' VerticalAlignment= '' Stretch '' / > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel > < ItemsControl.ItemTemplateSelector > < local : ColumnTemplateSelector InputParameterColumnTemplate= '' { StaticResource InputParamterColumn } '' SingleParameterColumnTemplate= '' { StaticResource SingleParameterColumn } '' / > < /ItemsControl.ItemTemplateSelector > < /ItemsControl > < DataTemplate x : Key= '' SingleParameterColumn '' > < DataGrid AutoGenerateColumns= '' False '' ItemsSource= '' { Binding Cells } '' RowHeight= '' 25 '' RowHeaderWidth= '' 0 '' > < DataGrid.Columns > < DataGridTemplateColumn > < DataGridTemplateColumn.HeaderTemplate > < DataTemplate > < StackPanel Orientation= '' Horizontal '' > < TextBlock Text= '' { Binding Name } '' TextWrapping= '' Wrap '' TextAlignment= '' Center '' MaxWidth= '' 60 '' > < /TextBlock > < Button > < Image ... / > < /Button > < /StackPanel > < /DataTemplate > < /DataGridTemplateColumn.HeaderTemplate > < DataGridTemplateColumn.CellTemplateSelector > ... . < /DataGridTemplateColumn.CellTemplateSelector > < /DataGridTemplateColumn > < /DataGrid.Columns > < /DataGrid > < /DataTemplate >",Applying The Same Height For All DataGridColumns when MaxWidth of the Header Is Set C_sharp : I have a list of custom type . And the custom type isI have to sort the list in such a way item with less number of stores and more number of order lines should be at top.Thanks in advance . public class PossibleMatch { public PossibleMatch ( ) { StoreIds = new List < long > ( ) ; OrderLineIds = new List < long > ( ) ; } public IList < long > StoreIds { get ; set ; } public IList < long > OrderLineIds { get ; set ; } },Sorting list in C # C_sharp : Here is an example : So if I loose the task reference and keep the func reference is GC going to collect the task and make the func throw null reference exception ? var task = Task.Run ( ) ; var func = ( ) = > task.Result ;,.NET Do lambdas prevent garbage collection of external references used in them ? "C_sharp : The situation : I am trying to make an application ( c # -asp.net ) to manipulate user 's on an exchange server . The application will be on a different server than the exchange 's one . So , to manipulate the data , I am using an `` Exchange remote management session '' created with c # . Exchange remote management session give access to simple powershell command like `` New-Mailbox '' and `` Set-User '' - This is good for simple task , but in my case , I have to do more complexe operations that will need some specific command that is not included in the default command . To access this command , I have to use some specific module like `` ActiveDirectory '' . It is simple ? Only use `` Import-Module '' ! Not really , like I said , the `` Exchange remote management session '' is very limited with the command , and `` Import-Module '' is not allowed ... So what we can do ? I read a lot about my problem , and the most `` simple '' ( That I understand the theory ) solution is something like : Start with a generic PS session , import the AD module , then connect to an Exchange management session and do an Import-PSSession and use implicit remoting for the Exchange management stuff.Given that I am pretty new to manipulate the Powershell with c # , I have no idea how to use this awesome solution in my code . So I am asking your help.Here 's my current code : This code work great for simple task ( like `` New-Mailbox '' ) ! But how can I create a `` generic PS session '' and then use this session in the `` Exchange remote management session '' ? // Prepare the credentials.string runasUsername = @ '' MarioKart 8 '' ; string runasPassword = `` MarioKart '' ; SecureString ssRunasPassword = new SecureString ( ) ; foreach ( char x in runasPassword ) ssRunasPassword.AppendChar ( x ) ; PSCredential credentials =new PSCredential ( runasUsername , ssRunasPassword ) ; // Prepare the connectionvar connInfo = new WSManConnectionInfo ( new Uri ( `` MarioKart8Server '' ) , `` http : //schemas.microsoft.com/powershell/Microsoft.Exchange '' , credentials ) ; connInfo.AuthenticationMechanism = AuthenticationMechanism.Basic ; connInfo.SkipCACheck = true ; connInfo.SkipCNCheck = true ; // Create the runspace where the command will be executedvar runspace = RunspaceFactory.CreateRunspace ( connInfo ) ; // create the PowerShell commandvar command = new Command ( `` New-Mailbox '' ) ; ... .// Add the command to the runspace 's pipelinerunspace.Open ( ) ; var pipeline = runspace.CreatePipeline ( ) ; pipeline.Commands.Add ( command ) ; // Execute the commandvar results = pipeline.Invoke ( ) ; if ( results.Count > 0 ) System.Diagnostics.Debug.WriteLine ( `` SUCCESS '' ) ; else System.Diagnostics.Debug.WriteLine ( `` FAIL '' ) ;",Powershell generic session and import this session in Exchange remote management session "C_sharp : The short version - Is there an easy way to take a variable of type object containing an instance of an unknown array ( UInt16 [ ] , string [ ] , etc . ) and treat it as an array , say call String.Join ( `` , '' , obj ) to produce a comma delimited string ? Trivial ? I thought so too.Consider the following : obj might contain different instances - an array for example , say UInt16 [ ] , string [ ] , etc.I want to treat obj as the type that it is , namely - perform a cast to an unknown type . After I accomplish that , I will be able to continue normally , namely : The above code , of course , does not work ( objType unknown ) .Neither does this : Just to be clear - I am not trying to convert the object to an array ( it 's already an instance of an array ) , just be able to treat it as one.Thank you . object obj = properties.Current.Value ; Type objType = obj.GetType ( ) ; string output = String.Join ( `` , '' , ( objType ) obj ) ; object [ ] objArr = ( object [ ] ) obj ; ( Unable to cast exception )",explicit casting of object containing array - to an array "C_sharp : I 'm using MonoDevelop 2.4.2 for OS X ( the version that comes with Unity 3.4.1 ) , and was wondering if there was some way to inherit comments from the base class or property.Example : This question seems somewhat similar toComment Inheritance for C # ( actually any language ) , although I am mostly concerned with how they behave in the editor at this point , and this is specific to MonoDevelop.Some of the solutions in that question referred to < inheritdoc / > , which does n't appear to be valid in MonoDevelop ( or I 'm misusing it ) , and Ghostdoc is for Visual Studio.It seems like the only solution would be to duplicate the property comments in the inherited class . Are there any alternatives ? public class Foo { /// < summary > /// The describes the ABC property /// < /summary > public virtual int ABC { get { return _abc ; } set { _abc = value ; } } protected int _abc ; /// < summary > /// The describes the XYZ property /// < /summary > public virtual int XYZ { get { return _xyz ; } set { _xyz = value ; } } protected int _xyz ; } public class Bar : Foo { public override int ABC { set { // DO SOMETHING base.ABC = value ; } } } Bar bar = new Bar ( ) ; // In MonoDevelop 2.4.2 ( OS X ) , the ABC property does n't show the comments// in the autocomplete popup or when you hover the mouse over the property.int abc = bar.ABC ; // ... but they do show up for XYZ , because it does n't overrideint xyz = bar.XYZ ;",XML Comments for Override Properties "C_sharp : I 'm currently using Selenium WebDriver 2.35 and hit a roadblock when it comes to taking a screenshot . I wrote up a small function that takes in an IWebElement and will return a screenshot of the specific element . The element I am trying to screenshot is actually an image pulled from a sprite . This element is tricky though , because upon mouseover/hover the image changes from gray to its true color ( by moving to a different part of sprite ) . I am able to get a proper screenshot of the image via this function , but can not get it to recognize the mouse interactions with ITakesScreenshot . I can visually see in the browser that the image is hovered over , but the screenshot can not . Any thoughts ? public static Bitmap GetImage ( IWebElement element ) { RemoteWebDriver driver = BrowserManager.GetInstance ( ) .GetDriver ( ) ; Actions action = new Actions ( driver ) ; //take screenshot of page action.MoveToElement ( element ) .Build ( ) .Perform ( ) ; Byte [ ] ba= ( ( ITakesScreenshot ) driver ) .GetScreenshot ( ) .AsByteArray ; Bitmap ss = new Bitmap ( new MemoryStream ( ba ) ) ; //ss.Save ( `` c : \\tmp\\ss.png '' , ImageFormat.Png ) ; Rectangle crop = new Rectangle ( element.Location.X , element.Location.Y , element.Size.Width , element.Size.Height ) ; //create a new image by cropping the original screenshot Bitmap image = ss.Clone ( crop , ss.PixelFormat ) ; return image ; }",Mouse interactions not showing in webdriver screenshots "C_sharp : Is there any way to pull out the properties , the operator and matching value from an Expression < Func < T > , bool > ? Given the following example : I need to be able to get out something like the following : I 've already written something that can pull out the property name of an Expression , but I can not seem to find out where the value and operator are held , although it 's quite clearly visible in the Expression 's DebugView property . var customers = GetCustomers ( ) ; var customerQuery = customers.Where ( x= > x.CustomerID == 1 & & x.CustomerName == `` Bob '' ) ; // The query is for illustration only Property : CustomerIDOperator : EqualsValue : 1Property : CustomerNameOperator : EqualsValue : Bob","How do you get the properties , operators and values from an Expression < Func < T , bool > > predicate ?" "C_sharp : I have an external method that receives some parameters , allocates memory and returns a pointer.I 'm well aware that it is bad practice to allocate unmanaged memory in a managed application but in this case I have no choice as the dll is 3rd party.There is an equivalent function that releases the memory and I do know what is the size of the allocated array.How do I pin the returned pointer so the GC does not move it ( without going unsafe ) ? 'fixed ' wo n't do it as this pointer is widely used throughout the class ? Is there a better methodology for this p/Invoke ? [ DllImport ( `` some.dll '' , CallingConvention = CvInvoke.CvCallingConvention ) ] public static extern IntPtr cvCreateHeader ( Size size , int a , int b ) ;",How to pin an 'unmanaged ' pointer ? "C_sharp : In my UWP app I have the following code : but when I run this it fails on the second line with the message An exception of type 'System.Runtime.InteropServices.COMException ' occurred in ... . but was not handled in user code . The HRESULT from the exception is -2147467259 = 0x80004005 = E_FAIL.I 'm using file pickers already elsewhere in the app without problem . This is running on a Win10 desktop ( launched from VS2015 ) . Can anyone suggest why the error occurs and/or what to do to resolve it ? Having a meaningless error message in what appears to be the simplest code possible I 'm not sure how to proceed . private async void testButton_Click ( object sender , RoutedEventArgs e ) { var picker = new Windows.Storage.Pickers.FolderPicker ( ) ; StorageFolder folder = await picker.PickSingleFolderAsync ( ) ; }",UWP FolderPicker.PickSingleFolderAsync fails with COMException / E_FAIL "C_sharp : I 've got a status menu on a tray icon application with Xamarin Mac.There is no window shown by setting Application is agent ( UIElement ) to 1 . A login window must only be shown after a menuItem is clicked . ( which is connected using a action . ) The following code initialized a new MainWindowController after a button is clicked . This action is called because a breakpoint is hit , yet no window is shown.When I set Application is agent ( UIElement ) back to 0 . The window gets shown when the dock icon is clicked . But when the login menu item is clicked , the window are initialized , but it is not brought to the front.The Main nib file name in Info.plist is set to MainMenu which is not the file for the window . partial void OpenLoginWindow ( NSMenuItem sender ) { var loginController = new MainWindowController ( ) ; loginController.Window.MakeKeyAndOrderFront ( this ) ; loginController.ShowWindow ( this ) ; }",Open window using a controller with Xamarin Mac "C_sharp : My problem in short : I need to deserialize two big JSON strings to one class , but strings are little different . Here is the first one : and the other one : You can see that one time it 's `` Persons '' , and the other time it 's `` Person '' . Is there any simple solution to this ? I was thinking about creating two lists in my class and after deserialization combine then manually somehow . But there must be a simplier way . By the way , this is not the exact code I need to deserialize . I just wanted to keep the main idea as simple as possible . { `` persons '' : [ { `` age '' :30 , `` name '' : '' david '' , `` hobbies '' : [ { `` name '' : '' tennis '' , `` hours '' :5 } , { `` name '' : '' football '' , `` hours '' :10 } ] } , { `` name '' : '' adam '' , `` age '' :23 , `` hobbies '' : [ ] } ] } { `` person '' : [ { `` age '' :25 , `` name '' : '' dave '' , `` hobbies '' : [ { `` name '' : '' Basketball '' , `` hours '' :5 } , { `` name '' : '' football '' , `` hours '' :10 } ] } , { `` name '' : '' Steve '' , `` age '' :28 , `` hobbies '' : [ ] } ] } List < Person > person ; List < Person > persons ;","Deserialize two slightly different JSON strings ( same structure , different names ) to the same class" "C_sharp : When looking for a memory- and handleleak in a .NET/WCF/Windows Service I noticed strange behavior that I can not explain.Here the setup and the resolution . What I am looking for would be an explanation for the observed behavior.I installed a Windows Service.I started the service.I called a simple method with a transactional WCF call ( new channel per call - no caching ) .For each call about 2 handles remain in memory.This can be observed if the following items are applicable : It is a Windows Service ; do n't run it as a Console App.Use a Transaction ( separate process or machine tested only ) to call the WCF method.Before calling ServiceBase.Run ( servicesToRun ) ; instantiate XmlSerializer with some type.The type is a custom type . It does not occur with new XmlSerializer ( typeof ( string ) ) or new XmlSerializer ( typeof ( XmlDocument ) ) . No call to serialize is necessary . It is enough if the custom type has only a string as property ( no handles anywhere ! ) Creating a static XmlSerialization.dll using i.e . SGen.exe will not produce this problem.My Code already includes the fix : Use XmlSerializer earliest in OnStart ( ) : Program.csWindowsService.csDemoService.csClient.cs : Can someone explain this behavior ? Please note , I 'm not interested in finding a way to avoid the leak ( I already know how to do this ) but in an explanation ( i.e . WHY is it happening ) . WindowsService winSvc = new WindowsService ( ) ; ServiceBase [ ] servicesToRun = new ServiceBase [ ] { winSvc } ; ServiceBase.Run ( servicesToRun ) ; internal sealed class WindowsService : ServiceBase { private ServiceHost wcfServiceHost = null ; internal WindowsService ( ) { AutoLog = true ; CanStop = true ; CanShutdown = true ; CanPauseAndContinue = false ; } internal void StartWcfService ( ) { wcfServiceHost = new ServiceHost ( typeof ( DemoService ) ) ; wcfServiceHost.Open ( ) ; } protected override void Dispose ( bool disposing ) { if ( wcfServiceHost ! = null ) { wcfServiceHost.Close ( ) ; } base.Dispose ( disposing ) ; } protected override void OnStart ( string [ ] args ) { new XmlSerializer ( typeof ( MyType ) ) ; StartWcfService ( ) ; } } [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.PerSession , TransactionAutoCompleteOnSessionClose = false , IncludeExceptionDetailInFaults = true ) ] public sealed class DemoService : IDemoService { [ TransactionFlow ( TransactionFlowOption.Allowed ) ] [ OperationBehavior ( TransactionScopeRequired = true , TransactionAutoComplete = true ) ] public int Add ( int a , int b ) { return a + b ; } } IChannelFactory < IDemoService > channelFactory = new ChannelFactory < IDemoService > ( `` defaultClientConfiguration '' ) ; IDisposable channel = null ; for ( int index = 0 ; index < 5000 ; index++ ) { using ( channel = ( IDisposable ) channelFactory.CreateChannel ( new EndpointAddress ( `` net.tcp : //localhost:23456/DemoService '' ) ) ) { IDemoService demoService = ( IDemoService ) channel ; using ( TransactionScope tx = new TransactionScope ( TransactionScopeOption.RequiresNew ) ) { demoService.Add ( 3 , 9 ) ; tx.Complete ( ) ; } ) }",Why does instantiating XmlSerializer before ServiceHost.Open is called produce a memory & handle leak "C_sharp : I ( lazily ) used var in the original version of the below code and got a strange runtime exception in an entirely different part of the code . Changing `` var '' to `` int '' fixed the runtime exception but I can not quite see why . I boiled the code down to this example ; I can see the type of the `` var '' being dynamic instead of int , but why does that type propagate to and affect the behaviour of the return value of the call to Test ( ) ? EDIT : Maybe I should clarify my question ; I can see that dynamic propagates to result2 , what I can not understand is why , when the IDE clearly indicates that List < string > Test ( string ) is the method called , it still infers the return value as dynamic . Is it a case of the IDE being more clever than the compiler ? public class Program { private static List < string > Test ( string i ) { return new List < string > { i } ; } private static dynamic GetD ( ) { return 1 ; } public static void Main ( ) { int value1 = GetD ( ) ; // < -- int var result1 = Test ( `` Value `` + value1 ) ; // No problem , prints `` Value 1 '' , First ( ) on List < string > works ok. Console.WriteLine ( result1.First ( ) ) ; var value2 = GetD ( ) ; // < -- var var result2 = Test ( `` Value `` + value2 ) ; // The below line gives RuntimeBinderException // 'System.Collections.Generic.List < string > ' does not contain a // definition for 'First ' Console.WriteLine ( result2.First ( ) ) ; } }","Odd behaviour change with var , dynamic and linq combination" "C_sharp : I am writing a generic extension method for IEnumerable for mapping a list of objects to another list of mapped objects . This is how I would like the method to work : This is the method : However articles.Map < ArticleViewModel > ( _mappingEngine ) ; gives a compile error.The problem is that the type inference for T1 does n't work . I have to explicitly call it like this instead : If I create an extension method with only one parameter T1 like this : Then I can call it like this , without having to specify T1 : Is there are reason why the compiler ca n't infer the type of T1 in the extension method for Map ? IList < Article > articles = GetArticles ( ) ; return articles.Map < ArticleViewModel > ( _mappingEngine ) ; public static IEnumerable < T2 > Map < T1 , T2 > ( this IEnumerable < T1 > list , IMappingEngine engine ) { return list.Select ( engine.Map < T1 , T2 > ) ; } articles.Map < Article , ArticleViewModel > ( _mappingEngine ) ; public static IEnumerable < T1 > DummyMap < T1 > ( this IEnumerable < T1 > list , IMappingEngine engine ) { return list ; } articles.DummyMap ( _mappingEngine ) ;",Type inference problem when writing a generic extension method with more than one type "C_sharp : I 'm currently converting our .net business objects library to a PCL file so that it can be used with Xamarin IOS/Android and while it contains mainly POCO objects , it also contains custom exceptions but this is throwing errors.Take a typical Custom Exception : As expected the PCL does n't like [ Serializable ] and SerializationInfo . While I might get away with sticking [ DataContract ] instead of using [ Serialiable ] , it still wo n't resolve the issue with SerializationInfo . Is there anyway to circumvent this problem ? Thanks.Update : I 've had a look at Implementing custom exceptions in a Portable Class Library as suggested but the following 2 attributes are not recognised : I must be missing a reference but to which assembly ? I 'm currently looking at an alternative solution as provided in Portable class library : recommended replacement for [ Serializable ] Hopefully this will work . I will update my answer once I have more info to provide.Update : ClassInterfaceAttribute is part of the System.RunTime.InteroServices but I can not add this to my PCL project , well at least it 's not visible . Am I missing something ? The other article is providing additional info and it looks that when using conditional compilation , this should work , but again , while the sample code from the json library appears to work , I must be missing something as I can not add a reference so that [ Serializable ] does not throw an error , but I do n't appear to be able to do so.One thing I 've tried is to simply comment out : And I can compile my pcl project ok , so the question is do I need this ? Thanks . [ Serializable ] public class EncryptKeyNotFoundException : Exception { public EncryptKeyNotFoundException ( ) : base ( ) { } public EncryptKeyNotFoundException ( string message ) : base ( message ) { } public EncryptKeyNotFoundException ( string format , params object [ ] args ) : base ( string.Format ( format , args ) ) { } public EncryptKeyNotFoundException ( string message , Exception innerException ) : base ( message , innerException ) { } public EncryptKeyNotFoundException ( string format , Exception innerException , params object [ ] args ) : base ( string.Format ( format , args ) , innerException ) { } protected EncryptKeyNotFoundException ( SerializationInfo info , StreamingContext context ) : base ( info , context ) { } } [ ClassInterfaceAttribute ( ClassInterfaceType.None ) ] [ ComVisibleAttribute ( true ) ] protected EncryptKeyNotFoundException ( SerializationInfo info , StreamingContext context ) : base ( info , context ) { }",Custom Exceptions in PCL files "C_sharp : In the image above , you can see a warning from Code Contracts . I do n't think this is legit , as this can never be null.Is this a bug or am I missing something ? This property is a member of the following class : Update : Changing the property to the following still shows the warning - on the line return result ; : public class NHibernateIQueryableQueryBase < TEntity , TQuery , TQueryInterface > : IQuery < TEntity > , IFluentQueryInterface < TEntity , TQueryInterface > where TQuery : NHibernateIQueryableQueryBase < TEntity , TQuery , TQueryInterface > , TQueryInterface where TQueryInterface : IQuery < TEntity > public TQueryInterface And { get { var result = this as TQuery ; return result ; } }",CodeContracts : false warning `` Possibly unboxing a null reference '' "C_sharp : I read that great post on Visual Studio 2008 annoyances , but did n't see this one . It drives me crazy . Now , I realize that some people use block comments like this for function documentation and the like : But you know , this is VS2008 and now we can use /// . The only time I ever feel the need to use C-style commenting is when I have some junk or test code that I temporarily want to remove . It absolutely drives me nuts when I do the first /* and then when I add a line after the test code , it automatically puts a space after the * and I end up with this : * / . So then I end up always having to backspace to complete the block comment.I looked through all of the C # editor settings in the VS2008 IDE , and did n't find anything relevant.Does this drive anyone else here crazy , or am I turning into a codemudgeon ? /* * * * */",Visual Studio 2008 's annoying auto-handling of block comments "C_sharp : See below codes : I want to create a Fluent Interface for that But I need , after Add ( ) method developer see Only Or ( ) or And ( ) andafter one of these , see Only Add ( ) method.so no one can write a code like : I want to have a limitation for some methods can accept special methods and etc.I can write all methods in one class and return this for each one but that is not suitable ! ! ! Please guide me How write Advanced Fluent Interface class . new ConditionCreator ( ) .Add ( ) .Or ( ) .Add ( ) .And ( ) .Add ( ) new ConditionCreator ( ) .Add ( ) .Add ( ) .Add ( ) .Or ( ) .And ( ) .Add ( ) .And ( ) .And ( )",How create Fluent Interface in C # with some limitation for some methods ? C_sharp : I found an empty for statement in an existing bit of code and I 'm wondering what it does and is it `` safe '' . It just feels wrong.Thanks ! for ( ; ; ) { //some if statements and a case statement },In C # is a for ( ; ; ) safe and what does it really do ? "C_sharp : I made a utility debug class in a C # game I 'm working on to be able to monitor and watch values of properties . Goes like this : Now in order to monitor a property , say my game 's FPS , I must doWould n't there be a way to somehow make this simpler to use ? Ideally I 'd like to be able to doBut since we ca n't store pointers to value types in C # , I do n't know how I would do this . Maybe using closures and lambada expressions ? I was suggested this earlier but I 'm not sure how to do it . Any other ways to improve this ? Thanks public static class Monitor { private static List < object > monitoredObjects ; public static void Initialize ( ) { monitoredObjects = new List < object > ( ) ; } public static void Watch ( object o ) { monitoredObjects.Add ( o ) ; } public static void Unwatch ( object o ) { monitoredObjects.Remove ( o ) ; } public static void Draw ( RenderWindow app ) { //Not actual code , I actually draw this in game foreach ( object o in monitoredObjects ) Console.WriteLine ( o.ToString ( ) ) ; } } public class Property { private object obj ; private PropertyInfo propertyInfo ; public override string ToString ( ) { return propertyInfo.Name + `` : `` + propertyInfo.GetValue ( obj , null ) .ToString ( ) ; } public Property ( object o , string property ) { obj = o ; propertyInfo = o.GetType ( ) .GetProperty ( property ) ; } } Monitor.Watch ( new Property ( Game , `` FPS '' ) ) ; Monitor.Watch ( Game.FPS ) ;",Improve property monitoring code ? "C_sharp : I am trying to upload a large file ( 1 GB ) from code to SharePoint 2013 on prem . I followed this tutorial , I dowloaded from NuGet the package `` Microsoft.SharePointOnline.CSOM '' and tried this piece of code : But I 'm getting runtime exception : ServerExecution with the message : Method `` StartUpload '' does not exist at line `` ctx.ExecuteQuery ( ) ; '' ( < -- I marked this line in the code ) I also tried with SharePoint2013 package and the method `` startupload '' does n't supported in this package.UPDATE : Adam 's code worked for ~1GB files it turns out that inside web.config in the path : C : \inetpub\wwwroot\wss\VirtualDirectories\ { myport } \web.configat the part < requestLimit maxAllowedContentLength= '' 2000000000 '' / > that 's in bytes and not kilobytes as I thougt at the begining , therefore I changed to 2000000000 and it worked . public Microsoft.SharePoint.Client.File UploadFileSlicePerSlice ( ClientContext ctx , string libraryName , string fileName , int fileChunkSizeInMB = 3 ) { // Each sliced upload requires a unique ID . Guid uploadId = Guid.NewGuid ( ) ; // Get the name of the file . string uniqueFileName = Path.GetFileName ( fileName ) ; // Ensure that target library exists , and create it if it is missing . if ( ! LibraryExists ( ctx , ctx.Web , libraryName ) ) { CreateLibrary ( ctx , ctx.Web , libraryName ) ; } // Get the folder to upload into . List docs = ctx.Web.Lists.GetByTitle ( libraryName ) ; ctx.Load ( docs , l = > l.RootFolder ) ; // Get the information about the folder that will hold the file . ctx.Load ( docs.RootFolder , f = > f.ServerRelativeUrl ) ; ctx.ExecuteQuery ( ) ; // File object . Microsoft.SharePoint.Client.File uploadFile ; // Calculate block size in bytes . int blockSize = fileChunkSizeInMB * 1024 * 1024 ; // Get the information about the folder that will hold the file . ctx.Load ( docs.RootFolder , f = > f.ServerRelativeUrl ) ; ctx.ExecuteQuery ( ) ; // Get the size of the file . long fileSize = new FileInfo ( fileName ) .Length ; if ( fileSize < = blockSize ) { // Use regular approach . using ( FileStream fs = new FileStream ( fileName , FileMode.Open ) ) { FileCreationInformation fileInfo = new FileCreationInformation ( ) ; fileInfo.ContentStream = fs ; fileInfo.Url = uniqueFileName ; fileInfo.Overwrite = true ; uploadFile = docs.RootFolder.Files.Add ( fileInfo ) ; ctx.Load ( uploadFile ) ; ctx.ExecuteQuery ( ) ; // Return the file object for the uploaded file . return uploadFile ; } } else { // Use large file upload approach . ClientResult < long > bytesUploaded = null ; FileStream fs = null ; try { fs = System.IO.File.Open ( fileName , FileMode.Open , FileAccess.Read , FileShare.ReadWrite ) ; using ( BinaryReader br = new BinaryReader ( fs ) ) { byte [ ] buffer = new byte [ blockSize ] ; Byte [ ] lastBuffer = null ; long fileoffset = 0 ; long totalBytesRead = 0 ; int bytesRead ; bool first = true ; bool last = false ; // Read data from file system in blocks . while ( ( bytesRead = br.Read ( buffer , 0 , buffer.Length ) ) > 0 ) { totalBytesRead = totalBytesRead + bytesRead ; // You 've reached the end of the file . if ( totalBytesRead == fileSize ) { last = true ; // Copy to a new buffer that has the correct size . lastBuffer = new byte [ bytesRead ] ; Array.Copy ( buffer , 0 , lastBuffer , 0 , bytesRead ) ; } if ( first ) { using ( MemoryStream contentStream = new MemoryStream ( ) ) { // Add an empty file . FileCreationInformation fileInfo = new FileCreationInformation ( ) ; fileInfo.ContentStream = contentStream ; fileInfo.Url = uniqueFileName ; fileInfo.Overwrite = true ; uploadFile = docs.RootFolder.Files.Add ( fileInfo ) ; // Start upload by uploading the first slice . using ( MemoryStream s = new MemoryStream ( buffer ) ) { // Call the start upload method on the first slice . bytesUploaded = uploadFile.StartUpload ( uploadId , s ) ; ctx.ExecuteQuery ( ) ; // < -- -- -- here exception // fileoffset is the pointer where the next slice will be added . fileoffset = bytesUploaded.Value ; } // You can only start the upload once . first = false ; } } else { // Get a reference to your file . uploadFile = ctx.Web.GetFileByServerRelativeUrl ( docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName ) ; if ( last ) { // Is this the last slice of data ? using ( MemoryStream s = new MemoryStream ( lastBuffer ) ) { // End sliced upload by calling FinishUpload . uploadFile = uploadFile.FinishUpload ( uploadId , fileoffset , s ) ; ctx.ExecuteQuery ( ) ; // Return the file object for the uploaded file . return uploadFile ; } } else { using ( MemoryStream s = new MemoryStream ( buffer ) ) { // Continue sliced upload . bytesUploaded = uploadFile.ContinueUpload ( uploadId , fileoffset , s ) ; ctx.ExecuteQuery ( ) ; // Update fileoffset for the next slice . fileoffset = bytesUploaded.Value ; } } } } // while ( ( bytesRead = br.Read ( buffer , 0 , buffer.Length ) ) > 0 ) } } finally { if ( fs ! = null ) { fs.Dispose ( ) ; } } } return null ; }",Upload file chunks to SPS 2013 - Method `` StartUpload '' does not exist at line C_sharp : What is the WinRT equivalent of these items from the .NET framework ? CultureInfo.CurrentCulture.LCIDEncoding.GetEncoding ( int codePage ) Encoding.CodePage,WinRT equivalent of these .Net culture methods ? "C_sharp : I found this site : https : //docs.microsoft.com/en-us/aspnet/core/security/corsHowever I am confused in how to enable it globally , because it seems there are 2 ways to do it , whats the difference between these 2 ways ? or they do 2 different things ? public IConfigurationRoot Configuration { get ; } // This method gets called by the runtime . Use this method to add services to the container . public void ConfigureServices ( IServiceCollection services ) { //https : //docs.microsoft.com/en-us/aspnet/core/security/cors services.AddCors ( options = > { options.AddPolicy ( `` AllowSpecificOrigin '' , builder = > builder.WithOrigins ( `` http : //example.com '' ) .AllowAnyHeader ( ) ) ; } ) ; services.Configure < MvcOptions > ( options = > { options.Filters.Add ( new CorsAuthorizationFilterFactory ( `` AllowSpecificOrigin '' ) ) ; } ) ; // Add framework services . services.AddMvc ( ) ; } // This method gets called by the runtime . Use this method to configure the HTTP request pipeline . public void Configure ( IApplicationBuilder app , IHostingEnvironment env , ILoggerFactory loggerFactory ) { loggerFactory.AddConsole ( Configuration.GetSection ( `` Logging '' ) ) ; loggerFactory.AddDebug ( ) ; app.UseCors ( `` AllowSpecificOrigin '' ) ; app.UseMvc ( ) ; }",How to enable CORS globally in ASP.NET web API core "C_sharp : I am using very similar loops to iterate all public fields and properties of any passed object . I determine if the field/property is decorated with a particular custom attribute ; if so , an action is performed on the value of the field or property . Two loops are necessary because the method to get a field value is different from the method to get a property value.I would like to place the loop in a single , common method so that I can instead write , more simply : This requires DoEachMember ( ) to accept the MemberInfo type ( which is the parent type of both FieldInfo and PropertyInfo ) . The problem is there is no GetValue method in the MemberInfo class . Both FieldInfo and PropertyInfo use different methods to get the field/property value : Thus , I declare a delegate to utilize inside the loop which takes a MemberInfo and returns the value of that member as an object : The QuestionHow can I detect the type of the objects in the members [ ] array , in order to define the delegate used inside the loop ? Currently , I am using the first element of the array , members [ 0 ] . Is this a good design ? Alternatively , I could detect the type upon each iteration , but there should be no reason individual array members will ever differ : // Iterate all public fields using reflectionforeach ( FieldInfo fi in obj.GetType ( ) .GetFields ( ) ) { // Determine if decorated with MyAttribute . var attribs = fi.GetCustomAttributes ( typeof ( MyAttribute ) , true ) ; if ( attribs.Length == 1 ) { // Get value of field . object value = fi.GetValue ( obj ) ; DoAction ( value ) ; } } // Iterate all public properties using reflectionforeach ( PropertyInfo pi in obj.GetType ( ) .GetProperties ( ) ) { // Determine if decorated with MyAttribute . var attribs = pi.GetCustomAttributes ( typeof ( MyAttribute ) , true ) ; if ( attribs.Length == 1 ) { // Get value of property . object value = pi.GetValue ( obj , null ) ; DoAction ( value ) ; } } DoEachMember ( obj.GetType ( ) .GetFields ( ) ) ; DoEachMember ( obj.GetType ( ) .GetProperties ( ) ) ; public void DoEachMember ( MemberInfo mi , object obj ) { foreach ( MemberInfo mi in obj.GetType ( ) .GetProperties ( ) ) { object value mi.GetValue ( obj ) ; // NO SUCH METHOD ! } } // Delegate to get value from field or property.delegate object GetValue ( MemberInfo mi , object obj ) ; public void DoEachMember ( MemberInfo [ ] members , object obj ) { // Protect against empty array . if ( members.Length == 0 ) return ; GetValue getValue ; // define delegate // First element is FieldInfo if ( members [ 0 ] as FieldInfo ! = null ) getValue = ( mi , obj ) = > ( ( FieldInfo ) mi ) .GetValue ( obj ) ; // First element is PropertyInfo else if ( members [ 0 ] as PropertyInfo ! = null ) getValue = ( mi , obj ) = > ( ( PropertyInfo ) mi ) .GetValue ( obj , null ) ; // Anything else is unacceptable else throw new ArgumentException ( `` Must be field or property . `` ) ; foreach ( MemberInfo mi in members ) { // Determine if decorated with MyAttribute . var attribs = mi.GetCustomAttributes ( typeof ( MyAttribute ) , true ) ; if ( attribs.Length == 1 ) { object value = getValue ( mi , obj ) ; DoStuff ( value ) ; } } } foreach ( MemberInfo mi in members ) { // ... object value ; if ( ( var fi = mi as FieldInfo ) ! = null ) value = fi.GetValue ( obj ) ; else if ( ( var pi = mi as PropertyInfo ) ! = null ) value = pi.GetValue ( obj , null ) ; else throw new ArgumentException ( `` Must be field or property . `` ) ; DoStuff ( value ) ; }",c # Iterate array of parent type to invoke non-polymorphic method on derived type "C_sharp : I have a c # class that takes an HTML and converts it to PDF using wkhtmltopdf.As you will see below , I am generating 3 PDFs - Landscape , Portrait , and combined of the two.The properties object contains the html as a string , and the argument for landscape/portrait.The PDFs `` abc_landscape.pdf '' and `` abc_portrait.pdf '' generate correctly , as expected , but the operation fails when I try to combine the two in a third pdf ( abc_combined.pdf ) .I am using MemoryStream to preform the merge , and at the time of debug , I can see that the finalStream.length is equal to the sum of the previous two PDFs . But when I try to open the PDF , I see the content of just 1 of the two PDFs.The same can be seen below : Additionally , when I try to close the `` abc_combined.pdf '' , I am prompted to save it , which does not happen with the other 2 PDFs.Below are a few things that I have tried out already , to no avail : Change CopyTo ( ) to WriteTo ( ) Merge the same PDF ( either Landscape or Portrait one ) with itselfIn case it is required , below is the elaboration of the GetPdfStream ( ) method . System.IO.MemoryStream PDF = new WkHtmlToPdfConverter ( ) .GetPdfStream ( properties ) ; System.IO.FileStream file = new System.IO.FileStream ( `` abc_landscape.pdf '' , System.IO.FileMode.Create ) ; PDF.Position = 0 ; properties.IsHorizontalOrientation = false ; System.IO.MemoryStream PDF_portrait = new WkHtmlToPdfConverter ( ) .GetPdfStream ( properties ) ; System.IO.FileStream file_portrait = new System.IO.FileStream ( `` abc_portrait.pdf '' , System.IO.FileMode.Create ) ; PDF_portrait.Position = 0 ; System.IO.MemoryStream finalStream = new System.IO.MemoryStream ( ) ; PDF.CopyTo ( finalStream ) ; PDF_portrait.CopyTo ( finalStream ) ; System.IO.FileStream file_combined = new System.IO.FileStream ( `` abc_combined.pdf '' , System.IO.FileMode.Create ) ; try { PDF.WriteTo ( file ) ; PDF.Flush ( ) ; PDF_portrait.WriteTo ( file_portrait ) ; PDF_portrait.Flush ( ) ; finalStream.WriteTo ( file_combined ) ; finalStream.Flush ( ) ; } catch ( Exception ) { throw ; } finally { PDF.Close ( ) ; file.Close ( ) ; PDF_portrait.Close ( ) ; file_portrait.Close ( ) ; finalStream.Close ( ) ; file_combined.Close ( ) ; } var htmlStream = new MemoryStream ( ) ; var writer = new StreamWriter ( htmlStream ) ; writer.Write ( htmlString ) ; writer.Flush ( ) ; htmlStream.Position = 0 ; return htmlStream ; Process process = Process.Start ( psi ) ; process.EnableRaisingEvents = true ; try { process.Start ( ) ; process.BeginErrorReadLine ( ) ; var inputTask = Task.Run ( ( ) = > { htmlStream.CopyTo ( process.StandardInput.BaseStream ) ; process.StandardInput.Close ( ) ; } ) ; // Copy the output to a memorystream MemoryStream pdf = new MemoryStream ( ) ; var outputTask = Task.Run ( ( ) = > { process.StandardOutput.BaseStream.CopyTo ( pdf ) ; } ) ; Task.WaitAll ( inputTask , outputTask ) ; process.WaitForExit ( ) ; // Reset memorystream read position pdf.Position = 0 ; return pdf ; } catch ( Exception ex ) { throw ex ; } finally { process.Dispose ( ) ; }",Unable to merge 2 PDFs using MemoryStream "C_sharp : I 've been reading this article about closures in which they say : '' all the plumbing is automatic '' the compiler `` creates a wrapper class '' and `` extends the life of the variables '' '' you can use local variables without worry '' the .NET compiler takes care of the plumbing for you , etc.So I made an example based on their code and to me , it seems as though closures just act similarly to regular named methods which also `` take care of the local variables without worry '' and in which `` all the plumbing is automatic '' . Or what problem did this `` wrapping of local variables '' solve that makes closures so special / interesting / useful ? AnswerSo the answer to this one is to read Jon Skeet 's article on closures that Marc pointed out . This article not only shows the evolution leading up to lambda expressions in C # but also shows how closures are dealt with in Java , an excellent read for this topic . using System ; namespace TestingLambda2872 { class Program { static void Main ( string [ ] args ) { Func < int , int > AddToIt = AddToItClosure ( ) ; Console.WriteLine ( `` the result is { 0 } '' , AddToIt ( 3 ) ) ; //returns 30 Console.ReadLine ( ) ; } public static Func < int , int > AddToItClosure ( ) { int a = 27 ; Func < int , int > func = s = > s + a ; return func ; } } }",What is so special about closures ? "C_sharp : I have read that there are good reasons to use properties instead of fields in c # on SO . So now I want to convert my code from using fields to using properties.For an instance field of a class , I can set a default value . For example : For the equivalent property , which I think is : My understanding is that the Speed property will be initialised to zero when the class is instantiated . I have been unable to find out how to set a default value to easily update my code . Is there an elegant way to provide a default value for a property ? It seems like there should be an elegant way to do this , without using a constructor , but I just ca n't find out how . int speed = 100 ; int Speed { get ; set ; }",Is there an elegant way to set a default value for a property in c # ? "C_sharp : interoping nim dll from c # i could call and execute the code belowif i will add another function ( proc ) that Calls GetPacks ( ) and try to echo on each element 's buffer i could see the output in the C # console correctlybut i could not transfer the data as it is , i tried everything but i could not accomplish the taskwhen i do same in c/c++ the type i am using is either an IntPtr or char*that is happy to contain returned buffer memberc # signature for c code aboveC # Structfinally calling the function like so : how could i produce similar c code as above from Nim ? it does n't have to be same code , but same effect , that in c # i would be able to read the content of the string . for now , the int is readable but the string is notEdit : this is what i tried to make things simplestruct array of int membersUpdate : it seem that the problem is to do with my settings of nim in my windows OS.i will be updating as soon as i discover what exactly is wrong . proc GetPacksPtrNim ( parSze : int , PackArrINOUT : var DataPackArr ) { .stdcall , exportc , dynlib . } = PackArrINOUT.newSeq ( parSze ) var dummyStr = `` abcdefghij '' for i , curDataPack in PackArrINOUT.mpairs : dummyStr [ 9 ] = char ( i + int8 ' 0 ' ) curDataPack = DataPack ( buffer : dummyStr , intVal : uint32 i ) type DataPackArr = seq [ DataPack ] DataPack = object buffer : string intVal : uint32 EXPORT_API void __cdecl c_returnDataPack ( unsigned int size , dataPack** DpArr ) { unsigned int dumln , Index ; dataPack* CurDp = { NULL } ; char dummy [ STRMAX ] ; *DpArr = ( dataPack* ) malloc ( size * sizeof ( dataPack ) ) ; CurDp = *DpArr ; strncpy ( dummy , `` abcdefgHij '' , STRMAX ) ; dumln = sizeof ( dummy ) ; for ( Index = 0 ; Index < size ; Index++ , CurDp++ ) { CurDp- > IVal = Index ; dummy [ dumln-1 ] = ' 0 ' + Index % ( 126 - ' 0 ' ) ; CurDp- > Sval = ( char* ) calloc ( dumln , sizeof ( dummy ) ) ; strcpy ( CurDp- > Sval , dummy ) ; } } [ DllImport ( @ '' cdllI.dll '' , CallingConvention = CallingConvention.Cdecl ) , SuppressUnmanagedCodeSecurity ] private static extern uint c_returnDataPack ( uint x , DataPackg.TestC** tcdparr ) ; public unsafe static class DataPackg { [ StructLayout ( LayoutKind.Sequential ) ] public struct TestC { public uint Id ; public IntPtr StrVal ; } } public static unsafe List < DataPackg.TestC > PopulateLstPackC ( int ArrL ) { DataPackg.TestC* PackUArrOut ; List < DataPackg.TestC > RtLstPackU = new List < DataPackg.TestC > ( ArrL ) ; c_returnDataPack ( ( uint ) ArrL , & PackUArrOut ) ; DataPackg.TestC* CurrentPack = PackUArrOut ; for ( int i = 0 ; i < ArrL ; i++ , CurrentPack++ ) { RtLstPackU.Add ( new DataPackg.TestC ( ) { StrVal = CurrentPack- > StrVal , Id = CurrentPack- > Id } ) ; } //Console.WriteLine ( `` Res= { 0 } '' , Marshal.PtrToStringAnsi ( ( IntPtr ) RtLstPackU [ 1 ] .StrVal ) ) ; //new string ( RtLstPackU [ 0 ] .StrVal ) ) ; return RtLstPackU ; }",interop with nim return Struct Array containing a string /char* member "C_sharp : I am upgrading an existing application that has implemented a home-brew Constants class in its business and datalayer objects . I want to replace this with Nullable types and do-away with the constants class , that looks like this , but with all non-nullable data types : These constants vaules are used as defaults on almost all the object properties like this : This causes some confusion on saving object properties to the Db as all decimal 's and ints have to be checked for psudo null values or else you save things like int.MinValue to the Db.Ok so now the question.. I want to change things around using Nullable value types as in my example below , will the change in a property from a decimal to a decimal ? affect any code thats implementing these objects ? EDIT : Thanks for the double check of my refactor , and yes the null check on the SET of the property in the original code would be redundant . I still want to know if code that implements this object could have any issues from the change of type to decimal ? from decimal class Constants { public static int nullInt { get { return int.MinValue ; } } } private decimal _unitPrice = Constants.nullInt ; public decimal UnitPrice { get { return _unitPrice ; } set { _unitPrice = ( value == null ) ? Constants.nullInt : value ; } } private void Save ( ) { //Datalayer calls and other props omitted SqlParameter sqlParm = new SqlParameter ( ) ; sqlParm.Value = ( this.UnitPrice == Constants.nullInt ) ? DBNull.Value : ( object ) this.UnitPrice ; } public decimal ? UnitPrice { get ; set ; } private void Save ( ) { //Datalayer calls and other props omitted SqlParameter sqlParm = new SqlParameter ( ) ; sqlParm.Value = this.UnitPrice ? ? DBNull.Value ; }",Implementing Nullable types in existing objects "C_sharp : Lets consider that I have a public property called AvatarSize like the following , Now if a target class wants to set this property , then they need to do it the following way , But if I try to set it like this , the compiler get me an error stating that it can not modify the return values . I know why it happens , but I would like it to support the second way also . Please help me with a solution.P.S . Sorry if the title is absurd public class Foo { ... public Size AvatarSize { get { return myAvatarSize ; } set { myAvatarSize = value ; } } ... } myFoo.AvatarSize = new Size ( 20 , 20 ) ; //this is one possible way myFoo.AvatarSize.Height = 20 ; //.NET stylemyFoo.AvatarSize.Width = 20 ; //error",Setting property 's property directly in C # "C_sharp : I 'm struggling in solving this architectural problem , Our system is using NService Bus , and Implementing DDD with EventSourcing using NEventStore and NES.The client application is WPF I still ca n't decide what is the best practice to update the UI , for example : I have a UI to create ( Batch { Id , StartDate , EndDate , etc.. } ) , after the user clicks save , I 'm sending a command ( CreateBatch ) , Now , Option # 1Shall I register for a reply as follows : and at server side : In this case , how to handle errors ? ( Validation errors , for example there is already a batch starts in the same date ? ) , since you can only return int or string ! ! Option # 2 : Send the command , close the window , fake that the record is added in the main grid , until user refresh the grid and get the real one from ReadModel database , or discover that the record is not added yet with no clue about what happened ! ! Option # 3 Send the command , close the window , fake that the record is added in the main grid but mark it as ( In progress ) , wait for ( BatchCreated ) event to arrive , check that it is the same batch id we sent before , and then mark the record as persisted in the grid.If you have any better options , or have suggestions about the mentioned options , or even some links about how to handle such situation , I would be grateful.Thank you . Bus.Send < CreateBatch > ( batch = > { batch.Id = Guid.NewGuid ( ) ; ... . etc } ) ; private void btnSave_Click ( object sender , EventsArg e ) { Bus.Send < CreateBatch > ( batch = > { batch.Id = Guid.NewGuid ( ) ; ... . etc } ) .Register < int > ( c= > { MessageBox.Show ( `` Command Succeded '' ) ; Close ( ) ; } ) ; } public void Hanlde ( CreateBatch cmd ) { //initiate aggregate and save it . Bus.Return ( /*What ? ? Success Code ? */ ) ; } private void btnSave_Click ( object sender , EventsArg e ) { Bus.Send < CreateBatch > ( batch = > { batch.Id = Guid.NewGuid ( ) ; ... . etc } ) ; Close ( ) ; } private void btnSave_Click ( object sender , EventsArg e ) { Bus.Send < CreateBatch > ( batch = > { batch.Id = Guid.NewGuid ( ) ; ... . etc } ) ; Close ( ) ; } public class BatchHandler : IHandleMessages < BatchCreated > { public void Handle ( BatchCreated evnt ) { if ( SomeCachForSentIDS.Contains ( evnt.BatchId ) ///Code to refresh the row in the grid and reflect that the command succeeded . } }",Updating UI after sending command "C_sharp : Using C # /.NET 4.0 , a Lazy < T > object can be declared as follows.Other options from the LazyThreadSafetyMode enumeration are PublicationOnly and None.Why is there no ExecutionOnly option ? The behavior in this case would be that the factory method is called at most once by a single thread , even if multiple threads try to get lazy.Value . Once the factory method was completed and the single result was cached , many threads would be able to access lazy.Value simultaneously ( i.e. , no thread safety after the initial factory method ) . using System ; using System.Threading ; ... var factory = ( ) = > { return new object ( ) ; } ; var lazy = new Lazy < object > ( factory , LazyThreadSafetyMode.ExecutionAndPublication ) ;",System.Lazy < T > and the System.Threading.LazyThreadSafetyMode Enumeration "C_sharp : Ok , consider the following code : Suprisingly this code does not throw a `` Use of unassigned local variable 'hello ' '' compile time error . It simply gives a warning `` Unreachable code detected '' . Even if the code is unreachable , it is still a compile time error , I 'd think the right thing to do is throw a compile time error . If I were to do the following : Sure enough , I get a `` 'string ' does not contain a definition for 'LMFAO ' and no extension method 'LMFAO ' accepting a first argument of type 'string ' could be found ( are you missing a using directive or an assembly reference ? ) '' compile time error.Why is n't it the same with the use of an unassigned variable ? EDIT Changed the const variable so it is less distracting . I think many are missing the point of the question which is whay depending on which case , compile time errors take precedence over unreachable code . private const int THRESHHOLD = 2 ; static void Main ( string [ ] args ) { string hello ; if ( THRESHHOLD > 1 ) return ; Console.WriteLine ( hello ) ; } private const int THRESHHOLD = 2 ; static void Main ( string [ ] args ) { string hello ; if ( THRESHHOLD > 1 ) return ; hello.LMFAO ( ) ; }",Compile time errors and unreachable code "C_sharp : I 'm roughly familiar with the Dispose pattern for non-finalizable types , eg , types that wrap some sort of managed resource that we want to have deterministic cleanup done on . These sort of types typically do not implement a finalizer , since it is completely unnecessary.However , I 'm implementing a C # wrapper for a native API where I 'm wrapping multiple , related unmanaged resources , and seemingly , would need multiple classes each implementing the finalizable-dispose pattern . The problem is that the guidelines for the dispose pattern says that finalizable A should not rely on finalizable B , which is exactly what I need : Dispose Pattern on MSDN : X DO NOT access any finalizable objects in the finalizer code path , because there is significant risk that they will have already been finalized . For example , a finalizable object A that has a reference to another finalizable object B can not reliably use B in A ’ s finalizer , or vice versa . Finalizers are called in a random order ( short of a weak ordering guarantee for critical finalization ) .So here are my constraints : To do anything , I have to create an `` API '' handle.To create `` child '' handles , I have to provide the API handle in the 'create child ' call.Both types of handles ca n't be leaked.If the API handle is closed , all of its child handles are implicitly closed.To close a child handle , I have to provide the child handle and the API handle in the native call.The native API looks something like this : The naive approach for this would be two parts : For the API handle , follow the typical SafeHandle pattern.For the child handle , follow the typical SafeHandle pattern , but modify it a little bit , since a child handle needs a reference to the API handle in order to implement its ReleaseHandle override - add a method that gives the API handle to the child SafeHandle after it 's been constructed.So everything would look something like this : However , now I have a flaw - my ChildSafeHandle 's ReleaseHandle is referencing another handle to do its work . I now have two finalizable disposable objects , where one 's finalizer depends on the other . MSDN explicitly says that finalizers should not rely on other finalizable objects , since they may already be finalized , or if .Net were to ever support multi-threaded finalization , they might be getting finalized concurrently.What is the right way to do this ? Do the rules allow me to access finalizable object A from the finalizer of B , so long as I test for validity first ? MSDN is n't clear on this . APIHANDLE GizmoCreateHandle ( ) ; CHILDHANDLE GizmoCreateChildHandle ( APIHANDLE apiHandle ) ; GizmoCloseHandle ( APIHANDLE apiHandle ) ; GizmoCloseChildHandle ( APIHANDLE apiHandle , CHILDHANDLE childHandle ) ; [ DllImport ( `` gizmo.dll '' ) ] private static extern ApiSafeHandle GizmoCreateHandle ( ) ; [ DllImport ( `` gizmo.dll '' ) ] private static extern void GizmoCloseHandle ( IntPtr apiHandle ) ; [ DllImport ( `` gizmo.dll '' ) ] private static extern ChildSafeHandle GizmoCreateChildHandle ( ApiSafeHandle apiHandle ) ; [ DllImport ( `` gizmo.dll '' ) ] private static extern void GizmoCloseChildHandle ( ApiSafeHandle apiHandle , IntPtr childHandle ) ; [ DllImport ( `` gizmo.dll '' ) ] private static extern void GizmoChildModify ( ChildSafeHandle childHandle , int flag ) ; public class ApiSafeHandle : SafeHandle { public ApiSafeHandle ( ) : base ( IntPtr.Zero , true ) { } public override bool IsInvalid { get { return this.handle == IntPtr.Zero ; } } protected override bool ReleaseHandle ( ) { GizmoCloseHandle ( this.handle ) ; return true ; } } public class ChildSafeHandle : SafeHandle { private ApiSafeHandle apiHandle ; public ChildSafeHandle ( ) : base ( IntPtr.Zero , true ) { } public override bool IsInvalid { get { return this.handle == IntPtr.Zero ; } } public void SetParent ( ApiSafeHandle handle ) { this.apiHandle = handle ; } // This method is part of the finalizer for SafeHandle . // It access its own handle plus the API handle , which is also a SafeHandle // According to MSDN , this violates the rules for finalizers . protected override bool ReleaseHandle ( ) { if ( this.apiHandle == null ) { // We were used incorrectly - we were allocated , but never given // the means to deallocate ourselves return false ; } else if ( this.apiHandle.IsClosed ) { // Our parent was already closed , which means we were implicitly closed . return true ; } else { GizmoCloseChildHandle ( apiHandle , this.handle ) ; return true ; } } } public class GizmoApi { ApiSafeHandle apiHandle ; public GizmoApi ( ) { this.apiHandle = GizmoCreateHandle ( ) ; } public GizmoChild CreateChild ( ) { ChildSafeHandle childHandle = GizmoCreateChildHandle ( this.apiHandle ) ; childHandle.SetParent ( this.apiHandle ) ; return new GizmoChild ( childHandle ) ; } } public class GizmoChild { private ChildSafeHandle childHandle ; internal GizmoChild ( ChildSafeHandle handle ) { this.childHandle = handle ; } public void SetFlags ( int flags ) { GizmoChildModify ( this.childHandle , flags ) ; } // etc . }",Implement finalizable dispose pattern with multiple related finalizable objects "C_sharp : I need to do a HTTP POST using C # . It needs to do a postback the same way as an IE6 page . From the documentation the postback should look like I think im having trouble with the boundary characters . I tried setting the boundary in the post data and fiddler shows something similar but I get a page back with the error `` Invalid procedure call or argument '' . the Content-disposition is in the body rather than the header to keep it within the boundaries . Im not sure that is right . Am I setting the boundary the correct way ? Can anyone give some guidance on how to do an IE6 style HTTP POST using C # ? ThanksMy Code Fiddler Output ( raw ) POST / ... /Upload.asp ? b_customerId= [ O/M1234 ] HTTP/1.1Content-length : 12345Content-type : multipart/form-data ; boundary=vxvxvHost : www.foo.com -- vxvxvContent-disposition : form-data ; name= ” File1 ” ; filename= ” noColonsSpacesOrAmpersandsInHere ” Content-type : text/xml < ? xml version= ” 1.0 ” encoding= ” UTF-8 ” ? > ... < bat : Batch ... ... ... . < /bat : Batch > -- vxvxv -- data = `` -- vxvxv '' + Environment.NewLine + `` Content-disposition : form-data ; name=\ '' File1\ '' ; '' + Environment.NewLine + `` filename=\ '' provideTest.xml\ '' '' + Environment.NewLine + `` Content-type : text/xml '' + Environment.NewLine + @ '' < ? xml version= '' '' 1.0 '' '' encoding= '' '' UTF-8 '' '' ? > '' + Environment.NewLine + data + Environment.NewLine + `` -- vxvxv -- '' ; var encoding = ASCIIEncoding.UTF8 ; HttpWebRequest request ; var postData = encoding.GetBytes ( data ) ; request = ( HttpWebRequest ) WebRequest.Create ( url ) ; request.ContentLength = postData.Length ; request.Method = `` POST '' ; request.ContentType = `` multipart/form-data ; boundary=vxvxv '' ; request.Host = `` www.foo.com '' ; request.ContentLength = postData.Length ; X509Certificate2Collection certCollect = new X509Certificate2Collection ( ) ; X509Certificate2 cert = new X509Certificate2 ( @ '' C : \a\cert.pfx '' , `` password '' ) ; certCollect.Add ( cert ) ; request.ClientCertificates = certCollect ; using ( Stream writeStream = request.GetRequestStream ( ) ) { writeStream.Write ( postData , 0 , postData.Length ) ; } WebResponse webResponse = request.GetResponse ( ) ; string output = new StreamReader ( webResponse.GetResponseStream ( ) ) .ReadToEnd ( ) ; LogEntry.Write ( `` Recieved : `` + output ) ; return output ; POST https : //../Upload.asp ? b_customerId= % 5BO/M1234 % 5D HTTP/1.1Content-Type : multipart/form-data ; boundary=vxvxvHost : www.foo.comContent-Length : 5500Expect : 100-continueConnection : Keep-Alive -- vxvxvContent-disposition : form-data ; name= '' File1 '' ; filename= '' provideTest.xml '' Content-type : text/xml < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > ... SNIP ... < /bat : Batch > -- vxvxv --",HTTP Post as IE6 using C # C_sharp : Is this possible to use let keyword with nhibernate linq ? I wroteand in response I have NHibernate.QueryException : could not resolve property : post of : Sys.Domain.Entities.Post var posts = from post in postsRepository.GetPosts ( name ) let commentsCount = ( from c in NHUnitOfWork.CurrentSession.Linq < Comment > ( ) where c.Post.ID == post.ID select c ) .Count ( ) select new ...,LINQ to NHibernate and let keyword C_sharp : Suppose that I have an object then how could I know if the object is derived from a specific generic class . For example : please notice that the code above will throw an exception . The type of the generic class can not be retrieved directly because there is no type for a generic class without a type parameter provided . public class GenericClass < T > { } public bool IsDeriveFrom ( object o ) { return o.GetType ( ) .IsSubclassOf ( typeof ( GenericClass ) ) ; //will throw exception here },How could I know if an object is derived from a specific generic class ? C_sharp : I have an abstract class that is inherited by two classes . Both classes represent tables in the database . I am having troubles mapping expressions though in the abstract class and therefore I keep getting exceptions that it can not be translated to SQL . All questions I found in Stackoverflow are talking about columns which is already working for me.Below is a very simple code that shows what I mean . Car and Motorcycle have completely separate implementations of _isNew Expression.I would like to be able to call either _isNew expression or IsNew property on an IQueryable and yet it runs the _isNew of the Car class in case Vehicle is type of Car . Is there anyway I can accomplish that ? All solutions I tried caused an exception that it can not be translated to SQL . public abstract class Vehicle { public abstract boolean IsNew ; } public partial class Car : Vehicle { public override boolean IsNew { get { _isNew.Invoke ( this ) ; } } } public partial class Motorcycle : Vehicle { public override boolean IsNew { get { _isNew.Invoke ( this ) ; } } },Mapping expressions in LINQ-to-sql abstract class "C_sharp : I am attempting to build a system that allows users to perform certain actions , but their account must have a specific 'Ticket ' per time they do it . For instance , suppose they wish to create a Product , they would need a CreateProductTicket . I could simply do this with some 'if ' statements , sure , but I want to try a bit more of a robust solution . My structure looks something like this ... My basic goal is to build an Attribute , perhaps like the following..And to be able to decorate Controller or Repository Actions with this . So like ... ProductsControlllerProblem 1I 'm not familiar enough with attributes to know how to tell if TicketRequired was 'met ' or not . Can anyone enlighten me on this ? Problem 2The problem I am running into is with database querying . I want to be able to check the user ( IMembershipRepository has a GetUser method ) , but I 'm not entirely certain how to do that through an attribute . Using Castle.Windsor , I have my Dependency Injection set up to inject repositories into controllers . I suppose I could pass the IMembershipRepository through the TicketRequired constructor , but I have a feeling that will become very messy - and extremely unstable . Is there a more logical way to approach this ? interface ITicket < T > where T : ITicketable { } public class TicketRequiredAttribute : Attribute { public TicketRequiredAttribute ( ITicket < T > ticket ) { if ( ticket == null ) return ; } } [ TicketRequired ( CreateProductTicket ) ] public ActionResult CreateProduct ( Product product ) { // ... **I am unsure how to tell if TicketRequired was true or not** }","ASP.NET MVC , 'Ticket Required ' Attribute" "C_sharp : I want to have to GET methods on my api , one with the Route with path parameters : api/people/ { personId } and one with the Route with query parameters : api/people ? text=somethingbut if i put this code : And then try to open /api/people/1 it says wrong format and when I try to open /api/people ? text=something it works.I only have the default route defined : How can I have them both working ? Define that if it 's a path parameter go to the first one and if it 's a query parameter go to second on ? // GET : api/people/ { personId } [ Route ( `` api/people/ { personId } '' ) ] [ HttpGet ] public HttpResponseMessage Get ( long personId ) { } // GET : api/people ? text=something [ Route ( `` api/people '' ) ] [ HttpGet ] public HttpResponseMessage Get ( string text ) { } config.Routes.MapHttpRoute ( name : `` DefaultApi '' , routeTemplate : `` api/ { controller } / { id } '' , defaults : new { id = RouteParameter.Optional } ) ;",How to distinguish query parameters from path parameters "C_sharp : Within a RichtTextBox I want to automatically replace emoticon strings ( e.g . : D ) with an emoticon image.I got it working so far , except that when I write the emoticon string between existing words / strings , the image gets inserted at the end of the line.For example : hello ( inserting : D here ) this is a messageresults in : hello this is a message ☺ < < imageAnother ( tiny ) problem is , that the caret position is set before the image after inserting.This is what I already got : public class Emoticon { public Emoticon ( string key , Bitmap bitmap ) { Key = key ; Bitmap = bitmap ; BitmapImage = bitmap.ToBitmapImage ( ) ; } public string Key { get ; } public Bitmap Bitmap { get ; } public BitmapImage BitmapImage { get ; } } public class EmoticonRichTextBox : RichTextBox { private readonly List < Emoticon > _emoticons ; public EmoticonRichTextBox ( ) { _emoticons = new List < Emoticon > { new Emoticon ( `` : D '' , Properties.Resources.grinning_face ) } ; } protected override void OnTextChanged ( TextChangedEventArgs e ) { base.OnTextChanged ( e ) ; Dispatcher.InvokeAsync ( Look ) ; } private void Look ( ) { const string keyword = `` : D '' ; var text = new TextRange ( Document.ContentStart , Document.ContentEnd ) ; var current = text.Start.GetInsertionPosition ( LogicalDirection.Forward ) ; while ( current ! = null ) { var textInRun = current.GetTextInRun ( LogicalDirection.Forward ) ; if ( ! string.IsNullOrWhiteSpace ( textInRun ) ) { var index = textInRun.IndexOf ( keyword , StringComparison.Ordinal ) ; if ( index ! = -1 ) { var selectionStart = current.GetPositionAtOffset ( index , LogicalDirection.Forward ) ; if ( selectionStart == null ) continue ; var selectionEnd = selectionStart.GetPositionAtOffset ( keyword.Length , LogicalDirection.Forward ) ; var selection = new TextRange ( selectionStart , selectionEnd ) { Text = string.Empty } ; var emoticon = _emoticons.FirstOrDefault ( x = > x.Key.Equals ( keyword ) ) ; if ( emoticon == null ) continue ; var image = new System.Windows.Controls.Image { Source = emoticon.BitmapImage , Height = 18 , Width = 18 , Margin = new Thickness ( 0 , 3 , 0 , 0 ) } ; // inserts at the end of the line selection.Start ? .Paragraph ? .Inlines.Add ( image ) ; // does n't work CaretPosition = CaretPosition.GetPositionAtOffset ( 1 , LogicalDirection.Forward ) ; } } current = current.GetNextContextPosition ( LogicalDirection.Forward ) ; } } } public static class BitmapExtensions { public static BitmapImage ToBitmapImage ( this Bitmap bitmap ) { using ( var stream = new MemoryStream ( ) ) { bitmap.Save ( stream , ImageFormat.Png ) ; stream.Position = 0 ; var image = new BitmapImage ( ) ; image.BeginInit ( ) ; image.CacheOption = BitmapCacheOption.OnLoad ; image.DecodePixelHeight = 18 ; image.DecodePixelWidth = 18 ; image.StreamSource = stream ; image.EndInit ( ) ; image.Freeze ( ) ; return image ; } } }",RichTextBox replace string with emoticon / image "C_sharp : How to implement multiple selections in a class which inherit from Enumeration With restrictions ? If I have five schedule types : Fixed scheduleRotated scheduleFullTime schedulePartTime scheduleFlexible scheduleThe first two options are versus ( Fixed vs Rotated ) and the second Two options ( FullTime vs PartTime ) are versus , I mean the schedule ca n't be fixed and rotated at the same time or fulltime and parttime at the same time . but It may be Fixed and FullTime for example.Fixed work schedules which consists of the same number of hours and days worked per week and tend to stay consistent once the number of hours and days have been agreed upon by both the employer and the worker . Flexible work schedules in which employees and employers work together to determine the number of hours and days of the week they are able to commit to . Full time work schedule which often require a commitment of 37 - 40 hours per week . Because of the long hours , careers with full time schedules are eligible for work benefits . These benefits can include leave , vacation and sickness , health insurance , and different retirement plan options.Part time work schedule which is any schedule less than full time employment.Rotating work schedule which cycle employees through day or week , swing , and night shifts . This cycle helps to distribute different shifts between all employees so that no one is stuck with just the less desirable hours.So I did the following : So based on the user selection for a specific option or set of options , I have to call a method to set flags ( IsFixed , ... ) in the Schedule class to control the the scheduledetails class in ( Fixed and rotated ) and the number of hours for ( full time and part time ) I 'll be grateful for any suggestions or recommendations ? public class Schedule { public Schedule ( ) { } private ICollection < ScheduleDetail > _assignedWeeks ; public int Id { get ; set ; } public string Name { get ; set ; } public int WorkingGroupId { get ; set ; } public ScheduleType ScheduleType { get ; set ; } public bool IsFixed { get ; } public bool IsFlexible { get ; } public bool IsFullTime { get ; } public ICollection < ScheduleDetail > AssignedWeeks { get = > _assignedWeeks ; set = > _assignedWeeks = value ; } } public abstract class ScheduleType : Enumeration { protected ScheduleType ( int value , string displayName ) : base ( value , displayName ) { } public static readonly ScheduleType Fixed = new FixedType ( ) ; public static readonly ScheduleType Flexible = new FlexibleType ( ) ; public static readonly ScheduleType FullTime = new FullTimeType ( ) ; public static readonly ScheduleType PartTime = new PartTimeType ( ) ; public static readonly ScheduleType Rotated = new RotatedType ( ) ; private class FixedType : ScheduleType { public FixedType ( ) : base ( 1 , `` Fixed Work Schedule '' ) { } } private class FlexibleType : ScheduleType { public FlexibleType ( ) : base ( 2 , `` Flexible Work Schedule '' ) { } } private class FullTimeType : ScheduleType { public FullTimeType ( ) : base ( 3 , `` Full Time Work Schedule '' ) { } } private class PartTimeType : ScheduleType { public PartTimeType ( ) : base ( 4 , `` Part Time Work Schedule '' ) { } } private class RotatedType : ScheduleType { public RotatedType ( ) : base ( 5 , `` Rotated Work Schedule '' ) { } } } public abstract class Enumeration : IComparable { private readonly int _value ; private readonly string _displayName ; protected Enumeration ( ) { } protected Enumeration ( int value , string displayName ) { _value = value ; _displayName = displayName ; } public int Value { get { return _value ; } } public string DisplayName { get { return _displayName ; } } public override string ToString ( ) { return DisplayName ; } public static IEnumerable < T > GetAll < T > ( ) where T : Enumeration , new ( ) { var type = typeof ( T ) ; var fields = type.GetFields ( BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly ) ; foreach ( var info in fields ) { var instance = new T ( ) ; var locatedValue = info.GetValue ( instance ) as T ; if ( locatedValue ! = null ) { yield return locatedValue ; } } } public override bool Equals ( object obj ) { var otherValue = obj as Enumeration ; if ( otherValue == null ) { return false ; } var typeMatches = GetType ( ) .Equals ( obj.GetType ( ) ) ; var valueMatches = _value.Equals ( otherValue.Value ) ; return typeMatches & & valueMatches ; } public override int GetHashCode ( ) { return _value.GetHashCode ( ) ; } public static int AbsoluteDifference ( Enumeration firstValue , Enumeration secondValue ) { var absoluteDifference = Math.Abs ( firstValue.Value - secondValue.Value ) ; return absoluteDifference ; } public static T FromValue < T > ( int value ) where T : Enumeration , new ( ) { var matchingItem = parse < T , int > ( value , `` value '' , item = > item.Value == value ) ; return matchingItem ; } public static T FromDisplayName < T > ( string displayName ) where T : Enumeration , new ( ) { var matchingItem = parse < T , string > ( displayName , `` display name '' , item = > item.DisplayName == displayName ) ; return matchingItem ; } private static T parse < T , K > ( K value , string description , Func < T , bool > predicate ) where T : Enumeration , new ( ) { var matchingItem = GetAll < T > ( ) .FirstOrDefault ( predicate ) ; if ( matchingItem == null ) { var message = string.Format ( `` ' { 0 } ' is not a valid { 1 } in { 2 } '' , value , description , typeof ( T ) ) ; throw new ApplicationException ( message ) ; } return matchingItem ; } public int CompareTo ( object other ) { return Value.CompareTo ( ( ( Enumeration ) other ) .Value ) ; } }",how to use flags attribute with class inherit from enumeration "C_sharp : Variations of this question have been asked and answered many times and the answers have a lot of overlapping details . I have tried so many different things suggested by these answers , but none of them have worked in my case.I have a SQLite database with a parent table and a child table . It 's a really simple setup . I 'm using NHibernate 4.0.4 with mapping by code instead of fluent as it was suggested to me that the former is newer and an improvement over the latter.ENTITIES : BillingItem MAPPING : PaymentItem MAPPING : REPOSITORY : BUSINESS LOGIC : As suggested by this answer ( and this and this and many , many others ) , I have made sure to set the Inverse ( true ) in my Set ( child collection ) in BillingItemMapping . I have also set my bi-directional references in the PaymentItem object : and BillingItem object : I feel I 've setup everything else the way it should be , and I 've tinkered around with a lot of the mapping settings based on suggestions from various other sources . However , I just ca n't figure out why it 's not working.The problem is , I ca n't get the foreign key column on the PaymentItem record to hold the ID from the BillingItem . If I set the column to not allow nulls ( which is the way it should be ) , I get a null constraint exception . If I set it to allow nulls ( for testing ) , it just gets set to null ( obviously ) .What am I doing wrong ? public class BillingItem { public virtual int ID { get ; set ; } public virtual string Name { get ; set ; } // ... other properties public virtual ICollection < PaymentItem > PaymentItems { get ; set ; } public BillingItem ( ) { PaymentItems = new List < PaymentItem > ( ) ; } } public class PaymentItem { public virtual int ID { get ; set ; } public virtual BillingItem OwningBillingItem { get ; set ; } // ... other properties } public class BillingItemMapping : ClassMapping < BillingItem > { public BillingItemMapping ( ) { Table ( `` BillingItems '' ) ; Lazy ( true ) ; Id ( x = > x.ID , map = > map.Generator ( Generators.Identity ) ) ; Set ( x = > x.PaymentItems , c = > { c.Key ( k = > { k.Column ( `` ID '' ) ; k.ForeignKey ( `` BillingItemID '' ) ; } ) ; c.Inverse ( true ) ; c.Cascade ( Cascade.None ) ; } , r = > r.OneToMany ( o = > { } ) ) ; Property ( x = > x.Name ) ; // ... other properties } } public class PaymentItemMapping : ClassMapping < PaymentItem > { public PaymentItemMapping ( ) { Table ( `` PaymentItems '' ) ; Lazy ( true ) ; Id ( x = > x.ID , map = > map.Generator ( Generators.Identity ) ) ; ManyToOne ( x = > x.OwningBillingItem , m = > { m.Column ( `` ID '' ) ; m.Update ( false ) ; m.Insert ( false ) ; m.Cascade ( Cascade.None ) ; m.Fetch ( FetchKind.Join ) ; m.NotFound ( NotFoundMode.Exception ) ; m.Lazy ( LazyRelation.Proxy ) ; m.ForeignKey ( `` BillingItemID '' ) ; } ) ; Property ( x = > x.DueDate , map = > map.NotNullable ( true ) ) ; // ... other properties . } } public void Add ( BillingItem toAdd ) { using ( ISession session = Helpers.NHibernateHelper.OpenSession ( ) ) using ( ITransaction tran = session.BeginTransaction ( ) ) { session.Save ( toAdd ) ; foreach ( var pi in toAdd.PaymentItems ) { session.Save ( pi ) ; } tran.Commit ( ) ; } } var bi = new BillingItem ( ) { Name = Guid.NewGuid ( ) .ToString ( ) , // ... others.. } ; var pi = new PaymentItem ( ) { OwningBillingItem = bi , DueDate = DateTime.Now.AddDays ( 3 ) // ... others.. } ; bi.PaymentItems.Add ( pi ) ; var repo = new Repository ( ) ; repo.Add ( bi ) ; OwningBillingItem = bi bi.PaymentItems.Add ( pi ) ;","NHibernate with mapping by code and a SQLite database : saving many-to-one parent-child entities , child gets a null foreign key" "C_sharp : I 'm trying to get the user 's IP address from ASP.NET MVC 5 . I 've looked up various examples , such as these : https : //stackoverflow.com/a/740431/177416https : //stackoverflow.com/a/20194511/177416https : //stackoverflow.com/a/3003254/177416They 've all produced the same result : the user is considered internal to the network . I 've had friends try their phones ( which are not on the network ) . Here 's my latest attempt : The log is showing 10.xxx.xx.xxx for all requests ( based on the log ) . This is an internal address rather than the IP of the client connecting to the web app . The IsIpInternal ( ) returns true always . What am I doing wrong ? Note that I 'm ignoring 192.168.x.x and 172.16.xxx.xxx addresses as being internal . private static Logger _logger = LogManager.GetCurrentClassLogger ( ) ; public static bool IsIpInternal ( ) { var ipAddress = HttpContext.Current.Request.UserHostAddress ; var logEvent = new LogEventInfo ( LogLevel.Info , _logger.Name , ipAddress ) ; _logger.Log ( logEvent ) ; try { if ( ipAddress ! = null ) { var ipParts = ipAddress.Split ( new [ ] { `` . '' } , StringSplitOptions.RemoveEmptyEntries ) .Select ( int.Parse ) .ToArray ( ) ; var isDebug = System.Diagnostics.Debugger.IsAttached ; if ( ipParts [ 0 ] == 10 ) { return true ; } } } catch ( Exception e ) { logEvent = new LogEventInfo ( LogLevel.Error , _logger.Name , e.Message ) ; _logger.Log ( logEvent ) ; return false ; } return false ; }",Client IP address returns the same internal network address "C_sharp : Taken directly from the immediate window : reader [ `` DateDue '' ] as DateTime ? yields : ( DateTime ? ) reader [ `` DateDue '' ] yields : and for reference , reader [ `` DateDue '' ] yields : Is this a bug ? If directly casting to DateTime ? works then casting with as DateTime ? should work too.I did find a work around for this by using reader.GetDateTime ( reader.GetOrdinal ( `` DateDue '' ) ) as DateTime ? . Nevermind , that does n't handle nulls well . Anyway there 's myriad ways to paper around this oddity.Repo demonstrating the issue can be found here : https : //github.com/jjoedouglas/exceptionAsDatetime 'reader [ `` DateDue '' ] as DateTime ? ' threw an exception of type 'System.NullReferenceException'Data : { System.Collections.ListDictionaryInternal } HResult : -2147467261HelpLink : nullInnerException : nullMessage : `` Object reference not set to an instance of an object . `` Source : nullStackTrace : nullTargetSite : null { 1/26/2015 12:00:00 AM } Date : { 1/26/2015 12:00:00 AM } Day : 26DayOfWeek : MondayDayOfYear : 26Hour : 0Kind : UnspecifiedMillisecond : 0Minute : 0Month : 1Second : 0Ticks : 635578272000000000TimeOfDay : { System.TimeSpan } Year : 2015 { 1/26/2015 12:00:00 AM } Date : { 1/26/2015 12:00:00 AM } Day : 26DayOfWeek : MondayDayOfYear : 26Hour : 0Kind : UnspecifiedMillisecond : 0Minute : 0Month : 1Second : 0Ticks : 635578272000000000TimeOfDay : { 00:00:00 } Year : 2015",Immediate Window - Cast as datetime ? throws exception but ( datetime ) does n't "C_sharp : Need to pass array as a command line argument to Asp.Net Core hosted service . Added providerssomewhere in application I have Try to run app likebut no results , the actions is nullWhen I add `` actions '' : [ `` Action1 '' , '' Action2 '' ] to appsettings.json then binding works well . How to pass array as a command line argument ? I can get it in this way _configuration.GetValue < string > ( `` actions '' ) .Split ( `` , '' ) ; , but how to bind it to list ? config .AddJsonFile ( `` appsettings.json '' ) .AddCommandLine ( args ) ; var actions = _configuration.GetSection ( `` actions '' ) .Get < List < string > > ( ) ; foreach ( var action in actions ) { Console.WriteLine ( action ) ; } dotnet MyService.dll -- actions Action1 , Action2dotnet MyService.dll -- actions [ Action1 , Action2 ] dotnet MyService.dll -- actions [ `` Action1 '' , '' Action2 '' ]",Pass array as a command line argument to Asp.Net Core "C_sharp : I have an ASP.NET application that presents a simple form to upload files ( images ) . That looks like this : This form in the application works fine . The problem is that I want to use Microsoft Flow to submit files that come into a SharePoint library over to the web application defined above.I have the file flow setup and it runs and does n't error out , but when I look at the body of the HTTP action 's result it says 0 files processed and nothing gets done.The Flow that I have setup is When a file is created ( SharePoint ) ( this is pointing to a specific document libraryHttp ( Http ) , Method : Post , Uri ( pointing to my app ) , Body : File Content from the SharePoint step above.As I mentioned this is posting to the site , but must not be passing in the file in a way that the ASP.NET method can handle , so it is not processing anything . How can I change either the flow or the Post method , so that it will work.Updated with new informationI have tried this with a very small image , so I can get some additional Request information . Using the form in the browser I tried this and going the following Request Raw result using Fiddler : Doing the same image through flow I get the following as the body in flow : So it looks like flow is submitting as JSON . I 'm going to try some additional processing now as a test , but if anybody knows what I can put in the Web app to handle this I would greatly appreciate it.I added a new method see below that works when I run it locally passing in the string that Flow says is the body . But when I run it from flow I get value can not be null error in the DeserializeObject line . How can I get the information that Flow is passing in . I have also tried a method with this signature , but no luck there either it comes in as nullI added some middleware , so that I could get the raw Request.Body and the end result that comes from that is this . I 'm not sure what this equates to . public IActionResult Process ( ) { return View ( ) ; } [ HttpPost ] public IActionResult Process ( List < IFormFile > files ) { var telemetry = new TelemetryClient ( ) ; try { var result = files.Count + `` file ( s ) processed `` + Environment.NewLine ; foreach ( var file in files ) { result += file.FileName + Environment.NewLine ; var memoryStream = new MemoryStream ( ) ; file.CopyTo ( memoryStream ) ; memoryStream.Seek ( 0 , SeekOrigin.Begin ) ; var binaryReader = new BinaryReader ( memoryStream ) ; var bytes = binaryReader.ReadBytes ( ( int ) memoryStream.Length ) ; var imageInformation = ImageService.ProcessImage ( bytes ) ; ImageService.SaveImage ( imageInformation.Result , bytes , file.FileName.Substring ( file.FileName.LastIndexOf ( `` . `` , StringComparison.Ordinal ) + 1 ) ) ; } return View ( ( object ) result ) ; } catch ( Exception ex ) { telemetry.TrackException ( ex ) ; throw ; } } POST https : //os-gbsphotoretain.azurewebsites.net/Image/Process HTTP/1.1Host : os-gbsphotoretain.azurewebsites.netConnection : keep-aliveContent-Length : 924Pragma : no-cacheCache-Control : no-cacheOrigin : https : //os-gbsphotoretain.azurewebsites.netUpgrade-Insecure-Requests : 1User-Agent : Mozilla/5.0 ( Windows NT 10.0 ; Win64 ; x64 ) AppleWebKit/537.36 ( KHTML , like Gecko ) Chrome/60.0.3112.90 Safari/537.36Content-Type : multipart/form-data ; boundary= -- -- WebKitFormBoundarySjQVgrsvAqJYXmSTAccept : text/html , application/xhtml+xml , application/xml ; q=0.9 , image/webp , image/apng , */* ; q=0.8Referer : https : //os-gbsphotoretain.azurewebsites.net/Image/ProcessAccept-Encoding : gzip , deflate , brAccept-Language : en-US , en ; q=0.8Cookie : _ga=GA1.3.955734319.1501514097 ; ai_user=UkqSf|2017-07-31T15:17:38.409Z ; ARRAffinity=1628d46398b292eb2e3ba76b4b0f1eb1e30abd9bd1036d7a90b9c51f7baa2306 ; ai_session=/fPFh|1502738361594.15|1502738361594.15 -- -- -- WebKitFormBoundarySjQVgrsvAqJYXmSTContent-Disposition : form-data ; name= '' files '' ; filename= '' printer.jpg '' Content-Type : image/jpeg JFIF ` ` C $ . ' `` , # ( 7 ) ,01444 ' 9=82 < .342 C 2 ! ! 22222222222222222222222222222222222222222222222222 `` } ! 1AQa `` q2 # B R $ 3br % & ' ( ) *456789 : CDEFGHIJSTUVWXYZcdefghijstuvwxyz w ! 1AQ aq '' 2 B # 3R br $ 4 % & ' ( ) *56789 : CDEFGHIJSTUVWXYZcdefghijstuvwxyz ? +X K 21 c Z ] ӥg v ; : P I f > m ; ] ֬u nm ` Q 1 P6 s 9 |b r| G -- -- -- WebKitFormBoundarySjQVgrsvAqJYXmST -- { `` $ content-type '' : `` image/jpeg '' , `` $ content '' : `` /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAQABADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD1C9EMuqzGK1juS+3P7rccgc4yMYxjv1q/ol0I4bfTpQVniXaoyDuQHjoTg7ccGsDU7O+0+xEdoJfMUKiKE84MB/dJ5B9mzj6VneFtO1271qx1G+hubaGBjmCSUfMSMZZQNoxzgDnPfGKqcnypEJW1R//Z '' } [ HttpPost ] public IActionResult ProcessJson ( string json ) { var telemetry = new TelemetryClient ( ) ; try { var result = `` JSON processed `` + Environment.NewLine ; var details = ( dynamic ) Newtonsoft.Json.JsonConvert.DeserializeObject ( json ) ; var content = ( string ) details [ `` $ content '' ] ; var bytes = Convert.FromBase64String ( content ) ; ProcessBytes ( bytes , `` jpeg '' ) ; return View ( `` Process '' , result ) ; } catch ( Exception ex ) { telemetry.TrackException ( ex ) ; throw ; } } [ HttpPost ] public IActionResult ProcessJson ( [ FromBody ] FlowFile file ) { ... } public class FlowFile { [ JsonProperty ( PropertyName = `` $ content-type '' ) ] public string ContentType { get ; set ; } [ JsonProperty ( PropertyName = `` $ content '' ) ] public string Content { get ; set ; } } & # xD ; & # xA ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x0 ; & # x10 ; JFIF & # x0 ; & # x1 ; & # x1 ; & # x1 ; & # x0 ; ` & # x0 ; ` & # x0 ; & # x0 ; & # xFFFD ; & # xFFFD ; & # x0 ; C & # x0 ; & # x8 ; & # x6 ; & # x6 ; & # x7 ; & # x6 ; & # x5 ; & # x8 ; & # x7 ; & # x7 ; & # x7 ; & # x9 ; & # x9 ; & # x8 ; & # xA ; & # xC ; & # x14 ; & # xD ; & # xC ; & # xB ; & # xB ; & # xC ; & # x19 ; & # x12 ; & # x13 ; & # xF ; & # x14 ; & # x1D ; & # x1A ; & # x1F ; & # x1E ; & # x1D ; & # x1A ; & # x1C ; & # x1C ; $ . & # x27 ; & quot ; , # & # x1C ; & # x1C ; ( 7 ) ,01444 & # x1F ; & # x27 ; 9=82 & lt ; .342 & # xFFFD ; & # xFFFD ; & # x0 ; C & # x1 ; & # x9 ; & # x9 ; & # x9 ; & # xC ; & # xB ; & # xC ; & # x18 ; & # xD ; & # xD ; & # x18 ; 2 ! & # x1C ; ! 22222222222222222222222222222222222222222222222222 & # xFFFD ; & # xFFFD ; & # x0 ; & # x11 ; & # x8 ; & # x0 ; & # x10 ; & # x0 ; & # x10 ; & # x3 ; & # x1 ; & quot ; & # x0 ; & # x2 ; & # x11 ; & # x1 ; & # x3 ; & # x11 ; & # x1 ; & # xFFFD ; & # xFFFD ; & # x0 ; & # x1F ; & # x0 ; & # x0 ; & # x1 ; & # x5 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x1 ; & # x2 ; & # x3 ; & # x4 ; & # x5 ; & # x6 ; & # x7 ; & # x8 ; & # x9 ; & # xA ; & # xB ; & # xFFFD ; & # xFFFD ; & # x0 ; & # xFFFD ; & # x10 ; & # x0 ; & # x2 ; & # x1 ; & # x3 ; & # x3 ; & # x2 ; & # x4 ; & # x3 ; & # x5 ; & # x5 ; & # x4 ; & # x4 ; & # x0 ; & # x0 ; & # x1 ; } & # x1 ; & # x2 ; & # x3 ; & # x0 ; & # x4 ; & # x11 ; & # x5 ; & # x12 ; ! 1A & # x6 ; & # x13 ; Qa & # x7 ; & quot ; q & # x14 ; 2 & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x8 ; # B & # xFFFD ; & # xFFFD ; & # x15 ; R & # xFFFD ; & # xFFFD ; $ 3br & # xFFFD ; & # x9 ; & # xA ; & # x16 ; & # x17 ; & # x18 ; & # x19 ; & # x1A ; % & amp ; & # x27 ; ( ) *456789 : CDEFGHIJSTUVWXYZcdefghijstuvwxyz & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x0 ; & # x1F ; & # x1 ; & # x0 ; & # x3 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x1 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x0 ; & # x1 ; & # x2 ; & # x3 ; & # x4 ; & # x5 ; & # x6 ; & # x7 ; & # x8 ; & # x9 ; & # xA ; & # xB ; & # xFFFD ; & # xFFFD ; & # x0 ; & # xFFFD ; & # x11 ; & # x0 ; & # x2 ; & # x1 ; & # x2 ; & # x4 ; & # x4 ; & # x3 ; & # x4 ; & # x7 ; & # x5 ; & # x4 ; & # x4 ; & # x0 ; & # x1 ; & # x2 ; w & # x0 ; & # x1 ; & # x2 ; & # x3 ; & # x11 ; & # x4 ; & # x5 ; ! 1 & # x6 ; & # x12 ; AQ & # x7 ; aq & # x13 ; & quot ; 2 & # xFFFD ; & # x8 ; & # x14 ; B & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x9 ; # 3R & # xFFFD ; & # x15 ; br & # xFFFD ; & # xA ; & # x16 ; $ 4 & # xFFFD ; % & # xFFFD ; & # x17 ; & # x18 ; & # x19 ; & # x1A ; & amp ; & # x27 ; ( ) *56789 : CDEFGHIJSTUVWXYZcdefghijstuvwxyz & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x0 ; & # xC ; & # x3 ; & # x1 ; & # x0 ; & # x2 ; & # x11 ; & # x3 ; & # x11 ; & # x0 ; ? & # x0 ; & # xFFFD ; & # xB ; & # xFFFD ; & # xC ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x2B ; X & # xFFFD ; K & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x1C ; & # xFFFD ; & # xFFFD ; 21 & # xFFFD ; c & # xFFFD ; Z & # xFFFD ; & # xFFFD ; ] & # x8 ; & # xFFFD ; & # x4E5 ; & # x5 ; g & # xFFFD ; v & # xFFFD ; & # xFFFD ; ; & # xFFFD ; & # x1E ; : & # x13 ; & # xFFFD ; & # xFFFD ; & # x1C ; & # x1A ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # xFFFD ; & # x11 ; & # x1D ; & # xFFFD ; & # xFFFD ; & # xFFFD ; P & # xFFFD ; & # xFFFD ; & # x13 ; & # xFFFD ; & # xC ; & # x7 ; & # xFFFD ; I & # xFFFD ; & # x1F ; f & # xFFFD ; & gt ; & # xFFFD ; & # xFFFD ; & # xFFFD ; m ; ] & # xFFFD ; & # x5AC ; u & # x1B ; & # xFFFD ; nm & # xFFFD ; & # xFFFD ; & # xFFFD ; ` & # xFFFD ; Q & # xFFFD ; & # x12 ; 1 & # xFFFD ; P6 & # xFFFD ; s & # xFFFD ; 9 & # xFFFD ; |b & # xFFFD ; r| & # xFFFD ; & # x10 ; & # xFFFD ; & # xFFFD ; G & # xFFFD ;",How to submit a file to an ASP.NET Core application "C_sharp : I 'm trying to use ILMerge to combine my C # program with 3 referenced DLL 's . If I run the program without merging them , everything runs well but when I merge them I get the `` Void System.Threading.Monitor.Enter '' Error.Here are the DLL 's I am combining : The error appears to be coming from the MySql.Data.dll but I am not really sure why it would throw this exception.Any ideas much appreciated.EDIT : Full error I am receiving is : HTMLAgilityPack.dllMySql.Data.dllRKLib.ExportData.dll ************** Exception Text **************System.MissingMethodException : Method not found : 'Void System.Threading.Monitor.Enter ( System.Object , Boolean ByRef ) '.at MySql.Data.MySqlClient.MySqlConnection.set_ConnectionString ( String value ) at MySql.Data.MySqlClient.MySqlConnection..ctor ( String connectionString ) in : line 0",Void System.Threading.Monitor.Enter Error when using ILMerge "C_sharp : This is my function . I already wrapped both client and message into using clause and still get error when run code inspection . Error points to first using line : This is warning I get : Warning 1 CA2000 : Microsoft.Reliability : In method 'Email.Send ( MailItem ) ' , object ' < > g_initLocal0 ' is not disposed along all exception paths . Call System.IDisposable.Dispose on object ' < > g_initLocal0 ' before all references to it are out of scope . C : \CodeWorkspace\Code\Utility\Email.cs 41 public static void Send ( MailItem mail ) { var sender = Membership.GetUser ( mail.CreatedBy ) ; if ( sender == null ) { return ; } using ( var msg = new MailMessage { From = new MailAddress ( ConfigurationManager.AppSettings [ `` EmailSender '' ] , ConfigurationManager.AppSettings [ `` EmailSenderName '' ] ) } ) { foreach ( var recipient in mail.MailRecipients ) { var recipientX = Membership.GetUser ( recipient.UserKey ) ; if ( recipientX == null ) { continue ; } msg.To.Add ( new MailAddress ( recipientX.Email , recipientX.UserName ) ) ; } msg.Subject = `` [ From : `` + sender.UserName + `` ] '' + mail.Subject ; msg.Body = mail.Body ; if ( HttpContext.Current ! = null ) { msg.Body += Environment.NewLine + Environment.NewLine + `` To reply via Web click link below : '' + Environment.NewLine ; msg.Body += ConfigurationManager.AppSettings [ `` MailPagePath '' ] + `` ? AID= '' + ContextManager.CurrentAccount.AccountId + `` & RUN= '' + sender.UserName ; } try { using ( var emailClient = new SmtpClient ( ) ) { emailClient.Send ( msg ) ; } } catch ( Exception ex ) { Logger.LogException ( ex ) ; } } }",Code inspection says I need to dispose object . Which one ? "C_sharp : So I have this bit of code , if I break point on the return statement the immediate window outputs the information below.Stored ProcedureHere is the relevant parts of the stored procedure . @ HasAuthTable and @ IsAuthorized are of the type bit.Immediate WindowI 've tried Rebuilding the solution did n't change anything . I have also tried restarting Visual Studio . No luck . Is this intended behavior ? It seems like a bug.Altered Stored ProcedureI tried changing the output of the stored procedure to match the following to see if it affects it in any way . The result is basically the same . static type of object with the expected dynamic type , both having values but still returning false for obj == null and obj ! = null.Respective Immediate Window try { await connection.OpenAsync ( ) ; var obj = await cmd.ExecuteScalarAsync ( ) ; return obj ! = null ? Int32.Parse ( obj.ToString ( ) ) ! = 1 : false ; } catch ( Exception ex ) { Log.Error ( `` An error has occurred checking a customer/product authorization . `` , ex ) ; return false ; } finally { connection.Close ( ) ; } SELECT ( CASE WHEN @ HasAuthTable = 0 THEN 1 ELSE 0 END ) | @ IsAuthorized AS IsAuthorized obj0obj == nullfalseobj ! = nullfalseobj == 0error CS0019 : Operator '== ' can not be applied to operands of type 'object ' and 'int'obj ! = 0error CS0019 : Operator ' ! = ' can not be applied to operands of type 'object ' and 'int ' ( int ) obj == 0true ( int ) obj ! = 0falseobj.GetType ( ) .FullName '' System.Int32 '' obj.Equals ( null ) false ! obj.Equals ( null ) trueObject.ReferenceEquals ( obj , null ) false ! Object.ReferenceEquals ( obj , null ) false SELECT CAST ( ( ( CASE WHEN @ HasAuthTable = 0 THEN 1 ELSE 0 END ) | @ IsAuthorized ) AS BIT ) AS IsAuthorized objfalseobj ! = nullfalseobj == nullfalseobj.GetType ( ) .FullName '' System.Boolean ''",How can an object be null and not null at the same time ? "C_sharp : I have a Winforms application that the user uses to take a region based screenshot . I want to have a small preview pane , but i 'm not sure how to do it . So far i tried recreating a bitmap on mouse move and its just way too laggy to be usable . So i thought if i used a pre-defined image ( screenshot of the whole screen ) and moved it inside the picturebox based off the mouse location so that you get a zoomed in look at the screen ( to select the precise pixels you want to take the screenshot with easier ) . I 'm not sure how i can implement this , i am also pretty new to drawing so i will show you what i have now.EDIT : Here is a mock up like requested : The black part of this image is a panel , of course the text being a label and the area where you see the image ( stack overflow ) would be the picturebox ( called zoomBox ) the lines on top of the zoomBox would be a guide and where the 2 lines intersect would be the mouse position . Hope this is a better assist to help you understand my issue . Another thing that might help explain my issue is The form actually fills the entire screen with a `` false desktop '' . its a picturebox that covers the entire screen with a screenshot of the desktop when `` printscreen '' was pressed . So I want this little `` preview pane '' to basically be a zoomed in location of where the mouse is . private void falseDesktop_MouseMove ( object sender , MouseEventArgs e ) { zoomBox.Image = showZoomBox ( e.Location ) ; zoomBox.Invalidate ( ) ; } private Image showZoomBox ( Point curLocation ) { int x = 0 ; int y = 0 ; if ( curLocation.X - 12 < = 0 ) { x = curLocation.X - 12 ; } else { x = curLocation.X ; } if ( curLocation.Y - 11 < = 0 ) { y = curLocation.Y - 11 ; } else { y = curLocation.Y ; } Point start = new Point ( curLocation.X - 12 , curLocation.Y - 11 ) ; Size size = new Size ( 24 , 22 ) ; Rectangle rect = new Rectangle ( start , size ) ; Image selection = cropImage ( falseDesktop.Image , rect ) ; return selection ; } private static Image cropImage ( Image img , Rectangle cropArea ) { if ( cropArea.Width ! = 0 & & cropArea.Height ! = 0 ) { Bitmap bmpImage = new Bitmap ( img ) ; Bitmap bmpCrop = bmpImage.Clone ( cropArea , bmpImage.PixelFormat ) ; bmpImage.Dispose ( ) ; return ( Image ) ( bmpCrop ) ; } return null ; }",How to draw a screenshot `` preview '' window ? "C_sharp : I 'm trying to fill an array with characters from a string inputted via console . I 've tried the code bellow but it doesnt seem to work . I get Index out Of Range exception in the for loop part , and i did n't understand why it occured . Is the for loop range incorrect ? Any insight would be greatly appreciated Console.WriteLine ( `` Enter a string : `` ) ; var name = Console.ReadLine ( ) ; var intoarray = new char [ name.Length ] ; for ( var i = 0 ; i < = intoarray.Length ; i++ ) { intoarray [ i ] = name [ i ] ; } foreach ( var n in intoarray ) Console.WriteLine ( intoarray [ n ] ) ;",Filling a character array with characters from a string "C_sharp : I have a sequence of type IObservable < T > and a function that maps T , CancellationToken to a Task < U > . What 's the cleanest way of getting an IObservable < U > out of them ? I need the following semantics : each tasks starts after the previous item 's task has finishedif a task has been cancelled or faulted , it is skippedthe order of the original sequence is strictly preservedHere 's the signature as I see it : I have n't written any code yet but I will unless someone beats me to it.In any case , I 'm not familiar with operators like Window , so my solution will likely be less elegant . I need the solution in C # 4 , but C # 5 answers are also welcome for the sake of comparison.If you 're curious , below is my real-world scenario , more or less : public static IObservable < U > Select < T , U > ( this IObservable < T > source , Func < T , CancellationToken , Task < U > > selector ) ; Dropbox.GetImagesRecursively ( ) .ObserveOn ( SynchronizationContext.Current ) .Select ( DownloadImage ) .Subscribe ( AddImageToFilePicker ) ;",How do I create an Rx sequence by running tasks over original sequence 's values ? "C_sharp : I am developing a WPF application and in one window I used a wizard component from WPF toolkit . In this wizard I 'm creating a new person . In second step I am using an enumeration as a source for possible contact types ( for example Phone , Email ... ) . This is my wizard page in XAML : The source of ItemsControl is a List of PersonContactModel class : the base class implement a IDataErrorInfo interface with validation info about Contact property.The desired behavior is that if the checkbox is checked , it is visible grid with a field for entering a contact , otherwise not . Button next step should be seen only when selected contact types are valid . This functionality is trying to accomplish the following styles in app.xaml : Unfortunately , the button for the next step is invisible , even if it asks all kinds of contact for the new person and will fulfill all the conditions for a valid entry.What 's wrong ? Where is an error ? < xctk : WizardPage x : Name= '' NewContactPage '' PageType= '' Interior '' Title= '' Contacts '' Style= '' { DynamicResource NewContactPage } '' CanCancel= '' True '' CanFinish= '' False '' Loaded= '' NewContactPage_Loaded '' PreviousPage= '' { Binding ElementName=NewPersonPage } '' > < Grid HorizontalAlignment= '' Stretch '' VerticalAlignment= '' Top '' > < control : DataLoader x : Name= '' ctrNewContactLoader '' / > < StackPanel HorizontalAlignment= '' Stretch '' VerticalAlignment= '' Top '' Orientation= '' Vertical '' > < ItemsControl ItemsSource= '' { Binding Path=Person.PersonContacts , Mode=TwoWay , RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType=Window } } '' Name= '' icContacts '' > < ItemsControl.ItemTemplate > < ItemContainerTemplate > < StackPanel HorizontalAlignment= '' Stretch '' VerticalAlignment= '' Top '' Orientation= '' Vertical '' Margin= '' 5 '' Background= '' WhiteSmoke '' > < CheckBox IsChecked= '' { Binding Path=IsValid } '' Content= '' { Binding Path=ContactType.Description } '' Name= '' cbContactVisible '' / > < Grid HorizontalAlignment= '' Stretch '' VerticalAlignment= '' Top '' Visibility= '' { Binding ElementName=cbContactVisible , Path=IsChecked , Converter= { StaticResource BooleanToVisibilityConverter } } '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < Grid.RowDefinitions > < RowDefinition Height= '' auto '' / > < /Grid.RowDefinitions > < TextBox Grid.Row= '' 0 '' Grid.Column= '' 0 '' HorizontalAlignment= '' Stretch '' MaxLength= '' 64 '' Name= '' txtContactValue '' Text= '' { Binding Path=Contact , ValidatesOnDataErrors=True , ValidatesOnNotifyDataErrors=True , ValidatesOnExceptions=True } '' / > < /Grid > < /StackPanel > < /ItemContainerTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl > < /StackPanel > < /Grid > public class PersonContactModel : BaseObjectModel { public PersonContactModel ( ) { this.Created = DateTime.Now ; this.Updated = DateTime.Now ; this.IsValid = true ; this.ContactType = new ContactTypeModel ( ) ; } public string Contact { get ; set ; } public ContactTypeModel ContactType { get ; set ; } public DateTime Created { get ; set ; } public int Id { get ; set ; } public bool IsValid { get ; set ; } public DateTime Updated { get ; set ; } public override string this [ string columnName ] { get { string retVal = string.Empty ; switch ( columnName ) { case `` Contact '' : retVal = base.Concat ( base.RequeiredField ( this.Contact ) , base.MinLength ( this.Contact , 5 ) , base.MaxLength ( this.Contact , 62 ) ) ; break ; } return retVal ; } } } < Style TargetType= '' xctk : WizardPage '' x : Key= '' NewContactPage '' > < Setter Property= '' NextButtonVisibility '' Value= '' Hidden '' / > < Style.Triggers > < MultiDataTrigger > < MultiDataTrigger.Conditions > < Condition Binding= '' { Binding Path= ( Validation.HasError ) , ElementName=txtContactValue } '' Value= '' False '' / > < /MultiDataTrigger.Conditions > < Setter Property= '' NextButtonVisibility '' Value= '' Visible '' / > < /MultiDataTrigger > < /Style.Triggers > < /Style >",Validating items in ItemsControl "C_sharp : I have a simple interfaceTo `` make '' it asynchronous , I would do thisAlthough the interface now hints that GetSomething is asynchronous , it allows synchronous execution , which is fine if the synchronous result is sufficiently fast . If it blocks , then I can assign the blame to poor implementation of the interface by the implementing programmer.So if the latter interface is implemented by a sufficiently fast blocking implementation , then the latter interface is more flexible than the former and thus preferable.In that case , should I rewrite all my interfaces to return tasks if there is the slightest chance that a call to a method will take more than some time ? EDIT : I would like to emphasize that this is not a question about what Tasks are or how they work , but instead a design question relating to the inherent unknown implementation of interfaces when defining them . When writing an interface , it appears beneficial to allow for synchronous and asynchronous implementation alike.A third `` solution '' could be some amalgamation of the two previous : but this breaks the Liskov substitution principle and adds nothing but confusion to the implementer . public interface SomethingProvider { public Something GetSomething ( ) ; } public interface SomethingProvider { public Task < Something > GetSomethingAsync ( ) ; } public interface SomethingProvider { public Something GetSomething ( ) ; public Task < Something > GetSomethingAsync ( ) ; }",Should all interfaces be re-written to return Task < Result > ? "C_sharp : Can you boostrap a Prism module system from within the WCF service ? Because no matter what I do my MEF dependencies are not being fulfilled.E.g . : This is my WCF service implementationThis is my Prism boostrapper with MEF flavor : Here is my module that contains the interfaces for Database Prism service : and lastly here is the Prism database service itself : Tried this for the last few hours with no success . My db import is always null and is never initialized . Note , that everything works if I do all of this without Prism , but only with MEF . public class MyService : IMyServiceContract { // This should get filled by MEF after Prism loads the required modules [ Import ] IDatabase db ; public MyService ( ) { var bootsrapper = new MyServiceBoostrapper ( ) ; bootsrapper.Run ( ) ; } } public class MyServiceBoostrapper : MefBootstrapper { protected override void ConfigureContainer ( ) { base.ConfigureContainer ( ) ; } protected override IModuleCatalog CreateModuleCatalog ( ) { return new ConfigurationModuleCatalog ( ) ; } protected override void ConfigureAggregateCatalog ( ) { base.ConfigureAggregateCatalog ( ) ; // TODO : Add this assembly ... do n't know why this.AggregateCatalog.Catalogs.Add ( new AssemblyCatalog ( typeof ( MyServiceBoostrapper ) .Assembly ) ) ; this.AggregateCatalog.Catalogs.Add ( new AssemblyCatalog ( typeof ( IDatabase ) .Assembly ) ) ; // This is what provides the service this.AggregateCatalog.Catalogs.Add ( new AssemblyCatalog ( typeof ( DatabaseImpl ) .Assembly ) ) ; } protected override DependencyObject CreateShell ( ) { // we do n't need the shell return null ; } } [ ModuleExport ( typeof ( IDatabase ) ) ] public class ModuleActivator : IModule { public void Initialize ( ) { // Do nothing as this module simply provides the API . } } public interface IDatabase { // interface methods here ... } [ ModuleExport ( typeof ( DatabaseImpl ) , DependsOnModuleNames = new string [ ] { `` IDatabase '' } ) ] public class ModuleActivator : IModule { public void Initialize ( ) { // Do nothing as this is a library module . } } [ Export ( typeof ( IDatabase ) ) ] public class DatabaseImpl : IDatabase { /// implementation here ... }",Prism module system from within WCF service ? "C_sharp : Possible Duplicate : Does C # optimize the concatenation of string literals ? I just found out that we write a line like this : However I opened the string class through reflector and I do n't see where this + operator is overloaded ? I can see that == and ! = are overloaded.So why does concat gets called when we use + for combining strings ? Thanks . string s = `` string '' ; s = s + s ; // this translates to s = string.concat ( `` string '' , `` string '' ) ; [ TargetedPatchingOptOut ( `` Performance critical to inline across NGen image boundaries '' ) ] public static bool operator == ( string a , string b ) { return string.Equals ( a , b ) ; } [ TargetedPatchingOptOut ( `` Performance critical to inline across NGen image boundaries '' ) ] public static bool operator ! = ( string a , string b ) { return ! string.Equals ( a , b ) ; }",C # + operator calls string.concat function ? "C_sharp : Suppose I have a member variable in a class ( with atomic read/write data type ) : And later I create a task to set it to true : I do n't care when exactly m_Done will be set to true.My question is do I have a guarantee by the C # language specification and the Task parallel library thateventually m_Done will be true if I 'm accessing it from a different thread ? Example : I know that using locks will introduce the necessary memory barriers and m_Done will be visible as true later.Also I can use Volatile.Write when setting the variable and Volatile.Read whenreading it.I 'm seeing a lot of code written this way ( without locks or volatile ) and I 'm not sure if it is correct.Note that my question is not targeting a specific implementation of C # or .Net , it is targeting the specification.I need to know if the current code will behave similarly if running on x86 , x64 , Itanium or ARM . bool m_Done = false ; Task.Run ( ( ) = > m_Done = true ) ; if ( m_Done ) { // Do something }",C # variable freshness "C_sharp : I spent some days testing MassTransit 3.1.2 to see if we can use it with Azure Service Bus in our applications.I made a sample with two console applications using MassTransit.AzureServiceBus ( 3.1.2 ) : one publisher and one suscriber . It works well . When I start the applications , the entities ( queues , topic , subscriptions ) are created automatically on my namespace on Azure.That 's nice when you are testing thing but in production , I do n't want the application to be allowed to create entities . We want to create them upfront.To try that , I thought It was a good idea to connect to the bus using SAS policy with `` Send '' or `` Listen '' permissions only ( before I was using a namespace policy with `` Manage '' permission ) .Now I 'm struggling on this point , I ca n't get it to work , I 'm always getting 401 errors Manage claim is required for this operation if I do n't use a policy with `` Manage '' permissions.I tried setting the policy on the namespace or the entities directly without success . After that I analyzed the stack trace exception ( useless part omitted with [ ... ] ) : I found out that the line with MassTransit.AzureServiceBusTransport.NamespaceManagerExtensions.CreateQueueSafeAsync to be really interesting because I was able to look at the MassTransit source code to see what it was doing . I saw that it was doing some calls using the NamespaceManager to get the queue or topic.Since this class is named NamespaceManager , I thought that would mean you need `` Manage '' permission anyway.To try that , I made a basic console application using only the Azure SDK to make some calls to the NamespaceManager using a policy with only Listen or Send permissions : I got 401 errors on all the calls I tried . Adding Manage permission worked.I did n't find anything about this assumption in the Azure documentation or maybe I missed something.Final question : Is there a way to use MassTransit on Azure Service Bus with a Send or Listen policy only ? Did I miss something and I 'm heading the wrong way ? System.UnauthorizedAccessException : Le serveur distant a retourné une erreur : ( 401 ) Non autorisé . Manage claim is required for this operation . TrackingId:2ca420e3-aac6-467c-bacb-6e051dbc3e39_G47 , TimeStamp:1/29/2016 11:20:41 PM -- - > System.Net.WebException : Le serveur distant a retourné une erreur : ( 401 ) Non autorisé . à System.Net.HttpWebRequest.EndGetResponse ( IAsyncResult asyncResult ) à Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.GetAsyncResult ` 1. < GetAsyncSteps > b__3c ( GetAsyncResult ` 1 thisPtr , IAsyncResult r ) à Microsoft.ServiceBus.Messaging.IteratorAsyncResult ` 1.StepCallback ( IAsyncResult result ) -- - Fin de la trace de la pile d'exception interne -- -Server stack trace : Exception rethrown at [ 0 ] : à Microsoft.ServiceBus.Common.ExceptionDispatcher.Throw ( Exception exception ) à Microsoft.ServiceBus.Common.AsyncResult.End [ TAsyncResult ] ( IAsyncResult result ) à Microsoft.ServiceBus.Common.AsyncResult ` 1.End ( IAsyncResult asyncResult ) à Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.EndGet [ TEntityDescription ] ( IAsyncResult asyncResult , String [ ] & resourceNames ) à Microsoft.ServiceBus.NamespaceManager.EndGetQueue ( IAsyncResult result ) à System.Threading.Tasks.TaskFactory ` 1.FromAsyncCoreLogic ( IAsyncResult iar , Func ` 2 endFunction , Action ` 1 endAction , Task ` 1 promise , Boolean requiresSynchronization ) -- - Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée -- - [ ... ] à MassTransit.AzureServiceBusTransport.NamespaceManagerExtensions. < CreateQueueSafeAsync > d__1.MoveNext ( ) -- - Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée -- - [ ... ] à MassTransit.AzureServiceBusTransport.Pipeline.PrepareReceiveQueueFilter. < Send > d__5.MoveNext ( ) -- - Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée -- - [ ... ] à MassTransit.AzureServiceBusTransport.ServiceBusReceiveTransport. < > c__DisplayClass12_0. < < Receiver > b__0 > d.MoveNext ( ) -- - Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée -- - [ ... ] à MassTransit.Internals.Extensions.TaskExtensions. < WithCancellation > d__0 ` 1.MoveNext ( ) -- - Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception [ ... ] à MassTransit.MassTransitBus. < StartAsync > d__30.MoveNext ( ) -- - Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée -- - à System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ( ) à MassTransit.MassTransitBus. < StartAsync > d__30.MoveNext ( ) -- - Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée -- - à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess ( Task task ) à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification ( Task task ) à System.Runtime.CompilerServices.TaskAwaiter ` 1.GetResult ( ) à MassTransit.Util.TaskUtil.Await [ T ] ( Func ` 1 taskFactory , CancellationToken cancellationToken ) à MassTransit.MassTransitBus.MassTransit.IBusControl.Start ( )",Is it possible to use MassTransit 3 with Azure Service Bus without Manage permission policy ? "C_sharp : If I get the list of types in my AppDomain , is there an inherent ordering to these types ? This seems to produce a list that 's grouped by types in a namespace , but I ca n't see a pattern to the namespace groups themselves ( or the types within each namespace group ) . List < Type > myTypes = new List < Type > ( ) ; foreach ( Assembly a in AppDomain.CurrentDomain.GetAssemblies ( ) ) myTypes.AddRange ( a.GetTypes ( ) ) ;",What is the order of returned Types by Assembly.GetTypes ( ) ? C_sharp : I realized that in the Microsoft .NET Framework the void return type is a structure . Why ? ... public void TestMethod ( ) { } ...,Why is Void a structure ? "C_sharp : I 'm making a ASP.NET Core 1.1 app and trying to setup localization.When I make on my ValuesController the implementation of IStringLocalizer it works fine and localize my resource file.The code above locate my resources at `` Resources/Controllers/ValuesController.en-US.resx '' .But , when I try to inject the IStringLocalizer with a generic service it ca n't find my resource file.The code above does n't locate my resource at `` Resources/Services/Base/Service.en-US.resx '' Any idea on how to do it ? -- - EDITMyControl.Api ( Startup.cs ) namespace MyControl.ApiThis line is inside `` MyControl.Api '' , with is in the namespace `` MyControl.Api '' .The resources folder in this aplication work for `` Resources/Controllers '' My services are in namespace `` MyControl.Services '' The resources folder in this Project ( two projects inside same solution ) are '' Resources/Services/Base '' The namespace of my service file is `` MyControl.Services.Services.Base '' public ValuesController ( IStringLocalizer < ValuesController > localizer , IService < BaseEntity > service ) { _localizer = localizer ; _service = service ; } public class Service < T > : IService < T > where T : BaseEntity { # region Properties protected IRepository Repository { get ; set ; } protected IUnitOfWorkFactory UnitOfWorkFactory { get ; set ; } private readonly ILogger _logger ; private readonly IStringLocalizer _localizer ; # endregion # region Ctor public Service ( IRepository repository , IUnitOfWorkFactory unitOfWorkFactory , ILogger < Service < T > > logger , IStringLocalizer < Service < T > > localizer ) { Repository = repository ; UnitOfWorkFactory = unitOfWorkFactory ; _logger = logger ; _localizer = localizer ; } } services.AddLocalization ( options = > options.ResourcesPath = `` Resources '' ) ;",ASP.NET Core 1.1 Localization Generic Service "C_sharp : In my Page I have bottom command bar , and if that command bar is open and user clicks on SplitView menu than command bar is overlaying the menu.Below is the xaml of splitview page : Here 's the how I set commandbar on my content Page which is loaded into splitview rootFrame : Please check below screenshot , I have a Splitview with Green background and you can see that commandbar is overlapping on it.SplitView Issue ScreenshotHere is the demo application onedrive link < SplitView x : Name= '' NavigationSplitView '' DisplayMode= '' CompactOverlay '' IsPaneOpen= '' True '' CompactPaneLength= '' { StaticResource ShellCompactPaneSize } '' OpenPaneLength= '' 300 '' PaneBackground= '' { ThemeResource SplitViewBackgroundBrush } '' > < ! -- //App root frame where all content data will be loaded -- > < Frame x : Name= '' rootFrame '' / > < SplitView.Pane > ... < /SplitView.Pane > < /SplitView > < Page.BottomAppBar > < CommandBar x : Name= '' AppCommandBar '' Background= '' Transparent '' > < CommandBar.PrimaryCommands > < AppBarButton Name= '' Save '' Icon= '' Save '' Label= '' Save '' > < /AppBarButton > < AppBarButton Name= '' Clear '' Icon= '' ClearSelection '' Label= '' Clear '' > < /AppBarButton > < /CommandBar.PrimaryCommands > < /CommandBar > < /Page.BottomAppBar >",Page command bar overlaps Splitview Pane "C_sharp : I was roaming around in different sites for casting techniques and I constructed the following code to cast to from float to int as shown below But above code throws an InvalidCastException . Why is this ? I thought it is supposed to print 3,3 and 4 . var floatList = new float [ ] { 2.7f , 3.1f , 4.5f } ; var intList = from int test1 in floatList select test1 ; foreach ( var v in intList ) Console.Write ( `` { 0 } `` , v.ToString ( ) ) ;",LINQ query throws an InvalidCastException ? C_sharp : I would like to split a string into a String [ ] using a String as a delimiter.But the method above only works with a char as a delimiter.Any takers ? String delimit = `` [ break ] '' ; String [ ] tokens = myString.Split ( delimit ) ;,how do you split a string with a string in C # "C_sharp : Can someone tell me why the commented line of code ( one before last ) does not compile ? Is n't it the same as the line following it ? public struct OtherStruct { public int PublicProperty { get ; set ; } public int PublicField ; public OtherStruct ( int propertyValue , int fieldValue ) : this ( ) { PublicProperty = propertyValue ; PublicField = fieldValue ; } public int GetProperty ( ) { return PublicProperty ; } public void SetProperty ( int value ) { PublicProperty = value ; } } public struct SomeStruct { public OtherStruct OtherStruct { get ; set ; } } class Program { static void Main ( string [ ] args ) { SomeStruct a = new SomeStruct ( ) ; //a.OtherStruct.PublicProperty++ ; a.OtherStruct.SetProperty ( a.OtherStruct.GetProperty ( ) + 1 ) ; } }",Modifying nested structs in c # "C_sharp : According to the msdn documentation , a labelControl supports the getSupertip property for setting a tooltip on the ribbon control.For some reason though , the tooltip is n't working . An identical implementation works on other controls ( like button ) , but not labelControl . Furthermore , other callbacks such as getLabel work for the label , just not getSupertip.Any idea what 's wrong ? Ribbon XMLRibbon CodeImage of getLabel working for labelControl and getSupertip working on button only . < customUI xmlns= '' http : //schemas.microsoft.com/office/2006/01/customui '' > < ribbon > < tabs > < tab id= '' custom '' label= '' Custom AddIn '' > < group id= '' ConfigGroup '' label= '' Configuration '' > < labelControl id= '' lb1 '' getLabel= '' GetLabel '' getSupertip= '' GetSupertip '' / > < button id= '' bt1 '' label= '' Set Server URL '' getSupertip= '' GetSupertip '' / > ... < /group > < /tab > < /tabs > < /ribbon > < /customUI > public class CustomRibbon : ExcelRibbon , IExcelAddIn { public string GetSupertip ( IRibbonControl control ) { switch ( control.Id ) { case `` lb1 '' : return `` The current server address is : `` + API.serverURL ; case `` bt1 '' : return `` Click to change the server URL . ( Currently : `` + API.serverURL + `` ) '' ; } }",Ribbon labelControl GetSuperTip does n't work "C_sharp : I have an enum type for user privileges that looks like this : These values are bound to CheckBoxes in the GUI with a value converter . ( I wanted to do this as generic as possible because there are also different privileges [ e.g . EmployeePrivileges ] ) This works really fine for displaying and adding privileges to the user in the GUI . Also it works for removing Superflags like Supervisor ( all flags > = Supervisor get removed , the other flags do n't change ) .The problem is when I uncheck Import for example , I want to remove all Superflags ( Supervisor , Admin ) but would like to keep the other flags ( View , Export ) .But I have n't come up with an good idea how to accomplish this . Anyboy who has a good solution for this ? [ Flags ] public enum UserPrivileges : byte { None = 0 , // 0000 0000 View = 1 < < 0 , // 0000 0001 Import = 1 < < 1 , // 0000 0010 Export = 1 < < 2 , // 0000 0100 Supervisor = View | Import | Export | 1 < < 3 , // 0000 1111 Admin = Supervisor | 1 < < 4 // 0001 1111 } public class ByteFlagsEnumValueConverter : IValueConverter { private byte _targetValue ; public object Convert ( object value , Type targetType , object parameter , CultureInfo culture ) { var mask = ( byte ) parameter ; _targetValue = ( byte ) value ; return ( ( mask | _targetValue ) == _targetValue ) ; } public object ConvertBack ( object value , Type targetType , object parameter , CultureInfo culture ) { var mask = ( byte ) parameter ; if ( ( bool ) value ) { _targetValue |= mask ; } else { // Get next superflag for mask ( e.g . 0110 - > 1111 ) var b = mask ; b -- ; b |= ( byte ) ( b > > 1 ) ; b |= ( byte ) ( b > > 2 ) ; b |= ( byte ) ( b > > 4 ) ; b |= ( byte ) ( b > > 8 ) ; // if you remove a superflag ( e.g . 1111 ) also remove // everything higher than this flag if ( mask == b || mask == 1 ) _targetValue & = ( byte ) ( mask > > 1 ) ; else // ? ? ? ? ? ? ? ? } return Enum.Parse ( targetType , _targetValue.ToString ( ) ) ; } } 0001 1111 // Admin0000 0010 // Import -- -- -- -- -0000 0101 // View | Export",Remove privilege enum flags the right way in C # "C_sharp : I 'm trying to hide UWP application from taskbar.I found two way from this question for windows application but that 's not works in UWP.1.Delete WS_EX_TOOLWINDOW and add WS_EX_APPWINDOW to windows styles.2.Delete it from taskbar with ITaskbarList : :DeleteTab.I Have problem with handler . The MainWindowHandle is empty ! I know its because of the UWP , But how can I do it now ? Process [ ] p = Process.GetProcessesByName ( `` Microsoft.StickyNotes '' ) ; IntPtr windowHandle = p [ 0 ] .Handle ; var taskbarList = ( ITaskbarList ) new CoTaskbarList ( ) ; taskbarList.HrInit ( ) ; taskbarList.DeleteTab ( windowHandle ) ; //does n't do anything",Hiding UWP application from taskbar "C_sharp : I am currently reading the Microsoft Official Course books for C # programming , the first concept they introduce you to is Console.WriteLineThe actual code they give you to type is : I am not sure whether I am supposed to place this code under Form Load or using System because I always get the following error ( s ) and I am not sure what it implies : Error ... Debug\WindowsFormsApplication1.exe ' has more than one entry point defined : 'Hello.Main ( ) ' . Compile with /main to specify the type that contains the entry point . ** class Hello { public static void Main ( ) { Console.WriteLine ( `` Hello , World '' ) ; } }",Where should I place public static void Main ? "C_sharp : I 'm trying to sort a list of objects using List.Sort ( ) , but at runtime it tells me that it can not compare elements in the array . Failed to compare two elements in the arrayClass structure : Why can I not compare subclasses of a base that implements IComparable < T > ? I 'm probably missing something , but I can not see why this should not be allowed.Edit : Should clarify that I 'm targeting .NET 3.5 ( SharePoint 2010 ) Edit2 : .NET 3.5 is the problem ( see answer below ) . public abstract class Parent : IComparable < Parent > { public string Title ; public Parent ( string title ) { this.Title = title ; } public int CompareTo ( Parent other ) { return this.Title.CompareTo ( other.Title ) ; } } public class Child : Parent { public Child ( string title ) : base ( title ) { } } List < Child > children = GetChildren ( ) ; children.Sort ( ) ; //Fails with `` Failed to compare two elements in the array . ''",Why can I not use IComparable < T > on ancestor class and compare child classes ? "C_sharp : Hoping someone will be able to help out with this , I 've been looking round and I ca n't seem to find an answer anywhere.I 'm creating a mail message using that will be delivered to a specified pickup directory , this code has been used numerous times in the past without issue . Now though , when I inspect the resulting file and more specifically a URL within the eml file , I can see that in the middle there is a double .. From what I 've been reading , I understand that this is part of the SMTP protocol to dot stuff if the first character of a line in the message begins with .. This file is later going to be picked up by another service that will ultimately carry out the sending of the email . I 've been able to narrow it down to the exact line when I call client.Send ( ) . If I inspect the message body before the send , the URL is correctly formed . Inspecting the message body after I have called it , there is the .. present in the URL.My question , or questions I suppose , are as follows : Has anyone else come across an issue with dot stuffing when using SmtpDeliveryMethod.SpecifiedPickupDirectory ? Whose job is it to correctly handle this ? The .NET SMTP or the secondary service that picks this message up at a later date and sends it on to the final destination ? Any advice on how to resolve this ? I have previously tried the approach described here , but it fails with numerous exceptions . I 'm mainly looking for a way to save this eml file to a location on disk that can later be picked back up and sent , my knowledge on C # is still fairly limited so there may be something simple I am just over looking , so any advice or guidance would be hugely appreciated ! I have created a small sample piece of code to try and recreate the issue , this is n't the exact content I 'm using , but it does show that after sending via the client.Send ( ) method , there are 2 '.. ' at the start of the string . using ( var client = new SmtpClient ( ) ) { client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory ; client.PickupDirectoryLocation = @ '' C : \temp '' ; var message = new MailMessage ( ) ; message.To.Add ( new MailAddress ( `` alice @ a.com '' ) ) ; message.From = new MailAddress ( `` bob @ b.com '' ) ; message.Subject = `` Smtp Dot Stuffing Test '' ; message.Body = `` .A.B.C ... .. .0.1.2.3.4.5.6.7.8.9 '' ; client.Send ( message ) ; }",.NET 4.5 SMTP Client Dot Stuffing Issue when Delivering to Pickup Directory C_sharp : Does C # have any equivalent for VB6 With End With,"What is the equivalent syntax in C # , if any ?" "C_sharp : I have following XML : Now I sort users using following template : But I need sorting , wich satisfies following condition : Sort by Name . If Name is empty or null , I need to sort by LastName . So in produced XML I need following ordering : User3 , User2 , User1.Any help is appreciated . P.S . : I use ASP.NET 3.5 < Users > < User Id= '' 1 '' > < Name > abc < /Name > < LastName > d < /LastName > < /User > < User Id= '' 2 '' > < Name > < /Name > < LastName > ab < /LastName > < /User > < User Id= '' 3 '' > < Name > a < /Name > < LastName > efg < /LastName > < /User > < /Users > < xsl : template match= '' Users '' > < Users > < xsl : for-each select= '' User '' > < xsl : sort select= '' Name '' / > < xsl : sort select= '' LastName '' / > < User > < xsl : attribute name= '' Id '' > < xsl : value-of select= '' attribute : :Id '' / > < /xsl : attribute > < Name > < xsl : value-of select= '' Name '' / > < /Name > < LastName > < xsl : value-of select= '' LastName '' / > < /LastName > < /User > < /xsl : for-each > < /Users > < /xsl : template >",XSLT conditional sorting C_sharp : How would I convert the existing C # codeinto F # ? _containerBuilder = new ContainerBuilder ( ) ; _containerBuilder.RegisterGeneric ( typeof ( CommandObserver < > ) ) .As ( typeof ( ICommandObserver < > ) ) ; _containerBuilder.RegisterGeneric ( typeof ( PropertyProvider < > ) ) .As ( typeof ( IPropertyProvider < > ) ) ;,Autofac with F # "C_sharp : I want to bind multiple implementations of a service and have all of them called at once : Ninject does n't like that , and will throw an exception about having multiple bindings . Is there a way I can get around that error , and have all the implementations called ? Also , the Bind < > calls can be in different projects which may or may not be loaded at run-time , so creating a single implementation to call them wo n't work . This is part of a plug-in architecture for an ASP.NET MVC 3 web site . var kernel = new StandardKernel ( ) ; kernel.Bind < IBreakfast > .To < Spam > ( ) ; kernel.Bind < IBreakfast > .To < Eggs > ( ) ; kernel.Bind < IBreakfast > .To < MoreSpam > ( ) ; kernel.Get < IBreakfast > ( ) .Eat ( ) ; // call Eat method on all three bound implementations",Ninject Multicasting "C_sharp : I have an RSS feed like so : I am trying to get the url value of media : content , when I loop through the syndication items like so : I get blank data , how can I get the url of the media content ? < item > < title > Ellen celebrates the 20th anniversary of coming out episode < /title > < link > http : //www.dailymail.co.uk/video/tvshowbiz/video-1454179/Ellen-celebrates-20th-anniversary-coming-episode.html ? ITO=1490 & ns_mchannel=rss & ns_campaign=1490 < /link > < description > Ellen celebrates 20th anniversary of coming out episode on her old sitcom 'Ellen ' . Ellen said she cried during rehearsals but urged everyone to stay true to themselves and it will benefit you in the long term. < /description > < enclosure url= '' http : //i.dailymail.co.uk/i/pix/2017/04/27/00/3FA409EA00000578-0-image-m-21_1493249529333.jpg '' type= '' image/jpeg '' length= '' 7972 '' / > < pubDate > Thu , 27 Apr 2017 00:45:14 +0100 < /pubDate > < guid > http : //www.dailymail.co.uk/video/tvshowbiz/video-1454179/Ellen-celebrates-20th-anniversary-coming-episode.html ? ITO=1490 & ns_mchannel=rss & ns_campaign=1490 < /guid > < media : description/ > < media : thumbnail url= '' http : //i.dailymail.co.uk/i/pix/2017/04/27/00/3FA409EA00000578-0-image-m-21_1493249529333.jpg '' width= '' 154 '' height= '' 115 '' / > < media : credit scheme= '' urn : ebu '' > YouTube < /media : credit > < media : content url= '' http : //video.dailymail.co.uk/video/mol/2017/04/26/4464646762446275941/1024x576_MP4_4464646762446275941.mp4 '' type= '' video/mp4 '' medium= '' video '' duration= '' 245 '' lang= '' en '' / > < /item > foreach ( SyndicationItem item in feed.Items ) { foreach ( SyndicationElementExtension extension in item.ElementExtensions ) { XElement ele = extension.GetObject < XElement > ( ) ; MessageBox.Show ( ele.Value ) ; } }",Getting custom rss feed item element with syndicationitem ? "C_sharp : I want to create a map of these 2 models , how do I do this in code-first ? Payment can be either of type PaymentBank or PaymentCheque . I 'm trying to follow a scenario like this . I 'd love if I could do inheritance of this if possible , such as : public class Payment { public int PaymentId { get ; set ; } } public class PaymentBank { public int PaymentId { get ; set ; } } public class PaymentCheque { public int PaymentId { get ; set ; } } public class PaymentCheque : Payment { public int RoutingNumber { get ; set ; } }",Entity Framework Code First 0 to 1 mapping "C_sharp : I 'm getting heavy CPU usage when making calls to Cisco 's AXL SOAP API using WCF . I start by creating a service model clientbase using generated classes from wsdl . I 'm using basichttpbinding and transfermode as buffered . When executing a call , the CPU maxes out , and a CPU profile shows that 96 % of CPU time is at _TransparentProxyStub_CrossContext @ 0 from clr.dll that is called after calls such as base.Channel.getPhone ( request ) ; . More correctly , the call maxes out the CPU core that the process is running on.Here 's a snip of the client creation from the wsdl generateThis is how I create the client : The generated wsdl code for the AXL API is very large . Both initial and subsequent calls have the CPU issue , although subsequent calls are faster . Is there anything else I can do to debug this issue ? Is there a way to reduce this high CPU usage ? UpdateA bit more info with the bounty : I 've created the C # classes like so : You have to download the wsdl for Cisco 's AXL api from a call manager system . I 'm using the 10.5 version of the API . I believe the a major slowdown is related to XML processing . The WSDL for the api is huge with the resulting classes making a 538406 lines of code ! Update 2I 've turned on WCF tracing with all levels . The largest time difference is in the process action activity between `` A message was written '' and `` Sent a message over a channel '' in which nearly a full minute passes between these two actions . Other activities ( construct channel , open clientbase and close clientbase ) all execute relatively fast.Update 3I 've made two changes to the generated client classes . First , I removed the ServiceKnownTypeAttribute from all the operation contracts . Second , I removed the XmlIncludeAtribute from some of the serializable classes . These two changes reduced the file size of the generated client by more than 50 % and had a small impact on test times ( a reduction of about 10s on a 70s test result ) .I also noticed that I have roughly 900 operation contracts for a single service interface and endpoint . This is due to the wsdl for the AXL API grouping all operations under a single namespace . I 'm thinking about breaking this up , but that would mean creating multiple clientbases that would each implement a reduced interface and end up breaking everything that implements this wcf library.Update 4It looks like the number of operations is the central problem . I was able to separate out operations and interface definitions by verb ( e.g . gets , adds , etc ) into their own clientbase and interface ( a very slow process using sublime text and regex as resharper and codemaid could n't handle the large file that 's still 250K+ lines ) . A test of the `` Get '' client with about 150 operations defined resulted in a 10 second execution for getPhone compared to a previous 60 second result . This is still a lot slower than it should be as simply crafting this operation in fiddler results in a 2 second execution . The solution will probably be reducing the operation count even more by trying to separate operations further . However , this adds a new problem of breaking all systems that used this library as a single client . [ System.Diagnostics.DebuggerStepThroughAttribute ( ) ] [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.ServiceModel '' , `` 4.0.0.0 '' ) ] public partial class AXLPortClient : System.ServiceModel.ClientBase < AxlNetClient.AXLPort > , AxlNetClient.AXLPort { public AXLPortClient ( ) { } public AXLPortClient ( string endpointConfigurationName ) : base ( endpointConfigurationName ) { } ... public class AxlClientFactory : IAxlClientFactory { private const string AxlEndpointUrlFormat = `` https : // { 0 } :8443/axl/ '' ; public AXLPortClient CreateClient ( IUcClientSettings settings ) { ServicePointManager.ServerCertificateValidationCallback = ( sender , certificate , chain , errors ) = > true ; ServicePointManager.Expect100Continue = false ; var basicHttpBinding = new BasicHttpBinding ( BasicHttpSecurityMode.Transport ) ; basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic ; basicHttpBinding.MaxReceivedMessageSize = 20000000 ; basicHttpBinding.MaxBufferSize = 20000000 ; basicHttpBinding.MaxBufferPoolSize = 20000000 ; basicHttpBinding.ReaderQuotas.MaxDepth = 32 ; basicHttpBinding.ReaderQuotas.MaxArrayLength = 20000000 ; basicHttpBinding.ReaderQuotas.MaxStringContentLength = 20000000 ; basicHttpBinding.TransferMode = TransferMode.Buffered ; //basicHttpBinding.UseDefaultWebProxy = false ; var axlEndpointUrl = string.Format ( AxlEndpointUrlFormat , settings.Server ) ; var endpointAddress = new EndpointAddress ( axlEndpointUrl ) ; var axlClient = new AXLPortClient ( basicHttpBinding , endpointAddress ) ; axlClient.ClientCredentials.UserName.UserName = settings.User ; axlClient.ClientCredentials.UserName.Password = settings.Password ; return axlClient ; } } svcutil AXLAPI.wsdl AXLEnums.xsd AXLSoap.xsd /t : code /l : C # /o : Client.cs /n : * , AxlNetClient",WCF maxes CPU when waiting on _TransparantProxyStub_CrossContext function during call "C_sharp : I am fairly new to C # coming from Java , and I 'm wondering if there 's a simple way to avoid code repetition involving primitive types like this : I ca n't find a `` Number '' supertype so that I can compare `` Item '' in a generics implementation ( I would n't mind the performance penalty of boxing , although I understand that in .NET there is no such thing ? ) : Is the only way to create my own Number implementation and having a compare ( ) method ? That sounds like overkill does n't it ? private Boolean AtLeastOneBufferItemIsNonZero ( int [ ] Buffer ) { Boolean result = false ; foreach ( int Item in Buffer ) { result = ! ( Item == ( int ) 0 ) ; if ( result ) break ; } return result ; } private Boolean AtLeastOneBufferItemIsNonZero ( float [ ] Buffer ) { Boolean result = false ; foreach ( float Item in Buffer ) { result = ! ( Item == ( float ) 0 ) ; if ( result ) break ; } return result ; } //SOMETHING LIKE THIS ? private Boolean AtLeastOneBufferItemIsNonZero < T > ( T [ ] Buffer ) where T : NUMBERTYPE { Boolean result = false ; foreach ( T Item in Buffer ) { result = ! ( Item.Equals ( 0 ) ) ; //Nope ... . if ( result ) break ; } return result ; }",C # Generics to avoid code repetition ? "C_sharp : In WPF do DependencyProperty 's cause lots of boxing/unboxing when used with value types ? Or does the implementation some how to prevent this and not box/unbox value types ? Is so how do they do this ? I think value types are a major use case for DependencyPropertys.Thanks public double Price { get { return ( double ) GetValue ( PriceProperty ) ; } set { SetValue ( PriceProperty , value ) ; } } public static readonly DependencyProperty PriceProperty = DependencyProperty.Register ( `` Price '' , typeof ( double ) , typeof ( Quote ) , new UIPropertyMetadata ( 0.0d ) ) ;",In WPF do DependencyProperty 's cause lots of boxing/unboxing when used with value types ? "C_sharp : So I 'm editing the default ASP.NET MVC with authentication template , and I 'm trying to create a ViewModel for _PartialLogin.cshtml in order to display a name instead of the user 's e-mail . I searched a lot of things , but they were pretty outdated so I hope someone can help . I do n't even know if creating a ViewModel is the best option.Here 's the LoginPartialViewModel : _LoginPartial.cshtml : ( ... ) HomeController : On _Layout.cshtml there 's this portion useful : ( the code is simplified to shorted this ) So this is working fine while I 'm on Home/index because it as no Model , but as soon as I enter a page with a model it shows an model error thing.I could replace : forBut the problem is that I lose the information by creating a new instance ... Thank you . **Some words like 'Nome ' are not misspelled , they are in portuguese namespace AplicacaoRoles2.Models.SharedViewModels { public class PartialLoginViewModel { [ Required ] public string Nome { get ; set ; } } } @ using Microsoft.AspNetCore.Identity @ using AplicacaoRoles2.Models @ model AplicacaoRoles2.Models.SharedViewModels.PartialLoginViewModel @ inject SignInManager < ApplicationUser > SignInManager @ inject UserManager < ApplicationUser > UserManager @ if ( SignInManager.IsSignedIn ( User ) ) { < form asp-area= '' '' asp-controller= '' Account '' asp-action= '' Logout '' method= '' post '' id= '' logoutForm '' class= '' navbar-right '' > < ul class= '' nav navbar-nav navbar-right '' > < li > < a asp-area= '' '' asp-controller= '' Manage '' asp-action= '' Index '' title= '' Manage '' > Hello @ Html.DisplayFor ( model = > model.Nome ) ! < /a > < /li > public class HomeController : Controller { private readonly ApplicationDbContext _context ; public HomeController ( ApplicationDbContext context ) { _context = context ; } public async Task < IActionResult > Index ( ) { PartialLoginViewModel model = new PartialLoginViewModel ( ) ; var userName = User.Identity.Name ; var applicationUser = await _context.ApplicationUser.SingleOrDefaultAsync ( m = > m.UserName == userName ) ; model.Nome = applicationUser.Nome ; return View ( model ) ; } @ Html.Partial ( `` _LoginPartial '' ) @ Html.Partial ( `` _LoginPartial '' ) @ Html.Partial ( `` _LoginPartial '' , new AplicacaoRoles2.Models.SharedViewModels.PartialLoginViewModel ( ) )",Trying to use a ViewModel on a partial view "C_sharp : Having a method to convert double [ ] d to IntPtr like : What would be the best way to make int [ ] , float [ ] , etc . I was thinking on making one method for each type like adding int [ ] :1 . Could this method be generalized , if so how ? 2 . Is it possible to get pointer in only one line of code ( As Marshal is void method ) ? public static IntPtr DoubleArrayToIntPtr ( double [ ] d ) { IntPtr p = Marshal.AllocCoTaskMem ( sizeof ( double ) * d.Length ) ; Marshal.Copy ( d , 0 , p , d.Length ) ; return p ; } public static IntPtr IntArrayToIntPtr ( int [ ] d ) { IntPtr p = Marshal.AllocCoTaskMem ( sizeof ( int ) * d.Length ) ; Marshal.Copy ( d , 0 , p , d.Length ) ; return p ; }",Make only one method of array of any kind to IntPtr "C_sharp : I want my program to constantly change the font background color , but I want it to go smoothly so I tried to modify a Color variable Color custom ; and use it to for the background color of the form this.BackColor = custom ; but it does n't work and I do n't know how to make it work , here is the complete code : private void Principal_Load ( object sender , EventArgs e ) { Color custom ; int contr = 0 , contg = 0 , contb = 0 ; do { while ( contr < 255 & & contg == 0 ) { if ( contb ! = 0 ) { contb -- ; } contr++ ; while ( contg < 255 & & contb == 0 ) { if ( contr ! = 0 ) { contr -- ; } contg++ ; while ( contb < 255 & & contr == 0 ) { if ( contg ! = 0 ) { contg -- ; } contb++ ; } } } custom = Color.FromArgb ( contr , contg , contb ) ; this.BackColor = custom ; } while ( true ) ; }",Change Form color constantly "C_sharp : I have a json file which has random names in roots but same structure in child elements . I would like to get all the child elements in an array or a list . Sample json file : I have tried these classes but could not do it.So my expected output from deserialization is like List which contains all the apiKeys in json file.Thanks in advance . { `` -LeHl495vL6vh-8CaLbD '' : { `` apiKey '' : '' sr-tr-137-beea04e44cb452ba0da0ca090b7e61b4ec6ffc69 '' } , `` -LeHl6jrhUEMb7slZcpB '' : { `` apiKey '' : '' sr-tr-137-aef7a23095c0c7baef1ef681bdd8bf9756ac2a17 '' } } public class RequestedReport { public Dictionary < string , List < ReportData > > ReportDatas { get ; set ; } } public class ReportData { public string apiKey { get ; set ; } }",Deserialize json with c # with random root names "C_sharp : I am reading Josh Bloch 's book Effective Java and he suggests using a builder design pattern when building objects that have large amounts of members . From what I can see it is n't the vanilla design pattern but looks like his variation . I rather like the look of it and was trying to use it in a C # web application that I am writting . This is the code written in Java and works perfectlyWhen I put this into what I think is the C # equivalentThen I get compiler warnings . Most of them `` can not declare instance members in a static class '' .So my question is firstly what have I missed ? If I have missed something , can I do it in the manner Josh Bloch recommends but in C # , and lastly , and this one important too , is this thread-safe ? public class Property { private String title ; private String area ; private int sleeps = 0 ; public static void main ( String [ ] args ) { Property newProperty = new Property.Builder ( `` Test Property '' ) .Area ( `` Test Area '' ) .Sleeps ( 7 ) .build ( ) ; } private Property ( Builder builder ) { this.title = builder.title ; this.area = builder.area ; this.sleeps =builder.sleeps ; } public static class Builder { private String title ; private String area ; private int sleeps = 0 ; public Builder ( String title ) { this.title = title ; } public Builder Area ( String area ) { this.area = area ; return this ; } public Builder Sleeps ( int sleeps ) { this.sleeps = sleeps ; return this ; } public Property build ( ) { return new Property ( this ) ; } } } public class Property { private String title ; private String area ; private Property ( Builder Builder ) { title = Builder.title ; area = Builder.area ; } public static class Builder { // Required parameters private String title ; private String area ; // Optional parameters private int sleeps = 0 ; public Builder ( String val ) { this.title = val ; } public Builder Area ( String val ) { this.area = val ; return this ; } public Builder Sleeps ( int val ) { this.sleeps = val ; return this ; } public Property build ( ) { return new Property ( this ) ; } } }",How is Java 's notion of static different from C # 's ? "C_sharp : When trying to assign a type to a property of type System.Type , why ca n't we do this ? The compiler produces this warning : `` Expression expected . `` The way to solve it is by doing this : My question is why ca n't we use the first approach ? Is n't the compiler smart enough to figure out what we 're trying to accomplish here ? Is there some reason why we have to go with the second approach ( typeof ) ? foo.NetType = bool ; foo.NetType = typeof ( bool ) ;","Why do we have to use typeof , instead of just using the type ?" C_sharp : We 're using very descriptive test names for work and it 's getting very annoying to horizontally scroll across them . Is there a way to get a method name to span multiple lines in C # ? Something like : Thanks . MyMethodNameIsReallyLong _SoImMakingItSpanMultipleLines _SoIDontHaveToHorizontallyScroll _AndMyLifeIsMuchEasier ( ) { DoSomething ( ) ; },Is there a way to span long method names across multiple lines ? "C_sharp : scripts/ai/Dream.booC # In the line bc.Parameters.References.Add ( Assembly.GetExecutingAssembly ( ) ) ; I add the executing assembly , which contains the namespace `` LonelyHero '' . However , the error rsc/script/ai/Dream.boo ( 2 , 8 ) : BCE0021 : Namespace LonelyHero not found . maybe you forgot to add an assembly reference ? appears.LonelyHero should exist , why does this error occur and what can I do to resolve it ? Note : Upon replacing Assembly.GetExecutingAssmebly ( ) with Assembly.GetAssembly ( typeof ( Enemy ) ) , thus assuring it adds the assembly with a class under the LonelyHero namespace , the same error occurs . Also with Assembly.LoadFile ( new DirectoryInfo ( `` LonelyHero.exe '' ) .FullName ) Occurs in Boo 0.9.4.9 and booxw-1203 import CultLibimport LonelyHeroclass Dream ( Enemy ) : pass var bc = new BooCompiler ( ) ; bc.Parameters.Input.Add ( new FileInput ( `` rsc/script/ai/ '' + `` Dream '' + `` .boo '' ) ) ; bc.Parameters.Pipeline = new CompileToMemory ( ) ; bc.Parameters.References.Add ( Assembly.GetExecutingAssembly ( ) ) ; bc.Parameters.References.Add ( Assembly.LoadFile ( new DirectoryInfo ( `` CultLib.dll '' ) .FullName ) ) ; bc.Parameters.References.Add ( Assembly.LoadFile ( new DirectoryInfo ( `` sfmlnet-audio-2.dll '' ) .FullName ) ) ; bc.Parameters.References.Add ( Assembly.LoadFile ( new DirectoryInfo ( `` sfmlnet-graphics-2.dll '' ) .FullName ) ) ; bc.Parameters.References.Add ( Assembly.LoadFile ( new DirectoryInfo ( `` sfmlnet-window-2.dll '' ) .FullName ) ) ; var cc = bc.Run ( ) ; if ( cc.GeneratedAssembly ! =null ) { cc.GeneratedAssembly.CreateInstance ( `` Dream '' , true , BindingFlags.NonPublic , null , new object [ ] { Parent , pos } , null , null ) ; } else { foreach ( var error in cc.Errors ) Console.WriteLine ( error ) ; }","Embedding boo in C # , does not recognise executing assembly" "C_sharp : This C # code : produces this CIL ( .NET 4 ) Why does the MSIL add the flag1 , continue to perform the same logic to set flag , set flag1 to flag and finally , check for ! flag1 . This seems like a compiler inefficiency to me.UPDATE : I was using Telerik 's JustDecompile and while the results are quite different from ILDASM , the additional boolean is still created in debug mode . Also , I modified the code by removing the boolean completely and the debug version still adds a boolean . I 'm really looking for why the compiler does this . private void LoadAssignments ( AssignmentType assignmentType , Collection < Assignment > assignments ) { bool flag ; DataTable lessons = this.GetResults ( assignmentType ) ; try { IEnumerator enumerator = lessons.Rows.GetEnumerator ( ) ; try { while ( true ) { flag = enumerator.MoveNext ( ) ; if ( ! flag ) { break ; } DataRow row = ( DataRow ) enumerator.Current ; } } finally { IDisposable disposable = enumerator as IDisposable ; flag = disposable == null ; if ( ! flag ) { disposable.Dispose ( ) ; } } } finally { flag = lessons == null ; if ( ! flag ) { lessons.Dispose ( ) ; } } } .method private hidebysig instance void LoadAssignments ( valuetype TTReporterCore.AssignmentType assignmentType , class [ mscorlib ] System.Collections.ObjectModel.Collection ` 1 < valuetype TTReporterCore.Assignment > assignments ) cil managed { .locals init ( [ 0 ] bool flag , [ 1 ] class [ System.Data ] System.Data.DataTable lessons , [ 2 ] class [ mscorlib ] System.Collections.IEnumerator enumerator , [ 3 ] class [ System.Data ] System.Data.DataRow row , [ 4 ] class [ mscorlib ] System.IDisposable disposable , [ 5 ] bool flag1 ) IL_0000 : nop IL_0001 : ldarg.0 IL_0002 : ldarg.1 IL_0003 : call instance class [ System.Data ] System.Data.DataTable TTReporterCore.TTReader : :GetResults ( valuetype TTReporterCore.AssignmentType ) IL_0008 : stloc.1 .try { IL_0009 : nop IL_000a : ldloc.1 IL_000b : callvirt instance class [ System.Data ] System.Data.DataRowCollection [ System.Data ] System.Data.DataTable : :get_Rows ( ) IL_0010 : callvirt instance class [ mscorlib ] System.Collections.IEnumerator [ System.Data ] System.Data.InternalDataCollectionBase : :GetEnumerator ( ) IL_0015 : stloc.2 .try { IL_0016 : nop IL_0017 : br.s IL_0038 .loop { IL_0019 : nop IL_001a : ldloc.2 IL_001b : callvirt instance bool [ mscorlib ] System.Collections.IEnumerator : :MoveNext ( ) IL_0020 : stloc.0 IL_0021 : ldloc.0 IL_0022 : stloc.s flag1 IL_0024 : ldloc.s flag1 IL_0026 : brtrue.s IL_002b IL_0028 : nop IL_0029 : br.s IL_003d IL_002b : ldloc.2 IL_002c : callvirt instance object [ mscorlib ] System.Collections.IEnumerator : :get_Current ( ) IL_0031 : castclass [ System.Data ] System.Data.DataRow IL_0036 : stloc.3 IL_0037 : nop IL_0038 : ldc.i4.1 IL_0039 : stloc.s flag1 IL_003b : br.s IL_0019 } IL_003d : nop IL_003e : leave.s IL_0062 } finally { IL_0040 : nop IL_0041 : ldloc.2 IL_0042 : isinst [ mscorlib ] System.IDisposable IL_0047 : stloc.s disposable IL_0049 : ldloc.s disposable IL_004b : ldnull IL_004c : ceq IL_004e : stloc.0 IL_004f : ldloc.0 IL_0050 : stloc.s flag1 IL_0052 : ldloc.s flag1 IL_0054 : brtrue.s IL_0060 IL_0056 : nop IL_0057 : ldloc.s disposable IL_0059 : callvirt instance void [ mscorlib ] System.IDisposable : :Dispose ( ) IL_005e : nop IL_005f : nop IL_0060 : nop IL_0061 : endfinally } IL_0062 : nop IL_0063 : nop IL_0064 : leave.s IL_007e } finally { IL_0066 : nop IL_0067 : ldloc.1 IL_0068 : ldnull IL_0069 : ceq IL_006b : stloc.0 IL_006c : ldloc.0 IL_006d : stloc.s flag1 IL_006f : ldloc.s flag1 IL_0071 : brtrue.s IL_007c IL_0073 : nop IL_0074 : ldloc.1 IL_0075 : callvirt instance void [ System ] System.ComponentModel.MarshalByValueComponent : :Dispose ( ) IL_007a : nop IL_007b : nop IL_007c : nop IL_007d : endfinally } IL_007e : nop IL_007f : ret }",Why Does The Compiler Add An Unnecessary Local Variable "C_sharp : I 've been experimenting with the recently open-sourced C # compiler in Roslyn , seeing if I can add language features.I 'm now trying to add some syntax sugar , a new prefix operator that is basically shorthand for a certain pattern . For now I 'm piggy-backing on the pre-existing & `` address of '' , outside of unsafe contexts.The pattern I want to expand is as follows : & n is equivalent to : The method Property.Bind is assumed to be available in a library , with the signature : So in essence I need to synthesize two lambdas : binds to n as an lvalue and does an assignment to it from its parameter , and has no parameters and evaluates n. I then need to make an invocation to Property.Bind passing those two lambdas as the parameters.My previous experiments have been much easier than this because they were able to piggy back on easy-to-find existing features , so there was practically zero work to do ! But this time I 'm struggling to find anything similar to what I 'm doing here . So far I 've been stepping through how a BoundLambda is built by the compiler from the source , and it 's unfolding into a big ol ' mess . I was modifying BindAddressOfExpression in Binder_Operators.cs , making it start with an extra if statement for safe contexts : So ( presumably ! ) now I have the assignment block for the first lambda , but getting a complete BoundLambda around it looks to be a whole new challenge.I 'm wondering : is there a way to `` cheat '' for this kind of syntactic sugar , by asking the parser/binder to work on a string of C # , as if it had appeared in place of the actual code ? That way , manually constructing all the parts and stitching them together wo n't be necessary . After all , the existing compiler is ideally suited for this ! Property.Bind ( v = > n = v , ( ) = > n ) public static IProperty < T > Bind < T > ( Action < T > set , Func < T > get ) private BoundExpression BindAddressOfExpression ( PrefixUnaryExpressionSyntax node , DiagnosticBag diagnostics ) { if ( ! this.InUnsafeRegion ) { BoundExpression rValue = BindValue ( node.Operand , diagnostics , BindValueKind.RValue ) ; BoundExpression lValue = BindValue ( node.Operand , diagnostics , BindValueKind.Assignment ) ; var valueParamSymbol = new SourceSimpleParameterSymbol ( null , rValue.Type , 0 , RefKind.None , `` __v '' , ImmutableArray < Location > .Empty ) ; var valueParam = new BoundParameter ( node , valueParamSymbol ) ; var assignment = new BoundAssignmentOperator ( node , lValue , valueParam , RefKind.None , rValue.Type ) ; var assignmentStatement = new BoundExpressionStatement ( node , assignment ) ; var assignmentBlock = new BoundBlock ( node , ImmutableArray < LocalSymbol > .Empty , ImmutableArray.Create < BoundStatement > ( assignmentStatement ) ) { WasCompilerGenerated = true } ; assignmentBlock = FlowAnalysisPass.AppendImplicitReturn ( assignmentBlock ) ;",Synthesizing a lambda in Roslyn 's C # compiler "C_sharp : I a have a very simple app with one JWT authenticated controller : With the authentication configured as : During tests , i want the user to be `` authenticated '' all the time so that [ Authorize ] would be skipped.Running the test like this will fail , so following this doc I added this simple auth handler : So now my test class looks like this : And it still fails , I have no idea what I 'm doing wrong . [ ApiController ] [ Authorize ] [ Route ( `` [ controller ] '' ) ] public class JwtController : ControllerBase { public JwtController ( ) { } [ HttpGet ] public ActionResult Get ( ) = > Ok ( `` Working ! `` ) ; } services.AddAuthentication ( x = > { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme ; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme ; } ) .AddJwtBearer ( x = > { x.RequireHttpsMetadata = false ; x.SaveToken = true ; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false , ValidateAudience = false } ; } ) ; [ Fact ] public async Task JwtIsSkipped ( ) { var response = ( await _Client.GetAsync ( `` /jwt '' ) ) .EnsureSuccessStatusCode ( ) ; var stringResponse = await response.Content.ReadAsStringAsync ( ) ; Assert.Equal ( `` Working ! `` , stringResponse ) ; } public class TestAuthHandler : AuthenticationHandler < AuthenticationSchemeOptions > { public const string DefaultScheme = `` Test '' ; public TestAuthHandler ( IOptionsMonitor < AuthenticationSchemeOptions > options , ILoggerFactory logger , UrlEncoder encoder , ISystemClock clock ) : base ( options , logger , encoder , clock ) { } protected override Task < AuthenticateResult > HandleAuthenticateAsync ( ) { var claims = new [ ] { new Claim ( ClaimTypes.Name , `` Test user '' ) } ; var identity = new ClaimsIdentity ( claims , DefaultScheme ) ; var principal = new ClaimsPrincipal ( identity ) ; var ticket = new AuthenticationTicket ( principal , DefaultScheme ) ; return Task.FromResult ( AuthenticateResult.Success ( ticket ) ) ; } } public class UnitTest : IClassFixture < WebApplicationFactory < Startup > > { private readonly WebApplicationFactory < Startup > _Factory ; private readonly HttpClient _Client ; public UnitTest ( WebApplicationFactory < Startup > factory ) { _Factory = factory ; _Client = _Factory.WithWebHostBuilder ( builder = > { builder.ConfigureTestServices ( services = > { services.AddAuthentication ( TestAuthHandler.DefaultScheme ) .AddScheme < AuthenticationSchemeOptions , TestAuthHandler > ( TestAuthHandler.DefaultScheme , options = > { } ) ; } ) ; } ) .CreateClient ( ) ; _Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ( TestAuthHandler.DefaultScheme ) ; } [ Fact ] public async Task JwtIsSkipped ( ) { var response = ( await _Client.GetAsync ( `` /jwt '' ) ) .EnsureSuccessStatusCode ( ) ; var stringResponse = await response.Content.ReadAsStringAsync ( ) ; Assert.Equal ( `` Working ! `` , stringResponse ) ; } }",Skip JWT Auth during Tests ASP.Net Core 3.1 Web Api "C_sharp : Was looking at some code in our codebase and I 'm unable to understand how/why this is even working ( and not causing a stackoverflow due to infinite recursion ) . I have pasted some equivalent code below : We have a virtual method Foo ( B ) defined in class P1 and overridden in class P2 . P2 also defines a private non-virtual method Foo ( A ) . B derives from A. P2 : :Foo ( B ) has a call in the end : Foo ( b ) . I expect this to end up in a stack overflow . However , the output is : P2 : :Foo VirtualP2 : :Foo Private Non-VirtualLooks like the second call to Foo in the overridden method is picking up the non-virtual method Foo in this case . On doing similar operations in P1 ( uncomment code ) , we end up calling Foo infinite number of times through recursion . Questions : ( finally ! ) 1 . Why is the behavior different in the original virtual method and the overridden method ? Why is one calling itself and the other calling a different method ? 2 . Is there an order of preference specified somewhere ? Note that if we change the private modifier to public , in both cases , we end up calling the non-virtual method ( Even if we instantiate P2 this way : P1 p2 = new P2 ( ) ; , instead of P2 p2 = new P2 ( ) ; ) It looks like the non-virtual version is preferred , except when it is inside a virtual method definition . Is this true ? } using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace ConsoleApplication1 { public class P1 { static void Main ( string [ ] args ) { B b = new B ( ) ; P2 p2 = new P2 ( ) ; p2.Foo ( b ) ; // Uncomment code to cause infinite recursion //P1 p1 = new P1 ( ) ; //p1.Foo ( b ) ; } private void Foo ( A a ) { Console.WriteLine ( `` P1 : :Foo Private Non-Virtual '' ) ; } public virtual void Foo ( B b ) { Console.WriteLine ( `` Inside P1 : :Foo '' ) ; // Uncomment code to cause infinite recursion // Foo ( b ) ; } } public class P2 : P1 { private void Foo ( A a ) { Console.WriteLine ( `` P2 : :Foo Private Non-Virtual '' ) ; } public override void Foo ( B b ) { Console.WriteLine ( `` P2 : :Foo Virtual '' ) ; Foo ( b ) ; } } public class A { public int a = 10 ; } public class B : A { public int b = 20 ; }",Virtual method overriding C # - why does n't this cause an infinite recursion ? "C_sharp : I have a webmethod that inserts a bunch of recipes into a queue in the database ( to store recipes the user is interested in cooking , similar to NetFlix 's movie queue ) . The user is able to check off a bunch of recipes at once and queue them . I have code similar to this : I have a unique constraint on UserId/RecipeId so a user can only enqueue a recipe once . However , if they happen to select a recipe that 's already in their queue I do n't really want to bother the user with an error message , I just want to ignore that recipe.The above code will throw a SQL exception if the unique constraint is violated . What 's the best approach to get around this , and simply ignore duplicate rows . My current ideas are:1 ) First load the user 's entire queue from the database and checkthat list first . If the recipe already exists , just continue inthe for loop . Pros : No unnecessary SQL inserts get sent to thedatabase . Cons : Slower , especially if the user has a big queue.2 ) Do n't use ActiveRecord and instead pass the entire recipeIds arrayinto a SQL function . This function will check if each row existsfirst . Pros : Potentially fast , lets SQL handle all the dirty work . Cons : Breaks ActiveRecord pattern and requires new DB code , which isoften harder to maintain and costlier to implement.3 ) CreateAndFlush after each loop . Basically , do n't run this entireloop in a single transaction . Commit each row as it 's added andcatch SQL errors and ignore . Pros : Low startup cost , and doesn'trequire new SQL backend code . Cons : Potentially slower for insertinglots of rows into the database at once , though it 's doubtful a userwould ever submit over a dozen or so new recipes at once.Are there any other little tricks with Castle or the NHibernate framework ? Also , my SQL backend is PostgreSQL 9.0 . Thanks ! Update : I took a shot at the first approach and it seems to work pretty well . It occured to me I do n't have to load the entire queue , just the ones that appear in recipeIds . I believe my foreach ( ) loop is now O ( n^2 ) depending on the efficiency of List < Guid > : :Contains ( ) but I think this is probably decent for the sizes I 'll be working with . [ WebMethod ] public void EnqueueRecipes ( SecurityCredentials credentials , Guid [ ] recipeIds ) { DB.User user = new DB.User ( credentials ) ; using ( new TransactionScope ( OnDispose.Commit ) ) { foreach ( Guid rid in recipeIds ) { DB.QueuedRecipe qr = new DB.QueuedRecipe ( Guid.NewGuid ( ) , user , new DB.Recipe ( rid ) ) ; qr.Create ( ) ; } } } //Check for dupesDB.QueuedRecipe [ ] dbRecipes = DB.QueuedRecipe.FindAll ( Expression.In ( `` Recipe '' , ( from r in recipeIds select new DB.Recipe ( r ) ) .ToArray ( ) ) ) ; List < Guid > existing = ( from r in dbRecipes select r.Recipe.RecipeId ) .ToList ( ) ; using ( new TransactionScope ( OnDispose.Commit ) ) { foreach ( Guid rid in recipeIds ) { if ( existing.Contains ( rid ) ) continue ; DB.QueuedRecipe qr = new DB.QueuedRecipe ( Guid.NewGuid ( ) , user , new DB.Recipe ( rid ) ) ; qr.Create ( ) ; } }",Recommended approach to insert many rows with Castle ActiveRecord and ignore any dupes "C_sharp : According to this question it should be guaranteed that static fields that i use are initialized:10.4.5.1 Static field initialization : The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration . If a static constructor ( Section 10.11 ) exists in the class , execution of the static field initializers occurs immediately prior to executing that static constructor . Otherwise , the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.I 've encountered a strange case where this does n't seem to be true . I have two classes which have a circular dependency on each other and where a NullReferenceException is thrown.I was able to reproduce this issue in following simplified sample , have a look : The problem still remains if you uncomment the static constructors as suggested in the other question . Use this code to get a TypeInitializationException with the NullRefernceException as InnerException in Synchronize at SessionManager.GetInstance ( ) .GetAllActiveSessions ( ) : Console output : I understand that there is some kind of circular dependency here ( in original code not so obvious ) , but I still do n't understand why the code fails to initialize the singletons . What would be the best approach for this use case apart from avoiding circular dependencies ? public class SessionManager { //// static constructor does n't matter //static SessionManager ( ) // { // _instance = new SessionManager ( ) ; // } private static SessionManager _instance = new SessionManager ( ) ; public static SessionManager GetInstance ( ) { return _instance ; } public SessionManager ( ) { Console.WriteLine ( $ '' { nameof ( SessionManager ) } constructor called '' ) ; this.RecoverState ( ) ; } public bool RecoverState ( ) { Console.WriteLine ( $ '' { nameof ( RecoverState ) } called '' ) ; List < SessionInfo > activeSessionsInDb = SessionManagerDatabase.GetInstance ( ) .LoadActiveSessionsFromDb ( ) ; // ... return true ; } public List < SessionInfo > GetAllActiveSessions ( ) { Console.WriteLine ( $ '' { nameof ( GetAllActiveSessions ) } called '' ) ; return new List < SessionInfo > ( ) ; } } public class SessionManagerDatabase { //// static constructor does n't matter //static SessionManagerDatabase ( ) // { // _instance = new SessionManagerDatabase ( ) ; // } private static readonly SessionManagerDatabase _instance = new SessionManagerDatabase ( ) ; public static SessionManagerDatabase GetInstance ( ) { return _instance ; } public SessionManagerDatabase ( ) { Console.WriteLine ( $ '' { nameof ( SessionManagerDatabase ) } constructor called '' ) ; Synchronize ( ) ; } public void Synchronize ( ) { Console.WriteLine ( $ '' { nameof ( Synchronize ) } called '' ) ; // NullReferenceException here List < SessionInfo > memorySessions = SessionManager.GetInstance ( ) .GetAllActiveSessions ( ) ; // ... } public List < SessionInfo > LoadActiveSessionsFromDb ( ) { Console.WriteLine ( $ '' { nameof ( LoadActiveSessionsFromDb ) } called '' ) ; return new List < SessionInfo > ( ) ; } } public class SessionInfo { } static void Main ( string [ ] args ) { try { var sessionManagerInstance = SessionManager.GetInstance ( ) ; } catch ( TypeInitializationException e ) { Console.WriteLine ( e ) ; throw ; } } SessionManager constructor calledRecoverState calledSessionManagerDatabase constructor calledSynchronize calledSystem.TypeInitializationException : Der Typeninitialisierer für `` SessionManager '' hat eine Ausnahme verursacht . -- - > System.TypeInitializationException : Der Typeninitialisierer für `` SessionManagerDatabase '' hat eine Ausnahme verursacht . -- - > System.NullReferenceException : Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt . bei ConsoleApplication_CSharp.Program.SessionManagerDatabase.Synchronize ( ) in ... ... bei ConsoleApplication_CSharp.Program.SessionManagerDatabase..ctor ( ) in ... ... bei ConsoleApplication_CSharp.Program.SessionManagerDatabase..cctor ( ) in ... ... -- - Ende der internen Ausnahmestapelüberwachung -- - bei ConsoleApplication_CSharp.Program.SessionManagerDatabase.GetInstance ( ) bei ConsoleApplication_CSharp.Program.SessionManager.RecoverState ( ) in ... ... bei ConsoleApplication_CSharp.Program.SessionManager..ctor ( ) in ... .. bei ConsoleApplication_CSharp.Program.SessionManager..cctor ( ) in ... ... -- - Ende der internen Ausnahmestapelüberwachung -- - bei ConsoleApplication_CSharp.Program.SessionManager.GetInstance ( ) bei ConsoleApplication_CSharp.Program.Main ( String [ ] args ) in ... ...",NullReferenceException from static singleton inline initialization "C_sharp : I 've been reading Joe Duffy 's book on Concurrent programming . I have kind of an academic question about lockless threading.First : I know that lockless threading is fraught with peril ( if you do n't believe me , read the sections in the book about memory model ) Nevertheless , I have a question : suppose I have an class with an int property on it . The value referenced by this property will be read very frequently by multiple threadsIt is extremely rare that the value will change , and when it does it will be a single thread that changes it.If it does change while another operation that uses it is in flight , no one is going to lose a finger ( the first thing anyone using it does is copy it to a local variable ) I could use locks ( or a readerwriterlockslim to keep the reads concurrent ) .I could mark the variable volatile ( lots of examples where this is done ) However , even volatile can impose a performance hit.What if I use VolatileWrite when it changes , and leave the access normal for reads . Something like this : I do n't think that I would ever try this in real life , but I 'm curious about the answer ( more than anything , as a checkpoint of whether I understand the memory model stuff I 've been reading ) . public class MyClass { private int _TheProperty ; internal int TheProperty { get { return _TheProperty ; } set { System.Threading.Thread.VolatileWrite ( ref _TheProperty , value ) ; } } }",Can I avoid using locks for my seldomly-changing variable ? "C_sharp : In VB.NET , I could make my math code a lot cleaner by Importing System.Math and referencing its methods directly : But I do n't think C # can Use classes in order to access their methods implicitly , so I have to do something like : But that 's ugly ; it needs its own scroll bar ! . Is there any way to write something in C # that looks like my VB.NET code ? I could write local wrapper methods for Sin and Cos , but would n't that reduce performance ( because of the overhead of function calls ) ? And , that would require writing wrapper functions for every Math function I 'm using in every class I 'm using them in ; that 's not so desirable either . Imports System.Math [ ... ] Return New Vector3 ( Sin ( az ) * Cos ( el ) , Cos ( az ) * Cos ( el ) , Sin ( el ) ) using System ; [ ... ] return new Vector3 ( Math.Sin ( az ) * Math.Cos ( el ) , Math.Cos ( az ) * Math.Cos ( el ) , Math.Sin ( el ) ) ;",Can Math references be shortened in C # ? "C_sharp : I want to reuse some code I wrote to add some functionality to a datagridview . I want the default datagridview properties and events to be exposed , so I did n't want to create a new custom component . so I tried writing a subclass , which works fine . but it also occurred to me that I could write a standalone utility class that takes a datagridview in the constructor and sets it up the same way . e.g.so somewhere in my app 's startup I would calland so forth . any disadvantages to this approach ? it seems like much of the code is going to be the same , the difference is between how you instantiate the extended grid ( drag and drop a subclassed control to the form vs drag a plain datagridview and call the above code ) public classMyGrid { private DataGridView m_dg ; public MyGrid ( DataGridView dg ) { m_dg = dg ; m_dg.RowHeadersVisible = false ; m_dg.SortCompare += new DataGridViewSortCompareEventHandler ( m_dg_SortCompare ) ; } void m_dg_SortCompare ( object sender , DataGridViewSortCompareEventArgs e ) { // do custom sorting here } } MyGrid g1 = new MyGrid ( dataGridView1 ) ; MyGrid g2 = new MyGrid ( dataGridView2 ) ;",utility class vs subclassing .net controls "C_sharp : I was trying to implement a generic repository , and I have this right now : I 'm having trouble with this method call : entities.CreateObjectSet < T > ( ) ; It should be fine , however I get this error : I have already added the System.Data.Entity to my project and at this point I do n't know what else to do . I am following this tutorial http : //www.codeproject.com/Articles/770156/Understanding-Repository-and-Unit-of-Work-Pattern . Does anyone know how to fix this issue ? using System ; using System.Collections.Generic ; using System.Linq ; using System.Data ; using System.Data.Entity.Core.Objects ; using Web_API.Models ; namespace Web_API.DAL { class GenericRepository < T > : IRepository < T > where T : class { private ApplicationDbContext entities = null ; IObjectSet < T > _objectSet ; public GenericRepository ( ApplicationDbContext _entities ) { entities = _entities ; _objectSet = entities.CreateObjectSet < T > ( ) ; } ...","Generic Repository , CreateObjectSet < T > ( ) Method" "C_sharp : Looking at using JSON for a new .net REST based system and it looks great , but there is one thing thats alluding my understanding . What is the strategy for keeping the JSON on either side of the application in sync ? What I mean by that is if you do a GET for : www.mysite.com/item/12345 . Then the .net side of the application goes away to the db , retrieves the Item with id 12345 and resolves it to your object model Item that is then serialised to JSON and returned.If you do a POST to : www.mysite.com/item and pass -Then the .net side of the application picks it up , deserialises it to an Item object and then hands it off to be added to the db.How do you get both sides , your JS object model and your .net object model serialisation to sync up ? Does this just need to be maintained by hand or is there a clever way of providing a template for the JSON based on the serialisation of the .net model ? I 'm kinda just looking for best practices and whats the done thing and do n't see how the client side knows what JSON to pass to the server side . { `` Id '' : `` 12346 '' , `` ItemName '' : `` New Item '' , `` ItemCost '' : 45 }","JSON based architecture , how best to synchronise front end and back end" "C_sharp : I am using Web API 2 . In web api controller I have used GetUserId method to generate user id using Asp.net Identity.I have to write MS unit test for that controller . How can I access user id from test project ? I have attached sample code below.Web API ControllerWeb API Controller Test classI tried using mock method like above . But it is not working . How do I generate Asp.net User identity when I call from test method to controller ? public IHttpActionResult SavePlayerLoc ( IEnumerable < int > playerLocations ) { int userId = RequestContext.Principal.Identity.GetUserId < int > ( ) ; bool isSavePlayerLocSaved = sample.SavePlayerLoc ( userId , playerLocations ) ; return Ok ( isSavePlayerLocSaved ) ; } [ TestMethod ( ) ] public void SavePlayerLocTests ( ) { var context = new Mock < HttpContextBase > ( ) ; var mockIdentity = new Mock < IIdentity > ( ) ; context.SetupGet ( x = > x.User.Identity ) .Returns ( mockIdentity.Object ) ; mockIdentity.Setup ( x = > x.Name ) .Returns ( `` admin '' ) ; var controller = new TestApiController ( ) ; var actionResult = controller.SavePlayerLoc ( GetLocationList ( ) ) ; var response = actionResult as OkNegotiatedContentResult < IEnumerable < bool > > ; Assert.IsNotNull ( response ) ; }",How to generate Asp.net User identity when testing WebApi controllers "C_sharp : I have an old function written in 2013 that decrypt xml that was encrypted by another program.The code is realy simpleIt worked like a charm until recently that some of our clients started to upgrade their framework to 4.6.2 , so the method DecryptDocument ( ) stopped working . Now it throws an exception `` The algorithm group `` is invalid '' . If I remove .net framework 4.6.2 it works again.The sample code in this link will reproduce the error , it will encrypt successfully then fail to decrypt.I 'm using A3 certificates , pendrive token . Anyone have faced this problem ? there is any work around in .net 4.6.2 ? Edit 1 : Stacktrace : at System.Security.Cryptography.CngAlgorithmGroup..ctor ( String algorithmGroup ) at System.Security.Cryptography.CngKey.get_AlgorithmGroup ( ) at System.Security.Cryptography.RSACng..ctor ( CngKey key ) at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey ( X509Certificate2 certificate ) at System.Security.Cryptography.CngLightup.GetRSAPrivateKey ( X509Certificate2 cert ) at System.Security.Cryptography.Xml.EncryptedXml.DecryptEncryptedKey ( EncryptedKey encryptedKey ) at System.Security.Cryptography.Xml.EncryptedXml.GetDecryptionKey ( EncryptedData encryptedData , String symmetricAlgorithmUri ) at System.Security.Cryptography.Xml.EncryptedXml.DecryptDocument ( ) at Criptografar.Program.Decrypt ( XmlDocument Doc ) in C : \Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs : line 152 at Criptografar.Program.Main ( String [ ] args ) in C : \Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs : line 83 public static void Decrypt ( XmlDocument Doc ) { // Check the arguments . if ( Doc == null ) throw new ArgumentNullException ( `` Doc '' ) ; // Create a new EncryptedXml object . EncryptedXml exml = new EncryptedXml ( Doc ) ; // Decrypt the XML document . exml.DecryptDocument ( ) ; }",EncryptedXml DecryptDocument method error after .Net framework update "C_sharp : I am trying to figure out how to refactor this LINQ code nicely . This code and other similar code repeats within the same file as well as in other files . Sometime the data being manipulated is identical and sometimes the data changes and the logic remains the same.Here is an example of duplicated logic operating on different fields of different objects.Anyone have a good way of refactoring this ? public IEnumerable < FooDataItem > GetDataItemsByColor ( IEnumerable < BarDto > dtos ) { double totalNumber = dtos.Where ( x = > x.Color ! = null ) .Sum ( p = > p.Number ) ; return from stat in dtos where stat.Color ! = null group stat by stat.Color into gr orderby gr.Sum ( p = > p.Number ) descending select new FooDataItem { Color = gr.Key , NumberTotal = gr.Sum ( p = > p.Number ) , NumberPercentage = gr.Sum ( p = > p.Number ) / totalNumber } ; } public IEnumerable < FooDataItem > GetDataItemsByName ( IEnumerable < BarDto > dtos ) { double totalData = dtos.Where ( x = > x.Name ! = null ) .Sum ( v = > v.Data ) ; return from stat in dtos where stat.Name ! = null group stat by stat.Name into gr orderby gr.Sum ( v = > v.Data ) descending select new FooDataItem { Name = gr.Key , DataTotal = gr.Sum ( v = > v.Data ) , DataPercentage = gr.Sum ( v = > v.Data ) / totalData } ; }",How to refactor this duplicated LINQ code ? "C_sharp : I am trying to solve the following problem : Some pirates have a chest full of treasure ( gold coins ) It is late in the evening , so they decide to split it up in the morning But , one of the pirates wakes up in the middle of the night concerned that the other pirates will steal his share so he decides to go divide the treasure himself . He divides it into equal shares ( one for each pirate ) . There is one coin left over , which he throws overboard . He takes his share , puts the other shares back in the chest , and returns to his cabin . Another pirate wakes up and does the same thing . Yes , there is still one extra coin . Yes , he throws that coin overboard . ... Each pirate does this once during the night ( yes , there is an extra coin and they throw it overboard each time ) , and the next morning they wake up and divide the treasure into equal shares . There is one left over which they throw overboard . They each take their share and live happily ever after . Given the number of pirates , what is the smallest number of coins that could have been in the treasure chest originally ? I tried the following , but any number greater than 8 brings it to its knees : I am fairly certain that every number must be a prime number , so I have also attempted the above with that in mind . However , I have not been able to figure out an efficient formula for solving this . My maths is simply too weakEDITThanks to the video Fr3d mentioned , I now have this for my CalculateTreasure method : It is much improved , but still not 100 % optimal class Program { static long _input ; static long _timesDivided ; static string _output ; static void Main ( ) { Console.WriteLine ( `` Enter the number of Pirates : `` ) ; var isValidInput = long.TryParse ( Console.ReadLine ( ) , out _input ) ; if ( ! isValidInput ) { Console.WriteLine ( `` Please enter a valid number '' ) ; Console.ReadKey ( ) ; return ; } Console.WriteLine ( `` Caculating minimum treasure ... \r\n \r\n '' ) ; _timesDivided = _input + 1 ; var answer = CalculateTreasure ( ) ; if ( answer > 0 ) _output = string.Format ( `` The minimum treasure is { 0 } '' , answer ) ; else _output = `` There was an error , please try another number '' ; Console.WriteLine ( _output ) ; Console.ReadKey ( ) ; } private static long CalculateTreasure ( ) { long result = 0 ; try { while ( true ) { result++ ; while ( true ) { if ( result % _input == 1 ) { break ; } else { result++ ; } } long treasure = result ; for ( long i = 0 ; i < _timesDivided ; i++ ) { var remainder = treasure % _input ; if ( remainder ! = 1 ) { break ; } var share = ( treasure - remainder ) / _input ; if ( i == ( _timesDivided - 1 ) ) { treasure = ( treasure - ( share * _input ) ) ; if ( treasure == 1 ) return result ; } else { treasure = ( treasure - share ) - 1 ; } } } } catch ( Exception ex ) { //log exception here return 0 ; } } } private static long CalculateTreasure ( ) { try { long result = ( long ) Math.Pow ( ( double ) _input , ( double ) _timesDivided ) ; while ( true ) { result -- ; while ( true ) { if ( result % _input == 1 ) { break ; } else { result -- ; } } long treasure = result ; for ( long i = 0 ; i < _timesDivided ; i++ ) { var remainder = treasure % _input ; if ( remainder ! = 1 ) { break ; } var share = ( treasure - remainder ) / _input ; if ( i == ( _timesDivided - 1 ) ) { treasure = ( treasure - ( share * _input ) ) ; if ( treasure == 1 ) return result ; } else { treasure = ( treasure - share ) - 1 ; } } } } catch ( Exception ex ) { //log exception here return 0 ; } }",Pirate Game in Maths - Solve it with C # "C_sharp : Reactive Extensions allow me to `` observe '' a stream of events . For example , when the user is typing their search query in the Windows 8 Search Pane , SuggestionsRequested is raised over and over ( for each letter ) . How can I leverage Reactive Extensions to throttle the requests ? Something like this : SolutionInstall RX for WinRT : http : //nuget.org/packages/Rx-WinRT/Learn more : http : //blogs.msdn.com/b/rxteam/archive/2012/08/15/reactive-extensions-v2-0-has-arrived.aspx SearchPane.GetForCurrentView ( ) .SuggestionsRequested += ( s , e ) = > { if ( e.QueryText.Length < 3 ) return ; // TODO : if identical to the last request , return ; // TODO : if asked less than 500ms ago , return ; } ; System.Reactive.Linq.Observable.FromEventPattern < Windows.ApplicationModel.Search.SearchPaneSuggestionsRequestedEventArgs > ( Windows.ApplicationModel.Search.SearchPane.GetForCurrentView ( ) , `` SuggestionsRequested '' ) .Throttle ( TimeSpan.FromMilliseconds ( 500 ) , System.Reactive.Concurrency.Scheduler.CurrentThread ) .Where ( x = > x.EventArgs.QueryText.Length > 3 ) .DistinctUntilChanged ( x = > x.EventArgs.QueryText.Trim ( ) ) .Subscribe ( x = > HandleSuggestions ( x.EventArgs ) ) ;",How can I use Reactive Extensions to throttle SearchPane.SuggestionsRequested ? "C_sharp : So I 've created a Web Application ( not Web Site ) with ASP.NET ( C # ) and it compiles just fine in the VS13 environment . But when I publish it on IIS , the Postback on the Default Document fails . The Default Document is called LoginPage.aspx . As soon as I click the < asp : Button > to run my code behind , all it does is refresh the page . This project has been published on my local 127.0.0.1 IP address for the time being.I know this has been a documented issue , but I 've tried many solutions and have not come across a resolution . Some solutions I have attempted : Creating a brand new Web App with minimal code to attempt accessing any Postback with no success.I tried the first solution presented here with no success : https : //stackoverflow.com/a/7367076/4204026I also tried URL mappings : I 'm honestly at a loss as to what 's happening here . One thing I did notice is when the application is being run through Visual Studio , the < form > tag on the LoginPage.aspx appears in Chrome as : Through IIS : Not sure if that 's a problem either . I tried hard-coding the action to login to see what would happen and it does redirect to the correct page , but as suspected no Postback was fired - My Session variable returned null and no query string was used.Here 's the related LoginPage.aspx front-end code ( trimmed out a bunch of unrelated HTML ) : And the LoginBtn_Click method in LoginPage.aspx.cs : Final pieces of info : Running IIS 8.0Application created with 4.5 Framework , Application Pool is also 4.5 FrameworkI have ensured that ASP.NET is installed on IISI do have URL ReWriting in the global.asax file , though I 'm not sure if that is related in any way ( I do n't see how ) .I have no Default.aspx pageEDIT : Just tested the project through 127.0.0.1 on IE11 and FF with the same result.EDIT # 2 : Additional things I have tried with no success : I tried removing my URL RewritingI tried adding an empty URL Rewrite rule , i.e . ( `` Empty URL '' , `` '' , `` ~/Views/LoginPage.aspx '' ) Additional notes : I do not use TelerikI do not use ISAPIThe project in Visual Studio was set to debug and not release < urlMappings > < add url= '' ~/login '' mappedUrl= '' ~/Views/LoginPage.aspx '' / > < add url= '' ~/login/ '' mappedUrl= '' ~/Views/LoginPage.aspx '' / > < /urlMappings > < form method= '' post '' action= '' LoginPage '' id= '' ct101 '' class= '' .myForm '' > < form method= '' post '' action= '' ./ '' id= '' ct101 '' class= '' .myForm '' > < % @ Page Title= '' DREW KENNEDY | WELCOME '' Language= '' C # '' MasterPageFile= '' Site.Master '' AutoEventWireup= '' true '' CodeBehind= '' LoginPage.aspx.cs '' Inherits= '' MyMedia.Views.LoginPage '' % > < asp : Content ID= '' BodyContent '' ContentPlaceHolderID= '' MainContent '' runat= '' server '' > < ! -- form is located on Site.Master -- > < asp : Button OnClick= '' LoginBtn_Click '' CssClass= '' login '' runat= '' server '' name= '' submit '' Text= '' Sign In '' / > < /asp : Content > protected void LoginBtn_Click ( object sender , EventArgs e ) { //Tried the following line while commenting out everything else to make sure Postback is being ignored //Response.Write ( `` < script > alert ( 'Test ' ) ; < /script > '' ) ; try { AbstractPersistenceDecorator decorator = new PersistenceDecorator ( ) ; string uname = username.Text.Trim ( ) ; //username is a TextBox Control string pass = password.Text.Trim ( ) ; //password is a TextBox control bool isCookieRequested = CheckBox.Checked ; if ( decorator.authenticate ( uname , pass ) ) { //calling SQL Server for authentication User AuthenticatedUser = ( User ) Session [ `` User '' ] ? ? decorator.getUserInfo ( uname ) ; if ( Session [ `` User '' ] == null ) Session [ `` User '' ] = AuthenticatedUser ; if ( isCookieRequested ) { HttpCookie cookie = new HttpCookie ( `` username '' , AuthenticatedUser.Username ) ; cookie.Expires.AddDays ( 7 ) ; Response.Cookies.Add ( cookie ) ; } else { Session.Timeout = 15 ; } Thread.Sleep ( 1600 ) ; //string redirect = string.Format ( `` dashboard ? username= { 0 } '' , AuthenticatedUser.Username ) ; Response.Redirect ( `` dashboard ? username= '' + AuthenticatedUser.Username ) ; } } catch ( Exception ex ) { //who cares ? } }",Postback Fails On Default Document "C_sharp : How to make a native API to be PInvoke friendly ? there are some tips on how to modify native-programs to be used with P/Invoke here . But before I even write a native programs , what are the things I should look out to make my programs/library PInvoke friendly ? using C or C++ are fine.update : if I write a C API , what are the things I have to do so that It is P/Invoke-able using C # syntax like the following : is it possible to do the same with native C++ code/library ? Summary/Rephrase of Some Tips to make a P/Invoke friendly native-API : + the parameters should be of native types ( int , char* , float , ... ) + less parameters is better+ if dynamic memory is allocated and passed to managed code , make sure to create a `` cleaner '' function which is also p/invoked+ provide samples and/or unit tests that illustrate how to call the API from .NET+ provide C++/CLI wrapper [ DLLimport ( `` MyDLL.dll '' ) ]",How to make a PInvoke friendly native-API ? "C_sharp : Recently , I was trying to answer another SO question about loading the frames ( Bitmap and duration ) of animated GIFs . The code can be found on pastenbin . While doing additional tests on this code before moving it into my dev library , I noticed that there is a problem with this line of code : When running this on Windows .Net using this ( example GIF ) , the array is of the same size as the amount of frames in the animated GIF and filled with the durations of the frames . In this case a byte [ 20 ] which converts to ( BitConverter.ToInt32 ( ) ) 5 durations : On MonoMac however , this line of code for the same example GIF returns a byte [ 4 ] which converts to only one duration ( the first ) : I tested this for 10 different GIF 's and the result is always the same . On Windows all durations are in the byte [ ] , while MonoMac only lists the first duration : Looking at the Mono System.Drawing.Image source code , the length seem to be set in this method , which is a GDI wrapper : However , I do n't really see any problems , not with the source as with my implementation . Am I missing something or is this a bug ? //Get the times stored in the gif//PropertyTagFrameDelay ( ( PROPID ) 0x5100 ) comes from gdiplusimaging.h//More info on http : //msdn.microsoft.com/en-us/library/windows/desktop/ms534416 ( v=vs.85 ) .aspxvar times = img.GetPropertyItem ( 0x5100 ) .Value ; [ 75,0,0,0,125,0,0,0,125,0,0,0,125,0,0,0,250,0,0,0 ] [ 75,0,0,0 ] [ x,0,0,0 ] [ 75,0,0,0 ] [ 50,0,0,0 ] [ 125,0,0,0 ] status = GDIPlus.GdipGetPropertyItemSize ( nativeObject , propid , out propSize ) ;",MonoMac System.Drawing.Image.GetPropertyItem ( 0x5100 ) "C_sharp : I have to draw a honeycomb pattern and recognize each cell ( row , column ) on mousemove . this is how i am generating the graph . and this what i am doing to get the coordinates of the graph . but the problem is i am able to get the column perfectly . but for the row i think there is a small difference in calculation . for eg . on the 99 row , for the ( 1/4 ) circle it say { row 98 } and for the remaining circle it says { row 99 } . the deviation increases as the number of rows increases.hope i was clear in explaining my problem.EDIT : the VERTICAL_PIXEL_OFFSET is 1 and the circle size is 16 protected override void GenerateGridBitmap ( ) { if ( _circleGrid ! = null ) { _circleGrid.Dispose ( ) ; _circleGrid = null ; } Bitmap _texture = new Bitmap ( circleSize , circleSize ) ; using ( Graphics g = Graphics.FromImage ( _texture ) ) { g.SmoothingMode = SmoothingMode.HighQuality ; g.InterpolationMode = InterpolationMode.HighQualityBicubic ; g.PixelOffsetMode = PixelOffsetMode.HighQuality ; Rectangle r = new Rectangle ( 0 , 0 , circleSize , circleSize ) ; g.DrawEllipse ( Pens.Black , r ) ; } Bitmap rowBlock = new Bitmap ( CanvasSize.Width - ( circleSize/ 2 ) , circleSize ) ; using ( Brush b = new TextureBrush ( _texture ) ) { using ( Graphics g = Graphics.FromImage ( rowBlock ) ) { g.CompositingQuality = CompositingQuality.HighQuality ; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic ; g.SmoothingMode = SmoothingMode.HighQuality ; g.FillRectangle ( b , new Rectangle ( new Point ( 0 , 0 ) , rowBlock.Size ) ) ; } } //rowBlock.Save ( `` rowblock.bmp '' ) ; _circleGrid = new Bitmap ( CanvasSize.Width , CanvasSize.Height ) ; using ( Graphics g = Graphics.FromImage ( _circleGrid ) ) { g.CompositingQuality = CompositingQuality.HighQuality ; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic ; g.SmoothingMode = SmoothingMode.HighQuality ; int x , y ; for ( int i = 0 ; i < rows ; i++ ) { x = 0 ; if ( i % 2 ! = 0 ) x = ( circleSize/ 2 ) ; y = ( i * circleSize ) ; if ( i ! = 0 ) { y -= ( VERTICAL_PIXEL_OFFSET * i ) ; } g.DrawImage ( rowBlock , x , y ) ; //g.DrawImage ( DrawCodedCrystal ( i , rowBlock ) , x , y ) ; Console.WriteLine ( i ) ; } } _circleGrid.Save ( `` grid.bmp '' ) ; Console.WriteLine ( _circleGrid.Size ) ; _texture.Dispose ( ) ; _texture = null ; rowBlock.Dispose ( ) ; rowBlock = null ; } protected override CanvasCell GetCanvasCellAt ( int x , int y ) { Rectangle rect = GetImageViewPort ( ) ; Point pt = new Point ( x , y ) ; CanvasCell c = new CanvasCell ( ) { Row = -1 , Column = -1 } ; if ( rect.Contains ( pt ) ) { double zoomedCircleSize = CircleSize * ZoomFactor ; Point p = pt ; // PointToClient ( new Point ( x , y ) ) ; p.X -= ( int ) ( rect.X + ( AutoScrollPosition.X ) ) ; p.Y -= ( int ) ( rect.Y + ( AutoScrollPosition.Y ) ) ; int row = ( int ) ( ( p.Y ) / ( zoomedCircleSize ) ) ; //row = ( int ) ( ( p.Y + ( row * ZoomFactor ) ) / zoomedCircleSize ) ; int col ; if ( row % 2 ! = 0 ) { if ( p.X > = 0 & & p.X < ( zoomedCircleSize / 2 ) ) { col = -1 ; } else col = ( int ) ( ( p.X - ( zoomedCircleSize / 2 ) ) / zoomedCircleSize ) ; } else { if ( p.X > ( zoomedCircleSize * cols ) ) { col = -1 ; } else { col = ( int ) ( ( p.X ) / zoomedCircleSize ) ; } } //if ( ! GetRectangle ( row , col ) .ContainsWithInBoundingCircle ( p ) ) // { // c.Column = -1 ; // c.Row = -1 ; // } //else { c.Column = col ; c.Row = row ; } } // return c ; }",Getting cell co ordinates on Honeycomb pattern "C_sharp : I have a form with a ComboBox . I found the post : http : //blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/ that helped me to centre-align all the items in the DropDown list . The problem is that the selected item ( the item shown in the comboBox.Text property ) remains left aligned.How can I centre-align also the selected Item ? The code is : using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Linq ; using System.Text ; using System.Windows.Forms ; namespace ComboBoxTextProperty { public partial class Form3 : Form { public Form3 ( ) { InitializeComponent ( ) ; List < string > source = new List < string > ( ) { `` 15 '' , `` 63 '' , `` 238 '' , `` 1284 '' , `` 13561 '' } ; comboBox1.DataSource = source ; comboBox1.DrawMode = DrawMode.OwnerDrawFixed ; comboBox1.DropDownStyle = ComboBoxStyle.DropDown ; comboBox1.SelectedIndex = 0 ; comboBox1.DrawItem += new DrawItemEventHandler ( ComboBox_DrawItem ) ; } /// < summary > /// Allow the text in the ComboBox to be center aligned . /// Change the DrawMode Property from Normal to either OwnerDrawFixed or OwnerDrawVariable . /// If DrawMode is not changed , the DrawItem event will NOT fire and the DrawItem event handler will not execute . /// For a DropDownStyle of DropDown , the selected item remains left aligned but the expanded dropped down list is centered . /// < /summary > /// < param name= '' sender '' > < /param > /// < param name= '' e '' > < /param > private void ComboBox_DrawItem ( object sender , DrawItemEventArgs e ) { ComboBox comboBox1 = sender as ComboBox ; // By using sender , one method could handle multiple ComboBoxes . if ( comboBox1 ! = null ) { e.DrawBackground ( ) ; // Always draw the background . if ( e.Index > = 0 ) // If there are items to be drawn . { StringFormat format = new StringFormat ( ) ; // Set the string alignment . Choices are Center , Near and Far . format.LineAlignment = StringAlignment.Center ; format.Alignment = StringAlignment.Center ; // Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings . // Assumes Brush is solid . Brush brush = new SolidBrush ( comboBox1.ForeColor ) ; if ( ( e.State & DrawItemState.Selected ) == DrawItemState.Selected ) // If drawing highlighted selection , change brush . { brush = SystemBrushes.HighlightText ; } e.Graphics.DrawString ( comboBox1.Items [ e.Index ] .ToString ( ) , comboBox1.Font , brush , e.Bounds , format ) ; // Draw the string . } } } } }",How to center-align a selected Item in a ComboBox in WinForms ? "C_sharp : I 'm currently implementing a browser helper object which would allow dragging emails from the outlook to the internet explorer 's page.I 'm following the approach described in the following post : Implementing a Drag-and-Drop function from MS Outlook into our web application . I 've got it working but only on x64 machines . On the x32/86 machines i 'm getting the exception in the following piece of code ( obviously i 've replaced real filename inserting with fake one for simplicity ) : On the executing the last ling of this code ( actually setting the fake HDROP descriptor ) i 'm getting the following exception : '' Invalid FORMATETC structure ( Exception from HRESULT : 0x80040064 ( DV_E_FORMATETC ) ) '' .Did someone experienced described problem or have an idea what can be the reason of this issue ? To be more specific about environment - i 'm having this trouble on win7 32 bit with IE 10 but i 'm pretty sure that the reason especially in that machine is 32 bit . DropFiles df = new DropFiles ( ) ; string filename = @ '' D : \projects\hello.txt '' ; byte [ ] binaryData = Encoding.Unicode.GetBytes ( filename ) ; binaryData = binaryData.Concat ( new byte [ ] { 0 , 0 } ) .ToArray ( ) ; IntPtr pointerToGlobalMemory = Marshal.AllocHGlobal ( Marshal.SizeOf ( df ) + binaryData.Length ) ; df.Files = Marshal.SizeOf ( df ) ; df.Wide = true ; Marshal.StructureToPtr ( df , pointerToGlobalMemory , true ) ; IntPtr newPointer = new IntPtr ( pointerToGlobalMemory.ToInt32 ( ) + Marshal.SizeOf ( df ) ) ; Marshal.Copy ( binaryData , 0 , newPointer , binaryData.Length ) ; var descriptorFormat = new COMInterop.FORMATETC ( ) ; descriptorFormat.cfFormat = HdropDescriptorId ; // 15descriptorFormat.ptd = IntPtr.Zero ; descriptorFormat.dwAspect = COMInterop.DVASPECT.DVASPECT_CONTENT ; descriptorFormat.lindex = -1 ; descriptorFormat.tymed = COMInterop.TYMED.TYMED_HGLOBAL ; var td = new COMInterop.STGMEDIUM ( ) ; td.unionmember = pointerToGlobalMemory ; td.tymed = COMInterop.TYMED.TYMED_HGLOBAL ; dataObject.SetData ( ref descriptorFormat , ref td , true ) ;",Drag/drop from outlook to internet explorer via BHO does n't work on x32/86 machines "C_sharp : Long time C # developer , learning F # . I picked a fairly functional-styled bit of C # code that I 'd written as a learning exercise - translate it to F # . I 've done a lot of reading about functional programming and use the functional constructs in C # regularly , but I 'm only a few hours into learning F # .This function is part of a program that solves a puzzle similar to `` LonPos 101 '' which you can find on Amazon , etc . The strategy used in the solver was based on recognizing that there are only 30 valid positions in the puzzle space , so a `` solution so far '' could be represented by a single integer , and every valid position of each piece could also be represented by a single integer and that a complete solution is a set containing one possible position from each of the 7 pieces where the `` weights '' of the 7 pieces add up to the solution weight ( 2^30-1 ) . In the given function , `` key '' is the `` primary key '' of the piece , wbk is `` weights by key '' - indexed by key , containing a list of valid positions for the corresponding piece , while `` w '' is the aforementioned `` solution-so-far '' . The return value is a map from key to chosen position and is filled-in on the exit path from a successful recursion that resulted in a solution . I found when developing the C # solution that making this a sorted list made the solution finder an order of magnitude faster , but it 's equally valid with an ordinary list.Here 's the C # function I 'm having trouble with : Here 's my attempt at an F # version - it compiles , but it does n't work correctly - it ends up failing with a KeyNotFoundException in the let ss= ... line when executing the case where w is not solutionWeight and key does equal 8 . It makes no sense to me why this line of code is even being executed in this case , but ... Point me in the right direction ! My next attempt will be to re-write the C # code in a more functional style first , but it feels like this version is on the verge of working ( while perhaps still far from idiomatic F # ) .UPDATE : I re-wrote the F # function to eliminate the loop by using a pair of mutually recursive functions . It does work , but it 's ~2X slower than the non-mutually-recursive C # version . How can I further improve it ? UPDATE : I tweaked it more - feeling a bit more F # ish , but I still feel like I should be able to get rid of more type annotations and use F # native types more . It 's a work in progress . int solutionWeight ; Dictionary < int , int > Evaluate ( int w , Dictionary < int , SortedSet < int > > wbk , int key ) { if ( w == solutionWeight ) return new Dictionary < int , int > ( ) ; if ( key == 8 ) return null ; foreach ( var w2 in wbk [ key ] ) { if ( ( w & w2 ) ! = 0 ) continue ; var s = Evaluate ( w | w2 , wbk , key + 1 ) ; if ( s ! = null ) { s.Add ( key , w2 ) ; return s ; } } return null ; } let rec Evaluate ( w : int , wbk : Dictionary < int , SortedSet < int > > , key : int ) : Dictionary < int , int > = if w = solutionWeight then Dictionary < int , int > ( ) else if key = 8 then null else // ... this is wrong - runs off the end of some collection - fails with key not found exception let ws = wbk . [ key ] | > Seq.filter ( fun w2 - > ( w2 & & & w ) = 0 ) /// ... for some reason , execution resumes here after the key = 8 clause above let ss = ws | > Seq.map ( fun w - > ( w , Evaluate ( w , wbk , key+1 ) ) ) let sw = ss | > Seq.find ( fun sw - > snd sw < > null ) let s = snd sw s.Add ( key , fst sw ) s let rec Evaluate ( w : int , wbk : Dictionary < int , SortedSet < int > > , key : int ) : Dictionary < int , int > = if w = solutionWeight then Dictionary < int , int > ( ) else if key = 8 then null else EvalHelper ( w , wbk , key , wbk . [ key ] .GetEnumerator ( ) ) and EvalHelper ( w : int , wbk : Dictionary < int , SortedSet < int > > , key : int , ws : IEnumerator < int > ) : Dictionary < int , int > = if ws.MoveNext ( ) then let w2 = ws.Current if ( w & & & w2 ) = 0 then let s = Evaluate ( w ||| w2 , wbk , key+ 1 ) if s < > null then s.Add ( key , w2 ) s else EvalHelper ( w , wbk , key , ws ) else EvalHelper ( w , wbk , key , ws ) else null let rec Evaluate ( w , wbk : Dictionary < int , SortedSet < int > > , key ) : Dictionary < int , int > option = let rec EvalHelper ( ws ) = match ws with | w2 : : mws - > match w & & & w2 with | 0 - > let s = Evaluate ( w ||| w2 , wbk , key+ 1 ) match s with | None - > EvalHelper ( mws ) | Some s - > s.Add ( key , w2 ) Some ( s ) | _ - > EvalHelper ( mws ) | _ - > None if w = solutionWeight then Some ( Dictionary < int , int > ( ) ) else if key = 8 then None else EvalHelper ( List.ofSeq wbk . [ key ] )",Recursive C # function returns from inside a for-loop - how to translate to F # ? "C_sharp : Consider the following method that stops a service : In order to unit test the the method I basically have two options : Use the Adapter pattern to wrap the ServiceController class 's methods I need into an interface I can control . This interface can then be injected into the service class ( a.k.a Inversion of Control ) . This way I have a loosely coupled code and can use the traditional mocking frameworks to test.Keep the class as is and useMicrosoft Moles ( or any other codedetouring framework ) to interceptthe calls to ServiceController toreturn canned results for testingpurposes . I agree that for domain model code that using the `` traditional '' unit testing approach makes the most sense as this would lead to a design that is easiest to maintain . However , for code that deals with the .net implementation of Windows API related stuff ( file system , services , etc ) , is there really an advantage to going thru the extra work to get `` traditionally '' testable code ? It 's hard for me to see the disadvantages of using Microsoft Moles for things such as ServiceController ( or the File object ) . I really do n't see any advantage of doing the traditional approach in this case . Am I missing anything ? Public Function StopService ( ByVal serviceName As String , ByVal timeoutMilliseconds As Double ) As Boolean Try Dim service As New ServiceController ( serviceName ) Dim timeout As TimeSpan = TimeSpan.FromMilliseconds ( timeoutMilliseconds ) service . [ Stop ] ( ) If timeoutMilliseconds < = 0 Then service.WaitForStatus ( ServiceControllerStatus.Stopped ) Else service.WaitForStatus ( ServiceControllerStatus.Stopped , timeout ) End If Return service.Status = ServiceControllerStatus.Stopped Catch ex As Win32Exception 'error occured when accessing a system API ' Return False Catch ex As TimeoutException Return False End TryEnd Function","What are the advantages to wrapping system objects ( File , ServiceController , etc ) using the Adapter pattern vs. detouring for unit testing ?" "C_sharp : I have the following array : Each element of this array references another array.However , most elements reference the same array . In fact , array A only references two or three unique arrays.Is there an easy way to determine how much memory the entire thing uses ? byte [ ] [ ] A = new byte [ 256 ] [ ] ; A [ n ] = new byte [ 256 ] ;",Determining the number of bytes used by a variable "C_sharp : I 've been trying to create a generic event . Basically it should look like this : I want to allow the user to pass any delegate which 's second parameter is derived from `` ISomeInterface . `` `` in '' specifies contra-variance , right ? That means if the API is expecting something more general , you can pass it something more specific ( in my base `` ISomeInterface '' would be general , and my `` SomeDerivedClass '' would be specific . ) I am , however , being told my the compiler that `` no overload for method handler matches DelegateTest.SomeClass.SomeEventDelegate . '' I am wondering why this is n't working . What are the problems that would be caused if it was ? Or am I missing something for it to work ? Thanks in advance ! namespace DelegateTest { class Program { static void Main ( string [ ] args ) { var lol = new SomeClass ( ) ; lol.SomeEvent += handler ; } static void handler ( object sender , SomeDerivedClass e ) { } } class SomeClass { public delegate void SomeEventDelegate < in T > ( object sender , T data ) ; public event SomeEventDelegate < ISomeInterface > SomeEvent ; } interface ISomeInterface { } class SomeDerivedClass : ISomeInterface { } }",EventHandlers and Covariance "C_sharp : I was given this question at a job interview recently and could n't figure out how to do it elegantly . Ever since , it has been nagging away at me and I ca n't work out if its a lack of knowledge about some 'modern ' technique/technology I 'm unaware of or if I 'm just stupid . Any advice would be very welcome.The ProblemImagine a simple class hierarchy : The problem is how to traverse a hierarchy of such objects and to print out all the people encountered . So for the following scenario : the output should be something like : All the processing needs to be done within a single method that accepts a single parameter of type Ancestor.I implemented , almost without thinking , a simple recursive solution but of course because of the way the objects involved relate to each other things are n't as simple as all that.Try as I might I can not think of a clean way of doing this and my post-interview Googlings have suggested I need to be doing something that is ( to me , with only a working knowledge of LINQ and List < T > ) something considerably more technically advanced than the sort of web-dev coding I 've been doing for the last decade or so . Is this the case ? Or should I be thinking of getting out of software development on the grounds that I 'm rubbish at it ? UpdateThanks to you all for your responses/suggestions . I 've accepted @ Daniel Hilgarth 's answer primarily because it was the only one I could genuinely understand : -o abstract class Person { public string Name { get ; set ; } } class Child : Person { } class Parent : Person { public List < Person > Children { get ; set ; } } class Ancestor : Parent { } Ancestor myAncestor = new Ancestor { Name = `` GrandDad '' , Children = new List < Person > { new Child { Name = `` Aunt '' } , new Child { Name = `` Uncle '' } , new Parent { Name = `` Dad '' , Children = new List < Person > { new Child { Name = `` Me '' } , new Child { Name = `` Sister '' } } } } } ; GrandDad - Aunt - Uncle - *Dad -Me -Sister",A tricky one involving List < T > and object casting "C_sharp : I see this type of code when looking through our working code base : orDisclaimer : I have not worked with CSS before . but I heard that we should separate css , js , html , C # , other than put them together.so , is the above code bad ? If yes , how is the better approach ? private Button AddClearButton ( ) { return new Button { OnClientClick = string.Format ( @ '' $ ( ' . { 0 } ' ) .css ( 'background-color ' , ' # FBFBFB ' ) ; $ ( ' # ' + { 1 } ) .val ( `` ) ; $ ( ' # ' + { 2 } ) .val ( `` ) ; return false ; '' , _className , _hiddenImageNameClientId , _hiddenPathClientId ) , Text = LanguageManager.Instance.Translate ( `` /button/clear '' ) } ; } _nameAndImageDiv = new HtmlGenericControl ( `` div '' ) ; var imageDiv = new HtmlGenericControl ( `` div '' ) ; imageDiv.Attributes.Add ( `` style '' , `` width : 70px ; height : 50px ; text-align : center ; padding-top : 5px ; `` ) ; var nameDiv = new HtmlGenericControl ( `` div '' ) ; nameDiv.Attributes.Add ( `` style '' , `` width : 70px ; word-wrap : break-word ; text-align : center ; '' ) ; var image = new HostingThumbnailImage ( ) ;",Is embedding CSS/jQuery code in C # code bad ? "C_sharp : We are creating a WPF application which makes heavy use of highly decorated input elements . A simple example of decorated element is a TextBox which looks like a read-only TextBlock when it does n't have focus , and turns into a TextBox after receiving focus . Also , additional visual feedback is provided when the changed value is being saved to database . The problem is that showing a view that contains lots of these elements ( let 's say 100 ) is very slow and makes application very unresponsive.We have implemented this decorator as UserControl which contains all required elements ( for example the TextBlock to show unfocused text and rotating image for busy indicator ) . Then we add the input element as child of this decorator control , meaning that in addition to all extra elements , the decorator also contains the input element in its visual tree . In XAML this would look like : This makes it easy for us to decorate any input element we want , be it either text box , date picker , combobox or any custom element . Now back to the problem : let 's say we have a view which contains 100 decorated text boxes and we navigate to that view . What happens ? At least my quad-core laptop freezes for a long time because it has to create many hundred text blocks , rectangles , images etc . to provide the visual feedback for every decorated element , although no decorations are visible yet . What really would be required is only 100 TextBlocks because that 's what is visible on the screen . It is only after element receives mouse over event or focus when other elements are needed . Also , only one element is being edited at a time , so only one input element ( in this case , textbox ) would be enough for the whole application.So , what would be the best way to achieve same decorations without creating all decorating elements ( or the actual input element ) for every element in the view ? An example of decorated TextBox to clarify use-case : The text box looks like a read-only TextBlock when it does not have focus or mouse cursor is not currently on top of it ( state 1 ) . Also , three dots ( `` ... '' ) are shown because element does not currenly have any value . When mouse cursor is moved on top of the element , a dotted green rectangle appears around TextBlock to indicate that element can be modified ( state 2 ) . The color would be red if TextBox happened to be read-only . After receiving focus element turns into actual TextBox which can be used to modify the actual value ( state 3 ) . The value is stored into database after textbox loses its focus , and to show that the value is currently being saved a busy indicator appears to left side of element ( state 4 ) . Finally , the value has been saved and element returns to its idle state showing the new value ( state 5 ) . ( Actually the elements have even more states related to validation and other specific requirements but you certainly got the point that elements really are highly decorated . ) < custom : Decorator Context= '' { Binding ValueHelper } '' > < TextBox Text= '' { Binding ValueHelper.Text } '' / > < /custom : Decorator >",How to create UI elements lazily in WPF ? "C_sharp : We have a method that accesses a network share . This method works fine when called directly , but we get a System.IO.IOException when it is called via reflecton . It appear that the user context is not available to the reflected code ( see stack trace below ) . Is there a way to prevent this ? this worksthis does not workWhere Library.Class.execute is defined asand serverPath is a network share that required the user enter credentials. -- -- -Update 1 -- -- -- -This appears to be somewhat environmental -- I have at least one test machine where everything works . I 'll be doing some more testing to determine what differences matter . System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation . -- - > System.IO.IOException : Logon failure : unknown user name or bad password.at System.IO.__Error.WinIOError ( Int32 errorCode , String maybeFullPath ) at System.IO.Directory.InternalGetFileDirectoryNames ( String path , String userPathOriginal , String searchPattern , Boolean includeFiles , Boolean includeDirs , SearchOption searchOption ) at System.IO.Directory.GetDirectories ( String path , String searchPattern , SearchOption searchOption ) Library.Class obj =new Library.Class ( ) ; obj.Execute ( serverPath ) ; Assembly assembly = Assembly.LoadFile ( @ '' pathTo\Library.dll '' ) ; Type type = assembly.GetType ( `` Library.Class '' ) ; MethodInfo executeMethod = type.GetMethod ( `` Execute '' ) ; object classInstance = Activator.CreateInstance ( type , null ) ; object [ ] parameterArray = new object [ ] { serverPath } ; executeMethod.Invoke ( classInstance , parameterArray ) ; public void Execute ( string serverPath ) { string [ ] directories = Directory.GetDirectories ( serverPath , `` 1 . * '' , SearchOption.TopDirectoryOnly ) ; foreach ( var directory in directories ) { Console.WriteLine ( directory ) ; } }",Accessing network shares in Reflected method calls "C_sharp : how can i send an email as a part of a gmail-conversation via smtp ? Taking the same subject doesnt work ... tell me if you need more infos ... thanks in advance ! MailMessage mail = new MailMessage ( ) ; SmtpClient SmtpServer = new SmtpClient ( `` smtp.gmail.com '' ) ; mail.From = new MailAddress ( `` @ googlemail.com '' ) ; mail.To.Add ( `` @ .com '' ) ; mail.Subject = `` ( Somee.com notification ) New order confirmation '' ; mail.Body = `` ( Somee.com notification ) New order confirmation '' ; SmtpServer.Port = 587 ; SmtpServer.Credentials = new System.Net.NetworkCredential ( `` '' , `` '' ) ; SmtpServer.EnableSsl = true ; SmtpServer.Send ( mail ) ;",gmail Conversation via smtp "C_sharp : I want to get the week number of a certain given DateTime . And then I use the above method in : And finally : Description : An unhandled exception occurred during the execution of the current web request . Please review the stack trace for more information about the error and where it originated in the code . Exception Details : SD.LLBLGen.Pro.ORMSupportClasses.ORMQueryConstructionException : The binary expression ' ( WeekOf ( Convert ( EntityField ( LPLA_1.StartDate AS StartDate ) ) ) == 19 ) ' ca n't be converted to a predicate expression.I do get the title error at return q.ToList ( ) ; . How can I achieve this ? public static int WeekOf ( DateTime ? date ) { if ( date.HasValue ) { GregorianCalendar gCalendar = new GregorianCalendar ( ) ; int WeekNumber = gCalendar.GetWeekOfYear ( date.Value , CalendarWeekRule.FirstFourDayWeek , DayOfWeek.Monday ) ; return WeekNumber ; } else return 0 ; } public static List < ExpressionListDictionary > MyMethod ( int weeknr ) { using ( DataAccessAdapter adapter = CreateAdapter ( ) ) { LinqMetaData meta = new LinqMetaData ( adapter ) ; var q = ( from i in meta.Test where WeekOf ( i.StartDate ) == weeknr select new ExpressionListDictionary ( ) { { `` SomeId '' , i.Id } } ) ; return q.ToList ( ) ; } } List < ExpressionListDictionary > someIDs = MyMethod ( weeknr ) ; /* weeknr = 19 - > step by step debugging */",the binary expression can not be converted to a predicate expression in LINQ "C_sharp : With the model above I try to serialize the following object : Where are my two values from TestA ? It 's possible duplicate from this thread ( XML ) , but I want to know if there is no option to include those values by setting some JSON serialize option ? Note : Creating a property List < B > in class A instead of inheritance is no option for me . [ DataContract ] public class A : List < B > { [ DataMember ] public double TestA { get ; set ; } } [ DataContract ] public class B { [ DataMember ] public double TestB { get ; set ; } } List < A > list = new List < A > ( ) { new A ( ) { TestA = 1 } , new A ( ) { TestA = 3 } } ; json = JsonConvert.SerializeObject ( list ) ; //json : [ [ ] , [ ] ]",Serialize object when the object inherits from list "C_sharp : I 'm writing different implementations of immutable binary trees in C # , and I wanted my trees to inherit some common methods from a base class.Unfortunately , classes which derive from the base class are abysmally slow . Non-derived classes perform adequately . Here are two nearly identical implementations of an AVL tree to demonstrate : AvlTree : http : //pastebin.com/V4WWUAyTDerivedAvlTree : http : //pastebin.com/PussQDmNThe two trees have the exact same code , but I 've moved the DerivedAvlTree.Insert method in base class . Here 's a test app : AvlTree : inserts 5000 items in 121 msDerivedAvlTree : inserts 5000 items in 2182 msMy profiler indicates that the program spends an inordinate amount of time in BaseBinaryTree.Insert . Anyone whose interested can see the EQATEC log file I 've created with the code above ( you 'll need EQATEC profiler to make sense of file ) .I really want to use a common base class for all of my binary trees , but I ca n't do that if performance will suffer.What causes my DerivedAvlTree to perform so badly , and what can I do to fix it ? using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; using Juliet.Collections.Immutable ; namespace ConsoleApplication1 { class Program { const int VALUE_COUNT = 5000 ; static void Main ( string [ ] args ) { var avlTreeTimes = TimeIt ( TestAvlTree ) ; var derivedAvlTreeTimes = TimeIt ( TestDerivedAvlTree ) ; Console.WriteLine ( `` avlTreeTimes : { 0 } , derivedAvlTreeTimes : { 1 } '' , avlTreeTimes , derivedAvlTreeTimes ) ; } static double TimeIt ( Func < int , int > f ) { var seeds = new int [ ] { 314159265 , 271828183 , 231406926 , 141421356 , 161803399 , 266514414 , 15485867 , 122949829 , 198491329 , 42 } ; var times = new List < double > ( ) ; foreach ( int seed in seeds ) { var sw = Stopwatch.StartNew ( ) ; f ( seed ) ; sw.Stop ( ) ; times.Add ( sw.Elapsed.TotalMilliseconds ) ; } // throwing away top and bottom results times.Sort ( ) ; times.RemoveAt ( 0 ) ; times.RemoveAt ( times.Count - 1 ) ; return times.Average ( ) ; } static int TestAvlTree ( int seed ) { var rnd = new System.Random ( seed ) ; var avlTree = AvlTree < double > .Create ( ( x , y ) = > x.CompareTo ( y ) ) ; for ( int i = 0 ; i < VALUE_COUNT ; i++ ) { avlTree = avlTree.Insert ( rnd.NextDouble ( ) ) ; } return avlTree.Count ; } static int TestDerivedAvlTree ( int seed ) { var rnd = new System.Random ( seed ) ; var avlTree2 = DerivedAvlTree < double > .Create ( ( x , y ) = > x.CompareTo ( y ) ) ; for ( int i = 0 ; i < VALUE_COUNT ; i++ ) { avlTree2 = avlTree2.Insert ( rnd.NextDouble ( ) ) ; } return avlTree2.Count ; } } }",Why does my performance slow to a crawl I move methods into a base class ? "C_sharp : I am expecting a HashSet that has been created with a specified EqualityComparer to use that comparer on a Remove operation . Especially since the Contains operations returns true ! Here is the code I am using : Below is some quick and dirty LINQ that gets me the logic I want , but I am guessing the HashSet remove based on the EqualityComparer would be significantly faster.Can anyone suggest why the Remove would fail when the Contains succeeds ? Cheers , Berryl=== EDIT === the comparer=== UPDATE - FIXED ===Well , the good news is that HashSet is not broken and works exactly as it should . The bad news , for me , is how incredibly stupid I can be when not being able to see the forest while examining the leaves on the trees ! The answer is actually in the posted code above , if you look at the class creating & owning the HashSet , and then taking another look at the Comparer to find out what is wrong with it . Easy points for the first person to spot it.Thanks to all who looked at the code ! public virtual IEnumerable < Allocation > Allocations { get { return _allocations ; } } private ICollection < Allocation > _allocations ; public Activity ( IActivitySubject subject ) { // constructor ... . _allocations = new HashSet < Allocation > ( new DurationExcludedEqualityComparer ( ) ) ; } public virtual void ClockIn ( Allocation a ) { ... if ( _allocations.Contains ( a ) ) _allocations.Remove ( a ) ; _allocations.Add ( a ) ; } public virtual void ClockIn ( Allocation a ) { ... var found = _allocations.Where ( x = > x.StartTime.Equals ( a.StartTime ) & & x.Resource.Equals ( a.Resource ) ) .FirstOrDefault ( ) ; if ( found ! = null ) { if ( ! Equals ( found.Duration , a.Duration ) ) { found.UpdateDurationTo ( a.Duration ) ; } } else { _allocations.Add ( a ) ; } public class DurationExcludedEqualityComparer : EqualityComparer < Allocation > { public override bool Equals ( Allocation lhs , Allocation rhs ) { if ( ReferenceEquals ( null , rhs ) ) return false ; if ( ReferenceEquals ( lhs , null ) ) return false ; if ( ReferenceEquals ( lhs , rhs ) ) return true ; return lhs.StartTime.Equals ( rhs.StartTime ) & & lhs.Resource.Equals ( rhs.Resource ) & & lhs.Activity.Equals ( rhs.Activity ) ; } public override int GetHashCode ( Allocation obj ) { if ( ReferenceEquals ( obj , null ) ) return 0 ; unchecked { var result = 17 ; result = ( result * 397 ) ^ obj.StartTime.GetHashCode ( ) ; result = ( result * 397 ) ^ ( obj.Resource ! = null ? obj.Resource.GetHashCode ( ) : 0 ) ; result = ( result * 397 ) ^ ( obj.Activity ! = null ? obj.Activity.GetHashCode ( ) : 0 ) ; return result ; } } }",HashSet.Remove not working with EqualityComparer "C_sharp : In the code below , I have a catch block for System.Data.Entity.Infrastructure.DbUpdateException class exception . My question is that why I ca n't use Exception class to catch each and every possible exception in my code and get stacktrace ? What is the advantage of specific exception types and their use in multiple catch blocks ? try { AddAdminUserInput input1 = JsonConvert.DeserializeObject < AddAdminUserInput > ( input ) ; Foundation_Services_DL_DataEntities Db = DLMetadataContext.GetContext ( ) ; UserAccount account = new UserAccount { emplid = input1.emplid , sso = input1.sso , deptid = input1.deptid , usertype = input1.usertype , status = input1.status , username = input1.username } ; Db.UserAccounts.Add ( account ) ; Db.SaveChanges ( ) ; Dictionary < string , string > dict = new Dictionary < string , string > ( ) ; dict.Add ( `` status '' , `` 0 '' ) ; dict.Add ( `` message '' , `` User Addition Successful '' ) ; Context.Response.Write ( JsonConvert.SerializeObject ( dict ) ) ; } catch ( System.Data.Entity.Infrastructure.DbUpdateException dbev ) { Dictionary < string , string > dict = new Dictionary < string , string > ( ) ; dict.Add ( `` status '' , `` 1 '' ) ; dict.Add ( `` message '' , `` User Addition Failed - User Already Exists '' ) ; Context.Response.Write ( JsonConvert.SerializeObject ( dict ) ) ; }",Why use specific exception catch blocks "C_sharp : I need to marshal some nested structures in C # 4.0 into binary blobs to pass to a C++ framework.I have so far had a lot of success using unsafe/fixed to handle fixed length arrays of primitive types . Now I need to handle a structure that contains nested fixed length arrays of other structures.I was using complicated workarounds flattening the structures but then I came across an example of the MarshalAs attribute which looked like it could save me a great deal of problems.Unfortunately whilst it gives me the correct amount of data it seems to also stop the fixed arrays from being marshalled properly , as the output of this program demonstrates . You can confirm the failure by putting a breakpoint on the last line and examining the memory at each pointer.Output : So for some reason it is only marshalling the first character of my fixed ANSI strings . Is there any way around this , or have I done something stupid unrelated to the marshalling ? using System ; using System.Threading ; using System.Runtime.InteropServices ; namespace MarshalNested { public unsafe struct a_struct_test1 { public fixed sbyte a_string [ 3 ] ; public fixed sbyte some_data [ 12 ] ; } public struct a_struct_test2 { [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 3 ) ] public sbyte [ ] a_string ; [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 4 ) ] public a_nested [ ] some_data ; } public unsafe struct a_struct_test3 { public fixed sbyte a_string [ 3 ] ; [ MarshalAs ( UnmanagedType.ByValArray , SizeConst = 4 ) ] public a_nested [ ] some_data ; } public unsafe struct a_nested { public fixed sbyte a_notherstring [ 3 ] ; } class Program { static unsafe void Main ( string [ ] args ) { a_struct_test1 lStruct1 = new a_struct_test1 ( ) ; lStruct1.a_string [ 0 ] = ( sbyte ) ' a ' ; lStruct1.a_string [ 1 ] = ( sbyte ) ' b ' ; lStruct1.a_string [ 2 ] = ( sbyte ) ' c ' ; a_struct_test2 lStruct2 = new a_struct_test2 ( ) ; lStruct2.a_string = new sbyte [ 3 ] ; lStruct2.a_string [ 0 ] = ( sbyte ) ' a ' ; lStruct2.a_string [ 1 ] = ( sbyte ) ' b ' ; lStruct2.a_string [ 2 ] = ( sbyte ) ' c ' ; a_struct_test3 lStruct3 = new a_struct_test3 ( ) ; lStruct3.a_string [ 0 ] = ( sbyte ) ' a ' ; lStruct3.a_string [ 1 ] = ( sbyte ) ' b ' ; lStruct3.a_string [ 2 ] = ( sbyte ) ' c ' ; IntPtr lPtr1 = Marshal.AllocHGlobal ( 15 ) ; Marshal.StructureToPtr ( lStruct1 , lPtr1 , false ) ; IntPtr lPtr2 = Marshal.AllocHGlobal ( 15 ) ; Marshal.StructureToPtr ( lStruct2 , lPtr2 , false ) ; IntPtr lPtr3 = Marshal.AllocHGlobal ( 15 ) ; Marshal.StructureToPtr ( lStruct3 , lPtr3 , false ) ; string s1 = `` '' ; string s2 = `` '' ; string s3 = `` '' ; for ( int x = 0 ; x < 3 ; x++ ) { s1 += ( char ) Marshal.ReadByte ( lPtr1+x ) ; s2 += ( char ) Marshal.ReadByte ( lPtr2+x ) ; s3 += ( char ) Marshal.ReadByte ( lPtr3+x ) ; } Console.WriteLine ( `` Ptr1 ( size `` + Marshal.SizeOf ( lStruct1 ) + `` ) says `` + s1 ) ; Console.WriteLine ( `` Ptr2 ( size `` + Marshal.SizeOf ( lStruct2 ) + `` ) says `` + s2 ) ; Console.WriteLine ( `` Ptr3 ( size `` + Marshal.SizeOf ( lStruct3 ) + `` ) says `` + s3 ) ; Thread.Sleep ( 10000 ) ; } } } Ptr1 ( size 15 ) says abcPtr2 ( size 15 ) says abcPtr3 ( size 15 ) says a",C # interop : bad interaction between fixed and MarshalAs "C_sharp : Please see question embedded in comment below.I 'm open to considering alternative implementations that reuse the base constructor and minimize initialization code . I 'd like to keep the _customField readonly , which is not possible if I extract a separate initialization method . public class CustomException : Exception { private readonly string _customField ; public CustomException ( string customField , string message ) : base ( message ) { // What 's the best way to reuse the customField initialization code in the // overloaded constructor ? Something like this ( customField ) } public CustomException ( string customField ) { _customField = customField ; } }","When chaining a base constructor , how can I reuse initialization code in an overload" "C_sharp : I was trying to migrate .Net Core console app and tests from 2.1 to 3.1 and got a problem in my tests . I was using Moq library and it was working fine . After migration i started to get A non-collectible assembly may not reference a collectible assembly when trying to access any mocked objects . I have reproduced same behavior in completely new project . I was not able to find any relevant information on this topic . I have tested it with both MSTest and Xunit . Is this a Moq library issue or .Net Core 3.1 should use different approach to such cases ? Exception : Project file : using Moq ; using Xunit ; namespace NetCore3.Tests { public interface IMyInterface { } public class UnitTest { [ Fact ] public void Test ( ) { var mock = new Mock < IMyInterface > ( ) ; var tmp = mock.Object ; // this line throwing exception } } } NetCore3.Tests.UnitTest.TestSystem.NotSupportedException : A non-collectible assembly may not reference a collectible assembly.System.NotSupportedExceptionA non-collectible assembly may not reference a collectible assembly . at System.Reflection.Emit.ModuleBuilder.GetTypeRef ( QCallModule module , String strFullName , QCallModule refedModule , String strRefedModuleFileName , Int32 tkResolution ) at System.Reflection.Emit.ModuleBuilder.GetTypeRefNested ( Type type , Module refedModule , String strRefedModuleFileName ) at System.Reflection.Emit.ModuleBuilder.GetTypeTokenWorkerNoLock ( Type type , Boolean getGenericDefinition ) at System.Reflection.Emit.ModuleBuilder.GetTypeTokenInternal ( Type type , Boolean getGenericDefinition ) at System.Reflection.Emit.TypeBuilder.AddInterfaceImplementation ( Type interfaceType ) at Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor ( ModuleScope modulescope , String name , Type baseType , IEnumerable ` 1 interfaces , TypeAttributes flags , Boolean forceUnsigned ) at Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter ( String typeName , Type parentType , IEnumerable ` 1 interfaces ) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.Init ( String typeName , ClassEmitter & emitter , Type proxyTargetType , FieldReference & interceptorsField , IEnumerable ` 1 interfaces ) at Castle.DynamicProxy.Generators.InterfaceProxyWithoutTargetGenerator.GenerateType ( String typeName , Type proxyTargetType , Type [ ] interfaces , INamingScope namingScope ) at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator. < > c__DisplayClass6_0. < GenerateCode > b__0 ( String n , INamingScope s ) at Castle.Core.Internal.SynchronizedDictionary ` 2.GetOrAdd ( TKey key , Func ` 2 valueFactory ) at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType ( CacheKey cacheKey , Func ` 3 factory ) at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget ( Type interfaceToProxy , Type [ ] additionalInterfacesToProxy , ProxyGenerationOptions options , IInterceptor [ ] interceptors ) at Moq.Mock ` 1.InitializeInstance ( ) at Moq.Mock ` 1.OnGetObject ( ) at Moq.Mock ` 1.get_Object ( ) at NetCore3.Tests.UnitTest.Test ( ) in C : \Work\NetCore3\NetCore3.Tests\UnitTest1.cs : line 14 < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < TargetFramework > netcoreapp3.1 < /TargetFramework > < IsPackable > false < /IsPackable > < /PropertyGroup > < ItemGroup > < PackageReference Include= '' Microsoft.NET.Test.Sdk '' Version= '' 16.6.1 '' / > < PackageReference Include= '' Moq '' Version= '' 4.14.5 '' / > < PackageReference Include= '' xunit '' Version= '' 2.4.1 '' / > < PackageReference Include= '' xunit.runner.visualstudio '' Version= '' 2.4.2 '' / > < PackageReference Include= '' coverlet.collector '' Version= '' 1.3.0 '' / > < /ItemGroup > < /Project >",A non-collectible assembly may not reference a collectible assembly "C_sharp : In a comment on this answer ( which suggests using bit-shift operators over integer multiplication / division , for performance ) , I queried whether this would actually be faster . In the back of my mind is an idea that at some level , something will be clever enough to work out that > > 1 and / 2 are the same operation . However , I 'm now wondering if this is in fact true , and if it is , at what level it occurs.A test program produces the following comparative CIL ( with optimize on ) for two methods that respectively divide and shift their argument : versusSo the C # compiler is emitting div or shr instructions , without being clever . I would now like to see the actual x86 assembler that the JITter produces , but I have no idea how to do this . Is it even possible ? edit to addFindingsThanks for answers , have accepted the one from nobugz because it contained the key information about that debugger option . What eventually worked for me is : Switch to Release configurationIn Tools | Options | Debugger , switch off 'Suppress JIT optimization on module load ' ( ie we want to allow JIT optimization ) Same place , switch off 'Enable Just My Code ' ( ie we want to debug all code ) Put a Debugger.Break ( ) statement somewhereBuild the assemblyRun the .exe , and when it breaks , debug using the existing VS instanceNow the Disassembly window shows you the actual x86 that 's going to be executedThe results were enlightening to say the least - it turns out the JITter can actually do arithmetic ! Here 's edited samples from the Disassembly window . The various -Shifter methods divide by powers of two using > > ; the various -Divider methods divide by integers using /Both statically-divide-by-2 methods have not only been inlined , but the actual computations have been done by the JITterSame with statically-divide-by-3.And statically-divide-by-4.The best : It 's inlined and then computed all these static divisions ! But what if the result is n't static ? I added to code to read an integer from the Console . This is what it produces for the divisions on that : So despite the CIL being different , the JITter knows that dividing by 2 is right-shifting by 1.00000283 idiv eax , ecx And it knows you have to divide to divide by 3.And it knows that dividing by 4 is right-shifting by 2.Finally ( the best again ! ) It has inlined the method and worked out the best way to do things , based on the statically-available arguments . Nice.So yes , somewhere in the stack between C # and x86 , something is clever enough to work out that > > 1 and / 2 are the same . And all this has given even more weight in my mind to my opinion that adding together the C # compiler , the JITter , and the CLR makes a whole lot more clever than any little tricks we can try as humble applications programmers : ) IL_0000 : ldarg.0 IL_0001 : ldc.i4.2 IL_0002 : div IL_0003 : ret } // end of method Program : :Divider IL_0000 : ldarg.0 IL_0001 : ldc.i4.1 IL_0002 : shr IL_0003 : ret } // end of method Program : :Shifter Console.WriteLine ( string.Format ( `` { 0 } shift-divided by 2 : { 1 } divide-divided by 2 : { 2 } '' , 60 , TwoShifter ( 60 ) , TwoDivider ( 60 ) ) ) ; 00000026 mov dword ptr [ edx+4 ] ,3Ch ... 0000003b mov dword ptr [ edx+4 ] ,1Eh ... 00000057 mov dword ptr [ esi+4 ] ,1Eh Console.WriteLine ( string.Format ( `` { 0 } divide-divided by 3 : { 1 } '' , 60 , ThreeDivider ( 60 ) ) ) ; 00000085 mov dword ptr [ esi+4 ] ,3Ch ... 000000a0 mov dword ptr [ esi+4 ] ,14h Console.WriteLine ( string.Format ( `` { 0 } shift-divided by 4 : { 1 } divide-divided by 4 { 2 } '' , 60 , FourShifter ( 60 ) , FourDivider ( 60 ) ) ) ; 000000ce mov dword ptr [ esi+4 ] ,3Ch ... 000000e3 mov dword ptr [ edx+4 ] ,0Fh ... 000000ff mov dword ptr [ esi+4 ] ,0Fh Console.WriteLine ( string.Format ( `` { 0 } n-divided by 2 : { 1 } n-divided by 3 : { 2 } n-divided by 4 : { 3 } '' , 60 , Divider ( 60 , 2 ) , Divider ( 60 , 3 ) , Divider ( 60 , 4 ) ) ) ; 0000013e mov dword ptr [ esi+4 ] ,3Ch ... 0000015b mov dword ptr [ esi+4 ] ,1Eh ... 0000017b mov dword ptr [ esi+4 ] ,14h ... 0000019b mov dword ptr [ edi+4 ] ,0Fh Console.WriteLine ( string.Format ( `` { 0 } shift-divided by 2 : { 1 } divide-divided by 2 : { 2 } '' , i , TwoShifter ( i ) , TwoDivider ( i ) ) ) ; 00000211 sar eax,1 ... 00000230 sar eax,1 Console.WriteLine ( string.Format ( `` { 0 } divide-divided by 3 : { 1 } '' , i , ThreeDivider ( i ) ) ) ; Console.WriteLine ( string.Format ( `` { 0 } shift-divided by 4 : { 1 } divide-divided by 4 { 2 } '' , i , FourShifter ( i ) , FourDivider ( i ) ) ) ; 000002c5 sar eax,2 ... 000002ec sar eax,2 Console.WriteLine ( string.Format ( `` { 0 } n-divided by 2 : { 1 } n-divided by 3 : { 2 } n-divided by 4 : { 3 } '' , i , Divider ( i , 2 ) , Divider ( i , 3 ) , Divider ( i , 4 ) ) ) ; 00000345 sar eax,1 ... 00000370 idiv eax , ecx ... 00000395 sar esi,2",Is there a way to see the native code produced by theJITter for given C # / CIL ? "C_sharp : I have a weird problem with a text file that I ship with my app.The file holds a bunch of sites , when the program starts it loads the sites into an array.On windows 7 , when I start the app I do n't get any errors . However , on XP I get c : \Document and setting\I\Application Data\fourmlinks.txt file not found.The weird part is that I made a text file with content with it , and I put it inside the application folder.This is how I call out in my code : My problem is that I ca n't create a new file because it is holding basic data that the app needs and is using.After the first launch the user can edit the file as much he wants.I 'm not sure why this is happening , but this is only happening on Windows XP.How can I solve this problem ? EDITkeyboardP suggest to check on what windows im runing and then change the path by it.so i came up with this code : the problem that even on windows 7 i get true , when i need to get false.is there a way to make sure i run on XP or Windows 7 i diffrent way ? EDIT 2using the check of the Operating System , I can now be sure I 'm Windows 7 or Windows XP.So , the code run find again on Windows 7 but on Windows XP I get a different error message : I really have no idea how the path that I add in my program becomes the path that the error is saying I 'm requesting . string path = Environment.GetFolderPath ( Environment.SpecialFolder.ApplicationData ) + `` \\fourmlinks.txt '' ; System.OperatingSystem osInfo = System.Environment.OSVersion ; if ( osInfo.Platform == PlatformID.Win32NT ) path = Environment.SpecialFolder.LocalApplicationData + `` \\fourmlinks.txt '' ; else path = Environment.GetFolderPath ( Environment.SpecialFolder.ApplicationData ) + `` \\fourmlinks.txt '' ;",File not found on xp "C_sharp : Is it possible to implement a class constrained to two unique generic parameters ? If it is not , is that because it is unimplemented or because it would be impossible given the language structure ( inheritance ) ? I would like something of the form : I am implementing a Bidirectional dictionary . This is mostly a question of curiosity , not of need.Paraphrased from the comments : Dan : `` What are the negative consequence if this constraint is not met ? `` Me : `` Then the user could index with map [ t1 ] and map [ t2 ] . If they were the same type , there would be no distinction and it would n't make any sense . `` Dan : The compiler actually allows [ two generic type parameters to define distinct method overloads ] , so I 'm curious ; does it arbitrarily pick one of the methods to call ? class BidirectionalMap < T1 , T2 > where T1 ! = T2 { ... }",A generic class with two non-equal ( unique ) types "C_sharp : I was looking over a fairly modern project created with a big emphasis on unit testing . In accordance with old adage `` every problem in object oriented programming can be solved by introducing new layer of indirection '' this project was sporting multiple layers of indirection . The side-effect was that fair amount of code looked like following : Now , because of the empahsis on unit testing and maintaining high code coverage , every piece of code had unit tests written against it.Therefore this little method would have three unit tests present . Those would check : If balanceProvider.IsOverdraft ( ) returns true then IsOverdraft should return trueIf balanceProvider.IsOverdraft ( ) returns false then IsOverdraft should return falseIf balanceProvider throws an exception then IsOverdraft should rethrow the same exceptionTo make things worse , the mocking framework used ( NMock2 ) accepted method names as string literals , as follows : That obviously made `` red , green , refactor '' rule into `` red , green , refactor , rename in test , rename in test , rename in test '' . Using differnt mocking framework like Moq , would help with refactoring , but it would require a sweep trough all existing unit tests.What is the ideal way to handle this situation ? A ) Keep smaller levels of layers , so that those forwarding calls do not happen anymore.B ) Do not test those forwarding methods , as they do not contain business logic . For purposes of coverage marked them all with ExcludeFromCodeCoverage attribute.C ) Test only if proper method is invoked , without checking return values , exceptions , etc.D ) Suck it up , and keep writing those tests ; ) public bool IsOverdraft ) { balanceProvider.IsOverdraft ( ) ; } NMock2.Expect.Once.On ( mockBalanceProvider ) .Method ( `` IsOverdraft '' ) .Will ( NMock2.Return.Value ( false ) ) ;",How to use unit tests in projects with many levels of indirection "C_sharp : How do you open the context menu of a window ( the normal Windows context that appears when you Right-Click the title-bar of a window ) .Things I 've tried ( on a button click ) And this : ReleaseCapture ( ) ; SendMessage ( this.Handle , WM_NCRBUTTONDOWN , 0 , 0 ) ; SendMessage ( this.Handle , WM_RBUTTONUP , 0 , 0 ) ; SendMessage ( this.Handle , WM_CONTEXTMENU , 0 , 0 ) ; ReleaseCapture ( ) ; SendMessage ( this.Handle , WM_NCRBUTTONDOWN , HT_CAPTION , 0 ) ; SendMessage ( this.Handle , WM_RBUTTONUP , HT_CAPTION , 0 ) ; SendMessage ( this.Handle , WM_CONTEXTMENU , HT_CAPTION , 0 ) ;",How to open the context menu of any window ? "C_sharp : I have a View ( Index.cshtml ) that it has two modals ( Bootstrap modal ) .I have loaded a Partial View in each ‍‍‍modal . So in this View , I have two Partial Views ( AddContractHistory.cshtml and AddCompany.cshtml ) .I have a model that it 's fields should be validated in each of the Partial Views . I need to validate each of the partial views separately.In same other issue , Html.BeginForm was used but I work on MVC module and DNN 8 that Html.BeginForm or Ajax.Html.BeginForm are n't supported.For doing this work without having BeginForm , I tested many ways like below but I could n't do it properly.ASP.NET MVC Validation Groups ? ASP.NET MVC Multiple form in one page : Validation does n't workIndex.cshtml ( View ) AddContractHistory.cshtml ( PartialView ) AddCompany.cshtml ( PartialView ) Thanks in advance ! @ using MyProject.BusinessLogic < div class= '' form-group '' > < div class= '' col-sm-12 '' > < button type= '' button '' class= '' btn btn-success '' onclick= '' $ ( ' # AddContractHistory ' ) .modal ( 'show ' ) ; '' > < i class= '' fa fa-plus '' > < /i > New ContractHistory < /button > < /div > < div class= '' col-sm-12 '' > < button type= '' button '' class= '' btn btn-success '' onclick= '' $ ( ' # AddCompany ' ) .modal ( 'show ' ) ; '' > < i class= '' fa fa-plus '' > < /i > New Company < /button > < /div > < /div > < div id= '' AddContractHistory '' class= '' modal fade '' role= '' dialog '' > < div class= '' modal-dialog modal-lg '' id= '' mymodal '' > @ Html.Partial ( `` AddContractHistory '' , new ContractHistory ( ) ) < /div > < /div > < div id= '' AddCompany '' class= '' modal fade '' role= '' dialog '' > < div class= '' modal-dialog modal-lg '' id= '' mymodal '' > @ Html.Partial ( `` AddCompany '' , new Company ( ) ) < /div > < /div > @ inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage < MyProject.BusinessLogic.ContractHistory > < div id= '' myform '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' > & times ; < /button > < h4 class= '' modal-title '' > contract < /h4 > < /div > < div class= '' modal-body '' > < div class= '' row '' > < div class= '' panel-body '' > < div class= '' form-horizontal '' > @ Html.ValidationSummary ( ) @ Html.HiddenFor ( c = > c.ID ) < div class= '' form-group '' > < div class= '' col-sm-6 '' > @ Html.LabelFor ( c = > c.PlaceName ) < div class= '' input-group '' > < span class= '' input-group-addon '' > < i class= '' fa fa-file-text-o '' aria-hidden= '' true '' > < /i > < /span > @ Html.EditorFor ( c = > c.PlaceName , new { htmlAttributes = new { @ class = `` form-control requierd-field '' } } ) < /div > < /div > < div class= '' col-sm-6 '' > @ Html.LabelFor ( c = > c.ActivityDescription ) < div class= '' input-group '' > < span class= '' input-group-addon '' > < i class= '' fa fa-file-text-o '' aria-hidden= '' true '' > < /i > < /span > @ Html.EditorFor ( c = > c.ActivityDescription , new { htmlAttributes = new { @ class = `` form-control requierd-field '' } } ) < /div > < /div > < /div > < /div > < /div > < /div > < /div > < div class= '' modal-footer '' > < button type= '' submit '' class= '' btn btn-success '' formaction= '' AddContractHistory '' > submit < /button > < button type= '' button '' class= '' btn btn-default '' data-dismiss= '' modal '' > cancel < /button > < /div > < /div > < /div > @ inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage < MyProject.BusinessLogic.Company > < div id= '' myform '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' > & times ; < /button > < h4 class= '' modal-title '' > Company < /h4 > < /div > < div class= '' modal-body '' > < div class= '' row '' > < div class= '' panel-body '' > < div class= '' form-horizontal '' > @ Html.ValidationSummary ( ) @ Html.HiddenFor ( c = > c.ID ) < div class= '' form-group '' > < div class= '' col-sm-6 '' > @ Html.LabelFor ( c = > c.PlaceName ) < div class= '' input-group '' > < span class= '' input-group-addon '' > < i class= '' fa fa-file-text-o '' aria-hidden= '' true '' > < /i > < /span > @ Html.EditorFor ( c = > c.PlaceName , new { htmlAttributes = new { @ class = `` form-control requierd-field '' } } ) < /div > < /div > < div class= '' col-sm-6 '' > @ Html.LabelFor ( c = > c.ActivityDescription ) < div class= '' input-group '' > < span class= '' input-group-addon '' > < i class= '' fa fa-file-text-o '' aria-hidden= '' true '' > < /i > < /span > @ Html.EditorFor ( c = > c.ActivityDescription , new { htmlAttributes = new { @ class = `` form-control requierd-field '' } } ) < /div > < /div > < /div > < /div > < /div > < /div > < /div > < div class= '' modal-footer '' > < button type= '' submit '' class= '' btn btn-success '' formaction= '' AddCompany '' > submit < /button > < button type= '' button '' class= '' btn btn-default '' data-dismiss= '' modal '' > cancel < /button > < /div > < /div > < /div >",Validate multiple Partial view without BeginForm in a View "C_sharp : I have this scenario in which memory conservation is paramount . I am trying to read in > 1 GB of Peptide sequences into memory and group peptide instances together that share the same sequence . I am storing the Peptide objects in a Hash so I can quickly check for duplication , but found out that you can not access the objects in the Set , even after knowing that the Set contains that object.Memory is really important and I do n't want to duplicate data if at all possible . ( Otherwise I would of designed my data structure as : peptides = Dictionary < string , Peptide > but that would duplicate the string in both the dictionary and Peptide class ) . Below is the code to show you what I would like to accomplish : Why does HashSet not let me get the object reference that is contained in the HashSet ? I know people will try to say that if HashSet.Contains ( ) returns true , your objects are equivalent . They may be equivalent in terms of values , but I need the references to be the same since I am storing additional information in the Peptide class . The only solution I came up with is Dictionary < Peptide , Peptide > in which both the key and value point to the same reference . But this seems tacky . Is there another data structure to accomplish this ? public SomeClass { // Main Storage of all the Peptide instances , class provided below private HashSet < Peptide > peptides = new HashSet < Peptide > ( ) ; public void SomeMethod ( IEnumerable < string > files ) { foreach ( string file in files ) { using ( PeptideReader reader = new PeptideReader ( file ) ) { foreach ( DataLine line in reader.ReadNextLine ( ) ) { Peptide testPep = new Peptide ( line.Sequence ) ; if ( peptides.Contains ( testPep ) ) { // ** Problem Is Here ** // I want to get the Peptide object that is in HashSet // so I can add the DataLine to it , I do n't want use the // testPep object ( even though they are considered `` equal '' ) peptides [ testPep ] .Add ( line ) ; // I know this does n't work testPep.Add ( line ) // THIS IS NO GOOD , since it wo n't be saved in the HashSet which i use in other methods . } else { // The HashSet does n't contain this peptide , so we can just add it testPep.Add ( line ) ; peptides.Add ( testPep ) ; } } } } } } public Peptide : IEquatable < Peptide > { public string Sequence { get ; private set ; } private int hCode = 0 ; public PsmList PSMs { get ; set ; } public Peptide ( string sequence ) { Sequence = sequence.Replace ( ' I ' , ' L ' ) ; hCode = Sequence.GetHashCode ( ) ; } public void Add ( DataLine data ) { if ( PSMs == null ) { PSMs = new PsmList ( ) ; } PSMs.Add ( data ) ; } public override int GethashCode ( ) { return hCode ; } public bool Equals ( Peptide other ) { return Sequence.Equals ( other.Sequence ) ; } } public PSMlist : List < DataLine > { // and some other stuff that is not important }",How to access the reference values of a HashSet < TValue > without enumeration ? C_sharp : The program was working with this implementation : But because I need to use Instrument in Dictionary I 've decided to implement equals/hashcode : Now the program has stopped working . In such or similar places I receive `` KeyNotFoundException '' : Is it possible that some pieces of the code assume that equals and hashcode IS NOT implemented ? Or probably I just implemented them wrong ? Sorry I 'm not familiar with such advanced features in C # as the last piece of code and do n't know how it is connected with equals or hashCode . class Instrument { public string ClassCode { get ; set ; } public string Ticker { get ; set ; } public override string ToString ( ) { return `` ClassCode : `` + ClassCode + `` Ticker : `` + Ticker + ' . ' ; } } class Instrument { public string ClassCode { get ; set ; } public string Ticker { get ; set ; } public override string ToString ( ) { return `` ClassCode : `` + ClassCode + `` Ticker : `` + Ticker + ' . ' ; } public override bool Equals ( object obj ) { if ( obj == null ) return false ; Instrument instrument = obj as Instrument ; if ( instrument == null ) return false ; return ( ( ClassCode.Equals ( instrument.ClassCode ) ) & & ( Ticker.Equals ( instrument.Ticker ) ) ; } public override int GetHashCode ( ) { int hash = 13 ; hash = ( hash * 7 ) + ClassCode.GetHashCode ( ) ; hash = ( hash * 7 ) + Ticker.GetHashCode ( ) ; return hash ; } } if ( cache.Keys.Any ( instrument = > instrument.Ticker == newTicker & & instrument.ClassCode == newClassCode ) ),Have I implemented Equals ( ) /GetHashCode ( ) correctly ? "C_sharp : I have an XAML button like this : I have no XAML styling attached to it and no resource dictionary styling it . No external thing is styling my button and that is fine ; that is how I want it.I want , now , to change the RadiusX and RadiusY of that button in code behind , because I want a button with rounded edges . I know System.Windows.Controls.Button does not have those properties , but I know a WPF rectangle does.I do n't know if this is correct ; but the WPF button control is made up of other controls ? Right ? Like perhaps a rectangle and a text block or label and by setting the Button.Content you 're actually changing the button 's inner label 's content . I 'm not sure how naive my thinking is there.The bottom line is I want to do something like this : I want it all in code , no XAML , because I have many buttons in different XAML files and I want to round their edges by calling one method in code without changing every single XAML file . Not all buttons in all my XAML files , just certain ones.I 'm already calling a single method in all my windows and user controls and I just want to add the button rounding edges styling to that method , and then it wo n't cause tedious code . < Button x : Name= '' buttonOK '' Content= '' OK '' / > buttonOK.InnerRectangle.RadiusX = 5 ; buttonOK.InnerRectangle.RadiusY = 5 ;",How do I set a button 's inner properties in code ? "C_sharp : What exactly is it that makes GDI+ switch to binary aliasing when using default Microsoft Office font Calibri between 9pt and 14pt with ClearTypeGridFit specified ? It 's somewhat disconcerting . How many other fonts are also affected by whatever is behind this , and at what sizes ? Is there a workaround ? ( Excluding GDI , which does n't have the same text layout features ? ) Here 's the code I used to generate the image : private void Form1_Paint ( object sender , PaintEventArgs e ) { e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit ; var height = 0 ; for ( var i = 1 ; i < = 17 ; i++ ) { using ( var font = new Font ( `` Calibri '' , i ) ) { var text = `` ClearTypeGridFit `` + i + `` pt '' ; e.Graphics.DrawString ( text , font , SystemBrushes.ControlText , 0 , height ) ; height += ( int ) e.Graphics.MeasureString ( text , font ) .Height ; } } }",What is causing Calibri to lose ClearType between 9 and 14 pt ? "C_sharp : In an asp.net-mvc project using C # .I use a function to format larger numbers with commas such as 1,000,000 , thanks to this post : The issue is , I have the inputs locked down to accept only numbers with a min value of zero.This poses a problem using the JS , as it needs only number input . Which brings me to a question like this How to make HTML input tag only accept numerical values ? , which also offers a JS solution.I 'm wondering if anyone has developed an elegant way to format numeric input display , while validating numeric input , is there are any other options available here ? It does n't have to purely be a JS solution . function numberWithCommas ( str ) { return str.toString ( ) .replace ( /\B ( ? = ( \d { 3 } ) + ( ? ! \d ) ) /g , `` , '' ) ; } < input type= '' number '' min= '' 0 '' class= '' myclass '' value= '' @ somevalue '' / >",Validating numeric input while formatting numeric input "C_sharp : I 'm building a RESTful API using dotnet core 1.1.2.A big part of this api requires making requests to an external WCF service . These requests are authenticated using windows-based authentication with username , password and domain.I 'm currently in the process of making the api production ready and I wanted to try dockerizing it.The problem I 'm having is that authentication fails towards this third party WCF service as soon as it 's called from within the docker container . Running the API using the dotnet runtime works from both windows and mac and the service gets authenticated as it should.I consume the WCF service using the Connect wcf service feature of Visual studio 2017 and then modifying the endpoint binding with the correct authentication mode.I 've tried both Ntml and Windows as ClientCredentialType.I 've verified that the authentication credentials do n't get messed up when transferring the api to the docker container by hard coding the credentials inside the app , then running it using the normal dotnet runtime to verify that it works . Finally building the docker image with exactly the same published app and running it again . When exactly the same app is running inside docker it fails to authenticate.The output from the application is : The HTTP request is unauthorized with client authentication scheme ‘ Negotiate ’ . The authentication header received from the server was ‘ Negotiate , NTLM ’ .Which is the same output as if when I 'm using incorrect credentials.I 'm wondering if this could be somehow related to how networking works with docker and if the api ca n't negotiate with the WCF service since it 's bridging through the docker host.If anyone more knowledgeable with docker or WCF consumtion inside dotnet core might have some insight it would be very helpful.Best regards , Linus . public ServiceSoapClient ( EndpointConfiguration endpointConfiguration , string username , string password , string domain ) : base ( ServiceSoapClient.GetBindingForEndpoint ( endpointConfiguration ) , ServiceSoapClient.GetEndpointAddress ( endpointConfiguration ) ) { this.ChannelFactory.Credentials.Windows.ClientCredential.UserName = username ; this.ChannelFactory.Credentials.Windows.ClientCredential.Password = password ; this.ChannelFactory.Credentials.Windows.ClientCredential.Domain = domain ; this.Endpoint.Name = endpointConfiguration.ToString ( ) ; ConfigureEndpoint ( this.Endpoint , this.ClientCredentials ) ; } private static System.ServiceModel.Channels.Binding GetBindingForEndpoint ( EndpointConfiguration endpointConfiguration ) { if ( ( endpointConfiguration == EndpointConfiguration.ServiceSoap ) ) { System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding ( ) ; result.MaxBufferSize = int.MaxValue ; result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max ; result.MaxReceivedMessageSize = int.MaxValue ; result.AllowCookies = true ; result.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.Transport ; result.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows ; return result ; } throw new System.InvalidOperationException ( string.Format ( `` Could not find endpoint with name \ ' { 0 } \ ' . `` , endpointConfiguration ) ) ; }",Dotnet core web api running inside docker fails to authenticate when consuming external WCF service "C_sharp : A recent article : https : //blogs.msdn.microsoft.com/dotnet/2017/04/05/announcing-the-net-framework-4-7/ announces a possible fix for intermittent problems with touch screen support . As I read the document , one only needs to change the app.config file . See the line : '' You can opt-into the new touch implementation with the following app.config entry.under section : WPF Touch/Stylus support for Windows 10My question is : Can I just make the change in Myapp.exe.config or must I actually make it in app.config ? Perhaps the question could be : Is the app.config info used at compile time or just translated into myapp.exe.config ? Further , I 'd like to know if it 's ok to leave : The documentation just mentions adding EnablePointerSupport and makes no mention of changing the Version in the config file . I did in fact download the .NET Framework 4.7 and install , but have not changed the Version in the config file . Do I need to ? Thanks . < runtime > < AppContextSwitchOverrides value= '' Switch.System.Windows.Input.Stylus.EnablePointerSupport=true '' / > < /runtime > < startup > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.5 '' / > < /startup >",Add a setting to app.config or will adding the setting to *.exe.config be suffice ? "C_sharp : When you use the new C # collection initialization syntax : does the compiler avoid initializing each array slot to the default value , or is it equivalent to : string [ ] sarray = new [ ] { `` A '' , `` B '' , `` C '' , `` D '' } ; string [ ] sarray = new string [ 4 ] ; // all slots initialized to nullsarray [ 0 ] = `` A '' ; sarray [ 1 ] = `` B '' ; sarray [ 2 ] = `` C '' ; sarray [ 3 ] = `` D '' ;",Does C # Collection Initialization Syntax Avoid Default Initialization Overhead "C_sharp : I do n't mean this question to be too subjective.I google 'd this for some time but got no specific answers to address this issue . The thing is , I think I 'm getting somewhat addicted to LINQ . I already used LINQ to query on lists among other things like using Linq to Sql , Xml , and so on . But then something struck me : `` What if I used it to query a single object ? '' So I did . It may seem wrong like trying to kill a fly with a grenade launcher . Though we all agree it would be artistically pleasant to see.I consider it very readable , I do n't think there is any performance issues regarding to this , but let me show you an example.In a web application , I need to retrieve a setting from my configuration file ( web.config ) . But this should have a default value if the key is not present . Also , the value I need is a decimal , not a string , which is the default return from ConfigurationManager.AppSettings [ `` myKey '' ] . Also , my number should not be more than 10 and it should not be negative . I know I could write this : Which is not complicated , not convoluted , and easy to read . However , this is how I like it done : Without the comments , it looks like this : I do n't know if I 'm the only one here , but I feel the second method is much more `` organic '' than the first one . It 's not easily debuggable , because of LINQ , but it 's pretty failproof I guess . At least this one I wrote . Anyway , if you needed to debug , you could just add curly braces and return statements inside the linq methods and be happy about it.I 've been doing this for a while now , and it feels much more natural than doing things `` line per line , step by step '' . Plus , I just specified the default value once . And it 's written in a line which says DefaultIfEmpty so it 's pretty straightforward.Another plus , I definitely do n't do it if I notice the query will be much larger than the one I wrote up there . Instead , I break into smaller chunks of linq glory so it will be easier to understand and debug.I find it easier to see a variable assignment and automatically think : this is what you had to do to set this value , rather than look at ifs , elses , switches , and etc , and try to figure out if they 're part of the formula or not.And it prevents developers from writing undesired side effects in wrong places , I think.But in the end , some could say it looks very hackish , or too arcane.So I come with the question at hand : Is using LINQ against a single object considered a bad practice ? string cfg = ConfigurationManager.AppSettings [ `` myKey '' ] ; decimal bla ; if ( ! decimal.TryParse ( cfg , out bla ) ) { bla = 0 ; // 0 is the default value } else { if ( bla < 0 || bla > 10 ) { bla = 0 ; } } // initialize it so the compiler does n't complain when you select it afterdecimal awesome = 0 ; // use Enumerable.Repeat to grab a `` singleton '' IEnumerable < string > // which is feed with the value got from app settingsawesome = Enumerable.Repeat ( ConfigurationManager.AppSettings [ `` myKey '' ] , 1 ) // Is it parseable ? grab it .Where ( value = > decimal.TryParse ( value , out awesome ) ) // This is a little trick : select the own variable since it has been assigned by TryParse // Also , from now on I 'm working with an IEnumerable < decimal > .Select ( value = > awesome ) // Check the other constraints .Where ( number = > number > = 0 & & number < = 10 ) // If the previous `` Where '' s were n't matched , the IEnumerable is empty , so get the default value .DefaultIfEmpty ( 0 ) // Return the value from the IEnumerable .Single ( ) ; decimal awesome = 0 ; awesome = Enumerable.Repeat ( ConfigurationManager.AppSettings [ `` myKey '' ] , 1 ) .Where ( value = > decimal.TryParse ( value , out awesome ) ) .Select ( value = > awesome ) .Where ( number = > number > = 0 & & number < = 10 ) .DefaultIfEmpty ( 0 ) .Single ( ) ;",Is using LINQ against a single object considered a bad practice ? "C_sharp : Back story : So I 've been stuck on an architecture problem for the past couple of nights on a refactor I 've been toying with . Nothing important , but it 's been bothering me . It 's actually an exercise in DRY , and an attempt to take it to such an extreme as the DAL architecture is completely DRY . It 's a completely philosophical/theoretical exercise.The code is based in part on one of @ JohnMacIntyre 's refactorings which I recently convinced him to blog about at http : //whileicompile.wordpress.com/2010/08/24/my-clean-code-experience-no-1/ . I 've modified the code slightly , as I tend to , in order to take the code one level further - usually , just to see what extra mileage I can get out of a concept ... anyway , my reasons are largely irrelevant.Part of my data access layer is based on the following architecture : This contains basic stuff , like creation of a command object and cleanup after the AppCommand is disposed of . All of my command base objects derive from this.This contains basic stuff that affects all read-commands - specifically in this case , reading data from tables and views . No editing , no updating , no saving.This contains some more basic generic stuff - like definition of methods that will be required to read a single item from a table in the database , where the table name , key field name and field list names are defined as required abstract properties ( to be defined by the derived class.This contains specific properties that define my table name , the list of fields from the table or view , the name of the key field , a method to parse the data out of the IDataReader row into my business object and a method that initiates the whole process.Now , I also have this structure for my ReadList ... The difference being that the List classes contain properties that pertain to list generation ( i.e . PageStart , PageSize , Sort and returns an IEnumerable ) vs. return of a single DataObject ( which just requires a filter that identifies a unique record ) .Problem : I 'm hating that I 've got a bunch of properties in my MyTableReadListCommand class that are identical in my MyTableReadItemCommand class . I 've thought about moving them to a helper class , but while that may centralize the member contents in one place , I 'll still have identical members in each of the classes , that instead point to the helper class , which I still dislike.My first thought was dual inheritance would solve this nicely , even though I agree that dual inheritance is usually a code smell - but it would solve this issue very elegantly . So , given that .NET does n't support dual inheritance , where do I go from here ? Perhaps a different refactor would be more suitable ... but I 'm having trouble wrapping my head around how to sidestep this problem.If anyone needs a full code base to see what I 'm harping on about , I 've got a prototype solution on my DropBox at http : //dl.dropbox.com/u/3029830/Prototypes/Prototype % 20- % 20DAL % 20Refactor.zip . The code in question is in the DataAccessLayer project.P.S . This is n't part of an ongoing active project , it 's more a refactor puzzle for my own amusement.Thanks in advance folks , I appreciate it . abstract public class AppCommandBase : IDisposable { } abstract public class ReadCommandBase < T , ResultT > : AppCommandBase abstract public class ReadItemCommandBase < T , FilterT > : ReadCommandBase < T , T > { } public class MyTableReadItemCommand : ReadItemCommandBase < MyTableClass , Int ? > { } abstract public ReadListCommandBase < T > : ReadCommandBase < T , IEnumerable < T > > { } public class MyTableReadListCommand : ReadListCommandBase < MyTableClass > { }",".NET refactoring , DRY . dual inheritance , data access and separation of concerns" "C_sharp : I need to send content to printer in C # .NET the same way as PRINT command does.I have Godex thermal printer with QLabel software bundled . Now it has the option to save the label as a command that you can pass to printer with command prompt PRINT command . The file looks like this : That works when i do something like this : And it prints my label out nicely.Now , if i open this in notepad and print , it just prints me this text.I wonder what does PRINT command do under the hood and how can i program my C # based program to replicate the behaviour ? Because when i implement printing logic , it just prints me the plain text as notepad does.I know i could call a PRINT command with Process.Start from C # , but i need to replace some placeholder value in the label template all the time . I could create a temporary file on the disk and print that , but i would prefer to avoid such a scenario . ^Q80,3^W100^H10^P1^S3^AD^C1^R2~Q+0^O0^D0^E35~R200^LDy2-me-ddTh : m : sAH,0,0,1,1,0,0 , XAH,744,0,1,1,0,0 , XAH,746,560,1,1,0,0 , XAH,0,550,1,1,0,0 , XAG,160,208,1,1,0,0 , AA,234,283,1,1,0,0 , HalooE net use LPT2 \\localhost\godexUsbPrinter /yesprint /D : LPT2 label.cmd",What does Notepad do differently under the hood than the PRINT command ? "C_sharp : I have a following classI need to create a custom collection , consisting of objects of class People , that lets me retrieve elements by its id and nameHash . The collection must have the ability to iterate through its elements using foreach : How do I do that ? If you can not give a detailed answer , at least give a brief plan of action . Thanks in advance ! public class People { public int id ; public string nameHash ; public string name ; } foreach ( People person in PeopleCollection ) { ... }",Retrieval of items from custom collection C_sharp : I have created a mycustomItemsPanel in App.Resourcesand providing this to a UIControl this way But I came to know that this can be provided asWhat is the difference between these ? < Application.Resources > < ItemsPanelTemplate x : Key= '' mycustomItemsPanel '' > ... . Some code here < /ItemsPanelTemplate > < /Application.Resources > < ... . ItemsPanel= '' { StaticResource mycustomItemsPanel } '' / > < ... . ItemsPanel= '' Binding Source= { StaticResource mycustomItemsPanel } } '' / >,What is the difference between using `` Binding with StaticResource '' and using `` StaticResource directly '' in WPF "C_sharp : Quite often I come across the need for small immutable data structures . Others would probably use Tuples in these cases , but I really dislike that Tuples do n't read nicely and do n't express that much meaning . A Value2 of int does n't tell me anything.An example would be creating a lookup table ( Dictionary ) for a combination of two properties , i.e . Name and Rating.The shortest way to make an immutable struct for these cases that I know of is this : In my opinion there is still a lot of 'syntactic fat ' in here that I would like to get rid of.I could make it a lot more readable when I would just expose fields directly.I really like the syntax of this , because there is barely any syntactic fat . The big disadvantage is of course that it is not immutable , with all it 's dangers.In the ideal case I would just like to have a special type for this , with the real bare minimum of definition , like : QuestionIs there a real world solution something closer to the example on the bottom , to reduce the amount of syntactic fat for a very simple immutable struct ? public struct Key { public string Name { get ; private set ; } public int Rating { get ; private set ; } public LolCat ( string name , int rating ) : this ( ) { Name = name ; Rating = rating ; } } // useagevar key = new Key ( `` MonorailCat '' , 5 ) ; public struct Key { public string Name ; public int Rating ; } // useagevar key = new Key { Name = `` MonorailCat '' , Rating = 5 } ; public immutable struct Key { string Name ; int Rating ; } // useage ( needs compiler magic ) var key = new Key ( Name : `` MonorailCat '' , Rating : 5 ) ;",Shortest way to write immutable struct in C # "C_sharp : I have a generic field and a property that encapsulates it : The problem is that this property can be written to from one thread and read from multiple threads at the same time . And if T is a struct , or long , readers might get results that are part old value and part new value . How can I prevent that ? I tried using volatile , but that 's not possible : A volatile field can not be of the type 'T'.Since this is a simpler case of code I 've already written , which uses ConcurrentQueue < T > , I thought about using it here too : This would work , but it seems to me that it 's overcomplicated solution to something that should be simple.Performance is important , so , if possible , locking should be avoided.If a set happens at the same time as get , I do n't care whether get returns the old value or the new value . T item ; public T Item { get { return item ; } set { item = value ; } } ConcurrentQueue < T > item ; public T Item { get { T result ; item.TryPeek ( out result ) ; return item ; } set { item.TryEnqueue ( value ) ; T ignored ; item.TryDequeue ( out ignored ) ; } }",Thread-safe generic field "C_sharp : Simple situation . I have a list of lists , almost table like , and I am trying to find out if any of the lists are duplicated.Example : I would like to know that there are 4 total items , 2 of which are duplicates . I was thinking about doing something like a SQL checksum but I did n't know if there was a better/easier way . I care about performance , and I care about ordering . Additional Information That May Help Things inserted into this list will never be removedNot bound to any specific collection.Dont care about function signatureThey type is not restricted to int List < List < int > > list = new List < List < int > > ( ) { new List < int > ( ) { 0 ,1 ,2 , 3 , 4 , 5 , 6 } , new List < int > ( ) { 0 ,1 ,2 , 3 , 4 , 5 , 6 } , new List < int > ( ) { 0 ,1 ,4 , 2 , 4 , 5 , 6 } , new List < int > ( ) { 0 ,3 ,2 , 5 , 1 , 6 , 4 } } ;",Finding duplicates within list of list "C_sharp : I have the following model : And a list with a lot of entries : Example : I 'd now like row 2 and 3 to be grouped because they have the same UserId , same CompanyId , same target and almost ( and this is the difficult part ) , let 's say in a range of 5 seconds , the same date time . After grouping my list should look like this : Is there any easy approach for this problem ? Any advices ? I bet Linq will help me around but I 'm not sure how.Edit : Thank you all for your feedback.I decided to change the design and to ensure that the datetime is now really the same . So grouping with linq is now very easy . public class Entry { public int UseraccountId { get ; set ; } public int CompanyId { get ; set ; } public DateTime CreationDate { get ; set ; } public string Target { get ; set ; } public string Message { get ; set ; } } List < Entry > entries = ... //get all entries .",Group list entries with LINQ "C_sharp : I have a Page with only a pivot in it . This page is always cached . Now whenever I navigate to this page , I want its contents and selections to be loaded from cached but I want to have the first PivotItem in view . XAML : This is my code behind : This does n't select the 0th index instead , it shows the cached PivotItem that was selected when the user navigated away from the view . < Pivot x : Name= '' FilterPivot '' IsHeaderItemsCarouselEnabled= '' True '' SelectedIndex= '' 0 '' > < PivotItem Header= '' Author '' > < ListBox ItemsSource= '' { x : Bind AuthorFacets , Mode=OneWay } '' Name= '' AuthorListBox '' SelectionMode= '' Multiple '' SelectionChanged= '' AuthorListBox_SelectionChanged '' > < ListBox.ItemContainerStyle > < Style TargetType= '' ListBoxItem '' > < Setter Property= '' HorizontalContentAlignment '' Value= '' Stretch '' / > < /Style > < /ListBox.ItemContainerStyle > < ListBox.ItemTemplate > < DataTemplate x : DataType= '' local : IFacet '' > < Grid > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' * '' > < /ColumnDefinition > < ColumnDefinition Width= '' Auto '' > < /ColumnDefinition > < /Grid.ColumnDefinitions > < TextBlock Grid.Column= '' 0 '' Text= '' { x : Bind read } '' TextWrapping= '' Wrap '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Center '' / > < Border Grid.Column= '' 1 '' Background= '' Gray '' MinWidth= '' 25 '' CornerRadius= '' 8 '' > < TextBlock Text= '' { x : Bind num } '' HorizontalAlignment= '' Center '' VerticalAlignment= '' Center '' Padding= '' 2 '' / > < /Border > < /Grid > < /DataTemplate > < /ListBox.ItemTemplate > < /ListBox > < /PivotItem > < PivotItem Header= '' Language '' > ... . ... . < /PivotItem > < PivotItem Header= '' Learning Resource Type '' > ... . ... . < /PivotItem > < PivotItem Header= '' Subject '' > ... . ... . < /PivotItem > < PivotItem Header= '' Type '' > ... . ... . < /PivotItem > < PivotItem Header= '' Education Level '' > ... . ... . < /PivotItem > < PivotItem Header= '' Source '' > ... . ... . < /PivotItem > < /Pivot > public FilterPage ( ) { this.InitializeComponent ( ) ; this.NavigationCacheMode = NavigationCacheMode.Required ; } protected override void OnNavigatedTo ( NavigationEventArgs e ) { base.OnNavigatedTo ( e ) ; FilterPivot.SelectedIndex = 0 ; }",Using the SelectedIndex proprety of Pivot in UWP "C_sharp : Consider the two following similar code samples.One where clause.Two where clauses.I prefer the second since I find it more readable and it causes less formatting issues , especially when using auto-formatting . It is also clearer when placing comments next to the separate conditions ( or even above ) to clarify the intent.My intuition says the second code sample would be less efficient . I could of course write a simple test myself ( and will if nobody knows the answer ) . For now I thought this is perfect food for SO . ; pIs one more efficient than the other ? Is the compiler smart enough to optimize this ? bool validFactory = fields .Where ( fields = > field.FieldType == typeof ( DependencyPropertyFactory < T > ) & & field.IsStatic ) .Any ( ) ; bool validFactory = fields .Where ( field = > field.FieldType == typeof ( DependencyPropertyFactory < T > ) ) .Where ( field = > field.IsStatic ) .Any ( ) ;",Does the compiler concatenate LINQ where queries ? C_sharp : I 'm trying to cast a contravariant delegate but for some reason I can only do it using the `` as '' operator.castFunc2 works fine but castFunc1 and castFunc3 cause the error : The MSDN article on the as operator states that castFunc2 and castFunc3 are `` equivalent '' so I do n't understand how only one of them could cause an error . Another piece of this that is confusing me is that changing MyInterface from an interface to a class gets rid of the error.Can anyone help me understand what is going on here ? Thanks ! interface MyInterface { } delegate void MyFuncType < in InType > ( InType input ) ; class MyClass < T > where T : MyInterface { public void callDelegate ( MyFuncType < MyInterface > func ) { MyFuncType < T > castFunc1 = ( MyFuncType < T > ) func ; //Error MyFuncType < T > castFunc2 = func as MyFuncType < T > ; MyFuncType < T > castFunc3 = func is MyFuncType < T > ? ( MyFuncType < T > ) func : ( MyFuncType < T > ) null ; //Error } } Can not convert type 'delegateCovariance.MyFuncType < myNamespace.MyInterface > ' to myNamespace.MyFuncType < T > ',I can only cast a contravariant delegate with `` as '' "C_sharp : I just ran across some code while working with System.DirectoryServices.AccountManagementWhat is the ? after the DateTime for.I found a reference for the ? ? Operator ( C # Reference ) , but it 's not the same thing . ( 280Z28 : Here is the correct link for Using Nullable Types . ) public DateTime ? LastLogon { get ; }","In C # , what is the ` ? ` in the type ` DateTime ? `" "C_sharp : Can anyone explain why this does n't work ? If you remove the interceptor from IFoo 's registration and resolve a Bar , you get a Foo ( MyFoo is n't null ) . But with the interceptor , the Foo does n't resolve anymore . Why ? How can I tell why it wo n't resolve via logging or tracing ? Versions : Castle.Core : 3.2Castle.Windsor : 3.2.NET 4.5C # 5Edit : I just found ( mostly by accident ) that changing the interceptor config from an interface to a concrete class works . However , I 'm registering the interceptor and its interface , so the original question is amended slightly : why does the interface specification fail ( silently , no less ) ? using Castle.DynamicProxy ; using Castle.MicroKernel.Registration ; using Castle.Windsor ; using System ; namespace Sandbox { public interface IFooInterceptor : IInterceptor { } public interface IFoo { void Print ( ) ; } public interface IBar { IFoo MyFoo { get ; set ; } } public class Foo : IFoo { public void Print ( ) { Console.WriteLine ( `` Print '' ) ; } } public class FooInterceptor : IFooInterceptor , IInterceptor { public void Intercept ( IInvocation invocation ) { Console.WriteLine ( `` Awesome '' ) ; invocation.Proceed ( ) ; } } public class Bar : IBar { public virtual IFoo MyFoo { get ; set ; } } class Program { static void Main ( string [ ] args ) { IWindsorContainer container = new WindsorContainer ( ) .Register ( Component.For < IBar > ( ) .ImplementedBy < Bar > ( ) .LifestyleTransient ( ) , Component.For < IFoo > ( ) .ImplementedBy < Foo > ( ) .LifestyleTransient ( ) .Interceptors < IFooInterceptor > ( ) , Component.For < IFooInterceptor > ( ) .ImplementedBy < FooInterceptor > ( ) .LifestyleTransient ( ) ) ; var bar = container.Resolve < IBar > ( ) ; var foo = container.Resolve < IFoo > ( ) ; // this is n't null bar.MyFoo.Print ( ) ; // exception : bar.MyFoo is null Console.WriteLine ( `` Done '' ) ; Console.ReadLine ( ) ; } } }",Windsor not resolving intercepted components "C_sharp : I have recently upgraded a ASP.Net forms application to .Net 4.5.2 , after fixing some relatively trivial namespace issues I was able to build the solution successfully . However at runtime I have been receiving the following error : An exception of type 'System.FormatException ' occurred in mscorlib.dll but was not handled in user codeWhich when debugging is thrown by the following line : Where renderStartTime = DateTime.NowI am somewhat puzzled why I am seeing this error since upgrading . Any thoughts ? string.Format ( `` Init took { 0 : mm : ss } '' , ( object ) DateTime.Now.Subtract ( renderStartTime ) )",String.Format exception following upgrade from .Net 2.0 to .Net 4.5.2 "C_sharp : C # 3 ( Visual Studio 2008 ) introduced a breaking change to the language ( http : //msdn.microsoft.com/en-us/library/cc713578.aspx , see change 12 ) that allows any literal zero to be implicitly converted to an Enum . This seems odd in many ways . Does anyone know why this is part of the spec ? Why not a literal one ? Or seven ? Why is zero special ? And it makes some very counterintuitive overload resolution choices . For instance.Very confusing , and an intentionally introduced breaking change to the language . Any ideas ? function string F ( object o ) { return o.ToString ( ) ; } function string F ( DbType t ) { return t.ToString ( ) ; } int i = 0 ; F ( ( long ) 0 ) == `` String '' // would have been `` 0 '' in VS 2005F ( 0 ) == `` String '' F ( i ) == `` 0 ''",Why does C # 3 allow the implicit conversion of literal zero ( 0 ) to any Enum ? "C_sharp : In a web application , I have linq To Object queries to make data extraction/consolidation.To allow easier debugging , I would like to show directly in the generated HTML the linq query structure ; something likeIndeed , a representation of the expression tree.Is it possible ? How ? Bananas - > Where color='blue ' - > Where size > '20cm ' - > Take 25",Get string representation of a Linq To Objects Query "C_sharp : The using keyword has three disparate meanings : type/namespace aliasingnamespace importsyntactic sugar for ensuring Dispose is calledThe documentation calls the first two definitions directives ( which I 'm guessing means they are preprocessing in nature ) , while the last is a statement.Regardless of the fact that they are distinguished by their syntaxes , why would the language developers complicate the semantics of the keyword by attaching three different meanings to it ? For example , ( disclaimer : off the top of my head , there may certainly be better examples ) why not add keywords like alias and import ? Technical , theoretical , or historical reasons ? Keyword quota ? ; - ) Contrived sample : '' Using '' is such a vague word . import System.Timers ; alias LiteTimer=System.Threading.Timer ; alias WinForms=System.Windows.Forms ; public class Sample { public void Action ( ) { var elapsed = false ; using ( var t = new LiteTimer.Timer ( _ = > elapsed = true ) { while ( ! elapsed ) CallSomeFinickyApi ( ) ; } } }",Why did the C # designers attach three different meanings to the 'using ' keyword ? "C_sharp : I have a ZonedDateTime and I want to display it such that the datetime is formatted with the short date and short time configured on the workstation followed by the offset ( something like ... 05/01/2005 02:30 PM -05:00 ) . I expected something like this would work ... BUT , it appears that the `` g '' is not supported in ZonedDateTimePattern the way it is in LocalDateTimePattern . The code above throws a NodaTime.Text.InvalidPatternException.I could replace the `` g '' with `` MM/dd/yyyy hh : mm '' , but then it 's not using the current culture.I could use a LocalDateTimePattern for the datetime and then concatenate the offset using the ZonedDateTimePattern . This works , but seems ugly.This seems like a pretty common thing . I 'm new to NodaTime , so I 'm certain I 'm missing something . I 'm using NodaTime 1.3.1 and targeting .net 4.0 . Any help is appreciated . var patternDateTimeOffset = ZonedDateTimePattern.CreateWithCurrentCulture ( `` g o < m > '' , DateTimeZoneProviders.Tzdb ) ; lblOriginalDateTimeAndOffsetVal.Text = patternDateTimeOffset.Format ( zonedDateTime ) ;","With NodaTime , how do I format a ZonedDateTime in current culture" "C_sharp : I have a part of code which I really do not like , if it 's possible to simplify it somehow - would be really nice . A a ; // I want to get rid of this variableif ( ( a = collection.FirstOrDefault ( x = > x.Field == null ) ) ! = null ) { throw new ScriptException ( `` { 0 } '' , a.y ) ; //I need to access other field of the object here , that 's why I had to declare a variable outside of the expression }",Simplifying a LINQ expression C_sharp : I have override GetHashCode and Equals and both methods provide same results for different objects but why still getting false ? class Program { static void Main ( string [ ] args ) { Console.WriteLine ( new Person ( `` james '' ) == new Person ( `` james '' ) ) ; Console.ReadKey ( ) ; } } class Person { private string Name ; public Person ( string name ) { Name = name ; } public override int GetHashCode ( ) { return 1 ; } public override bool Equals ( object obj ) { return true ; } },Why returning false ? new Person ( `` james '' ) == new Person ( `` james '' ) ? "C_sharp : A colleague of mine is convinced there is a memory leak in Oracle 's odp.net ado.net implementation . He has written a test program to test this theory and is doing the following after calling dispose on each object in order to determine how much memory is being freed : The resulting performance value is then compared with a value retrieved prior to disposing of the object . Will this produce accurate results ? PerformanceCounter p = new PerformanceCounter ( `` Memory '' , `` Available Bytes '' ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; float mem = p.NextValue ( ) ;",GC.Collect ( ) and PerformanceCounter "C_sharp : I 've tried to define a gRPC service where client can subscribe to receive broadcasted messages and they can also send them.My idea was that when a client requests to subscribe to the messages , the response stream would be added to a collection of response streams , and when a message is sent , the message is sent through all the response streams.However , when my server attempts to write to the response streams , I get an exception System.InvalidOperationException : 'Response stream has already been completed . 'Is there any way to tell the server to keep the streams open so that new messages can be sent through them ? Or is this not something that gRPC was designed for and a different technology should be used ? The end goal service would be allows multiple types of subscriptions ( could be to new messages , weather updates , etc ... ) through different clients written in different languages ( C # , Java , etc ... ) . The different languages part is mainly the reason I chose gRPC to try this , although I intend on writing the server in C # .Implementation example syntax = `` proto3 '' ; package Messenger ; service MessengerService { rpc SubscribeForMessages ( User ) returns ( stream Message ) { } rpc SendMessage ( Message ) returns ( Close ) { } } message User { string displayName = 1 ; } message Message { User from = 1 ; string message = 2 ; } message Close { } using System ; using System.Collections.Concurrent ; using System.Collections.Generic ; using System.Linq ; using System.Threading ; using System.Threading.Tasks ; using Grpc.Core ; using Messenger ; namespace SimpleGrpcTestStream { /* DependenciesInstall-Package Google.ProtobufInstall-Package GrpcInstall-Package Grpc.ToolsInstall-Package System.Interactive.AsyncInstall-Package System.Linq.Async */ internal static class Program { private static void Main ( ) { var messengerServer = new MessengerServer ( ) ; messengerServer.Start ( ) ; var channel = Common.GetNewInsecureChannel ( ) ; var client = new MessengerService.MessengerServiceClient ( channel ) ; var clientUser = Common.GetUser ( `` Client '' ) ; var otherUser = Common.GetUser ( `` Other '' ) ; var cancelClientSubscription = AddCancellableMessageSubscription ( client , clientUser ) ; var cancelOtherSubscription = AddCancellableMessageSubscription ( client , otherUser ) ; client.SendMessage ( new Message { From = clientUser , Message_ = `` Hello '' } ) ; client.SendMessage ( new Message { From = otherUser , Message_ = `` World '' } ) ; client.SendMessage ( new Message { From = clientUser , Message_ = `` Whoop '' } ) ; cancelClientSubscription.Cancel ( ) ; cancelOtherSubscription.Cancel ( ) ; channel.ShutdownAsync ( ) .Wait ( ) ; messengerServer.ShutDown ( ) .Wait ( ) ; } private static CancellationTokenSource AddCancellableMessageSubscription ( MessengerService.MessengerServiceClient client , User user ) { var cancelMessageSubscription = new CancellationTokenSource ( ) ; var messages = client.SubscribeForMessages ( user ) ; var messageSubscription = messages .ResponseStream .ToAsyncEnumerable ( ) .Finally ( ( ) = > messages.Dispose ( ) ) ; messageSubscription.ForEachAsync ( message = > Console.WriteLine ( $ '' New Message : { message.Message_ } '' ) , cancelMessageSubscription.Token ) ; return cancelMessageSubscription ; } } public static class Common { private const int Port = 50051 ; private const string Host = `` localhost '' ; private static readonly string ChannelAddress = $ '' { Host } : { Port } '' ; public static User GetUser ( string name ) = > new User { DisplayName = name } ; public static readonly User ServerUser = GetUser ( `` Server '' ) ; public static readonly Close EmptyClose = new Close ( ) ; public static Channel GetNewInsecureChannel ( ) = > new Channel ( ChannelAddress , ChannelCredentials.Insecure ) ; public static ServerPort GetNewInsecureServerPort ( ) = > new ServerPort ( Host , Port , ServerCredentials.Insecure ) ; } public sealed class MessengerServer : MessengerService.MessengerServiceBase { private readonly Server _server ; public MessengerServer ( ) { _server = new Server { Ports = { Common.GetNewInsecureServerPort ( ) } , Services = { MessengerService.BindService ( this ) } , } ; } public void Start ( ) { _server.Start ( ) ; } public async Task ShutDown ( ) { await _server.ShutdownAsync ( ) .ConfigureAwait ( false ) ; } private readonly ConcurrentDictionary < User , IServerStreamWriter < Message > > _messageSubscriptions = new ConcurrentDictionary < User , IServerStreamWriter < Message > > ( ) ; public override async Task < Close > SendMessage ( Message request , ServerCallContext context ) { await Task.Run ( ( ) = > { foreach ( var ( _ , messageStream ) in _messageSubscriptions ) { messageStream.WriteAsync ( request ) ; } } ) .ConfigureAwait ( false ) ; return await Task.FromResult ( Common.EmptyClose ) .ConfigureAwait ( false ) ; } public override async Task SubscribeForMessages ( User request , IServerStreamWriter < Message > responseStream , ServerCallContext context ) { await Task.Run ( ( ) = > { responseStream.WriteAsync ( new Message { From = Common.ServerUser , Message_ = $ '' { request.DisplayName } is listening for messages ! `` , } ) ; _messageSubscriptions.TryAdd ( request , responseStream ) ; } ) .ConfigureAwait ( false ) ; } } public static class AsyncStreamReaderExtensions { public static IAsyncEnumerable < T > ToAsyncEnumerable < T > ( this IAsyncStreamReader < T > asyncStreamReader ) { if ( asyncStreamReader is null ) { throw new ArgumentNullException ( nameof ( asyncStreamReader ) ) ; } return new ToAsyncEnumerableEnumerable < T > ( asyncStreamReader ) ; } private sealed class ToAsyncEnumerableEnumerable < T > : IAsyncEnumerable < T > { public IAsyncEnumerator < T > GetAsyncEnumerator ( CancellationToken cancellationToken = default ) = > new ToAsyncEnumerator < T > ( _asyncStreamReader , cancellationToken ) ; private readonly IAsyncStreamReader < T > _asyncStreamReader ; public ToAsyncEnumerableEnumerable ( IAsyncStreamReader < T > asyncStreamReader ) { _asyncStreamReader = asyncStreamReader ; } private sealed class ToAsyncEnumerator < TEnumerator > : IAsyncEnumerator < TEnumerator > { public TEnumerator Current = > _asyncStreamReader.Current ; public async ValueTask < bool > MoveNextAsync ( ) = > await _asyncStreamReader.MoveNext ( _cancellationToken ) ; public ValueTask DisposeAsync ( ) = > default ; private readonly IAsyncStreamReader < TEnumerator > _asyncStreamReader ; private readonly CancellationToken _cancellationToken ; public ToAsyncEnumerator ( IAsyncStreamReader < TEnumerator > asyncStreamReader , CancellationToken cancellationToken ) { _asyncStreamReader = asyncStreamReader ; _cancellationToken = cancellationToken ; } } } } }",gRPC keeping response streams open for subscriptions "C_sharp : I have been creating a simple chess engine in c # over the last month and made some nice progress on it . It is using a simple Alpha-Beta algorithm.In order to correct the Horizon-Effect , I tried to implement the Quiescence Search ( and failed several times before it worked ) . The strength of the engine seems to have improved quiet a bit from that , but it is terribly slow ! Before , I could search to a 6 ply depth in about 160 secs ( somewhere in a midgame state ) , with the quiescent search , it takes the computer about 80secs to get a move on search depth 3 ! The brute-force node counter is at about 20000 Nodes at depth 3 , while the quiescent node counter is up to 20 millions ! Since this is my first chess engine , I do n't really know if those numbers are normal or if I might have made a mistake in my Quiescence-Algorithm . I would appreciate if someone more experienced could tell me what the usual ratio of BF Nodes/Quiescent nodes is.Btw , just to have a look at : ( this Method is called by the BF tree whenever the searchdepth is 0 ) public static int QuiescentValue ( chessBoard Board , int Alpha , int Beta ) { QuiescentNodes++ ; int MinMax = Board.WhoseMove ; // 1 = maximierend , -1 = minimierend int Counter = 0 ; int maxCount ; int tempValue = 0 ; int currentAlpha = Alpha ; int currentBeta = Beta ; int QuietWorth = chEvaluation.Evaluate ( Board ) ; if ( MinMax == 1 ) //Max { if ( QuietWorth > = currentBeta ) return currentBeta ; if ( QuietWorth > currentAlpha ) currentAlpha = QuietWorth ; } else //Min { if ( QuietWorth < = currentAlpha ) return currentAlpha ; if ( QuietWorth < currentBeta ) currentBeta = QuietWorth ; } List < chMove > HitMoves = GetAllHitMoves ( Board ) ; maxCount = HitMoves.Count ; if ( maxCount == 0 ) return chEvaluation.Evaluate ( Board ) ; chessBoard tempBoard ; while ( Counter < maxCount ) { tempBoard = new chessBoard ( Board ) ; tempBoard.Move ( HitMoves [ Counter ] ) ; tempValue = QuiescentValue ( tempBoard , currentAlpha , currentBeta ) ; if ( MinMax == 1 ) //maximierend { if ( tempValue > = currentBeta ) { return currentBeta ; } if ( tempValue > currentAlpha ) { currentAlpha = tempValue ; } } else //minimierend { if ( tempValue < = currentAlpha ) { return currentAlpha ; } if ( tempValue < currentBeta ) { currentBeta = tempValue ; } } Counter++ ; } if ( MinMax == 1 ) return currentAlpha ; else return currentBeta ; }",Chess Quiescence Search ist too extensive C_sharp : Say you create an object and saving to database by using ADO Entity Framwork as in the code below.How can I retrieve the ID of the newly created object ? Thanks in advance . private void CreateAddress ( BizObjects.Address address ) { var entity = new EntityFramework.Address ( ) ; entity.Line1 = address.Line1 ; entity.Line2 = address.Line2 ; entity.City = address.City ; entity.State = address.State ; entity.ZipCode = address.ZipCode ; _entities.AddToAddress ( entity ) ; _entities.SaveChanges ( ) ; },Getting ID of recently created entity - ADO Entity Framework "C_sharp : After answering this question I put together the following C # code just for fun : The problem is that I do n't like needing to pass a max parameter to the function . Right now , if I do n't use one the code will output the correct data but then appear to hang as the IEnumerable continues to work . How can I write this so that I could just use it like this : public static IEnumerable < int > FibonacciTo ( int max ) { int m1 = 0 ; int m2 = 1 ; int r = 1 ; while ( r < = max ) { yield return r ; r = m1 + m2 ; m1 = m2 ; m2 = r ; } } foreach ( int i in FibonacciTo ( 56 ) .Where ( n = > n > = 24 ) ) { Console.WriteLine ( i ) ; } foreach ( int i in Fibonacci ( ) .Where ( n = > n > = 24 & & n < = 56 ) ) { Console.WriteLine ( i ) ; }",Infinite IEnumerable in a foreach loop "C_sharp : So the program I 'm working on can be launched using command lines in CMD using the following code.However I want to be able to return a message to the CMD window where the command lines came from after handling them . Any help would be appreciated.Edit : I 'm running the program as a Windows Application , not a console application . string [ ] commandLines = Environment.GetCommandLineArgs ( ) ;",How do I echo into an existing CMD window "C_sharp : I 'm using a custom implementation of a Stream that will stream an IEnumerable < T > into a stream . I 'm using this EnumerableStream implementation to perform the conversion.I 'm using it to perform streaming over WCF in streaming mode . I 'm able to convert the IEnumerable to a stream without problem . Once , I 'm in the client side , I can deserialize and get all the data , however I 'm not able to find the condition to stop looping over my stream . I 'm getting : System.Runtime.Serialization.SerializationException : End of Stream encountered before parsing was completed.Here 's sample example of what I 'm trying to achieve : I did not include the custom stream . I created a fiddle for those that want to see the entire code.Do I need to add something in the custom stream itself to notify that all the data have been read ? Is it because the format of the deserializer and serialiser are not the same ( I do n't think so ) .I also want to know why when I put a break point in the read function , the buffer size is changing randomly.I would prefer not to wrap the code with a try and catch , I want a clean solution that does not crash . class Program { public static void Main ( ) { var ListToSend = new List < List < string > > ( ) ; var ListToReceive = new List < List < string > > ( ) ; ListToSend = SimulateData ( ) .ToList ( ) ; using ( Stream stream = GetStream ( ListToSend ) ) { var formatter = new BinaryFormatter ( ) ; while ( stream.CanRead || 1 == 1 || true ... ) // What should I put in here to stop once I read everything ? ? ? { List < string > row = formatter.Deserialize ( stream ) as List < string > ; ListToReceive.Add ( row ) ; } Printer ( ListToReceive ) ; Console.WriteLine ( `` Done '' ) ; } } private static void Printer ( List < List < string > > data ) { Console.WriteLine ( `` Printing '' ) ; foreach ( var row in data ) { foreach ( var cell in row ) { Console.Write ( cell + `` \t '' ) ; } Console.WriteLine ( `` -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - '' ) ; } } private static Stream GetStream ( IEnumerable < List < string > > data ) { return EnumerableStream.Create ( data , DeserializerCallback ) ; } private static List < byte > DeserializerCallback ( object obj ) { var binFormatter = new BinaryFormatter ( ) ; var mStream = new MemoryStream ( ) ; binFormatter.Serialize ( mStream , obj ) ; return mStream.ToArray ( ) .ToList ( ) ; } private static IEnumerable < List < string > > SimulateData ( ) { Random randomizer = new Random ( ) ; for ( var i = 0 ; i < 10 ; i++ ) { var row = new List < string > ( ) ; for ( var j = 0 ; j < 1000 ; j++ ) { row.Add ( ( randomizer.Next ( 100 ) ) .ToString ( ) ) ; } yield return row ; } } }",Consuming a custom stream ( IEnumerable < T > ) "C_sharp : I 'm using the ViewportControl to scroll around and zoom in and out of my Map . In this map I 've got a green ellipse which I wish to move around . Previously I used a ScrollViewer where I set the manipulationMode of the ScrollViewer to control , and thus making it capable of moving my ellipse around . However I ca n't find a similar way for the ViewportControl . So is there a way to move my ellipse around ? The code I 've got so far is : The xaml part where I have my ViewportControl around my mapIt is in the map where I add the ellipse . The viewModel where I manipulate my ellipseWhere Temp.x and Temp.y is the new position of the ellipse . < ViewportControl x : Name= '' ViewPortTestTest '' Bounds= '' 0,0,1271,1381.5 '' Height= '' 480 '' Width= '' 800 '' Canvas.ZIndex= '' 1 '' Grid.Row= '' 1 '' > < ViewportControl.RenderTransform > < CompositeTransform x : Name= '' myTransformTest '' / > < /ViewportControl.RenderTransform > < View : Map x : Name= '' ZoomableContent '' > < View : Map.RenderTransform > < CompositeTransform x : Name= '' myTransform '' / > < ! -- ScaleX= '' { Binding Map.imageScale } '' ScaleY= '' { Binding Map.imageScale } '' / > -- > < /View : Map.RenderTransform > < /View : Map > < /ViewportControl > public void ManStart ( ManipulationStartedEventArgs e ) { e.Handled = true ; ViewportControl VP = FindParentOfType < ViewportControl > ( ChampViewModelSel ) ; } } public void ManDelta ( ManipulationDeltaEventArgs e ) { e.Handled = true ; Point fingerPosition = e.DeltaManipulation.Translation ; Temp.x = fingerPosition.X ; Temp.y = fingerPosition.Y ; } }",Move object in ViewportControl WP8 "C_sharp : I created an array like this : And now , I would like to take the 2nd , 3rd and the 4th item in the array and join together , currently I 'm using this code : So the result would be banana tomato pineapple and this works fine.And I would like to ask if there 's a standard or better way to achieve this ? string [ ] test = new string [ ] { `` apple '' , `` banana '' , `` tomato '' , `` pineapple '' , `` grapes '' } ; string result = `` '' ; for ( int i = 1 ; i < 4 ; i++ ) { result += test [ i ] + `` `` ; }",How to take nth item in array to zth item in array ? "C_sharp : I am working with expando object and I am trying to define a calculated property.I know that I can define a simple property by doing something like the following : Likewise , I can also define a method : When working with a standard object we can define a calculated property , ie define a property that will return the results of a custom method/calc . No need for an example.I need to do something similar on my expando - having a property that actually calls a `` Func '' ( or some other form of delegate , anything goes as soon as I can call a custom method and have a custom return type ) . So basically I need to invoke a method like in the second example BUT have it work like a property.Basically I need to be able to call it with myExpando.GetTheQuestion instead of myExpando.GetTheQuestion ( ) , while keeping the ability of defining a custom delegate as the property body.Is there a way to do this ? I belive that I could do this by using Expression trees , but I admit I am a little lost there . Can anyone provide some guidance on how to achieve this ? ? EDITDone some more research.. Unless there is some very specific class/interface/sintax that I do n't know I am starting to think that the above is impossible . From what I get , the ExpandoObject class works by defining some methods that do the background plumbing - TryGetMember , TrySetMember and such.Now when `` accessing a property '' on the dynamic objetc , TryGetMember is the memeber that gets called . That member returns a value from a sort of inner dictionary ( yes , I know ... this is a little simplified but should give the idea ) ... no test on the type of value returned . This means that in my example myExpando.GetTheQuestion would return the original Func.It would seem that since TryGetMember just returns a value , there is no way to make it `` execute '' the property code . To achieve that , you would need some sort of expression/lambda/func/action surrogate which value is actually the RESULT of a method . Which seems impossible ( nor would make much sense unless I miss something - basically you would have a value that is set to a 'delegate ' and then is get as the delegate return value ? ? ? ) . Am I correct or this or I am missing something ? dynamic myExpando = new ExpandoObject ( ) ; myExpando.TheAnswerToLifeTheUniverseAndEverything= 42 ; myExpando.GetTheQuestion = ( ( Func < string > ) ( ( ) = > { return `` How many road must a man walk down before we can call him a man ? `` ; } ) ) ;",Define a calculated property on an expando object "C_sharp : Tried to something like this in our code but it fails : The last two cases give this error : Can not implicitly convert type System.Func < Employee , Employee > to System.Func < Person , Employee > . An explicit conversion exists ( are you missing a cast ? ) Any idea why ? Func < Employee , Employee > _myFunc ; void Main ( ) { Func < Employee , Employee > test1 = _myFunc ; //Ok Func < Employee , Person > test2 = _myFunc ; //Ok Func < Person , Employee > test3 = _myFunc ; //Fails Func < Person , Person > test4 = _myFunc ; //Fails } public class Person { } public class Employee : Person { }",Func variance with multiple parameters "C_sharp : I 'm using code very similar to the following Stack Overflow question : Ca n't find an Entry Point 'GetDeviceUniqueID ' in a PInvoke DLL 'coredll.dll ' ( My code pasted here for posterity 's sake ) : I have no issues compiling the program on my emulator and deploying to my physical device . However , this code always returns a value of : `` 00000000-0000-0000-0000-00000000000000000000 '' . ( Upon introspection , i_rc has a value of 2147024809 ) .What is going wrong ? Why does the function seem to return a default/safe value ? [ DllImport ( `` coredll.dll '' ) ] private extern static int GetDeviceUniqueID ( [ In , Out ] byte [ ] appdata , int cbApplictionData , int dwDeviceIDVersion , [ In , Out ] byte [ ] deviceIDOuput , out uint pcbDeviceIDOutput ) ; public static string GetDeviceID ( ) { string appString = `` MyApp '' ; byte [ ] appData = new byte [ appString.Length ] ; for ( int count = 0 ; count < appString.Length ; count++ ) { appData [ count ] = ( byte ) appString [ count ] ; } int appDataSize = appData.Length ; byte [ ] DeviceOutput = new byte [ 20 ] ; uint SizeOut = 20 ; int i_rc = GetDeviceUniqueID ( appData , appDataSize , 1 , DeviceOutput , out SizeOut ) ; string idString = `` '' ; for ( int i = 0 ; i < DeviceOutput.Length ; i++ ) { if ( i == 4 || i == 6 || i == 8 || i == 10 ) idString = String.Format ( `` { 0 } - { 1 } '' , idString , DeviceOutput [ i ] .ToString ( `` x2 '' ) ) ; else idString = String.Format ( `` { 0 } { 1 } '' , idString , DeviceOutput [ i ] .ToString ( `` x2 '' ) ) ; } return idString ; }",Trouble implementing GetDeviceUniqueID on Windows Mobile 6 "C_sharp : So , I 'm doing a lot of database work in an application - and there are several possible return values of my caching system . It can return null , it can return a default ( type ) or it can return an invalid object ( by invalid object , I mean one with incorrect properties / values ) . I want to create an extension method to make all those checks for me , like so : The problem is , my compiler is telling me that if ( obj == default ( T ) ) will always be false . Why is that ? public static bool Valid < T > ( this T obj ) where T : class { if ( obj == null ) return false ; else if ( obj == default ( T ) ) return false ; //Other class checks here else return true ; }",Null checking extension method "C_sharp : In a Unit Test ( in Visual Studio 2008 ) I want to compare the content of a large object ( a list of custom types , to be precise ) with a stored reference of this object . The goal is to make sure , that any later refactorings of the code produces the same object content.Discarded Idea : A first thought was to serialize to XML , and then compare the hardcoded strings or a file content . This would allow for easy finding of any difference . However since my types are not XML serializable without a hack , I must find another solution . I could use binary serialization but this will not be readable anymore.Is there a simple and elegant solution to this ? EDIT : According to Marc Gravell 's proposal I do now like this : In essence I do select the comparable properties first , then encode the graph , then compare it to a similarly encoded reference . Encoding enables deep comparison in a simple way . The reason I use base64 encoding is , that I can easily store the reference it in a string variable . using ( MemoryStream stream = new MemoryStream ( ) ) { //create actual graph using only comparable properties List < NavigationResult > comparableActual = ( from item in sparsed select new NavigationResult { Direction = item.Direction , /* ... */ VersionIndication = item.VersionIndication } ) .ToList ( ) ; ( new BinaryFormatter ( ) ) .Serialize ( stream , comparableActual ) ; string base64encodedActual = System.Convert.ToBase64String ( stream.GetBuffer ( ) , 0 , ( int ) stream.Length ) ; //base64 encoded binary representation of this string base64encodedReference = @ '' AAEAAAD ... . '' ; //this reference is the expected value Assert.AreEqual ( base64encodedReference , base64encodedActual , `` The comparable part of the sparsed set is not equal to the reference . `` ) ; }",( Deep ) comparison of an object to a reference in unit tests ( C # ) "C_sharp : I have a very simple linq query which is as following : The issue is for some strange reason it fetches me the record of every person who I search for whether in lower case or upper case . i.e . test userTest UserTEST USERI will get back the correct records . However when I search for my own name using lower case I do n't get any results back but if I use the first letter of my name as upper case then I get the results . I ca n't seem to figure out why its doing that.Every first and last name in the database start with upper case . The searchString which I 'm using are : richard - I get correct resultswaidande - no results foundBoth of the above users are in the database.I 'm also using Entity Framework to query Sql Server 2012 . var result = ( from r in employeeRepo.GetAll ( ) where r.EmployeeName.Contains ( searchString ) || r.SAMAccountName.Contains ( searchString ) orderby r.EmployeeName select new SelectListItem { Text = r.EmployeeName , Value = r.EmployeeName } ) ;",Linq query not behaving as expected C_sharp : Possible Duplicate : C # : Passing null to overloaded method - which method is called ? Consider these 2 methods : When I try calling : in Visual Studio 2008 SP1 I get int [ ] .Why is this ? void Method ( object obj ) { Console.WriteLine ( `` object '' ) ; } void Method ( int [ ] array ) { Console.WriteLine ( `` int [ ] '' ) ; } Method ( null ) ;,Method overloading and null value "C_sharp : I want to implement a simple search in my application , based on search query I have.Let 's say I have an array containing 2 paragraphs or articles and I want to search in these articles for related subject or related keywords I enter . For example : How can I get the first article based on the search query I provided above ? Any idea ? //this is my search querystring mySearchQuery = `` how to play with matches '' ; //these are my articlesstring [ ] myarticles = new string [ ] { `` article 1 : this article will teach newbies how to start fire by playing with the awesome matches.. '' , `` article 2 : this article does n't contain anything '' } ;",How to implement a simple String search "C_sharp : Why a form is still visible after a FormClosed event is raised ? How to detect when a form is actually closed ? Interesting part is thatleads to the same result . _form2.VisibleChanged += ( s , a ) = > { if ( _form2.Visible == false ) MessageBox.Show ( `` TEXT '' ) ; } ;",Form closed but visible "C_sharp : I am using Xamarin to develop an Apple Watch app . I am trying to send a message from my watch to the iPhone with my SendMessage function . When I do this , I get in the out error the message payload could not be delivered . I can only read part of the message ( `` payload could n ... '' ) because I am writing it on a label ( since my debugger does n't work in Xamarin I ca n't take a look at the message ) , but after doing some googling I 'm assuming that 's what it is written . Any idea why ? Here is my code : public sealed class WCSessionManager : NSObject , IWCSessionDelegate { // Setup is converted from https : //www.natashatherobot.com/watchconnectivity-say-hello-to-wcsession/ // with some extra bits private static readonly WCSessionManager sharedManager = new WCSessionManager ( ) ; private static WCSession session = WCSession.IsSupported ? WCSession.DefaultSession : null ; # if __IOS__ public static string Device = `` Phone '' ; # else public static string Device = `` Watch '' ; # endif public event ApplicationContextUpdatedHandler ApplicationContextUpdated ; public delegate void ApplicationContextUpdatedHandler ( WCSession session , Dictionary < string , object > applicationContext ) ; public event MessageReceivedHandler MessageReceived ; public delegate void MessageReceivedHandler ( Dictionary < string , object > message , Action < Dictionary < string , object > > replyHandler ) ; private WCSession validSession { get { # if __IOS__ // Even though session.Paired and session.WatchAppInstalled are underlined , it will still build as they are available on the iOS version of WatchConnectivity.WCSession Console.WriteLine ( $ '' Paired status : { ( session.Paired ? '✓ ' : '✗ ' ) } \n '' ) ; Console.WriteLine ( $ '' Watch App Installed status : { ( session.WatchAppInstalled ? '✓ ' : '✗ ' ) } \n '' ) ; return ( session.Paired & & session.WatchAppInstalled ) ? session : null ; //return session ; # else return session ; # endif } } private WCSession validReachableSession { get { return session.Reachable ? validSession : null ; } } private WCSessionManager ( ) : base ( ) { } public static WCSessionManager SharedManager { get { return sharedManager ; } } public void StartSession ( ) { if ( session ! = null ) { session.Delegate = this ; session.ActivateSession ( ) ; Console.WriteLine ( $ '' Started Watch Connectivity Session on { Device } '' ) ; } } [ Export ( `` sessionReachabilityDidChange : '' ) ] public void SessionReachabilityDidChange ( WCSession session ) { Console.WriteLine ( $ '' Watch connectivity Reachable : { ( session.Reachable ? '✓ ' : '✗ ' ) } from { Device } '' ) ; // handle session reachability change if ( session.Reachable ) { // great ! continue on with Interactive Messaging } else { // prompt the user to unlock their iOS device } } # region Application Context Methods public void UpdateApplicationContext ( Dictionary < string , object > applicationContext ) { // Application context doesnt need the watch to be reachable , it will be received when opened if ( validSession ! = null ) { try { var NSValues = applicationContext.Values.Select ( x = > new NSString ( JsonConvert.SerializeObject ( x ) ) ) .ToArray ( ) ; var NSKeys = applicationContext.Keys.Select ( x = > new NSString ( x ) ) .ToArray ( ) ; var NSApplicationContext = NSDictionary < NSString , NSObject > .FromObjectsAndKeys ( NSValues , NSKeys ) ; UpdateApplicationContextOnSession ( NSApplicationContext ) ; } catch ( Exception ex ) { Console.WriteLine ( $ '' Exception Updating Application Context : { ex.Message } '' ) ; } } } public void GetApplicationContext ( ) { UpdateApplicationContext ( new Dictionary < string , object > ( ) { { `` GET '' , null } } ) ; } [ Export ( `` session : didReceiveApplicationContext : '' ) ] public void DidReceiveApplicationContext ( WCSession session , NSDictionary < NSString , NSObject > applicationContext ) { Console.WriteLine ( $ '' Recieving Message on { Device } '' ) ; if ( ApplicationContextUpdated ! = null ) { var keys = applicationContext.Keys.Select ( k = > k.ToString ( ) ) .ToArray ( ) ; IEnumerable < object > values ; try { values = applicationContext.Values.Select ( v = > JsonConvert.DeserializeObject ( v.ToString ( ) , typeof ( DoorWatchDTO ) ) ) ; } catch ( Exception ) { values = applicationContext.Values.Select ( v = > JsonConvert.DeserializeObject ( v.ToString ( ) ) ) ; } var dictionary = keys.Zip ( values , ( k , v ) = > new { Key = k , Value = v } ) .ToDictionary ( x = > x.Key , x = > x.Value ) ; ApplicationContextUpdated ( session , dictionary ) ; } } [ Export ( `` session : didReceiveMessage : : '' ) ] public void DidReceiveMessage ( WCSession session , NSDictionary < NSString , NSObject > message , WCSessionReplyHandler replyHandler ) { if ( MessageReceived ! = null ) { var keys = message.Keys.Select ( k = > k.ToString ( ) ) .ToArray ( ) ; IEnumerable < object > values ; values = message.Values.Select ( v = > JsonConvert.DeserializeObject ( v.ToString ( ) ) ) ; var dictionary = keys.Zip ( values , ( k , v ) = > new { Key = k , Value = v } ) .ToDictionary ( x = > x.Key , x = > x.Value ) ; MessageReceived ( dictionary , ( dict ) = > { var NSValues = dict.Values.Select ( x = > new NSString ( JsonConvert.SerializeObject ( x ) ) ) .ToArray ( ) ; var NSKeys = dict.Keys.Select ( x = > new NSString ( x ) ) .ToArray ( ) ; var NSDict = NSDictionary < NSString , NSObject > .FromObjectsAndKeys ( NSValues , NSKeys ) ; replyHandler.Invoke ( NSDict ) ; } ) ; } } public void SendMessage ( Dictionary < string , object > message , Action < Dictionary < string , object > > replyHandler , WKInterfaceLabel label ) { if ( validSession ! = null ) { try { var NSValues = message.Values.Select ( x = > new NSString ( JsonConvert.SerializeObject ( x ) ) ) .ToArray ( ) ; var NSKeys = message.Keys.Select ( x = > new NSString ( x ) ) .ToArray ( ) ; var NSMessage = NSDictionary < NSString , NSObject > .FromObjectsAndKeys ( NSValues , NSKeys ) ; var reply = new WCSessionReplyHandler ( ( replyMessage ) = > { var values = replyMessage.Values.Select ( x = > JsonConvert.SerializeObject ( x ) ) .ToArray ( ) ; var keys = replyMessage.Keys.Select ( x = > x.ToString ( ) ) .ToArray ( ) ; var dict = keys.Zip ( values , ( k , v ) = > new { Key = k , Value = v } ) .ToDictionary ( x = > x.Key , x = > ( object ) x.Value ) ; replyHandler.Invoke ( dict ) ; } ) ; validSession.SendMessage ( NSMessage , reply , ( error ) = > { label.SetText ( error.ToString ( ) ) ; // I can see the error in here : `` payload could n ... '' } ) ; } catch ( Exception ex ) { Console.WriteLine ( $ '' Exception sending message : { ex.Message } '' ) ; } } } private void UpdateApplicationContextOnSession ( NSDictionary < NSString , NSObject > NSApplicationContext ) { NSError error ; var sendSuccessfully = validSession.UpdateApplicationContext ( NSApplicationContext , out error ) ; if ( sendSuccessfully ) { Console.WriteLine ( $ '' Sent App Context from { Device } \nPayLoad : { NSApplicationContext.ToString ( ) } \n '' ) ; # if __IOS__ Logging.Log ( `` Success , payload : `` + NSApplicationContext.ToString ( ) ) ; # endif } else { Console.WriteLine ( $ '' Error Updating Application Context : { error.LocalizedDescription } '' ) ; # if __IOS__ Logging.Log ( `` error : `` + error.LocalizedDescription ) ; # endif } } # endregion",WCSession Send Message gives error `` payload could not be delivered '' "C_sharp : I have a class with code as followsWhen setting the client and context , I lock as followsMy question is , if I only need to get the m_client by itself , is it safe to do this ? m_client is a reference type , so the read ( when assigning to localClient ) is guaranteed to be atomic , so this should work fine on a single CPU.I could ( also in theory ) make the m_client variable volatile , and then this would be safe across multiple cpu 's by preventing out-of-order reads by other CPU 's , but the question is , does the lock-when-writing make it safe to read without being volatile ? Does locking when writing `` flush '' the CPU caches so that when they do a read it wo n't be out-of-order ? private readonly object m_lock = new object ( ) ; private IClient m_clientprivate object m_context ; lock ( m_lock ) { m_client = theClientFromSomewhere ; m_context = contextObject ; } var localClient = m_client ; Debug.Assert ( localClient ! = null ) ; localClient.DoStuff ( ) ;","If I lock when writing to a variable , do I also need to lock when reading , if the read is otherwise atomic ?" "C_sharp : Some times Regex got stuck on some values although it is gives result for most of the documents.I am talking about when scenerio when it got stuck.I Debugged the solution and wanted to see the Values of collection in watch window . I saw following result for most properties.Later it got stuck on 2nd line.I can see there is some problem with regex so it went into the loop.Question : I do n't get any exception for this .Is there any way i can get exception after timeout so my tool can carry on with rest of the work . 1- collection = Regex.Matches ( document , pattern , RegexOptions.Compiled ) ; 2- if ( collection.Count > 0 ) //This Line { Function evaluation disabled because a previous function evaluation timed out . You must continue execution to reenable function evaluation . Regex : @ '' '' '' price '' '' > ( .|\r|\n ) * ? pound ; ( ? < data > .* ? ) < /span > '' Part of Document : < /span > < span > 1 < /span > < /a > < /li > \n\t\t\t\t < li > \n\t\t\t\t\t < span class=\ '' icon icon_floorplan touchsearch-icon touchsearch-icon-floorplan none\ '' > Floorplans : < /span > < span > 0 < /span > < /li > \n\t\t\t\t < /ul > \n\t\t < /div > \n < /div > \n\t < /div > \n < div class=\ '' details clearfix\ '' > \n\t\t < div class=\ '' price-new touchsearch-summary-list-item-price\ '' > \r\n\t < a href=\ '' /commercial-property-for-sale/property-47109002.html\ '' > POA < /a > < /div > \r\n < p class=\ '' price\ '' > \r\n\t\t\t < span > POA < /span > \r\n\t\t\t\t < /p > \r\n\t < h2 class=\ '' address bedrooms\ '' > \r\n\t < a id=\ '' standardPropertySummary47109002\ ''",Regex get stuck for some records "C_sharp : In general does the instantiation of classes with methods , but no fields or properties , have much overhead ? I 'm developing an ASP.NET MVC application that heavily uses constructor injection and some controllers have up to 10 dependencies so far . But due to the high number of dependencies , I resorted to a IMyAppServiceProvider interface and class that provides generic access to all the dependencies , through the DependencyResolver in MVC 3.I ripped out all my application specific code and created a Gist with my basic setup ( This does n't include the BaseController setup mentioned below though ) .I also created a BaseController class that accepts the IMyAppServiceProvider . All controllers inherit from this base class . The base class takes the IMyAppServiceProvider object and has protected variables for all of the various services . Code looks something like this : This makes the code for the controllers `` squeaky clean '' . No private/protected variables , no assignments in the constructor , and the services are referenced by the base class protected variables . However , every request will instantiate every single service that my application uses , whether or not the specific controller uses all of them.My services are simple and just contain method calls with some business logic and database interaction . They are stateless and have no class fields or properties . Therefore , instantiation should be fast , but I 'm wondering if this is a best practice ( I know that 's a loaded term ) . public class BaseController { protected IService1 _service1 ; protected IService2 _service2 ; protected IService3 _service3 ; // ... public BaseController ( IMyAppServiceProvider serviceProvider ) { _service1 = serviceProvider.GetService < IService1 > ; _service2 = serviceProvider.GetService < IService2 > ; _service3 = serviceProvider.GetService < IService3 > ; // ... } }","How fast is class instantiation with methods , but no fields or properties ?" "C_sharp : Goal : Marshal C++ ( pointer to an ? ) array of structs to C # .C++ : CreateVertexDeclaration ( ) C # : I 'm using this to define the D3DVERTEXELEMENT9 structure . SharpDX is a managed DirectX library generated directly from the DirectX SDK C++ headers , so it 's supposedly quite compatible for COM interop . I 've actually already got 10 other hooks working perfectly , but this is the first with a pointer to an array of structures.Just in case SharpDX 's structure definition does n't work , I 've also tried replacing it with my own definition : I have tried the following C # method signatures : Note : Having IntPtr devicePointer as the first parameter should n't be the problem . I have it for 10 other hooks that works successfully.Note : These are Direct3D API hooks . So my program is being passed the data that I need to marshal from an unmanaged C++ environment to a managed C # environment.1 : CreateVertexDeclaration ( IntPtr devicePointer , D3DVERTEXELEMENT9 [ ] vertexElements , out IntPtr vertexDeclaration ) Result : The array has one element , but its values are default ( does n't make sense ) . This means that short Stream , short Offset , Type , Method , Usage , and UsageIndex are all 0 ( the enums take their first value ) .2 : CreateVertexDeclaration ( IntPtr devicePointer , ref D3DVERTEXELEMENT9 [ ] vertexElements , out IntPtr vertexDeclaration ) Result : The array itself is null.3 : CreateVertexDeclaration ( IntPtr devicePointer , [ In , Out ] D3DVERTEXELEMENT9 [ ] vertexElements , out IntPtr vertexDeclaration ) Same as 1 . No benefit.4 : CreateVertexDeclaration ( IntPtr devicePointer , D3DVERTEXELEMENT9 vertexElements , out IntPtr vertexDeclaration ) Same as 1 , does n't change anything . I get a defaulted structure . The same if I called new D3DVERTEXELEMENT9 ( ) .5 : CreateVertexDeclaration ( IntPtr devicePointer , ref D3DVERTEXELEMENT9 vertexElements , out IntPtr vertexDeclaration ) I forgot the result , but it did n't work . I think it actually crashed the hooks.6 : CreateVertexDeclaration ( IntPtr devicePointer , IntPtr vertexElements , out IntPtr vertexDeclaration ) I think either this # 6 or # 1/ # 2 are supposed to be correct . I 've probably messed up the implementation for this method ? I tried to use this code with it : But it does n't work ! It 's the same as # 1 . My marshalled pointer-to-structure is a defaulted structure , the same as if I called new D3DVERTEXELEMENT9 ( ) .7 : CreateVertexDeclaration ( IntPtr devicePointer , ref IntPtr vertexElements , out IntPtr vertexDeclaration ) Null or zero ; not valid.For method # 6 ( using IntPtr ) , I tried viewing the memory region in Visual Studio . The next 50 bytes or so were all zeros . There was maybe one 2 byte in the field of 50 zeros . But it was pretty much 49 bytes of zeros starting from the IntPtr supplied to the method.Is n't that a problem ? Does n't that mean that the supplied pointer is already incorrect ? So I took that to mean I had the wrong method signature . The problem is I 've been trying all sorts of possible combinations , and they either crash the program or give me a default array the same as if I called new D3DVERTEXELEMENT9 ( ) .Question : What is the solution to correctly marshalling the pVertexElements array of structs from C++ to C # , and why are my current signatures incorrect ? Additional Note : In C++ , the length of this specific array is defined by suffixing a D3DDECL_END . I have no idea how I 'm supposed to get the corresponding array length in C # without some sort of passed length parameter.Other Working Hooks : C++ : ... C # : Note : I use SharpDX enums and structures for all of these delegates , and they work fine . They also all begin with IntPtr devicePointer.Log of passed parameters for other hooks : The method signature most similar to this CreateVertexDeclaration ( ) seems to be Clear ( ) . Here is my implementation of Clear ( ) : HRESULT CreateVertexDeclaration ( [ in ] const D3DVERTEXELEMENT9 *pVertexElements , [ out , retval ] IDirect3DVertexDeclaration9 **ppDecl ) ; [ StructLayout ( LayoutKind.Sequential , Pack = 1 ) ] public class D3DVERTEXELEMENT9 { public short Stream ; public short Offset ; public DeclarationType Type ; // Enum public DeclarationMethod Method ; // Enum public DeclarationUsage Usage ; // Enum public byte UsageIndex ; } var vertex = ( D3DVERTEXELEMENT9 ) Marshal.PtrToStructure ( vertexElements , typeof ( D3DVERTEXELEMENT9 ) ) ; BeginScene ( LPDIRECT3DDEVICE9 pDevice ) BeginStateBlock ( LPDIRECT3DDEVICE9 pDevice ) Clear ( LPDIRECT3DDEVICE9 pDevice , DWORD Count , CONST D3DRECT* pRects , DWORD Flags , D3DCOLOR Color , float Z , DWORD Stencil ) ColorFill ( LPDIRECT3DDEVICE9 pDevice , IDirect3DSurface9* pSurface , CONST RECT* pRect , D3DCOLOR color ) CreateAdditionalSwapChain ( LPDIRECT3DDEVICE9 pDevice , D3DPRESENT_PARAMETERS* pPresentationParameters , IDirect3DSwapChain9** pSwapChain ) CreateCubeTexture ( LPDIRECT3DDEVICE9 pDevice , UINT EdgeLength , UINT Levels , DWORD Usage , D3DFORMAT Format , D3DPOOL Pool , IDirect3DCubeTexture9** ppCubeTexture , HANDLE* pSharedHandle ) BeginSceneDelegate ( IntPtr devicePointer ) ; BeginStateBlocKDelegate ( IntPtr devicePointer ) ; ClearDelegate ( IntPtr devicePointer , int count , IntPtr rects , ClearFlags flags , ColorBGRA color , float z , int stencil ) ; ColorFillDelegate ( IntPtr devicePointer , IntPtr surface , IntPtr rect , ColorBGRA color ) ; CreateAdditionalSwapChainDelegate ( IntPtr devicePointer , [ In , Out ] PresentParameters presentParameters , out SwapChain swapChain ) ; CreateCubeTextureDelegate ( IntPtr devicePointer , int edgeLength , int levels , Usage usage , Format format , Pool pool , out IntPtr cubeTexture , IntPtr sharedHandle ) ; ... DLL injection suceeded.Setting up Direct3D 9 hooks ... Activating Direct3D 9 hooks ... CreateDepthStencilSurface ( IntPtr devicePointer : 147414976 , Int32 width : 1346 , Int32 height : 827 , Format format : D24S8 , MultisampleType multiSampleType : None , Int32 multiSampleQuality : 0 , Boolean discard : False , IntPtr & surface : ( out ) , IntPtr sharedHandle : 0 ) CreateDepthStencilSurface ( IntPtr devicePointer : 147414976 , Int32 width : 1346 , Int32 height : 827 , Format format : D24S8 , MultisampleType multiSampleType : None , Int32 multiSampleQuality : 0 , Boolean discard : False , IntPtr & surface : ( out ) , IntPtr sharedHandle : 0 ) Clear ( IntPtr devicePointer : 147414976 , Int32 count : 0 , IntPtr rects : ( Empty ) , ClearFlags flags : Target , ColorBGRA color : A:0 R:0 G:0 B:0 , Single z : 1 , Int32 stencil : 0 ) Clear ( IntPtr devicePointer : 147414976 , Int32 count : 0 , IntPtr rects : ( Empty ) , ClearFlags flags : Target , ColorBGRA color : A:0 R:0 G:0 B:0 , Single z : 1 , Int32 stencil : 0 ) BeginScene ( IntPtr devicePointer : 147414976 ) Clear ( IntPtr devicePointer : 147414976 , Int32 count : 0 , IntPtr rects : ( Empty ) , ClearFlags flags : Target , ColorBGRA color : A:0 R:0 G:0 B:0 , Single z : 1 , Int32 stencil : 0 ) Clear ( IntPtr devicePointer : 147414976 , Int32 count : 0 , IntPtr rects : ( Empty ) , ClearFlags flags : Target , ColorBGRA color : A:0 R:0 G:0 B:0 , Single z : 1 , Int32 stencil : 0 ) Clear ( IntPtr devicePointer : 147414976 , Int32 count : 0 , IntPtr rects : ( Empty ) , ClearFlags flags : ZBuffer , ColorBGRA color : A:0 R:0 G:0 B:0 , Single z : 1 , Int32 stencil : 0 ) BeginScene ( IntPtr devicePointer : 147414976 ) private Result Clear ( IntPtr devicePointer , int count , IntPtr rects , ClearFlags flags , ColorBGRA color , float z , int stencil ) { try { var structSize = Marshal.SizeOf ( typeof ( Rectangle ) ) ; var structs = new Rectangle [ count ] ; for ( int i = 0 ; i < count ; i++ ) { structs [ i ] = ( Rectangle ) Marshal.PtrToStructure ( rects , typeof ( Rectangle ) ) ; } // Seems to work fine , not sure why it does n't work for CreateVertexDeclaration var rectangles = structs ; Log.LogMethodSignatureTypesAndValues ( devicePointer , count , rectangles.PrintTypesNamesValues ( ) , flags , color , z , stencil ) ; GetOrCreateDevice ( devicePointer ) ; if ( rectangles.Length == 0 ) Device.Clear ( flags , color , z , stencil ) ; else Device.Clear ( flags , color , z , stencil , rectangles ) ; } catch ( Exception ex ) { Log.Warn ( ex.ToString ( ) ) ; } return Result.Ok ; }",Difficult Marshalling DirectX array of structs from C++ to C # "C_sharp : We 're using Web API with Json.Net using TypeNameHandling = TypeNameHandling.Objects in our serializer settings . This works fine , but we use the type information only client-side , never for deserialization . Our serialized objects look like this : I would like to customize the value in the $ type property so it reads as : I already have a contract resolver that inherits from CamelCasePropertyNamesContractResolver . I figure what I need to do is turn off TypeNameHandling and add a custom property myself . I 'm 95 % there : At this point I 'm stuck with supplying the property 's value.I 'm unsure that this is the correct approach because each of the ValueProvider types from Json.Net take a MemberInfo as a constructor parameter . I do n't have a MemberInfo to supply as a parameter , so ... . I 'm stuck.How do I add a custom $ type value ? Since I 'm not doing deserialization in C # I will never need to convert the type information back into a type . { `` $ type '' : `` PROJECTNAME.Api.Models.Directory.DtoName , PROJECTNAME.Api '' , `` id '' : 67 , `` offices '' : [ { `` $ type '' : `` PROJECTNAME.Api.Models.Directory.AnotherDtoName , PROJECTNAME.Api '' , `` officeName '' : `` FOO '' } ] } , { `` $ type '' : `` Models.Directory.DtoName '' , `` id '' : 67 , `` offices '' : [ { `` $ type '' : `` Models.Directory.AnotherDtoName '' , `` officeName '' : `` FOO '' } ] } , protected override IList < JsonProperty > CreateProperties ( Type type , MemberSerialization memberSerialization ) { var assemblyName = type.Assembly.GetName ( ) .Name ; var typeName = type.FullName.Substring ( assemblyName.Length + 1 ) ; var typeProperty = new JsonProperty ( ) { PropertyName = `` $ type '' , PropertyType = typeof ( string ) , Readable = true , Writable = true , ValueProvider = null // ? ? ? ? ? typeName } ; var retval = base.CreateProperties ( type , memberSerialization ) ; retval.Add ( typeProperty ) ; return retval ; }",Custom $ type value for serialized objects "C_sharp : Random example : .Net has tons of these little WhateverCollection classes that do n't implement IEnumerable < T > , which means I ca n't use Linq to objects with them out of the box.Even before Linq , you 'd think they would have wanted to make use of generics ( which were introduced all the way back in C # 2 I believe ) It seems I run across these annoying little collection types all the time . Is there some technical reason ? ConfigurationElementCollection",Why do so many named collections in .NET not implement IEnumerable < T > ? "C_sharp : Here is the code that I use to close my application , its associated processes and to delete all the files that have been extracted during the use of the application : However , the problem is that when it tries to delete the files ( which are the images used somewhere in the app ) it shows the following exception : `` The process can not access the file because it is being used by another process . `` Update : I found that the process 'Mastersolution.vhost.exe ' is holding all the files that I am attempting to delete . Mastersolution is actually the main app that I am closing on the line App.Current.Shutdown ( ) ; So I need to somehow disconnect the files from the main application prior to deleting them . But hoe to do this ? private void Quit_Click ( object sender , RoutedEventArgs e ) //close the application { //kill cinector after all import is done Process [ ] processes = Process.GetProcesses ( ) ; for ( int i = 0 ; i < processes.Count ( ) ; i++ ) { if ( processes [ i ] .ProcessName.ToLower ( ) .Contains ( `` CinectorProcess '' ) ) { processes [ i ] .Kill ( ) ; } } //also kill powerpoint just in case for ( int i = 0 ; i < processes.Count ( ) ; i++ ) { if ( processes [ i ] .ProcessName.ToLower ( ) .Contains ( `` powerpnt '' ) ) { processes [ i ] .Kill ( ) ; } } //kill the engine ShutdownEngine ( ) ; //kill the main app App.Current.Shutdown ( ) ; //also delete all three folders //slides_png_prev if ( Directory.Exists ( slides_png_prev ) ) { Thumbnails = null ; Directory.Delete ( slides_png_prev , true ) ; } //slides_png if ( Directory.Exists ( slides_png ) ) { Directory.Delete ( slides_png , true ) ; } //slides_png_prev_seleect if ( Directory.Exists ( slides_png_prev_seleect ) ) { Directory.Delete ( slides_png_prev_seleect , true ) ; } }",How to delete files programmatically ? "C_sharp : I have TcpListener class and I 'm using async/await reading and writing.For this server I have created single database instance where I have prepared all database queries.But for more then one TcpClient I 'm keep getting exception : An exception of type MySql.Data.MySqlClient.MySqlException occurred in MySql.Data.dll but was not handled in user code Additional information : There is already an open DataReader associated with this Connection which must be closed first.If I understand it correctly there ca n't be more then one database query at time which is problem with more then one async client.So I simply added locks in my queries like this and everything seems fine.I have also try the method with usings which create new connection for every query as mentioned from someone of SO community but this method is much more slower than locks : I used Stopwatch to benchmarks this methods and queries with one connection with locks are performed in +- 20ms which is +- only delay of network but with usings it is +- 55ms because of .Open ( ) method which takes +- 35ms.Why a lot of people use method with usings if there is much worse performance ? Or am I doing something wrong ? // One MySqlConnection instance for whole program . lock ( thisLock ) { var cmd = connection.CreateCommand ( ) ; cmd.CommandText = `` SELECT Count ( * ) FROM logins WHERE username = @ user AND password = @ pass '' ; cmd.Parameters.AddWithValue ( `` @ user '' , username ) ; cmd.Parameters.AddWithValue ( `` @ pass '' , password ) ; var count = int.Parse ( cmd.ExecuteScalar ( ) .ToString ( ) ) ; return count > 0 ; } using ( MySqlConnection connection = new MySqlConnection ( connectionString ) ) { connection.Open ( ) ; // This takes +- 35ms and makes worse performance than locks using ( MySqlCommand cmd = connection.CreateCommand ( ) ) { cmd.CommandText = `` SELECT Count ( * ) FROM logins WHERE username = @ user AND password = @ pass '' ; cmd.Parameters.AddWithValue ( `` @ user '' , username ) ; cmd.Parameters.AddWithValue ( `` @ pass '' , password ) ; int count = int.Parse ( cmd.ExecuteScalar ( ) .ToString ( ) ) ; return count > 0 ; } }",C # Mysql - Using of locks on database query for async await server "C_sharp : Is there a simple fix for the following ? Or is this a bug in VSCode and/or the language-specific extensions ? I created two projects and a solution like this : I added a project reference to the ClassLibrary from within the MainProgram.I updated the Program.cs to call the ClassLibrary.I can restore , build , and run the program successfully.The problem is when I open the solution folder in Visual Studio Code.When I open Program.cs , the editor red-underlines the F # library types as being missing.When I open Library.fs , the editor red-underlines pretty much everything . Interestingly , the errors are from a C # compiler , not an F # compiler . Ctrl-Shift-B builds the projects with 0 Warning ( s ) and 0 Error ( s ) .VSCode 's Problems windows displays 12 compiler errors.I have also tried opening the project folders separately.If I open VS Code in the F # library project , Intellisense works.If I open VS Code in the C # console project , the editor still does not recognize the types from F # library . UpdateI have VS Code version 1.15.1 , with five extensions installed.C # , 1.12.1Ionide-fsharp , 2.33.0Language PL/SQL , 1.0.4Mono Debug , 0.15.7XML Tools , 1.9.2 dotnet new library -lang F # -o .\ClassLibrarydotnet new console -lang C # -o .\MainProgramdotnet new slndotnet sln add .\ClassLibrary\ClassLibrary.fsprojdotnet sln add .\MainProgram\MainProgram.csproj dotnet add reference ..\ClassLibrary\ClassLibrary.fsproj static void Main ( string [ ] args ) { ClassLibrary.Say.hello ( `` world . `` ) ; } dotnet restoredotnet run -p .\MainProgram\MainProgram.csproj","Can Visual Studio Code work with mixed-language , .NET Core solutions ?" "C_sharp : CLR uses distinct System.Type instances to represent SZ-arrays ( Single-dimensional , Zero-based , aka vectors ) and non-zero-based arrays ( even if they are single-dimensional ) . I need a function that takes an instance of System.Type and recognizes if it represents a SZ-array . I was able to check the rank using GetArrayRank ( ) method , but do not know how to check that it is zero-based . Would you please help me ? using System ; class Program { static void Main ( ) { var type1 = typeof ( int [ ] ) ; var type2 = Array.CreateInstance ( typeof ( int ) , new [ ] { 1 } , new [ ] { 1 } ) .GetType ( ) ; Console.WriteLine ( type1 == type2 ) ; // False Console.WriteLine ( IsSingleDimensionalZeroBasedArray ( type1 ) ) ; // True Console.WriteLine ( IsSingleDimensionalZeroBasedArray ( type2 ) ) ; // This should be False } static bool IsSingleDimensionalZeroBasedArray ( Type type ) { // How do I fix this implementation ? return type ! = null & & type.IsArray & & type.GetArrayRank ( ) == 1 ; } }",How do I recognize a System.Type instance representing SZ-Array ? "C_sharp : There are a fair share of questions about Interlocked vs. volatile here on SO , I understand and know the concepts of volatile ( no re-ordering , always reading from memory , etc . ) and I am aware of how Interlocked works in that it performs an atomic operation.But my question is this : Assume I have a field that is read from several threads , which is some reference type , say : public Object MyObject ; . I know that if I do a compare exchange on it , like this : Interlocked.CompareExchange ( ref MyObject , newValue , oldValue ) that interlocked guarantees to only write newValue to the memory location that ref MyObject refers to , if ref MyObject and oldValue currently refer to the same object.But what about reading ? Does Interlocked guarantee that any threads reading MyObject after the CompareExchange operation succeeded will instantly get the new value , or do I have to mark MyObject as volatile to ensure this ? The reason I 'm wondering is that I 've implemented a lock-free linked list which updates the `` head '' node inside itself constantly when you prepend an element to it , like this : Now after Prepend succeeds , are the threads reading head guaranteed to get the latest version , even though it 's not marked as volatile ? I have been doing some empirical tests , and it seems to be working fine , and I have searched here on SO but not found a definitive answer ( a bunch of different questions and comments/answer in them all say conflicting things ) . [ System.Diagnostics.DebuggerDisplay ( `` Length= { Length } '' ) ] public class LinkedList < T > { LList < T > .Cell head ; // ... . public void Prepend ( T item ) { LList < T > .Cell oldHead ; LList < T > .Cell newHead ; do { oldHead = head ; newHead = LList < T > .Cons ( item , oldHead ) ; } while ( ! Object.ReferenceEquals ( Interlocked.CompareExchange ( ref head , newHead , oldHead ) , oldHead ) ) ; } // ... . }","Fields read from/written by several threads , Interlocked vs. volatile" "C_sharp : Today , I pull the code from my client , and I get an error in this line.This line alsoThe $ symbols is so weird with me . This is C # code . throw new Exception ( $ '' One or more errors occurred during removal of the company : { Environment.NewLine } { Environment.NewLine } { exc.Message } '' ) ; moreCompanies = $ '' { moreCompanies } , { databaseName } '' ;",What do dollar symbols in C # Code mean ? C_sharp : I have path variable which I got from my appsettings : I am trying to use it in Directory.CreateDirectory ( path ) method . But I got new folder in my application bin folder instead of C : \Users\Evgeny\AppData\Local\Temp\myapplication\data.Should I replace % TEMP % manually ? var path= '' % TEMP % \myapplication\data '' ;,How to use system\environment variables in .NET string ? "C_sharp : Is there a way to sort a String List by the number of words matched from a string array ? Is there a way to generate an output without using another list or for loop to sort var targets = new string [ ] { `` one '' , `` two '' , `` three '' } ; var list = new List < string > ( ) ; list.Add ( `` one little pony '' ) ; list.Add ( `` one two little pony '' ) ; list.Add ( `` one two three little pony '' ) ; list.Add ( `` little pony '' ) ; x = x.OrderByDescending ( u = > targets.Any ( u.Contains ) ) .ToList ( ) ; foreach ( var item in list ) { Debug.Writeline ( item ) ; } one two three little ponyone two little ponyone little ponylittle pony",How do you sort a String List by the number of words matched with an Array in Linq C_sharp : I have been given a sample statement : How is it possible to make this a valid statement ? What code do I need to include in MyClass to support the implicit conversion from an int ? MyClass myclass = 3 ;,Interview question on C # implicit conversion "C_sharp : Summary.NET Core apps fail to XML serialize an object which contains an enum value , while .NET Framework ( 4.7.2 ) succeeds . Is this a known breaking change , and if so , how can I work around it ? Code ExampleThe following console application does not throw an exception in .NET Framework 4.7.2 project : The exact same code in a .NET Core 3.0 Console Application throws the following exception when calling Serialize : Am I doing something wrong in my code ? Is this a breaking change between .NET Framework and .NET Core ? Is there a workaround ? UpdateI should have pointed out that when serializing in .NET 4.7.2 , I get the following ( desired ) output for Value : I would like whatever solution is proposed for .NET Core to also output the same XML , as I need to maintain compatibility with existing files and older versions of the app which are n't using .NET Standard.Update 2I should have included this information in the original question , but now that I 'm attempting to implement an answer , I see that there are a few requirements I did n't think of at first.First , the object which is being serialized is also being used in logic , and the logic depends on the object stored in the value being an enumeration . Therefore , converting the value permanently to an integer ( such as by casting in a setter ) will impact the logic of the application so it 's something I ca n't do.Second , even though my example has been simplified to show a difference between .NET Framework and .NET Core , the real application uses many enumerations . Therefore , the solution should allow multiple enumeration values to be used . public enum MyEnum { One , } public class ValueContainer { public object Value ; } class Program { static void Main ( string [ ] args ) { XmlSerializer newSerializer = XmlSerializer.FromTypes ( new [ ] { typeof ( ValueContainer ) } ) [ 0 ] ; var instance = new ValueContainer ( ) ; instance.Value = MyEnum.One ; using ( var memoryStream = new MemoryStream ( ) ) { newSerializer.Serialize ( memoryStream , instance ) ; } } } System.InvalidOperationException HResult=0x80131509 Message=There was an error generating the XML document . Source=System.Private.Xml StackTrace : at System.Xml.Serialization.XmlSerializer.Serialize ( XmlWriter xmlWriter , Object o , XmlSerializerNamespaces namespaces , String encodingStyle , String id ) at System.Xml.Serialization.XmlSerializer.Serialize ( Stream stream , Object o , XmlSerializerNamespaces namespaces ) at System.Xml.Serialization.XmlSerializer.Serialize ( Stream stream , Object o ) at CoreXml.Program.Main ( String [ ] args ) in C : \Users\vchel\source\repos\CoreXml\CoreXml\Program.cs : line 28Inner Exception 1 : InvalidOperationException : The type CoreXml.MyEnum may not be used in this context . < Value xsi : type= '' xsd : int '' > 0 < /Value >",Why does XmlSerializer fail to serialize enum value in .Net Core but works fine in .NET Framework "C_sharp : I have a piece of code that runs a Parallel.Foreach on a list of items to process . Each iteration creates a couple of objects with each object instantiating and disposing it 's own instance of the Ninject IKernel . The IKernel is disposed when the object is done it 's work.That said , this code works perfectly well on my Windows 7 , I7 laptop . However when I push it out to my VPS that runs Windows 2008 I get this exception . The exception does n't happen on the same iteration , sometimes it will get through 10 iterations and throw an exception , other times it will go through hundreds of them . Obviously seems like a threading issue , but it does n't happen anywhere but my VPS . If it matters this is being hosted in ASP.NET IIS.Here is a snippet of the code : Edit 1One thing is for sure , this is a thread safety issue and I should not be creating more than one instance of IKernel per application . It 's a matter of understanding on how to configure the proper scopes in order to accomplish Entity Framework Context thread safety yet preserving the UoW type approach where multiple business layer classes can share the same EF context within the UoW scope within a single thread . System.AggregateException : One or more errors occurred . -- - > System.ArgumentOutOfRangeException : Index was out of range . Must be non-negative and less than the size of the collection . Parameter name : index at System.Collections.Generic.List ` 1.RemoveAt ( Int32 index ) at Ninject.KernelBase.Dispose ( Boolean disposing ) //Code that creates and disposes the Ninject kernelusing ( ninjectInstance = new NinjectInstance ( ) ) { using ( var unitOfWork = ninjectInstance.Kernel.Get < NinjectUnitOfWork > ( ) ) { Init ( ) ; continueValidation = Validate ( tran , ofr ) ; } } public class NinjectInstance : IDisposable { public IKernel Kernel { get ; private set ; } public NinjectInstance ( ) { Kernel = new StandardKernel ( new NinjectSettings ( ) { AllowNullInjection = true } , new NinjectUnitOfWorkConfigModule ( ) ) ; } public void Dispose ( ) { if ( Kernel ! = null ) { Kernel.Dispose ( ) ; } } }",Ninject exception in Parallel.Foreach "C_sharp : Right now I have a few services that are defined in an assembly that is not dependent on an IoC container ( Ninject in my case ) . In the main project I have an IRepository for data access registered in the container . I also have IAuthenticationService and IErrorLogger services registered , whose concrete implementation I want to use the repository for their logic . However , I am not sure how to best accomplish this . Currently , my constructor on both concrete implementations take an IRepository parameter and I pass it in when I register them : Here I just tell the container to grab the IRepository instance and pass it to the constructor.I did n't feel right about making my service assembly depend on ninject or even the common service locator ( CSL ) , but I am not sure about my current way either . I am looking for opinions and alternate solutions.If my other services do n't use an IRepository , I would have to create new concrete implementations of these services for each type of underlying IRepository type ( e.g . an AuthenticationService for both fake and real data ) . It would be a lot of logic repetition . this.Bind < IRepository > ( ) .To < EntityFrameworkRepository < MyDatabaseEntities > > ( ) ; this.Bind < IAuthenticationService > ( ) .To < MyAuthenticationService > ( ) . WithConstructorArgument ( `` myRepository '' , ctx = > ctx.Kernel.Get < IRepository ( ) ) ;",General IoC practice - is it wrong for services to depend on each other ? "C_sharp : I have got an Angular + Net Core application with an ( RSA + AES ) encrypted connection.All requests from client are coming via POST . ( You will be given an example below.The script provided below works quite well but throws in 5 % cases an exception : The length of the data to decrypt is not valid for the size of this key in the line : Encryption part ( Front-end ) } Decryption part ( C # Back-end ) Example , a user wants to open a page by id . Front-end:1 ) encrypts request Id using AES2 ) encrypts AES ' key & iv using RSA3 ) sends to Back-end Back-end:1 ) decrypts AES ' key & value using RSA < -- - BREAKS HERE2 ) decrypts request Id using AES ' key & iv3 ) decrypts and get id as if there was no encryption This logic works quite well but breaks sometimes ... EXAMPLE OF FAILING request : EXAMPLE OF CORRECT REQUEST : var decryptedAesKey = Encoding.UTF8.GetString ( rsaCng.Decrypt ( Convert.FromBase64String ( request.k ) , RSAEncryptionPadding.Pkcs1 ) ) ; encrypt ( requestObj : any ) : any { var rsaEncrypt = new JsEncryptModule.JSEncrypt ( ) ; var key = this.generateAesKey ( 32 ) ; //secret keyvar iv = this.generateAesKey ( 16 ) ; //16 digitvar stringifiedRequest = CryptoJS.enc.Utf8.parse ( JSON.stringify ( requestObj ) ) ; var aesEncryptedRequest = CryptoJS.AES.encrypt ( stringifiedRequest , CryptoJS.enc.Utf8.parse ( key ) , { keySize : 128 / 8 , iv : CryptoJS.enc.Utf8.parse ( iv ) , padding : CryptoJS.pad.Pkcs7 , mode : CryptoJS.mode.CBC } ) ; rsaEncrypt.setPrivateKey ( this.publicPemKey ) ; var encryptedKey = rsaEncrypt.encrypt ( key ) ; var encryptedIV = rsaEncrypt.encrypt ( iv ) ; var encryptedRequestObj = { k : encryptedKey , v : encryptedIV , r : aesEncryptedRequest.toString ( ) } ; return encryptedRequestObj ; var decryptedAesKey = Encoding.UTF8.GetString ( rsaCng.Decrypt ( Convert.FromBase64String ( request.k ) , RSAEncryptionPadding.Pkcs1 ) ) ; var decryptedAesIV = Encoding.UTF8.GetString ( rsaCng.Decrypt ( Convert.FromBase64String ( request.v ) , RSAEncryptionPadding.Pkcs1 ) ) ; byte [ ] encryptedBytes = request.r ; AesCryptoServiceProvider aes = new AesCryptoServiceProvider ( ) { Mode = CipherMode.CBC , Padding = PaddingMode.PKCS7 , Key = Encoding.UTF8.GetBytes ( decryptedAesKey ) , IV = Encoding.UTF8.GetBytes ( decryptedAesIV ) } ; ICryptoTransform crypto = aes.CreateDecryptor ( aes.Key , aes.IV ) ; byte [ ] secret = crypto.TransformFinalBlock ( encryptedBytes , 0 , encryptedBytes.Length ) ; crypto.Dispose ( ) ; requestJson = Encoding.UTF8.GetString ( secret ) ; { `` k '' : '' L+ikMb/JGvFJmhBpADMGTVLFlkHOe69dZUVSQ5r7yHCvWSwY2x6KMR274ByflF0lDMYdCmywo+Nfq6JUybRctDqmAp8UFHXnhwBAv49d99mF5x2yGbJr/j0cn6EZyhweNK4p97i5yMM6MQtluZTIErpsUa22Cajtj8F+xl0jJPUMXIf8cs2X+ooFr5VP/p/vlbPmnEY3K/hMCRZRdXMkEqaCWoA5EnYMTQABtRXPZWgLSQwJpr4dqEAhGCBtga1AGsKF3dQCsKO92NYyst0ngkBiKwFNfy1QDwbk4SzKAKeBckaY17SHt526NMvpEv08BGV6btBxcM+ypsmpB4o0 '' , '' v '' : '' LIndJOjUgKHDlXqwpg7uSmDuut3oi5z9L/GKm2KgU7P2EXmf/JIpXM0JgpTXPJL7wUTndq3F9UMlMdU70JBOV56x/4uIBRbHbyvaG2JZYxbBZblwyYgdo1ZcK1OSE4k5oesQmMEGNEk9RVu+EZO4xAme6+mlyd2/Y/709jaC90PuiOG/k/4JMTTI/2q4s7tk6IgSxLBT8ZiOtgJVGdasSaAksEBMRHyUkzAIr5tSUw1VXedwJFPfwQT2nOD5dU2cxiNJKOwtO9uAYXly0U0FDoa/nkWskca8zaU+4EiPikJ6Km7phViH9JvwZFgHhBj+8FM6Jof+AdrY3q1dcMLFlg== '' , '' r '' : '' OJnA3wFoKKG+iu4FciXyJg== '' } { `` k '' : '' uW8d7vIzlgkEkKTkDnHbBZeqKwdgoG+1BVZ/NUiC0pZ/LqZM9aUasQSx+qDg+X50ur30uRnEyAyIZXruYeHQb8cacx5mvr9LWLud+wueJXsOlEEdocD/4A1DfE9TDFdnTaVcMSIwhSVlLPUjO7ubJdANY9yK4S+vb0IyPbsrYpAT7ho01mDkvsH1rZsId/TmzQadmsGhThowu+mrQlz78rrdlN8nI5LnUQHXRNWMUgBvuteTpVBmyrfnIELIKoo/jI6Nj4rGPQBf7+2OOoZPs0Y1GtjXxUCTAt7madNLKSOdaPjdWjaOfGSwnymDNeEFyJQOmAwHZoOGYNd2B/UhQQ== '' , '' v '' : '' IimiJFcKv5ZHWHljJixX0LUgV4I2GWAWPbk7dWHVhwmHEhTHA/hCdih/E1wiWFS+0KaL05ZobiZInyK7gCwYPHaz0aRCSQtVeBPiFg4f7L0gwfvk1GHwJ1wZjqNJZaYf0elXJzc2l5BwN+aXNWaNJDPA7M6kfK6UPkq84IV3ohCQcTuC8zPM7aMJHxpz9IudcrMmYIkeqrj9Do88CkTLv8yg5hk3EASPk9HqsUieuQixggv/8ZlHnp00iftc62LJlIuCkGn4WR3FkMdFdqpKXf6Ebj8PU1HOmokEtKtYJiOZ5JxieZO5Pnd+ez6sO7khIbdRFDhAQ20chsxKUypezw== '' , '' r '' : '' 2mbUgU44JFFDlWu8As2RIw== '' }",RSA Decryption exception : The length of the data to decrypt is not valid for the size of this key "C_sharp : Basically , I have an observable of input strings that I want to process individually and then do something with the result . If the input string contains commas ( as a delimiter ) , I want to split the string and process each substring individually and then do something with the each sequence of strings . The snippet below illustrates a simplified version of what I am trying to do : As explained in the comment , the above does NOT work . The .ToArray ( ) -call concatenates the entire observable into a single sequence.However , I have solved this by putting the splitting and processing into a single action , as such : But is there a way , using Rx , to solve this problem by NOT putting the splitting and processing in the same action ? What is the recommended solution for this problem ? I should also mention that the processing , i.e . the ToUpper ( ) -call , is in reality a web-service call . I used ToUpper ( ) in my examples so that my problem should be easy to explain . But that means I want this processing to be done in parallel and non-blocking . [ Fact ] public void UniTest1 ( ) { var observable = new ReplaySubject < string > ( ) ; observable.OnNext ( `` a , b '' ) ; observable.OnNext ( `` c , d , e '' ) ; observable.OnCompleted ( ) ; var result = new List < string [ ] > ( ) ; observable .SelectMany ( x = > x.Split ( ' , ' ) ) .Select ( x = > x.ToUpper ( ) ) .ToArray ( ) // How to collect an IEnumerable for each item here ? .Do ( s = > result.Add ( s ) ) .Subscribe ( ) ; // Here , result is actually { { `` A '' , '' B '' , '' C '' , '' D '' , '' E '' } } , I need { { `` A '' , '' B '' } , { `` C '' , '' D '' , '' E '' } } Assert.Equal ( 2 , result.Count ) ; Assert.Equal ( `` A '' , result [ 0 ] [ 0 ] ) ; Assert.Equal ( `` B '' , result [ 0 ] [ 1 ] ) ; Assert.Equal ( `` C '' , result [ 1 ] [ 0 ] ) ; Assert.Equal ( `` D '' , result [ 1 ] [ 1 ] ) ; Assert.Equal ( `` E '' , result [ 1 ] [ 2 ] ) ; } [ Fact ] public void UniTest2 ( ) { var observable = new ReplaySubject < string > ( ) ; observable.OnNext ( `` a , b '' ) ; observable.OnNext ( `` c , d , e '' ) ; observable.OnCompleted ( ) ; var result = new List < string [ ] > ( ) ; observable .Select ( x = > x.Split ( ' , ' ) .Select ( s = > s.ToUpper ( ) ) .ToArray ( ) ) .Do ( s = > result.Add ( s ) ) .Subscribe ( ) ; // Result is as expected : { { `` A '' , '' B '' } , { `` C '' , '' D '' , '' E '' } } Assert.Equal ( 2 , result.Count ) ; Assert.Equal ( `` A '' , result [ 0 ] [ 0 ] ) ; Assert.Equal ( `` B '' , result [ 0 ] [ 1 ] ) ; Assert.Equal ( `` C '' , result [ 1 ] [ 0 ] ) ; Assert.Equal ( `` D '' , result [ 1 ] [ 1 ] ) ; Assert.Equal ( `` E '' , result [ 1 ] [ 2 ] ) ; }","Reactive Extensions : Split input , process , and concatenate back" "C_sharp : By lock helpers I am referring to disposable objects with which locking can be implemented via using statements . For example , consider a typical usage of the SyncLock class from Jon Skeet 's MiscUtil : Now , consider the following usage : My question is this - since example is created on one thread and ConcurrentMethod is called on another , could n't ConcurrentMethod 's thread be oblivious to _padock 's assignment in the constructor ( due to thread caching / read-write reordering ) , and thus throw a NullReferenceException ( on _padLock itself ) ? I know that locking with Monitor/lock has the benefit of memory barriers , but when using lock helpers such as these I ca n't see why such barriers are guaranteed . In that case , as far as I understand , the constructor would have to be modified : Source : Understanding the Impact of Low-Lock Techniques in Multithreaded AppsEDIT Hans Passant suggests that the creation of a thread implies a memory barrier . So how about : Now a thread is not necessarily created ... public class Example { private readonly SyncLock _padlock ; public Example ( ) { _padlock = new SyncLock ( ) ; } public void ConcurrentMethod ( ) { using ( _padlock.Lock ( ) ) { // Now own the padlock - do concurrent stuff } } } var example = new Example ( ) ; new Thread ( example.ConcurrentMethod ) .Start ( ) ; public Example ( ) { _padlock = new SyncLock ( ) ; Thread.MemoryBarrier ( ) ; } var example = new Example ( ) ; ThreadPool.QueueUserWorkItem ( s = > example.ConcurrentMethod ( ) ) ;",Thread safe usage of lock helpers ( concerning memory barriers ) "C_sharp : I 've been studying Android lately and I tried to port one of its functions to C # compact framework.What I did is create an Abstract class that I call Activity.This class looks like thisThe problem I have is with running the part of the Show ( ) commandBasically all my classes implement the above class , load an xml file and display it.When I want to transition to a new class/form ( for example going from ACMain to ACLogIn ) I use this codeWhich is supposed to load the next form , show it , and unload the current formI have tried these solutions ( in the Show ( ) method ) and here is the problem with each oneusing myForm.ShowDialog ( ) This works , but blocks execution , which means that the old form does not close , and the more I move between the forms the more the process stack increasesusing myForm.Show ( ) This works , closes the old form after the old one is shown , but immediately after that closes the program and terminates itusing Application.Run ( myForm ) This works only on the first form loaded , when I move to the next form , it shows it then throws an exception saying `` Value does not fall within the expected range '' Can someone help me fix this or find an alternative ? internal abstract class Activity { protected Form myForm ; private static Activity myCurrentActivity = null ; private static Activity myNextActivity = null ; internal static void LoadNext ( Activity nextActivity ) { myNextActivity = nextActivity ; if ( myNextActivity ! = null ) { myNextActivity.Show ( ) ; if ( myCurrentActivity ! = null ) { myCurrentActivity.Close ( ) ; myCurrentActivity = null ; } myCurrentActivity = myNextActivity ; myNextActivity = null ; } } internal void Show ( ) { //PROBLEM IS HERE Application.Run ( myForm ) ; //myForm.Show ( ) ; //myForm.ShowDialog ( ) ; // } internal void Close ( ) { myForm.Close ( ) ; } internal void GenerateForm ( ) { ///Code that uses the Layout class to create a form , and then stores it in myForm //then attaches click handlers on all the clickable controls in the form //it is besides the point in this problem } protected abstract void Click ( Control control ) ; //this receives all the click events from all the controls in the form //it is besides the point in this problem } Activity.LoadNext ( new ACLogIn ) ;",Trying to close a form after the next one is shown in C # cf "C_sharp : I 've implemented a Vehicle service that is responsible for servicing vehicles such as cars and trucks : I also have a vehicle service factory that is responsible for creating a vehicle service according to the type of vehicle passed in to the factory method : The main issue I have is specifically with CarService.ServiceVehicle method . It 's accepting a Vehicle when ideally it should accept a Car instead , as it knows that it will only service cars . So I decided to update this implementation to use generics instead : The issue I 'm having is how to update VehicleServiceFactory to return the generic version of the vehicle service . I 've tried the following but it results in a compilation error as it 's unable to cast CarService to the generic return type IVehicleService : Any suggestions would be appreciated . public interface IVehicleService { void ServiceVehicle ( Vehicle vehicle ) ; } public class CarService : IVehicleService { void ServiceVehicle ( Vehicle vehicle ) { if ( ! ( vehicle is Car ) ) throw new Exception ( `` This service only services cars '' ) //logic to service the car goes here } } public class VehicleServiceFactory { public IVehicleService GetVehicleService ( Vehicle vehicle ) { if ( vehicle is Car ) { return new CarService ( ) ; } if ( vehicle is Truck ) { return new TruckService ( ) ; } throw new NotSupportedException ( `` Vehicle not supported '' ) ; } } public interface IVehicleService < T > where T : Vehicle { void ServiceVehicle ( T vehicle ) ; } public class CarService : IVehicleService < Car > { void ServiceVehicle ( Car vehicle ) { //this is better as we no longer need to check if vehicle is a car //logic to service the car goes here } } public class VehicleServiceFactory { public IVehicleService < T > GetVehicleService < T > ( T vehicle ) where T : Vehicle { if ( vehicle is Car ) { return new CarService ( ) ; } if ( vehicle is Truck ) { return new TruckService ( ) ; } throw new NotSupportedException ( `` Vehicle not supported '' ) ; } }",C # Returning a generic interface from a factory "C_sharp : Im certain that Session id keeps changing if no value is stored in it.but seems that 2010 have an exception : here is the demo vidnew page ( empty project ) : strange but after postback / refresh / ctrl+f5 : i get the same number ... but it should'nt be like that ... . ( since i didnt store nothing ) what am i missing ? p.s . Session.Count =0 ... ..editive just run the same code in vs2005 and a new session id is each time ! ! ! ! protected void Page_Load ( object sender , EventArgs e ) { Response.Write ( Session.SessionID ) ; }",Empty Session object remembers the sessionID ? "C_sharp : This question is related to a currently live application that is undergoing evolutionary maintenance . Please allow me to spend a few lines explaining how it works.The application scans large datasets imported from a big text file using 182 SQL queries that , by design , are stored in the database itself , encrypted . The main disadvantage is that we are maintaining separate queries for SQL Server and MySQL due to their syntax differences.Currently the root user is allowed to view and edit the SQL text . Viewing the SQL in order to understand how the query works for some particular cases ( we are rarely asked to modify them ) is a requirement.In order to overcome the DBMS differences I am trying to convert those queries to LINQ , which is a difficult task per se due to their complexity . But my question is another.Given that I am creating an IQuery interface that runs the specific query from the EF DbContext and scan parametrization , I still want to keep a readable , and possibly formatted , string representation of the predicate to show the root user ( otherwise our functional analyst will have to expect my mail with LINQ source code ) .I have done some homework . I have read about the possibility to stringify an Expression tree , which is a great starting point . The problem is that creating an interface method Expression < Func < ? , bool > > GetWhereExpression ( ) , to be used later to build the query , is not viable because queries span across 6 main entities and some lookup tables . Let me say that clearly : my idea was to build the IQueryable like this : But this approach will never work because each query runs on different joins of the dataset ( some inner , some left join , not all 6 entities are joined in all queries ) .The best I can do is to create an interface method IQueryable < NormalizedRow > DoQuery ( DbContext dbContext , ... ) . Now , from here , does anyone know a way to stringify the IQueryable object before running it ? I could use the same object to either run query and get dataset or to display its `` source '' .Another option is to create a string Source { get ; } property in which I copy & paste the C # source code of the query , which will work definitely . But we are creative developers , are n't we ? Following is an example of SQL query ( formatting courtesy of Instant SQL Formatter ) , with original column names and placeholders to replace ( no need to redact anything ) : C # code that returns list ( believe it or not , it will do the same thing ) : I have an almost identical query joining SectionA and SectionE , for exampleWrapping it upI want , from an IQueryable < > , to produce an output text that is at least readable and contains at least , if not all , the following clausesHow can an IQueryable in LINQ to Entities be stringified ? IQuery theQueryToRun ; var query = from SectionA a in dataContext.sectionA join SectionD b in dataContext.sectionB on a.A03 equals b.A03 ... . join ... .query = query.Where ( theQueryToRun.GetWhereClause ( ... ) ) ; query = query.OrderBy ( theQueryToRun.GetOrderByClause ( ) ) ; return query.ToList ( ) ; SELECT a.a01 , a.a01a , a.a01b , a.a02 , a.a03 , a11 , a12 , a12a , a12b , a12c , a21 , a22 , a23 , a24 , a25 , a31 , a31a , a31b , a32 , a33 , a33a , a33b , a33c , a34 , a41 , a42 , a43 , a51 , a52 , a53 , a54 , a54a , a54b , a54c , b11 , b12 , b13 , b14 , b15 , z0 , a.prog , a.utente , c11 , d11 , d13 , d14 , d14a , d14b , d14c , d15 , d16 , d17 , d18 , d19 , d21 , d22 , d23 , d31 , d32 , d41 , d42 , d43 , d44 , d45 , z1FROM sezione_a a INNER JOIN sezione_d d ON a.a03 = d.a03 AND a.utente = d.utenteWHERE ( ( a.a42 IN ( ' 0 ' , ' 1 ' , `` ) AND d.d21 IN ( SELECT codice FROM sottogruppi WHERE flagpf = 1 ) ) AND ( d.d11 IS NOT NULL AND d.d11 < > `` ) AND d.d45 IN ( ' 1 ' , ' 2 ' ) AND ( ( d.d18 > = '19000101 ' AND d.d18 < = a.a21 ) AND ( d.d43 > = '19000101 ' AND d.d43 < = a.a21 ) AND d.d43 > = d.d18 ) AND ( Date_add ( Str_to_date ( d.d43 , ' % Y % m % d ' ) , INTERVAL 10 year ) > Str_to_date ( a.a21 , ' % Y % m % d ' ) AND Date_add ( Str_to_date ( d.d43 , ' % Y % m % d ' ) , INTERVAL 10 year ) < Now ( ) ) ) AND ( ( a.a21 BETWEEN ' @ @ datamin ' AND ' @ @ datamax ' ) AND a.utente = @ @ user AND a.a52 NOT IN @ @ a52 ) ORDER BY a.a11 ASC , d.d11 ASC public IList < QueryRow > Run ( Models.auitool2014Entities dataContext , int aUserId , DateTime ? dataInizioControllo , DateTime ? dataFineControllo , string [ ] a52Exclude , bool codifiche2014 , out long totalCount ) { string sysdate10String = DateTime.Now.AddYears ( -10 ) .ToString ( `` yyyyMMdd '' , CultureInfo.InvariantCulture ) ; var inner = codifiche2014 ? from Sottogruppo sg in dataContext.sottogruppi where sg.flagpf select sg.codice : from Sottogruppo2015 sg in dataContext.sottogruppi2015 where sg.flagpf select sg.codice ; var q = dataContext.sezione_a.Join ( dataContext.sezione_d , a = > new { A03 = a.A03 , User = a.utente } , d = > new { A03 = d.A03 , User = d.utente } , ( a , d ) = > new SezioneJoin { A = a , D = d } ) .Where ( x = > x.A.utente == aUserId & & //Flusso utente new string [ ] { `` 0 '' , `` 1 '' , String.Empty } .Contains ( x.A.A42 ) & & // A42 IN ( 0,1 , '' ) inner.Contains ( x.D.D21 ) & & //D.D21 IN ( SELECT CODICE FROM SOTTOGRUPPPI.A..A . WHERE FLAGPF = 1 ) ( x.D.D11 ! = null & & x.D.D11 ! = String.Empty ) & & //D11 IS NOT NULL AND D11 < > `` new string [ ] { `` 1 '' , `` 2 '' } .Contains ( x.D.D45 ) & & //D45 IN ( ' 1 ' , ' 2 ' ) ( ( x.D.D18.CompareTo ( `` 19000101 '' ) > = 0 & & x.D.D18.CompareTo ( x.A.A21 ) < = 0 ) & & //D18 > = '1900101 ' AND D18 < = A21 ( x.D.D43.CompareTo ( `` 19000101 '' ) > = 0 & & x.D.D43.CompareTo ( x.D.D18 ) > = 0 ) // D43 > = '19000101 ' AND D43 > = D18 ) & & x.D.D43.CompareTo ( sysdate10String ) < 0 // D43 < = ( SYSDATE ( ) - 10 YEARS ) ) ; if ( dataInizioControllo ! = null ) { string dataInzio = dataInizioControllo.Value.ToString ( `` yyyyMMdd '' ) ; q = q.Where ( x = > x.A.A21.CompareTo ( dataInzio ) > = 0 ) ; } if ( dataFineControllo ! = null ) { string dataFine = dataFineControllo.Value.ToString ( `` yyyyMMdd '' ) ; q = q.Where ( x = > x.A.A21.CompareTo ( dataFine ) < = 0 ) ; } if ( a52Exclude ! = null ) q = q.Where ( x = > ! a52Exclude.Contains ( x.A.A52 ) ) ; q = q .OrderBy ( x = > x.A.A11 ) .OrderBy ( x = > x.D.D11 ) ; totalCount = q.Count ( ) ; return q.Take ( Parameters.ROW_LIMIT ) .Select ( j = > new QueryRow { A01 = j.A.A01 , A01a = j.A.A01a , A01b = j.A.A01b , A02 = j.A.A02 , A03 = j.A.A03 , A11 = j.A.A11 , A12 = j.A.A12 , A12a = j.A.A12a , A12b = j.A.A12b , A12c = j.A.A12c , ... ... . redacted for brevity D43 = j.D.D43 , D44 = j.D.D44 , D45 = j.D.D45 , Z1 = j.D.Z1 } ) .ToList ( ) ; } ( x ) = > new string [ ] { `` 0 '' , `` 1 '' , String.Empty } .Contains ( x.A.A42 ) & & inner.Contains ( x.D.D21 ) & & ( x.D.D11 ! = null & & x.D.D11 ! = String.Empty ) & & new string [ ] { `` 1 '' , `` 2 '' } .Contains ( x.D.D45 ) & & ( ( x.D.D18.CompareTo ( `` 19000101 '' ) > = 0 & & x.D.D18.CompareTo ( x.A.A21 ) < = 0 ) & & //D18 > = '1900101 ' AND D18 < = A21 ( x.D.D43.CompareTo ( `` 19000101 '' ) > = 0 & & x.D.D43.CompareTo ( x.D.D18 ) > = 0 ) // D43 > = '19000101 ' ) & & x.D.D43.CompareTo ( `` 20050623 '' ) < 0",Getting `` source '' of LINQ query and serialize to string "C_sharp : Edit : This will be fixed in a new version of pythonnet ( when this pull request is merged ) .I have a problem with Python.NET inheritance . I have a DLL which consists of the following code : I would expect a call to the Transmit method of an instance of InheritedClass to write to the console and return true and the Transmit method of BaseClass to throw a NotImplementedException.When running the following python code : I am using pythonnet version 2.3.0 and .NET Framework 4.6.1 . Thanks for your help ! Edit : This is not answered by this question . There , it is said that The new modifier instructs the compiler to use your child class implementation instead of the parent class implementation . Any code that is not referencing your class but the parent class will use the parent class implementation.which is clearly not what happens here.Edit 2 : This seems to be a problem with the pythonnet library . The issue is now on github . using System ; namespace InheritanceTest { public class BaseClass { public bool Transmit ( ) { throw new NotImplementedException ( ) ; } } public class InheritedClass : BaseClass { public new bool Transmit ( ) { Console.WriteLine ( `` Success ! `` ) ; return true ; } } } # # setupimport clrimport osclr.AddReference ( os.getcwd ( ) + '\\InheritanceTest.dll ' ) import InheritanceTest # # method testbase_class = InheritanceTest.BaseClass ( ) base_class.Transmit ( ) # throws a NotImplementedException as expectedinherited_class = InheritanceTest.InheritedClass ( ) inherited_class.Transmit ( ) # still throws a NotImplementedException , although it should call InheritedClass.Transmit",Why does Python.NET use the base method instead of the method from a derived class ? "C_sharp : I am trying to refactor a piece of code which seems easily refactorable but is proving difficult . There are two method which seem very similar and I feel should be refactored : -The reference code for this class is here ... My first attempt was to refactor like this ... The problem with this is objects like new AHelper ( ) is not assignable to Helper < IMyObj > : - ( Can anyone see how this could be nicely refactored ? Thanks in advance Russell public class MyClass { private void AddBasicData ( Receiver receiver ) { var aHelper = new AHelper ( ) ; var bHelper = new BHelper ( ) ; var cHelper = new CHelper ( ) ; receiver.ObjA = aHelper.GetBasic ( ) ; receiver.ObjB = bHelper.GetBasic ( ) ; receiver.ObjC = cHelper.GetBasic ( ) ; } private void AddExistingData ( Receiver receiver ) { var aHelper = new AHelper ( ) ; var bHelper = new BHelper ( ) ; var cHelper = new CHelper ( ) ; receiver.ObjA = aHelper.GetExisting ( ) ; receiver.ObjB = bHelper.GetExisting ( ) ; receiver.ObjC = cHelper.GetExisting ( ) ; } } public class AHelper : Helper < A > { } public class BHelper : Helper < B > { } public class CHelper : Helper < C > { } public class Helper < T > : IHelper < T > where T : IMyObj { public T GetBasic ( ) { ... } public T GetExisting ( ) { ... } } public interface IHelper < T > { T GetBasic ( ) ; T GetExisting ( ) ; } public class A : IMyObj { } public class B : IMyObj { } public class C : IMyObj { } public interface IMyObj { } public class Receiver { public A ObjA { get ; set ; } public B ObjB { get ; set ; } public C ObjC { get ; set ; } } public class MyClass { private void AddBasicData ( Receiver receiver ) { Func < Helper < IMyObj > , IMyObj > func = x = > x.GetBasic ( ) ; AddData ( receiver , func ) ; } private void AddExistingData ( Receiver receiver ) { Func < Helper < IMyObj > , IMyObj > func = x = > x.GetExisting ( ) ; AddData ( receiver , func ) ; } private void AddData ( Receiver receiver , Func < Helper < IMyObj > , IMyObj > func ) { var aHelper = new AHelper ( ) ; var bHelper = new BHelper ( ) ; var cHelper = new CHelper ( ) ; receiver.ObjA = func ( aHelper ) ; receiver.ObjB = func ( bHelper ) ; receiver.ObjC = func ( cHelper ) ; } }",C # Generics Refactoring "C_sharp : I am writing a C # client that connects to IBM Websphere MQ Manager using amqmdnet.dll using the following construct : In the properties Hashtable I am setting hostname , channel and queuemanager . Now , how can I have auto reconnect functionality in my client application ? We have IBM MQ multi-instance queue manager HA configuration.Basically , I have four end points to which I have to fall back in case of connection failure from my client ? _myQueueManager = new MQQueueManager ( queueManagerName , properties ) ;",How to connect to IBM MQ Manager with HA configuration ? "C_sharp : My SQL query is like below working fine in SQL I need to convert this to LINQ syntaxSQL-LINQ syntax I triedGetting error : Operator ' ! ' can not be applied to operand of type 'int'Any clue where I made mistake ? SELECT [ Key ] , IdFROM LocalizationKeys AS lkWHERE NOT EXISTS ( SELECT 1 FROM Languages AS l JOIN LocalizationValues AS lv ON l.Id = lv.LanguageId WHERE l.Title = 'en-US ' AND lv.LocalizationKeyId = lk.Id ) var result = ( from lk in localizationKey where ! ( from l in lang join lv in localizationValue on l.Id equals lv.LanguageId where l.Title == `` en-US '' & & lv.LocalizationKeyId == lk.Id select 1 ) .FirstOrDefault ( ) select lk ) .ToList ( ) ;",SQL Query to LINQ syntax using not exist and join "C_sharp : This may sound stupid but ... When I create big SQL commands I want to keep my code readable and I do this : See the concatenations ? Now , to save performance I now do this : It keeps the code readable but saves concatenations . Now does it really save any performance or the compiler is smart enough to `` pre-concatenate '' the first string ? cmd.CommandText = `` SELECT top 10 UserID , UserName `` + `` FROM Users `` + `` INNER JOIN SomeOtherTable ON xxxxx `` + `` WHERE UserID IN ( blablabla ) '' ; cmd.CommandText = @ '' SELECT top 10 UserID , UserName FROM Users INNER JOIN SomeOtherTable ON xxxxx WHERE UserID IN ( blablabla ) '' ;",Constructing big strings ( e.g . for SQL commands ) how smart is the C # compiler ? "C_sharp : I have a button on a form in the click of which I call FooAsync and block the UI thread on its completion.Below is the code and my questions.Why is the synchronization context returning null in the anonymous method that I pass to Task.Run in FooAsync even when I try to set button1 's Text property ? And the synchronization context is null if I do n't do anything to the UI from within the anonymous method , which is the behavior I expected from my present understanding of a synchronization context.Why is there this dead-lock ? It looks like the anonymous method passed to Task.Run , even though clearly running on a thread pool thread and even when not touching the UI , i.e . when I comment out the line that sets button1 's Text property , is trying to post something to the Windows message pump . Is that correct ? And if it is , why so ? At any rate , what is happening ? What is causing the dead lock . I understand that the UI thread is blocked , but why is this other worker thread trying to wait on the UI thread to be free ? using System ; using System.Diagnostics ; using System.Threading ; using System.Threading.Tasks ; using System.Windows.Forms ; namespace SynContextIfIDontTouchUIInWorkerThread { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } # pragma warning disable 1998 private async void button1_Click ( object sender , EventArgs e ) { // Nicely prints out the WindowsForms.SynchronizationContext // because we *are* indeed on the UI thread this.Text = SynchronizationContext.Current.GetType ( ) .Name ; Thread.CurrentThread.Name = `` UI Thread '' ; Debug.Print ( Thread.CurrentThread.Name ) ; var t = FooAsync ( ) ; // CompletedSynchronously is false , // so the other work was indeed run on a worker thread button1.Text = ( t as IAsyncResult ) .CompletedSynchronously ? `` Sync '' : `` Async '' ; // block the UI thread // Code freezes here var s = t.Result ; button1.Text = s ; } # pragma warning restore 1998 public async Task < string > FooAsync ( ) { return await Task.Run ( ( ) = > { // Whether or not I touch the UI in this worker // thread , the current sync context returns null . // Why is that ? // However , it looks like this thread is posting // something to the UI thread and since the UI // thread is also waiting for this guy to complete // it results in a dead lock . Why is that when // I am not even touching the UI here . Why // is this guy assuming that I have to post // something to message queue to run on the UI thread ? // Could it be that this guy is actually running on // the UI thread ? var ctx = SynchronizationContext.Current ; Debugger.Break ( ) ; // Current thread name evaluates to null // This clearly means it is a thread pool thread // Then why is the synchronization context null // when I uncomment out the line that changes the text // of button1 ? Debug.Print ( Thread.CurrentThread.Name ) ; if ( ctx ! = null ) { // Post to Windows message queue using the UI thread 's sync ctx // button1.Text = ctx.GetType ( ) .Name ; Debugger.Break ( ) ; } return `` Hello '' ; } ) ; } } }",Why is the synchronization context null even when I try to change UI from a worker and why does the worker wait on the UI thread even when I do n't ? "C_sharp : I have a very heavy LINQ-to-SQL query , which does a number of joins onto different tables to return an anonymous type . The problem is , if the amount of rows returned is fairly large ( > 200 ) , then the query becomes awfully slow and ends up timing out . I know I can increase the data context timeout setting , but that 's a last resort.I 'm just wondering if my query would work better if I split it up , and do my comparisons as LINQ-to-Objects queries so I can possibly even use PLINQ to maximise the the processing power . But I 'm that 's a foreign concept to me , and I ca n't get my head around on how I would split it up . Can anyone offer any advice ? I 'm not asking for the code to be written for me , just some general guidance on how I could improve this would be great.Note I 've ensured the database has all the correct keys that I 'm joining on , and I 've ensured these keys are up to date.The query is below : Here 's the generated SQL as requested : var cons = ( from c in dc.Consignments join p in dc.PODs on c.IntConNo equals p.Consignment into pg join d in dc.Depots on c.DeliveryDepot equals d.Letter join sl in dc.Accounts on c.Customer equals sl.LegacyID join ss in dc.Accounts on sl.InvoiceAccount equals ss.LegacyID join su in dc.Accounts on c.Subcontractor equals su.Name into sug join sub in dc.Accountsubbies on ss.ID equals sub.AccountID into subg where ( sug.FirstOrDefault ( ) == null || sug.FirstOrDefault ( ) .Customer == false ) select new { ID = c.ID , IntConNo = c.IntConNo , LegacyID = c.LegacyID , PODs = pg.DefaultIfEmpty ( ) , TripNumber = c.TripNumber , DropSequence = c.DropSequence , TripDate = c.TripDate , Depot = d.Name , CustomerName = c.Customer , CustomerReference = c.CustomerReference , DeliveryName = c.DeliveryName , DeliveryTown = c.DeliveryTown , DeliveryPostcode = c.DeliveryPostcode , VehicleText = c.VehicleReg + c.Subcontractor , SubbieID = sug.DefaultIfEmpty ( ) .FirstOrDefault ( ) .ID.ToString ( ) , SubbieList = subg.DefaultIfEmpty ( ) , ScanType = ss.PODScanning == null ? 0 : ss.PODScanning } ) ; { SELECT [ t0 ] . [ ID ] , [ t0 ] . [ IntConNo ] , [ t0 ] . [ LegacyID ] , [ t6 ] . [ test ] , [ t6 ] . [ ID ] AS [ ID2 ] , [ t6 ] . [ Consignment ] , [ t6 ] . [ Status ] , [ t6 ] . [ NTConsignment ] , [ t6 ] . [ CustomerRef ] , [ t6 ] . [ Timestamp ] , [ t6 ] . [ SignedBy ] , [ t6 ] . [ Clause ] , [ t6 ] . [ BarcodeNumber ] , [ t6 ] . [ MainRef ] , [ t6 ] . [ Notes ] , [ t6 ] . [ ConsignmentRef ] , [ t6 ] . [ PODedBy ] , ( SELECT COUNT ( * ) FROM ( SELECT NULL AS [ EMPTY ] ) AS [ t10 ] LEFT OUTER JOIN ( SELECT NULL AS [ EMPTY ] FROM [ dbo ] . [ PODs ] AS [ t11 ] WHERE [ t0 ] . [ IntConNo ] = [ t11 ] . [ Consignment ] ) AS [ t12 ] ON 1=1 ) AS [ value ] , [ t0 ] . [ TripNumber ] , [ t0 ] . [ DropSequence ] , [ t0 ] . [ TripDate ] , [ t1 ] . [ Name ] AS [ Depot ] , [ t0 ] . [ Customer ] AS [ CustomerName ] , [ t0 ] . [ CustomerReference ] , [ t0 ] . [ DeliveryName ] , [ t0 ] . [ DeliveryTown ] , [ t0 ] . [ DeliveryPostcode ] , [ t0 ] . [ VehicleReg ] + [ t0 ] . [ Subcontractor ] AS [ VehicleText ] , CONVERT ( NVarChar , ( SELECT [ t16 ] . [ ID ] FROM ( SELECT TOP ( 1 ) [ t15 ] . [ ID ] FROM ( SELECT NULL AS [ EMPTY ] ) AS [ t13 ] LEFT OUTER JOIN ( SELECT [ t14 ] . [ ID ] FROM [ dbo ] . [ Account ] AS [ t14 ] WHERE [ t0 ] . [ Subcontractor ] = [ t14 ] . [ Name ] ) AS [ t15 ] ON 1=1 ORDER BY [ t15 ] . [ ID ] ) AS [ t16 ] ) ) AS [ SubbieID ] , ( CASE WHEN [ t3 ] . [ PODScanning ] IS NULL THEN @ p0 ELSE [ t3 ] . [ PODScanning ] END ) AS [ ScanType ] , [ t3 ] . [ ID ] AS [ ID3 ] FROM [ dbo ] . [ Consignments ] AS [ t0 ] INNER JOIN [ dbo ] . [ Depots ] AS [ t1 ] ON [ t0 ] . [ DeliveryDepot ] = [ t1 ] . [ Letter ] INNER JOIN [ dbo ] . [ Account ] AS [ t2 ] ON [ t0 ] . [ Customer ] = [ t2 ] . [ LegacyID ] INNER JOIN [ dbo ] . [ Account ] AS [ t3 ] ON [ t2 ] . [ InvoiceAccount ] = [ t3 ] . [ LegacyID ] LEFT OUTER JOIN ( ( SELECT NULL AS [ EMPTY ] ) AS [ t4 ] LEFT OUTER JOIN ( SELECT 1 AS [ test ] , [ t5 ] . [ ID ] , [ t5 ] . [ Consignment ] , [ t5 ] . [ Status ] , [ t5 ] . [ NTConsignment ] , [ t5 ] . [ CustomerRef ] , [ t5 ] . [ Timestamp ] , [ t5 ] . [ SignedBy ] , [ t5 ] . [ Clause ] , [ t5 ] . [ BarcodeNumber ] , [ t5 ] . [ MainRef ] , [ t5 ] . [ Notes ] , [ t5 ] . [ ConsignmentRef ] , [ t5 ] . [ PODedBy ] FROM [ dbo ] . [ PODs ] AS [ t5 ] ) AS [ t6 ] ON 1=1 ) ON [ t0 ] . [ IntConNo ] = [ t6 ] . [ Consignment ] WHERE ( ( NOT ( EXISTS ( SELECT TOP ( 1 ) NULL AS [ EMPTY ] FROM [ dbo ] . [ Account ] AS [ t7 ] WHERE [ t0 ] . [ Subcontractor ] = [ t7 ] . [ Name ] ORDER BY [ t7 ] . [ ID ] ) ) ) OR ( NOT ( ( ( SELECT [ t9 ] . [ Customer ] FROM ( SELECT TOP ( 1 ) [ t8 ] . [ Customer ] FROM [ dbo ] . [ Account ] AS [ t8 ] WHERE [ t0 ] . [ Subcontractor ] = [ t8 ] . [ Name ] ORDER BY [ t8 ] . [ ID ] ) AS [ t9 ] ) ) = 1 ) ) ) AND ( [ t2 ] . [ Customer ] = 1 ) AND ( [ t3 ] . [ Customer ] = 1 ) ORDER BY [ t0 ] . [ ID ] , [ t1 ] . [ ID ] , [ t2 ] . [ ID ] , [ t3 ] . [ ID ] , [ t6 ] . [ ID ] }",Optimising LINQ-to-SQL queries C_sharp : I know it could be done in JavaScriptBut is there any possible solution to print `` Hurraa '' on the condition given below in C # without multi-threading ? if ( a==1 & & a==2 & & a==3 ) { Console.WriteLine ( `` Hurraa '' ) ; },Can ( a==1 & & a==2 & & a==3 ) evaluate to true in C # without multi-threading ? "C_sharp : Given the following C # code : ... when the short date ( under Windows 7 , Control Panel - > Region and Language - > Additonal Settings - > Date ) is set to the USA standard of `` M/d/yyyy , '' I get this : However , when I change the short date to `` ddd dd MMM yyyy , '' I get this : I was under the impression that Console.WriteLine and string.Format always string formatted DateTime values identically . What is the explanation for this discrepancy ? EDIT : Looks like this happens only in standard unit test output ( Visual Studio ) , which is where I originally saw the problem . When the code executes in a console app , the output is 06 17 14 ... 06 17 14 . var dt = DateTime.Now ; Console.WriteLine ( `` { 0 : MM/dd/yy } ... { 1 } '' , dt , string.Format ( `` { 0 : MM/dd/yy } '' , dt ) ) ; 06/17/14 ... 06/17/14 06/17/14 ... 06 17 14",Interpreting dates : Console.Writeline vs. string.Format "C_sharp : If I have theses general sql valid dates in c # strings : ( each date can be in different order inside ) e.g . : I want to convert a string date to DateTime ( c # ) . ( i want the ability to convert every format from above list ) while parse exact requires me 3 ! combinations , is there any better solution ? 01 feb 2010feb 01 20102010 01 feb ... ...",Convert general SQL time format in c # ( all variations ) ? "C_sharp : So I came across some code of mine from an old VSTO project , and noted this little bit : What does specifying [ , ] on a datatype mean ? Looking at the code it appears to function as a matrix , but honestly I thought c # matrices were handled with notation like object [ ] [ ] . Excel.Worksheet sheet = Globals.ThisAddIn.Application.Worksheets [ `` Unique Hits Per URL '' ] ; Dictionary < int , string > ids = new Dictionary < int , string > ( ) ; object [ , ] cellRange = ( object [ , ] ) sheet.get_Range ( `` E : E '' ) .Cells.Value ; for ( int i = 1 ; i < cellRange.GetUpperBound ( 0 ) ; i++ ) if ( cellRange [ i , 1 ] ! = null ) ids.Add ( i , cellRange [ i , 1 ] .ToString ( ) ) ;","What does object [ , ] mean in c # ?" "C_sharp : I 'd like to use a custom helper to simplify argument validation , something like this.However , the static code analysis of course does n't know that I do validate the input in public methods when using this helper , so it gives me CA1062 errors about public method arguments not being validated.The particular issue is this one.Is there a way to teach the code analyzer that this helper handles argument null validation ? What is the proper solution for this issue ? public static void ThrowIfNull ( this object value , string parameterName ) { if ( value == null ) { throw new ArgumentNullException ( parameterName ) ; } }",Using a custom argument validation helper breaks code analysis "C_sharp : I want to force the usage of an attribute , if another attribute is used.If a special 3rd party attribute is attached to a property , this attribute also needs to be given to a property.Is there any possibility of doing this ? For example : should bring no compile error , should bring a compile error or warning.The attribute itself is definded like the example from http : //msdn.microsoft.com/en-US/library/z919e8tw ( v=vs.80 ) .aspx itself . But how to force the usage of the attribute if another attribute is used ? [ Some3rdPartyAttribute ( `` ... '' ) ] [ RequiredAttribute ( `` ... ) ] public bool Example { get ; set ; } [ Some3rdPartyAttribute ( `` ... '' ) ] public bool Example { get ; set ; }","Force the usage of an attribute on properties , if they already have another attribute" "C_sharp : My recent project requires me to read csv file.People direct me to filehelpers , since `` you should n't reinvent the whell '' .However , the documentation really sucks , I ca n't seem to find a way to deal with optional quotation marks.Here is my csv : I am not the one who generated above csv , it 's from bank.As you can see , their csv file sucks and have some serious issue.Some strings are enclosed by quotation marks , some are not.Furthermore , the currency values are encoded as string.I made a class for it : I thought filehelpers is clever enough to see the quotation marks by itself , but the result is total disaster . Please help me . : - ( 2734000585 , IDR,04/04/2016,04/04/2016,0000000,1010 , SETOR TUNAI , '' 783275305006511 VENDY '' , , '' 820,000.00 '' , '' 5,820,000.00 '' using System ; using FileHelpers ; [ DelimitedRecord ( `` , '' ) ] public class ImporBii { public long RekNum ; public string Currency ; [ FieldConverter ( ConverterKind.Date , `` dd/MM/yyyy '' ) ] public DateTime TransDate ; [ FieldConverter ( ConverterKind.Date , `` dd/MM/yyyy '' ) ] public DateTime RecordDate ; public string Unused1 ; public int TransCode ; public string TransCodeStr ; public string Keterangan ; [ FieldConverter ( ConverterKind.Decimal , `` # , # # 0.00 '' ) ] public decimal Debet ; [ FieldConverter ( ConverterKind.Decimal , `` # , # # 0.00 '' ) ] public decimal Kredit ; [ FieldConverter ( ConverterKind.Decimal , `` # , # # 0.00 '' ) ] public decimal Saldo ; }",Optional quotation marks in filehelpers "C_sharp : I am adding Background Tasks to a Blocking Collection ( added in the Background ) .I am waiting with Task.WhenAll on a Enumerable returned by GetConsumingEnumerable.My question is : Is the overload of Task.WhenAll which receives an IEnumerable `` prepared '' to potentially receive an endless amount of tasks ? I am simply not sure if i can do it this way or if it was meant to be used this way ? private async Task RunAsync ( TimeSpan delay , CancellationToken cancellationToken ) { using ( BlockingCollection < Task > jobcollection = new BlockingCollection < Task > ( ) ) { Task addingTask = Task.Run ( async ( ) = > { while ( true ) { DateTime utcNow = DateTime.UtcNow ; var jobs = Repository.GetAllJobs ( ) ; foreach ( var job in GetRootJobsDue ( jobs , utcNow ) ) { jobcollection.Add ( Task.Run ( ( ) = > RunJob ( job , jobs , cancellationToken , utcNow ) , cancellationToken ) , cancellationToken ) ; } await Task.Delay ( delay , cancellationToken ) ; } } , cancellationToken ) ; await Task.WhenAll ( jobcollection.GetConsumingEnumerable ( cancellationToken ) ) ; } }",Usage of Task.WhenAll with infinite Tasks produced by BlockingCollection "C_sharp : Google Material Icons has different variations in Icon font Families : Rounded , Sharp , TwoTone , etc.The UX team is taking some icons , and customizing them bit , little thicker or minor touch up.Is it possible to replace/edit the icons , and keep the same content code without any issues ? Example : We are using Visual Studio .Net Core application , and placed Material Icons in our library.Additionally , is it possible to Create New Content Code ? Say , I create Company logo . Can I assign it a Content Code ? Referring to Material icons with both content code and class nameRight now , currently replacing the rounded icon base . Another reason to conduct this besides saving coding time/existing code base ; if client ever want to swap to Google Material : Filled , Sharp , Two Tone , Outlined , it can be done in easy manner.References : How to set the CSS content property with a Google Material Icon ? Material Design Icons - CodepointsPossible Solution LinksHow to Use Material IconsCustom SVG Icons Angular Material .carouselrightarrow { font-family : Material Icons ; font-size : 36px ; position : absolute ; top : 16px ; content : `` \e409 '' ; } < button id= '' add-to-favorites '' class= '' mdc-icon-button '' > < i class= '' material-icons mdc-icon-button__icon mdc-icon-button__icon -- on '' > favorite < /i > < i class= '' material-icons mdc-icon-button__icon '' > favorite_border < /i > < /button >","Replace Google Material Icons with Own Icons , Keep Same Content Code or Create New One" "C_sharp : The title for this post was quite hard to think of , so if you can think of a more descriptive title please tell me . Anyway , my problem is quite specific and requires some simple maths knowledge . I am writing a C # WinForms application which is a bit like the old 'xeyes ' Linux application . It basically is a set of eyes which follow around your mouse cursor . This may sound easy at first , however can get rather complicated if you 're a perfectionist like me : P. This is my code so far ( only the paint method , that is called on an interval of 16 ) .Now this does work at a basic level , however sometimes this can happen if the user puts the cursor at 0,0.Now my question is how to fix this ? What would the IF statement be to check where the mouse pointer is , and then reduce the pupil X depending on that ? Thanks.Edit : This is where I get the mouse positions ( my and mx ) : The timer is started in the eyes_Load event and the interval is 16.Edit 2 : Final solution : http : //pastebin.com/fT5HfiQR int lx = 35 ; int ly = 50 ; int rx ; int ry ; int wx = Location.X + Width / 2 ; int wy = Location.Y + Height / 2 ; Rectangle bounds = Screen.FromControl ( this ) .Bounds ; // Calculate Xfloat tempX = ( mx - wx ) / ( float ) ( bounds.Width / 2 ) ; // Calculate Yfloat tempY = ( my - wy ) / ( float ) ( bounds.Height / 2 ) ; // Draw eyese.Graphics.FillEllipse ( Brushes.LightGray , 10 , 10 , 70 , 100 ) ; e.Graphics.FillEllipse ( Brushes.LightGray , 90 , 10 , 70 , 100 ) ; // Draw pupils ( this only draws the left one ) e.Graphics.FillEllipse ( Brushes.Black , lx += ( int ) ( 25 * tempX ) , ly += ( int ) ( 40 * tempY ) , 20 , 20 ) ; private void timer_Tick ( object sender , EventArgs e ) { mx = Cursor.Position.X ; my = Cursor.Position.Y ; Invalidate ( ) ; }",How to bound a circle inside an ellipse ? "C_sharp : In VS 2015 , we used to be able to specify a local path in global.json like so : It would then add all the projects from that path to the current solution , allowing us to easily reference them from existing projects.Now that VS 2017 has changed its ' model to using csproj , and getting rid of project.json and global.json in the process , does anybody know of a way to this ? The best I 've gotten is to manually include the other projects , one by one , into the solution . Then , in all the existing projects that need to reference it , I would have to edit their csproj to include them . This is really cumbersome compared to the previous way of simply including a filepath in one location.Thanks for any help with this . { “ projects ” : [ “ src ” , “ test ” , “ C : \\path\\to\\other\\projects ” ] }",VS 2017 reference local projects by filepath ( like using global.json in VS 2015 ) "C_sharp : I was watching a Silverlight tutorial video , and I came across an unfamiliar expressionin the example code.what is = > ? what is its name ? could you please provide me a link ? I could n't search for it because they are special characters.code : var ctx = new EventManagerDomainContext ( ) ; ctx.Events.Add ( newEvent ) ; ctx.SubmitChanges ( ( op ) = > { if ( ! op.HasError ) { NavigateToEditEvent ( newEvent.EventID ) ; } } , null ) ;",What is '= > ' ? ( C # Grammar Question ) "C_sharp : I 'd like to be able to implement a dictionary with a key of Type and a value of Func < T > where T is an object of the same type as the key : So , basically , the dictionary would be populated with types that would reference a Func < T > which would return that value : How can I go about implementing and enforcing this ? Dictionary < Type , Func < T > > TypeDictionary = new Dictionary < Type , Func < T > > ( ) /*Func < T > returns an object of the same type as the Key*/TypeDictionary.Add ( typeof ( int ) , ( ) = > 5 ) ; TypeDictionary.Add ( typeof ( string ) , ( ) = > `` Foo '' ) ; int Bar = TypeDictionary [ typeof ( int ) ] ( ) ; string Baz = TypeDictionary [ typeof ( string ) ] ( ) ;",Is it possible to store a Func < T > within a dictionary ? "C_sharp : Code updatedFor fixing the bug of a filtered Interminable , the following code is updated and merged into original : bindingAttr is declared a constant . Summary I 'm trying to implement an infinite enumerable , but encountered something seem to be illogical , and temporarily run out of idea . I need some direction to complete the code , becoming a semantic , logical , and reasonable design . The whole storyI 've asked the question a few hours ago : Is an infinite enumerable still `` enumerable '' ? This might not be a good pattern of implementation . What I 'm trying to do , is implement an enumerable to present infinity , in a logical and semantic way ( I thought .. ) . I would put the code at the last of this post . The big problem is , it 's just for presenting of infinite enumerable , but the enumeration on it in fact does n't make any sense , since there are no real elements of it . So , besides provide dummy elements for the enumeration , there are four options I can imagine , and three lead to the StackOverflowException . Throw an InvalidOperationException once it 's going to be enumerated . and 3. are technically equivalent , let the stack overflowing occurs when it 's really overflowed . ( described in 2 ) Do n't wait for it happens , throw StackOverflowException directly . The tricky things are : If option 1 is applied , that is , enumerate on this enumerable , becomes an invalid operation . Is n't it weird to say that this lamp is n't used to illuminate ( though it 's true in my case ) . If option 2 or option 3 is applied , that is , we planned the stack overflowing . Is it really as the title , just when stackoverflow is fair and sensible ? Perfectly logical and reasonable ? The last choice is option 4 . However , the stack in fact does not really overflow , since we prevented it by throwing a fake StackOverflowException . This reminds me that when Tom Cruise plays John Anderton said that : `` But it did n't fall . You caught it . The fact that you prevented it from happening doesnt change the fact that it was going to happen . '' Some good ways to avoid the illogical problems ? The code is compile-able and testable , note that one of OPTION_1 to OPTION_4 shoule be defined before compile . Simple testClasses public static bool IsInfinity ( this IEnumerable x ) { var it= x as Infinity ? ? ( ( Func < object > ) ( ( ) = > { var info=x.GetType ( ) .GetField ( `` source '' , bindingAttr ) ; return null ! =info ? info.GetValue ( x ) : x ; } ) ) ( ) ; return it is Infinity ; } public IEnumerator < T > GetEnumerator ( ) { for ( var message= '' Attempted to enumerate an infinite enumerable '' ; ; ) throw new InvalidOperationException ( message ) ; } public IEnumerator < T > GetEnumerator ( ) { foreach ( var x in this ) yield return x ; } public IEnumerator < T > GetEnumerator ( ) { return this.GetEnumerator ( ) ; } public IEnumerator < T > GetEnumerator ( ) { throw new StackOverflowException ( `` ... `` ) ; } var objects=new object [ ] { } ; Debug.Print ( `` { 0 } '' , objects.IsInfinity ( ) ) ; var infObjects=objects.AsInterminable ( ) ; Debug.Print ( `` { 0 } '' , infObjects.IsInfinity ( ) ) ; using System.Collections.Generic ; using System.Collections ; using System ; public static partial class Interminable /* extensions */ { public static Interminable < T > AsInterminable < T > ( this IEnumerable < T > x ) { return Infinity.OfType < T > ( ) ; } public static Infinity AsInterminable ( this IEnumerable x ) { return Infinity.OfType < object > ( ) ; } public static bool IsInfinity ( this IEnumerable x ) { var it= x as Infinity ? ? ( ( Func < object > ) ( ( ) = > { var info=x.GetType ( ) .GetField ( `` source '' , bindingAttr ) ; return null ! =info ? info.GetValue ( x ) : x ; } ) ) ( ) ; return it is Infinity ; } const BindingFlags bindingAttr= BindingFlags.Instance|BindingFlags.NonPublic ; } public abstract partial class Interminable < T > : Infinity , IEnumerable < T > { IEnumerator IEnumerable.GetEnumerator ( ) { return this.GetEnumerator ( ) ; } # if OPTION_1 public IEnumerator < T > GetEnumerator ( ) { for ( var message= '' Attempted to enumerate an infinite enumerable '' ; ; ) throw new InvalidOperationException ( message ) ; } # endif # if OPTION_2 public IEnumerator < T > GetEnumerator ( ) { foreach ( var x in this ) yield return x ; } # endif # if OPTION_3 public IEnumerator < T > GetEnumerator ( ) { return this.GetEnumerator ( ) ; } # endif # if OPTION_4 public IEnumerator < T > GetEnumerator ( ) { throw new StackOverflowException ( `` ... `` ) ; } # endif public Infinity LongCount < U > ( Func < U , bool > predicate=default ( Func < U , bool > ) ) { return this ; } public Infinity Count < U > ( Func < U , bool > predicate=default ( Func < U , bool > ) ) { return this ; } public Infinity LongCount ( Func < T , bool > predicate=default ( Func < T , bool > ) ) { return this ; } public Infinity Count ( Func < T , bool > predicate=default ( Func < T , bool > ) ) { return this ; } } public abstract partial class Infinity : IFormatProvider , ICustomFormatter { partial class Instance < T > : Interminable < T > { public static readonly Interminable < T > instance=new Instance < T > ( ) ; } object IFormatProvider.GetFormat ( Type formatType ) { return typeof ( ICustomFormatter ) ! =formatType ? null : this ; } String ICustomFormatter.Format ( String format , object arg , IFormatProvider formatProvider ) { return `` Infinity '' ; } public override String ToString ( ) { return String.Format ( this , `` { 0 } '' , this ) ; } public static Interminable < T > OfType < T > ( ) { return Instance < T > .instance ; } }",Just when is a stackoverflow fair and sensible ? "C_sharp : I have written a class using TDD containing a method ( method under test ) which takes a simple value object as a parameter ( range ) . Code : The method under test looks like this : Furthermore I have a unit test to verify my method under test : Question : I have read Roy Osherove 's book on unit testing ( `` The Art of Unit Testing '' ) . In there he says `` external dependencies ( filesystem , time , memory etc . ) should be replaced by stubs '' What does he mean by external dependency ? Is my value object ( range ) also an external dependency which should be faked ? Should I fake all dependencies a class have ? Can someone give me an advice public List < string > In ( IRange range ) { var result = new List < string > ( ) ; for ( int i = range.From ; i < = range.To ; i++ ) { // ... } return result ; } [ TestMethod ] public void In_SimpleNumbers_ReturnsNumbersAsList ( ) { var range = CreateRange ( 1 , 2 ) ; var expected = new List < string > ( ) { `` 1 '' , `` 2 '' } ; var result = fizzbuzz.In ( range ) ; CollectionAssert.AreEqual ( expected , result ) ; } private IRange CreateRange ( int from , int to ) { return new Fakes.StubIRange ( ) { FromGet = ( ) = > { return from ; } , ToGet = ( ) = > { return to ; } } ; }",Do I have to fake a value object in my unit test "C_sharp : I am developing an extension for existing application via COM.Current interface of the application to extend allows to create custom property windows and use them inside that application.Now , I am using .NET for that purpose and have strange problems : As you can see below , the property sheets actually get extended , but after that something strange starts to happen.Basically , if I switch to Ololo tab , then back to any of other 3 tabs ( Attributes , Drawing or Services ) , the application freezes . I also know that the freeze happens inside of some unmanaged code block.Another interesting fact here is that if I do n't write the extensionForm.Controls.Add ( new Button ( ) ) ( with or without the Suspend / Resume Layout calls ) , everything works fine . So , if the recently constructed form has no controls ( buttons or any other ) on it , it does n't freeze.Here is a Spy++ log on the Ololo window right before the freeze ( last message is the WM_CTLCOLORBTN , right after that the application became frozen ) : Combining everything together : Freezing happens only if I switch from Ololo to some other tab and then switch to the Ololo tab again.Freezing only happens if the integrated form has at least one control on it , forms without controls do n't freeze.Application is not running any managed code at the moment and is not spending any CPU time.So - any ideas / similiar problems solved / etc to help me in this case ? extensionForm = new Form ( ) ; extensionForm.SetBounds ( 0 , 0 , 100 , 100 ) ; extensionForm.Controls.Add ( new Button ( ) ) ; ExApplAPI.AddCustomPropertyWindow ( extensionForm.Handle.ToInt32 ( ) , `` Ololo '' ) ;",C # add-in for application ( via COM ) freezes when a Control is added to the form ? "C_sharp : I 'm developing an extension for visual studio . There I have an option page : The Bar property works perfectly and is persisted.The Foos Property does also work ( it even gives you a nice popup in the options page where you can enter one string per line ) , which means I can set it and also use it in my extension but it is not written to the registry/storage . When I close VS and open it again it 's always empty.Quote from MSDN : The default implementation of DialogPage supports properties that have appropriate converters or that are structures or arrays that can be expanded into properties that have appropriate converters . For a list of converters , see the System.ComponentModel namespace . The Visual Studio Extensibility Samples manages int , string , and System.Drawing.Size properties.In my understanding I 'm using valid components from the System.ComponentModel namespace.So what am I doing wrong ? Do I have to treat arrays somehow differently ? public class GeneralOptionsPage : DialogPage { [ Category ( `` General '' ) ] [ DisplayName ( `` Foos '' ) ] [ Description ( `` Bla Foo Bla '' ) ] public string [ ] Foos { get ; set ; } [ Category ( `` General '' ) ] [ DisplayName ( `` Bar '' ) ] [ Description ( `` Bar Foo Bar '' ) ] public string Bar { get ; set ; } }",DialogPage - string array not persisted "C_sharp : I 've encountered an issue with finalizable objects that does n't get collected by GC if Dispose ( ) was n't called explicitly.I know that I should call Dispose ( ) explicitly if an object implements IDisposable , but I always thought that it is safe to rely upon framework and when an object becomes unreferenced it can be collected.But after some experiments with windbg/sos/sosex I 've found that if GC.SuppressFinalize ( ) was n't called for finalizable object it does n't get collected , even if it becomes unrooted . So , if you extensively use finalizable objects ( DbConnection , FileStream , etc ) and not disposing them explicitly you can encounter too high memory consumption or even OutOfMemoryException.Here is a sample application : Even after 10 iterations you can find that memory consumption is too high ( from 700MB to 1GB ) and gets even higher with more iterations . After attaching to process with WinDBG you can find that all large objects are unrooted , but not collected.Situation changes if you call SuppressFinalize ( ) explicitly : memory consumption is stable around 300-400MB even under high pressure and WinDBG shows that there are no unrooted objects , memory is free.So the question is : Is it a bug in framework ? Is there any logical explanation ? More details : After each iteration , windbg shows that : finalization queue is emptyfreachable queue is emptygeneration 2 contains objects ( Hundred ) from previous iterationsobjects from previous iterations are unrooted public class MemoryTest { private HundredMegabyte hundred ; public void Run ( ) { Console.WriteLine ( `` ready to attach '' ) ; for ( var i = 0 ; i < 100 ; i++ ) { Console.WriteLine ( `` iteration # { 0 } '' , i + 1 ) ; hundred = new HundredMegabyte ( ) ; Console.WriteLine ( `` { 0 } object was initialized '' , hundred ) ; Console.ReadKey ( ) ; //hundred.Dispose ( ) ; hundred = null ; } } static void Main ( ) { var test = new MemoryTest ( ) ; test.Run ( ) ; } } public class HundredMegabyte : IDisposable { private readonly Megabyte [ ] megabytes = new Megabyte [ 100 ] ; public HundredMegabyte ( ) { for ( var i = 0 ; i < megabytes.Length ; i++ ) { megabytes [ i ] = new Megabyte ( ) ; } } public void Dispose ( ) { Dispose ( true ) ; GC.SuppressFinalize ( this ) ; } ~HundredMegabyte ( ) { Dispose ( false ) ; } private void Dispose ( bool disposing ) { } public override string ToString ( ) { return String.Format ( `` { 0 } MB '' , megabytes.Length ) ; } } public class Megabyte { private readonly Kilobyte [ ] kilobytes = new Kilobyte [ 1024 ] ; public Megabyte ( ) { for ( var i = 0 ; i < kilobytes.Length ; i++ ) { kilobytes [ i ] = new Kilobyte ( ) ; } } } public class Kilobyte { private byte [ ] bytes = new byte [ 1024 ] ; }",Why does n't object with finalizer get collected even if it is unrooted ? "C_sharp : I use C++ library in WPF . It 's SDK for Magnetic Stripe Reader/Writer . When I call one of it 's methods in WPF , I receive StackOverFlowException after 10 seconds . Method called from button click event.This method connects to Magnetic Stripe Reader device . First I tested this method on Windows Forms application , and everything was great . But when I started to write WPF app with this library , I receive StackOverFlowException everytime . What could be the reason of this `` feature '' ? [ DllImport ( `` MSR_API.dll '' ) ] static extern bool MSR_InitComm ( string portname , UInt32 baud ) ;",StackOverFlowException in WPF when call method from C++ library "C_sharp : I am trying to use LINQ to generate my Sitemap . Each url in the sitemap is generate with the following C # code : When I generate my sitemap , I get XML that looks like the following : My problem is , how do I remove the `` xmlns= '' '' '' from the url element ? Everything is correct except for this.Thank you for your help ! XElement locElement = new XElement ( `` loc '' , location ) ; XElement lastmodElement = new XElement ( `` lastmod '' , modifiedDate.ToString ( `` yyyy-MM-dd '' ) ) ; XElement changefreqElement = new XElement ( `` changefreq '' , changeFrequency ) ; XElement urlElement = new XElement ( `` url '' ) ; urlElement.Add ( locElement ) ; urlElement.Add ( lastmodElement ) ; urlElement.Add ( changefreqElement ) ; < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < urlset xmlns= '' http : //www.sitemaps.org/schemas/sitemap/0.9 '' > < url xmlns= '' '' > < loc > http : //www.mydomain.com/default.aspx < /loc > < lastmod > 2011-05-20 < /lastmod > < changefreq > never < /changefreq > < /url > < /urlset >",How do you remove xmlns from elements when generating XML with LINQ ? "C_sharp : In C # this is certainly possible , as this compilable example can show : But can it be done in C++ ( /CLI ) with a constructor ? See the example below : Although this class does compile with these constructors I ca n't see how to choose when I apply one are the other , that is , the call is ambiguos , as there is no keyword I know for this purpose as `` ref '' in C # . I tried it in a constructor , where the name must be the same as the class ( of course I can add a useless parameter , but I want to know if I can not do it ) .BTW , I googled and only got things like `` what 's the difference between passing by ref and by value ? '' but nothing covering overloading like this . And I guess that as workarounds I can use pointer , thanks to the `` take the address of '' ( & ) ; or have , as mentioned above , an extra useless parameter . But what I want to know is : can I have overloads like these ( by ref/by value ) ? Thanks in advance , static void Teste ( int x ) { } static void Teste ( ref int x ) { } static void Teste ( ) { int i = 0 ; Teste ( i ) ; Teste ( ref i ) ; } class Foo { Foo ( int bar ) { // initializing `` Foo '' instance ... } Foo ( int & bar ) { // initializing `` Foo '' instance ... } // ... }",Can I have a function/method passing an argument by reference and an overload passing it by value in C++ ? "C_sharp : The JSON looks like this : And the class looks like this : And when using No exception is thrown , JSON.NET just converts the string value `` 50 '' into a float value 50.0.This question is raised in the the context of input-validation . I want to get an exception , because the JSON string does not comply to the contract ( the x field should be a real float ) .And I do n't want to use property annotations in the 'Test ' class.Is there a JsonSerializerSettings which can be be used to avoid this ? { `` x '' : `` 50 '' } public class Test { public float ? x { get ; set ; } } var test = JsonConvert.DeserializeObject < Test > ( json ) ;",Avoid deserializing a JSON string token to a numeric property C_sharp : Is there an equivalent to Perl 's $ _ function ? I 'm rewriting some old perl scripts in C # and I never learned any perl . Heres an example of what i 'm trying to figure out sub copyText { while ( $ _ [ 0 ] ) { $ _ [ 1 ] - > Empty ( ) ; $ _ [ 0 ] = $ _ [ 1 ] - > IsText ( ) ; sleep ( 1 ) ; },C # equivalent of perl 's $ _ C_sharp : I 'm new to LINQ and doing some experiments with it.Sorry if it is a duplicate but I cant seem to find proper guide ( for me ) to itI want to replace this code : with something LINQ like : but it does n't even compile.what I want Is not a one line solution but would like some logic to understand how construct it with more complicated environments ( Like choosing many node in XML with some logic ) DataTable tableList < string > header = new List < string > ( ) ; table.Columns.Cast < DataColumn > ( ) .ToList ( ) .ForEach ( col = > header.Add ( col.ColumnName ) ) ; var LINQheader = from mycol in table.Columns select mycol.ColumnName ; LINQheader.tolist ( ) ;,replace List.foreach to LINQ "C_sharp : I 'm attempting to compile my new C # 7 code on a Linux build server using Mono 5 . Unfortunately , the project fails when I use the new ValueTuple syntax : MyClass.cs ( 100,38 ) : error CS1003 : Syntax error , ' ( ' expected [ /path/to/My.csproj ] I have the following package reference in my project file : and I 'm using the following commands in my quick build script : and the MSBuild log indicates a language version of 7 and shows a reference to System.ValueTuple.dll : CoreCompile : /usr/lib/mono/4.5/csc.exe /noconfig /unsafe- /checked- /nowarn:1701,1702,1705,1701,1702 /langversion:7 /nostdlib+ /errorreport : prompt /warn:4 /doc : bin/Release/net461/My.xml /define : TRACE ; RELEASE ; NET461 /highentropyva+ ... /reference : /root/.nuget/packages/system.valuetuple/4.3.0/lib/netstandard1.0/System.ValueTuple.dll ... /debug- /debug : portable /filealign:512 /nologo /optimize+ /out : obj/Release/net461/My.dll /subsystemversion:6.00 /target : library /warnaserror- /utf8output /deterministic+ My.cs `` /tmp/.NETFramework , Version=v4.6.1.AssemblyAttributes.cs '' obj/Release/net461/My.AssemblyInfo.csHas anyone successfully compiled C # using the new ValueTuple syntax on Linux using Mono 5 ? Did it just work , or did you need to adjust the environment to make it work ? My build server is running Ubuntu 16.04 and has mono-devel 5.0.1.1-0xamarin5+ubuntu1604b1 installed . < PackageReference Include= '' System.ValueTuple '' Version= '' 4.3.0 '' / > # msbuild My.sln /t : restore # msbuild My.sln /p : Configuration=Release /p : Platform= '' Any CPU ''",Compiling C # 7 code containing ValueTuple with Mono 5 "C_sharp : I can not for the life of me figure this out , using the same control template I get a blurry Adorner on one Element in my panel : Control Template : Non-Blury Text Box Code : Blurry TextBox Code : Something about the way it renders , the first ( non blury ) is within a `` ListViewItem '' Control Template , the other is a userControl.. Any ideas ? FIXEDFixed by adding UseLayoutRounding= '' True '' to parent Control ie : ContentControl ! Thank you Aybe ! < ControlTemplate x : Key= '' validationErrorTemplateBubble '' > < DockPanel > < Grid DockPanel.Dock= '' Bottom '' Margin= '' 10,0,0,0 '' > < Grid.Effect > < DropShadowEffect ShadowDepth= '' 2 '' Direction= '' 315 '' / > < /Grid.Effect > < Grid.RowDefinitions > < RowDefinition Height= '' * '' / > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' Auto '' / > < /Grid.RowDefinitions > < Border Grid.Row= '' 1 '' BorderBrush= '' Gray '' BorderThickness= '' 1 '' CornerRadius= '' 5 '' Margin= '' 0 , -1.6,0,0 '' > < Border.Background > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' # FFE7E8F1 '' Offset= '' 1 '' / > < GradientStop Color= '' White '' / > < GradientStop Color= '' # FFF3F4F6 '' Offset= '' 0.472 '' / > < /LinearGradientBrush > < /Border.Background > < Grid > < WrapPanel VerticalAlignment= '' Center '' Margin= '' 5,5,10,5 '' > < Image Source= '' /Sesam ; component/Modules/Images/wrongsmall.png '' Height= '' 15 '' Width= '' 15 '' / > < TextBlock Foreground= '' Red '' FontSize= '' 12 '' Margin= '' 5,0,0,0 '' Text= '' { Binding ElementName=ErrorAdorner , Path=AdornedElement . ( Validation.Errors ) .CurrentItem.ErrorContent } '' / > < /WrapPanel > < ContentPresenter Margin= '' 5 '' Grid.Column= '' 1 '' Grid.Row= '' 1 '' / > < /Grid > < /Border > < Path Data= '' M306.375,133.125L306.375,100.875L335.75,133.25 '' Stroke= '' Gray '' Height= '' 15 '' Fill= '' White '' StrokeThickness= '' 1 '' Stretch= '' Uniform '' Margin= '' 10,0,0,0 '' HorizontalAlignment= '' Left '' VerticalAlignment= '' Center '' / > < /Grid > < AdornedElementPlaceholder x : Name= '' ErrorAdorner '' / > < /DockPanel > < TextBox BorderThickness= '' 0 '' VerticalAlignment= '' Center '' Width= '' 150 '' Padding= '' 3 '' Margin= '' 8,0,0,0 '' Foreground= '' { StaticResource myDarkBlue } '' Text= '' { Binding RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type ListView } } , Path=DataContext.encTypeValidation , UpdateSourceTrigger=PropertyChanged , ValidatesOnDataErrors=True } '' Validation.ErrorTemplate= '' { StaticResource validationErrorTemplateBubble } '' HorizontalAlignment= '' Left '' > < TextBox.Style > < Style TargetType= '' { x : Type TextBox } '' > < Setter Property= '' Visibility '' Value= '' Collapsed '' / > < Style.Triggers > < MultiDataTrigger > < MultiDataTrigger.Conditions > < Condition Binding= '' { Binding RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type ListViewItem } } , Path=IsSelected } '' Value= '' True '' / > < Condition Binding= '' { Binding RelativeSource= { RelativeSource Mode=FindAncestor , AncestorType= { x : Type ListView } } , Path=DataContext.editClicked } '' Value= '' True '' / > < /MultiDataTrigger.Conditions > < Setter Property= '' Visibility '' Value= '' Visible '' / > < /MultiDataTrigger > < /Style.Triggers > < /Style > < /TextBox.Style > < Grid > < WrapPanel > < TextBox x : Name= '' tbox '' Text= '' { Binding encTypeValidation , Mode=OneWayToSource , UpdateSourceTrigger=PropertyChanged , ValidatesOnDataErrors=True } '' Foreground= '' { StaticResource myTextBoxColor } '' Validation.ErrorTemplate= '' { StaticResource validationErrorTemplateBubble } '' PreviewMouseDown= '' tbox_PreviewMouseDown '' Width= '' 200 '' > < TextBox.InputBindings > < MouseBinding Gesture= '' LeftClick '' Command= '' { Binding addBoxClicked } '' / > < /TextBox.InputBindings > < /TextBox > < /WrapPanel > < /Grid > < Grid Grid.Row= '' 2 '' Background= '' { StaticResource myLightGrey } '' > < Border BorderBrush= '' { StaticResource myLightGrey } '' BorderThickness= '' 0,1,1,0 '' > < ContentControl x : Name= '' AddPanel '' VerticalAlignment= '' Center '' HorizontalAlignment= '' Center '' UseLayoutRounding= '' True '' / > < /Border > < /Grid >",Blurry Adorner WPF Xaml "C_sharp : When using a 64-bit sized struct , the following code snippetProducesHowever , when just using a long , the following code producesProduces : Does anyone know what difference ldobj/stobj and ldind.i8/stind.i8 makes , if any , for this example ? ldobj/stobj seems to give a 20 % performance improvement , but I can not figure out why that is happening . Are n't these two lines doing the exact same thing ? Thanks ! edit : [ 64-bit release mode ] The bytecode looks the same when compiled in release mode . The performance measurement was done a while ago in release mode . [ StructLayout ( LayoutKind.Explicit , Pack = 1 , Size = 8 ) ] unsafe struct BUF { } ( ( BUF* ) dst ) = * ( ( BUF* ) src ) ; IL_0046 : nop IL_0047 : ldloc.s dst IL_0049 : ldloc.2 IL_004a : ldobj MyClass/BUF IL_004f : stobj MyClass/BUF * ( ( long* ) dst ) = * ( ( long* ) src ) ; IL_0046 : nopIL_0047 : ldloc.s dstIL_0049 : ldloc.2IL_004a : ldind.i8 IL_004b : stind.i8","What is the difference between ldobj and ldind. < type > , and why is ldobj faster ?" "C_sharp : This is a algorithm question , I have solution but it has performance issue.Question DescriptionThere are n variables and m requirements . Requirements are represented as ( x < = y ) , which means the x-th variable must be smaller or equal to the y-th variable . Assign nonnegative numbers smaller than 10 to each variable . Please calculate how many different assignments that match all requirements . Two assignments are different if and only if at least one variable is assigned different number in these two assignment . Module the answer by 1007.Input Format : First line of the input contains two integers n and m.Then following m lines each containing 2 space-seperated integers x and y , which means a requirement ( x < = y ) .Output Format : Output the answer in one line.Constraints:0 < n < 140 < m < 2000 < = x , y < nSample Input:6 71 30 12 40 42 53 40 2Sample Output:1000Below is my solution . it takes too long time get result when n=13 and m=199 but the acceptable time is 5 seconds.So can anyone think of a better way to optimize this further ? Thank you.My current solution : using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace ConsoleApplication81 { class Program { const int N = 10 ; static List < Condition > condition = new List < Condition > ( ) ; static void Main ( string [ ] args ) { string [ ] line1 = Console.ReadLine ( ) .Split ( new char [ ] { ' ' } , StringSplitOptions.RemoveEmptyEntries ) ; int n = int.Parse ( line1 [ 0 ] ) ; int m = int.Parse ( line1 [ 1 ] ) ; for ( int i = 0 ; i < m ; i++ ) { string [ ] line = Console.ReadLine ( ) .Split ( new char [ ] { ' ' } , StringSplitOptions.RemoveEmptyEntries ) ; condition.Add ( new Condition ( ) { X = int.Parse ( line [ 0 ] ) , Y = int.Parse ( line [ 1 ] ) } ) ; } // List < int [ ] > rlist = new List < int [ ] > ( ) ; for ( int j = 0 ; j < N ; j++ ) { int [ ] assignments = new int [ n ] ; for ( int i = 0 ; i < n ; i++ ) assignments [ i ] = -1 ; assignments [ 0 ] = j ; rlist.Add ( assignments ) ; } for ( int j = 1 ; j < n ; j++ ) { List < int [ ] > rlist2 = new List < int [ ] > ( rlist.Count*5 ) ; for ( int k = 0 ; k < rlist.Count ; k++ ) { for ( int l = 0 ; l < N ; l++ ) { rlist [ k ] [ j ] = l ; if ( CanPassCondition ( rlist [ k ] ) ) rlist2.Add ( ( int [ ] ) rlist [ k ] .Clone ( ) ) ; } } rlist = rlist2 ; } Console.Write ( rlist.Count % 1007 ) ; } private static bool CanPassCondition ( int [ ] p ) { foreach ( var c in condition ) { if ( p [ c.X ] == -1 || p [ c.Y ] == -1 ) continue ; if ( p [ c.X ] > p [ c.Y ] ) return false ; } return true ; } } class Condition { public int X ; public int Y ; public override string ToString ( ) { return string.Format ( `` x : { 0 } , y : { 1 } '' , X , Y ) ; } } }",Optimizing this C # algorithm "C_sharp : Code to create textboxes ... Code for to remove all text boxes.When I click the btnAddIncrement I get the following as expected ... But when I click reset it misses every second textbox . See below ... No idea what 's going on here but this is the same no matter how may text boxes I add . It always misses every second box . private void btnAddIncrement_Click ( object sender , EventArgs e ) { SmartTextBox dynamictextbox = new SmartTextBox ( ) ; dynamictextbox.BackColor = Color.Bisque ; dynamictextbox.Width = this.tbWidth ; dynamictextbox.Left = ( sender as Button ) .Right + this.lastLeft ; dynamictextbox.K = `` Test '' ; this.lastLeft = this.lastLeft + this.tbWidth ; dynamictextbox.Top = btnAddStart.Top ; this.Controls.Add ( dynamictextbox ) ; } foreach ( Control c in this.Controls ) { if ( c.GetType ( ) == typeof ( BnBCalculator.SmartTextBox ) ) { count++ ; //MessageBox.Show ( ( c as SmartTextBox ) .K.ToString ( ) ) ; c.Dispose ( ) ; } // else { MessageBox.Show ( `` not txtbox '' ) ; } }",Foreach loop for disposing controls skipping iterations "C_sharp : I am seeing base ( options ) in Entity Framework examples . What does base ( options ) mean , since can not locate Microsoft documentation.Example here : Documentation does define DbContextOptions , but not base options.https : //docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext public class BloggingContext : DbContext { public BloggingContext ( DbContextOptions < BloggingContext > options ) : base ( options ) { } }",Definition of Entity Framework context Base Options "C_sharp : I am trying to check if an object variable is ( int , int ) and if so I will use the casted variable so I have tried the codes below : The MyMethodWithIs method gives the error below in the editor : No suitable deconstruct instance or extension method was found for typeMy QuestionWhy one works fine but the other gives an error at all ? I think MyMethodWithIs more readable and suitable to use for my case but I ca n't use it due to giving an error . //this one gives the errorpublic void MyMethodWithIs ( object val ) { if ( val is ( int id , int name ) pair ) { ConsoleWriteLine ( $ '' { pair.id } , { pair.name } '' ) ; } } //This one workspublic void MyMethodWithAs ( object val ) { var pair = val as ( int id , int name ) ? ; if ( pair ! =null ) { ConsoleWriteLine ( $ '' { pair.id } , { pair.name } '' ) ; } }",Using ` is ` operator with value type tuples gives error "C_sharp : So here 's the code I 've been using . Its just a simple program to test to see if 3 randomly generated numbers are in ascending or descending order . For some reason if I 'm using the debugger and stepping into every line then the code works properly . If not then it says the numbers are in order 100 % or out of order 100 % , which should not be the case.Here is the code I 've been using : I think that it might be a problem with the pseudo random and the code generating the same 3 numbers every time , but I 'm still learning more about programming and other help would be greatly appreciated . int num1 ; int num2 ; int num3 ; int yes = 0 ; int no = 0 ; for ( int i = 0 ; i < = 99 ; i++ ) { Random rnd = new Random ( ) ; num1 = rnd.Next ( 1 , 11 ) ; num2 = rnd.Next ( 1 , 11 ) ; num3 = rnd.Next ( 1 , 11 ) ; if ( ( ( num1 < = num2 ) & & ( num2 < = num3 ) ) || ( ( num1 > = num2 ) & & ( num2 > = num3 ) ) ) { yes += 1 ; } else { no += 1 ; } } Console.WriteLine ( `` The Number are in ascending order `` + yes.ToString ( ) + `` Times '' ) ; Console.WriteLine ( `` The Number are not in ascending order `` + no.ToString ( ) + `` Times '' ) ; Console.ReadLine ( ) ;",C # Code only works when using the debugger ? "C_sharp : I would like to be able to get a list of parameters in the form of a IDictionary < string , object > of the previous method called . There is one catch : I can not make use of third-party Aspect Oriented Programming framework even when it 's free.For example : Any suggestion or ideas ? Feel free to use reflection if necessary . using System ; using System.Collections.Generic ; using System.Diagnostics ; namespace Question { internal class Program { public static void Main ( string [ ] args ) { var impl = new Implementation ( ) ; impl.MethodA ( 1 , `` two '' , new OtherClass { Name = `` John '' , Age = 100 } ) ; } } internal class Implementation { public void MethodA ( int param1 , string param2 , OtherClass param3 ) { Logger.LogParameters ( ) ; } } internal class OtherClass { public string Name { get ; set ; } public int Age { get ; set ; } } internal class Logger { public static void LogParameters ( ) { var parameters = GetParametersFromPreviousMethodCall ( ) ; foreach ( var keyValuePair in parameters ) Console.WriteLine ( keyValuePair.Key + `` = '' + keyValuePair.Value ) ; // keyValuePair.Value may return a object that maybe required to // inspect to get a representation as a string . } private static IDictionary < string , object > GetParametersFromPreviousMethodCall ( ) { throw new NotImplementedException ( `` I need help here ! `` ) ; } } }","How to get a IDictionary < string , object > of the parameters previous method called in C # ?" "C_sharp : I 'm trying to pass a readonly struct to a method with in modifier.When I look at generated IL code , it seems that defensive copy of the readonly struct is made.The readonly struct is defined asMethod that accepts ReadonlyPoint3DAnd the way I 'm calling this method : If I look at generated IL for CalculateDistance method calling , I see that ReadonlyPoint3D instances are passed by reference : However , CalculateDistance method 's IL seem to make copies of point1 & point2 arguments : ldarg.0 & ldarg.1 in CalculateDistance method 's generated IL makes me think that copies of point1 & point2 were made.What I was expecting to see here are ldloca.s instructions which I think would 've mean to load the address of point1 & point2.Do I understand it correctly , defensive copies are made ? Or is my interpretation of IL code is wrong ? I 'm using .NET Core 2.1 with C # 7.3EDITAccording to Microsoft docs , mutable structs passed with in modifier will have defensive copies created.If I define mutable structAnd pass it with inI can see generated IL code is similar to what readonly struct had generated : Another observation is if I remove in modifier from CalculateDisctance method which accepts ReadonlyPoint3D , generated IL code is what I would expectBut this does n't seem to correspond to the suggestion in Microsoft DocsEDIT 2As suggested by @ PetSerAl in the comments , sharplab.io produces different IL for this code . The difference - ldobj instruction seen only for CalculateDistance ( in MutablePoint3D point1 , in MutablePoint3D point2 ) would explain that defensive copy is done only for this case . However , the IL instructions posted in the question were taken from ReSharper 's IL Viewer and verified by ILDASM.exe tool ( for Release configuration , like in sharplab.io ) . So I 'm not sure where this difference comes from and which output to be trusted . public readonly struct ReadonlyPoint3D { public ReadonlyPoint3D ( double x , double y , double z ) { this.X = x ; this.Y = y ; this.Z = z ; } public double X { get ; } public double Y { get ; } public double Z { get ; } } private static double CalculateDistance ( in ReadonlyPoint3D point1 , in ReadonlyPoint3D point2 ) { double xDifference = point1.X - point2.X ; double yDifference = point1.Y - point2.Y ; double zDifference = point1.Z - point2.Z ; return Math.Sqrt ( xDifference * xDifference + yDifference * yDifference + zDifference * zDifference ) ; } static void Main ( string [ ] args ) { var point1 = new ReadonlyPoint3D ( 0 , 0 , 0 ) ; var point2 = new ReadonlyPoint3D ( 1 , 1 , 1 ) ; var distance = CalculateDistance ( in point1 , in point2 ) ; } IL_0045 : ldloca.s point1IL_0047 : ldloca.s point2IL_0049 : call float64 CSharpTests.Program : :CalculateDistance ( valuetype CSharpTests.ReadonlyPoint3D & , valuetype CSharpTests.ReadonlyPoint3D & ) IL_004e : stloc.2 // distance // [ 25 9 - 25 10 ] IL_0000 : nop// [ 26 13 - 26 54 ] IL_0001 : ldarg.0 // point1IL_0002 : call instance float64 CSharpTests.ReadonlyPoint3D : :get_X ( ) IL_0007 : ldarg.1 // point2IL_0008 : call instance float64 CSharpTests.ReadonlyPoint3D : :get_X ( ) IL_000d : subIL_000e : stloc.0 // xDifference// the resit is omitted for the sake of brevity , essentially same code repeated for Y & Z public struct MutablePoint3D { public MutablePoint3D ( double x , double y , double z ) { this.X = x ; this.Y = y ; this.Z = z ; } public double X { get ; set ; } public double Y { get ; set ; } public double Z { get ; set ; } } private static double CalculateDistance ( in MutablePoint3D point1 , in MutablePoint3D point2 ) { double xDifference = point1.X - point2.X ; double yDifference = point1.Y - point2.Y ; double zDifference = point1.Z - point2.Z ; return Math.Sqrt ( xDifference * xDifference + yDifference * yDifference + zDifference * zDifference ) ; } // [ 26 13 - 26 54 ] IL_0001 : ldarg.0 // point1IL_0002 : call instance float64 CSharpTests.MutablePoint3D : :get_X ( ) IL_0007 : ldarg.1 // point2IL_0008 : call instance float64 CSharpTests.MutablePoint3D : :get_X ( ) IL_000d : subIL_000e : stloc.0 // xDifference// the resit is omitted for the sake of brevity // [ 35 13 - 35 54 ] IL_0001 : ldarga.s point1IL_0003 : call instance float64 CSharpTests.ReadonlyPoint3D : :get_X ( ) IL_0008 : ldarga.s point2IL_000a : call instance float64 CSharpTests.ReadonlyPoint3D : :get_X ( ) IL_000f : subIL_0010 : stloc.0 // xDifference",Is this a defensive copy of readonly struct passed to a method with in keyword "C_sharp : I 've defined the following two states in Expression Blend . I 've been trying to follow this guide but I feel like it leaves me hanging when I need information on how and when to change state . According to the guide I am to attach a behaviour ( I assume `` GotoState '' ) to my UserControl - Unfortunately I do n't think I actually have a User Control - and even if I did , would I have to attach a behaviour to both my PortraitState and my LandscapeState ? It seems I can attach a GotoState to my LayoutRoot element . So do I attach my behaviour to that in both states ? Any help would be greatly appreciated . *edit : I was playing around in my xaml.cs file and figured that this might be the way to do it programmatically . when debugging and changing the orientation I enter my switch case and find the correct orientation . The state , however , is never switched . What am I doing wrong ? edit2 : When attempting the above It seems that GotoElementState returns false and , according to MSDN : `` returns true if the control successfully transitioned to the new state ; otherwise , false . `` Now I 'm left with the question : What can cause my state transition to fail ? protected override void OnOrientationChanged ( OrientationChangedEventArgs e ) { switch ( e.Orientation ) { case PageOrientation.Landscape : ExtendedVisualStateManager.GoToElementState ( root : this.LayoutRoot , stateName : `` LandscapeState '' , useTransitions : true ) ; break ; case PageOrientation.LandscapeRight : ExtendedVisualStateManager.GoToElementState ( root : this.LayoutRoot , stateName : `` LandscapeState '' , useTransitions : true ) ; break ; case PageOrientation.LandscapeLeft : ExtendedVisualStateManager.GoToElementState ( root : LayoutRoot , stateName : `` LandscapeState '' , useTransitions : true ) ; break ; case PageOrientation.Portrait : ExtendedVisualStateManager.GoToElementState ( root : this.LayoutRoot , stateName : `` PortraitState '' , useTransitions : true ) ; break ; case PageOrientation.PortraitUp : ExtendedVisualStateManager.GoToElementState ( root : this.LayoutRoot , stateName : `` PortraitState '' , useTransitions : true ) ; break ; case PageOrientation.PortraitDown : ExtendedVisualStateManager.GoToElementState ( root : this.LayoutRoot , stateName : `` PortraitState '' , useTransitions : true ) ; break ; default : break ; } }",How do I change the VisualState in WP7 "C_sharp : So I 'm just hacking around with a state machine type I was working on and mostly wanting to just try out the Activator.CreateInstance method to see what it was like , and I ran into a problem where I cant seem to use the where clause as I would think . I apologize ahead of time if I am just an idiot and everyone laughs me out of here . So I have 2 small classes.as well asSo on the line _transitions.Add ( typeof ( TTransition ) , transitionContainer ) ; I receive a can not convert TransitionContainer < TTransition , TStateTo > expression to type TransitionContainer < ITransition , IState > error.If I change the generic parameters to it works fine , but I wanted to use inherited types that are new ( ) so I could be sure I could instantiate them.Again I apologize if I 'm doing something incredibly wrong , I was just kind of ran into a brick wall and my googling led me in no good direction . I didnt include any of the other interfaces or classes as they did n't seem to be part of the problem , but if there needed I can attach them . Thanks for any help ! public class TransitionContainer < TTransition , TStateTo > : ITransitionContainer < TTransition , TStateTo > where TTransition : ITransition where TStateTo : IState { public TransitionContainer ( ) { StateTo = typeof ( TStateTo ) ; Transition = Activator.CreateInstance < TTransition > ( ) ; } public Type StateTo { get ; private set ; } public TTransition Transition { get ; private set ; } } public class StateContainer < T > : IStateContainer < T > where T : IState { private Dictionary < Type , TransitionContainer < ITransition , IState > > _transitions = new Dictionary < Type , TransitionContainer < ITransition , IState > > ( ) ; public StateContainer ( ) { State = Activator.CreateInstance < T > ( ) ; } public T State { get ; private set ; } public int TransitionCount { get { return _transitions.Count ; } } public void AddTransition < TTransition , TStateTo > ( ) where TTransition : ITransition , new ( ) where TStateTo : IState , new ( ) { var transitionContainer= new TransitionContainer < TTransition , TStateTo > ( ) ; _transitions.Add ( typeof ( TTransition ) , transitionContainer ) ; } var transitionContainer= new TransitionContainer < ITransition , IState > ( ) ;",C # Is Not Assignable Type - Generics "C_sharp : Why does n't Type.GetProperty ( string ) get a property from a base interface if the type is an interface ? For example , the following code prints : which seems inconsistent : EDIT : another aspect of the runtime that supports Cole 's answer is the following : System.String XnullSystem.String XSystem.String X void Main ( ) { Console.WriteLine ( typeof ( I1 ) .GetProperty ( `` X '' ) ) ; Console.WriteLine ( typeof ( I2 ) .GetProperty ( `` X '' ) ) ; Console.WriteLine ( typeof ( C1 ) .GetProperty ( `` X '' ) ) ; Console.WriteLine ( typeof ( C2 ) .GetProperty ( `` X '' ) ) ; ; } public interface I1 { string X { get ; } } public interface I2 : I1 { } public class C1 { public string X { get { return `` x '' ; } } } public class C2 : C1 { } public class C : I2 { // not allowed : the error is // 'I2.X ' in explicit interface declaration is not a member of interface string I2.X { get ; set ; } // allowed string I1.X { get ; set ; } }",Why does C # Type.GetProperty ( ) behave differently for interfaces than for base classes ? "C_sharp : I found this gem ( IMO ) in System.Windows.Forms namespace . I 'm struggling to figure out why is it set like this.Can somebody explain why it uses these values ( power of 2^20 to 2^24 ) instead of this : The first value is 100000000000000000000 in binary , which leaves space for another 20 bits ! Why do we need such space and why is it preserved like this ? [ Flags ] public enum MouseButtons { None = 0 , Left = 1048576 , Right = 2097152 , Middle = 4194304 , XButton1 = 8388608 , XButton2 = 16777216 , } public enum MouseButtons { None = 0 , Left = 1 , // 2^0 Right = 2 , // 2^1 Middle = 4 , // 2^2 XButton1 = 8 , // 2^3 XButton2 = 16 , // 2^4 }",Odd enum values in Windows.Forms.MouseButtons "C_sharp : I 've got two classes , MyClassA and MyClassB . MyClassB inherits from MyClassA . I 've written a method with the following signatureI 've also got the following event handler.I understand that MyGeneric < MyClassA > is not of the same type MyGeneric < MyClassB > but since MyClassB is a subclass of MyClassA is there still a way to make this work ? For reference , the exact error message : Unable to cast object of type 'MSUA.GraphViewer.GraphControls.TreeNode1 [ MSUA.GraphViewer.GraphControls.MaterialConfigControl ] ' to type 'MSUA.GraphViewer.GraphControls.TreeNode1 [ MSUA.GraphViewer.PopulatableControl ] ' . public void DoSomething ( MyGeneric < MyClassA > obj ) ; public void MyEventHandler ( Object source , EventArgs e ) { //source is of type MyGeneric < MyClassB > DoSomething ( ( MyGeneric < MyClassA > ) obj ) ; }",C # Casting Generic < B > to Generic < A > where B : A "C_sharp : Is this at all possible ? If so , how ? The flow would be something like : All this code would be a windows service , so what would be the 'best ' way to tell the OnStart method to skip DoStuff if pc was restarted and go straight to DoStuffAfterRestart since service would be set to auto start . private void DoStuff ( ) { // Do some stuff RestartPc ( ) ; } private void RestartPc ( ) { Process.Start ( `` shutdown '' , `` /r /t 0 '' ) ; } // Call this when the PC is restarted : private void DoStuffAfterRestart ( ) { }","Start executing an exe file in windows , restart computer , and pick up where the process left off" "C_sharp : I want to generate HTML head section in a child action ; while the page has many other child actions . The html head section is depended on the other actions to determine which js/css files should be included . Different child actions could share the same js/css file ; and different pages have different combination of the css/js , so there is a reason to do that . Here is my sample code : Each zone has 1 or many child actions . The RenderZone is atually an action too . The data mode : The RenderZone view : Because the Header zone is the top so it is always executed first then it can not get data from other child actions . I have tried filters ( onActionExecuted ; onActionResultExcuted and so on ) but none of them works . I really need to execute the header action after all child actions are rendered . I do not want to generate the css in the bottom of a page . I could but I do not want to use javascript to inject the js/css files ; or write an http module to `` manually '' change the output html . It is very easy to handle it in webform . I believe there is a way to do that in MVC too . Any help will be greatly appreciated ! Layout.cshtml : < html > < head > @ RenderZone ( `` header '' ) < /head > < body > @ RenderZone ( `` zone1 '' ) @ RenderZone ( `` zone2 '' ) @ RenderZone ( `` zone3 '' ) < /html > Model = GetAllChildActions ( zoneName ) foreach ( var m in Model ) @ html.action ( controller = m.controller , action = m.action )",How to change the sequences of child actions in MVC "C_sharp : from my title it might be a little hard to understand what I 'm trying to achieve , so I 'll go a little further into detail.I have the following interface : Now I want to implement the interface in my actual builder . The builder I use to map different object types . So this looks as follows : Now the problem is the following . I ca n't get the constraint to work . Since I defined the constraint on the interface it wo n't let me use a different constraint on my actual method , even though my BusinessModel inherits from BaseModel . It keeps telling me my constraint M must match the constraint from the interface . I tried several different approaches , but none seem to work . Does anyone know if or how this can be achieved ? I just want to tell my constraint in the interface that inherited models are allowed . public interface IModelBuilder < T > where T : IStandardTemplateTemplate { M Build < M > ( T pTemplate , params object [ ] pParams ) where M : BaseModel ; } public class BusinessModelBuilder : IModelBuilder < IBusinessTemplate > { public virtual M Build < M > ( IBusinessTemplate pTemplate , params object [ ] pParams ) where M : BussinessModel { var businessModel = Activator.CreateInstance < M > ( ) ; // map data return businessModel ; } }",How to implement generic method with constraints "C_sharp : I have a rather large file consisting of several million lines and there is the need to check and remove corrupt lines from the file.I have shamelessly tried File.ReadAllLines but it did n't work . Then I tried to stream lines as below reading from the original file and writing to a new one . While it does the job , it does so in several hours ( 5+ ) . I have read about using buffers which sounds like the only option but how am I going to keep line integrity in that way ? Solution : StreamWriter moved to outside of while . Instead of split , count is used . using ( FileStream inputStream = File.OpenRead ( ( localFileToProcess + `` .txt '' ) ) ) { using ( StreamReader inputReader = new StreamReader ( inputStream , System.Text.Encoding.GetEncoding ( 1254 ) ) ) { using ( StreamWriter writer=new StreamWriter ( localFileToProcess , true , System.Text.Encoding.GetEncoding ( 1254 ) ) ) { while ( ! inputReader.EndOfStream ) { if ( ( tempLineValue = inputReader.ReadLine ( ) ) .Count ( c = > c == ' ; ' ) == 4 ) { writer.WriteLine ( tempLineValue ) ; } else incrementCounter ( ) ; } } } }",reading and modifying large text files 3-5GB C_sharp : I got the following code : The output is : Why are n't they both System.Object ? object var3 = 3 ; Console.WriteLine ( var3.GetType ( ) .ToString ( ) ) ; Console.WriteLine ( typeof ( object ) .ToString ( ) ) ; System.Int32System.Object,"boxing and unboxing , why are n't the outputs both `` System.Object '' ?" "C_sharp : The issue is specific to Internet Explorer . The favicon works fine in chrome . I have an angular application which is running alongside the legacy application . When I navigate to the angular application from legacy application the favicon appears as expected in the internet explorer , but when I navigate within the angular application the favicon disappears.I have tried full path , relative path , as well as CDN but nothing seems to be working . < link rel= '' icon '' type= '' image/x-icon '' href= '' https : //cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png ? v=c78bd457575a '' / > < link rel= '' shortcut icon '' type= '' image/x-icon '' href= '' https : //cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png ? v=c78bd457575a '' / >",In IE 11 the favicon disappears on navigating to another page in Angular application C_sharp : Given these integers : What 's the best way to create a byte [ ] array from them ? If all their values are 1 the resulting array would be : public uint ServerSequenceNumber ; public uint Reserved1 ; public uint Reserved2 ; public byte Reserved3 ; public byte TotalPlayers ; 00000000000000000000000000000001 00000000000000000000000000000001 00000000000000000000000000000001 00000001 00000001,create byte array from set of integers "C_sharp : I am working on integrating Google Cloud PubSub into a sample c # project , I am a newbie with c # as this will probably be the only c # project I will work on in my company due to some requirements on integrating with a game written in c # .I used NuGet to install Google.Cloud.PubSub.V1.0.0-beta13 and the installation went successfully , however when I try to run the sample code created using the docs I get the following error : I then tried downgrading Google.Apis.Auth to 1.21.0 but then the problem moves to `` Could not load Google.Api.Gax , Version=1.0.1.0 '' and then ( if I keep downgrading dependencies ) on Google.Protobuf 3.2.0.0 , then on Google.Apis.Core 1.24.1 and then back to `` Could not load Google.Apis.Auth 1.21.0 '' so I guess the problem is somewhere else.What causes this dependency issue ? If I load the Google Pubsub sample project from Github I do not get any issues even if the packages.config is the same of the one in my project.Here is my Program.cs : and my packages.configI use Rider 2017.1.1 to run my project and I run it on .NET framework 4.5.2.Please note that I already know that a very similar question is already posted at this URL Unable to run Google Cloud PubSub in c # , DLL problems but due to my low `` reputation '' I ca n't comment it ( you know , I usually try to read documentation and search for questions already answered and try to avoid creating duplicates , that is why I have n't build a high reputation on this site ) and the guy that made the question solved the issue for himself without knowing how.In the answer is written : ... if you manage all the dependencies via NuGet , I 'd expect it to be okay - it should add assembly binding redirects for you.which it seems to me I am already doing . C : /Users/MyUser/RiderProjects/TestConsole/TestConsole/bin/Debug/TestConsole.exeUnhandled Exception : System.IO.FileLoadException : Could not load file or assembly 'Google.Apis.Auth , Version=1.21.0.0 , Culture=neutral , PublicKeyToken=4b01fa6e34db77ab ' or one of its dependencies . The located assembly 's manifest definition does not match the assembly reference . ( Exception from HRESULT : 0x80131040 ) at Google.Api.Gax.TaskExtensions.WaitWithUnwrappedExceptions ( Task task ) in C : \Users\jon\Test\Projects\gax-dotnet\releasebuild\src\Google.Api.Gax\TaskExtensions.cs : line 48 at Google.Api.Gax.Grpc.ChannelPool.GetChannel ( ServiceEndpoint endpoint ) in C : \Users\jon\Test\Projects\gax-dotnet\releasebuild\src\Google.Api.Gax.Grpc\ChannelPool.cs : line 92 at Google.Cloud.PubSub.V1.PublisherClient.Create ( ServiceEndpoint endpoint , PublisherSettings settings ) in C : \Users\jon\Test\Projects\google-cloud-dotnet\releasebuild\apis\Google.Cloud.PubSub.V1\Google.Cloud.PubSub.V1\PublisherClient.cs : line 558 at TestConsole.Program.CreateTopic ( String projectId , String topicId ) in C : \Users\MyUser\RiderProjects\TestConsole\TestConsole\Program.cs : line 11 at TestConsole.Program.Main ( String [ ] args ) in C : \Users\MyUser\RiderProjects\TestConsole\TestConsole\Program.cs : line 32 using Google.Cloud.PubSub.V1 ; using Google.Protobuf ; namespace TestConsole { internal class Program { public static object CreateTopic ( string projectId , string topicId ) { var publisher = PublisherClient.Create ( ) ; var topicName = new TopicName ( projectId , topicId ) ; var message = new PubsubMessage { // The data is any arbitrary ByteString . Here , we 're using text . Data = ByteString.CopyFromUtf8 ( `` Hello Cloud Pub/Sub ! `` ) , // The attributes provide metadata in a string-to-string // dictionary . Attributes = { { `` description '' , `` Simple text message '' } } } ; publisher.Publish ( topicName , new [ ] { message } ) ; return 0 ; } public static void Main ( string [ ] args ) { CreateTopic ( `` MyProjectID '' , `` MyProjectTopic '' ) ; } } } < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < packages > < package id= '' Google.Api.CommonProtos '' version= '' 1.0.0 '' targetFramework= '' net452 '' / > < package id= '' Google.Api.Gax '' version= '' 1.0.1 '' targetFramework= '' net452 '' / > < package id= '' Google.Api.Gax.Grpc '' version= '' 1.0.1 '' targetFramework= '' net452 '' / > < package id= '' Google.Apis '' version= '' 1.24.1 '' targetFramework= '' net452 '' / > < package id= '' Google.Apis.Auth '' version= '' 1.24.1 '' targetFramework= '' net452 '' / > < package id= '' Google.Apis.Core '' version= '' 1.24.1 '' targetFramework= '' net452 '' / > < package id= '' Google.Cloud.Iam.V1 '' version= '' 1.0.0-beta09 '' targetFramework= '' net452 '' / > < package id= '' Google.Cloud.PubSub.V1 '' version= '' 1.0.0-beta09 '' targetFramework= '' net452 '' / > < package id= '' Google.Protobuf '' version= '' 3.2.0 '' targetFramework= '' net452 '' / > < package id= '' Grpc.Auth '' version= '' 1.4.0 '' targetFramework= '' net452 '' / > < package id= '' Grpc.Core '' version= '' 1.4.0 '' targetFramework= '' net452 '' / > < package id= '' Newtonsoft.Json '' version= '' 10.0.2 '' targetFramework= '' net452 '' / > < package id= '' System.Interactive.Async '' version= '' 3.1.1 '' targetFramework= '' net452 '' / > < package id= '' System.Net.Http '' version= '' 4.3.1 '' targetFramework= '' net425 '' / > < package id= '' Zlib.Portable.Signed '' version= '' 1.11.0 '' targetFramework= '' net452 '' / > < /packages >",Dependency issue when running c # sample project based on cloud pubsub "C_sharp : I have an image which I grab using a camera . Sometimes , the lighting is uneven in them image . There are some dark shades . This causes incorrect optimal thresholding in EMGU as well as Aforge to process the image for OCR.This is the image : This is what I get after thresholding : How do I correct the lighting ? I tried adaptive threshold , gives about the same result . Tried gamma correction too using the code below : same result . Please help.UPDATE : as per Nathancy 's suggestion I converted his code to c # for uneven lighting correction and it works : ImageAttributes attributes = new ImageAttributes ( ) ; attributes.SetGamma ( 10 ) ; // Draw the image onto the new bitmap // while applying the new gamma value . System.Drawing.Point [ ] points = { new System.Drawing.Point ( 0 , 0 ) , new System.Drawing.Point ( image.Width , 0 ) , new System.Drawing.Point ( 0 , image.Height ) , } ; Rectangle rect = new Rectangle ( 0 , 0 , image.Width , image.Height ) ; // Make the result bitmap . Bitmap bm = new Bitmap ( image.Width , image.Height ) ; using ( Graphics gr = Graphics.FromImage ( bm ) ) { gr.DrawImage ( HSICONV.Bitmap , points , rect , GraphicsUnit.Pixel , attributes ) ; } Image < Gray , byte > smoothedGrayFrame = grayImage.PyrDown ( ) ; smoothedGrayFrame = smoothedGrayFrame.PyrUp ( ) ; //canny Image < Gray , byte > cannyFrame = null ; cannyFrame = smoothedGrayFrame.Canny ( 50 , 50 ) ; //smoothing grayImage = smoothedGrayFrame ; //binarize Image < Gray , byte > grayout = grayImage.Clone ( ) ; CvInvoke.AdaptiveThreshold ( grayImage , grayout , 255 , AdaptiveThresholdType.GaussianC , ThresholdType.BinaryInv , Convert.ToInt32 ( numericmainthreshold.Value ) + Convert.ToInt32 ( numericmainthreshold.Value ) % 2 + 1 , 1.2d ) ; grayout._Not ( ) ; Mat kernelCl = CvInvoke.GetStructuringElement ( ElementShape.Rectangle , new Size ( 3 , 3 ) , new System.Drawing.Point ( -1 , -1 ) ) ; CvInvoke.MorphologyEx ( grayout , grayout , MorphOp.Close , kernelCl , new System.Drawing.Point ( -1 , -1 ) , 1 , BorderType.Default , new MCvScalar ( ) ) ;",Image lighting correction "C_sharp : I 'm having some trouble computing the same hash in PHP as I am in C # .NET . In C # , I have the following : Which produces something like : yBV7ZfAyT1FwO5sGEVd3aPYUfBz9geN6ghK9RO68jwo=In PHP , I thought this would calculate the hash the same way : However it produces a much different , larger hash : YzgxNTdiNjVmMDMyNGY1MTcwM2I5YjA2MTE1Nzc3NjhmNjE0N2MxY2ZkODFlMzdhODIxMmJkNDRlZWJjOGYwYQ== HMAC hasher = new HMACSHA256 ( Encoding.UTF8.GetBytes ( `` secret '' ) ) ; //keybyte [ ] data = hasher.ComputeHash ( Encoding.UTF8.GetBytes ( `` 2012-10-01T17:48:56 '' ) ) ; //timestampConvert.ToBase64String ( data ) ; //computed token $ hmac = hash_hmac ( `` sha256 '' , `` 2012-10-01T17:48:56 '' , `` secret '' ) ; $ hmac = base64_encode ( $ hmac ) ;",How would I generate this same token in PHP ? ( From .NET ) "C_sharp : I had never used UDP before , so I gave it a go . To see what would happen , I had the 'server ' send data every half a second , and the client receive data every 3 seconds . So even though the server is sending data much faster than the client can receive , the client still receives it all neatly one by one.Can anyone explain why/how this happens ? Where is the data buffered exactly ? SendAll CSomeObjServer does is increment an integer by one every half secondReceiveCSomeObjClient stores the variable and has one function ( alterSomeVar ) to update itOuput : class CSimpleSend { CSomeObjServer obj = new CSomeObjServer ( ) ; public CSimpleSend ( ) { obj.changedVar = varUpdated ; obj.threadedChangeSomeVar ( ) ; } private void varUpdated ( int var ) { string send = var.ToString ( ) ; byte [ ] packetData = System.Text.UTF8Encoding.UTF8.GetBytes ( send ) ; string ip = `` 127.0.0.1 '' ; int port = 11000 ; IPEndPoint ep = new IPEndPoint ( IPAddress.Parse ( ip ) , port ) ; Socket client = new Socket ( AddressFamily.InterNetwork , SocketType.Dgram , ProtocolType.Udp ) ; client.SendTo ( packetData , ep ) ; Console.WriteLine ( `` Sent Message : `` + send ) ; Thread.Sleep ( 100 ) ; } } class CSimpleReceive { CSomeObjClient obj = new CSomeObjClient ( ) ; public Action < string > showMessage ; Int32 port = 11000 ; UdpClient udpClient ; public CSimpleReceive ( ) { udpClient = new UdpClient ( port ) ; showMessage = Console.WriteLine ; Thread t = new Thread ( ( ) = > ReceiveMessage ( ) ) ; t.Start ( ) ; } private void ReceiveMessage ( ) { while ( true ) { //Thread.Sleep ( 1000 ) ; IPEndPoint remoteIPEndPoint = new IPEndPoint ( IPAddress.Any , port ) ; byte [ ] content = udpClient.Receive ( ref remoteIPEndPoint ) ; if ( content.Length > 0 ) { string message = Encoding.UTF8.GetString ( content ) ; if ( showMessage ! = null ) showMessage ( `` Recv : '' + message ) ; int var_out = -1 ; bool succ = Int32.TryParse ( message , out var_out ) ; if ( succ ) { obj.alterSomeVar ( var_out ) ; Console.WriteLine ( `` Altered var to : '' + var_out ) ; } } Thread.Sleep ( 3000 ) ; } } } Sent Message : 1Recv:1Altered var to :1Sent Message : 2Sent Message : 3Sent Message : 4Sent Message : 5Recv:2Altered var to :2Sent Message : 6Sent Message : 7Sent Message : 8Sent Message : 9Sent Message : 10Recv:3Altered var to :3",Where is data sent by UDP stored ? "C_sharp : I 've got a weak imagination when it comes to names , so I often find myself re-using identifiers in my code . This caused me to run into this specific problem.Here 's some example code : Here are the compilation errors ( output by ideone ) : Line 11 contains test++ , line 9 contains the lambda.Incidentally , Visual Studio 2013 gives a different error : The error occurs at the increment on line 11 only.The code compiles successfully if I comment out either line 9 ( the lambda ) or line 11 ( the increment ) .This issue is a surprise to me - I was sure that lambda parameter names can conflict only with local method variable names ( which is sort of confirmed by the code compiling when I comment out the increment ) . Also , how can the lambda parameter possibly affect the increment , which is right outside the lambda 's scope ? I ca n't get my head around this ... What exactly did I do wrong ? And what do the cryptic error messages mean in this case ? EDIT after all the great answers : So I think I finally understood the rule that I broke . It is not well-worded in the C # spec ( 7.6.2.1 , see Jon Skeet 's answer for the quote ) . What it was supposed to mean is something like : You can not use the same identifier to refer to different things ( entities ) in the same `` local variable declaration space '' if one of the offending uses is ( directly ) located in a scope which can be `` seen '' from the scope where the other is ( directly ) located.Not the standard 's standard phrasing , but I hope you understood what I mean . This rule was supposed to allow this : because neither of the scopes of the two variables a can be `` seen '' from the other 's scope ; and disallow this : because the second variable declaration is `` seen '' from the first variable 's scopeand disallow this : because the increment of the field can be `` seen '' from the block 's scope ( it not being a declaration does n't matter ) .It seems that C # 6 changed this rule , specifically making the last example ( and my original code ) legit , though I do n't really understand how exactly.Please correct me if I made some mistakes in these examples . public delegate void TestDelegate ( int test ) ; public class Test { private int test ; private void method ( int aaa ) { TestDelegate del = test = > aaa++ ; test++ ; } public static void Main ( ) { } } prog.cs ( 11,3 ) : error CS0135 : ` test ' conflicts with a declaration in a child blockprog.cs ( 9,22 ) : ( Location of the symbol related to previous error ) Compilation failed : 1 error ( s ) , 0 warnings 'test ' conflicts with the declaration 'Namespace.Test.test ' { int a ; } { int a ; } { int a ; } int a ; class Test { int test ; void method ( ) { { int test ; } test++ ; } }",Lambda parameter conflicting with class field on accessing field in later scope "C_sharp : Our app running on client server A and creates a file on the server 2008 R2 file-server using : The client is testing a disaster situation and powering off 'server A ' and leaving it off.They 're reporting that our app running on 'server B ' using the same filename and the same code fragment above fails ( ie the file continues to exist ) for at least 15 minutes until , we believe , they browse to folder containing the file in Windows Explorer at which point the file is deleted automatically.Is anyone aware of how this is supposed to behave in this situation , where the creating server has gone away , should the handles be released and the file removed automatically ? And why does looking at the file cause it to delete ? Interestingly , on another supposedly similar setup the issue does not occur . CreateFile ( LockFileName , GENERIC_READ or GENERIC_WRITE , FILE_SHARE_READ , nil , CREATE_ALWAYS , FILE_FLAG_WRITE_THROUGH or FILE_FLAG_DELETE_ON_CLOSE , 0 ) ;",Machine retains file exists/locks on client-side power outage "C_sharp : I need to generate n random strings and this process may take a while and block the main thread UI . For avoid this and let user use the programm while the process is running I decided to use a backGroundWorker . But it did n't work well and the main thread still is blocked . In my DoWork event I have something like this : Even although I call ReportProgress ( ) inside the loop , the progressbar only changes its value when the loop is done.Why is this happening and how can I fix this ? private void backgroundWorker1_DoWork ( object sender , DoWorkEventArgs e ) { // using Invoke because I change value of some controls , e.g , ListView , labels and a progressbar this.Invoke ( ( Action ) delegate { for ( int i = 0 ; i < nSteps ; ++i ) { string s = getnStr ( ) ; // ... int progress = ( int ) ( 100.0 / nSteps * ( i + 1 ) ) ; backgroundWorker1.ReportProgress ( progress ) ; } } ) ; }",Run code without block main thread "C_sharp : TargetNullValue is supposed to update the binding Target when the binding Source evaluates to null : Gets or sets the value that is used in the target when the value of the source is null.In addition to that it also appears to set the Source to null ( if possible ) , when the value of Target is equals to given TargetNullValue . In other words , it effectively sets up an equivalency between null and the TargetNullValue property 's value . However this is not mentioned in the documentation at all.See this example : Note : UpdateSourcetrigger is only set to make testing easier and has nothing to do with the effect in question.If you put a breakpoint in NullableInt 's setter , you can see that it gets triggered ( with value == null ) when you change the TextBox content to `` .Is this a undocumented behavior by TargetNullValue or is there some other side effect in play here ? Edit : I stumbled upon this topic , because I was looking at this question : Set value to null in WPF binding < Window x : Class= '' WPF_Sandbox.MainWindow '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : local= '' clr-namespace : WPF_Sandbox '' Title= '' MainWindow '' x : Name= '' ThisControl '' > < StackPanel x : Name= '' MainStackPanel '' > < TextBox x : Name= '' MyTextBox '' Text= '' { Binding NullableInt , ElementName=ThisControl , TargetNullValue= '' , UpdateSourceTrigger=PropertyChanged } '' / > < /StackPanel > < /Window > public partial class MainWindow : Window { private int ? nullableInt ; public int ? NullableInt { get { return nullableInt ; } set { nullableInt = value ; } } public MainWindow ( ) { InitializeComponent ( ) ; } }",Why does TargetNullValue update nullable Source "C_sharp : From Jon Skeet 's wonderful book C # In Depth , First Edition : A paragraph follows the above-listed snippet of code . The first half of listing 9.4 involves just setting up the data . I would have used an anonymous type , but it ’ s relatively tricky to create a generic list from a collection of anonymous type instances . ( You can do it by creating a generic method that takes an array and converts it to a list of the same type , then pass an implicitly typed array into that method . An extension method in .NET 3.5 called ToList provides this functionality too , but that would be cheating as we haven ’ t looked at extension methods yet ! ) And the code snippet provided above , is listing 9.4 of the book that the paragraph refers to.My question : I am trying out the technique outlined in the above paragraph by hand ( look at the italicized text ) but I ca n't quite understand what he means.I tried something like this but it is n't what he meant , I suppose , as it does n't work ( and I did n't expect it to ) : } Note : I know about the IEnumerable.ToList ( ) extension method and have used it many times . I just want to try the technique outlined in the paragraph by hand.Also , I 'm intrigued by scenarios where anonymous types are used outside of Linq , as a syntactic convenience and one of such scenarios is given below . I can always use dynamic in C # 4 and accept an anonymous type as an argument and work with it knowing what I expect . I wish I could do that with C # 3 . Something like below : } EditThey should have a tag named jon-skeet . class Film { public string Name { get ; set ; } public int Year { get ; set ; } public override string ToString ( ) { return string.Format ( `` Name= { 0 } , Year= { 1 } '' , Name , Year ) ; } } var films = new List < Film > { new Film { Name= '' Jaws '' , Year=1975 } , new Film { Name= '' Singing in the Rain '' , Year=1952 } , new Film { Name= '' Some Like It Hot '' , Year=1959 } , new Film { Name= '' The Wizard of Oz '' , Year=1939 } , new Film { Name= '' It 's a Wonderful Life '' , Year=1946 } , new Film { Name= '' American Beauty '' , Year=1999 } , new Film { Name= '' High Fidelity '' , Year=2000 } , new Film { Name= '' The Usual Suspects '' , Year=1995 } } ; Action < Film > print = film = > { Console.WriteLine ( film ) ; } ; films.ForEach ( print ) ; films.FindAll ( film = > film.Year < 1960 ) .ForEach ( print ) ; films.Sort ( ( f1 , f2 ) = > f1.Name.CompareTo ( f2.Name ) ) ; films.ForEach ( print ) ; using System ; using System.Collections.Generic ; namespace ScratchPad { class Film { public string Name { get ; set ; } public int Year { get ; set ; } public override string ToString ( ) { return string.Format ( `` Name = { 0 } \tYear = { 1 } '' , Name , Year ) ; } } class Program { static void Main ( string [ ] args ) { ToList < Film > ( new [ ] { new { Name = `` North By Northwest '' , Year = 1959 } , new { Name = `` The Green Mile '' , Year = 1999 } , new { Name = `` The Pursuit of Happyness '' , Year = 2006 } } ) .ForEach ( f = > { Console.WriteLine ( f ) ; } ) ; Console.ReadKey ( ) ; } static List < T > ToList < T > ( System.Collections.IEnumerable list ) { var newList = new List < T > ( ) ; foreach ( var thing in list ) if ( thing is T ) newList.Add ( ( T ) thing ) ; return newList ; } } using System ; using Microsoft.CSharp.RuntimeBinder ; namespace PlayWithAnonType { class Program { static void Main ( string [ ] args ) { PrintThingy ( new { Name = `` The Secret '' , Genre = `` Documentary '' , Year = 2006 } ) ; Console.ReadKey ( ) ; } static void PrintWhatever ( dynamic whatever ) { // the anonymous type 's ToString ( ) will print Console.WriteLine ( whatever ) ; } static void PrintThingy ( dynamic thingy ) { try { // I know what the thingy is Console.WriteLine ( `` Name = { 0 } \tGenre = { 1 } \tYear = { 2 } '' , thingy.Name , thingy.Genre , thingy.Year ) ; } catch ( RuntimeBinderException ex ) { # pragma warning disable 0168 Console.WriteLine ( `` By thingy , I really meant film . Sorry , I should 've clarified . `` ) ; # pragma warning restore 0168 } } }",Playing with anonymous types "C_sharp : I have this C # example , which will create a dictionary of odd and even numbers from an array of integers : Output is : I want to do it similarly in F # using ToDictionary , and have this so far : But how will I write the logic inside ToDictionary ? int [ ] values = new int [ ] { 1 , 2 , 3 , 5 , 7 } ; Dictionary < int , string > dictionary = values.ToDictionary ( key = > key , val = > ( val % 2 == 1 ) ? `` Odd '' : `` Even '' ) ; // Display all keys and values.foreach ( KeyValuePair < int , string > pair in dictionary ) { Console.WriteLine ( pair ) ; } [ 1 , Odd ] [ 2 , Even ] [ 3 , Odd ] [ 5 , Odd ] [ 7 , Odd ] let values = [ | 1 ; 2 ; 3 ; 5 ; 7 | ] let dictionary = values.ToDictionary ( ? ? ? ) // Display all keys and values.for d in dictionary do printfn `` % d % s '' d.Key d.Value",How to get ToDictionary to work in F # ? "C_sharp : I see some code like this : but I do n't know what are `` s '' and `` e '' ? what is the topic I should study in C # for this line of code ? textBox.TextChanged += ( s , e ) = > this.Foo ( ) ;",what are `` s '' and `` e '' in C # code syntax "C_sharp : I 'd like to automatically wrap a value in a generic container on return ( I am aware that this is not always desirable , but it makes sense for my case ) . For example , I 'd like to write : I 'm able to do this by adding the following to my Wrapper class : Unfortunately , this fails when I attempt to convert an IEnumerable , complete code here ( and at ideone ) : The compilation error I get is : Can not implicitly convert type 'System.Collections.Generic.IEnumerable < string > ' to ' ... Wrapper < System.Collections.Generic.IEnumerable < string > > 'What exactly is going on , and how can I fix it ? public static Wrapper < string > Load ( ) { return `` '' ; } public static implicit operator Wrapper < T > ( T val ) { return new Wrapper < T > ( val ) ; } public class Test { public static void Main ( ) { string x = `` '' ; Wrapper < string > xx = x ; string [ ] y = new [ ] { `` '' } ; Wrapper < string [ ] > yy = y ; IEnumerable < string > z = new [ ] { `` '' } ; Wrapper < IEnumerable < string > > zz = z ; // ( ! ) } } public sealed class Wrapper < T > { private readonly object _value ; public Wrapper ( T value ) { this._value = value ; } public static implicit operator Wrapper < T > ( T val ) { return new Wrapper < T > ( val ) ; } }",Implicitly converting a generic to a wrapper "C_sharp : I wrote the following to test the performance of using foreach vs LINQ : I get something like following output : In every run , LINQ outperforms foreach by around 20 % . It was my understanding that the LINQ extension methods used standard c # under the covers.So why is LINQ faster in this case ? EDIT : So I changed my code to use stopwatch instead of datetime and still get the same results . If I run the LINQ query first then my results show LINQ to be about 20 % slower then foreach . This has to be some sort of JIT warmnup issue . My question is how do I compensate for JIT warmup in my test case ? private class Widget { public string Name { get ; set ; } } static void Main ( string [ ] args ) { List < Widget > widgets = new List < Widget > ( ) ; int found = 0 ; for ( int i = 0 ; i < = 500000 - 1 ; i++ ) widgets.Add ( new Widget ( ) { Name = Guid.NewGuid ( ) .ToString ( ) } ) ; DateTime starttime = DateTime.Now ; foreach ( Widget w in widgets ) { if ( w.Name.StartsWith ( `` 4 '' ) ) found += 1 ; } Console.WriteLine ( found + `` - `` + DateTime.Now.Subtract ( starttime ) .Milliseconds + `` ms '' ) ; starttime = DateTime.Now ; found = widgets.Where ( a = > a.Name.StartsWith ( `` 4 '' ) ) .Count ( ) ; Console.WriteLine ( found + `` - `` + DateTime.Now.Subtract ( starttime ) .Milliseconds + `` ms '' ) ; Console.ReadLine ( ) ; } 31160 - 116ms31160 - 95 ms",Why is LINQ faster in this example "C_sharp : What I know about async/await is that when the task completes , the continuation is run on the same context when the await was called , which would , in my case , be the UI thread.But my question is , does it create a new thread ( internally ) after IO is complete and before moving to the same UI thread.I am sharing a piece of code . If I click on this button once , It shows that available thread is 1023 before executing await , but after that , available threads dropped to 1022 . Although When I check the thread id , it is the same as UI thread.But interestingly , next time when I click on this button , number of available threads remains 1023 ( before and after await ) . private async void button1_ClickAsync ( object sender , EventArgs e ) { int x , y ; ThreadPool.GetAvailableThreads ( out x , out y ) ; textBox1.Text = x.ToString ( ) + '' ... '' +y.ToString ( ) ; await Task.Delay ( 5000 ) ; ThreadPool.GetAvailableThreads ( out x , out y ) ; textBox1.Text = x.ToString ( ) + `` ... '' + y.ToString ( ) ; }",Does await create another thread internally before shifting to the same thread as the caller ( for UI application ) C_sharp : I have : How do I get the TypeName of MyDocumentType if I 'm in another class ? public class MyUserControl : WebUserControlBase < MyDocumentType > { ... },Get type name of T using reflection "C_sharp : I 'm trying to maintain a collection of objects based on their URI : However , the URI regularly only differs based on the Fragment of the Uri . So , the following causes an error : Per http : //msdn.microsoft.com/en-us/library/f83xtf15.aspx : The Equals method compares the two instances without regard to user information ( UserInfo ) and fragment ( Fragment ) parts that they might contain . For example , given the URIs http : //www.contoso.com/index.htm # search and http : //user : password @ www.contoso.com/index.htm , the Equals method would return true.I 'm resigned to having to hack around this . But why does it behave this way ? I can see the logic for user-info , but not for fragment . public class ConceptCollection : KeyedCollection < Uri , Concept > { protected override Uri GetKeyForItem ( Concept item ) { return item.Uri ; } } ConceptCollection wines = new ConceptCollection ( ) ; Concept red = new Concept ( `` http : //www.w3.org/2002/07/owl # RedWine '' ) ; Concept white = new Concept ( `` http : //www.w3.org/2002/07/owl # WhiteWine '' ) ; wines.Add ( red ) ; wines.Add ( white ) ; // Error : An item with the same key has already been added .",Why is the Fragment of a Uri ignored in the Equals method ? "C_sharp : In Visual Studio 2013 targeting .NET Framework 4.5.1 , I find that disposing of an X509Chain is more difficult than expected . According to the MSDN documentation , starting in 4.5 X509Chain is disposable . The reference source confirms it , and looking at the class with ildasm also confirms it : And yet , when attempting to put it in a using statement like so : I get a compilation error : Error 1 'System.Security.Cryptography.X509Certificates.X509Chain ' : type used in a using statement must be implicitly convertible to 'System.IDisposable ' More confusingly , Visual Studio 's definition of the class says that it is n't IDisposable.However , if at run time I do this : Indeed , the cast to IDisposable will succeed , and dispose will get called.I think the issue is because the reference assembly in C : \Program Files ( x86 ) \Reference Assemblies\Microsoft\Framework.NETFramework\v4.5.1 does not implement IDisposable even though the actual assembly used at run time does.Is there a way I can cleanly dispose of an X509Chain without having to do the try/finally and cast myself , i.e . can I get it working in a using statement ? I suppose I could wrap the class myself , but I 'd prefer not to introduce a new type , I 'd rather get the compiler to do the work for me.It appears that the reference assembly has the same issue in 4.5.2 , however it is fixed in 4.6 , but moving to 4.6 is not on the radar right now . using ( var chain = new X509Chain ( ) ) { } var chain = new X509Chain ( ) ; try { } finally { var disposable = chain as IDisposable ; if ( disposable ! = null ) { disposable.Dispose ( ) ; } }",Disposing of X509Chain "C_sharp : Just want to be sure that I have n't been coding for too long ... But , this seems highly unlikely : http : //i.imgur.com/TBjpNTX.pngI create the var , check for null , return if it is , so there 's no way I can see it as being null at that point : ) Resharper bug ? Edit : As per Igal Tabachnik answer , he 's right , I 'm using the following method extension : I find it much easier to readrather than the : Solution : Igal Tabachnik was right . The only 2 missing pieces were : Resharper - > Options - > Code Annotations ( under Code inspection group ) - > turn on for solution.Give VS a couple of minutes to get refresh everything . public static bool IsNullOrEmpty ( this string target ) { return String.IsNullOrEmpty ( target ) ; } if ( some_string.IsNullOrEmpty ( ) ) // do something here if ( string.IsNullOrEmpty ( some_string ) ) // do something here",Resharper warns about a null string ( System.NullReferenceException ) "C_sharp : Problem Context I have written an application in C # which uses a MySqlConnector . I 've added MySql.Data.dll ( Version 6.9.3.0 ) to the References - this all works as expected on my PC ( running Windows 7 ) . However , starting with recent builds , when I try to run the application on another PC ( running Windows XP ) , it throws an Exception on startup . I added an UnhandledExceptionEventHandler which shows the error Could not load file or assembly 'MySql.Data , Version 6.8.3.0 . ( ... etc ... ) ' or one of its dependencies . The located assembly 's manifest description does not match the assembly reference . File name : 'MySql.Data , Version=6.8.3.0 , ( ... etc ... ) .Obviously it is looking for Version 6.8.3.0 but only finding Version 6.9.3.0 in the References - but what I want to know is why it is looking for this version when it worked correctly with earlier builds , and how I can specify which version of MySql to look for . I know I could just add another reference to the earlier version of the .dll , but I want to understand why this is happening . Steps taken to attempt to diagnose the problem Checked the project 's References after seeing this question on Stack Overflow and confirming that a reference to MySql.Data.dll has been added to the project , along with its version ( 6.9.3.0 ) .Searched for results relating to the Exception error message and found this article on Stack Overflow describing its cause ( which I was aware of , but it confirms it ) A colleague asked me to confirm that the SpecificVersion property of the MySql.Data Reference is set to False ( it is ) .Tried adding an assembly binding to the config as suggested in an answer below - it does not help , the same error is thrown.Replaced the MySqlData.dll on the other PC with version 6.8.3.0 as a 'dirty fix ' to see what happened . It now throws the same error as before , but for missing 6.9.3.0.Asked a colleague to run the application on his ( Windows 7 ) PC - no error was generated and it worked as expected . I tried using the Dependency Walker utility on the .exe as a commenter suggested but it only showed the following .dlls missing - IESHIMS.DLL ( on both PCs ) , WER.DLL ( on the XP PC ) , and GPSVC.DLL ( on my PC ) . There was nothing about MySql.Data.dll . ( Though I have since learned this is not a useful tool in this case - see this question . ) On a whim , I decided to change the SpecificVersion property of MySql.Data Reference to True - this fixes the problem.Additional InformationMy app.config file - < ? xml version= '' 1.0 '' ? > < configuration > < startup > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.0 , Profile=Client '' / > < /startup > < /configuration >",DLL Hell - My application throws an error if Version 6.9.3.0 OR 6.8.3.0 of MySql.Data.dll is missing "C_sharp : I am very new to this , so bear with me.I have a MVC app using Service/Repository/EF4 pattern and I am trying to use Ninject . I have it working on the controllers , they are constructor injected with services , but the services are constructor injected with repositories and I am not sure where to handle this.I am trying to make it so each layer only knows about the layer below , is that correct ? If so , the MVC app only knows of the Service Layer , and the Service Layer only knows about the Repository Layer , etc . So in my Ninject Module where I am creating the bindings , I can not say : Where do I handle the injection at ? Bind ( Of IRepository ( Of Category ) ) .To ( Of EFRepository ( Of Category ) )",Dependency Injection "C_sharp : I have been saddled with using an in-house data access library that is effectively XML passed to a stored procedure , which returns XML . There is nothing I can do about this . I tried to get ActiveRecord approved , but my request was declined . However , using the excellent code provided at http : //blog.bodurov.com/Post.aspx ? postID=27 , I added an extension method to IEnumerable that converts the key-value pairs I make out of the ragged XML coming back into strongly typed objects , complete with property names ! This : becomesNow the interface supports databinding ! Pretty cool ! I 'd like to take it a step further , though . I want the objects emitted to have Save ( ) methods too , so that I can ape the ActiveRecord pattern and provide my web guys with an intuitive object layer to use from ASP.net.How do I write a method in Visual Studio , in source code , and attach it at runtime to the emitted objects ? I am not interested in ( or qualified for ) writing assembly or IL . I 'd like to do this in C # . This is my first StackOverflow question and I am posting this with company-mandated IE6 , so please be gentle . dict [ `` keyName1 '' ] MyObject.keyName1",How do I attach a method to a dynamically-created C # type at runtime ? "C_sharp : I 've been asked to look into creating a simple iterative application with Unity . This application has 2 major functions regarding the camera.LERP-ing the camera to focus on a target object.Once moved relinquish control to the user and allow the user to rotate and zoom around the object.I 'm new to this but I 've managed to create two scripts that achieve these goals in isolation . Now I 'm struggling to fit them together.I 'll start with the relevant code for user interaction.First , I use TouchKit to set the delta values on each frame this is in Start.And on Update : This works beautifully and does exactly what I want . The problem comes when I try to integrate this code with my camera moving script . This shows where I want to add the Update codeThese are the functions that actually move the camera : I think what I need to do ( and I may be wrong on this ) is set rotateDistance to be the difference between the currentTarget in the second script and currentTarget in the first script.Thank you in advance , it 's quite a tricky one for me . // set the delta on each frame for horizontal and vertical rotationvar oneTouch = new TKPanRecognizer ( ) ; oneTouch.gestureRecognizedEvent += ( r ) = > { HorizontalDelta += r.deltaTranslation.x * rotateSpeed * Time.deltaTime ; VerticalDelta -= r.deltaTranslation.y * rotateSpeed * Time.deltaTime ; } ; // do the same for pinchvar pinch = new TKPinchRecognizer ( ) ; pinch.gestureRecognizedEvent += ( r ) = > { rotateDistance -= r.deltaScale * 200.0f * Time.deltaTime ; } ; TouchKit.addGestureRecognizer ( oneTouch ) ; TouchKit.addGestureRecognizer ( pinch ) ; VerticalDelta = Mathf.Clamp ( VerticalDelta , verticalPivotMin , verticalPivotMax ) ; var direction = GetDirection ( HorizontalDelta , VerticalDelta ) ; var currentTarget = targetsSwitched ? target2 : target ; transform.position = currentTarget.position - direction * rotateDistance ; transform.LookAt ( currentTarget.position ) ; // ... private Vector3 GetDirection ( float x , float y ) { Quaternion q = Quaternion.Euler ( y , x , 0 ) ; return q * Vector3.forward ; } void Update ( ) { if ( currentlyMoving ) { FocusTarget ( currentTarget ) ; } else { // accept user input if not moving if ( Input.GetKeyDown ( KeyCode.Space ) ) { SetMoveToTarget ( mainTargetObject ) ; } if ( Input.GetKeyDown ( KeyCode.Q ) ) { SetMoveToTarget ( subTargetObject1 ) ; } if ( Input.GetKeyDown ( KeyCode.E ) ) { SetMoveToTarget ( subTargetObject2 ) ; } } } void SetMoveToTarget ( GameObject target ) { if ( currentlyMoving == false ) { currentlyMoving = true ; fromRotation = currentTarget.transform.rotation ; currentTarget = target ; toRotation = currentTarget.transform.rotation ; timeStartedLerping = Time.time ; } } void FocusTarget ( GameObject target ) { float timeSinceStarted = Time.time - timeStartedLerping ; float percentageComplete = timeSinceStarted / ( lerpSpeed ) ; transform.position = Vector3.MoveTowards ( transform.position , target.transform.position , moveSpeed * Time.deltaTime ) ; transform.rotation = Quaternion.Lerp ( fromRotation , toRotation , Mathf.Pow ( percentageComplete , ( float ) 1.2 ) ) ; if ( Vector3.Distance ( transform.position , target.transform.position ) < 0.1 & & percentageComplete > 0.99 ) { transform.position = target.transform.position ; transform.rotation = target.transform.rotation ; currentlyMoving = false ; } }",Combine camera pan to with touch controls in Unity C_sharp : What 's the difference between these two ways to add something ? And private string abc = > `` def '' ; private string abc = `` def '' ;,What is the difference between = and = > for a variable ? "C_sharp : I have changed my previous code so I am not using 'using ' . It work earlier , and code in different class basically represent the same thing , but its working.I have stared at it for 2 hours now and I just ca n't figure out where the problems might be.I have only one reader but each time I am using DisplayFileContent method I am getting the error : Error : There is already an open DataReader associated with this command which must be closed first . // May be public so we can display// content of file from different forms.public void DisplayFileContent ( string filePath ) { // Counting all entries . int countEntries = 0 ; // Encrypting/Decrypting data . EncryptDecrypt security = new EncryptDecrypt ( ) ; using ( OleDbConnection connection = new OleDbConnection ( ) ) { connection.ConnectionString = `` Provider=Microsoft.ACE.OLEDB.12.0 ; '' + `` Data Source= '' + filePath + `` ; '' + `` Persist Security Info=False ; '' + `` Jet OLEDB : Database Password= '' + hashPhrase.ShortHash ( storedAuth.Password ) + `` ; '' ; using ( OleDbCommand command = new OleDbCommand ( `` Select * FROM PersonalData '' , connection ) ) { OleDbDataReader read ; try { // Open database connection . connection.Open ( ) ; // Create a data reader . read = command.ExecuteReader ( ) ; // Clearing the textbox before proceeding . txtDisplay.Text = string.Empty ; // Checking if there is any data in the file . if ( read.HasRows ) { // Reading information from the file . while ( read.Read ( ) ) { // Count all entries read from the reader . countEntries++ ; // Reading all values from the file as string . // While each string is encrypted , we must decrypt them . // User name and password is the same as user provided // while authentication . txtDisplay.Text += `` === Entry ID : `` + read.GetValue ( 0 ) + `` === '' + Environment.NewLine ; txtDisplay.Text += `` Type : `` + security.Decrypt ( read.GetString ( 1 ) , storedAuth.Password , storedAuth.UserName ) + Environment.NewLine ; if ( ! read.IsDBNull ( 2 ) ) txtDisplay.Text += `` URL : `` + security.Decrypt ( read.GetString ( 2 ) , storedAuth.Password , storedAuth.UserName ) + Environment.NewLine ; if ( ! read.IsDBNull ( 3 ) ) txtDisplay.Text += `` Software Name : `` + security.Decrypt ( read.GetString ( 3 ) , storedAuth.Password , storedAuth.UserName ) + Environment.NewLine ; if ( ! read.IsDBNull ( 4 ) ) txtDisplay.Text += `` Serial Code : `` + security.Decrypt ( read.GetString ( 4 ) , storedAuth.Password , storedAuth.UserName ) + Environment.NewLine ; if ( ! read.IsDBNull ( 5 ) ) txtDisplay.Text += `` User Name : `` + security.Decrypt ( read.GetString ( 5 ) , storedAuth.Password , storedAuth.UserName ) + Environment.NewLine ; if ( ! read.IsDBNull ( 6 ) ) txtDisplay.Text += `` Password : `` + security.Decrypt ( read.GetString ( 6 ) , storedAuth.Password , storedAuth.UserName ) + Environment.NewLine ; txtDisplay.Text += Environment.NewLine ; } } else { txtDisplay.Text = `` There is nothing to display ! `` + `` You must add something before so I can display anything here . `` ; } // Displaying number of entries in the status bar . tsslStatus.Text = `` A total of `` + countEntries + `` entries . `` ; // Selecting 0 character to make sure text // is n't completly selected . txtDisplay.SelectionStart = 0 ; command.ExecuteNonQuery ( ) ; } catch ( Exception ex ) { MessageBox.Show ( `` Error : `` + ex.Message ) ; } } } }","I did n't close previous DataReader , but where ?" "C_sharp : I am defining a Color from argb , exIn visual studio 2012 , winRT application it says that this is tagged with [ security critical ] . Are there any reasons why ? I tried searching , no results . And no idea why this relates to security.Update : Now I notice , not only does FromArgb ( ... ) ; methods gives this [ SECURITY CRITICAL ] warning . any of these : Also does . Color.FromArgb ( 255,255,0,0 ) ; c.A = 255 ; c.R = 255 ; c.G = 0 ; c.B = 0 ;",Color.FromArgb ( ... ) ; security message "C_sharp : I 'm trying to add a ProfileProperty into the ProfileProperties table using ObjectContext.AddObject.The db fields for the ProfileProperties table are : The db fields for the ProfilePropertyDefinitions table are : The variables for the ProfileProperty object passed in are : The ProfilePropertyDefinitionID and UserID both are foreign keys , so after creating the ProfileProperty object I select the User and the ProfilePropertyDefinition from their tables to fill the ProfileProperty with the related objects . Then , when I try to AddObject , passing in an object with those variables I get an error : InnerException = { `` Can not insert the value NULL into column 'PropertyName ' , table 'mydbserver.dbo.ProfilePropertyDefinitions ' ; column does not allow nulls . INSERT fails.\r\nThe statement has been terminated . `` } I did a break to check to see what the object I passed in was holding and it has this : QuestionsWhy is saying that the PropertyName is null when it 's there ? Why is it trying to add the ProfilePropertyDefinition object into the ProfilePropertyDefinitions table in the first place ? ( I do n't want it to add or update related objects ) Service Layer AddProfile ( ) Repository Add ( ) : ProfilePropertyIDProfilePropertyDefinitionIDUserIDPropertyValue ProfilePropertyDefinitionIDPropertyName ProfilePropertyIDProfilePropertyDefinitionUserPropertyValue ProfilePropertyID = -1ProfilePropertyDefinition = { ProfilePropertyDefinitionID = 3 PropertyName = `` First Name '' } User = /*Not going to put details here , but assume the user object is there*/PropertyValue = `` Matt '' public int AddProfile ( ProfilePropertyViewModel property ) { int objId = -1 ; ProfileProperty profile = null ; if ( ValidateProfile ( property ) ) { try { using ( DbTransaction transaction = _profileRepository.BeginTransaction ( ) ) { profile = ProfilePropertyTranslator.ViewToDomain ( property ) ; profile.User = _userRepository.SelectByKey ( UserColumns.UserName , property.UserName ) ; profile.ProfilePropertyDefinitionReference.EntityKey = new EntityKey ( `` GraffytysDBEntities.ProfilePropertyDefinition '' , `` ProfilePropertyDefinitionID '' , property.ProfilePropertyDefinitionID ) ; _profileRepository.Add ( profile ) ; if ( _profileRepository.Save ( ) > = 0 ) { transaction.Commit ( ) ; objId = property.ProfilePropertyId ; } } } catch ( Exception ex ) { throw ex ; } } return objId ; } public void Add ( E entity ) { _ctx.AddObject ( entity.GetType ( ) .Name , entity ) ; }",Having Entity Framework trouble "C_sharp : Lets say I have an object which contains a persons name , and their city of origin.And I have a List with the following entries added.What I 'm looking for is all possible combinations of names , grouped by city.I can do this if I know in advance the number of groups , by using the following codeHowever , this only works if i know the number of groups in advance , and quickly becomes unwieldy as the amount of groups grow larger . I 'm sure that there is an elegant way to do this using LINQ , can anybody shed some light ? public class personDetails { public string City ; public string Name ; } Name CityJohn | LondonJane | LondonTom | New YorkBob | New YorkFred | New York John TomJohn Bob John FredJane TomJane BobJane Fred List < personDetails > personList = new List < personDetails > ( ) ; //populate listvar groupedPersons = personList.GroupBy ( c = > c.City ) ; foreach ( var item1 in groupedPersons [ 0 ] ) { foreach ( var item2 in groupedPersons [ 1 ] ) { Console.WriteLine ( item1.Name + `` `` + item2.Name ) ; } }",Finding combinations of a grouped list using LINQ in c # "C_sharp : I am preparing for a interview question.One of the question is to revert a sentence . Such as `` its a awesome day '' to `` day awesome a its . After this , they asked if there is duplication , can you remove the duplication such as `` I am good , Is he good '' to `` good he is , am I '' . for reversal of the sentence i have written following methodBut i am not getting ideas on removing of duplication.Can i get some help here . public static string reversesentence ( string one ) { StringBuilder builder = new StringBuilder ( ) ; string [ ] split = one.Split ( ' ' ) ; for ( int i = split.Length-1 ; i > = 0 ; i -- ) { builder.Append ( split [ i ] ) ; builder.Append ( `` `` ) ; } return builder.ToString ( ) ; }",Reversal and removing of duplicates in a sentence "C_sharp : Is there a regex ( or any other way ) to check if a numbers in a string is in running sequence ? E.g. , `` 123456 '' will return true '' 456789 '' will return true '' 345678 '' will return true '' 123467 '' will return false '' 901234 '' will return false",How do I check if a number string is in running sequence "C_sharp : I 'm trying to figure out how IFormatProvider and ICustomFormatter work after following Format TimeSpan in DataGridView column on how to customize a TimeSpan in a DataGridView . I 've created a completely custom formatter that always returns `` foo '' regardless of what it is formatting.I 'm using it on Int but I assume it should work on all types as it does n't check the value being passed , it just returns `` foo '' .And I 'm passing it to int.ToString ( ) : What I 'm getting is : While what I was hoping to get is : Edit : I found How to create and use a custom IFormatProvider for DateTime ? and the answers there say that DateTime.ToString ( ) will not accept anything but DateTimeFormatInfo or CultureInfo and an object will be rejected if it 's not of these types even if it implements ICustomFormatter - https : //stackoverflow.com/a/2382481/492336.So my question is then does that hold in all cases of the ToString ( ) methods ? Does it hold also for DataGridView , and in which cases can I pass a truly custom formatter ? class MyFormatter : IFormatProvider , ICustomFormatter { public object GetFormat ( Type formatType ) { Console.WriteLine ( `` GetFormat '' ) ; return this ; } public string Format ( string format , object arg , IFormatProvider formatProvider ) { Console.WriteLine ( `` Format '' ) ; return `` foo '' ; } } int number = 10 ; Console.WriteLine ( number.ToString ( new MyFormatter ( ) ) ) ; GetFormat10 GetFormatFormatfoo",Trying to implement a custom formatter but ICustomFormatter.Format is never called "C_sharp : I 'm just learning about binary and bytes . I understand that 8 bits make up a byte and that a byte can have 256 possibilities . The thing I am confused about is this : What does 85 or any of the numbers above have to do with binary . There is simply something not fully clicking in my mind . byte [ ] b = new byte [ ] { 85 , 85 , 67 , 75 } ;",What exactly is a byte and what does it have to do with binary ? "C_sharp : I 've been trying to wrap WPF app inside a Windows Universal App , using Desktop Bridge . In order to make the app 's taskbar icon unplated , with transparent background , I followed the instructions that can be found in various blogs and MSDN articles/forums , such as this one.The first commands I 've been executing are these two : These commands were executed in the WPF app 's output folder , where I also put an AppxManifest.xml file , along with the files and folders referenced by it ( such as the Executable file and the Assets ' images in various scales and resolutions ) .From this point , I got two different weird errors : First , If the AppManifest.xml file contains the following section : then the second makepri command will result in the following error message : onecoreuap\base\mrt\tools\indexertool\src\tool\parametermanager.cpp ( :908 ) : error PRI175 : 0x80080204 - onecoreuap\base\mrt\tools\indexertool\src\tool\parametermanager.cpp ( :318 ) : error PRI175 : 0x80080204 - Microsoft ( R ) MakePRI Tool Copyright ( C ) 2013 Microsoft . All rights reserved . error PRI191 : 0x80080204 - Appx manifest not found or is invalid . Please ensure well-formed manifest file is present . Or specify an index name with /in switch.Then if I remove that FirewallRules section , everything seems to run fine - at least on my machine.Second , It does n't always run as expected : when I try to run exactly the same files ( with the fixed version of AppxManifest.xml ) and same commands on a different machine , I get the same error that I used to get in the first machine ( from before removing the FirewallRules section ) .Any idea what could be causing these problems ? What possible differences between the build machines could cause the second problem ? What should I look for ? `` C : \Program Files ( x86 ) \Windows Kits\10\bin\10.0.15063.0\x64\makepri.exe '' createconfig /o /cf priconfig.xml /dq en-US '' C : \Program Files ( x86 ) \Windows Kits\10\bin\10.0.15063.0\x64\makepri.exe '' new /o /pr . /cf priconfig.xml < Extensions > < desktop2 : Extension Category= '' windows.firewallRules '' > < desktop2 : FirewallRules Executable= '' app\MyWpfApp.exe '' > < desktop2 : Rule Direction= '' in '' IPProtocol= '' TCP '' Profile= '' all '' / > < desktop2 : Rule Direction= '' in '' IPProtocol= '' UDP '' Profile= '' all '' / > < /desktop2 : FirewallRules > < /desktop2 : Extension > < /Extensions >",Mysterious error running makepri for Windows Universal App 's Desktop Bridge "C_sharp : I am building a web part to put on Sharepoint My Sites . I need to get the SPUser whose My Site the web part is on . Currently I simply usebut this will not work on my own My Site , and I am not sure it will work all the time either . Request.QueryString [ `` accountname '' ]",Whose My Site am I on ? ( Programmatically ) "C_sharp : I just noticed a strange behavior with overload resolution.Assume that I have the following method : Now , I know that this method will often be called with a small number of explicit arguments , so for convenience I add this overload : Now I try to call these methods : But in both cases , the overload with params is called . I would have expected the IEnumerable < T > overload to be called in the case of a List < T > , because it seems a better match ( at least to me ) .Is this behavior normal ? Could anyone explain it ? I could n't find any clear information about that in MSDN docs ... What are the overload resolution rules involved here ? public static void DoSomething < T > ( IEnumerable < T > items ) { // Whatever // For debugging Console.WriteLine ( `` DoSomething < T > ( IEnumerable < T > items ) '' ) ; } public static void DoSomething < T > ( params T [ ] items ) { // Whatever // For debugging Console.WriteLine ( `` DoSomething < T > ( params T [ ] items ) '' ) ; } var items = new List < string > { `` foo '' , `` bar '' } ; DoSomething ( items ) ; DoSomething ( `` foo '' , `` bar '' ) ;","Overloading , generic type inference and the 'params ' keyword" "C_sharp : Here 's some background . I 'm working on game similar to `` Collapse . '' Blocks fill up at the bottom and when all twelve blocks have been filled they push up on to the playfield . I have a counter called ( intNextSpawn ) that not only tells when to `` push up '' the next row , as well as calculating vectors for the graphics . It resets to 0 when the blocks have been pushed up.I 've added some debug text on the screen to try and see what is happening , but I ca n't seem to hunt down the issue . It almost seems like it is still incrementing the counter while trying to randomize the the block that 's supposed to appear ( things acting out of order ) . I end up getting `` blank '' blocks and it causes some really screwy effects while testing . It gets worse when jack up the speed.I 'm willing to post any additional code that might help . Below are the two main blocks where this is could happening . Is there something I might be doing wrong or may there be a way I can prevent this from happening ( if that 's what it 's doing ) ? Any help would be greatly appreciated.Edit ... The first code block is in the `` Update '' method // Calculate time between spawning bricksfloat spawnTick = fltSpawnSpeed * fltSpawnSpeedModifier ; fltSpawn += elapsed ; if ( fltSpawn > spawnTick ) { // Fetch a new random block . poNextLayer [ intNextSpawn ] = RandomSpawn ( ) ; // Increment counter intNextSpawn++ ; // Max index reached if ( intNextSpawn == 12 ) { // Push the line up . Returns true if lines go over the top . if ( PushLine ( ) ) { gmStateNew = GameState.GameOver ; gmStateOld = GameState.Playing ; } // Game still in play . else { // Reset spawn row to empty bricks . for ( int i = 0 ; i < 12 ; i++ ) poNextLayer [ i ] = new PlayObject ( ObjectType.Brick , PlayColor.Neutral , Vector2.Zero ) ; intNextSpawn = 0 ; // Reset spawn counter . intLines -- ; // One less line to go ... } } fltSpawn -= spawnTick ; } private bool PushLine ( ) { // Go through the playfield top down . for ( int y = 14 ; y > = 0 ; y -- ) { // and left to right for ( int x = 0 ; x < 12 ; x++ ) { // Top row contains an active block ( GameOver ) if ( ( y == 14 ) & & ( poPlayField [ x , y ] .Active ) ) // Stop here return true ; else { // Not bottom row if ( y > 0 ) { // Copy from block below poPlayField [ x , y ] = poPlayField [ x , y - 1 ] ; // Move drawing position up 32px poPlayField [ x , y ] .MoveUp ( ) ; } // Bottom row else { // Copy from spawning row poPlayField [ x , y ] = poNextLayer [ x ] ; // Move drawing position up 32px ( plus 4 more ) poPlayField [ x , y ] .MoveUp ( 4 ) ; // Make the block active ( clickable ) poPlayField [ x , y ] .Active = true ; } } } } // Game still in play . return false ; }",Why does it seem like operations are not being performed in the order of the code ? "C_sharp : I have a string.format issue ... I 'm trying to pass my invoice ID as an arguments to my program ... and the 6th argument always end up with `` - '' no matter what I do ( we must use the ¿ because of an old program ) ... In the end , `` - '' is always added to my formatted result , but only before my IdInvoice ... ( so Id 10 ends up -10 in my Arguments ) now the fun part ... I hardcode some string and ... if I pass -1 instead of an Id , I have -- 1 as a result and If I write `` banana '' ... i get `` -banana '' ... I know I could just build the string otherwise ... but I 'm getting curious as to why it happens . Here 's the screenshot ... EDIT : thats the copy/paste of my codeand thats the copy/paste of my text visualiser result :12346¿fake DB¿false¿myScreenName¿123456¿­Banana¿123456 public static void OpenIdInvoice ( string wdlName , string IdInvoice , Form sender ) { MessageBox.Show ( string.Format ( `` ¿ { 0 } '' , IdInvoice ) ) ; proc.Arguments = string.Format ( `` { 0 } ¿ { 1 } ¿ { 2 } ¿ { 3 } ¿ { 4 } ¿­ { 5 } '' , session.SessionId.ToString ( ) , Session.GetCurrentDatabaseName ( ) , session.Librairie , wdlName , `` '' , IdInvoice ) ; System.Windows.Forms.MessageBox.Show ( proc.Arguments ) ; var proc = new System.Diagnostics.ProcessStartInfo ( `` Achat.exe '' ) ; System.Windows.Forms.MessageBox.Show ( string.Format ( `` ¿ { 0 } '' , args ) ) ; proc.Arguments = string.Format ( @ '' { 0 } ¿ { 1 } ¿ { 2 } ¿ { 3 } ¿ { 4 } ¿­ { 5 } ¿ { 6 } '' , `` 12346 '' , //session.SessionId.ToString ( ) , `` fake DB '' , //Session.GetCurrentDatabaseName ( ) .ToString ( ) , `` false '' , //session.Librairie.ToString ( ) , `` myScreenName '' , //wdl.ToString ( ) , `` 123456 '' , `` Banana '' , `` 123456 '' //args.ToString ( ) , ) ; System.Windows.Forms.MessageBox.Show ( proc.Arguments ) ; System.Windows.Forms.MessageBox.Show ( args ) ;",C # string.format add a `` - '' value ? "C_sharp : I 'm using BitFactory logging , which exposes a bunch of methods like this : I 've got an extension method that makes this a bit nicer for our logging needs : Which just wraps up some common logging operations , and means I can log like : Logging.LogWarning ( `` Something bad happened to the { 0 } . Id was { 1 } '' , foo , bar ) ; But when I only have one string in my params object [ ] , then my extension method wo n't be called , instead the original method will be chosen.Apart from naming my method something else , is there a way I can stop this from happening ? public void LogWarning ( object aCategory , object anObject ) public static void LogWarning ( this CompositeLogger logger , string message = `` '' , params object [ ] parameters )",Force my code to use my extension method "C_sharp : In C # , this is the standard code for invoking an event in a thread-safe way : Where , potentially on another thread , the compiler-generated add method uses Delegate.Combine to create a new multicast delegate instance , which it then sets on the compiler-generated field ( using interlocked compare-exchange ) . ( Note : for the purposes of this question , we do n't care about code that runs in the event subscribers . Assume that it 's thread-safe and robust in the face of removal . ) In my own code , I want to do something similar , along these lines : Where this.memberFoo could be set by another thread . ( It 's just one thread , so I do n't think it needs to be interlocked - but maybe there 's a side-effect here ? ) ( And , obviously , assume that Foo is `` immutable enough '' that we 're not actively modifying it while it is in use on this thread . ) Now I understand the obvious reason that this is thread-safe : reads from reference fields are atomic . Copying to a local ensures we do n't get two different values . ( Apparently only guaranteed from .NET 2.0 , but I assume it 's safe in any sane .NET implementation ? ) But what I do n't understand is : What about the memory occupied by the object instance that is being referenced ? Particularly in regards to cache coherency ? If a `` writer '' thread does this on one CPU : What guarantees that the memory where the new Foo is allocated does n't happen to be in the cache of the CPU the `` reader '' is running on , with uninitialized values ? What ensures that localFoo.baz ( above ) does n't read garbage ? ( And how well guaranteed is this across platforms ? On Mono ? On ARM ? ) And what if the newly created foo happens to come from a pool ? This seems no different , from a memory perspective , to a fresh allocation - but maybe the .NET allocator does some magic to make the first case work ? My thinking , in asking this , is that a memory barrier would be required to ensure - not so much that memory accesses can not be moved around , given the read is dependent - but as a signal to the CPU to flush any cache invalidations.My source for this is Wikipedia , so make of that what you will . ( I might speculate that maybe the interlocked-compare-exchange on the writer thread invalidates the cache on the reader ? Or maybe all reads cause invalidation ? Or pointer dereferences cause invalidation ? I 'm particularly concerned how platform-specific these things sound . ) Update : Just to make it more explicit that the question is about CPU cache invalidation and what guarantees .NET provides ( and how those guarantees might depend on CPU architecture ) : Say we have a reference stored in field Q ( a memory location ) .On CPU A ( writer ) we initialize an object at memory location R , and write a reference to R into QOn CPU B ( reader ) , we dereference field Q , and get back memory location RThen , on CPU B , we read a value from RAssume the GC does not run at any point . Nothing else interesting happens.Question : What prevents R from being in B 's cache , from before A has modified it during initialisation , such that when B reads from R it gets stale values , in spite of it getting a fresh version of Q to know where R is in the first place ? ( Alternate wording : what makes the modification to R visible to CPU B at or before the point that the change to Q is visible to CPU B . ) ( And does this only apply to memory allocated with new , or to any memory ? ) +Note : I 've posted a self-answer here . var handler = SomethingHappened ; if ( handler ! = null ) handler ( this , e ) ; var localFoo = this.memberFoo ; if ( localFoo ! = null ) localFoo.Bar ( localFoo.baz ) ; thing.memberFoo = new Foo ( 1234 ) ; thing.memberFoo = FooPool.Get ( ) .Reset ( 1234 ) ;",Why is the standard C # event invocation pattern thread-safe without a memory barrier or cache invalidation ? What about similar code ? "C_sharp : I need to understand this . There is a big difference between EF5.0 and EF6 . * in TSQL code-generation In my code this is my LINQ - statemantEntityFramework 5.0 generate just a simple and fast TSQL WHERE - statement like this , which is perfectbut EntityFramework 6 . * generate a much complex and slow statementthe field article_EAN17 has a index , too.however EF6 . * takes ages anyway to initialize , BUT is there a way to generate a simple WHERE statement in EF6 . * with attributes or something like this ? I tried string.Equals ( ) , string.Compare ( ) , swaping the parameter , but nothing changed.Why does Entity Framework 6 generate complex SQL queries for simple lookups ? explain the difference , But is there a way to force EF generating simple TSQL . var qry2 = context.viw_overview_1.Where ( i = > i.article_EAN17 == ean ) .Select ( i = > i.article_id ) .Take ( 200 ) ; ... WHERE [ Extent1 ] . [ article_EAN17 ] = @ p__linq__000.0960096ms in SSMS ... WHERE ( ( [ Extent1 ] . [ article_EAN17 ] = @ p__linq__0 ) AND ( NOT ( [ Extent1 ] . [ article_EAN17 ] IS NULL OR @ p__linq__0 IS NULL ) ) ) OR ( ( [ Extent1 ] . [ article_EAN17 ] IS NULL ) AND ( @ p__linq__0 IS NULL ) ) 45.3665362ms in SSMS",EntityFramework LINQToEntities generate weird slow TSQL Where-Clause C_sharp : I am trying to use Approval-Tests but ca n't even run `` Hello World '' . When I run the test I getMy class is : What should I do to make this run and create a file ? Test Name : TestHelloWorldTest FullName : HelloApprovalTests.Class1.TestHelloWorldTest Source : C : \Users\Lassi\Documents\Visual Studio 2015\Projects\HelloApprovalTests\HelloApprovalTests\Class1.cs : line 14Test Outcome : FailedTest Duration : 0:00:00.01Result StackTrace : at ApprovalTests.Namers.UnitTestFrameworkNamer..ctor ( ) at ApprovalTests.Approvals. < .cctor > b__c ( ) at ApprovalTests.Approvals.GetDefaultNamer ( ) at ApprovalTests.Approvals.Verify ( IApprovalWriter writer ) at ApprovalTests.Approvals.Verify ( String text ) at HelloApprovalTests.Class1.TestHelloWorld ( ) in C : \Users\Lassi\Documents\Visual Studio 2015\Projects\HelloApprovalTests\HelloApprovalTests\Class1.cs : line 15Result Message : System.MissingMethodException : Method not found : 'System.Diagnostics.StackTrace ApprovalUtilities.CallStack.Caller.get_StackTrace ( ) ' . using ApprovalTests ; using ApprovalTests.Reporters ; using NUnit.Framework ; namespace HelloApprovalTests { [ TestFixture ] [ UseReporter ( typeof ( DiffReporter ) ) ] public class Class1 { [ Test ] public void TestHelloWorld ( ) { Approvals.Verify ( `` Hello World Welcome to ApprovalTests '' ) ; } } },Approval-Test throws System.MissingMethodException "C_sharp : Basically this has been in my head for a while ... and I 'd like to read your opinionI read the great book from Jon Skeet called : C # in Depth , Second Edition and there 's a recommendation to use something like this when declaring custom events : This declaration will release us from the nullity check statement before firing the event , so instead of this : We can simply call : And our code simply will work.When you declare events like this , the event will be initialized with an empty delegate so we do not have the need to check for null.This is another way to declare events , they are equivalentFor more info : http : //csharpindepth.com/Articles/Chapter2/Events.aspxI just had a discussion with some fellows , at work and we were discussing this topic , they were arguing that sometimes we would have the need to clear all the subscriptions for the event at once , we can simply do that assigning null to the delegate behind and if we want to keep using the same pattern we would have to re-initialize the event with an empty delegate . They were also asking what would happen in a multi-threading scenario , that 's the main reason I placed this questionQuestionI would like to know if there are some hidden implications ( perhaps when using multi-threading ) when declaring events following this pattern vs checking for nullIf I use this patter I 'm effectively removing several if conditions , which result removing jump statements . Would n't this be better in overall performance terms ? Cheers public event Action < string > MyEvent = delegate { } ; if ( this.MyEvent ! = null ) { this.MyEvent ( `` OMG osh '' ) ; } this.MyEvent ( `` OMG osh '' ) ; private Action < string > myDelegate ; public event Action < string > MyEvent { add { this.myDelegate += value ; } remove { this.myDelegate -= value ; } }",Initializeng events vs checking for null "C_sharp : I have a get-only property in C # that returns an IEnumerable . If that property will only ever yield once , then I could define my property like so : But how would I do this with a C # 6 expression-bodied member ? The following approaches do NOT work : returning compiler error CS0103 : `` The name 'yield ' does not exist in the current context '' . Is a yielding expression-bodied member even possible in C # 6 ? How about in C # 7 ? I 'm aware that an IEnumerable member that only returns once looks smelly , but I 'm mainly just curious . I came across this situation while experimenting with the NUnit TestCaseSource API , trying to provide a method that yields only one test case . I could also see this being relevant to Unity developers who want to define an expression-bodied method to be called with StartCoroutine ( ) .Anyway , thanks in advance for your thoughts ! public IEnumerable Derp { get { yield return new SomeObject ( ) ; } } // These definitions do NOT workpublic IEnumerable Derp = > yield return new SomeObject ( ) ; public IEnumerable Derp = > yield new SomeObject ( ) ;",IEnumerable Expression-Bodied Member C # "C_sharp : I have the following client : I am using native-script to build an android app that can log in with Identity Server 4 . What currently happens is that I make a request to IS4 by opening a browser and using all the correct OpenID configuration and I end up on the login screen which then I choose to login with Google . Once on google , I enter my email and password and its all good and then Google tries to send me back to my site but it just hangs ... Its a white page with nothing loaded and its just sits there forever , there are no error messages logged by is4 as far as I can tell.The login part above for nativescript is from OAutho2 library https : //www.npmjs.com/package/nativescript-oauth2I 'm trying to understand would this be a problem on the IS4 or the native Android application . Is the page hanging because it is waiting on the android application to take over having the login have worked ? Mabye the problem is with the RedirectURI Scheme ? The URL it hangs on is as follows : http : //login.mysite.com/connect/authorize ? client_id=nativeapptest & response_type=code & redirect_uri=com.mysite.nativeapp.12365789785256-buv2dwer7jjjjv5fckasdftn367psbrlb % 3A % 2Fhome & scope=openid % 20profile % 20MySite & response_mode=query & stEDIT : Since I 'm running this on the actual server , I ca n't debug it directly , however , I did add logs to see how far the code goes . My logs tell me that the user was logged in by google and my system and my logs also show that ExternalCallback has redirected the page to /connect/authorize/callback ? client_id=nativeapptest & response_type=code & redirect_uri=com.mysite.nativeapp % 3A % 2F % 2Fhome & scope=openid % 20profile % 20MyScope & response_mode=query & state=abcdAt this point , the page hangs.Please note that we changed RedirectUri to com.mysite.nativeapp to help with testing.Lastly , I 'm not sure if it matters , but we are not using https as this is still development phase . new Client { ClientId = `` nativeapptest '' , ClientName = `` Native App Test '' , Enabled = true , RequireClientSecret = false , AllowedGrantTypes = GrantTypes.Code , RedirectUris = { `` com.mysite.nativeapp.12365789785256-buv2dwer7jjjjv5fckasdftn367psbrlb : /home '' } , AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId , IdentityServerConstants.StandardScopes.Profile , `` MyScope '' } , RequirePkce = false , AllowOfflineAccess = true , RequireConsent = false }",Identity Server 4/nativescript Hangs "C_sharp : With the following dataI 'd very much like to find duplicates and get this result : I tried the following codeobviously this did n't work , I can see what is happening above but I 'm not sure how to fix it . string [ ] data = { `` a '' , `` a '' , `` b '' } ; a var a = data.Distinct ( ) .ToList ( ) ; var b = a.Except ( a ) .ToList ( ) ;",Lambda expression to find difference "C_sharp : I was wondering how is is operator implemented in C # .And I have written a simple test program ( nothing special , just for demonstration purposes ) : And looked at the generated IL code : When I look at the documentation it says : Pushes a null reference ( type O ) onto the evaluation stack.for ldnull . Ofcourse , I was n't expecting to see a source code here , but I 'm surprised that there is only a null-check.I thought it may be relevant with compiler optimizations because Derived derives from Base so there is no check the compatibility about the types.then I check out and see that the optimizations are turned off.when I turn on the optimizations there was n't even null-check.So the question is why there is nothing generated about is operator ? why I see only a null-check ? Is it somehow relevant with is operator and I could n't see ? class Base { public void Display ( ) { Console.WriteLine ( `` Base '' ) ; } } class Derived : Base { } class Program { static void Main ( string [ ] args ) { var d = new Derived ( ) ; if ( d is Base ) { var b = ( Base ) d ; d.Display ( ) ; } } } .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 27 ( 0x1b ) .maxstack 2 .locals init ( [ 0 ] class ConsoleApplication1.Derived d , [ 1 ] bool V_1 , [ 2 ] class ConsoleApplication1.Base b ) IL_0000 : nop IL_0001 : newobj instance void ConsoleApplication1.Derived : :.ctor ( ) IL_0006 : stloc.0 // set derived ( d ) IL_0007 : ldloc.0 // load derived IL_0008 : ldnull // push a null reference IL_0009 : ceq // and compare with d ! ? IL_000b : stloc.1 IL_000c : ldloc.1 IL_000d : brtrue.s IL_001a IL_000f : nop IL_0010 : ldloc.0 IL_0011 : stloc.2 IL_0012 : ldloc.0 IL_0013 : callvirt instance void ConsoleApplication1.Base : :Display ( ) IL_0018 : nop IL_0019 : nop IL_001a : ret } // end of method Program : :Main",When I use is operator why there is only a null-check in IL code ? "C_sharp : I 'm trying to upgrade my .NET 4 project to .NETStandard and Core , but unable to find the equivalent for this : -GetConstructors is a part of reflection , so seems like the support is intentionally lacking or moving ... Thanks.Simon . var ctors = typeof ( T ) .GetConstructors ( ) ;",What 's the equivalent for getting the list of constructors in .NET Standard / Core ? "C_sharp : My ultimate goal is to iterate through nested properties in a lambda expression and determine if any of the properties are null , but I am having trouble creating a new lambda expression based on a member expression.Take this dummy method : On the Compile.exec line I get the following error : variable ' x ' of type 'Blah ' referenced from scope `` , but it is not definedwhere Blah is the type of TModelDetail.How do I build the lambda with the MemberExpression ? What I ultimately want to do is recursively find the root member expression , determine if it is null , and bubble up and determine if each subsequent member expression is null . public static void DoStuff < TModelDetail , TValue > ( Expression < Func < TModelDetail , TValue > > expr , TModelDetail detail ) { var memberExpression = expr.Body as MemberExpression ; if ( memberExpression == null & & expr.Body is UnaryExpression ) { memberExpression = ( ( UnaryExpression ) expr.Body ) .Operand as MemberExpression ; } var pe = Expression.Parameter ( typeof ( TModelDetail ) , `` x '' ) ; var convert = Expression.Convert ( memberExpression , typeof ( object ) ) ; var wee = Expression.Lambda < Func < TModelDetail , object > > ( convert , pe ) ; var hey = wee.Compile ( ) ( detail ) ; }",How do you create a lambda expression from a MemberExpression "C_sharp : I need to group my data by each minute of the day and get the count of the events that occurred during that minute . I currently have : This does what I need , but the problem is that I may not have data points for each minute , how could I add 0 to Count field if I do n't have data for that minute ? Alternatively I could add minute number ( 0 ... 1440 ) and add the missing values later.EDITThe solution currently groups by the starting date only , but that object actually has a field end_date . So basically at the moment I have all the events that started on that minute , but I need to get the count of events that were running at that minute.The data I have contains : At the moment the it does not use the end_date field so the output isI need to have all the events that were running , something like items.GroupBy ( x = > new { x.date.Minute , x.date.Hour } ) .Select ( x = > new TransferObject { Minute = x.Key.Minute , Hour = x.Key.Hour , Count = x.Count ( ) , Day = date } ) .OrderBy ( x = > x.Hour ) .ThenBy ( x = > x.Minute ) .ToList ( ) ; date end_date2015-05-15 09:52:15.650 2015-05-15 09:55:38.0972015-05-15 09:52:15.633 2015-05-15 09:52:16.0972015-05-15 09:52:11.633 2015-05-15 09:52:13.0472015-05-15 09:51:49.097 2015-05-15 09:55:17.6872015-05-15 09:51:49.087 2015-05-15 09:56:17.510 { Count:2 ; Hour:9 ; Minute:51 } { Count:3 ; Hour:9 ; Minute:52 } { Count:2 ; Hour:9 ; Minute:51 } { Count:5 ; Hour:9 ; Minute:52 } { Count:3 ; Hour:9 ; Minute:53 } { Count:3 ; Hour:9 ; Minute:54 } { Count:3 ; Hour:9 ; Minute:55 } { Count:2 ; Hour:9 ; Minute:56 }",C # get minute number from date in linq group by "C_sharp : If I use Select on IQueryable on my entity framework result I 'll get 4 items as a result.If I use Select on an IQueryable.ToList ( ) I get all 36 items.Here 's code of the function : Out of the 36 items 2 Subreddits will be distinct . But since only 4 out of 36 are fetched from Select ( ) it only finds 1 distinct . So is there anything I can do with the LINQ expressions to get correct data so the distinct statement works or do I have to make it into a List before continuing with the Select & Distinct functions ? Edit : by moving the where satement from the end to the start of the whole query.It appears to work correctly now . Select returns all 36 items e.t.c ... which in turn makes the Distinct work since it can find more than 1 unique value . public ImagesGetModelView Get ( int start , int count ) { if ( count < = 0 ) count = 9 ; else if ( count > ImageHandler.MaxResult ) count = ImageHandler.MaxResult ; IQueryable < Image > imagesList = ImagesHandler.FetchRangeScore ( start , count ) .Where ( m = > m.Domain == Database.Enums.ImageDomain.Gfycat ) ; //Works using list : ( //var list = imagesList.ToList ( ) ; //Select all subreddits once //Returns 4 instead of 36 if not using the list ... //Returns 1 instead of 2 with Distinct ( ) if not using the list IEnumerable < Subreddit > subreddits = imagesList .Select ( m = > m.Subreddit ) ; //.Distinct ( ) ; ImagesGetModelView result = new ImagesGetModelView ( ) { Items = imagesList , Subreddits = subreddits } ; return result ; } public IQueryable < Image > FetchRangeScore ( int a_start , int a_count ) { return Repository.AllQueryable ( ) .OrderByDescending ( m = > m.Score ) .Skip ( a_start ) .Take ( a_count ) ; } public IQueryable < Image > FetchRangeScore ( int a_start , int a_count ) { return Repository.AllQueryable ( ) .Where ( m = > m.Domain == Database.Enums.ImageDomain.Gfycat ) .OrderByDescending ( m = > m.Score ) .Skip ( a_start ) .Take ( a_count ) ; }",IQueryable < T > gives different result than a List < T > "C_sharp : I have an app in the store that has been causing me some headaches . My client reported , and I verified , that the app crashes/closes in the following scenario : Launch the appClose the appWait at least ~15 minutesOpen the app The app will close right as the splash screen ends and the extended splash screen starts . It 's unclear what 's causing the issue . The app will keep closing/crashing . The app has to be completely deinstalled and installed again before it starts working again . I 'm only able to reproduce this issue with the store version of the app . I 'm not finding any crash reports in the Event Viewer program . I 've downloaded some crash reports from the dev portal but I do n't think I 'm seeing that crash show up based on the timestamps and frequency of the crashes.Extra Information : I 'm not running any background tasks , or tile updates.I have three sub-questions : What are the good places to look for in the system to find out more about why the app is closing ? Is it possible for me to run a store build on my system so that I can run some tests without having to submit the app to the store each time ? Based on the fact that 1 ) the app runs the first time 2 ) runs any subsequent time when launched within ~15 minutes or the previous launch 3 ) will close itself when running it when the previous launch was > 15 minutes ago 4 ) it only happens in the store build , does anyone have any ideas what could be causing this ? UPDATE : I tried to debug the store version of the app using Visual Studio and all I can see is the following : I guess programs normally exit with code 0 , so something must be wrong . It 's hard to see what the exception thrown is . I tried to break at the exception and step over to see what is causing it but all I got was another exception : I uploaded a version of the app to the store with a built in easter egg allowing me to disabled all code in the extended splash screen . Even all the code disabled it still crashes/closes.UPDATE 2 : The time-frame after which the app starts closing on startup seems to be related to the time it takes the system to hibernate/sleep . Exception thrown at 0x00007FFF54D7A1C8 ( KernelBase.dll ) in App.exe : 0x40080201 : WinRT originate error ( parameters : 0x000000008000000E , 0x000000000000002C , 0x0000006E46EAE9B0 ) .Exception thrown at 0x00007FFF54D7A1C8 ( KernelBase.dll ) in App.exe : 0x40080201 : WinRT originate error ( parameters : 0x000000008000000E , 0x0000000000000046 , 0x0000006E46EAE630 ) .The thread 0x1be8 has exited with code 1 ( 0x1 ) .The thread 0xfa8 has exited with code 1 ( 0x1 ) .The thread 0x115c has exited with code 1 ( 0x1 ) .The thread 0x730 has exited with code 1 ( 0x1 ) .The thread 0xed4 has exited with code 1 ( 0x1 ) .The thread 0x1894 has exited with code 1 ( 0x1 ) .The thread 0x18a0 has exited with code 1 ( 0x1 ) .The thread 0x194c has exited with code 1 ( 0x1 ) .The thread 0x1a3c has exited with code 1 ( 0x1 ) .The thread 0x1988 has exited with code 1 ( 0x1 ) .The thread 0x16ec has exited with code 1 ( 0x1 ) .The thread 0x1584 has exited with code 1 ( 0x1 ) .The thread 0xfd0 has exited with code 1 ( 0x1 ) .The thread 0xd8c has exited with code 1 ( 0x1 ) .The thread 0xcec has exited with code 1 ( 0x1 ) .The thread 0x16b4 has exited with code 1 ( 0x1 ) .The thread 0x12f8 has exited with code 1 ( 0x1 ) .The thread 0x146c has exited with code 1 ( 0x1 ) .The thread 0x36c has exited with code 1 ( 0x1 ) .The thread 0x1854 has exited with code 1 ( 0x1 ) .The thread 0x1ae4 has exited with code 1 ( 0x1 ) .The thread 0xa38 has exited with code 1 ( 0x1 ) .The thread 0x230 has exited with code 1 ( 0x1 ) .The program ' [ 3840 ] App.exe ' has exited with code 1 ( 0x1 ) . Exception thrown at 0x00007FFF54D7A1C8 in App.exe : Microsoft C++ exception : _com_error at memory location 0x000000EE2788E9D0 .",Windows 10 Crash Whodunit "C_sharp : I 'm sure the answer is something obvious , and I 'm kind of embarrassed that I do n't really know the answer already , but consider the following code sample I picked up while reading `` Professional ASP.NET MVC 1.0 '' : I understand what this static method is doing , but what I do n't understand is what purpose the word `` this '' is serving in the method signature . Can anyone enlighten me ? public static class ControllerHelpers { public static void AddRuleViolations ( this ModelStateDictionary modelState , IEnumerable < RuleViolation > errors ) { foreach ( RuleViolation issue in errors ) modelState.AddModelError ( issue.PropertyName , issue.ErrorMessage ) ; } }",What does `` this '' mean when used as a prefix for method parameters ? "C_sharp : I am creating a board game similar to tic tac toe , and I 've created an AI to play that game . The AI is very CPU intensive , so I decided to put it on it 's own thread . I 'm using this plugin to do multithreading : https : //www.assetstore.unity3d.com/en/ # ! /content/15717 .I have this IEnumerator : and I run it usingNormally when I run executeAITurn it works normally without problems , but for some reason sometimes when I run it , it does what it 's supposed to but in task manager my memory just starts to increase by like 30 mb / sec . The memory increases all the way to 1000 mb and the game gets really slow . When I turn off play mode , the memory sometimes continues to increase or just stops where it is . I have to end Unity through task manager to free the memory.One thing I 've tried is replacing foreach loops with regular for loops and that seemed to help . The rate at which the memory was increasing decreased by a lot ( initially it would increase at around 100 mb / sec ) .Any help would be appreciated.Here 's some of the code involved in executeAITurn : mctsManager Class : https : //pastebin.com/yzeHrY2pinput Function : https : //pastebin.com/8f2hzZws static IEnumerator executeAITurn ( Turn turn ) { Vector2 [ ] move = mctsManager.mcts ( new State ( sections , null , turn ) , AIIterations ) [ 0 , 0 ] .metaData.lastMove ; yield return Ninja.JumpToUnity ; input ( move , true ) ; yield return Ninja.JumpBack ; Debug.Log ( `` DONE ! `` ) ; } gameManager.StartCoroutineAsync ( executeAITurn ( ( AITurn == Turn.X ) ? Turn.O : Turn.X ) ) ;",Unity Board Game AI Causing Memory Leak "C_sharp : I am trying to create a route in route table that routes to a virtual item ( using a cms that creates url like example.com/about/company , where there is no physical file called company exists ) using system.web.routing ( unfortunately i can not use iis rewriting/routing ) . I have tried the following but it results in 404 . If I were to point to another physical file ( tor testing purpose ) , the routing works fine . So , is it possible to point to an item like that ? void RegisterRoutes ( RouteCollection routes ) { routes.RouteExistingFiles = true ; routes.MapPageRoute ( `` about '' , `` about/us '' , `` ~/about/company '' , false ) ; }",Routing to virtual item "C_sharp : If I have , for example the following List < int > sWhat is the best way to retrieve the following corresponding List < int ? > s ? { 1 , 2 , 3 , 4 } //list1 { 2 , 3 , 5 , 6 } //list2 ... { 3 , 4 , 5 } //listN { 1 , 2 , 3 , 4 , null , null } //list1 { null , 2 , 3 , null , 5 , 6 } //list2 ... { null , null , 3 , 4 , 5 , null } //listN",Align multiple sorted lists "C_sharp : I 've been trying to experiment with reflection and I have a question.Lets say I have a class , and in this class I have a property initilized with the new feature of c # 6.0Is there any way of getting this value , with reflection , without initilizating the class ? I know I could do this ; But what I want to do is something similiar to this ; I know I could use a field to get the value . But it needs to be a property . Thank you . Class MyClass ( ) { public string SomeProperty { get ; set ; } = `` SomeValue '' ; } var foo= new MyClass ( ) ; var value = foo.GetType ( ) .GetProperty ( `` SomeProperty '' ) .GetValue ( foo ) ; typeof ( MyClass ) .GetProperty ( `` SomeProperty '' ) .GetValue ( ) ;","c # 6.0 and reflection , getting value of Property Initializers" "C_sharp : My co-worker played with TPL and task cancellations . He showed me the following code : This prints `` Canceled '' as expected , but if you just comment while line like this : you 'll get `` Faulted '' . I am well aware about ThrowIfCancellationRequested ( ) method and that I should pass cancellationToken in the constructor of OperationCanceledException ( and this leads to `` Canceled '' result in both cases ) but anyway I ca n't explain why this happens . var cancellationToken = cts.Token ; var task = Task.Run ( ( ) = > { while ( true ) { Thread.Sleep ( 300 ) ; if ( cancellationToken.IsCancellationRequested ) { throw new OperationCanceledException ( ) ; } } } , cancellationToken ) .ContinueWith ( t = > { Console.WriteLine ( t.Status ) ; } ) ; Thread.Sleep ( 200 ) ; cts.Cancel ( ) ; // ..//while ( true ) { Thread.Sleep ( 300 ) ; if ( cancellationToken.IsCancellationRequested ) { throw new OperationCanceledException ( ) ; } } //..",Why throwing OperationCanceledException gets me different results ? "C_sharp : I 've been trying to implement the shallow water equations in Unity , but I 've run in a weird bug . I get these strange oscillating ripples in my water . I made some screenshot : And a video you can find here : https : //www.youtube.com/watch ? v=crXLrvETdjAI based my code on the paper Fast Hydraulic Erosion Simulation and Visualization on GPU by Xing Mei . And you can find the entire solver code here : http : //pastebin.com/JktpizHW ( or see below . ) Each time I use a formula from the paper , I added its number as a comment.I tried different timesteps , for the video I used 0.02 , lowering it just made it oscillate slower . I also tried a bigger grid ( video uses 100 , I tried 200 but then the ripples just were smaller . ) I checked all formulas several times , and ca n't find any error.Anyone here who can figure out what 's going wrong ? Extra info : As you can see from the pastebin , I programmed it in c # . I used Unity as my engine for visualisation , and I 'm just using a grid mesh to visualise the water . I alter the mesh 's vertex y component to match the height I calculate.The DoUpdate method gets a float [ ] [ ] lowerLayersHeight parameter , that 's basically the height of the terrain under the water . In the video it 's just all 0 . public override void DoUpdate ( float dt , float dx , float [ ] [ ] lowerLayersHeight ) { int x , y ; float totalHeight , dhL , dhR , dhT , dhB ; float dt_A_g_l = dt * _A * g / dx ; //all constants for equation 2 float K ; // scaling factor for the outflow flux float dV ; for ( x=1 ; x < = N ; x++ ) { for ( y=1 ; y < = N ; y++ ) { // // 3.2.1 Outflow Flux Computation // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- totalHeight = lowerLayersHeight [ x ] [ y ] + _height [ x ] [ y ] ; dhL = totalHeight - lowerLayersHeight [ x-1 ] [ y ] - _height [ x-1 ] [ y ] ; // ( 3 ) dhR = totalHeight - lowerLayersHeight [ x+1 ] [ y ] - _height [ x+1 ] [ y ] ; dhT = totalHeight - lowerLayersHeight [ x ] [ y+1 ] - _height [ x ] [ y+1 ] ; dhB = totalHeight - lowerLayersHeight [ x ] [ y-1 ] - _height [ x ] [ y-1 ] ; _tempFlux [ x ] [ y ] .left = Mathf.Max ( 0.0f , _flux [ x ] [ y ] .left + dt_A_g_l * dhL ) ; // ( 2 ) _tempFlux [ x ] [ y ] .right = Mathf.Max ( 0.0f , _flux [ x ] [ y ] .right + dt_A_g_l * dhR ) ; _tempFlux [ x ] [ y ] .top = Mathf.Max ( 0.0f , _flux [ x ] [ y ] .top + dt_A_g_l * dhT ) ; _tempFlux [ x ] [ y ] .bottom = Mathf.Max ( 0.0f , _flux [ x ] [ y ] .bottom + dt_A_g_l * dhB ) ; float totalFlux = _tempFlux [ x ] [ y ] .left + _tempFlux [ x ] [ y ] .right + _tempFlux [ x ] [ y ] .top + _tempFlux [ x ] [ y ] .bottom ; if ( totalFlux > 0 ) { K = Mathf.Min ( 1.0f , _height [ x ] [ y ] * dx * dx / totalFlux / dt ) ; // ( 4 ) _tempFlux [ x ] [ y ] .left = K * _tempFlux [ x ] [ y ] .left ; // ( 5 ) _tempFlux [ x ] [ y ] .right = K * _tempFlux [ x ] [ y ] .right ; _tempFlux [ x ] [ y ] .top = K * _tempFlux [ x ] [ y ] .top ; _tempFlux [ x ] [ y ] .bottom = K * _tempFlux [ x ] [ y ] .bottom ; } //swap temp and the real one after the for-loops // // 3.2.2 Water Surface // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- dV = dt * ( //sum in _tempFlux [ x-1 ] [ y ] .right + _tempFlux [ x ] [ y-1 ] .top + _tempFlux [ x+1 ] [ y ] .left + _tempFlux [ x ] [ y+1 ] .bottom //minus sum out - _tempFlux [ x ] [ y ] .right - _tempFlux [ x ] [ y ] .top - _tempFlux [ x ] [ y ] .left - _tempFlux [ x ] [ y ] .bottom ) ; // ( 6 ) _tempHeight [ x ] [ y ] = _height [ x ] [ y ] + dV / ( dx*dx ) ; // ( 7 ) //swap temp and the real one after the for-loops } } Helpers.Swap ( ref _tempFlux , ref _flux ) ; Helpers.Swap ( ref _tempHeight , ref _height ) ; }",Strange oscillating ripples in my shallow water implementation "C_sharp : Automatic properties were added to the language in about .net 3 which create a 'private ' field , anyway , using the code : Is it possible to actually get any sort of reference to this private field ? I want to do something like Without losing this automatic property feature and writing something like public string foo { get ; set ; } public string foo { get { /*some code to check foo for nulls etc*/ } ; set ; } private string _foo = null ; public string foo { get { _foo==null ? _foo= '' hello '' ; return _foo ; } set { _foo=value ; } }",Access automatic property - c # "C_sharp : I have this code to send a HTTP Request : It works well for most calls but one POST where I receive this as response : And when I see the call captured by Fiddler it says the routine received : So , what is happening exactly ? How is that Fiddler sees one response and the applications sees another response ? public string MakeRequest ( string requestUrl , object data ) { HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( requestUrl ) ; request.ContentType = `` application/json '' ; request.KeepAlive = false ; request.Headers.Add ( `` Authorization '' , `` BEARER `` + apiToken ) ; System.Net.ServicePointManager.Expect100Continue = false ; if ( data ! = null ) { request.Method = `` POST '' ; using ( var streamWriter = new StreamWriter ( request.GetRequestStream ( ) ) ) { string json = new JavaScriptSerializer ( ) .Serialize ( data ) ; streamWriter.Write ( json ) ; streamWriter.Flush ( ) ; streamWriter.Close ( ) ; } } else request.Method = `` GET '' ; using ( HttpWebResponse response = request.GetResponse ( ) as HttpWebResponse ) { if ( response.StatusCode ! = HttpStatusCode.OK & & response.StatusCode ! = HttpStatusCode.Created ) throw new Exception ( String.Format ( `` Server error ( HTTP { 0 } : { 1 } ) . `` , response.StatusCode , response.StatusDescription ) ) ; string Charset = response.CharacterSet ; Encoding encoding = Encoding.GetEncoding ( Charset ) ; StreamReader reader = new StreamReader ( response.GetResponseStream ( ) , encoding ) ; return reader.ReadToEnd ( ) ; } } `` �\b\0\0\0\0\0\0�V�M , .I-�/JI-R��V3 < S����L�L , �L��jk [ ��� & \0\0\0 '' { `` MasterOrder '' : { `` OrderId '' : `` 65250824 '' } }",C # - Receiving strange character from HttpWebResponse "C_sharp : There are lots of questions on SO regarding the releasing COM objects and garbage collection but nothing I could find that address this question specifically.When releasing COM objects ( specifically Excel Interop in this case ) , in what order should I be releasing the reference and calling garbage collection ? In some places ( such as here ) I have seen this : And in others ( such as here ) this : Or does n't it matter and I 'm worrying about nothing ? Marshall.FinalReleaseComObject ( obj ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; GC.Collect ( ) ; GC.WaitForPendingFinalizers ( ) ; Marshall.FinalReleaseComObject ( obj ) ;",In what order should one release COM objects and garbage collect ? "C_sharp : Ok , I am an amateur programmer and just wrote this . It gets the job done , but I am wondering how bad it is and what kind of improvements could be made . [ Please note that this is a Chalk extension for Graffiti CMS . ] public string PostsAsSlides ( PostCollection posts , int PostsPerSlide ) { StringBuilder sb = new StringBuilder ( ) ; decimal slides = Math.Round ( ( decimal ) posts.Count / ( decimal ) PostsPerSlide , 3 ) ; int NumberOfSlides = Convert.ToInt32 ( Math.Ceiling ( slides ) ) ; for ( int i = 0 ; i < NumberOfSlides ; i++ ) { int PostCount = 0 ; sb.Append ( `` < div class=\ '' slide\ '' > \n '' ) ; foreach ( Post post in posts.Skip < Post > ( i * PostsPerSlide ) ) { PostCount += 1 ; string CssClass = `` slide-block '' ; if ( PostCount == 1 ) CssClass += `` first '' ; else if ( PostCount == PostsPerSlide ) CssClass += `` last '' ; sb.Append ( string.Format ( `` < div class=\ '' { 0 } \ '' > \n '' , CssClass ) ) ; sb.Append ( string.Format ( `` < a href=\ '' { 0 } \ '' rel=\ '' prettyPhoto [ gallery ] \ '' title=\ '' { 1 } \ '' > < img src=\ '' { 2 } \ '' alt=\ '' { 3 } \ '' / > < /a > \n '' , post.Custom ( `` Large Image '' ) , post.MetaDescription , post.ImageUrl , post.Title ) ) ; sb.Append ( string.Format ( `` < a class=\ '' button-launch-website\ '' href=\ '' { 0 } \ '' target=\ '' _blank\ '' > Launch Website < /a > \n '' , post.Custom ( `` Website Url '' ) ) ) ; sb.Append ( `` < /div > < ! -- .slide-block -- > \n '' ) ; if ( PostCount == PostsPerSlide ) break ; } sb.Append ( `` < /div > < ! -- .slide -- > \n '' ) ; } return sb.ToString ( ) ; }",How Bad is this Code ? "C_sharp : A friend and I ( both new in programming ) were arguing if it was wise to include a Dictionary inside a Class that contains all instances of that class.I say that is better that the dictionary is in the main instead in the class itself.I have no strong reasons to say why , but i 've never seen classes keeping records of the objects that has created.Could you give me pros and cons of each approach ? Thanks in advance.A : B : class Table { public static Dictionary < int , Table > Tables = new Dictionary < int , Table > ( ) ; ... public table ( int ID ) // constructor { ... Tables.Add ( ID , this ) ; } } class Program { public Dictionary < int , Table > Tables = new Dictionary < int , Table > ( ) ; static void Main ( string [ ] args ) { ... Table A = new Table ( 10 ) ; Tables.Add ( 10 , A ) ; } }",List or Dictionary of Objects inside Class "C_sharp : I 'm attempting to download an image in bytes from a server , but the image wo n't display . I get a proper byte array and resize it . It works adding picture from the camera but does n't work when adding them from the internet . I 've confirmed that the image is saved correctly , and downloaded properly as I can copy the byte Array and display it using the byte array string . I found the problem comparing the two methods while debugging , and in the execturepickcommand it triggers my `` ItemSourceChanged '' method but it does n't trigger with the AddImages method . The Collection This works adding the Pictures from this classThen I download the images and put them into the Collection , XamlAnd this is the Control , it is the itemsourcechanged which is what is not triggering . public class ImageGalleryPageModel { public ObservableCollection < ImageModel > Images { get { return images ; } } private ObservableCollection < ImageModel > images = new ObservableCollection < ImageModel > ( ) ; } private async Task ExecutePickCommand ( ) { MediaFile file = await CrossMedia.Current.PickPhotoAsync ( ) ; if ( file == null ) return ; byte [ ] imageAsBytes ; using ( MemoryStream memoryStream = new MemoryStream ( ) ) { file.GetStream ( ) .CopyTo ( memoryStream ) ; file.Dispose ( ) ; imageAsBytes = memoryStream.ToArray ( ) ; } if ( imageAsBytes.Length > 0 ) { IImageResizer resizer = DependencyService.Get < IImageResizer > ( ) ; imageAsBytes = resizer.ResizeImage ( imageAsBytes , 1080 , 1080 ) ; ImageSource imageSource = ImageSource.FromStream ( ( ) = > new MemoryStream ( imageAsBytes ) ) ; Images.Add ( new ImageModel { Source = imageSource , OrgImage = imageAsBytes } ) ; } } private void AddTheImages ( int imageIssueId ) { var imageData = App.Client.GetImage ( imageIssueId ) ; byte [ ] imageAsBytes = imageData.Item1 ; if ( imageAsBytes.Length > 0 ) { IImageResizer resizer = DependencyService.Get < IImageResizer > ( ) ; imageAsBytes = resizer.ResizeImage ( imageAsBytes , 1080 , 1080 ) ; ImageSource imageSource = ImageSource.FromStream ( ( ) = > new MemoryStream ( imageAsBytes ) ) ; ImageGalleryViewModel.Images.Add ( new ImageModel { Source = imageSource , OrgImage = imageAsBytes } ) ; } } < freshMvvm : FreshBaseContentPage NavigationPage.HasNavigationBar= '' False '' xmlns= '' http : //xamarin.com/schemas/2014/forms '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2009/xaml '' xmlns : freshMvvm= '' clr-namespace : FreshMvvm ; assembly=FreshMvvm '' xmlns : converters= '' clr-namespace : ASFT.Converters ; assembly=ASFT '' xmlns : controls= '' clr-namespace : ASFT.Controls ; assembly=ASFT '' x : Class= '' ASFT.Pages.IssuePage '' Padding= '' 4,25,4,4 '' x : Name= '' IssuePages '' > ... < ! -- PictureGallery -- > < Label Text= '' IMAGES '' HorizontalTextAlignment= '' Start '' VerticalTextAlignment= '' Center '' Style= '' { StaticResource Labelfont } '' TextColor= '' White '' / > < Grid BindingContext= '' { Binding ImageGalleryViewModel } '' > < Grid.RowDefinitions > < RowDefinition Height= '' 128 '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < controls : ImageGalleryControl Grid.Row= '' 0 '' ItemsSource= '' { Binding Images } '' > < controls : ImageGalleryControl.ItemTemplate > < DataTemplate > < Image Source= '' { Binding Source } '' Aspect= '' AspectFit '' > < Image.GestureRecognizers > < TapGestureRecognizer Command= '' { Binding Path=BindingContext.PreviewImageCommand , Source= { x : Reference IssuePages } } '' CommandParameter= '' { Binding ImageId } '' / > < /Image.GestureRecognizers > < /Image > < /DataTemplate > < /controls : ImageGalleryControl.ItemTemplate > < /controls : ImageGalleryControl > < Grid Grid.Row= '' 1 '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' * '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < Button Grid.Column= '' 0 '' Text= '' Add photo '' Command= '' { Binding CameraCommand } '' / > < Button Grid.Column= '' 1 '' Text= '' Pick photo '' Command= '' { Binding PickCommand } '' / > < /Grid > < /Grid > < Label Grid.Column= '' 0 '' Grid.Row= '' 3 '' Grid.ColumnSpan= '' 3 '' Text= '' { Binding ImageText } '' HorizontalTextAlignment= '' Center '' VerticalTextAlignment= '' Center '' TextColor= '' White '' / > ... < /freshMvvm : FreshBaseContentPage > private readonly StackLayout imageStack ; public ImageGalleryControl ( ) { this.Orientation = ScrollOrientation.Horizontal ; imageStack = new StackLayout { Orientation = StackOrientation.Horizontal } ; this.Content = imageStack ; } public new IList < View > Children { get { return imageStack.Children ; } } public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create < ImageGalleryControl , IList > ( view = > view.ItemsSource , default ( IList ) , BindingMode.TwoWay , propertyChanging : ( bindableObject , oldValue , newValue ) = > { ( ( ImageGalleryControl ) bindableObject ) .ItemsSourceChanging ( ) ; } , propertyChanged : ( bindableObject , oldValue , newValue ) = > { ( ( ImageGalleryControl ) bindableObject ) .ItemsSourceChanged ( bindableObject , oldValue , newValue ) ; } ) ; public IList ItemsSource { get { return ( IList ) GetValue ( ItemsSourceProperty ) ; } set { SetValue ( ItemsSourceProperty , value ) ; } } private void ItemsSourceChanging ( ) { if ( ItemsSource == null ) return ; } private void CreateNewItem ( IList newItem ) { View view = ( View ) ItemTemplate.CreateContent ( ) ; if ( view is BindableObject bindableObject ) bindableObject.BindingContext = newItem ; imageStack.Children.Add ( view ) ; } private void ItemsSourceChanged ( BindableObject bindable , IList oldValue , IList newValue ) { if ( ItemsSource == null ) return ; if ( newValue is INotifyCollectionChanged notifyCollection ) { notifyCollection.CollectionChanged += ( sender , args ) = > { if ( args.NewItems ! = null ) { if ( args.NewItems.Count > 0 ) { foreach ( object newItem in args.NewItems ) { View view = ( View ) ItemTemplate.CreateContent ( ) ; if ( view is BindableObject bindableObject ) bindableObject.BindingContext = newItem ; imageStack.Children.Add ( view ) ; } } } else { imageStack.Children.Clear ( ) ; foreach ( object item in ItemsSource ) { View view = ( View ) ItemTemplate.CreateContent ( ) ; BindableObject bindableObject = ( BindableObject ) view ; if ( bindableObject ! = null ) bindableObject.BindingContext = item ; imageStack.Children.Add ( view ) ; } } if ( args.OldItems ! = null ) { // not supported } } ; } } public DataTemplate ItemTemplate { get ; set ; } public static readonly BindableProperty SelectedItemProperty = BindableProperty.Create < ImageGalleryControl , object > ( view = > view.SelectedItem , null , BindingMode.TwoWay , propertyChanged : ( bindable , oldValue , newValue ) = > { ( ( ImageGalleryControl ) bindable ) .UpdateSelectedIndex ( ) ; } ) ; public object SelectedItem { get { return GetValue ( SelectedItemProperty ) ; } set { SetValue ( SelectedItemProperty , value ) ; } } private void UpdateSelectedIndex ( ) { if ( SelectedItem == BindingContext ) return ; SelectedIndex = Children .Select ( c = > c.BindingContext ) .ToList ( ) .IndexOf ( SelectedItem ) ; } public static readonly BindableProperty SelectedIndexProperty = BindableProperty.Create < ImageGalleryControl , int > ( carousel = > carousel.SelectedIndex , 0 , BindingMode.TwoWay , propertyChanged : ( bindable , oldValue , newValue ) = > { ( ( ImageGalleryControl ) bindable ) .UpdateSelectedItem ( ) ; } ) ; public int SelectedIndex { get { return ( int ) GetValue ( SelectedIndexProperty ) ; } set { SetValue ( SelectedIndexProperty , value ) ; } } private void UpdateSelectedItem ( ) { SelectedItem = SelectedIndex > -1 ? Children [ SelectedIndex ] .BindingContext : null ; } }",ImageGalleryControl not triggering "C_sharp : I have the following string : aWesdE , which I want to convert to http : //myserver.com/aWesdE.jpg using Regex.Replace ( string , string , string , RegexOptions ) Currently , I use this code : The result is that output is ending up as : http : //myserver.com/aWesdE.jpghttp : //myserver.com/.jpg So , the replacement value shows up correctly , and then appears to be appended again - very strange . What 's going on here ? string input = `` aWesdE '' ; string match = `` ( . * ) '' ; string replacement = `` http : //myserver.com/ $ 1.jpg '' ; string output = Regex.Replace ( input , match , replacement , RegexOptions.IgnoreCase | RegexOptions.Singleline ) ;",Why does my Regex.Replace string contain the replacement value twice ? "C_sharp : I do n't understand the difference between these two implementations of calling SendMailAsync . Much of the time with the first , I 'm receiving a TaskCanceledException , but with the second , everything works as expected.I thought the two consuming methods would be equivalent , but clearly I 'm missing something.This seems related to , but opposite from : TaskCanceledException when not awaitingEDIT : It turns out the Caller2 method was also causing exceptions , I just was n't seeing them due to the WebJobs framework this was being called by . Yuval 's explanation cleared all of this up and is correct . // Common SmtpEmailGateway librarypublic class SmtpEmailGateway : IEmailGateway { public Task SendEmailAsync ( MailMessage mailMessage ) { using ( var smtpClient = new SmtpClient ( ) ) { return smtpClient.SendMailAsync ( mailMessage ) ; } } } // Caller # 1 code - Often throws TaskCanceledExceptionpublic async Task Caller1 ( ) { // setup code here var smtpEmailGateway = new SmtpEmailGateway ( ) ; await smtpEmailGateway.SendEmailAsync ( myMailMessage ) ; } // Caller # 2 code - No problemspublic Task Caller2 ( ) { // setup code here var smtpEmailGateway = new SmtpEmailGateway ( ) ; return smtpEmailGateway.SendEmailAsync ( myMailMessage ) ; }",Cause of TaskCanceledException with SendMailAsync ? "C_sharp : The gist of my code is as follows : Now I want to split the above code into a single IEnumerator method with 2 calls.This is what I came up with : The problem with this is that instead of the beats sounding with their correct interval , both beats sounded at the the same time and because I have these calls in an infinite loop , Unity crashed because the intervals are not being considered.What 's the best way to extract my two repetitive blocks of code above into a single IEnumerator method ? // Play the first beataudio.PlayOneShot ( beat ) ; // Show 1st heartbeat border flashTweenAlpha.Begin ( heartbeatPanel.gameObject , 0.1f , currentStress ) ; yield return new WaitForSeconds ( 0.1f ) ; TweenAlpha.Begin ( heartbeatPanel.gameObject , 0.5f , 0 ) ; yield return new WaitForSeconds ( interval ) ; // Play the second beataudio.PlayOneShot ( beat ) ; // Show 2nd heartbeat border flashTweenAlpha.Begin ( heartbeatPanel.gameObject , 0.1f , currentStress ) ; yield return new WaitForSeconds ( 0.1f ) ; TweenAlpha.Begin ( heartbeatPanel.gameObject , 0.5f , 0 ) ; yield return new WaitForSeconds ( interval * 2 ) ; StartCoroutine ( PlayBeat ( currentStress , interval ) ) ; StartCoroutine ( PlayBeat ( currentStress , interval * 2 ) ) ; // ... IEnumerator PlayBeat ( float currentStress , float interval ) { audio.PlayOneShot ( beat ) ; TweenAlpha.Begin ( heartbeatPanel.gameObject , 0.1f , currentStress ) ; yield return new WaitForSeconds ( 0.1f ) ; TweenAlpha.Begin ( heartbeatPanel.gameObject , 0.5f , 0 ) ; yield return new WaitForSeconds ( interval ) ; }",Having trouble refactoring an IEnumerator method with multiple yields "C_sharp : I have a constructor method similar to this : And I am calling this constructor method like this : But when I debug it , I find that the 002 milliseconds are set to 000 when passed to the default constructor which is a Nullable DateTime parameter.Is it normal that I lose the milliseconds of a DateTime when I pass it as a parameter to a method which takes Nullable DateTime ? public class Foo { public Foo ( DateTime ? startFrom ) { _startFrom = startFrom ; } } var context = new Foo ( new DateTime ( 2012 , 7 , 15 , 11 , 2 , 10 , 2 ) ) ; // 2 miliseconds",Why do I lose milliseconds of a DateTime when it 's passed to a method which takes Nullable DateTime ? "C_sharp : Within the scope of a web application , what are the implications of declaring a method 's accessibility to be public vs. internal ? Web applications typically contain methods used only within the application itself . For example , an ecommerce web site may contain a method to retrieve a user 's order history . Along the lines of : If this method was contained within a class library , the significance of public and internal access modifiers is fairly straightforward ; public methods would be accessible outside of the library itself , internal methods would not.Is there any practical difference when it comes to web applications ? EDIT : My question has been suggested to be a duplicate of What is the difference between Public , Private , Protected , and Nothing ? . I am not asking for an explanation of access modifiers . I am asking whether there is any significance for access modifiers on methods within a web site specifically . public List < Orders > RetrieveOrders ( ) { //code goes here }",Should methods in a web app be public or internal ? "C_sharp : I 'm using a very simple ternary expression in my C # code : In both cases , the functions on each path of the expression return a non-null object , but if I look at the result in the debugger , it is null until I reference it in the code such as using an assert : This only appears to happen if I use an `` x64 '' or `` Any CPU '' platform setting in Debug mode . It 's fine in `` x86 '' mode.I try to be very cautious before assuming I 've found a bug in the compiler or debugger , but I ca n't find any other explanation for this behavior.Here 's a full class to do a repro , just call SomeClass.SomeAction ( ) in the debugger in x64 mode and step through to see it : Am I missing something or is this a bug in the x64 debugger ? I 'm using debug mode so no optimizations should be present . helperClass.SomeData = helperClass.HasData ? GetSomeData ( ) : GetSomeOtherData ( ) ; Debug.Assert ( helperClass.SomeData ! = null ) ; public class SomeClass { public bool HasData ; public object SomeData ; private SomeClass ( ) { HasData = false ; } public static void SomeAction ( ) { var helperClass = new SomeClass ( ) ; // Exhibits weird debugger behavior of having helperClass.SomeData = null after this line : helperClass.SomeData = helperClass.HasData ? GetSomeData ( ) : GetSomeOtherData ( ) ; // Note that trying helperClass.SomeData.ToString ( ) returns a debugger error saying SomeData is null // But this code is just fine //if ( helperClass.HasData ) { // helperClass.SomeData = GetSomeData ( ) ; // } //else { // helperClass.SomeData = GetSomeOtherData ( ) ; // } // In both cases though , after this line things are fine : Debug.Assert ( helperClass.SomeData ! = null ) ; } private static object GetSomeData ( ) { return new object ( ) ; } private static object GetSomeOtherData ( ) { return new object ( ) ; } }",Bizarre ternary operator behavior in debugger on x64 platform "C_sharp : Is it okay to pass parameters , with await ? what are the PROS and CONS of doing this ? var results = MapResults ( await GetDataAsync ( ) ) ;",Best Practice with C # . Is it okay to pass parameters with await ? "C_sharp : I wrote a simple program to test a theory that `` finally '' block will always execute no matter what.But , what i 'm seeing from the below pgm is that control never seems to enter the outer finaly block.I tried doing F5 and also Ctrl-F5 in Visual studio and it 's the same result.Can someone explain why I 'm seeing this behavior ? Output on the console window is : inner catchinner finallyouter catchunhandled exeption : ..and then the app crashes public class Program { static void Main ( ) { try { try { string s = null ; s.ToString ( ) ; } catch { Console.WriteLine ( `` inner catch '' ) ; throw ; } finally { Console.WriteLine ( `` inner finally '' ) ; } return ; } catch { Console.WriteLine ( `` outer catch '' ) ; throw ; } finally { Console.WriteLine ( `` outer finally '' ) ; } } }",Why is outer `` finally '' not being executed when inner `` catch '' throws ? "C_sharp : This is my first time to hear about LINQ and I have no idea about it . Please be gentle on me . I have this set of data.What I need to do is to write a method that returns a list of NodeID . example , My expected results are NodeIDs : 2 and 11 . NodeID = 2 is included because there is a RadioID = R7 that is connected to RadioID = R0 which belongs to NodeID = 1 . NodeID = 11 is also included because RadioID = R11 is connected to Radio = R9 which belongs to NodeID = 2 ( which is also connected to NodeID = 1 ) .I lookup this article but I always get StackOverFlowExceptionRendering a hierarchy using LINQHere 's the full code : You can suggest if there is much better way to do it . Sorry Newbie here . + -- -- -- -- -+ -- -- -- -- + -- -- -- -- -- -- -- -+| RadioID | NodeID | SourceRadioID |+ -- -- -- -- -+ -- -- -- -- + -- -- -- -- -- -- -- -+| R0 | 1 | || R1 | 1 | || R2 | 1 | || R3 | 1 | || R4 | 1 | || R5 | 2 | || R6 | 2 | || R7 | 2 | R0 || R8 | 2 | || R9 | 2 | || R10 | 11 | || R11 | 11 | R9 || R12 | 11 | || R13 | 11 | |+ -- -- -- -- -+ -- -- -- -- + -- -- -- -- -- -- -- -+ List < int > dependentNode = GetChildNode ( 1 ) ; // int ParentNode public class RadioEntity { public string RadioID { get ; set ; } public int NodeID { get ; set ; } public string SourceRadioID { get ; set ; } } public class SampleDemo { public void SampleMethod ( ) { Func < int , int , List < int > > GetChildNode = null ; GetChildNode = ( x , y ) = > { return ( from _x in GetRadio ( ) where ( GetRadio ( ) .Where ( i = > i.NodeID == x ) .Select ( i = > i.RadioID ) ) .Contains ( _x.RadioID ) from _y in new [ ] { _x.NodeID } .Union ( GetChildNode ( _x.NodeID , y + 1 ) ) select _y ) .ToList < int > ( ) ; } ; var _res = GetChildNode ( 1 , 0 ) ; } public List < RadioEntity > GetRadio ( ) { List < RadioEntity > _returnVal = new List < RadioEntity > ( ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R0 '' , NodeID = 1 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R1 '' , NodeID = 1 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R2 '' , NodeID = 1 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R3 '' , NodeID = 1 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R4 '' , NodeID = 1 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R5 '' , NodeID = 2 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R6 '' , NodeID = 2 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R7 '' , NodeID = 2 , SourceRadioID = `` R0 '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R8 '' , NodeID = 2 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R9 '' , NodeID = 2 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R10 '' , NodeID = 11 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R11 '' , NodeID = 11 , SourceRadioID = `` R9 '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R12 '' , NodeID = 11 , SourceRadioID = `` '' } ) ; _returnVal.Add ( new RadioEntity ( ) { RadioID = `` R13 '' , NodeID = 11 , SourceRadioID = `` '' } ) ; return _returnVal ; } }",Get child record using Linq "C_sharp : Is there a generally accepted best approach to coding complex math ? For example : Is this a point where hard-coding the numbers is okay ? Or should each number have a constant associated with it ? Or is there even another way , like storing the calculations in config and invoking them somehow ? There will be a lot of code like this , and I 'm trying to keep it maintainable.Note : The example shown above is just one line . There would be tens or hundreds of these lines of code . And not only could the numbers change , but the formula could as well . double someNumber = .123 + .456 * Math.Pow ( Math.E , .789 * Math.Pow ( ( homeIndex + .22 ) , .012 ) ) ;",Is it okay to hard-code complex math logic inside my code ? "C_sharp : Is there any tools/plugins that can generate `` manual '' mapping code in VS/Resharper.I.e . there are 2 classes ( Foo & Bar ) with the same properties set : Is it possible to generate the following code somehow ? Avoid mapping tools like AutoMapper , EmitMapper , etc . { public string A { get ; set ; } public int B { get ; set ; } public decimal C { get ; set ; } } public Bar Create ( Foo foo ) { var bar = new Bar ( ) ; bar.A = foo.A ; bar.B = foo.B ; bar.C = foo.C ; return bar ; }",How to generate object-object mapping in VS/Resharper "C_sharp : I want to do some async work after Startup.cs is finished . I 've implemented some async tasks in a background service by extending BackgroundService.My question is how to cancel the task from running at a time when I determine ? I can only see examples in the documentation for delaying the next cycle.I 've tried to manually execute StopAsync but the while loop executes forever ( the token is not cancelled , even though I feel like it should be , because I 've passed the token to StopAsync and the implementation looks like that 's what it 's meant to do ) .Here is some simplified code : public class MyBackgroundService : BackgroundService { private readonly ILogger < MyBackgroundService > _logger ; public MyBackgroundService ( ILogger < MyBackgroundService > logger ) { _logger = logger ; } protected override async Task ExecuteAsync ( CancellationToken stoppingToken ) { _logger.LogInformation ( `` MyBackgroundService is starting . `` ) ; while ( ! stoppingToken.IsCancellationRequested ) { _logger.LogInformation ( `` MyBackgroundService task doing background work . `` ) ; var success = await DoOperation ( ) ; if ( ! success ) { // Try again in 5 seconds await Task.Delay ( 5000 , stoppingToken ) ; continue ; } await StopAsync ( stoppingToken ) ; } } }",How can I manually cancel a .NET core IHostedService background task ? "C_sharp : In Windows Phone 8 ( only on device ! ) try running this code : You will see myTrue always is False ! Why ? ! How it can be ? ! UPDATE : Tested on devices : Nokia Lumia 920 , HTC 8X , Nokia Lumia 925 public MainPage ( ) { InitializeComponent ( ) ; var myTrue = GetTrue ( ) ; Debug.WriteLine ( myTrue ) ; // false } [ MethodImpl ( MethodImplOptions.Synchronized ) ] private static bool ? GetTrue ( ) { return true ; }",Why does the Synchronized method always return false ? "C_sharp : I am having a Windows Service that needs to pick the jobs from database and needs to process it.Here , each job is a scanning process that would take approx 10 mins to complete.I am very new to Task Parallel Library . I have implemented in the following way as sample logic : But , this is creating lot of threads . Since loop is repeating 100 times , it is creating 100 threads.Is it right approach to create that many number of parallel threads ? Is there any way to limit the number of threads to 10 ( concurrency level ) ? Queue queue = new Queue ( ) ; for ( int i = 0 ; i < 10000 ; i++ ) { queue.Enqueue ( i ) ; } for ( int i = 0 ; i < 100 ; i++ ) { Task.Factory.StartNew ( ( Object data ) = > { var Objdata = ( Queue ) data ; Console.WriteLine ( Objdata.Dequeue ( ) ) ; Console.WriteLine ( `` The current thread is `` + Thread.CurrentThread.ManagedThreadId ) ; } , queue , TaskCreationOptions.LongRunning ) ; } Console.ReadLine ( ) ;",Is it the correct implementation ? "C_sharp : Reading this question , I wanted to test if I could demonstrate the non-atomicity of reads and writes on a type for which the atomicity of such operations is not guaranteed.To my surprise , the assertion refused to fail even after a full three minutes of execution.What gives ? The test is incorrect.The specific timing characteristics of the test make it unlikely/impossible that the assertion will fail.The probability is so low that I have to run the test for much longer to make it likely that it will trigger.The CLR provides stronger guarantees about atomicity than the C # spec.My OS/hardware provides stronger guarantees than the CLR.Something else ? Of course , I do n't intend to rely on any behaviour that is not explicitly guaranteed by the spec , but I would like a deeper understanding of the issue.FYI , I ran this on both Debug and Release ( changing Debug.Assert to if ( .. ) throw ) profiles in two separate environments : Windows 7 64-bit + .NET 3.5 SP1Windows XP 32-bit + .NET 2.0EDIT : To exclude the possibility of John Kugelman 's comment `` the debugger is not Schrodinger-safe '' being the problem , I added the line someList.Add ( dCopy ) ; to the KeepReading method and verified that this list was not seeing a single stale value from the cache.EDIT : Based on Dan Bryant 's suggestion : Using long instead of double breaks it virtually instantly . private static double _d ; [ STAThread ] static void Main ( ) { new Thread ( KeepMutating ) .Start ( ) ; KeepReading ( ) ; } private static void KeepReading ( ) { while ( true ) { double dCopy = _d ; // In release : if ( ... ) throw ... Debug.Assert ( dCopy == 0D || dCopy == double.MaxValue ) ; // Never fails } } private static void KeepMutating ( ) { Random rand = new Random ( ) ; while ( true ) { _d = rand.Next ( 2 ) == 0 ? 0D : double.MaxValue ; } }",Why does n't this code demonstrate the non-atomicity of reads/writes ? "C_sharp : I have created a few DropDownLists that get populated with data from a database . The first lines of the Dropdownlists are ListItem : I also have a GridView that has a RowCommand event on Select button.When I press Select the DropDownLists will get back whatever value that the respected column/row has : This works when Change Request column/row in the GridView has value but not when it 's `` white-space '' / `` Empty '' / `` Null '' . I do not really know how to fix it ? I would like to be able to do something like : However I would only want this in the background because I would like to have empty row in GridView but on RowCommand Select should understand that empty means ListItem value.Is this possible ? < asp : DropDownList ID= '' ddlChange_Requestor '' runat= '' server '' AppendDataBoundItems= '' True '' CssClass= '' ddlChange_Requestor '' > < asp : ListItem > Change Requestor < /asp : ListItem > protected void gwActivity_RowCommand ( object sender , GridViewCommandEventArgs e ) { { GridViewRow row = ( ( e.CommandSource as Control ) .NamingContainer as GridViewRow ) ; txtActivity.Text = row.Cells [ 2 ] .Text ; ddlChange_Requestor.SelectedValue = row.Cells [ 10 ] .Text ; } } ddlChange_Requestor.SelectedValue = isnullOrwhitespace ( row.Cells [ 10 ] .Text , `` Change Requestor '' ) ;",Gridview RowCommand event with DropDownList is not working "C_sharp : I 've created a custom struct to represent an amount . It is basically a wrapper around decimal . It has an implicit conversion operator to cast it back to decimal.In my unit test , I assert that the Amount equals the original decimal value , but the test fails.When I use an int though ( for which I did not create a conversion operator ) , the test does succeed.When I hover the AreEqual , it shows that the first one resolves toand the second one leads toIt looks like the int value 1 is implicitly cast to an Amount , while the decimal value 1.5M is not.I do n't understand why this happens . I would 've expected just the opposite . The first unit test should be able to cast the decimal to an Amount.When I add an implicit cast to int ( which would n't make sense ) , the second unit test also fails . So adding an implicit cast operator breaks the unit test.I have two questions : What is the explanation for this behavior ? How can I fix the Amount struct so both tests will succeed ? ( I know I could change the test to do an explicit conversion , but if I do n't absolutely have to , I wo n't ) My Amount struct ( just a minimal implementation to show the problem ) [ TestMethod ] public void AmountAndDecimal_AreEqual ( ) { Amount amount = 1.5M ; Assert.AreEqual ( 1.5M , amount ) ; } [ TestMethod ] public void AmountAndInt_AreEqual ( ) { Amount amount = 1 ; Assert.AreEqual ( 1 , amount ) ; } public static void AreEqual ( object expected , object actual ) ; public static void AreEqual < T > ( T expected , T actual ) ; public struct Amount { private readonly decimal _value ; private Amount ( decimal value ) { _value = value ; } public static implicit operator Amount ( decimal value ) { return new Amount ( value ) ; } public static implicit operator decimal ( Amount amount ) { return amount._value ; } }",Why does Assert.AreEqual on custom struct with implicit conversion operator fail ? "C_sharp : When using ValueTuple and dynamic object , I received this weird CS8133 error . I am passing dynamic object as input and taking ValueTuple as output . Why are they affecting each other . Edit : The error message is : CS8133 Can not deconstruct dynamic objects public static ( string , string ) foo ( dynamic input ) { return ( `` '' , `` '' ) ; } public void foo_test ( ) { dynamic input = new { a = `` '' , b = `` '' } ; ( string v1 , string v2 ) = foo ( new { a = `` '' , b = `` '' } ) ; //compiles fine ( string v3 , string v4 ) = foo ( input ) ; //CS8133 Can not deconstruct dynamic objects var result = foo ( input ) ; //compiles fine }",Why this compiler error when mixing C # ValueTuple and dynamic "C_sharp : I have model with property : And I have ValueResolverThen I configure mappingBut it says me thatWhat I should to do to make it work ? public class MyModel { public SelectList PropertyTypeList { get ; set ; } } public class MyPropertyValueResolver : ValueResolver < ProductProperty , SelectList > { protected override SelectList ResolveCore ( ProductProperty source ) { myList = ... ... . ; return new SelectList ( myList , `` Value '' , `` Text '' ) ; } } Mapper.CreateMap < Source , Destination > ( ) .ForMember ( s = > s.PropertyTypeList , opt = > opt.ResolveUsing < MyPropertyValueResolver > ( ) ) ; Type 'System.Web.Mvc.SelectList ' does not have a default constructor",How to use ValueResolver if field type does not have a default constructor ? "C_sharp : After creating a new blazor component i get this error : Is it a bug with auto generation or something ? How can i fix it in blazor ? It appears very often and i have no idea why . Blazor is pretty new framework , can somebody defeated this problem ? Thank you in advance ! The namespace 'Razor ' already contains a definition for 'Template '",How to fix blazor error `` The namespace 'Razor ' already contains a definition for 'Template ' `` "C_sharp : Technology Stack : .NET 4 , C # , NUnitI am attempting to apply test driven development to a new project that performs image processing . I have a base class that contains shared file I/O methods and subclasses that perform various specific processing algorithms . As I understand it , unit tests do not touch the file system or other objects , and mock behavior where that occurs . My base class only contains simple accessors and straightforward file system I/O calls.Is there any value in testing these methods ? If so , how could I abstract away the calls to the file system ? My other question is how to test the subclass which is specific to a type of image file ( ~200 MB ) . I have searched the site and found similar questions , but none dealing with the file sizes I am working with on this project . Is it plausible for a class to have integration tests ( using a `` golden file '' ) , but no unit tests ? How could I strictly follow TDD methods and first write a failing test in this case ? public class BaseFile { public String Path { get ; set ; } public BaseFile ( ) { Path = String.Empty ; } public BaseFile ( String path ) { if ( ! File.Exists ( path ) ) { throw new FileNotFoundException ( `` File not found . `` , path ) ; } Path = path ; } }","TDD : Is it plausible to have integration tests , but no unit tests ?" "C_sharp : The title pretty much says it all . Some caveats are : I need to be able to do it in C # It needs to be able to be done from a remote server ( ie , running on one server , checking IIS on another ) Needs to be close to real-time ( within 1 second ) Can use WMI callsI 've tried watching the log file , but it turns out that is n't nearly close enough to real-time.Thanks ! EDIT : I put this in a comment on Tom 's answer , but it 's more visible here : I was able to look for changes using this counter : var perf = new PerformanceCounter ( `` ASP.NET Apps v2.0.50727 '' , `` Requests Total '' , `` _LM_W3SVC_ [ IIS-Site-ID ] _ROOT '' , `` [ Server-Name ] '' ) ;",How can I programatically determine if an IIS site is receiving requests ? "C_sharp : BackgroundTo help improve my understanding of IOC and how to use it , I want to create an example of all three IOC techniques : Constructor injection , Setter injection , and Interface injection without having to use a third party framework . I think I have a basic example of constructor injection , but struggling with setter and interface injection . My QuestionHow would you approach tackling writing interface and setter injection from the ground up ? Here 's my thoughts , let me know if I 'm on the right track . Interface injection : Loop through resolved objects instantiated using constructor injection , check to see what interfaces are implemented in interfaceDependencyMapDefine some sort of interfaceDependencyMap to associate an interface to the implementation.Resolve the implementation using interfaceDependencyMapAssign the appropriate property to the object initialized with constructor injectionSetter injection : Loop through resolved objects instantiated using constructor injectionDefine some sort of setterInjectionMapResolve the expected parameter from MethodInfo using the constructor mappingsCall the setter method passing in the resolved parameter objectHere 's what I have so far for constructor injection public class Program { static void Main ( string [ ] args ) { // //instead of doing this : // //ICreditCard creditCard = new Visa ( ) ; //var customer = new Customer ( creditCard ) ; //customer.Charge ( ) ; var resolver = new Resolver ( ) ; //map the types in the container resolver.Register < Customer , Customer > ( ) ; resolver.Register < ICreditCard , Visa > ( ) ; //because the customer constructor has an ICreditCard parameter //our container will automatically instantiate it recursively var customer = resolver.Resolve < Customer > ( ) ; customer.Charge ( ) ; } } public interface ICreditCard { string Charge ( ) ; } public class Visa : ICreditCard { public string Charge ( ) { return `` Charging Visa '' ; } } public class MasterCard : ICreditCard { public string Charge ( ) { return `` Charging MasterCard '' ; } } public class Customer { private readonly ICreditCard _creditCard ; public Customer ( ICreditCard creditCard ) { this._creditCard = creditCard ; } public void Charge ( ) { _creditCard.Charge ( ) ; } } public class Resolver { private Dictionary < Type , Type > dependencyMap = new Dictionary < Type , Type > ( ) ; public T Resolve < T > ( ) { return ( T ) Resolve ( typeof ( T ) ) ; } private object Resolve ( Type typeToResolve ) { Type resolvedType = null ; try { resolvedType = dependencyMap [ typeToResolve ] ; } catch { throw new Exception ( string.Format ( `` could not resolve type { 0 } '' , typeToResolve.FullName ) ) ; } var firstConstructor = resolvedType.GetConstructors ( ) .First ( ) ; var constructorParameters = firstConstructor.GetParameters ( ) ; if ( constructorParameters.Count ( ) == 0 ) return Activator.CreateInstance ( resolvedType ) ; IList < object > parameters = constructorParameters.Select ( parameterToResolve = > Resolve ( parameterToResolve.ParameterType ) ) .ToList ( ) ; return firstConstructor.Invoke ( parameters.ToArray ( ) ) ; } public void Register < TFrom , TTo > ( ) { dependencyMap.Add ( typeof ( TFrom ) , typeof ( TTo ) ) ; } }",Custom IOC container - need help on 2/3 types "C_sharp : This is not a duplicate ! - Well , after reading the comments , maybe it is.I was looking for a way to italicize text in the console output of a console application , in c # , Visual Studio 2015 , Targeting .NET Framework 4.5.2 , OS = Windows 7 . The Microsoft Documentation is pretty clearIt 's here - and it 's so misleading it 's wrong . This is an OS problem . I found the following question with a solution that does what I want by Vladimir Reshetnikov , adding text decorations to console outputanswered Mar 28 at 19:52 in one of the answers , and code like it in git , and elsewhere ... my problem is - naturally - it does n't work for me.I copied the author 's code with minor mods into the following console applicationand I get the VT commands in the window , instead of underline , as in the article.Here 's my console window : I 've trapped the return value from ConsoleSetMode - it 's zero . I 've seen this failure with lasterror = 6 , but the lasterror here is 0.Think it 's a recent update ? ... or something ? [ edit ] It 's a Windows version problem - Windows 10 AU , apparently , is required . using System ; using System.Runtime.InteropServices ; namespace ConsoleApplication1 { class Program { const int STD_OUTPUT_HANDLE = -11 ; const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4 ; [ DllImport ( `` kernel32.dll '' , SetLastError = true ) ] static extern IntPtr GetStdHandle ( int nStdHandle ) ; [ DllImport ( `` kernel32.dll '' ) ] static extern bool GetConsoleMode ( IntPtr hConsoleHandle , out uint lpMode ) ; [ DllImport ( `` kernel32.dll '' ) ] static extern bool SetConsoleMode ( IntPtr hConsoleHandle , uint dwMode ) ; static void Main ( ) { var handle = GetStdHandle ( STD_OUTPUT_HANDLE ) ; uint mode ; GetConsoleMode ( handle , out mode ) ; mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING ; SetConsoleMode ( handle , mode ) ; const string UNDERLINE = `` \x1B [ 4m '' ; const string RESET = `` \x1B [ 0m '' ; Console.WriteLine ( `` Some `` + UNDERLINE + `` underlined '' + RESET + `` text '' ) ; Console.ReadLine ( ) ; } } }","SetConsoleMode fails with zero , lasterror = 0" "C_sharp : Projects are often broken down into folders , and those folders are typically expected to map to code namespaces . However , in many of my core projects I have classes that I have merged into existing namespaces - for example I have an MVC reference library that adds additional types into System.Web.Mvc , or System.ComponentModel.DataAnnotations , for example.In other projects , I might have a suite of interfaces and a suite of default implementations of those interfaces ; so I might split the code files into two separate folders ( e.g . 'Objects ' and 'Interfaces ' ) but I do n't want to have Objects and Interfaces sub namespaces.Equally , I often write extension methods for types in other libraries - e.g . System.String , which I merge into the System namespace so they are already 'there ' as soon as you reference the assembly.So given a project structure like this ( in response to the first answer , this project is intended to produce a single assembly with all the namespaces ; and could be a dll that might be signed ) : In the above , I want new files added to the root to be in the namespace Our.Core.Library , but I want new files added to the System and System.Web.Mvc folders to be in System and System.Web.Mvc respectively . But VS will give them a default namespace of Our.Core.Library.System.It 's a small gripe , but I 'd like to be able to override the default namespace for a specific code folder so I can control it . Any ideas how to achieve this ? I 've tried an empty default namespace for the project , which might logically make it work for sub-folders , but obviously not for the root ; however , the VS Properties page does n't accept an empty namespace.Ideally it would be a solution that I can easily replicate across our entire dev team to enable other developers to be able to add code files whilst adhering to the namespace structure set out at the architect/planning stage . Our.Core.Library|- > System| |- > StringExtensions.cs|- > System.Web.Mvc| |- > AnotherModelBinder.cs|- > OurCoreClass.cs",How to override VS2010 's automatic folder- > namespace mapping in new cs files "C_sharp : I am using XPath to exclude certain nodes within a menu . I want to expand on this to exclude nodes identified within an array.This works to exclude all the nodes in the menu with id 2905 whose type is not content : What I 'd like is to store the menuId and several others in an array and then reference that array within the string.Format functionSomething like : Any advice would be greatly appreciated ! taNathanEdit - include example xml XmlNodeList nextLevelNodeList = currentNode .SelectNodes ( string .Format ( `` Menu [ not ( MenuId = 2905 ) ] /Item [ ItemLevel = { 0 } and ItemType ! = 'Javascript ' ] | Menu [ MenuId = 2905 ] /Item [ ItemLevel = { 0 } and ItemType = 'content ' ] '' , iLevel ) ) ; int [ ] excludeSubmenus = { 2905 , 323 } ; XmlNodeList nextLevelNodeList = currentNode .SelectNodes ( string .Format ( `` Menu [ not ( MenuId in excludesubMenus ) ] /Item [ ItemLevel= { 0 } and ItemType ! = 'Javascript ' ] | Menu [ MenuId in excludeSubMenus ] /Item [ ItemLevel= { 0 } and ItemType='content ' ] '' , iLevel ) ) ; < Item > < ItemId > 322 < /ItemId > < ItemType > Submenu < /ItemType > < ItemLevel > 2 < /ItemLevel > < Menu > < MenuId > 322 < /MenuId > < MenuLevel > 2 < /MenuLevel > < Item > < ItemId > 2905 < /ItemId > < ItemType > Submenu < /ItemType > < ItemLevel > 3 < /ItemLevel > < Menu > < MenuId > 2905 < /MenuId > < MenuLevel > 3 < /MenuLevel > < Item > < ItemId > 19196 < /ItemId > < ItemType > content < /ItemType > < ItemLevel > 4 < /ItemLevel > < /Item > < Item > < ItemId > 19192 < /ItemId > < ItemType > Submenu < /ItemType > < ItemLevel > 4 < /ItemLevel > < /Item > < /Menu > < /Item > < Item > < ItemId > 2906 < /ItemId > < ItemType > Submenu < /ItemType > < ItemLevel > 3 < /ItemLevel > < Menu > < MenuId > 323 < /MenuId > < MenuLevel > 3 < /MenuLevel > < Item > < ItemId > 2432 < /ItemId > < ItemType > content < /ItemType > < ItemLevel > 4 < /ItemLevel > < /Item > < Item > < ItemId > 12353 < /ItemId > < ItemType > Submenu < /ItemType > < ItemLevel > 4 < /ItemLevel > < /Item > < /Menu > < /Item > < /Menu > < /Item >",How do I reference array values within string.Format ? "C_sharp : I 'm trying to call unmanaged printf-like function using DynamicMethod . At runtime I get a BadImageFormatException : Index not found . ( Exception from HRESULT : 0x80131124 ) Is this a limitation of runtime or my emited code is wrong ? public class Program { [ DllImport ( `` msvcrt40.dll '' , CallingConvention = CallingConvention.Cdecl ) ] public static extern int printf ( string format , __arglist ) ; static void Main ( string [ ] args ) { var method = new DynamicMethod ( `` printf '' , typeof ( void ) , new Type [ 0 ] , true ) ; var il = method.GetILGenerator ( ) ; il.Emit ( OpCodes.Ldstr , `` % s= % d\n '' ) ; il.Emit ( OpCodes.Ldstr , `` a '' ) ; il.Emit ( OpCodes.Ldc_I4_0 ) ; il.EmitCall ( OpCodes.Call , typeof ( Program ) .GetMethod ( `` printf '' , BindingFlags.Public | BindingFlags.Static ) , new Type [ ] { typeof ( string ) , typeof ( int ) } ) ; il.Emit ( OpCodes.Pop ) ; il.Emit ( OpCodes.Ret ) ; var action = ( Action ) method.CreateDelegate ( typeof ( Action ) ) ; action.Invoke ( ) ; } }",Calling varargs method via DynamicMethod "C_sharp : I have a class that parses in data from a comma delimited text file . I have an enum for the fields to help me parse data in easier . The class that parses all the records in holds public variables for each field , and of course their variable types . I need to get the type of these variables based on the enum given.NumID1 , NumID2 , NumID3 all get assigned within my constructor . However , I want to get these types without ever creating an instance of DataBaseRecordInfo . Right now my static method above would work , however , if I wanted to change the variable type , I would have to change it in 2 places . Is there a way to get around having to change this in both places and keep it as a static method ? public enum DatabaseField : int { NumID1 = 1 , NumID2 = 2 , NumID3 = 3 , } ; public class DataBaseRecordInfo { public long NumID1 { get ; set ; } public int NumID2 { get ; set ; } public short NumID3 { get ; set ; } public static Type GetType ( DatabaseField field ) { Type type ; switch ( field ) { case DatabaseField.NumID1 : type = typeof ( long ) ; break ; case DatabaseField.NumID2 : type = typeof ( int ) ; break ; case DatabaseField.NumID3 : type = typeof ( short ) ; break ; default : type = typeof ( int ) ; break ; } return type ; } } ;",C # Getting the Type of a Public Variable based on an Enum value "C_sharp : We 're running Entity Framework 6 and have a DatabaseLogFormatter that formats our data , and it 's logged via an NLog AsyncTargetWrapper to a file . The application is an MVC5 web app.The DatabaseLogFormatter is mostly empty stubs , except LogCommand and LogResult . Both of which format the data correctly . The NLog logging has worked without issue until now.The issue we 're running into is that after a few hours uptime ( seems random , have n't been able to find a pattern ) it will create almost duplicate log rows . Once it starts it continues to log every row twice or thrice . Sometimes it randomly goes back to one row.The rows will differ in elapsed time which is read in the DatabaseLogFormatter , implying that the requests are being reformatted ( and not an NLog issue ) .And EF context ( from DB first model ) . DB calls are made using the unmodified EF generated functions and we mainly use stored procedures.Example of how log output can appear public class NLogFormatter : DatabaseLogFormatter { private static readonly DbType [ ] StringTypes = { DbType.String , DbType.StringFixedLength , DbType.AnsiString , DbType.AnsiStringFixedLength , DbType.Date , DbType.DateTime , DbType.DateTime2 , DbType.Time , DbType.Guid , DbType.Xml } ; public NLogFormatter ( DbContext context , Action < string > writeAction ) : base ( context , writeAction ) { } public override void LogCommand < TResult > ( DbCommand command , DbCommandInterceptionContext < TResult > interceptionContext ) { var builder = new StringBuilder ( ) ; builder.Append ( $ '' COMMAND| { ( command.CommandType == CommandType.StoredProcedure ? `` EXEC `` : '' '' ) } { command.CommandText.Replace ( Environment.NewLine , `` `` ) } `` ) ; foreach ( var parameter in command.Parameters.OfType < DbParameter > ( ) ) { builder.Append ( `` @ '' ) .Append ( parameter.ParameterName ) .Append ( `` = `` ) .Append ( parameter.Value == null || parameter.Value == DBNull.Value ? `` null '' : StringTypes.Any ( t = > t == parameter.DbType ) ? $ '' ' { parameter.Value } ' '' : parameter.Value ) ; builder.Append ( `` , `` ) ; } Write ( builder.ToString ( ) ) ; } public override void LogResult < TResult > ( DbCommand command , DbCommandInterceptionContext < TResult > interceptionContext ) { var sw = Stopwatch ; Write ( $ '' COMPLETED| { command.CommandText.Replace ( Environment.NewLine , `` `` ) } | { sw.ElapsedMilliseconds } ms '' ) ; } //rest removed for brevity } public class EfDbConfiguration : DbConfiguration { public EfDbConfiguration ( ) { SetDatabaseLogFormatter ( ( context , action ) = > new NLogFormatter ( context , action ) ) ; } } public class EfFunctions { private readonly EfEntities _db = new EfEntities { Database = { Log = Logger.LogEfRequest } } ; //Function calls etc } 2017-10-22 23:47:22.0611|Debug|REQUEST|Example.Page|POST|/example/page2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.0611|Debug|DB|COMMAND|EXEC [ Test ] . [ GetOrder ] @ OrderNumber = '123456789 ' , @ ErrorCode = null , 2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|DB|COMPLETED| [ Test ] . [ GetOrder ] |149ms2017-10-22 23:47:22.2111|Debug|APP|No order or session , creating new session|123456789",Entity Framework logs duplicates C_sharp : This program throws ArrayIndexOutOfBoundException.Why is it so ? If strings are not null-terminated . How strings are getting handled in C # ? How can I get the length without using string.Length property ? I 'm confused here . ! string name = `` Naveen '' ; int c = 0 ; while ( name [ c ] ! = '\0 ' ) { c++ ; } Console.WriteLine ( `` Length of string `` + name + `` is : `` + c ) ;,How are strings terminated in C # ? "C_sharp : Apparently , C # is as susceptible to ' > > ' lexer dilemma as is C++.This C # code is pretty valid , it compiles and runs just fine : You 'd have to overload ' < ' and ' > > ' operators for the Dummy class above.But the compiler manages to guess that in ' x ' case the meaning is to use List , Nullable and Guid local variables . And in ' y ' case it suddenly decides to treat them as names of well-known types.Here 's a bit more detailed description with another example : http : //mihailik.blogspot.co.uk/2012/05/nested-generics-c-can-be-stinky.htmlThe question is : how does C # compiler resolve ' a < b < c > > ' to arithmetic expression or generic type/method ? Surely it does n't try to have multiple 'goes ' over the text of the program until it succeeds , or does it ? That would require unbounded look-ahead , and a very complex too . var List = new Dummy ( `` List '' ) ; var Nullable = new Dummy ( `` Nullable '' ) ; var Guid = new Dummy ( `` Guid '' ) ; var x = List < Nullable < Guid > > 10 ; var y = List < Nullable < Guid > > .Equals ( 10,20 ) ;",Nested generic syntax ambiguity > > "C_sharp : I have just migrated my Xamarin Forms project to .NET Standard 2.0 and am fighting with some odd behavior . In the following situation , I am getting a Null Reference Exception on a ListDictionaryInternal with no exception breakpoint , no stack trace and no other information available . The situation is , from my view model I am setting the bindable text property on a custom button control . I have debugged all the way through the text setting process and the exception happens after . I am completely stumped by this one . And to be clear , this code was working before the .NET Standard 2.0 migration . Thank you in advance ! UPDATE : So this exception has started happening with Forms iOS as well but now I am able to get a stack trace when the System.Exception breakpoint hits . Also this is not related to .NET Standard 2.0 because this is also happening when targeting a PCL 4.5 project , Profile 111 to be exact.I can set a breakpoint in the code behind 's OnSizeAllocated override method and see that the view has accepted the bound text and laid out properly . So it is not the binding that is the issue but rather something to do with the laying out of the view . Also , for clarification , this exception only happens if the text is set with a bindable property . If the text is set in the xaml the exception does not happen.The ViewModel ... The View ... The SVGImageButton ... public class SimpleSearchViewModel : BaseViewModel { enum SearchCatagories { All , SubjectId , PublicationNumber } public override void OnStart ( ) { UpdateTypeButton ( `` ALL '' ) ; } private void UpdateTypeButton ( string item ) { SearchTypeButtonText = item ; } private string _searchTypeButtonText ; public string SearchTypeButtonText { get { return _searchTypeButtonText ; } private set { _searchTypeButtonText = value ; OnPropertyChanged ( nameof ( SearchTypeButtonText ) ) ; } } } < core : BasePage xmlns= '' http : //xamarin.com/schemas/2014/forms '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2009/xaml '' xmlns : viewmodels= '' using : App.ViewModels '' xmlns : customcontrols= '' clr-namespace : App ; assembly=App '' xmlns : core= '' clr-namespace : App.Core ; assembly=App.Core '' x : Class= '' Pages.SimpleSearchPage '' Title= '' Simple Search '' > < ContentPage.BindingContext > < viewmodels : SimpleSearchViewModel / > < /ContentPage.BindingContext > < ContentPage.Content > < StackLayout Padding= '' 10 , 10 , 10 , 10 '' HorizontalOptions= '' FillAndExpand '' VerticalOptions= '' FillAndExpand '' Orientation= '' Horizontal '' > < customcontrols : SVGImageButton x : Name= '' TypeSelectionButton '' HorizontalOptions= '' Start '' VerticalOptions= '' Center '' ButtonPressedCommand= '' { Binding TypeButtonClickedCommand } '' SVGImageName= '' SVGImages.ic_triangle_down.svg '' CommandParameter= '' { x : Reference TypeSelectionButton } '' ButtonText= '' { Binding SearchTypeButtonText } '' ButtonBackgroundColor= '' { Binding ButtonBackgroundColor } '' / > < /StackLayout > < /ContentPage.Content > < /core : BasePage > [ XamlCompilation ( XamlCompilationOptions.Compile ) ] public class SVGImageButton : ContentView { private readonly Button _button ; private readonly SvgCachedImage _svgImage ; public static BindableProperty ButtonTextProperty = BindableProperty.Create ( nameof ( ButtonText ) , typeof ( string ) , typeof ( SVGImageButton ) , string.Empty , BindingMode.OneWay , propertyChanged : ( bindable , oldValue , newValue ) = > { if ( newValue == null ) return ; var control = ( SVGImageButton ) bindable ; control.ButtonText = newValue.ToString ( ) ; } ) ; public string ButtonText { get { return _button.Text ; } set { _button.Text = value ; } } public string SVGImageName { get ; set ; } protected override void OnParentSet ( ) { base.OnParentSet ( ) ; _button.Text = ButtonText ; _svgImage.Source = SvgImageSource.FromResource ( SVGImageName ) ; } public SVGImageButton ( ) { var content = new RelativeLayout ( ) ; _button = new Button { BackgroundColor = Color.Gray , TextColor = Color.Black } ; _svgImage = new SvgCachedImage { IsEnabled = false } ; content.Children.Add ( _button , Constraint.RelativeToParent ( ( parent ) = > { return parent.X ; } ) , Constraint.RelativeToParent ( ( parent ) = > { return parent.Y ; } ) , Constraint.RelativeToParent ( ( parent ) = > { return parent.Width ; } ) , Constraint.RelativeToParent ( ( parent ) = > { return parent.Height ; } ) ) ; content.Children.Add ( _svgImage , Constraint.RelativeToParent ( ( parent ) = > { return parent.Width - ( parent.Height / 2 ) - ( parent.Height / 4 ) ; } ) , Constraint.RelativeToParent ( ( parent ) = > { return parent.Height - ( parent.Height / 2 ) - ( parent.Height / 4 ) ; } ) , Constraint.RelativeToParent ( ( parent ) = > { return parent.Height / 2 ; } ) , Constraint.RelativeToParent ( ( parent ) = > { return parent.Height / 2 ; } ) ) ; Content = content ; } } }",Null reference exception on a ListDictionaryInternal when setting bindable property on custom view "C_sharp : I 'm wetting my feet with dynamic code generation and System.Reflection.Emit . All seems pretty easy and straightforward , but there 's one question which I can not find answered on the web.When building dynamic assemblies with AssemblyBuilder it 's possible to create a type and then start using it immediately . If later you need to add another type to the assembly , you can do that too and it 's all fine ( as far as I can tell ) .But what if there are two threads that are trying to build types for that assembly ? Or what if one ready-made type is already being used , while another is in the making ? Will there be any conflicts or race conditions ? Added : OK , I think that a bit more information is necessary.What I 'm doing with Reflection.Emit is dynamically implementing interfaces at runtime . Basically I have something like : Where T needs to be an interface ( and a few other unrelated requirements ) .Each interface will have exactly one implementation and that implementation will have exactly one instance . They will all be thread-safe singletons.So when a request for a new , hitherto unseen interface comes in , I implement it , make an instance and then cache it for all eternity ( which is here defined as `` until my program is stopped '' ) .This will however be done in a ASP.NET web application , so we have many threads requesting interfaces all the time . Performance is important and I 'm trying to figure out how much multithreading I can afford.It 's pretty clear that a single interface will ever only be implemented by a single thread . But can I implement two different interfaces in two different threads at the same time ? I guess the answer is - `` better not '' .OK , so I can add a lock that only one thread is doing an implementation at the same time . That will take care of builders interfering with each other . But what about those interfaces that were implemented previously ? Other threads are using them at the same time while we 're making a new one . I guess they 're fine , unless they 're trying to use some kind of reflection on their own assembly ? I could , of course , make one-assembly-per-interface-implementation policy , but that would spam the `` Loaded Modules '' debugger window real fast . Also , I do n't know what performance effects there will be of having a 100 loaded assemblies ( but I doubt that they will be good ) .Added 2 : Right , there must be something wrong with my language , since people do n't seem to get it . Let me try with a code example : Can there be a threading-related error between DoSomethingInAnotherThread ( object1 ) and MagicClass.GetImplementation < I2 > ( ) ? We can assume that : DoSomethingInAnotherThread ( object1 ) does NOT call MagicClass.GetImplementation < T > ( ) DoSomethingInAnotherThread ( object1 ) does NOT use reflection on object1 and neither does object1 itself.Basically , the question is - can an innocent call to object1.SomeMethod ( ) blow up because the assembly is being reorganized on another thread . class MagicClass { public static T GetImplementation < T > ( ) ; } var object1 = MagicClass.GetImplementation < I1 > ( ) ; DoSomethingInAnotherThread ( object1 ) ; var object2 = MagicClass.GetImplementation < I2 > ( ) ;",How threadsafe is System.Reflection.Emit ? "C_sharp : I am currently calling up several stored procedures in some .NET code , SqlConnection . I 'd like to disable the caching done by SQL Server , so that I can measure performance periodically ( I 'm gon na be comparing it to another server that likely wo n't have any cached data either ) . Is this possible to do without modifying the sprocs ? This is the code that I am currently using : using ( SqlConnection connection = new SqlConnection ( /* connection string goes here */ ) ) { SqlCommand command = new SqlCommand ( procName , connection ) ; command.Parameters.AddRange ( parameters ) ; command.CommandType = System.Data.CommandType.StoredProcedure ; connection.Open ( ) ; SqlDataReader r = command.ExecuteReader ( ) ; // todo : read data here r.Close ( ) ; connection.Close ( ) ; }",Disabling SQL Server 's caching through .NET code "C_sharp : This is next step of my previous question . I 'm creating a C # WinForm Application which will display Network Activity ( Bytes Received / Bytes Sent ) for a given Process ( For Example : Process name 's chrome.exe ) and Speed in Megabits/s generated by the Process.While using the Performance Counters IO Read Bytes/sec and IO Read Bytes/sec shows I/O read and write bytes instead of 'Send and Received Bytes ' . PS : I/O counts all File , Network , and Device I/Os bytes generated by a Process . But , I wants only Network Bytes generated by a particular Process.I wanted to retrieve only Bytes Received and Bytes Sent . But , do n't know what counters are used to get these bytes of a Process.I have searched these links for this purpose but not useful : C # Resource Monitor get network activity valuesRetrieve process network usageMissing network sent/receivedNeed `` Processes with Network Activity '' functionality in managed code - Like resmon.exe does itHere is Process 's Performance Counter code that tried : Question : How I can only get the Received and Sent Bytes generated by a Process for a network activity . PerformanceCounter bytesReceived = new PerformanceCounter ( `` Process '' , `` IO Read Bytes/sec '' ) ; PerformanceCounter bytesSent = new PerformanceCounter ( `` Process '' , `` IO Write Bytes/sec '' ) ; string ProcessName = `` chrome '' ; bytesReceived.InstanceName = ProcessName ; bytesSent.InstanceName = ProcessName ;",Getting Received and Sent Bytes generated by Process for Network Activity "C_sharp : I am creating a VSTO Ribbon AddIn for excel , and I am storing some workbook state information in my application that I use to update visual Buttons Enabled . Considering there can be multiple workbooks I am storing this state object in a dictionary in the ThisAddIn class . My problem is that I do n't know how to get a unique Hash/Key/Guid for the workbook because all I get is a COM wrapper that continually changes the hash . fair enough , I totally understand that.One solution I 've used for a long time has been to create a guid and store it in the CustomDocumentProperties for the workbook , and to map the state based on that as a key . This at least works , but it fails if I create a copy of the workbook and open that in the same Application instance and have multiple workbooks with the same guid now..I just had an idea now that I suppose I could refresh this Guid on the Workbook_Open event . But still this seems like a dodgy solution.The second solution I found here : http : //social.msdn.microsoft.com/Forums/en-US/vsto/thread/04efa74d-83bd-434d-ab07-36742fd8410e/So I used that guys code and created this : It works very well for a few minutes , until it starts giving me the infamous error `` COM object that has been separated from its underlying RCW can not be used '' when accessing the Application.ActiveWorkbook.Is this a safe way of referencing the Workbook COM object ? What if I had two ribbon applications both using this method to get a single workbooks GUID ? What if one of those applications runs the garbage collector on my state object , which calls a finalizer to call Marshal.FinalReleaseComObject ( workbook ) ? Is there any way I can get the Ref Count for a Workbook so that I do n't call FinalRelease before other Ribbon Apps have finished with them ? What are some best practices for cleaning up Workbook COM objects in VSTO to keep playing fair with these other apps ? Surely I 'm not the first person to want to have buttons enabled based on Workbook state , how does everyone else do this ? I 've looked at a few other articles here on Stack Overflow but none quite help me with the Workbook Guid solution.I am using the Ribbon Designer , and hooking up to the Workbook Load and Deactivate events.Thanks in advance , hope ive included all the details . public static class WorkbookExtensions { public static IntPtr GetHashery ( this msExcel.Workbook workbook ) { IntPtr punk = IntPtr.Zero ; try { punk = Marshal.GetIUnknownForObject ( workbook ) ; return punk ; } finally { //Release to decrease ref count Marshal.Release ( punk ) ; } } }",Get Hashcode for Excel Workbook in VSTO to enable buttons based on state "C_sharp : If you have an immutable list , you expect it to always return a reference to the same object when you ask for , sayMy question is , would you expect to be able to mutate the object and have the mutation reflected next time you get it from the list ? list.get ( 0 )",How deep would you expect the immutability of an immutable list to be ? "C_sharp : Can anyone tell me what the correct Plinq code is for this ? I 'm adding up the square root of the absolute value of the sine of each element fo a double array , but the Plinq is giving me the wrong result.Output from this program is : Linq aggregate = 75.8310477905274 ( correct ) Plinq aggregate = 38.0263653589291 ( about half what it should be ) I must be doing something wrong , but I ca n't work out what ... ( I 'm running this with Visual Studio 2008 on a Core 2 Duo Windows 7 x64 PC . ) Here 's the code : using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Collections ; namespace ConsoleApplication1 { class Program { static void Main ( ) { double [ ] array = new double [ 100 ] ; for ( int i = 0 ; i < array.Length ; ++i ) { array [ i ] = i ; } double sum1 = array.Aggregate ( ( total , current ) = > total + Math.Sqrt ( Math.Abs ( Math.Sin ( current ) ) ) ) ; Console.WriteLine ( `` Linq aggregate = `` + sum1 ) ; IParallelEnumerable < double > parray = array.AsParallel < double > ( ) ; double sum2 = parray.Aggregate ( ( total , current ) = > total + Math.Sqrt ( Math.Abs ( Math.Sin ( current ) ) ) ) ; Console.WriteLine ( `` Plinq aggregate = `` + sum2 ) ; } } }",Plinq gives different results from Linq - what am I doing wrong ? C_sharp : I 'm learning multi-threading in C # and I saw a code belowI wonder when does it require to use nested locking ? Why do n't use only one lock in this case ? static readonly object _locker = new object ( ) ; static void Main ( ) { lock ( _locker ) { AnotherMethod ( ) ; // ... some work is going on } } static void AnotherMethod ( ) { lock ( _locker ) { Console.WriteLine ( `` Another method '' ) ; } },Nested locking in C # "C_sharp : Currently I 'm preparing a presentation of the new generic variance features in C # for my colleagues . To cut the story short I wrote following lines : Yes , this is of course not possible , as IList ( Of T ) is invariant ( at least my thought ) . The compiler tells me that : Can not implicitly convert type System.Collections.Generic.IList < System.Windows.Forms.Form > to System.Collections.Generic.IList < System.Windows.Forms.Control > . An explicit conversion exists ( are you missing a cast ? ) Hm , does this mean I can force an explicit conversion ? I just tried it : And… it compiles ! Does it mean I can cast the invariance away ? - At least the compiler is ok with that , but I just turned the former compile time error to a run time error : Unable to cast object of type 'System.Collections.Generic.List ` 1 [ System.Windows.Forms.Form ] ' to type 'System.Collections.Generic.IList ` 1 [ System.Windows.Forms.Control ] '.My question ( s ) : Why can I cast the invariance of IList < T > ( or any other invariant interface as to my experiments ) away ? Do I really cast the invariance away , or what kind of conversion happens here ( as IList ( Of Form ) and IList ( Of Control ) are completely unrelated ) ? Is this a dark corner of C # I did n't know ? IList < Form > formsList = new List < Form > { new Form ( ) , new Form ( ) } ; IList < Control > controlsList = formsList ; IList < Form > formsList = new List < Form > { new Form ( ) , new Form ( ) } ; IList < Control > controlsList = ( IList < Control > ) formsList ;",Why can I cast the invariance of IList < T > away ? "C_sharp : I 've got an abstract class CommandBase < T , X > that I want to have a property InnerCommand . But since the InnerCommand might have other types for T and X than the command that contains it , how can I define that ? The abstract class : In the example above InnerCommand will only accept instances that have the same types for T and X , but I need to allow for other types . An AddOrderitemCommand : Might contain a WebserviceCommand : Please advise on the syntax for allowing this . public abstract class CommandBase < T , X > where T : CommandResultBase where X : CommandBase < T , X > { public CommandBase < T , X > InnerCommand { get ; set ; } ( ... ) } public class AddOrderitemCommand : CommandBase < AddOrderitemResult , AddOrderitemCommand > { ( ... ) } public class GetMenuCommand : CommandBase < GetMenuResult , GetMenuCommand > { ( ... ) }",Property in generic base class with different implementation "C_sharp : I 'm trying to get a better understanding of general practice ... specifically deriving this ( ) in a constructor . I understand that its less code , but I consider it less readable . Is it common/good practice to do it this way ? Or is it better to write a second constructor that handles it specifically ? or Any input would be greatly appreciated public SomeOtherStuff ( string rabble ) : this ( rabble , `` bloop '' ) { } Public SomeOtherStuff ( string rabble ) { //set bloop }",: this ( ) As a constructor "C_sharp : I have successfully bound a column in a DataGrid to an observable collection with objects implementing the INotifyPropertyChanged interface : This is the xaml : And the property in the objects class : But in another column I am using a Template : The Fill property of the rectangle is bound to a `` calculated '' property : Some other property setters , which change the value of StapelStatus are calling I thought this would be enough to change also the color in the rectangle color in the grid column . But unfortunately when the StapelStatus is changed and OnPropertyChanged ( `` StatusColor '' ) is called the grid does n't reflect this change . I guess that I have to change somehow the binding in the DataTemplate . Can someone please give me an advice ? < dxg : GridColumn Name= '' Name '' FieldName= '' Stapel '' DisplayMemberBinding= '' { Binding Path=Name } '' / > public string Name { get { return _name ; } set { if ( value == _name ) return ; _name = value ; OnPropertyChanged ( `` Name '' ) ; } } < dxg : GridColumn.CellTemplate > < DataTemplate > < StackPanel > < Rectangle Height= '' 19 '' Width= '' 19 '' Fill= '' { Binding Path=Data.StatusColor } '' > < /Rectangle > < /StackPanel > < /DataTemplate > < /dxg : GridColumn.CellTemplate > public SolidColorBrush StatusColor { get { if ( StapelStatus == StapelStatus.Neu ) { return new SolidColorBrush ( Colors.CornflowerBlue ) ; } return new SolidColorBrush ( Colors.DarkOrange ) ; } } OnPropertyChanged ( `` StatusColor '' ) ;",INotifyPropertyChanged Binding to DataTemplate in GridColumn "C_sharp : I 've been trying to find an answer to this question for a few hours now on the web and on this site , and I 'm not quite there.I understand that .NET allocates 1MB to apps , and that it 's best to avoid stack overflow by recoding instead of forcing stack size . I 'm working on a `` shortest path '' app that works great up to about 3000 nodes , at which point it overflows . Here 's the method that causes problems : For reference , the Node class has one member : graph [ ] is : I 've tried to opimize the code so that it is n't carrying any more baggage than needed from one iteration ( recursion ? ) to the next , but with a 100K-Node graph with each node having between 1-9 edges it 's going to hit that 1MB limit pretty quickly . Anyway , I 'm new to C # and code optimization , if anyone could give me some pointers ( not like this ) I would appreciate it . public void findShortestPath ( int current , int end , int currentCost ) { if ( ! weight.ContainsKey ( current ) ) { weight.Add ( current , currentCost ) ; } Node currentNode = graph [ current ] ; var sortedEdges = ( from entry in currentNode.edges orderby entry.Value ascending select entry ) ; foreach ( KeyValuePair < int , int > nextNode in sortedEdges ) { if ( ! visited.ContainsKey ( nextNode.Key ) || ! visited [ nextNode.Key ] ) { int nextNodeCost = currentCost + nextNode.Value ; if ( ! weight.ContainsKey ( nextNode.Key ) ) { weight.Add ( nextNode.Key , nextNodeCost ) ; } else if ( weight [ nextNode.Key ] > nextNodeCost ) { weight [ nextNode.Key ] = nextNodeCost ; } } } visited.Add ( current , true ) ; foreach ( KeyValuePair < int , int > nextNode in sortedEdges ) { if ( ! visited.ContainsKey ( nextNode.Key ) || ! visited [ nextNode.Key ] ) { findShortestPath ( nextNode.Key , end , weight [ nextNode.Key ] ) ; } } } //findShortestPath public Dictionary < int , int > edges = new Dictionary < int , int > ( ) ; private Dictionary < int , Node > graph = new Dictonary < int , Node > ( ) ;",How do I avoid changing the Stack Size AND avoid getting a Stack Overflow in C # "C_sharp : I 'm doing some heavy work on a backgroundworker , so that it does n't affect my Silverlight UI thread . However , in the DoWork function I 'm getting this exception : UnauthorizedAccessException `` Invalid cross-thread access '' .I know I ca n't access the UI thread from the BackgroundWorker , However , this exception occurs on this line : How is that accessing my ui thread ? ? Here 's the actual piece of code I 've narrowed it down to . I 'm basically doing work creating listboxitems which i 'd like to insert to the sourceList listbox : ListBoxItem insert = new ListBoxItem ( ) ; void FillSourceList ( ) { busyIndicator.IsBusy = true ; BackgroundWorker bw = new BackgroundWorker ( ) ; bw.DoWork += ( sender , args ) = > { List < ListBoxItem > x = new List < ListBoxItem > ( ) ; for ( int i = 0 ; i < 25 ; i++ ) { ListBoxItem insert = new ListBoxItem ( ) ; // < -- -Getting exception here insert.Content = `` whatever '' ; x.Add ( insert ) ; } args.Result = x ; } ; bw.RunWorkerCompleted += ( sender , args ) = > { foreach ( ListBoxItem insert in ( List < ListBoxItem > ) ( args.Result ) ) sourceList.Items.Add ( insert ) ; busyIndicator.IsBusy = false ; } ; bw.RunWorkerAsync ( ) ; }",Getting `` UnauthorizedAccessException '' in a BackgroundWorker without accessing UI thread "C_sharp : This feels like the kind of code that only fails in-situ , but I will attempt to adapt it into a code snippet that represents what I 'm seeing.After stepping through the code , i==269 , and i2==268 . What 's going on here to account for the difference ? float f = myFloat * myConstInt ; /* Where myFloat==13.45 , and myConstInt==20 */int i = ( int ) f ; int i2 = ( int ) ( myFloat * myConstInt ) ;",Why is my number being rounded incorrectly ? "C_sharp : Why would this compile : but not this other one with one extra parameter in the Func ( the boolean ) : Either I 'm getting blind or there 's something else I 'm going to learn today : D public Dictionary < ValueLineType , Func < HtmlHelper , string , object , Type , string > > constructor = new Dictionary < ValueLineType , Func < HtmlHelper , string , object , Type , string > > ( ) ; public Dictionary < ValueLineType , Func < HtmlHelper , string , object , Type , bool , string > > constructor = new Dictionary < ValueLineType , Func < HtmlHelper , string , object , Type , bool , string > > ( ) ;",Dictionaries and Lambdas fun "C_sharp : Lets assume we have a very simple IConfiguration interface that responsible for returning a proper connection stringand lets assume only one instance of type that implemented such interface can be used ( because it just returns a string , not manage a state , etc . ) So , there are , at least , two ways of how the interface could be registered within a container : as usual - new object per each type requesting , or as a singleton - one object for all type requests . Are there any differences between approaches ( maybe performance reasons , lifetime management tricks , etc . ) vs interface IConfiguration { string ConnectionString { get ; } } container.For < IConfiguration > ( ) .Use < ConfigurationImpl > ( ) ; container.For < IConfiguration > ( ) .Singleton ( ) .Use < ConfigurationImpl > ( ) ;",IoC container mappings : singleton vs each-call creation "C_sharp : EnvironmentWindows XP x32 Visual Studio 2005 Standard Edition Honeywell Dolphin 9500 running Windows Mobile 2003 ( Pocket PC 2003 ) With built in Barcode scanner and B & W camera Using their SDK located here . .NET Compact Framework 1.0 SP3 and .NET Framework 1.1 Using VC # GoalI have a ListView control with CheckBoxes = true and View = Details on a form but I do n't want the check boxes to be `` checkable '' by the user . I am using it for a status display of record completion . I do , however , want to use the event handler function to check the box via code ( i.e . on record completion : lvMeters_ItemCheck ( null , null ) ; ) .ProblemI have disabled checking the box itself ( I think , the touch screen is n't real precise on this device ) . However , when selecting a row ( I have FullRowSelect = true ) , the control often checks the checkbox and the event handler does n't seem to be getting called.Things I have TriedI tried to basically undo the action in the event handler : The problem is the above handler does n't get called on a listview select , nor does the SelectedItemChanged event handler call this event handler but it 's still checking the box on select . It does get called when checking the box itself.Need additional information ? Ask away and I 'll do my best ! I 'm A NoviceSo please feel free to tell me I am doing this completely wrong and should do the entire thing differently . private void lvMeters_ItemCheck ( object sender , ItemCheckEventArgs e ) { if ( sender is ListView ) { if ( e.CurrentValue == CheckState.Checked ) lvMeters.Items [ e.Index ] .Checked = true ; else lvMeters.Items [ e.Index ] .Checked = false ; } else if ( e.CurrentValue == CheckState.Checked ) lvMeters.Items [ e.Index ] .Checked = false ; else lvMeters.Items [ e.Index ] .Checked = true ; }",How Can I Keep A C # Listview Control with Check Boxes from `` Checking '' on Row Selection ? "C_sharp : I have some weird issues with List in my C # app . It must be an allocation mistake or that I 'm doing something wrong ( I 'm average C # developer ) .Let me give an example close to my lines : So now I would expect first value in the first array in MyPrimaryList to be `` onehalf '' and `` one '' in MySecondaryList.But my issue/problem is that both lists gets updated with `` onehalf '' as first value in the first array in both lists.Do you have a good explanation ? : ) THANKS ! ! List < String [ ] > MyPrimaryList = new List < String [ ] > ( ) ; List < String [ ] > MySecondaryList = new List < String [ ] > ( ) ; String [ ] array ; String arrayList = `` one , two , three , four , five '' ; array = arrayList.Split ( ' , ' ) ; MyPrimaryList.Add ( array ) ; MySecondaryList.Add ( array ) ; MyPrimaryList [ 0 ] [ 0 ] += `` half '' ;",C # `` funny '' issues with List < String [ ] > "C_sharp : I want to do a very simple thing : move some code in VS13 from one project in to another one and I 'm facing the strange problem with datasets . For simplicity let 's say that in my source project I have one dataset named MyDataSet which consists from 5 files : MyDataSet.cs , MyDataSet.Designer.cs , MyDataSet.xsc , MyDataSet.xsd , MyDataSet.xss.Then I copy these files to my destination project folder using standard windows functionality and use Include in Project menu option in VS13 . After that I see that one extra file was added : MyDataSet1.Designer.cs.I tried to check cproj files and they are different.Source ( only parts different from target are shown ) : Target ( only part different from source are shown ) : Also I noticed that in MyDataSet.cs and MyDataSet1.Designer.cs namespaces were automatically changed to correct ones.I 'm using ReSharper , and first I thought that it can be a reason of that , but I disabled ReSharper and the same behavior continues to happen.Probably I can fix that by removing newly created files and modifying cproj files , but actually there are a lot of datasets that I need to copy and I really do n't like that kind of work.Does anyone have any ideas what can be a reason of such problem and how can it be solved ? < Compile Include= '' MyDataSet.Designer.cs '' > < AutoGen > True < /AutoGen > < DesignTime > True < /DesignTime > < DependentUpon > MyDataSet.xsd < /DependentUpon > < /Compile > < None Include= '' MyDataSet.xsd '' > < SubType > Designer < /SubType > < Generator > MSDataSetGenerator < /Generator > < LastGenOutput > MyDataSet.Designer.cs < /LastGenOutput > < /None > < Compile Include= '' MyDataSet.Designer.cs '' > < DependentUpon > MyDataSet.cs < /DependentUpon > < /Compile > < Compile Include= '' MyDataSet1.Designer.cs '' > < AutoGen > True < /AutoGen > < DesignTime > True < /DesignTime > < DependentUpon > MyDataSet.xsd < /DependentUpon > < /Compile > < None Include= '' MyDataSet.xsd '' > < Generator > MSDataSetGenerator < /Generator > < LastGenOutput > MyDataSet1.Designer.cs < /LastGenOutput > < SubType > Designer < /SubType > < /None >",`` Include in Project '' strange behavior for dataset in VisualStudio 2013 "C_sharp : I currently have a for loop to compare 2 arrays and determine if they 're equal.This works well but it 's one of the slowest parts of my progam . This way my testcase takes about 7 seconds to compute . Although i may have 50K tasks running , the CPU usage was about 50 % on my i7 860 CPU ( 4 cores , 8 threads ) . My idea was to use a parallel for loop to maximize CPU usage and make this faster . This is what i came up with.To me this looks like it will try to run parallel and also stop working on it as soon as a difference has been found because of loopState.Stop . This way the CPU usage is 90 % + but my testcase takes about 35 seconds to compute and I do not understand why.Is there something wrong with my implementation or is my entire approach wrong ? EDIT : carCoords.Length will be a value between 2 and +-100 . It sounds like that value is too low to justify doing this in parallel . public override bool Equals ( object obj ) { RushHourPathLengthNode otherNode = ( RushHourPathLengthNode ) obj ; // Compare their carCoords and return false as soon as we find a difference for ( int i = 0 , l = carCoords.Length ; i < l ; ++i ) if ( carCoords [ i ] .x ! = otherNode.carCoords [ i ] .x || carCoords [ i ] .y ! = otherNode.carCoords [ i ] .y ) return false ; return true ; } public override bool Equals ( object obj ) { RushHourPathLengthNode otherNode = ( RushHourPathLengthNode ) obj ; bool result = true ; Parallel.For ( 0 , carCoords.Length , ( i , loopState ) = > { if ( ! result ) loopState.Stop ( ) ; if ( carCoords [ i ] .x ! = otherNode.carCoords [ i ] .x || carCoords [ i ] .y ! = otherNode.carCoords [ i ] .y ) result = false ; } ) ; return result ; }",Testing 2 arrays for equality in a parallel for loop "C_sharp : How can I create a style that only exists within the context of a ResourceDictionary , but not in the context of controls that include that ResourceDictionary ? For instance , I want to be able to have a ResourceDictionary that looks like this : And then in some other control or window , I want to be able to go : < ! -- ControlTemplates.xaml -- > < ResourceDictionary > < ! -- Private Local styles used to set up the publicly usable templates -- > < Style x : Key= '' TextBoxes '' TargetType= '' TextBox '' > < Setter Property= '' TextWrapping '' Value= '' Wrap '' / > < /Style > < ! -- End of Private Local Stuff -- > < ! -- Public Dictionary Resources Follow -- > < ControlTemplate x : Key= '' CustomTextBox '' > < TextBox Style= '' { StaticResource TextBoxes } '' / > < /ControlTemplate > < /ResourceDictionary > < Window > < Window.Resources > < ResourceDictionary Source= '' ControlTemplates.xaml '' > < /Window.Resources > < Grid > < ! -- This Should Work -- > < CustomControl Template= '' { StaticResources CustomTextBox } '' > < ! -- This Should NOT Work ! -- > < TextBox Template= '' { StaticResources TextBoxes } '' > < /Grid > < /Window >",How to make a Style that only exists within the context of a ResourceDictionary "C_sharp : All of a sudden the binding for my TextInputEditText started failing , and it has something to do with the Linker . If I set the linker to `` None '' , everything works as intended . Alot of other bindings im using still works just fine . Stack im getting : Exception thrown during the view binding ArgumentNullException : missing source event info in MvxWeakEventSubscription Parameter name : sourceEventInfo at MvvmCross.Platform.WeakSubscription.MvxWeakEventSubscription2 [ TSource , TEventArgs ] ..ctor ( Android.Widget.TextView source , System.Reflection.EventInfo sourceEventInfo , System.EventHandler1 [ TEventArgs ] targetEventHandler ) [ 0x00017 ] in D : \git\MvvmCross\MvvmCross\Platform\Platform\WeakSubscription\MvxWeakEventSubscription.cs:47 at MvvmCross.Platform.WeakSubscription.MvxWeakEventSubscription2 [ TSource , TEventArgs ] ..ctor ( Android.Widget.TextView source , System.String sourceEventName , System.EventHandler1 [ TEventArgs ] targetEventHandler ) [ 0x00000 ] in D : \git\MvvmCross\MvvmCross\Platform\Platform\WeakSubscription\MvxWeakEventSubscription.cs:34 at MvvmCross.Platform.WeakSubscription.MvxWeakSubscriptionExtensionMethods.WeakSubscribe [ TSource , TEventArgs ] ( TSource source , System.String eventName , System.EventHandler1 [ TEventArgs ] eventHandler ) [ 0x00000 ] in D : \git\MvvmCross\MvvmCross\Platform\Platform\WeakSubscription\MvxWeakSubscriptionExtensionMethods.cs:81 at MvvmCross.Binding.Droid.Target.MvxTextViewTextTargetBinding.SubscribeToEvents ( ) [ 0x0000b ] in < 6a0c851a22864d0993089d65320a630c > :0 at MvvmCross.Binding.Bindings.MvxFullBinding.CreateTargetBinding ( System.Object target ) [ 0x00057 ] in D : \git\MvvmCross\MvvmCross\Core\Binding\Bindings\MvxFullBinding.cs:157 at MvvmCross.Binding.Bindings.MvxFullBinding..ctor ( MvvmCross.Binding.MvxBindingRequest bindingRequest ) [ 0x00028 ] in D : \git\MvvmCross\MvvmCross\Core\Binding\Bindings\MvxFullBinding.cs:64 at MvvmCross.Binding.Binders.MvxFromTextBinder.BindSingle ( MvvmCross.Binding.MvxBindingRequest bindingRequest ) [ 0x00000 ] in D : \git\MvvmCross\MvvmCross\Core\Binding\Binders\MvxFromTextBinder.cs:56 at MvvmCross.Binding.Binders.MvxFromTextBinder+ < > c__DisplayClass2_0. < Bind > b__0 ( MvvmCross.Binding.Bindings.MvxBindingDescription description ) [ 0x00000 ] in D : \git\MvvmCross\MvvmCross\Core\Binding\Binders\MvxFromTextBinder.cs:38 at System.Linq.Enumerable+ < CombineSelectors > c__AnonStorey1D3 [ TSource , TMiddle , TResult ] . < > m__0 ( TSource x ) [ 0x00012 ] in :0 at System.Linq.Enumerable+c__AnonStorey1D3 [ TSource , TMiddle , TResult ] . < > m__0 ( TSource x ) [ 0x00000 ] in < fcebdd9506364c04ba70cbb6c51ded52 > :0 at System.Linq.Enumerable+WhereSelectEnumerableIterator2 [ TSource , TResult ] .MoveNext ( ) [ 0x00064 ] in :0 at System.Collections.Generic.List1 [ T ] .InsertRange ( System.Int32 index , System.Collections.Generic.IEnumerable1 [ T ] collection ) [ 0x000ff ] in < 2f8f5c28c7474bed8a8f35ed56258fb1 > :0 at System.Collections.Generic.List1 [ T ] .AddRange ( System.Collections.Generic.IEnumerable1 [ T ] collection ) [ 0x00000 ] in < 2f8f5c28c7474bed8a8f35ed56258fb1 > :0 at MvvmCross.Binding.Droid.Binders.MvxAndroidViewBinder.StoreBindings ( Android.Views.View view , System.Collections.Generic.IEnumerable ` 1 [ T ] newBindings ) [ 0x00028 ] in < 6a0c851a22864d0993089d65320a630c > :0 at MvvmCross.Binding.Droid.Binders.MvxAndroidViewBinder.ApplyBindingsFromAttribute ( Android.Views.View view , Android.Content.Res.TypedArray typedArray , System.Int32 attributeId ) [ 0x0001c ] in < 6a0c851a22864d0993089d65320a630c > :0I 've already added the following to `` LinkerPleaseInclude '' , but it didnt help . Changing the TextInputEditText to a simple EditText , doesnt help either and throws the same exception . What am I missing ? Im not getting any closer to a solution by looking at the stack . public void Include ( TextInputEditText text ) { text.TextChanged += ( sender , args ) = > text.Text = `` '' + text.Text ; text.Hint = `` '' + text.Hint ; text.Background = ( Drawable ) Android.Resource.Color.Black ; text.Text = `` Text '' + text.Text ; } public void Include ( TextInputLayout text ) { text.Hint = `` '' + text.Hint ; text.Background = ( Drawable ) Android.Resource.Color.Black ; }",TextInputEditText : ArgumentNullException : missing source event info in MvxWeakEventSubscription "C_sharp : I have defined ISpecimenBuilder for my models and use it like that : I want to use it in most of my tests concerning model . I also want to apply some form of post-processing in one of my test classes . Specifically I want to fill property CompanyHistory of all created Offers . It feels like it could be done like that : But Build < T > disables all customizations and I need them.Can I do something like that ? Or should I write my own Behavior ? If so , can someone provide me with guidelines on doing that ? EDIT : I feel I have to stress out that I want to use both my common customization ( ModelCustomization ) and PostprocessorEDIT 2 : What I meant from the beginning is that ModelCustomization can ( and should ) create Offer and my to-be postprocessor should use that already created specimen and fill some of its properties . new Fixture ( ) .Customize ( new ModelCustomization ( ) ) ; fixture.Build < Offer > ( ) .With ( o = > o.CompanyHistory , _previouslyCreatedCompanyHistory ) .Create ( ) ; fixture.Build < Offer > ( ) .WithCustomization ( new ModelCustomization ( ) ) // there is no such method , but i 'd like it to be.With ( o = > o.CompanyHistory , _previouslyCreatedCompanyHistory ) .Create ( ) ;",How can I add common postprocessing applied after customization "C_sharp : I have xamarin.android project Client1 & 1 CommonApp project ( within the same solution ) which have all common code . From Client1 project I need to start CommonApp , my code to do so in Client1 appBelow 1 is CommonApp MainActivity where debugger point going but not starting new activity but the same activity getting added in backstack when i am pressing physical back button it is getting removed.CommonApp activity_main haveDescription : I have I solution with 2 android app . 1 CommonApp & 2nd Client1 . Cleint1 is startup projet having .dll of type CommonApp . From Cleint1 app I am starting CommonApp by importing CommonApp namespace . I can have many project Client1 , Client2 , Client3 ... etc with their own icons , app name , splash screen & google-service.json . When I set Client2 on startup it becomes Client2 project & all common code available in CommonApp.Requirement : HereOutput screenshotApp LogLogUpdated screenshot : public class MainActivity : AppCompatActivity { protected override void OnCreate ( Bundle savedInstanceState ) { base.OnCreate ( savedInstanceState ) ; SetContentView ( Resource.Layout.activity_main ) ; FindViewById < Button > ( Resource.Id.btn1 ) .Click += delegate { //Starting CommonApp project StartActivity ( new Intent ( Application.Context , typeof ( CommonApp.MainActivity ) ) ) ; } ; } } protected override void OnCreate ( Bundle savedInstanceState ) { base.OnCreate ( savedInstanceState ) ; //This is CommonApp SetContentView ( Resource.Layout.activity_main ) ; } < TextView android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : text= '' This is CommonApp '' > < /TextView >",Starting app from other app 's entry point android "C_sharp : The .NET c # compiler ( .NET 4.0 ) compiles the fixed statement in a rather peculiar way.Here 's a short but complete program to show you what I am talking about.Compile it with `` csc.exe FixedExample.cs /unsafe /o+ '' if you want to follow along.Here 's the generated IL for the method Good : Good ( ) Here 's the generated IL for the method Bad : Bad ( ) Here 's what Good does : Get the address of buffer [ 0 ] .Dereference that address.Call WriteLine with that dereferenced value.Here 's what 'Bad ` does : If buffer is null , GOTO 3.If buffer.Length ! = 0 , GOTO 5.Store the value 0 in local slot 0 , GOTO 6.Get the address of buffer [ 0 ] .Deference that address ( in local slot 0 , which may be 0 or buffer now ) .Call WriteLine with that dereferenced value.When buffer is both non-null and non-empty , these two functions do the same thing . Notice that Bad just jumps through a few hoops before getting to the WriteLine function call.When buffer is null , Good throws a NullReferenceException in the fixed-pointer declarator ( byte * p = & buffer [ 0 ] ) . Presumably this is the desired behavior for fixing a managed array , because in general any operation inside of a fixed-statement will depend on the validity of the object being fixed . Otherwise why would that code be inside the fixed block ? When Good is passed a null reference , it fails immediately at the start of the fixed block , providing a relevant and informative stack trace . The developer will see this and realize that he ought to validate buffer before using it , or perhaps his logic incorrectly assigned null to buffer . Either way , clearly entering a fixed block with a null managed array is not desirable.Bad handles this case differently , even undesirably . You can see that Bad does not actually throw an exception until p is dereferenced . It does so in the roundabout way of assigning null to the same local slot that holds p , then later throwing the exception when the fixed block statements dereference p.Handling null this way has the advantage of keeping the object model in C # consistent . That is , inside the fixed block , p is still treated semantically as a sort of `` pointer to a managed array '' that will not , when null , cause problems until ( or unless ) it is dereferenced . Consistency is all well and good , but the problem is that p is not a pointer to a managed array . It is a pointer to the first element of buffer , and anybody who has written this code ( Bad ) would interpret its semantic meaning as such . You ca n't get the size of buffer from p , and you ca n't call p.ToString ( ) , so why treat it as though it were an object ? In cases where buffer is null , there is clearly a coding mistake , and I believe it would be vastly more helpful if Bad would throw an exception at the fixed-pointer declarator , rather than inside the method.So it seems that Good handles null better than Bad does . What about empty buffers ? When buffer has Length 0 , Good throws IndexOutOfRangeException at the fixed-pointer declarator . That seems like a completely reasonable way to handle out of bounds array access . After all , the code & buffer [ 0 ] should be treated the same way as & ( buffer [ 0 ] ) , which should obviously throw IndexOutOfRangeException.Bad handles this case differently , and again undesirably . Just as would be the case if buffer were null , when buffer.Length == 0 , Bad does not throw an exception until p is dereferenced , and at that time it throws NullReferenceException , not IndexOutOfRangeException ! If p is never dereferenced , then the code does not even throw an exception . Again , it seems that the idea here is to give p the semantic meaning of `` pointer to a managed array '' . Yet again , I do not think that anybody writing this code would think of p that way . The code would be much more helpful if it threw IndexOutOfRangeException in the fixed-pointer declarator , thereby notifying the developer that the array passed in was empty , and not null.It looks like fixed ( byte * p = buffer ) should have been compiled to the same code as was fixed ( byte * p = & buffer [ 0 ] ) . Also notice that even though buffer could have been any arbitrary expression , it 's type ( byte [ ] ) is known at compile time and therefore the code in Good would work for any arbitrary expression.EditIn fact , notice that the implementation of Bad actually does the error checking on buffer [ 0 ] twice . It does it explicitly at the beginning of the method , and then does it again implicitly at the ldelema instruction.So we see that the Good and Bad are semantically different . Bad is longer , probably slower , and certainly does not give us desirable exceptions when we have bugs in our code , and even fails much later than it should in some cases.For those curious , the section 18.6 of the spec ( C # 4.0 ) says that behavior is `` Implementation-defined '' in both of these failure cases : A fixed-pointer-initializer can be one of the following : • The token “ & ” followed by a variable-reference ( §5.3.3 ) to a moveable variable ( §18.3 ) of an unmanaged type T , provided the type T* is implicitly convertible to the pointer type given in the fixed statement . In this case , the initializer computes the address of the given variable , and the variable is guaranteed to remain at a fixed address for the duration of the fixed statement.• An expression of an array-type with elements of an unmanaged type T , provided the type T* is implicitly convertible to the pointer type given in the fixed statement . In this case , the initializer computes the address of the first element in the array , and the entire array is guaranteed to remain at a fixed address for the duration of the fixed statement . The behavior of the fixed statement is implementation-defined if the array expression is null or if the array has zero elements ... . other cases ... Last point , the MSDN documentation suggests that the two are `` equivalent '' : // The following two assignments are equivalent ... fixed ( double* p = arr ) { / ... / } fixed ( double* p = & arr [ 0 ] ) { / ... / } If the two are supposed to be `` equivalent '' , then why use different error handling semantics for the former statement ? It also appears that extra effort was put into writing the code paths generated in Bad . The compiled code in Good works fine for all the failure cases , and is the same as the code in Bad in non-failure cases . Why implement new code paths instead of just using the simpler code generated for Good ? Why is it implemented this way ? using System ; public static class FixedExample { public static void Main ( ) { byte [ ] nonempty = new byte [ 1 ] { 42 } ; byte [ ] empty = new byte [ 0 ] ; Good ( nonempty ) ; Bad ( nonempty ) ; try { Good ( empty ) ; } catch ( Exception e ) { Console.WriteLine ( e.ToString ( ) ) ; /* continue with next example */ } Console.WriteLine ( ) ; try { Bad ( empty ) ; } catch ( Exception e ) { Console.WriteLine ( e.ToString ( ) ) ; /* continue with next example */ } } public static void Good ( byte [ ] buffer ) { unsafe { fixed ( byte * p = & buffer [ 0 ] ) { Console.WriteLine ( *p ) ; } } } public static void Bad ( byte [ ] buffer ) { unsafe { fixed ( byte * p = buffer ) { Console.WriteLine ( *p ) ; } } } } .maxstack 2 .locals init ( uint8 & pinned V_0 ) IL_0000 : ldarg.0 IL_0001 : ldc.i4.0 IL_0002 : ldelema [ mscorlib ] System.Byte IL_0007 : stloc.0 IL_0008 : ldloc.0 IL_0009 : conv.i IL_000a : ldind.u1 IL_000b : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_0010 : ldc.i4.0 IL_0011 : conv.u IL_0012 : stloc.0 IL_0013 : ret .locals init ( uint8 & pinned V_0 , uint8 [ ] V_1 ) IL_0000 : ldarg.0 IL_0001 : dup IL_0002 : stloc.1 IL_0003 : brfalse.s IL_000a IL_0005 : ldloc.1 IL_0006 : ldlen IL_0007 : conv.i4 IL_0008 : brtrue.s IL_000f IL_000a : ldc.i4.0 IL_000b : conv.u IL_000c : stloc.0 IL_000d : br.s IL_0017 IL_000f : ldloc.1 IL_0010 : ldc.i4.0 IL_0011 : ldelema [ mscorlib ] System.Byte IL_0016 : stloc.0 IL_0017 : ldloc.0 IL_0018 : conv.i IL_0019 : ldind.u1 IL_001a : call void [ mscorlib ] System.Console : :WriteLine ( int32 ) IL_001f : ldc.i4.0 IL_0020 : conv.u IL_0021 : stloc.0 IL_0022 : ret",Why does MSFT C # compile a Fixed `` array to pointer decay '' and `` address of first element '' differently ? "C_sharp : In a WPF application using MVVM I query a database to get an ObservableCollection of clients , create an ICollectionView and apply a filter function.On my usercontrol I bind the text used for the filter to a textbox and the ICollectionView to a Listbox.The ICollectionView initally contains 1104 clients ( just ClientID and ClientName ) .Retrieving the data from the database is very quick . However , the listbox takes about 4 seconds to populate.As I enter text into the filter , if the number of clients to return is low then the listbox redraws relatively quickly . However , if I clear out the textbox then it 's another 4 seconds to redraw.Am I missing something , or is my code not very well written.Thanks for any advice/help.View : ViewModel : < UserControl x : Class= '' ClientReports.Module.SchemeSelection.Views.Clients '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : local= '' clr-namespace : ClientReports.Module.SchemeSelection.Views '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : materialDesign= '' http : //materialdesigninxaml.net/winfx/xaml/themes '' mc : Ignorable= '' d '' d : DesignHeight= '' 300 '' d : DesignWidth= '' 300 '' xmlns : prism= '' http : //prismlibrary.com/ '' prism : ViewModelLocator.AutoWireViewModel= '' True '' > < Grid > < StackPanel > < TextBox materialDesign : HintAssist.Hint= '' Client Search '' Style= '' { StaticResource MaterialDesignFloatingHintTextBox } '' Text= '' { Binding Search , UpdateSourceTrigger=PropertyChanged } '' / > < ListBox ItemsSource= '' { Binding ClientsFiltered } '' DisplayMemberPath= '' ClientName '' / > < /StackPanel > < /Grid > < /UserControl > using ClientReports.Common.Infrastructure.Models ; using ClientReports.Common.Infrastructure.Services ; using Prism.Mvvm ; using System ; using System.Collections.ObjectModel ; using System.ComponentModel ; using System.Threading.Tasks ; using System.Windows.Data ; namespace ClientReports.Module.SchemeSelection.ViewModels { public class ClientsViewModel : BindableBase { private IClientService clientService ; public ClientsViewModel ( ) { } public ClientsViewModel ( IClientService clientService ) { this.clientService = clientService ; Clients = new ObservableCollection < Client > ( ) ; GetClients ( ) .ContinueWith ( x = > { } ) ; } public ObservableCollection < Client > Clients { get ; } public ICollectionView ClientsFiltered { get ; set ; } private string clientFilter ; public string Search { get = > clientFilter ; set { clientFilter = value ; ClientsFiltered.Refresh ( ) ; RaisePropertyChanged ( `` ClientsFiltered '' ) ; } } private bool Filter ( Client client ) { return Search == null || client.ClientName.IndexOf ( Search , StringComparison.OrdinalIgnoreCase ) ! = -1 ; } private async Task GetClients ( ) { var clients = await clientService.GetAllAsync ( ) ; foreach ( var client in clients ) { Clients.Add ( client ) ; } ClientsFiltered = CollectionViewSource.GetDefaultView ( Clients ) ; ClientsFiltered.Filter = new Predicate < object > ( c = > Filter ( c as Client ) ) ; } } }",Slow performance when filtering ICollectionView < object > "C_sharp : I 've decided to take a quick look into the LINQ side of things , as opposed to just using a straight up foreach loop , but i 'm having some trouble getting it to work , mainly due to datatypes i believe.So i 've got this , so far ; siteTypeList is a list of SiteTypes . I 'm trying to find a particular one ( Which i 've denounced with variable `` temp '' .How do i then use this selected SiteType AS a SiteType ? When i try and pass `` selectedSiteType '' through to another function , like so ; note : I tried with providing an index , as if selectedSiteType was a list / Array , but that didnt work either , i get the following error : Am i missing something ? perhaps a cast of some kind ? Like i said i 'm new to this and am struggling to get my head around this . Chances are i 've got the whole concept wrong and bingbangbosh i 've made a fool of myself ! Cheers in advance . var selectedSiteType = from sites in siteTypeList where sites.SiteTypeID == temp select sites ; mSiteTypeSub.EditSitetype ( selectedSiteType ) ; Argument 1 : can not convert from 'System.Collections.Generic.IEnumerable < DeviceManager_take_2.SiteType > ' to 'DeviceManager_take_2.SiteType '",How to use returned linq variable ? "C_sharp : I have a list ( to be precise ImmutableHashSet < ListItem > from System.Collections.Immutable ) of base items and try to call the following codebut this returns false.Even though the following code lines all return trueI can even write the following and it returns true : What am I doing wrong , I would like to avoid writing the .OfType stuff.Edit : Edit2 : Here a reproducible code of my problem , seems like ImmutableHashSet < > caches GetHashCode and does n't compare the current GetHashCode with the entries inside the list , is there a way to tell ImmutableHashSet < > that the GetHashCode of the items could be different , atleast for the item I am currently checking since hey its the damn same reference ... If I would change the ImmutableHashSet < > to ImmutableList < > the code works fine , so if you guys do n't come up with any good idea I will switch to the list . _baseList.Contains ( derivedItem ) object.ReferenceEquals ( _baseList.First ( ) , derivedItem ) object.Equals ( _baseList.First ( ) , derivedItem ) _baseList.First ( ) .GetHashCode ( ) == derivedItem.GetHashCode ( ) _baseList.OfType < DerivedClass > ( ) .Contains ( derivedItem ) private ImmutableHashSet < BaseClass > _baseList ; public class BaseClass { } public class DerivedClass : BaseClass { } public void DoStuff ( ) { var items = _baseList.OfType < DerivedClass > ( ) .ToList ( ) ; foreach ( var derivedItem in items ) { RemoveItem ( derivedItem ) ; } } public void RemoveItem ( BaseClass derivedItem ) { if ( _baseList.Contains ( derivedItem ) ) { //does n't reach this place , since _baseList.Contains ( derivedItem ) returns false ... _baseList = _baseList.Remove ( derivedItem ) ; } //object.ReferenceEquals ( _baseList.First ( ) , derivedItem ) == true //object.Equals ( _baseList.First ( ) , derivedItem ) == true //_baseList.First ( ) .GetHashCode ( ) == derivedItem.GetHashCode ( ) == true //_baseList.OfType < DerivedClass > ( ) .Contains ( derivedItem ) == true } namespace ConsoleApplication1 { class Program { private static ImmutableHashSet < BaseClass > _baseList ; static void Main ( string [ ] args ) { _baseList = ImmutableHashSet.Create < BaseClass > ( ) ; _baseList = _baseList.Add ( new DerivedClass ( `` B1 '' ) ) ; _baseList = _baseList.Add ( new DerivedClass ( `` B2 '' ) ) ; _baseList = _baseList.Add ( new DerivedClass ( `` B3 '' ) ) ; _baseList = _baseList.Add ( new DerivedClass ( `` B4 '' ) ) ; _baseList = _baseList.Add ( new DerivedClass ( `` B5 '' ) ) ; DoStuff ( ) ; Console.WriteLine ( _baseList.Count ) ; //output is 5 - put it should be 0 ... Console.ReadLine ( ) ; } private static void DoStuff ( ) { var items = _baseList.OfType < DerivedClass > ( ) .ToList ( ) ; foreach ( var derivedItem in items ) { derivedItem.BaseString += `` Change ... '' ; RemoveItem ( derivedItem ) ; } } private static void RemoveItem ( BaseClass derivedItem ) { if ( _baseList.Contains ( derivedItem ) ) { _baseList = _baseList.Remove ( derivedItem ) ; } } } public abstract class BaseClass { private string _baseString ; public string BaseString { get { return _baseString ; } set { _baseString = value ; } } public BaseClass ( string baseString ) { _baseString = baseString ; } public override int GetHashCode ( ) { unchecked { int hashCode = ( _baseString ! = null ? _baseString.GetHashCode ( ) : 0 ) ; return hashCode ; } } } public class DerivedClass : BaseClass { public DerivedClass ( string baseString ) : base ( baseString ) { } } }",ImmutableHashSet .Contains returns false "C_sharp : In this following example the third evaluation returns false , all good , but the fourth example returns true..I do n't quite understand how this works however , by default Object.Equals compares two references for object equality , and seeing as a and b both point to a unique instance of a string , this should return false , which it does in the third example but not in the fourth.Now I understand why it returns true in the 2nd example seeing as the .Equals ( ) method is overridden in the string class , but in the fourth example we 're casting this string as an object.So would n't it call Object.Equals in this case ? static void Main ( ) { // Create two equal but distinct strings string a = new string ( new char [ ] { ' h ' , ' e ' , ' l ' , ' l ' , ' o ' } ) ; string b = new string ( new char [ ] { ' h ' , ' e ' , ' l ' , ' l ' , ' o ' } ) ; Console.WriteLine ( a == b ) ; // Returns true Console.WriteLine ( a.Equals ( b ) ) ; // Returns true // Now let 's see what happens with the same tests but // with variables of type object object c = a ; object d = b ; Console.WriteLine ( c == d ) ; // Returns false Console.WriteLine ( c.Equals ( d ) ) ; // Returns true }",Overriding Equals and type casting "C_sharp : Is there a way to launch the OpenFileDialog in the C : \Users\Public\Documents folder ? I am writing a C # application , using the DotNet framework . I am trying to launch an OpenFileDialog , with an InitialDirectory of `` C : \\Users\\Public\\Documents\\ '' and a FileName of `` world.txt '' . Unfortunately , the OpenFileDialog is putting me in the Documents shortcut instead of into C : \Users\Public\Documents .Expected resultsI expect to see the OpenFileDialog open , with the top textbox showing > This PC > Windows7_OS ( C : ) > Users > Public > Documents and the bottom textbox showing world.txt . I expect that if I click in the top textbox , it will show C : \Users\Public\Documents .Actual resultsThe OpenFileDialog opens . The top textbox shows > This PC > Documents and the bottom textbox shows world.txt . If I click in the top textbox , it shows Documents . The displayed folder contents are not the same as the contents of C : \Users\Public\Documents .Things I have triedI have stopped the code in the Visual Studio debugger after the following line of code : OpenFileDialog dlg = new OpenFileDialog ( ) ; In the Immediate Window , I have executed code such as the following : I cancel out of each dialog.I used C : \WINDOWS\System32\cmd.exe to cd between C : \ and C : \Users\ and C : \Users\Public and C : \Users\Public\Documents\ .Results of things I have tried When dlg.InitialDirectory = `` C : \\NonExistentDirectory\\ '' , the dialog 's folder initially displays as This PC > Documents > Visual Studio 2015 > Projects > SimpleGame > Controller > bin > Debug '' . Clicking in the textbox causes it to display C : \Users\Owner\Documents\Visual Studio 2015\Projects\SimpleGame\Controller\bin\Debug . I therefore assume that OpenFileDialog silently handles an invalid InitialDirectory by not changing directories . In this case , it is defaulting to my project 's assembly 's bin 's Debug folder.When dlg.InitialDirectory is `` C : \\ '' or `` C : \\Users\\ '' or `` C : \\Users\\Public\\ '' the dialog behaves as expected . Clicking in the top textbox produces C : \ or C : \Users or C : \Users\Public respectively.When dlg.InitialDirectory = `` C : \\Users\\Public\\Documents\\ '' the dialog behaves incorrectly . The top textbox shows > This PC > Documents and the bottom textbox shows world.txt . If I click in the top textbox , it shows Documents . The displayed folder contents are not the same as the contents of C : \Users\Public\Documents .Using cmd.exe lets me cd between the folders as expected , including into C : \Users\Public\Documents .My environmentI am running Microsoft Visual Studio Community 2015 Version 14.0.23107.0 D14REL , using Microsoft Visual C # 2015 . My operating system is Windows 10 Pro . dlg.FileName = `` world.txt '' ? dlg.FileName dlg.InitialDirectory = `` C : \\NonExistentDirectory\\ '' ; dlg.ShowDialog ( ) ; dlg.InitialDirectory = `` C : \\ '' ; dlg.ShowDialog ( ) ; dlg.InitialDirectory = `` C : \\Users\\ '' ; dlg.ShowDialog ( ) ; dlg.InitialDirectory = `` C : \\Users\\Public\\ '' ; dlg.ShowDialog ( ) ; dlg.InitialDirectory = `` C : \\Users\\Public\\Documents\\ '' ; dlg.ShowDialog ( ) ;",Can I launch DotNet 's OpenFileDialog in C : \Users\Public\Documents ? "C_sharp : I ca n't really go into to much depth of my project for a number of constraining reasons.Essentially I am trying to pre-validate an object before serializing it and then validating it against a schema . The schema has validation for a name , which I know is n't ideal and your better off not validating a name - but I ca n't seem to replicate a valid regex for what the schema is trying to do.I simply thought in the above case that I could try and just use the xsd : pattern for the charset.I tried to use [ A-Za-z \- & apos ; ] * which returned a name such as Luke2 as valid , but the schema validation said it was n't because it contained a number.My question is , how can I replicate the above in a single c # regex ? Also , is there any differences between how the schema pattern operates compared to if I used it in .NET that I can note for the future ? < xsd : simpleType name= '' CharsetD '' > < xsd : restriction base= '' xsd : string '' > < xsd : pattern value= '' [ A-Za-z \- & apos ; ] * '' / > < /xsd : restriction > < /xsd : simpleType > < xsd : element minOccurs= '' 0 '' maxOccurs= '' 2 '' name= '' Fore '' > < xsd : simpleType > < xsd : restriction base= '' CharsetD '' > < xsd : minLength value= '' 1 '' / > < xsd : maxLength value= '' 35 '' / > < xsd : pattern value= '' [ A-Za-z ] . * '' / > < /xsd : restriction > < xsd : simpleType > < /xsd : element >",Is there a difference between XSD : Pattern and C # Regex ? "C_sharp : I have several commands in my ViewModel and I want to have the CanExecute of each button to be bound to an observable busy which is defined as none of the buttons is currently executing.The following is what I came up with , but obviously it runs into a NullReferenceException.Also the CanExecuteObservable property on ReactiveCommand is readonly , so I need to define an IObservable before I initialize the commands.Any ideas on how to solve this chicken and egg problem ? A better way of observing busy state for a ViewModel ( or a collection of ViewModels ) would be appreciated also : - ) busy = Observable.CombineLatest ( this.PlayCommand.IsExecuting , this.PauseCommand.IsExecuting , ( play , pause ) = > play & & pause ) ; this.PauseCommand = new ReactiveCommand ( busy.Select ( b = > ! b ) ) ; this.PlayCommand = new ReactiveCommand ( busy.Select ( b= > ! b ) ) ;",Howto let ReactiveCommands observe their own IsExecuting observable "C_sharp : Suppose we have two classes : The task is to express the following code in linq expressions : To do that I tried to use the following code : Running this code withthrows an ArgumentException at the last line ( at the return statement in the GetCondition ) , saying that the types of arguments are mismatched . Having analysed this code I found out that Activator.CreateInstance < TChildKey > ( ) returns object , but not TChildKey , when TChildKey is System.Nullable < T > , i.e . ifTrue.Type is object , while I expected it to be System.Nullable < byte > .This very issue is discussed in SO : Creating a nullable object via Activator.CreateInstance returns null pointing to Reflection and NullableBut none of these suggests anything to solve the issue.Is there a way to create an instance of exactly System.Nullable < T > type , having value null ? Or maybe there is some other way to express the original conditional expression ? public class ParentEntity { public ChildEntity Child { get ; set ; } } public class ChildEntity { public byte ? NullableValue { get ; set ; } public byte Value { get ; set ; } } parent.Child == null ? null : parent.Child.NullableValue public static Expression GetCondition < TParent , TChild , TChildKey > ( Expression < Func < TParent , TChild > > pe , Expression < Func < TChild , TChildKey > > ce ) { var test = Expression.Equal ( pe.Body , Expression.Constant ( null ) ) ; var ifTrue = Expression.Constant ( Activator.CreateInstance < TChildKey > ( ) ) ; var ifFalse = Expression.Property ( pe.Body , ( ce.Body as MemberExpression ) .Member.Name ) ; return Expression.Condition ( test , ifTrue , ifFalse ) ; } Expression < Func < ParentEntity , ChildEntity > > pe = n = > n.Child ; GetCondition ( pe , n = > n.Value ) ; // okGetCondition ( pe , n = > n.NullableValue ) ; // throws an ArgumentException",How to create an instance of a Nullable < T > ? "C_sharp : So I was stuck on this problem for about a week . I was trying to run a project to recieve a TCP connection and start a SignalR Hub as a Service . Both worked perfectly running the project as a .exe file . The TCP part would work perfectly , however I was having problems with the SignalR side.The reason ended up being the using statement.BeforeAfterI had tried running the the code with the Console.WriteLine ( ) commented out , as I thought it might be throwing an exception as the is no console to output to once run as a service . This also did n't work , but also would n't work as a .exe file either as it needed the Console.ReadLine ( ) to keep the console open , sort of how you need it to keep HelloWorld.cs open . Once the using wrapper was removed along with the console , it would then work in both the .exe and the service.I have read that the using statement kills objects in it once you leave the wrapper . But I do n't understand how the After bit of code keeps the .exe code open once running . Is there any point in using using or have I been using it wrong ? EditThe call is being made from the StartSignalR ( ) method . using ( WebApp.Start < SignalrStartup > ( url ) ) { Console.ForegroundColor = ConsoleColor.Green ; Console.WriteLine ( `` Server running on { 0 } '' , url ) ; // was url Console.WriteLine ( `` ID\tMessage '' ) ; Console.ReadLine ( ) ; } WebApp.Start < SignalrStartup > ( url ) ; protected override void OnStart ( string [ ] args ) { Task.Factory .StartNew ( ( ) = > StartTCP ( ) ) .ContinueWith ( t = > StartSignalR ( ) ) ; }",Explain why `` using '' wo n't work in service ? "C_sharp : I am trying to do 2 left joins . I have tested the query in SQL server and it works but I am unable to recreate the query in linq . The query : In LINQ : I am getting Object reference not set to an instance of an object.at line on new { co.InvoiceId , co.ConsumerId , } . If I remove into temp2 from co in temp2.DefaultIfEmpty ( ) , it displays but invoice ids which does not have any consumer id is not displayed . How do I do a proper left join where 3 tables are involved ? select Master.InvoiceId , Consumer.ConsumerId , ConsumerCharge.ChargeId , Amount from Master left outer join Consumer on Master.InvoiceId=Consumer.InvoiceId left outer join ConsumerCharge on Consumer.ConsumerId = ConsumerCharge.ConsumerId and Consumer.InvoiceId = ConsumerCharge.InvoiceId and Master.InvoiceId = ConsumerCharge.InvoiceIdorder by InvoiceId var query = from m in IM.GetMaster ( ) join co in CM.GetConsumers ( ) on m.InvoiceId equals co.InvoiceId into temp2 from co in temp2.DefaultIfEmpty ( ) join ch in CCM.GetCharge ( ) on new { co.InvoiceId , co.ConsumerId , } equals new { ch.InvoiceId , ch.ConsumerId } into temp from ch in temp.DefaultIfEmpty ( ) orderby m.InvoiceId select new { InvioceID = m.InvoiceId , ConsumerID = co == null ? 0 : co.ConsumerId , ChargeID = ch == null ? 0 : ch.ChargeId , Amount = ch == null ? 0 : ch.Amount } ;",NullReferenceException when Selecting from Left Join "C_sharp : Very very rare my MVC 3 application have following exception . It is only in Release mode , and when it starts only restart of IIS application pool helps . Does anyone could give me a tip what can cause this error ? And the exception : System.NullReferenceException : Object reference not set to an instance of an object . at System.Web.Mvc.FilterProviderCollection. < RemoveDuplicates > d__b.MoveNext ( ) at System.Linq.Buffer ` 1..ctor ( IEnumerable ` 1 source ) at System.Linq.Enumerable. < ReverseIterator > d__a0 ` 1.MoveNext ( ) at System.Linq.Enumerable.WhereSelectEnumerableIterator ` 2.MoveNext ( ) at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) at System.Web.Mvc.FilterInfo..ctor ( IEnumerable ` 1 filters ) at System.Web.Mvc.ControllerActionInvoker.GetFilters ( ControllerContext controllerContext , ActionDescriptor actionDescriptor ) at System.Web.Mvc.ControllerActionInvoker.InvokeAction ( ControllerContext controllerContext , String actionName ) at System.Web.Mvc.Controller.ExecuteCore ( ) at System.Web.Mvc.ControllerBase.Execute ( RequestContext requestContext ) at System.Web.Mvc.MvcHandler. < > c__DisplayClass6. < > c__DisplayClassb. < BeginProcessRequest > b__5 ( ) at System.Web.Mvc.Async.AsyncResultWrapper. < > c__DisplayClass1. < MakeVoidDelegate > b__0 ( ) at System.Web.Mvc.MvcHandler. < > c__DisplayClasse. < EndProcessRequest > b__d ( ) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute ( ) at System.Web.HttpApplication.ExecuteStep ( IExecutionStep step , Boolean & completedSynchronously )",Strange exception in MVC "C_sharp : I 'm using LINQPad to test code ( what a great product , I must say ) but now I 'm encountering an exception when I try to set the Thread.CurrentPrincipal to a custom IPrincipal that is marked with the SerializableAttributefollowing a sample that demonstrate the problemWhen I run this code in LINQPad ( C # Program as Language ) I get the following exceptionIf I remove the Serializable attribute everything goes fine . It seems a problem related with the AppDomain architecture that LINQPad uses and the inability of the framework to find the assembly that define the MyCustomPrincipal . Also , I believe that defining MyCustomPrincipal into another assembly and putting it into the GAC would solve the problem , but that 's not an option for me.Anyone have an idea ? Thanks , MarcoEDIT : I do n't know if it could help , but I 've had the same problem with SqlDependency.Start : putting Serializable on IPrincipal made the framework to throw an error complaining that it ca n't find the assembly that define the type of IPrincipal . I 've solved with an ignominious hack : void Main ( ) { Thread.CurrentPrincipal = new MyCustomPrincipal ( ) ; } // Define other methods and classes here [ Serializable ] public class MyCustomPrincipal : IPrincipal { public bool IsInRole ( string role ) { return true ; } public IIdentity Identity { get { return new WindowsIdentity ( `` RECUPERA\\m.casamento '' ) ; } } } Type is not resolved for member 'UserQuery+MyCustomPrincipal , query_nhxfev , Version=0.0.0.0 , Culture=neutral , PublicKeyToken=null ' RuntimeMethodInfo : PluginWindowManager.get_Form ( ) System.Security.Principal.IPrincipal principal ; principal = System.Threading.Thread.CurrentPrincipal ; System.Threading.Thread.CurrentPrincipal = null ; try { SqlDependency.Start ( connectionString ) ; m_SqlDependencyStarted = true ; } catch ( Exception ex ) { throw ( ex ) ; } finally { System.Threading.Thread.CurrentPrincipal = principal ; }",linqpad and custom IPrincipal serializable "C_sharp : Let 's say you have a date string like follows : How would you shorten this string like follows ( or something similar ) Because imagine 30 days in a row it would be better to see 12/1-31/10 than have all dates listed.Just to make it a little more compact ? Thanks , rod . 11/15/2010 , 12/1/10 , 12/2/10 , 12/3/10 , 12/4/10 , 12/9/10 11/15/2010 , 12/1-4 , 9/10",dates in shorthand "C_sharp : I 've found a bug ( feature ? ) during learning dynamic in C # . Can anyone explain me , why do I have an exception ? ? Note : typeof both exectuer and someObj is dynamic static class Program { public static void Main ( string [ ] args ) { dynamic someObj = ConstructSomeObj ( ( Action ) ( ( ) = > Console.WriteLine ( `` wtf '' ) ) ) ; var executer = someObj.Execute ; executer ( ) ; // shows `` wtf '' someObj.Execute ( ) ; // throws RuntimeBinderException Console.ReadKey ( ) ; } static dynamic ConstructSomeObj ( dynamic param ) = > new { Execute = param } ; }",Unpredictible behaviour in c # dynamic "C_sharp : Consider this example , it shows two possible ways of lazy initialization . Except for being thread-safe , are there any specific advantates of using Lazy < T > here ? UPDATE : Please consider above code as a simple example , data types are irrelevant , the point here is to compare Lazy < T > over standard lazy initialization . class Customer { private decimal ? _balance2 ; private static decimal GetBalanceOverNetwork ( ) { //lengthy network operations Thread.Sleep ( 2000 ) ; return 99.9M ; } public decimal ? GetBalance2Lazily ( ) { return _balance2 ? ? ( _balance2 = GetBalanceOverNetwork ( ) ) ; } private readonly Lazy < decimal > _balance1 = new Lazy < decimal > ( GetBalanceOverNetwork ) ; public Lazy < decimal > Balance1 { get { return _balance1 ; } } }",What advantages does Lazy < T > offer over standard lazy instantiation ? "C_sharp : I have a long text and part of the text is Hello , i am John how ( 1 ) are ( are/is ) you ? I used this to detect ( 1 ) .But I got stuck here at continue on how to detect after ( 1 ) to find are.Full code ( thanks to falsetru for bringing me this far ) : I assume if I split like this , it will remove all the words after ( 0-9 ) , however when I run it it only removes the word after ( ) in the last detection.As you can see the word after ( 7 ) is gone but the rest is not . How do I detect the are after the ( 1 ) ? Is it possible to replace the word after ( 1 ) with a textbox too ? string optionPattern = `` [ \\ ( ] + [ 0-9 ] + [ \\ ) ] '' ; Regex reg = new Regex ( optionPattern ) ; string optionPattern = @ '' ( ? < =\ ( \d+\ ) ) \w+ '' ; Regex reg = new Regex ( optionPattern ) ; string [ ] passage = reg.Split ( lstQuestion.QuestionContent ) ; foreach ( string s in passage ) { TextBlock tblock = new TextBlock ( ) ; tblock.FontSize = 19 ; tblock.Text = s ; tblock.TextWrapping = TextWrapping.WrapWithOverflow ; wrapPanel1.Children.Add ( tblock ) ; }",Detect the word after a regex "C_sharp : I 've defined my own Excel function ( called ADXExcelFunctionDeescriptor ) . The method stub looks like following : The method receives an array of double values and a string , called name.In the design view my ADXExcelFunctionDeescriptor looks like following : I call and set the function by the following lines of code : This will result in an exception ! The exception looks like the following : Further , if I do n't pass the tagName parameter the function returns a result without any exception or error . So I think it has something to do with the string parameter.I also tried to surround the string parameter with `` or ' characters but no change so far.Further if I type the function directly into Excel it works without any problems . So , for example , if I type in the following formula in Excel : Maybe I miss out something or doing something wrong ? public static object ExecuteMyFunction ( object values , object tagName ) { // Some code here } var formula = string.Format ( @ '' = { 0 } ( { 1 } ; { 2 } ) '' , Temp.FORMULA_NAME , this.DataRangeTextBox.Text , tagCaption ) ; resultRange.set_Value ( Type.Missing , formula ) ; resultRange.Formula = resultRange.Value ; System.Runtime.InteropServices.COMException occurred HResult=-2146827284 Message=Ausnahme von HRESULT : 0x800A03EC Source= '' '' ErrorCode=-2146827284 StackTrace : bei System.RuntimeType.ForwardCallToInvokeMember ( String memberName , BindingFlags flags , Object target , Int32 [ ] aWrapperTypes , MessageData & msgData ) bei Microsoft.Office.Interop.Excel.Range.set_Value ( Object RangeValueDataType , Object ) bei bb.ExcelToolbar.Controls.bbControl.ApplyFormula ( Object sender , EventArgs e ) in c : \xx\yy\zz\bb\bb.ExcelToolbar\Controls\bbControlcs : Zeile 88 . InnerException : var formula = string.Format ( @ '' = { 0 } ( { 1 } ) '' , Temp.FORMULA_NAME , this.DataRangeTextBox.Text , tagCaption ) ; resultRange.set_Value ( Type.Missing , formula ) ; resultRange.Formula = resultRange.Value ; =Temp.DoSomething ( B2 : B13 ; '' Flow '' )",Excel function throws exception when set by code behind . Works when used in excel "C_sharp : I read this statement in a C # book . Enumerations do not necessarily need to follow a sequential ordering , and need not have unique values.If I understand that statement , it means one of this is acceptable ( I do n't know which ) :1.2.Can someone please explain to me ? I thought C # was supposed to be a subset of C/C++ . enum EmpType { Manager = 1 , Grunt = 1 , Contractor = 100 , VicePresident = 9 } enum EmpType { Manager = 10 , Manager = 1 , Contractor = 100 , VicePresident = 9 }",enum types in C # "C_sharp : This program execute two different threads and tell me who the winner of the `` race '' is.Unexpectedly sometimes BOTH threads `` wins '' ( I expected someone or no one to win ) . Is this expected behaviour and why ? I 'm obviously missing something fundamental here.Results : class Program { public volatile static int a = 0 ; public volatile static int b = 0 ; public static void Main ( ) { for ( int i = 0 ; i < 1000 ; i++ ) { a = 0 ; b = 0 ; Parallel.Invoke ( delegate { a = 1 ; if ( b == 0 ) Console.WriteLine ( `` A wins '' ) ; } , delegate { b = 1 ; if ( a == 0 ) Console.WriteLine ( `` B wins '' ) ; } ) ; Console.WriteLine ( System.Environment.NewLine ) ; Thread.Sleep ( 500 ) ; } } } A winsB winsA winsB winsA wins ...",Variant of Dekker 's algorithm confusion "C_sharp : So , I 'm trying to wrap my head around Microsoft 's Dataflow library . I 've built a very simple pipeline consisting of just two blocks : Now I can asynchronously process Foo instances by calling : What I do not understand is how to do the processing synchronously , when needed . I thought that waiting on SendAsync would be enough : But apparently it returns as soon as item is accepted by first processor in pipeline , and not when item is fully processed . So is there a way to wait until given item was processed by last ( end ) block ? Apart from passing a WaitHandle through entire pipeline . var start = new TransformBlock < Foo , Bar > ( ) ; var end = new ActionBlock < Bar > ( ) ; start.LinkTo ( end ) ; start.SendAsync ( new Foo ( ) ) ; start.SendAsync ( new Foo ( ) ) .Wait ( ) ;",How to wait until item goes through pipeline ? "C_sharp : This is a very weird behaviour of Newtonsoft.Json 's serialization functionality . I 've tried almost everything ( for instance I did n't go ahead and use .NET Reflector to walk step by step through the Newtonsoft.Json.dll assembly 's algorithms ) .SymptomsThe situation is as follows : I have a small POCO which holds 4 string properties : I create an array of 618 MyPoco instances : The resulting json is always broken at the middle by an ellipsis : The exact anatomy of the resulting string is this : The first part of the string is the successful serialization of the first 156 MyPoco instancesThe second part of the string is literally 3 dots ( which also breaks the Json syntax - which is actually a good thing ) followed by the last half of the MyPoco instance who 's 0 based index is 466The third part of the string is the successful serialization of the last 152 MyPoco instancesSo basically , to wrap it up : Newtonsoft.Json is successfully serializing the first 156 items of my array ( indices 0 through 155 ) It also successfully serializes the last 152 items ( indices 467 through 617 ) It also successfully writes the opening and closing square brackets ( representing the Array ) at the very beginning and at the very end of the resulting stringAt the very middle of this string , it adds and ellipsis which cuts the string in half , after what would appear to be a leading bunch of 15,000 `` healthy '' characters and before the trailing bunch of 15,000 `` healthy '' charactersProblemI do n't know what to do . I could go on and use JavaScriptSerializer but I do n't want to lose trust in Newtonsoft.Json.That is the main issue.It feels like it should 've crashed with a comprehensive exception , but instead it silently fails , which could leave to serious complications in production apps.I 've looked everywhere for `` Max Buffer Size '' like settings and could n't find anything more than the already notorious `` Max Depth '' setting which is not the case here since I have a 3 layer tree ( with primitive strings on the deepest layer ) .Has anyone ever experienced such a weird behaviour of Newtonsoft.Json ? Further informationI used both 8.0.2 and 7.0.1 Nuget package versions ( I skipped 8.0.1 ) .Both versions exhibit the same symptoms.I 'm targeting .NET 4.6 and we 're talking about an empty Console App ( I replicated the symptoms in the cleanest way possible ) .EDIT # 1Here 's a snapshot of the ellipsis as seen right there , in the Visual Studio debugger : public class MyPoco { public string op { get ; set ; } public string left { get ; set ; } public string right { get ; set ; } public string result { get ; set ; } }",Newtonsoft.Json adds ellipsis ( ... ) at the middle of a serialized array "C_sharp : I 'm using a lot of dictionary collections that contain other dictionary collections like : I 'm looping through these maps , and passing them around in parameters in my code.This seems like a bad idea since you ca n't really extend the nature of these collections now.Should I wrap these around in a class ? Dictionary < Guid , List < string > > ( ) Dictionary < Guid , Dictionary < Guid , List < string > > > ( )",Using many dictionaries within dictionaries in my code C_sharp : When I was running my tests on C # -visualnUnit it runs successfully but when I was running it on Nunit only and just having the dll on the project it out puts like this : I was having multithreading here . It works just fine with my vs and visualnUnit . The problem was when I tried to run it in Nunit only.I am declaring IWebdriver driver = new ChromeDriver ( ) ; in visualNunit and vs it does n't spawn any cmd and runs smoothly while with using Nunit it only spawns cmd prompts of its driver and does n't continues the flow.The system I am running on is : Windows7 64bit . Started ChromeDriverport=49771version=23.0.1240.0log=\chromedriver.log [ 1220/011848 : ERROR : ipc_sync_channel.cc ( 738 ) ] Canceling pending sends [ 1220/011848 : ERROR : ipc_sync_channel.cc ( 738 ) ] Canceling pending sends [ 1220/011848 : ERROR : ipc_sync_channel.cc ( 738 ) ] Canceling pending sends [ 18104:3564:1220/011849 : ERROR : window_impl.cc ( 55 ) ] Failed to unregister class Chrome_WidgetWin_0 . Error = 1412,Running Selenium test on nUnit not executing scripts "C_sharp : I am trying to understand the performance impact of having one DbContext class vs multiple when using EF6 framework.For example , if we have a simple DbContext such as this : Now let us say I have a service that uses the said DbContext in the following way : At what point in time did the DbContext go to the database and retrieved all cars that are stored in the database ? Was it when I called var dbContext = new MainDbContext ( ) ; or was it when I called Cars = dbContext.Cars.ToList ( ) ; ? If former , if I had a DbContext that contains 100 tables , will all 100 tables be queried when the DbContext is created ? public class MainDbContext : DbContext { public DbSet < Car > Cars { get ; set ; } public void AddCar ( Car car ) { Cars.Add ( car ) ; SaveChanges ( ) ; } } public class CarService { public List < Car > Cars { get ; private set ; } public CarService ( ) { var dbContext = new MainDbContext ( ) ; Cars = dbContext.Cars.ToList ( ) ; } }",When are queries executed on DbContext "C_sharp : I have the following string : In C # is there anyway to break this string out into Long . Latt . and then city state and discare the middle part ? So basically I want 3 strings : Is this possible with multiple forms of this string ? They are in the same formate but obviously the data would be different.Thanks +53.581N -113.587W 4.0 Km W of Edmonton , AB LongLattLocation .",C # Break string into multiple parts "C_sharp : I know that the compiler can cast from lambda expression to Predicate.For example : is good.But when I want to create a tuple that holds a Predicate.I tried to do this ( simplified version ) : and I got the compilation error : The type arguments for method 'System.Tuple.Create ( T1 ) ' can not be inferred from the usage . Try specifying the type arguments explicitly.My question is what this is an error , where is the ambiguity here ? ( I know I can fix it by casting : t = Tuple.Create ( ( Predicate < int > ) ( x = > true ) ) ; but I want to understand why the first way is not good , and also I want not to do the casting to save typing : ) Predicate < int > p = x = > true ; Tuple < Predicate < int > > t ; t = Tuple.Create ( x = > true ) ;",Why I ca n't use lambda expression inside Tuple.Create ? "C_sharp : I am working on a Windows Forms app for quite some time now , and I really find myself doing more typecasts in the GUI code than I ever did in my underlying business code.What I mean becomes apparent if you watch the ComboBox control that accepts some vague `` object '' as it 's item . Then you go off and may display some DisplayMember and a ValueMember and so on.If I want to retrieve that value later I need to typecast my object back to what it was . Like with strings getting the value takesSince there are generics in the Framework for quite some time now , I still wonder why in the Hell not one control from the standard toolbox is generic.I also find myself using the .Tag property on ListViewItems all the time to keep the displayed domain object . But everytime I need to access that object I then need another typecast.Why cant I just create a ComboBox or ListView with items of type ListViewItemAm I missing something here or is this just another example of not perfectly well thought through controls ? string value = ( string ) combobox1.SelectedItem ;",Strongly Typed Controls in .NET "C_sharp : I have data that has been stored using binary serialization for the following class : At some point , the class was changed to this : This is causing issues deserializing old data.My first thought was to implement ISerializable , but this class has numerous properties as well as hundreds of inheriting classes that I would have to implement this for as well.I would like to either change the old data to match the current structure during deserialization or have a clean way of upgrading the old data . [ Serializable ] public abstract class BaseBusinessObject { private NameValueCollection _fieldErrors = new NameValueCollection ( ) ; protected virtual NameValueCollection FieldErrors { get { return _fieldErrors ; } set { _fieldErrors = value ; } } ... } [ Serializable ] public abstract class BaseBusinessObject { private Dictionary < string , string > _fieldErrors = new Dictionary < string , string > ( ) ; protected virtual Dictionary < string , string > FieldErrors { get { return _fieldErrors ; } set { _fieldErrors = value ; } } ... }",How do I deserialize old data for a type that has changed ? "C_sharp : My C # application writes its full path surrounded by double quotes to a file , with : Normally it works , the written file containsBut , if the executable path of my application contains a # , something weird happens . The output becomes : The slashes after the # become forward slashes . This causes issues with the system I am developing.Why is this happening , and is there a way to prevent it that is more elegant than string.replacing the path before writing ? streamWriter.WriteLine ( `` \ '' '' + Application.ExecutablePath + `` \ '' '' ) ; `` D : \Dev\Projects\MyApp\bin\Debug\MyApp.exe '' `` D : \Dev\Projects # /MyApp/bin/Debug/MyApp.exe ''",Odd C # path issue "C_sharp : I 'm attempting to capture a PayPal transaction that has been authorized using the PayPal button . I 'm trying to use CyberSource Simple Order API to do this . I have the only 3 pieces of information that seem to come back from the PayPal button are : payerID , paymentID and paymentToken . I 've tried a few ways of handing this off to the Simple Order API , but always get a 102 code with the DECLINE message in the response . Cybersource 's logging system indicates this is because The following request field ( s ) is either invalid or missing : request_token.Do I need to conduct the whole transaction - authorize and capture - via cybersource ? Or what is the way I can take the paypal-generated button and authorize a transaction , then capture it via CyberSource ? Here 's my code snippet for the CyberSource SOAPI request : RequestMessage request = new RequestMessage { merchantID = WebConfigurationManager.AppSettings [ `` cybs.merchantID '' ] , payPalDoCaptureService = new PayPalDoCaptureService { run = `` true '' , invoiceNumber = orders , paypalAuthorizationId = authId , paypalAuthorizationRequestToken = requestToken , completeType = `` Complete '' } , clientApplication = `` MyClient Application '' , clientApplicationVersion = `` 2.0 '' , clientApplicationUser = userName , clientEnvironment = WebConfigurationManager.AppSettings [ `` Tier '' ] , merchantReferenceCode = orders , customerID = OrderConstants.CustomerNumber , merchantDefinedData = new MerchantDefinedData { field1 = `` Customer # : `` + OrderConstants.CustomerNumber , field2 = orders } , purchaseTotals = new PurchaseTotals { currency = `` usd '' , grandTotalAmount = total , taxAmount = taxtotal } , item = items.ToArray ( ) } ; ReplyMessage reply = new ReplyMessage ( ) ; try { reply = SoapClient.RunTransaction ( request ) ; } catch ( Exception ex ) { reply.decision = `` SYSTEM ERROR '' ; reply.additionalData = string.Format ( `` Error processing request . Exception message : { 0 } '' , ex.Message ) ; }",CyberSource Simple Order API Capture PayPal transaction "C_sharp : I have often wondered this , is there a performance cost of splitting a string over multiple lines to increase readability when initially assigning a value to a string . I know that strings are immutable and therefore a new string needs to be created every time . Also , the performance cost is actually irrelevant thanks to today 's really fast hardware ( unless you are in some diabolical loop ) . So for example : How does the JVM or .Net 's compiler and other optimizations handle this . Will it create a single string ? Or will it create 1 string then a new concatenating the value and then another one concatenating the values again ? This is for my own curiosity . String newString = `` This is a really long long long long long '' + `` long long long long long long long long long long long long `` + `` long long long long long long long long long string for example . `` ;",What is the performance cost of assigning a single string value using + 's "C_sharp : I am trying to use Rx to read from a TCPClient receive stream and parse the data into an IObservable of string , delimited by newline `` \r\n '' The following is how I 'm receiving from the socket stream ... Here is what I came up with to parse the string . This currently does not work ... The message subject receives the message in chunks so I 'm trying to concat them and test whether the concatenated string contains newline , thus signaling the buffer to close and output the buffered chunks . Not sure why it is n't working . Seems that I only get the first chunk out of obsStrings.So I am looking for two things . I 'd like to simplify reading of the io stream and eliminate the use of the messages subject . Secondly , I 'd like to get my string parsing working . I have been hacking on this for a bit and can not come up with a working solution . I am a beginner with Rx.EDIT : Here is the finished product after the problem was solved ... . '' ReceiveUntilCompleted '' is an extension from the RXX project . var messages = new Subject < string > ( ) ; var functionReceiveSocketData = Observable.FromAsyncPattern < byte [ ] , int , int , SocketFlags , int > ( client.Client.BeginReceive , client.Client.EndReceive ) ; Func < byte [ ] , int , byte [ ] > copy = ( bs , n ) = > { var rs = new byte [ buffer.Length ] ; bs.CopyTo ( rs , 0 ) ; return rs ; } ; Observable .Defer ( ( ) = > { var buffer = new byte [ 50 ] ; return from n in functionReceiveSocketData ( buffer , 0 , buffer.Length , SocketFlags.None ) select copy ( buffer , n ) ; } ) .Repeat ( ) .Subscribe ( x = > messages.OnNext ( System.Text.Encoding.UTF8.GetString ( x ) ) ) ; obsStrings = messages.Buffer < string , string > ( ( ) = > messages.Scan ( ( a , c ) = > a + c ) .SkipWhile ( a = > ! a.Contains ( `` \r\n '' ) ) ) ; var receivedStrings = socket.ReceiveUntilCompleted ( SocketFlags.None ) .SelectMany ( x = > System.Text.Encoding.UTF8.GetString ( x ) .ToCharArray ( ) ) .Scan ( String.Empty , ( a , b ) = > ( a.EndsWith ( `` \r\n '' ) ? `` '' : a ) + b ) .Where ( x = > x.EndsWith ( `` \r\n '' ) ) .Select ( buffered = > String.Join ( `` '' , buffered ) ) .Select ( a = > a.Replace ( `` \n '' , `` '' ) ) ;",Observable Network IO Parsing "C_sharp : I am using Microsoft.ReportViewer.WebForms version 11 via an aspx page embedded in an MVC application . The report is rendered directly as a PDF from the report viewer.ProblemI have a tablix that displays external images . The images do n't display if the URL to the image is calculated from an expression or set from a column in the database . The image only displays if I hardcode the URL directly in the report . Obviously this is not a solution , but it shows that the report is capable of accessing the URL and rendering the image.I get these warnings from rendering the report : The ImageData for the image ‘ LinkedImage ’ is invalid . Details : Invalid URI : The format of the URI could not be determined.The value of the ImageData property for the image ‘ LinkedImage ’ is “ ” , which is not a valid ImageData.What I 've triedI 've double checked the URL that gets generated and it is correct . I 've even made it the click action a hyperlink to the image and it goes to the image correctly.Initially I was concatenating the URL in the expression but after this did n't work I had the SQL Query build the entire URL . It still does n't display.I have tried setting a flag : Using .NET Reflector to generate PDB files I was able to step through the code of the report viewer . There is a flag on the value object called `` IsExpression '' which is set to false when the report renders . I do n't know much about the inner workings of the Report viewer so I do n't know if this is a red herring.I 've changed the output format to HTML and it still does n't display . The image markup ( as seen in Chrome developer tools ) renders as : I 've tried setting the MIMEType value to the correct value for each image . ( Thanks Mike Honey for the suggestion ) I have tried the different Sizing values of AutoSize , Fit , FitProportional , and Clip.I both repaired and reinstalled entirely the ReportViewer runtime installation using the installer here : https : //www.microsoft.com/en-gb/download/details.aspx ? id=35747I have run the website from my local Visual Studio instance and a deployed version in a website on another server ( same installed ReportViewer version ) and the problem persists.I 'd like to draw attention to number 4 . Could there be a configuration which is causing the ReportViewer code to not see the value as an expression ? CodeHere is the markup in the RDL : Here 's an example URL ( host removed from example ) : Am I missing something ? Thanks ! reportViewer.LocalReport.EnableExternalImages = true ; < img onload= '' this.fitproportional=true ; this.pv=0 ; this.ph=0 ; '' height= '' 5px '' width= '' 1px '' src= ( unknown ) > < Image Name= '' LinkedImage '' > < Source > External < /Source > < Value > =Fields ! imageUrl.Value < /Value > < Sizing > FitProportional < /Sizing > < Style > < Border > < Style > None < /Style > < /Border > < /Style > < /Image > http : // -- -- -- -- -/images/FEE40608-0457-E511-A17F-00155D145C00/FFE40608-0457-E511-A17F-00155D145C00.jpg",SSRS external image not displayed when value set by expression "C_sharp : I am working on a game project using Microsoft XNA framework , although this question is a generic one that involves decoupling of classes/systems.Let 's say i have a class ( simplified to suit this example ) as shown here : I would like to reuse as much code as i can between multiple platforms that use C # .The problem of directly referncing the Color struct is that this type is defined in the XNA assemblies , creating a strong coupling ( or dependency ) between my code and XNA.The other framework i will be using may ( or may not ) have its own Color object , with its own set of properties and API.I would like to have the same source file `` know '' to use either the XNA or other framework 's implementation automagically.I know other types of decoupling methods such as IoC , but that would mean i would be plugging in different versions of a system/class , instead of reusing the same class in different contexts.Is this even possible to do ? how would u suggest to keep such a system portable ? I 've seen some cases ( in native C++ development ) where you would define a set of classes that mirror the classes the framework you 're using has ( for example here - define Color again ) , and so it is possible to `` re-map '' this later on to use different classes , upon need.Another option is to mess around using # IFDEF to play with the using statements in the header of the class ( switching from XNA to other platforms ) .What is the best alternative in this case ? public class GameCell { public Color Color { get ; set ; } }",How to properly decouple classes from frameworks ( source level decoupling ) "C_sharp : I 've been working on a .NET library to assist with internationalization of an application . It 's written in C # , called SmartFormat , and is open-source on GitHub.It contains Grammatical Number rules for multiple languages that determine the correct singular/plural form based on the template and locale . The rules were obtained from Unicode Language Plural Rules.When translating a phrase that has words that depend on a quantity ( such as nouns , verbs , and adjectives ) , you specify the multiple forms and the formatter chooses the correct form based on these rules.An example in English : ( notice the syntax is nearly identical to String.Format ) I would like to write unit tests for many of the supported languages . However , I only speak English and Spanish ( which both have the same grammatical-number rules ) . What are some good non-English test phrases that can be used for these unit tests ? I am looking for phrases similar to `` There { 0 : is : are } { 0 } { 0 : item : items } remaining. '' . Notice how this example requires a specific verb and noun based on the quantity.A note about syntax : This library looks for : delimited words and chooses the correct word based on the rules defined for the locale . For example , in Polish , there are 3 plural forms for the word `` File '' : 1 `` plik '' , 2-4 `` pliki '' , 5-21 `` plików '' . So , you would specify all 3 forms in the format string : `` { 0 } { 0 : plik : pliki : plików } '' . The words are typically ordered from smallest possible value to largest , such as `` { 0 : zero : one : two : few : many : other } '' , as defined by the Unicode Language Plural Rules.Additional information about this code has been discussed here : Localization of singular/plural words - what are the different language rules for grammatical numbers ? var message = `` There { 0 : is : are } { 0 } { 0 : item : items } remaining . `` ; var output = Smart.Format ( culture , message , items.Count ) ;",What are some good non-English phrases with singular and plural forms that can be used to test an internationalization and localization library ? "C_sharp : I 'm using Newtonsoft 's Json.Net to select nodes from the following json : The following c # snippetYields : Which is cool , now , what I 'd like to do is filter by client code , I would think that would work , but I obviously do n't understand the syntax well enough . This returns an empty list : And the single token selector returns a null : I tried a few different configurations on https : //jsonpath.curiousconcept.com/ and it seems my query syntax is indeed broken . Using Flow Communications ' JSONPath 0.3.4 implementation ( on the above link ) I can get the client using however , this syntax does not seem valid for Json.Net ( nor the Goessner implementation on the same page ) .Anyone see what I 'm doing wrong ? { `` projects '' : [ { `` name '' : '' Project 1 '' , `` client '' : { `` code '' : '' ABC '' , `` name '' : '' Client 1 '' } } , { `` name '' : '' Project 2 '' , `` client '' : { `` code '' : '' DEF '' , `` name '' : '' Client 2 '' } } , { `` name '' : '' Project 3 '' , `` client '' : { `` code '' : '' GHI '' , `` name '' : '' Client 3 '' } } ] } //json is a JObject representation of the json listed abovevar clients = json.SelectTokens ( `` $ .projects [ * ] .client '' ) ; [ { `` code '' : '' ABC '' , `` name '' : '' Client 1 '' } , { `` code '' : '' DEF '' , `` name '' : '' Client 2 '' } , { `` code '' : '' GHI '' , `` name '' : '' Client 3 '' } ] $ .projects [ * ] .client [ ? ( @ .code == 'DEF ' ) ] var test1 = json.SelectTokens ( `` $ .projects [ * ] .client [ ? ( @ .code == 'DEF ' ) ] '' ) .ToList ( ) ; var test2 = json.SelectToken ( `` $ .projects [ * ] .client [ ? ( @ .code == 'DEF ' ) ] '' ) ; $ .. [ ? ( @ .code == 'DEF ' ) ]",Json.NET JSONPath query not returning expected results "C_sharp : I have the following code : The second parameter ( x.ProductName == `` Chai '' ) contains a dynamic clause ( x.ProductName ) , so the resulting expression is also dynamic . When this code is executed on .NET 4.0 , sometimes it throws the following exception : System.InvalidCastException Unable to cast object of type 'System.Runtime.CompilerServices.TaskAwaiter ` 1 [ System.String ] ' to type 'System.Runtime.CompilerServices.INotifyCompletion'.The exception is not thrown if I explicitly case the method result to Task : Is there a more elegant way to resolve this problem ( without casting every single line of code that awaits for a dynamic result ) , or is this a known problem with using TPL on .NET 4.0.I have n't experienced this on .NET 4.5 . string commandText = await _client .GetCommandTextAsync ( `` Products '' , x.ProductName == `` Chai '' ) ; string commandText = await ( Task < string > ) _client .GetCommandTextAsync ( `` Products '' , x.ProductName == `` Chai '' ) ;",Exception ( sometimes ) is thrown when awaiting a method with dynamic argument "C_sharp : I am curious to know that whether optional parameter introduced in C # 4 is backward compatible or not ? Let me clarify my question with a simple example . Suppose I write the following code in C # 4 on .Net2 in VS2010 : Now I compiled the code , make a dll and reference it to a C # 2 / C # 3 project on .Net2 . In the code editor ( other than VS2010 , say VS2008 ) what I 'll see in intellisense ? Two overloaded methods like : Something else like : How I am supposed to call the C # 4 method in C # 2 project ? public void Foo ( int val1 , int val2 , int val3 = 5 ) { ... . } public void Foo ( int val1 , int val2 ) public void Foo ( int val1 , int val2 , int val3 ) public void Foo ( int val1 , int val2 , int val3 ) public void Foo ( int val1 , int val2 , int val3 = 5 ) //VS2008 is not supposed to show this",Is the Optional Parameter in C # 4 Backwards Compatible ? "C_sharp : So , this is simple to explain , but I have searched and can not find anyone with the same issue . My problem originated in a long-term periodic task which was running more frequently than I wanted . It seems every Task.Delay ( ) I create and await returns in about 65 % of the delay I specified in ms . The problem boiled down to the following line of code returning in roughly 640-660ms ( According to visual studio . I set a breakpoint on this line of code and the one following it , and it said that 's how long had passed ) : On two other machines , the IDENTICAL code base runs just fine . Not only this simple statement above , but the periodic tasks as well . Is there a setting somewhere that would affect Task.Delay ( int millisecondsDelay ) ? Tick type , clock speed , anything , system clock ? ? ? I am at a loss ... EDIT : In the snippet below , EtMilliseconds is anywhere from 130-140ms , which is the same approx . 65 % of expected duration seen above . Never anything outside that ( besides the first time into the while ( ) which is irrelevant ) .EDIT 2 : The following code causes EtMilliseconds to be once again 131ms or so . Using Thread.Sleep seems to have no effect ... This snippet is the same but uses Task.Delay ( 200 ) . This one updates the GUI label correctly ( the Thread.Sleep does not ) and it is either 131 or 140ms . Always ... EDIT 3 : Using DispatcherTimer instead , I still get approx 130ms from my Stopwatch.ElapsedMilliseconds ... BUT here 's the strange thing . If I also update a display of DateTime.Now ( ) , they increment by just about 200ms ( or slightly more ) , which is what I would expect . What the ? ! ? ! await Task.Delay ( 1000 ) ; Long EtMilliseconds ; Stopwatch etWatch = new Stopwatch ( ) ; etWatch.Restart ( ) ; while ( true ) { EtMilliseconds = etWatch.ElapsedMilliseconds ; taskDelay = Task.Delay ( 200 ) ; etWatch.Restart ( ) ; await taskDelay ; } public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private void button_Click ( object sender , RoutedEventArgs e ) { long EtMilliseconds ; Stopwatch etWatch = new Stopwatch ( ) ; etWatch.Restart ( ) ; while ( true ) { EtMilliseconds = etWatch.ElapsedMilliseconds ; label.Content = EtMilliseconds.ToString ( ) ; etWatch.Restart ( ) ; Thread.Sleep ( 200 ) ; } } } public partial class MainWindow : Window { public MainWindow ( ) { InitializeComponent ( ) ; } private async void button_Click ( object sender , RoutedEventArgs e ) { Task taskDelay ; long EtMilliseconds ; Stopwatch etWatch = new Stopwatch ( ) ; etWatch.Restart ( ) ; while ( true ) { EtMilliseconds = etWatch.ElapsedMilliseconds ; label.Content = EtMilliseconds.ToString ( ) ; taskDelay = Task.Delay ( 200 ) ; etWatch.Restart ( ) ; await taskDelay ; } } } public partial class MainWindow : Window { public long etMilliseconds ; public Stopwatch etWatch ; public MainWindow ( ) { InitializeComponent ( ) ; this.DataContext = this ; } // System.Windows.Threading.DispatcherTimer.Tick handler // // Updates the current seconds display and calls // InvalidateRequerySuggested on the CommandManager to force // the Command to raise the CanExecuteChanged event . private void dispatcherTimer_Tick ( object sender , EventArgs e ) { // Updating the Label which displays the current second tBoxCurrTime.Text += DateTime.Now.ToString ( `` yyyy_MMM_dd-hh : mm : ss.fff_tt '' ) + `` \n '' ; tBoxMilliSecElapsed.Text += etWatch.ElapsedMilliseconds + `` \n '' ; etWatch.Restart ( ) ; // Forcing the CommandManager to raise the RequerySuggested event CommandManager.InvalidateRequerySuggested ( ) ; } private void button_Click ( object sender , RoutedEventArgs e ) { etWatch = new Stopwatch ( ) ; // DispatcherTimer setup DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer ( ) ; dispatcherTimer.Tick += new EventHandler ( dispatcherTimer_Tick ) ; dispatcherTimer.Interval = new TimeSpan ( 0 , 0 , 0 , 0 , 200 ) ; dispatcherTimer.Start ( ) ; etWatch.Restart ( ) ; } }",C # await Task.Delay ( 1000 ) ; only takes 640ms to return C_sharp : Code : I currently get stackoverflow exceptions when I do this . public ActionResult View ( string id ) { return View ( ) ; },Can I have an ActionResult called `` View '' "C_sharp : I 'm trying to convert the following into vb.net . Thanks in advanceThis is where I get stuck , I have tried two different methods but still nothing works : or Categories.DataSource = objDT.Rows.Cast < DataRow > ( ) .Select ( r = > new { Attendee = r.Field < string > ( `` Attendee '' ) , Item = r.Field < string > ( `` Item '' ) } ) .GroupBy ( v = > v.Attendee ) .Select ( g = > new { Attendee = g.Key , Item = g.ToList ( ) } ) ; Categories.DataSource = objDT.AsEnumerable ( ) _ .Select ( Function ( r ) New With { .Attendee = r.Field ( Of String ) ( `` Attendee '' ) , .Item = r.Field ( Of String ) ( `` Item '' ) } ) _ .GroupBy ( Function ( v ) v.Field ( Of String ) ( `` Attendee '' ) ) _ .Select ( Function ( g ) Attendee = g.Key ) Categories.DataSource = objDT.Rows.Cast ( Of DataRow ) ( ) .AsEnumerable _ .Select New Object ( ) { Function ( r As DataRow ) Attendee = r.Field ( Of String ) ( `` Attendee '' ) , Item = r.Field ( Of String ) ( `` Item '' ) } _.GroupBy ( Function ( v ) v.Category ) _.Select ( Function ( g ) new { Category = g.Key , Numbers = g.ToList ( ) }",Ca n't convert this into VB.net "C_sharp : I have a C # service application which interacts with a database . It was recently migrated from .NET 2.0 to .NET 4.0 so there are plenty of new tools we could use.I 'm looking for pointers to programming approaches or tools/libraries to handle defining tasks , configuring which tasks they depend on , queueing , prioritizing , cancelling , etc.There are various types of services : Data ( for retrieving and updating ) Calculation ( populate some table with the results of a calculation on the data ) ReportingThese services often depend on one another and are triggered on demand , i.e. , a Reporting task , will probably have code within it such as Also , any Data modification is likely to set the Required flag on some of the Calculation or Reporting services , ( so the report could be out of date before it 's finished generating ) . The tasks vary in length from a few seconds to a couple of minutes and are performed within transactions.This has worked OK up until now , but it is not scaling well . There are fundamental design problems and I am looking to rewrite this part of the code . For instance , if two users request the same report at similar times , the dependent tasks will be executed twice . Also , there 's currently no way to cancel a task in progress . It 's hard to maintain the dependent tasks , etc..I 'm NOT looking for suggestions on how to implement a fix . Rather I 'm looking for pointers to what tools/libraries I would be using for this sort of requirement if I were starting in .NET 4 from scratch . Would this be a good candidate for Windows Workflow ? Is this what Futures are for ? Are there any other libraries I should look at or books or blog posts I should read ? Edit : What about Rx Reactive Extensions ? if ( IsSomeDependentCalculationRequired ( ) ) PerformDependentCalculation ( ) ; // which may trigger further calculationsGenerateRequestedReport ( ) ;","What C # tools exist for triggering , queueing , prioritizing dependent tasks" "C_sharp : Okay , here is what i would like to do.Basically , to sum up the above example , I have a generic wrapper type of type T.I would like that wrapper type to notify whatever it contains that it is being contained ( with a copy of its self ! ) IF the contained object implements a specific interface ( this bit I know how to do ) But it gets tricky ! Why ? Well because the container generic needs to have a type.Remember that important line ? If REPLACE_THIS is IContainableObject , then all implementers of the interface must use IContainerObject , not the name of the implementing class in their NotifyContained method.Using ImplementingType as the type of the container within the interface is even worse , for obvious reasons ! So my question is , what do I do to make REPLACE_THIS represent the class of the object implementing the interface ? Class Container < T > { T contained ; public void ContainObject ( T obj ) { contained = obj ; if ( /*Magical Code That Detects If T Implemtns IContainableObject*/ ) { IContainableObect c = ( IContainableObject ) obj ; c.NotifyContained ( self ) ; } } } interface IContainableObject { public void NotifyContained ( Container < REPLACE_THIS > ) ; //This line is important , see below after reading code . } Class ImplementingType : IContaiableObject { public Container < ImplementingType > MyContainer ; public void NotifyContained ( Container < ImplmentingType > c ) { MyContainer = c ; } } Class Main { public static void Main ( args ) { ImplementingType iObj = new ImplementingType ( ) ; Container < ImplementingType > container = new Container ( ) ; container.ContainObject ( iObj ) ; //iObj.MyContainer should now be pointing to container . } }",Self reference in interfaces "C_sharp : I noticed when I reflect into an assembly , calls to property accessors sometimes look like methodsNow I was curious , and I put a method with a similar signature in Class1 that looks like the standard convention for accessors.Somehow , the C # compiler still treats get_Boolean as a method.What 's the magic sauce to get a method to be a property ? // `` Reflected '' exampleclass Class1 { public bool Boolean { get ; set ; } } class Class2 { public Class2 ( ) { var class1 = new Class1 ( ) ; var boolean = class1.get_Boolean ( ) ; } } // `` Hacked '' exampleclass Class1 { public bool get_Boolean ( ) { return true ; } }",What is the magic that makes properties work with the CLR ? "C_sharp : I 'm trying to grasp the new compiled bindings , but right at the start I get stopped by this simple problem.I have Hub control with one HubSection . The content of this section is an ItemsControl that needs to bind to view models ' observable collection . I ca n't get this binding to work as I expect it to.ViewModel property is just a property and is instantiated before InitializeComponents ( ) call . NewsItems is observable collection inside view model that is filled after the page has loaded - asynchronously ( web request ) .What am I doing wrong here ? EDIT : Code-behindHomePage.xaml.csHomePageViewModel.cs < Pivot x : Name= '' rootPivot '' Style= '' { StaticResource TabsStylePivotStyle } '' > < PivotItem > < Hub > < HubSection Header= '' News '' > < DataTemplate x : DataType= '' local : HomePage '' > < ItemsControl ItemsSource= '' { x : Bind ViewModel.NewsItems , Mode=OneWay } '' / > /// < summary > /// Home pag view./// < /summary > public sealed partial class HomePage : Page { /// < summary > /// Initializes a new instance of the < see cref= '' HomePage '' / > class . /// < /summary > public HomePage ( ) { // Retrieve view model this.ViewModel = ViewModelResolver.Home ; // Trigger view model loaded on page loaded this.Loaded += ( sender , args ) = > this.ViewModel.LoadedAsync ( ) ; this.InitializeComponent ( ) ; } /// < summary > /// Gets the view model . /// < /summary > /// < value > /// The view model . /// < /value > public IHomeViewModel ViewModel { get ; } } /// < summary > /// Home view model./// < /summary > public sealed class HomeViewModel : IHomeViewModel { /// < summary > /// Occurs on page loaded . /// < /summary > public async Task LoadedAsync ( ) { // Retrieve news items var news = await new NewsService ( ) .GetNewsAsync ( ) ; foreach ( var newsItem in news ) this.NewsItems.Add ( newsItem ) ; } /// < summary > /// Gets the news items . /// < /summary > /// < value > /// The news items . /// < /value > public ObservableCollection < IFeedItem > NewsItems { get ; } = new ObservableCollection < IFeedItem > ( ) ; }",HubSection with compiled binding "C_sharp : I 've been trying to sort out some of our code using Dispose properly in a number of places that things were being left hanging around . Once such instance was Icons , and something I noticed which I thought was odd , if I call Icon.Dispose ( ) I was still able to use the Icon.So I extracted it out into a little console application that I fully expected to crash ( throw an ObjectDisposedException ) , but it did n't ... Am I mis-understanding what dispose should be doing here ? using System ; using System.Collections.Generic ; using System.Text ; using System.Drawing ; using System.IO ; namespace DisposeTest { class Program { static void Main ( string [ ] args ) { Icon icon = new Icon ( @ '' C : \temp\test.ico '' ) ; icon.ToBitmap ( ) .Save ( @ '' C : \temp\1.bmp '' ) ; icon.Save ( new FileStream ( @ '' C : \temp\1.ico '' , FileMode.OpenOrCreate , FileAccess.ReadWrite ) ) ; icon.Dispose ( ) ; GC.Collect ( ) ; // Probably not needed , but just checking . icon.Save ( new FileStream ( @ '' C : \temp\2.ico '' , FileMode.OpenOrCreate , FileAccess.ReadWrite ) ) ; icon.ToBitmap ( ) .Save ( @ '' C : \temp\2.bmp '' ) ; } } }",Icon still usable after calling Dispose ( ) ? "C_sharp : I 'm working with the VBIDE API , and ca n't assume that the host application is Excel , or any Office app either.So all I know is that I 'm looking at a VBComponent , and that its Type is vbext_ct_document.In the VBE 's immediate pane I can get this output : But the Sheet1 object only exists in the runtime environment , so if I 'm a C # add-in I do n't even see it.The only thing that gets anywhere close to what I need , is via the Parent and Next properties of the component : This gets me the type names I 'm after ... but on the wrong component ! And for ThisWorkbook , which is the top-level document object , I get the Application object as the Parent : The approach is potentially useful , but only if I hard-code host-specific logic that knows that whichever component has a `` Parent '' property of type `` Application '' is a Workbook instance when the host application is Excel ... and there 's no guarantee that other document modules in other hosts will even have that `` Parent '' property , so I 'm pretty much stumped.I 'm open to literally anything - from p/invoke calls and low-level COM `` reflection '' magic ( the ITypeInfo kind of magic ) to ... to ... I do n't know - unsafe code with funky pointers that will require // here be dragons comments - any lead that can potentially end up a working solution is welcome.AFAIK the VBE add-in lives in the same process as the host , so somewhere there 's a pointer to ThisWorkbook and Sheet1 and whatever other document-type VBComponent in the VBA project.I think I just need to grab that pointer somehow and I 'll be where I need to be . ? TypeName ( Application.VBE.ActiveVBProject.VBComponents ( `` Sheet1 '' ) ) VBComponent ? TypeName ( Sheet1 ) Worksheet ? TypeName ( Application.VBE.ActiveVBProject.VBComponents ( `` Sheet1 '' ) .Properties ( `` Parent '' ) .Object ) Workbook ? TypeName ( Application.VBE.ActiveVBProject.VBComponents ( `` Sheet1 '' ) .Properties ( `` Next '' ) .Object ) Worksheet ? TypeName ( Application.VBE.ActiveVBProject.VBComponents ( `` ThisWorkbook '' ) .Properties ( `` Parent '' ) .Object ) Application ? ObjPtr ( ThisWorkbook ) 161150920",How do I know that ` ThisWorkbook ` is a ` Workbook ` ? C_sharp : I have the following data structure ( apologies in advance as I 'm not sure of the best way to represent the data structure in SO ) .The following is a list of tables linked ( represented by the one to many relationship.The data in it 's simplest form would look like thisWhat I want to do is to query ( in lambda ) the data and return the data but filtered by ProductListTypeId and ComponentTypeId So for example I have for the first ( easy ) bitI have tried addingBut that does n't seem to work.I would like to pass in ( say ) the above parameters and have the following returned : Edit : Using EntityFramework to retrieve the dataEdit : I 'm beginning to think this is n't possible with standard linq queries . The only way I seem to be able to get this working is to iterate through the query and manually remove the unwanted records . 1|8 -- -- -- -- -- -- -- -- -- -- -|GlobalListTable : || -- -- -- -- -- -- -- -- -- -||Id ||ProductGroupTableId||ProductListTypeId | -- -- -- -- -- -- -- -- -- -- - 8 | 1 -- -- -- -- -- -- -- -- -- -- -|ProductGroupTable : || -- -- -- -- -- -- -- -- -- -||Id ||Name | -- -- -- -- -- -- -- -- -- -- - 1 | 8 -- -- -- -- -- -- -- -- -- -- -|ProductTable : || -- -- -- -- -- -- -- -- -- -||Id ||Name ||ProductGroupTableId| -- -- -- -- -- -- -- -- -- -- - 1 | 8 -- -- -- -- -- -- -- -- -- -- -|ComponentTable : || -- -- -- -- -- -- -- -- -- -||Id ||Name ||ProductTableId ||ComponentTypeId | -- -- -- -- -- -- -- -- -- -- - GlobalListTable1 ProductGroupTable ProductTable1 ComponentTable ComponentTypeId1 ComponentTable ComponentTypeId2 ComponentTable ComponentTypeId3 ComponentTable ComponentTypeId4 ProductTable2 ComponentTable ComponentTypeId1 ComponentTable ComponentTypeId3 ProductTable3 ComponentTable ComponentTypeId3 ComponentTable ComponentTypeId4 var productListTypeId=1 ; var componentTypeId=4 ; var _results=this.Context.GlobalListTable.Where ( i= > i.ProductListTypeId==productListTypeId ) ; .Where ( i= > i.ProductGroupTable.ProductTable.ComponentTable.ComponentTypeId == componentTypeId ) ; GlobalListTable1 ProductGroupTable ProductTable1 ComponentTable4 ProductTable3 ComponentTable4,Linq query to return filtered data "C_sharp : I 've been busy with C # 4.0 generics , and now I basically want to do something like this : The base Tree class looks like this : Here is my first problem . The constructor of GenericTree ca n't cast the the generic collection to a fruit collection . I 've also got an implementation of the GenericTree : Here 's my second problem . When I add fruit to an instance of AppleTree , using myAppleTree.GetFruits.Add ( ... ) , I am not restricted to apples only . I am allowed to add all kinds of fruit . I do n't want this.I tried to solve that problem by adding this to the GenericTree : But this is not possible either . It somehow always returns null . It could be possible that this will be solved , when my first problem is solved.The IFruitCollection interface looks like this : And the FruitCollection class is a simple implementation of the Collection class.Oh , and of course , the Apple class extends the Fruit class.The solution is to make the IFruitCollection interface compatible with both covariance and contravariance . But how do I achieve this ? The `` in '' or `` out '' parameter keywords are not possible , because the ICollection interface does n't allow it.Thanks a lot for your help ! public abstract class GenericTree < T > : Tree where T : Fruit { public Tree ( IFruitCollection < T > fruits ) : base ( fruits ) { } } public abstract class Tree { private IFruitCollection < Fruit > fruits ; public IFruitCollection < Fruit > GetFruits { get { return fruits ; } } public Tree ( IFruitCollection < Fruit > fruits ) { this.fruits = fruits ; } } public class AppleTree : GenericTree < Apple > { public AppleTree ( ) : base ( new FruitCollection < Apple > ) { } } new public IFruitCollection < T > GetFruits { get { return base.GetFruits as IFruitCollection < T > ; } } public interface IFruitCollection < T > : ICollection < T > where T : Fruit { ... }",C # - Is there some way to cast a generic collection ? "C_sharp : I have many methods ( they only run one at a time though ) , they all use the same RunWorkerCompleated and ProgressChanged methods but they all have different Dowork methods . Is it safe to do the following : or can I hit a edge case doing this ? I did not see anything on the MSDN on it saying it was not allowed and it as ( so far ) run fine in my program , but I wanted to check here to see if anyone has run in to trouble doing this . private void button_Process_Click ( object sender , EventArgs e ) { bgWork_Process.DoWork += Scrub_DoWork ; bgWork_Process.RunWorkerAsync ( ) ; bgWork_Process.DoWork -= Scrub_DoWork ; }",Is this safe to unsubscribe DoWork after calling RunWorkerAsync but before the function exits ? "C_sharp : Today I came across a strange phenomenon I ca n't really explain . There 's a webpage with a number of rows in a gridview , which need to be saved to the database and to an XML file one by one . I ended up using a Parallel.ForEach , as there is no relation between the rows , so they can be executed independently . The code is basically this : Why on earth would this code work any different when I replace the Parallel.ForEach with a good old foreach and I change nothing else ? The difference is that the culture in which the XML is created in the first case is different from the second case , and I have not the slightest clue why.Any suggestions ? Parallel.ForEach ( gvWithData.Rows.Cast < GridViewRow > ( ) , row = > { if ( row.RowType == DataControlRowType.DataRow ) { // do some logic and stuff ... var type = new Object { ... } ; // save to the database type.Save ( ) ; // retrieve the saved item from the database again // since we need some autoincrement values from the db var typeAfterSave = TypeManager.GetFromDb ( ) ; // create a custom XML from the object XmlManager.CreateXml ( typeAfterSave ) ; } }",Why does Parallel.ForEach change the culture of its threads ? "C_sharp : I 've seen a very interesting post on Fabio Maulo 's blog . Here 's the code and the bug if you do n't want to jump to the url . I defined a new generic class like so : Note that InitializeInstance accepts one parameter , which is of type dynamic . Now to test this class , I defined another class that is nested inside my main Program class like so : Note : the inner class `` MyClass '' is declared private . Now if i run this code I get a Microsoft.CSharp.RuntimeBinder.RuntimeBinderException on the line `` entity.PartitionKey = Guide.NewGuid ( ) .ToString ( ) '' . The interesting part , though is that the message of the exception says `` Object does n't contain a definition for PartitionKey '' .alt text http : //img697.imageshack.us/img697/4188/testdl.pngAlso note that if you changed the modifier of the nested class to public , the code will execute with no problems . So what do you guys think is really happening under the hood ? Please refer to any documentation -of course if this is documented anywhere- that you may find ? public class TableStorageInitializer < TTableEntity > where TTableEntity : class , new ( ) { public void Initialize ( ) { InitializeInstance ( new TTableEntity ( ) ) ; } public void InitializeInstance ( dynamic entity ) { entity.PartitionKey = Guid.NewGuid ( ) .ToString ( ) ; entity.RowKey = Guid.NewGuid ( ) .ToString ( ) ; } } class Program { static void Main ( string [ ] args ) { TableStorageInitializer < MyClass > x = new TableStorageInitializer < MyClass > ( ) ; x.Initialize ( ) ; } private class MyClass { public string PartitionKey { get ; set ; } public string RowKey { get ; set ; } public DateTime Timestamp { get ; set ; } } }",Is this a hole in dynamic binding in C # 4 ? "C_sharp : When I try to get the list of available audio devices like this.I get the error Exception has been thrown by the target of an invocation.Here is the stack traceAnd the inner exception stack trace LyncClient client = LyncClient.GetClient ( ) ; foreach ( Device dev in client.DeviceManager.AudioDevices ) { //Do something } `` Unable to cast COM object of type 'System.__ComObject ' to interface type 'Microsoft.Office.Uc.IAudioDevice2 ' . This operation failed because the QueryInterface call on the COM component for the interface with IID ' { 86B3E5FE-4635-4C1E-A725-C80B71D04984 } ' failed due to the following error : No such interface supported ( Exception from HRESULT : 0x80004002 ( E_NOINTERFACE ) ) . '' at System.RuntimeMethodHandle.InvokeMethod ( Object target , Object [ ] arguments , Signature sig , Boolean constructor ) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal ( Object obj , Object [ ] parameters , Object [ ] arguments ) at System.Reflection.RuntimeMethodInfo.Invoke ( Object obj , BindingFlags invokeAttr , Binder binder , Object [ ] parameters , CultureInfo culture ) at System.Reflection.MethodBase.Invoke ( Object obj , Object [ ] parameters ) at Microsoft.Lync.Model.Internal.UCWCache.CreateUCW ( Object source , CCOMInfo ccomInfo ) at Microsoft.Lync.Model.Internal.UCWCache.GetITTargetNS ( Object source ) at Microsoft.Lync.Model.Internal.UCEnumerator ` 2.get_Current ( ) at Microsoft.Lync.Model.Internal.UCEnumerator ` 2.System.Collections.Generic.IEnumerator < S > .get_Current ( ) at Microsoft.Lync.Model.Device.AudioDevice.INTERNAL_Init ( IAudioDevice initInterface ) at Microsoft.Lync.Model.Device.AudioDevice.INTERNAL_Init_Object ( Object initInterface )",Unable to get available audio device from Lync 2013 sdk "C_sharp : I just got the following exception , which seems to indicate that Guid is not an object . Expression of type 'System.Guid ' can not be used for return type 'System.Object'How is Guid not an object ? And how does the compiler figure this out ? There must be something that would allow me to detect at runtime when a type is not an object , if so what would this be ? ====================Edit with additional info====================Where SomeExpression could be a constant value of a Guid , for all that matters . Expression.Lambda < Func < object > > ( SomeExpression )",Why is Guid NOT an object in c # ? "C_sharp : When performing a dynamic query , RavenDB will typically create a temp index.Retrieving document by its Id does n't trigger this behaviour : Does RavenDB have a built-in optimisation for this type of query ? var entity = documentSession.Query < Entity > ( ) .Single ( x = > x.Id == 1 ) ;",Does RavenDB internally optimise `` get document by id '' type of queries ? "C_sharp : I am trying to rotate the Player about X , Y , and Z axis . The Y axis should not move from last angle . Example , if I rotate 45 degree 's to the left , the player should not rotate back to 0 . The players X and Z axis rotate a maximum of 30 degrees , then when Input is no longer in use , settle to 0 . Through trial and error , I have finally gotten my Y angle to not Slerp back to 0 . However , X and Z , still consider Y to be 0 degree 's . The player is rotated ( assume 45 degree 's to the left ) , but movement along X and Z is as if Y is 0 degree's.I 've been reading articles and threads , and watching video 's across multiple domains , including but not limited StackOverflow , Unity forums , Unity API , and YouTube video's.Video of Current Game - notice the engine exhaust - X and Z never change to the new normal of the Camera view / Player Y direction . void Update ( ) { if ( ! controller.isGrounded ) { //Three degree 's moveDirection = new Vector3 ( Input.GetAxis ( `` Horizontal '' ) , Input.GetAxis ( `` Thrust '' ) , Input.GetAxis ( `` Vertical '' ) ) ; moveDirection *= speed ; //rotate around Y-Axis transform.Rotate ( 0 , Input.GetAxis ( `` Yaw '' ) * rotationSpeed , 0 ) ; float currentY = transform.eulerAngles.y ; //save Y for later //rotation around X and Z float tiltAroundX = Input.GetAxis ( `` Vertical '' ) * tiltAngle ; float tiltAroundZ = -1 * ( Input.GetAxis ( `` Horizontal '' ) * tiltAngle ) ; Quaternion targetRotation = Quaternion.Euler ( tiltAroundX , currentY , tiltAroundZ ) ; Vector3 finalRotation = Quaternion.Slerp ( transform.rotation , targetRotation , smooth ) .eulerAngles ; finalRotation.y = currentY ; //reintroduce Y transform.rotation = Quaternion.Euler ( finalRotation ) ; controller.Move ( moveDirection * Time.deltaTime ) ; }",Quaternion.Slerp on X and Z axis without Y axis "C_sharp : I have defined a generic class that derives from BindingList and has a nested non-generic class : A StackOverflowException occurs in mscorlib when attempting to access the Value property via a dynamic reference like so : This is the smallest reproduction i was able to make.Deriving from BindingList is an important detail , if i change it to a List the program executes correctly.Why does this happen ? Edit : This is the top of the call stack : class Generic < T > : BindingList < Generic < T > .Inner > { public class Inner { public object Foo { get ; set ; } } } dynamic d = new Generic < string > .Inner ( ) ; var value = d.Foo ; // StackOverflowExceptionvar value = d.Bar // StackOverflowException as well , not a // 'RuntimeBinderException ' like you would expect when // trying to access a non-existing member [ Managed to Native Transition ] mscorlib.dll ! System.RuntimeTypeHandle.Instantiate ( System.Type [ ] inst ) mscorlib.dll ! System.RuntimeType.MakeGenericType ( System.Type [ ] instantiation ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.CType.CalculateAssociatedSystemTypeForAggregate ( Microsoft.CSharp.RuntimeBinder.Semantics.AggregateType aggtype ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.CType.CalculateAssociatedSystemType ( Microsoft.CSharp.RuntimeBinder.Semantics.CType src ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.CType.AssociatedSystemType.get ( ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.TypeManager.GetAggregate ( Microsoft.CSharp.RuntimeBinder.Semantics.AggregateSymbol agg , Microsoft.CSharp.RuntimeBinder.Semantics.AggregateType atsOuter , Microsoft.CSharp.RuntimeBinder.Semantics.TypeArray typeArgs ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.TypeManager.GetAggregate ( Microsoft.CSharp.RuntimeBinder.Semantics.AggregateSymbol agg , Microsoft.CSharp.RuntimeBinder.Semantics.TypeArray typeArgsAll ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.TypeManager.GetAggregate ( Microsoft.CSharp.RuntimeBinder.Semantics.AggregateSymbol agg , Microsoft.CSharp.RuntimeBinder.Semantics.TypeArray typeArgsAll ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.TypeManager.SubstTypeCore ( Microsoft.CSharp.RuntimeBinder.Semantics.CType type , Microsoft.CSharp.RuntimeBinder.Semantics.SubstContext pctx ) Microsoft.CSharp.dll ! Microsoft.CSharp.RuntimeBinder.Semantics.TypeManager.SubstTypeArray ( Microsoft.CSharp.RuntimeBinder.Semantics.TypeArray taSrc , Microsoft.CSharp.RuntimeBinder.Semantics.SubstContext pctx )",StackOverflowException when accessing member of nested class via a dynamic reference C_sharp : I have the following method : now I call this in a for loop like this : in scenario 1 the output is : 10 10 10 10 ... 10in scenario 2 the output is : 2 6 5 8 4 ... 0 ( random permutation of 0 to 9 ) How do you explain this ? Is c # not supposed to preserve variables ( here i ) for the anonymous delegate call ? static Random rr = new Random ( ) ; static void DoAction ( Action a ) { ThreadPool.QueueUserWorkItem ( par = > { Thread.Sleep ( rr.Next ( 200 ) ) ; a.Invoke ( ) ; } ) ; } for ( int i = 0 ; i < 10 ; i++ ) { var x = i ; DoAction ( ( ) = > { Console.WriteLine ( i ) ; // scenario 1 //Console.WriteLine ( x ) ; // scenario 2 } ) ; },Why c # does n't preserve the context for an anonymous delegate calls ? "C_sharp : In a few places in our code we use # if DEBUG blocks to simplify development . Things like : orThere are also a few places where we make cosmetic changes like this : Is it dangerous to depend on # if debug to make development easier ? If it is , what is a valid use of # if debug ? # if DEBUG serverIP = localhost ; # else serverIP = GetSetting ( ) # endif private bool isLicensed ( ) # if DEBUG return true ; # endifreturn CheckSetting ( ) # if DEBUG background = humorousImage.jpg # else background = standardColor # endif",Is it a bad idea to put development shortcuts in # if DEBUG blocks ? "C_sharp : I create a new PDF file using PDFsharp and MigraDoc.Now I want to add a field where the user can click on it and select a certificate for digital signing the file.I found in the web , that this should be possible with AcroForms.But I was n't able to use AcroForm because it is always null.My current example code : Why is this property null ? What can I do to set this to a correct value ? Or better , how can I add a field to select the digital certificate ? Document document = new Document ( ) ; Section section = document.AddSection ( ) ; section.AddParagraph ( `` Signature Test '' ) ; PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer ( false , PdfFontEmbedding.Always ) ; pdfRenderer.Document = document ; pdfRenderer.RenderDocument ( ) ; // NullPointerException at the following line . AcroForm is null pdfRenderer.PdfDocument.AcroForm.Elements.Add ( PdfAcroForm.Keys.SigFlags , new PdfInteger ( 3 ) ) ; const string filename = `` HelloWorld.pdf '' ; pdfRenderer.PdfDocument.Save ( filename ) ; Process.Start ( filename ) ;",Add field for a digital signature to PDF "C_sharp : I have a problem with verifying that certain method was called on mock inside LINQ Select ( ) query.Here is the method of ContentManager I want to test : I want to test that Process ( ) is called for elements of the list . My test method looks like this : When I run this test it fails and returns the following message : Test method ProcessItems_ValidItems_ProcessCalled threw exception : Moq.MockException : Expected invocation on the mock at least once , but was never performed : m = > m.Process ( It.IsAny ( ) ) No setups configured.No invocations performed.But if I change Select ( ) to foreach , then test passes successfully : What is wrong with Moq + Select ( ) ? How can I fix this ? public string ProcessElements ( List < Item > items ) { var processed = items.Select ( item = > item.Process ( Constants.Text ) ) ; return Serialize ( processed ) ; } [ TestMethod ] public void ProcessItems_ValidItems_ProcessCalled ( ) { var contentManager = new ContentManager ( ) ; var itemMock = new Mock < Item > ( ) ; itemMock.Setup ( m = > m.Process ( It.IsAny < string > ( ) ) ) .Returns ( `` serialized '' ) ; contentManager.ProcessElements ( new List < Item > ( ) { itemMock.Object } ) ; itemMock.Verify ( m = > m.Process ( It.IsAny < string > ( ) ) , Times.Once ( ) ) ; } public string ProcessElements ( List < Item > iitem ) { var processed = new List < string > ( ) ; foreach ( var item in iitem ) { processed.Add ( item.Process ( Constants.Text ) ) ; } return Serialize ( processed ) ; }",Ca n't verify method called inside Select ( ) using Moq framework "C_sharp : Here is fairly simple generic class . Generic parameter is constrained to be reference type . IRepository and DbSet also contain the same constraint.Compiled IL contains box instruction . Here is the release version ( debug version also contains it though ) .UPDATE : With object.Equals ( entity , default ( TEntity ) ) it looks even worse : UPDATE2 : For those who are interested , here is the code compiled by jit shown in debugger : The reason of this question is actually that NDepend warns about using boxing/unboxing . I was curious why it found boxing in some generic classes , and now it 's clear . public class Repository < TEntity > : IRepository < TEntity > where TEntity : class , IEntity { protected readonly DbSet < TEntity > _dbSet ; public void Insert ( TEntity entity ) { if ( entity == null ) throw new ArgumentNullException ( `` entity '' , `` Can not add null entity . `` ) ; _dbSet.Add ( entity ) ; } } .method public hidebysig newslot virtual final instance void Insert ( ! TEntity entity ) cil managed { // Code size 38 ( 0x26 ) .maxstack 8 IL_0000 : ldarg.1 > > > IL_0001 : box ! TEntity IL_0006 : brtrue.s IL_0018 IL_0008 : ldstr `` entity '' IL_000d : ldstr `` Can not add null entity . '' IL_0012 : newobj instance void [ mscorlib ] System.ArgumentNullException : :.ctor ( string , string ) IL_0017 : throw IL_0018 : ldarg.0 IL_0019 : ldfld class [ EntityFramework ] System.Data.Entity.DbSet ` 1 < ! 0 > class Repository ` 1 < ! TEntity > : :_dbSet IL_001e : ldarg.1 IL_001f : callvirt instance ! 0 class [ EntityFramework ] System.Data.Entity.DbSet ` 1 < ! TEntity > : :Add ( ! 0 ) IL_0024 : pop IL_0025 : ret } // end of method Repository ` 1 : :Insert .maxstack 2 .locals init ( [ 0 ] ! TEntity CS $ 0 $ 0000 ) IL_0000 : ldarg.1 > > > IL_0001 : box ! TEntity IL_0006 : ldloca.s CS $ 0 $ 0000 IL_0008 : initobj ! TEntity IL_000e : ldloc.0 > > > IL_000f : box ! TEntity IL_0014 : call bool [ mscorlib ] System.Object : :Equals ( object , object ) IL_0019 : brfalse.s IL_002b 0cd5af28 55 push ebp0cd5af29 8bec mov ebp , esp0cd5af2b 83ec18 sub esp,18h0cd5af2e 33c0 xor eax , eax0cd5af30 8945f0 mov dword ptr [ ebp-10h ] , eax0cd5af33 8945ec mov dword ptr [ ebp-14h ] , eax0cd5af36 8945e8 mov dword ptr [ ebp-18h ] , eax0cd5af39 894df8 mov dword ptr [ ebp-8 ] , ecx //entity reference to [ ebp-0Ch ] 0cd5af3c 8955f4 mov dword ptr [ ebp-0Ch ] , edx //some debugger checks0cd5af3f 833d9424760300 cmp dword ptr ds : [ 3762494h ] ,00cd5af46 7405 je 0cd5af4d Branch0cd5af48 e8e1cac25a call clr ! JIT_DbgIsJustMyCode ( 67987a2e ) 0cd5af4d c745fc00000000 mov dword ptr [ ebp-4 ] ,00cd5af54 90 nop //comparison or entity ref with zero0cd5af55 837df400 cmp dword ptr [ ebp-0Ch ] ,00cd5af59 0f95c0 setne al0cd5af5c 0fb6c0 movzx eax , al0cd5af5f 8945fc mov dword ptr [ ebp-4 ] , eax0cd5af62 837dfc00 cmp dword ptr [ ebp-4 ] ,0 //if not zero , jump further0cd5af66 7542 jne 0cd5afaa Branch //throwing exception here",Why is 'box ' instruction emitted for generic ? "C_sharp : I have a need to optimize a large apps that use linq extensively . Many of the linq statements create anonymous objects within the linq extension methods . An example : -The problem is that a new List gets created for every iteration.Is there a compiler flag I can set to get the compiler to do some static analysis and extract the loop invariant code to be outside of the loop ? // custom sort ordervar sortedData = data.OrderBy ( x = > ( new List < string > ( ) { `` Orange '' , `` Apple '' , `` Pear '' } ) .IndexOf ( x.Name ) ) ; foreach ( var d in sortedData ) { ... .",Loop compiler optimization "C_sharp : The problemI am trying to avoid code that looks like the following : I thought I could do this through method overloading , but it always picks the least derived type , I assume this is because the overloading is determined at compile time ( unlike overriding ) , and therefore only the base class can be assumed in the following code : Code structure : Code Implementation ( key classes ) : My scenario : Essentially I am creating a game , and want to decouple real-world classes ( such as a man ) , from on-screen classes ( an image of a person ) . The real world object should have no knowledge of it 's on-screen representation , the representation will need to be aware of the real object ( to know how old the man is , and therefore how many wrinkles are drawn ) . I want to have the fallback where if a RealObject is of an unknown type , it still displays something ( like a big red cross ) .Please note that this code is not what i 'm using , it 's a simplified version to keep the question clear . I may need to add details later if applicable , I 'm hoping the solution to this code will also work in the application.What 's the most elegant way to solve this ? - Without the RealObject itself holding information on how it should be represented . The XNA game is a proof of concept which is very AI heavy , and if it proves doable , will be changed from 2D to 3D ( probably supporting both for lower end computers ) . If ( object Is Man ) Return Image ( `` Man '' ) ElseIf ( object Is Woman ) Return Image ( `` Woman '' ) Else Return Image ( `` Unknown Object '' ) NS : Real RealWorld ( Contains a collection of all the RealObjects ) RealObject Person Man WomanNS : Virtual VirtualWorld ( Holds a reference to the RealWorld , and is responsible for rendering ) Image ( The actual representation of the RealWorldObject , could also be a mesh.. ) ArtManager ( Decides how an object is to be represented ) class VirtualWorld { private RealWorld _world ; public VirtualWorld ( RealWorld world ) { _world = world ; } public void Render ( ) { foreach ( RealObject o in _world.Objects ) { Image img = ArtManager.GetImageForObject ( o ) ; img.Render ( ) ; } } } static class ArtManager { public static Image GetImageForObject ( RealObject obj ) // This is always used { Image img = new Image ( `` Unknown object '' ) ; return img ; } public static Image GetImageForObject ( Man man ) { if ( man.Age < 18 ) return new Image ( `` Image of Boy '' ) ; else return new Image ( `` Image of Man '' ) ; } public static Image GetImageForObject ( Woman woman ) { if ( woman.Age < 70 ) return new Image ( `` Image of Woman '' ) ; else return new Image ( `` Image of Granny '' ) ; } }",Overloading with a class hierarchy - most derived not used "C_sharp : I have relation between two classes Credentials < = > UserData . And I would like to use MemoryCache to filter my incoming request.My key = Credential and value = UserData.How can I implement public string GetKey ( Credentials credential ) for incoming request ? Credentials its a DataContract that contains other DataContracts like GoogleCredentials , FacebookCredentials . And they contains their own strings like user_name and password.Now the cache items are added with keys credential.ToString ( ) and it is important for this method to return the same value for Credentials objects having the same credential values , and distinct values for Credentials instances with different credential values.Inside Credential class I have the following method ( Data ) MemoryCache.Default.AddOrGetExisting ( GetKey ( credential ) , // must be a string userData , DateTime.Now.AddMinutes ( 5 ) ) ; public override int GetHashCode ( ) { int hashCode = 0 ; if ( GoogleCredentials ! = null ) { hashCode ^= GoogleCredentials.GetHashCode ( ) ; } if ( FacebookCredentials ! = null ) { hashCode ^= FacebookCredentials.GetHashCode ( ) ; } return hashCode ; }",How to create unique key value ? "C_sharp : Scenario : I am developing a web application that allows users to upload Excel files into their respective tables in a SQL Server 2008 R2 database . I am also running an ETL process developed using SSIS when the user clicks on the upload button . My development environment : Asp.net , IIS7 , C # , SQL Server 2008 R2I am currently facing the problem of saving the file name of the file into another column in the tables as I will also be creating gridview function for the user to view the files that have already been uploaded into the database and enables the users to download the error files.Question : are there any ways I can save the file name into the same tables while running the SSIS packages during the ETL process ? Below are a sample example of my codes : This method allows me to retrieve the fileName : So when I execute the package , how do I save the file name to the tables at the same time ? string filePath1 = Server.MapPath ( System.IO.Path.GetFileName ( file.FileName.ToString ( ) ) ) ; file.SaveAs ( filePath1 ) ; package = app.LoadPackage ( packageString , null ) ; package.Connections [ `` Excel Connection Manager '' ] .ConnectionString = @ '' Provider=Microsoft.ACE.OLEDB.12.0 ; Data Source= '' + filePath1 + `` ; Extended Properties=Excel 12.0 ; HDR=YES ; IMEX=1 '' ; Microsoft.SqlServer.Dts.Runtime.DTSExecResult results = package.Execute ( ) ; String.Format ( `` File : { 0 } uploaded . `` , file.FileName )",Saving the filename into sql database and running ssis package at the same time "C_sharp : This is an ajax handler , checking all passed params are OK. Is this considered bad , and is there a better way to write this , or is it not that important ? int uploadsID ; int pageNumber ; int x ; int y ; int w ; int h ; bool isValidUploadID = int.TryParse ( context.Request.QueryString [ `` uploadID '' ] , out uploadsID ) ; bool isValidPage = int.TryParse ( context.Request.QueryString [ `` page '' ] , out pageNumber ) ; bool isValidX = int.TryParse ( context.Request.QueryString [ `` x '' ] , out x ) ; bool isValidY = int.TryParse ( context.Request.QueryString [ `` y '' ] , out y ) ; bool isValidW = int.TryParse ( context.Request.QueryString [ `` w '' ] , out w ) ; bool isValidH = int.TryParse ( context.Request.QueryString [ `` h '' ] , out h ) ; if ( isValidUploadID & & isValidPage & & isValidX & & isValidY & isValidW & isValidH ) {",C # is there a nicer way of writing this ? "C_sharp : I am having restful API which is written in C # using dot net framework 4.5..Currently its working alright ... i 'm returning a result after a JSON conversion.. I 'm expecting a pure JSON result ... which i 'm not getting currently.. I 'm expecting simple solution to omit the string XMLNS at the root element where i return the JSON ... Result i'am getting : My code : Thanks public String GetAllSalesInvoices ( string customer_id , string Startdate , string Enddate ) { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer ( ) ; string query = `` SELECT * FROM sales_invoice WHERE customer_id = '' + customer_id + `` AND invoice_date BETWEEN ' '' + Startdate + `` ' AND ' '' + Enddate + `` ' '' ; DataSet ds = conObj.execQuery ( query ) ; DataTable dt = new DataTable ( ) ; dt = ds.Tables [ 0 ] ; List < sales_invoice > result = new List < sales_invoice > ( ) ; foreach ( DataRow dr in dt.Rows ) { sales_invoice inv = new sales_invoice ( ) { Invoice_id = Convert.ToInt32 ( dr [ `` invoice_id '' ] ) , Invoice_date = Convert.ToString ( dr [ `` invoice_date '' ] .ToString ( ) ) , Customer_id = Convert.ToInt32 ( dr [ `` customer_id '' ] ) , Product_id = Convert.ToInt32 ( ( dr [ `` product_id '' ] ) ) , Time = Convert.ToString ( ( dr [ `` time '' ] ) .ToString ( ) ) , Quantity = Convert.ToInt32 ( ( dr [ `` quantity '' ] ) ) , Unit_of_measure = Convert.ToString ( dr [ `` unit_of_measure '' ] ) , Product_price = Convert.ToInt32 ( ( dr [ `` product_price '' ] ) ) , Sub_total = Convert.ToInt32 ( ( dr [ `` sub_total '' ] ) ) , } ; result.Add ( inv ) ; } string json=serializer.Serialize ( result ) ; return json ; }",Removing xml namespaces in C # restful web service returned string "C_sharp : I am trying to XOR some values with RGB values of my image , save that image and to do back steps , to get an original image.The problem is , that I do n't know why I get not clear ( with some noise ) image.Here is my code , and an image below : After an image has been saved , I change for and remove and I get an image like ( left original , right - result ) ; As you can see , I get some wrong colors at picture 4 , why ? All in all it is close to original , but still it 's not right Bitmap original = new Bitmap ( `` D : \\img\\1.jpg '' ) ; Bitmap inp_bmp = new Bitmap ( `` D : \\img\\1.jpg '' ) ; int width = inp_bmp.Width ; int height = inp_bmp.Height ; Color pixel ; for ( int y = 0 ; y < height ; y += 1 ) { for ( int x = 0 ; x < width ; x += 1 ) { pixel = inp_bmp.GetPixel ( x , y ) ; int a = pixel.A ; int r = ( pixel.R ^ ( 1000 ) ) % 256 ; int g = ( pixel.G ^ ( 185675 ) ) % 256 ; int b = ( pixel.B ^ ( 78942 ) ) % 256 ; inp_bmp.SetPixel ( x , y , Color.FromArgb ( a , r , g , b ) ) ; } } pictureBox2.Image = inp_bmp ; pictureBox1.Image = original ; inp_bmp.Save ( `` D : \\img\\4.jpg '' ) ; Bitmap inp_bmp = new Bitmap ( `` D : \\img\\1.jpg '' ) ; Bitmap inp_bmp = new Bitmap ( `` D : \\img\\4.jpg '' ) ; //inp_bmp.Save ( `` D : \\img\\4.jpg '' ) ;",Getting wrong colors after an image manipulations "C_sharp : Some text before the code so that the question summary is n't mangled.I have n't used events much in C # , but the fact that this would cause a NullRefEx seems weird . The EventHandler reference is considered null because it currently has no subsribers - but that does n't mean that the event has n't occurred , does it ? EventHandlers are differentiated from standard delegates by the event keyword . Why did n't the language designers set them up to fire silently in to the void when they have no subscribers ? ( I gather you can do this manually by explicitly adding an empty delegate ) . class Tree { public event EventHandler MadeSound ; public void Fall ( ) { MadeSound ( this , new EventArgs ( ) ) ; } static void Main ( string [ ] args ) { Tree oaky = new Tree ( ) ; oaky.Fall ( ) ; } }",Why must someone be subscribed for an event to occur ? "C_sharp : Possible Duplicate : Why does var evaluate to System.Object in “ foreach ( var row in table.Rows ) ” ? I was rather suprised to discovered the following today ... .Whats going on here ? Is this a type inference failure ? And if so , what causes it ? Or is it part of the defined behaviour or var ? And if so , why ? I thought the idea of var was that you could use it anywhere in a variable declaration/initialisation without changing behaviour . SqlDataReader reader = cmd.ExecuteReader ( ) ; DataTable schemaTable = reader.GetSchemaTable ( ) ; // the following compiles correctlyforeach ( DataRow field in schemaTable.Rows ) { Console.WriteLine ( field [ `` ColumnName '' ] ) ; } // the following does not compile as 'var ' is of type 'object'foreach ( var field in schemaTable.Rows ) { // Error : Can not apply indexing with [ ] to an expression of type 'object ' Console.WriteLine ( field [ `` ColumnName '' ] ) ; }",`` var '' type inference in C # C_sharp : I 'm using the below code in c sharp . But both the WriteLine statements are giving the same result 25 . Then what is the need for converting Tostring in c sharp ? Is there any special purpose ? using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; using System.Threading.Tasks ; namespace sample { class Program { static void Main ( string [ ] args ) { int value = 25 ; Console.WriteLine ( value.ToString ( ) ) ; Console.WriteLine ( value ) ; Console.ReadLine ( ) ; } } },What is the need of ToString ( ) in C # ? "C_sharp : Given the following interface and two classes : And given following logic that uses them : The test passes , and I see inside list exactly what I want - two object instances per a number : My question is , how do I simplify the foreach loop logic with LINQ ? I 'm thinking there might be an elegant way in doing the same with the SelectMany operator perhaps , but I 've not been able to produce the same output . public interface IMyObj { int Id { get ; set ; } } public class MyObj1 : IMyObj { public MyObj1 ( int id ) { Id = id ; } public int Id { get ; set ; } public override string ToString ( ) = > $ '' { GetType ( ) .Name } : { Id } '' ; } public class MyObj2 : IMyObj { public MyObj2 ( int id ) { Id = id ; } public int Id { get ; set ; } public override string ToString ( ) = > $ '' { GetType ( ) .Name } : { Id } '' ; } var numbers = new [ ] { 1 , 5 , 11 , 17 } ; var list = new List < IMyObj > ( ) ; foreach ( var n in numbers ) { // I 'd like to simplify this part with LINQ ... list.Add ( new MyObj1 ( n ) ) ; list.Add ( new MyObj2 ( n ) ) ; } Assert.AreEqual ( 8 , list.Count ) ; Count = 8 [ 0 ] : { MyObj1 : 1 } [ 1 ] : { MyObj2 : 1 } [ 2 ] : { MyObj1 : 5 } [ 3 ] : { MyObj2 : 5 } [ 4 ] : { MyObj1 : 11 } [ 5 ] : { MyObj2 : 11 } [ 6 ] : { MyObj1 : 17 } [ 7 ] : { MyObj2 : 17 }",Simplifying a foreach loop with LINQ ( selecting two objects in each iteration ) "C_sharp : Consider the two fragments of code that simply order strings in C # and F # respectively : C # : F # : These two fragments of code return different results : C # : Tea and Coffee , Telephone , TVF # : TV , Tea and Coffee , TelephoneIn my specific case I need to correlate the ordering logic between these two languages ( one is production code , and one is part of a test assertion ) . This poses a few questions : Is there an underlying reason for the differences in ordering logic ? What is the recommended way to overcome this `` problem '' in my situation ? Is this phenomenon specific to strings , or does it apply to other .NET types too ? EDITIn response to several probing comments , running the fragments below reveals more about the exact nature of the differences of this ordering : F # : C # : Gives : C # : tv , tV , Tv , TV , uv , uV , Uv , UVF # : TV , Tv , UV , Uv , tV , tv , uV , uvThe lexicographic ordering of strings differs because of a difference in the underlying order of characters : C # : `` aAbBcCdD ... tTuUvV ... '' F # : `` ABC..TUV..Zabc..tuv.. '' var strings = new [ ] { `` Tea and Coffee '' , `` Telephone '' , `` TV '' } ; var orderedStrings = strings.OrderBy ( s = > s ) .ToArray ( ) ; let strings = [ | `` Tea and Coffee '' ; `` Telephone '' ; `` TV '' | ] let orderedStrings = strings | > Seq.sortBy ( fun s - > s ) | > Seq.toArray let strings = [ | `` UV '' ; `` Uv '' ; `` uV '' ; `` uv '' ; `` Tv '' ; `` TV '' ; `` tv '' ; `` tV '' | ] let orderedStrings = strings | > Seq.sortBy ( fun s - > s ) | > Seq.toArray var strings = new [ ] { `` UV '' , `` Uv '' , `` uv '' , `` uV '' , `` TV '' , `` tV '' , `` Tv '' , `` tv '' } ; var orderedStrings = strings.OrderBy ( s = > s ) .ToArray ( ) ;",Default ordering in C # vs. F # "C_sharp : I have objects from which measurements are saved to a single table . I want to find out how long an object has been in a certain state within a time period.So in addition to getting the record with the wanted state I need to pair it up with the next measurement made from the same object to calculate the time between them.I came up with this monster : I would say this does n't seem very efficient especially when I 'm using Compact Edition 3.5 . Is there any way to navigate to the next measurement through m or could I somehow use orderby or group to select next by Id ? Or even make the join clause simpler ? // Get the the object entry from DatabaseMeasuredObject object1 ; try { object1 = ( MeasuredObject ) ( from getObject in db.MeasuredObject where wantedObject.Id.Equals ( getObject.Id ) select getObject ) .Single ( ) ; } catch ( System.ArgumentNullException e ) { throw new System.ArgumentException ( `` Object does not exist '' , `` wantedObject '' , e ) ; } // Get every measurement which matches the state in the time period and the next measurement from itvar pairs = ( from m in object1.Measurements join nextM in object1.Measurements on ( from next in object1.Measurements where ( m.Id < next.Id ) select next.Id ) .Min ( ) equals nextM.Id where 'm is in time period and has required state ' select new { meas = m , next = nextM } ) ;",LINQ select next record with each matching result "C_sharp : I know it is a bad idea to put a WebBrowser inside a Pivot/RadSlideView control.I did so anyway : Basically I want to use the Pivot to slide through an array of HTML docs at URIs I provide via my ViewModel , which just wraps an the array in a Caliburn.Micro OneActive Conductor : That runs pretty well in debug and release versions I deploy manually . The App passes all tests imposed by the Store , but as soon as I try to open this specific view within the app , it crashes without any chance to redirect to a Telerik MessageBox.As soon as I remove the outer Pivot and adjust the ViewModel accordingly , it runs smoothely . As I a said , the crash only happens in production . The Application.UnhandledException handler ca n't get the app to swallow the exception and display the error . This is really intricate and bugs me since months . Can anyone resolve this error or point me in a worthwhile direction ? I would also appreciate a more WP-ish suggestion for displaying multiple Web links that works . < phone : PhoneApplicationPage x : Class= '' **.HtmlView '' xmlns= '' http : //schemas.microsoft.com/winfx/2006/xaml/presentation '' xmlns : x= '' http : //schemas.microsoft.com/winfx/2006/xaml '' xmlns : phone= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone '' xmlns : d= '' http : //schemas.microsoft.com/expression/blend/2008 '' xmlns : mc= '' http : //schemas.openxmlformats.org/markup-compatibility/2006 '' xmlns : controls= '' clr-namespace : Microsoft.Phone.Controls ; assembly=Microsoft.Phone.Controls '' FontFamily= '' { StaticResource PhoneFontFamilyNormal } '' FontSize= '' { StaticResource PhoneFontSizeNormal } '' Foreground= '' { StaticResource PhoneForegroundBrush } '' SupportedOrientations= '' PortraitOrLandscape '' Orientation= '' Portrait '' mc : Ignorable= '' d '' Style= '' { StaticResource LeafPageNavigationStyle } '' > < controls : Pivot x : Name= '' Html '' ItemsSource= '' { Binding Items } '' Style= '' { StaticResource HeaderlessPivot } '' > < controls : Pivot.ItemTemplate > < DataTemplate > < phone : WebBrowser Source= '' { Binding } '' / > < /DataTemplate > < /controls : Pivot.ItemTemplate > < /controls : Pivot > < /phone : PhoneApplicationPage > namespace DSBMobile.ViewModels { public class HtmlViewModel : Conductor < Uri > .Collection.OneActive { private readonly IUnburyableState < Uri [ ] , HtmlViewModel > _state ; public HtmlViewModel ( IUnburyableState < Uri [ ] , HtmlViewModel > state ) { _state = state ; Items.AddRange ( _state.State.ForceGetValue ( ) ) ; } } }",Crash in production when using a WebBrowser inside a Pivot "C_sharp : The scenario : Create a MarkupExtension to replace Grid.Row= ” 0 ” by Grid.Row= ” { namespace : ClassExtension GridRowName } ” ( same for column ) Xaml Code : The requirement : Show XAML Errors when an incorrent GridRowName ( or columnName ) isused Show no XAML errors when a correct GridRowName ( or columnName ) is used When a Valid ColumnName is used for a Row declaration ( andvica verca ) a XAML error should be shownThe problem : Everything works fine for Grid.Column , but Grid.Row always throws an “ Not Implemented Exception ” at designtime ( grid.row is underlined , grid.column is not ) .The rows and columns are both named correct , but row always shows an error.If we specify an invalid column name , the column shows an error ( which is expected , so Grid.Column works fine ! ) As you can see , column works fine , but Rows don ’ t.The problem lies inside the MarkupExtension called GridDefinitionExtension : The Exception is trown on the line : After looking inside the DLL from which this method is called I have found that the body of this ProvideValue method looks like this : I ’ ve simplified this ProvideValue method to only show the code which it is actually using in my scenario : Apparantly the Exception is thrown by the GetFixUpToken method , but the cause is the Resolve method.This Resolve method returns a valid object when lookup up the ColumnDefinition by its name , but it returns NULL when doing the exact same thing for a RowDefinition.The Error thrown by GetFixUpToken is : “ NotImplementedException ” , which is expected since when looking at the sourcecode of the IXamlNameResolver ( which in this case is of Type : XamlNameResolverImpl ) When looking at the source code of this XamlNameResolverImpl , you can see that the method “ GetFixUpToken ” is empty and throws a NotImplemented exception ( look at http : //dotnetinside.com/en/framework/Microsoft+Expression/Microsoft.Expression.WpfPlatform/WpfMarkupExtensionValueSetter ) But the problem is , as I already said , is the Resolve call , which works fine for columndefinition but fails for rowdefinitions… : Column : Row : At this point , I do n't know what to do anymore ... Source code ( example project ) available at : http : //www.frederikprijck.net/stuff/MarkupExtension.rar < Grid > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' x : Name= '' TitleRow '' / > < RowDefinition Height= '' Auto '' x : Name= '' LastNameRow '' / > < RowDefinition Height= '' Auto '' x : Name= '' FirstNameRow '' / > < RowDefinition Height= '' Auto '' x : Name= '' EmailRow '' / > < /Grid.RowDefinitions > < Grid.ColumnDefinitions > < ColumnDefinition x : Name= '' LabelColumn '' / > < ColumnDefinition x : Name= '' ValueColumn '' / > < /Grid.ColumnDefinitions > < Label Grid.Row= '' { me : GridDefinition Name=TitleRow } '' Grid.ColumnSpan= '' 2 '' FontWeight= '' Bold '' FontSize= '' 14 '' / > < Label Grid.Row= '' { me : GridDefinition Name=LastNameRow } '' Grid.Column= '' { me : GridDefinition Name=LabelColumn } '' FontWeight= '' Bold '' FontSize= '' 14 '' / > < /Grid > [ MarkupExtensionReturnType ( typeof ( int ) ) ] public class GridDefinitionExtension : MarkupExtension { public string Name { private get ; set ; } public override object ProvideValue ( IServiceProvider serviceProvider ) { var referenceExt = new Reference ( Name ) ; var definition = referenceExt.ProvideValue ( serviceProvider ) ; if ( definition is DefinitionBase ) { var grid = ( definition as FrameworkContentElement ) .Parent as Grid ; if ( grid ! = null & & definition is RowDefinition ) return grid.RowDefinitions.IndexOf ( definition as RowDefinition ) ; if ( grid ! = null & & definition is ColumnDefinition ) return grid.ColumnDefinitions.IndexOf ( definition as ColumnDefinition ) ; } // This Extension only works for DefinitionBase Elements . throw new NotSupportedException ( ) ; } } var definition = referenceExt.ProvideValue ( serviceProvider ) ; public override object ProvideValue ( IServiceProvider serviceProvider ) { if ( serviceProvider == null ) throw new ArgumentNullException ( `` serviceProvider '' ) ; IXamlNameResolver xamlNameResolver = serviceProvider.GetService ( typeof ( IXamlNameResolver ) ) as IXamlNameResolver ; if ( xamlNameResolver == null ) throw new InvalidOperationException ( System.Xaml.SR.Get ( `` MissingNameResolver '' ) ) ; if ( string.IsNullOrEmpty ( this.Name ) ) throw new InvalidOperationException ( System.Xaml.SR.Get ( `` MustHaveName '' ) ) ; object obj = xamlNameResolver.Resolve ( this.Name ) ; if ( obj == null ) { string [ ] strArray = new string [ 1 ] { this.Name } ; obj = xamlNameResolver.GetFixupToken ( ( IEnumerable < string > ) strArray , true ) ; } return obj ; } if ( serviceProvider == null ) throw new ArgumentNullException ( `` serviceProvider '' ) ; IXamlNameResolver xamlNameResolver = serviceProvider.GetService ( typeof ( IXamlNameResolver ) ) as IXamlNameResolver ; object obj = xamlNameResolver.Resolve ( this.Name ) ; if ( obj == null ) { var strArray = new string [ 1 ] { this.Name } ; obj = xamlNameResolver.GetFixupToken ( ( IEnumerable < string > ) strArray , true ) ; } return obj ; public object GetFixupToken ( IEnumerable < string > names , bool canAssignDirectly ) { throw new NotImplementedException ( ) ; } public object GetFixupToken ( IEnumerable < string > names ) { throw new NotImplementedException ( ) ; }",WPF MarkupExtension and RowDefinition results in NotImplementedException "C_sharp : As my ( unit- ) test coverage is still quite low , unfortunately , I have to find lots of errors the hard way . Therefore , during refactoring , I heavily rely on type checking of the C # compiler.Today , I fixed a bug introduced during refactoring by missing a line with x.Equals ( aThingWrappingOriginalThing ) . As it 's bool Equals ( object T ) , the compiler did not complain . However , 90 % of the time I use Equals ( ) directly ( instead through the BCL ) , I intend to logically compare objects of the same type.Now I 'm wondering why I 've never seen someone promoting a type-safe version of Equals ( ) for such situations ( in C # ) . Is there a best practice for this ? I 'm tempted to use an extension method for those comparisions , like so : Could these be optimized ? Here 's the only blog post about the topic I found , for java : http : //rickyclarkson.blogspot.com/2006/12/making-equalsobject-type-safe.html public static bool SafeEquals < T > ( this T a , T b ) { if ( a == null ) return b == null ; return a.Equals ( b ) ; } public static bool SafeEquals < X > ( this IEquatable < X > a , IEquatable < X > b ) { if ( a == null ) return b == null ; return a.Equals ( b ) ; }",Type-safe Equals ( ) C_sharp : I 'm curious how to check if given type is closed version of open type . For instance public bool IsGenericList ( Type source ) { return ( source.IsGenericType & & /*here goes the manipulation on source type*/ == typeof ( List < > ) ) ; },Compare closed type with open type "C_sharp : I am using Accord.net 3.7.0 in dot net core 1.1.The algorithm I use is naive bayesian . And the source code of the learning mechanism is as follows : I have tested this piece of code on a little data but as data grew the Index was outside the bounds of the arrayerror occurred.As I ca n't navigate in the Learn method so I do n't know what to do . the screen shot of the run-time is this : No extra information , no inner exception no IDEA ! ! ! TG.// UPDATE_1 ***The inputs array is a 180 by 4 matrix ( array ) as the bellow image shows : which has 4 columns in every row . checked by hand ( I can share its video too if needed ! ! ! ) The outputs array is a 180 one as shown here : which only contains 0 and 1 ( I can share its video too if needed ! ! ! ) .And about NaiveBayesinLearning doc is here : NaiveBayesinLearning More examples bottom of this page : More examplesAnd the learn method docs here : learn method doc public LearningResultViewModel NaiveBayes ( int [ ] [ ] inputs , int [ ] outputs ) { // Create a new Naive Bayes learning var learner = new NaiveBayesLearning ( ) ; // Learn a Naive Bayes model from the examples NaiveBayes nb = learner.Learn ( inputs , outputs ) ; # region test phase // Compute the machine outputs int [ ] predicted = nb.Decide ( inputs ) ; // Use confusion matrix to compute some statistics . ConfusionMatrix confusionMatrix = new ConfusionMatrix ( predicted , outputs , 1 , 0 ) ; # endregion LearningResultViewModel result = new LearningResultViewModel ( ) { Distributions = nb.Distributions , NumberOfClasses = nb.NumberOfClasses , NumberOfInputs = nb.NumberOfInputs , NumberOfOutputs = nb.NumberOfOutputs , NumberOfSymbols = nb.NumberOfSymbols , Priors = nb.Priors , confusionMatrix = confusionMatrix } ; return result ; }",Accord.net NaiveBayesLearning `` Index was outside the bounds of the array '' "C_sharp : This is a problem I have encountered again and again in C # , but have n't found a general solution . In C++/STL , all values in a map can be updated in O ( n ) time using an iterator without using keys to access each element . Is there a way to obtain similar behavior with any of the C # collections such as SortedList , SortedDictionary ? I can do something likeBut that would take O ( n * log ( n ) ) as the searching each element using key takes log ( n ) .Just to give an idea , I am looking for something along the lines of : Since the List is already sorted it should be possible to traverse it updating values ( not keys ) at the same time . It does n't look like there is a problem with that from the implementation point of view , but for some reason the functionality is not made available it seems.Also this is not a trivial case as the same method can be used to iterate from a known position to another modifying values in that range.Is there a way to do this in C # with any of the keyed collections in .NET without using 3rd party libraries ? Thank youJeeves foreach ( int key in list.Keys ) { list [ key ] *= 3 ; } SortedList < int , double > list = new SortedList < int , double > ( ) ; // Add few values fist// E.g . first try ... IList < double > values = list.Values ; for ( int i = 0 ; i < values.Count ; i++ ) { values [ i ] *= 3 ; } // E.g . second tryforeach ( KeyValuePair < int , double > kv in list ) { kv.Value *= 3 ; }",Updating all values in a C # keyed collection in O ( n ) time ? "C_sharp : I 'm some what new to Generics and I ca n't figure out why the following does n't work . I have an extension to IEnumerable < T > , called Grid and it looks like soSay , I have a variable in my razor Model called `` Products '' and it is the type List < Product > , so I tried to doIt states `` Can not convert method group 'Grid '' to non-delegate type 'object ' . Did you intend to invoke the method ? `` , with `` @ Model.tasks.Grid '' red underlined . The funny thing is , visual studio compiles , everything is fine . Of course , if i simply doIt 's all fine . public static class IEnumberableGridExtension { public static HelperResult Grid < T > ( this IEnumerable < T > gridItems , Action < GridView < T > > thegrid ) { ... ... .. } } @ Model.Products.Grid < Product > ( grid= > { ... } ) ; @ Model.Products.Grid ( grid= > { ... } ) ;","C # Generics , what am I doing wrong ?" C_sharp : Consider the following code where LockDevice ( ) could possibly fail and throw an exception on ist own . What happens in C # if an exception is raised from within a finally block ? UnlockDevice ( ) ; try { DoSomethingWithDevice ( ) ; } finally { LockDevice ( ) ; // can fail with an exception },Exception from within a finally block "C_sharp : For example , in : eq will be false.double.Parse would have to go through some trouble to explicitly ignore the sign for zero , even though not doing that almost never results in a problem . Since I need the raw representation , I had to write my own parsing function which special-cases negative zero and uses double.Parse for everything else.That 's not a big problem , but I 'm really wondering why they made the decision to ignore the sign of zero , because it seems to me that not doing so would n't be a bad thing . bool eq = ( 1 / double.Parse ( `` -0.0 '' ) ) == ( 1 / -0.0 ) ;",Why does double.Parse ignore the sign of zero ? "C_sharp : I was working on refactoring some c # code with ReSharper . One of the things I 've run into is a c # operator that I 'm unfamiliar with.In my code , I had this where NumRows is an integer . ReSharper suggests that I should change it toI 'm pretty sure that f : is some flag that tells it to cast NumRows as a float but I can not find any documentation for f : online . Can anyone elaborate on what exactly f : does or link me to a MSDN page about it ? ( Although I have a good idea of what f : does , it 's hard to search the internet for a colon , and I 'd like to know what it does before I use it ) Update 1 : Regardless of what I 'm trying to do , I 'm interested in the f-colon syntaxUpdate 2 : Turns out it was actually Visual Studio suggesting that I could add the argument name ' f ' not ReSharper , but that does't change the correct answer.. Mathf.FloorToInt ( NumRows/2 ) Mathf.FloorToInt ( f : NumRows/2 )",Mystical `` F colon '' in c # "C_sharp : I 've got an aggregation query in the C # driver like this : which matches the following shell syntax : I think the C # version is not working because of the CurrentStatus = group.First ( ) [ `` statuses '' ] and the exception is : My approach for the First ( ) convention is based on this : MongoDB C # Driver First Expression ReferenceAny ideas of how to translate it in a way the driver likes ? var result = await _records.Aggregate ( ) .Match ( record = > record.Statuses.Any ( status = > status.Status == currentStatus ) ) .Unwind ( record = > record.Statuses ) .Sort ( Builders < BsonDocument > .Sort.Descending ( `` statuses.date '' ) ) .Group ( doc = > doc [ `` _id '' ] , group = > new { Id = group.Key , CurrentStatus = group.First ( ) [ `` statuses '' ] } ) .Match ( arg = > arg.CurrentStatus [ `` status '' ] == BsonValue.Create ( currentStatus.ToString ( ) ) ) .ToListAsync ( ) ; db.records.aggregate ( [ { $ match : { `` statuses.status '' : `` Finished '' } } , { $ unwind : `` $ statuses '' } , { $ sort : { `` statuses.date '' : -1 } } , { $ group : { _id : `` $ _id '' , current_status : { $ first : `` $ statuses '' } } } , { $ match : { `` current_status.status '' : `` Finished '' } } ] ) System.NotSupportedException : get_Item of type MongoDB.Bson.BsonValue is an unsupported method in a $ project or $ group pipeline operator .",MongoDB $ first unsupported error C # driver "C_sharp : I have a WinForms application containing Button and a RichTextBox controls . After user clicks on Button , an IO demanding operation is executed . To prevent blocking of the UI thread I have implemented the async/await pattern . I would also like to report progress of this operation into RichTextBox . This is how the simplified logic looks like : After operation gets successfully completed , the RichTextBox contains following text : As you can see the progress for 3rd work item is reported after Done ! .My question is , what is causing the delayed progress reporting and how can I achieve that flow of LoadData_Click will continue only after all progress has been reported ? private async void LoadData_Click ( Object sender , EventArgs e ) { this.LoadDataBtn.Enabled = false ; IProgress < String > progressHandler = new Progress < String > ( p = > this.Log ( p ) ) ; this.Log ( `` Initiating work ... '' ) ; List < Int32 > result = await this.HeavyIO ( new List < Int32 > { 1 , 2 , 3 } , progressHandler ) ; this.Log ( `` Done ! `` ) ; this.LoadDataBtn.Enabled = true ; } private async Task < List < Int32 > > HeavyIO ( List < Int32 > ids , IProgress < String > progress ) { List < Int32 > result = new List < Int32 > ( ) ; foreach ( Int32 id in ids ) { progress ? .Report ( `` Downloading data for `` + id ) ; await Task.Delay ( 500 ) ; // Assume that data is downloaded from the web here . progress ? .Report ( `` Data loaded successfully for `` + id ) ; Int32 x = id + 1 ; // Assume some lightweight processing based on downloaded data . progress ? .Report ( `` Processing succeeded for `` + id ) ; result.Add ( x ) ; } return result ; } private void Log ( String message ) { message += Environment.NewLine ; this.RichTextBox.AppendText ( message ) ; Console.Write ( message ) ; } Initiating work ... Downloading data for 1Data loaded successfully for 1Processing succeeded for 1Downloading data for 2Data loaded successfully for 2Processing succeeded for 2Downloading data for 3Done ! Data loaded successfully for 3Processing succeeded for 3",Delayed progress reporting from async method "C_sharp : I am using amazing NAudio framework to get the list of the audio devices.But as I see is impossible difference which audio device is PC 's integrated audio and which is a headphones . I mean they have the same name and only if we plug the headphones it goes to Active state . Imagine , if I start application with plugged in headphones how do I know if the current device is a headphones and not the PC 's integrated audio ? I mean can do we detect via NAduio that plugged audio device is an external audio device and is a headphones itself ? Where NotificationClient is implemented as follows : var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator ( ) ; // Allows you to enumerate rendering devices in certain statesvar endpoints = enumerator.EnumerateAudioEndPoints ( DataFlow.Render , DeviceState.Unplugged | DeviceState.Active ) ; foreach ( var endpoint in endpoints ) { Console.WriteLine ( `` { 0 } - { 1 } '' , endpoint.DeviceFriendlyName , endpoint.State ) ; } // Aswell as hook to the actual eventenumerator.RegisterEndpointNotificationCallback ( new NotificationClient ( ) ) ; class NotificationClient : NAudio.CoreAudioApi.Interfaces.IMMNotificationClient { void IMMNotificationClient.OnDeviceStateChanged ( string deviceId , DeviceState newState ) { Console.WriteLine ( `` OnDeviceStateChanged\n Device Id -- > { 0 } : Device State { 1 } '' , deviceId , newState ) ; } void IMMNotificationClient.OnDeviceAdded ( string pwstrDeviceId ) { } void IMMNotificationClient.OnDeviceRemoved ( string deviceId ) { } void IMMNotificationClient.OnDefaultDeviceChanged ( DataFlow flow , Role role , string defaultDeviceId ) { } void IMMNotificationClient.OnPropertyValueChanged ( string pwstrDeviceId , PropertyKey key ) { } }",How to difference headphones from integrated audio in PC "C_sharp : Ok I 've been messing around with tasks in .net 4.5 and I 'm trying to get my head around everything so I created a small app that does some work and I have a few questions about it.Here is the code : Account Controller.cs : User Manager.cs : UserQueries.cs : IDBContext.csSo I have a few questions here.Do I have to create a new instance of the UserQuery class in every function ? Not sure if it needs to be sync locked or not , still confused there.Do I need to copy the ID to localID , I 'm worried about scoping and reference changes when the function is called , is that even something to worry about in any case ? Should UserQueries be Task < UserProfile > as well ? If UserQueries should be Task < UserProfile > should the DBContext that returns a DataTable also be Task < DataTable > , does .net have a function for Taskable sql calls ? I 'm not 100 % sure how deep you go with Task namespace MvcApplication1.Controllers { public class AccountController : Controller { private readonly UserManager _manager ; public AccountController ( ) { _manager = new UserManager ( ContextFactory.GetContext ( ) ) ; } [ HttpPost ] public async Task < ActionResult > Register ( LoginModel model ) { var user = await _manager.FindAsync ( model.UserName ) ; if ( user ! = null ) { //do some work } else { ModelState.AddModelError ( `` '' , `` Can not Find User '' ) ; return View ( model ) ; } } } } namespace MvcApplication1 { public class UserManager { private readonly IDBContext _context ; public UserManager ( IDBContext context ) { _context = context ; } public Task < UserProfile > FindAsync ( string ID ) { var queryHelper = new UserQueries ( _context ) ; var localID = ID ; return Task.Factory.StartNew ( ( ) = > queryHelper.GetProfile ( localID ) ) ; } } } public class UserQueries { private readonly IDBContext _context ; public UserQueries ( IDBContext context ) { _context = context ; } public UserProfile GetProfile ( string ID ) { DataTable dt = _context.ExecuteDataTable ( ... ) //do work with dt and return UserProfile } } } public interface IDBContext { DataTable ExecuteDataTable ( string sql , IEnumerable < SqlParameter > parameters ) ; }",Trying to understand Tasks in .net "C_sharp : Came across with a problem of pasing format.Using Bootstrap Datetimepicker , it does takes a strings from textboxes in format dateString = 11/28/2015 and timeString = 6:46 AMBut in the result I do have false and is parsing default date . What could be the problem ? if ( ! DateTime.TryParseExact ( dateString , `` MM/dd/yyyy '' , CultureInfo.InvariantCulture , DateTimeStyles.None , out dateOn ) ) { return false ; } else if ( ! DateTime.TryParseExact ( timeString , `` hh : mm tt '' , CultureInfo.InvariantCulture , DateTimeStyles.None , out timeOn ) ) { return false ; } return SaveWorkshop ( id , name , dateOn , timeOn , capacity , description , duration , isCancelled ) ;",DateTime.TryParseExact C # valid format and parsing "C_sharp : If I wanted to create a method that takes an instance of IList as a parameter ( or any other interface , but let 's use IList as an example ) , I could create a generic method with a type constraint , e.g . : Alternatively , I could create a method that takes an IList parameter directly : For all intents and purposes , it seems like these methods behave exactly the same : So here 's my question -- what 's the difference between these two approaches ? It seems like the second approach is slightly more readable ; are there any other differences I should be aware of ( different IL being generated , etc ) ? Thanks in advance . public static void Foo1 < T > ( T list ) where T : IList { } public static void Foo2 ( IList list ) { } List < string > myList = new List < string > ( ) ; Foo1 ( myList ) ; Foo2 ( myList ) ;",Difference between interface as type constraint and interface as parameter ? "C_sharp : From the project Roslyn , file src\Compilers\CSharp\Portable\Syntax\CSharpSyntaxTree.cs at line 446 there is : What is the ? . there ? Does it check whatever oldTree is null and if it 's not then it 's running the GetRoot method , and if not then what it returns ? This is my first assumption ( Which might be wrong ) , but I ca n't get forward with it . ( Confirm it , and/or answer the new question ) I googled What is ? . C # and nothing related came up , it is as if it ignored my ? . ( ? ) using ( var parser = new InternalSyntax.LanguageParser ( lexer , oldTree ? .GetRoot ( ) , changes ) )",What does the ? . mean in C # ? "C_sharp : First , here 's a simple example database model , which has Products assigned to Categories , where CategoryId in Products is the FK relationship to Categories.Products : ProductId ( PK ) , INTProductName VARCHAR ( 255 ) CategoryId ( FK ) , INTCategoriesCategoryId ( PK ) , INTCategoryName VARCHAR ( 255 ) For the .NET application data model , only a de-normalized representation of a Product is defined as an entity class : There is no Category class defined , and for this example , none is planned.In the code-first Entity Framework DbContext-derived class , I 've setup the DbSet < Product > Products entity set : And in the EntityTypeConfiguration , I 'm attempting to wire it up , but I 'm just not able to get it working right : I realize that a SQL View could be created and then I could tell EF to map to that view using ToTable ( `` App1ProductsView '' ) , but in this example , I 'd like to avoid doing so.In a SQL ADO.NET ORM solution , there 's no issue here . I can simply write my own SQL statement to perform the INNER JOIN Categories c ON c.CategoryId = p.CategoryId join . How can I use the EF code-first Fluent API to perform this same inner join when populating the entity ? In my research , I 've seen a lot of `` entity split across multiple tables '' topics , but this is not that . Categories and Products are two distinct entities ( from a database perspective ) , but the .NET code is meant to stay unaware of that.Failed Attempt 1 : This does not work , and produces a strange query ( seen with SQL Server Profiler ) .Fluent config : Resulting SQL : public class Product { public int ProductId { get ; set ; } public string ProductName { get ; set ; } public int CategoryId { get ; set ; } public string CategoryName { get ; set ; } } public virtual DbSet < Product > Products { get ; set ; } public class ProductConfiguration : EntityTypeConfiguration < Product > { public ProductConfiguration ( ) { HasKey ( t = > t.ProductId ) ; // How do I instruct EF to pull just the column 'CategoryName ' // from the FK-related Categories table ? } } Map ( m = > { m.Property ( t = > t.CategoryName ) ; m.ToTable ( `` Categories '' ) ; } ) ; SELECT [ Extent1 ] . [ ProductId ] AS [ ProductId ] , [ Extent2 ] . [ ProductName ] AS [ ProductName ] , [ Extent2 ] . [ CategoryId ] AS [ CategoryId ] , [ Extent1 ] . [ CategoryName ] AS [ CategoryName ] , FROM [ dbo ] . [ Categories ] AS [ Extent1 ] INNER JOIN [ dbo ] . [ Product1 ] AS [ Extent2 ] ON [ Extent1 ] . [ ProductId ] = [ Extent2 ] . [ ProductId ]","De-normalizing data into a code first Entity Framework entity , without a SQL View" "C_sharp : I 've been using TDD for some time but now I 'm looking at mocking frameworks and I do n't get some things . This question might sound stupid for someone experienced but I just do n't get it . The library I use is Moq + xUnit.QuestionWhat 's the point of testing Calculator class if I explicitly say that 2 + 2 will return 4 on this line mock.Setup ( x = > x.Add ( 2 , 2 ) ) .Returns ( 4 ) ; and then assert it ? Of course result will be 4 , I just `` forced '' it to return 4 in few lines above the test itself . And now even in my implementation if I do return a * b ; instead of return a + b ; the test will pass.Here is another example of this same calculator tests . http : //nsubstitute.github.io/Example Code namespace UnitTestProject1 { using Xunit ; using Moq ; public class CalculatorTests { private readonly ICalculator _calculator ; public CalculatorTests ( ) { var mock = new Mock < ICalculator > ( ) ; mock.Setup ( x = > x.Add ( 2 , 2 ) ) .Returns ( 4 ) ; mock.Setup ( x = > x.Subtract ( 5 , 2 ) ) .Returns ( 3 ) ; this._calculator = mock.Object ; } [ Fact ] public void Calculator_Should_Add ( ) { var result = _calculator.Add ( 2 , 2 ) ; Assert.Equal ( 4 , result ) ; } [ Fact ] public void Calculator_Should_Subtract ( ) { var result = _calculator.Subtract ( 5 , 2 ) ; Assert.Equal ( 3 , result ) ; } } public class Calculator : ICalculator { public int Add ( int a , int b ) { return a + b ; } public int Subtract ( int a , int b ) { return a - b ; } } public interface ICalculator { int Add ( int a , int b ) ; int Subtract ( int a , int b ) ; } }",What is purpose of mocking a class like Calculator ? "C_sharp : I have two methods that basically converts underlying checkboxes ' text or tag as CSV strings.These two methodsGetSelectedTextAsCsv ( ) GetTagAsCsv ( ) differ only by which property to extract value from SelectedCheckBoxes , which is of type IList < CheckBox > I was trying to extract a method that returns a Func < T , TResult > but not sure how I can pull that off.My poor attempt was like the following but I can not figure out how to extract the property portion as shown in the comment within ConvertToCsv ( ) If I am on a wrong track , would you please advise me on how I can refactor above code to use a common method ? [ UPDATE 1 ] Here is the combination of both Brian and Jon 's answers [ UPDATE 2 ] version 2 [ UPDATE 3 ] Made the parameter of GetAsCsv ( ) as a closed generic of CheckBox and string Func < CheckBox , T > to Func < CheckBox , string > . That allowed me to make GetAsCsv ( ) even simpler and more readable . public string GetSelectedTextAsCsv ( ) { var buffer = new StringBuilder ( ) ; foreach ( var cb in SelectedCheckBoxes ) { buffer.Append ( cb.Text ) .Append ( `` , '' ) ; } return DropLastComma ( buffer.ToString ( ) ) ; } public string GetTagAsCsv ( ) { var buffer = new StringBuilder ( ) ; foreach ( var cb in SelectedCheckBoxes ) { buffer.Append ( cb.Tag ) .Append ( `` , '' ) ; } return DropLastComma ( buffer.ToString ( ) ) ; } public Func < T , string > ConvertToCsv < T > ( ) { return propertyName = > { var buffer = new StringBuilder ( ) ; foreach ( var checkBox in SelectedCheckBoxes ) { buffer.Append ( /* How can you abstract this portion ? like following ? */ checkBox.propertyName ) .Append ( `` , '' ) ; } return DropLastComma ( buffer.ToString ( ) ) ; } ; } public string ConvertToCsv < T > ( Func < CheckBox , T > getValue ) { var stringValues = SelectedCheckBoxes.Select ( cb = > getValue ( cb ) .ToString ( ) ) .ToArray ( ) ; return string.Join ( `` , '' , stringValues ) ; } public string GetSelectedTextAsCsv ( ) { return ConvertToCsv ( cb = > cb.Text ) ; } public string GetTagAsCsv ( ) { return ConvertToCsv ( cb = > cb.Tag ) ; } public string GetAsCsv < T > ( Func < CheckBox , T > getValue ) { return string.Join ( `` , '' , SelectedCheckBoxes.Select ( cb = > getValue ( cb ) .ToString ( ) ) .ToArray ( ) ) ; } public string GetSelectedTextAsCsv ( ) { return GetAsCsv ( cb = > cb.Text ) ; } public string GetTagAsCsv ( ) { return GetAsCsv ( cb = > cb.Tag == null ? string.Empty : cb.Tag.ToString ( ) ) ; } private string GetAsCsv ( Func < CheckBox , string > getValue ) { return string.Join ( `` , '' , SelectedCheckBoxes.Select ( getValue ) .ToArray ( ) ) ; }",Can you refactor out a common functionality from these two methods ? "C_sharp : I 'm stuck . Where can I add `` Trim '' to this C # statement ? Each line will be a separate file name . But because each file may have space after it , I 'd like to trim it off.Thanks string [ ] lines = ( File.ReadAllLines ( @ '' C : \Users\Jim\Desktop\adminkeys.cfg '' ) ) ;",Where can I add `` Trim '' to this C # statement ? "C_sharp : When we define our interfaces in C # 4.0 , we are allowed to mark each of the generic parameters as in or out . If we try to set a generic parameter as out and that 'd lead to a problem , the compiler raises an error , not allowing us to do that.Question : If the compiler has ways of inferring what are valid uses for both covariance ( out ) and contravariance ( in ) , why do we have to mark interfaces as such ? Would n't it be enough to just let us define the interfaces as we always did , and when we tried to use them in our client code , raise an error if we tried to use them in an un-safe way ? Example : Also , is n't it what Java does in the same situation ? From what I recall , you just do something likeOr am I mixing things ? Thanks interface MyInterface < out T > { T abracadabra ( ) ; } //works OKinterface MyInterface2 < in T > { T abracadabra ( ) ; } //compiler raises an error.//This makes me think that the compiler is cappable //of understanding what situations might generate //run-time problems and then prohibits them . IMyInterface < ? extends whatever > myInterface ; //covarianceIMyInterface < ? super whatever > myInterface2 ; //contravariance",Covariance and Contravariance inference in C # 4.0 "C_sharp : I have large switch statement in which I create UIElements based on input value from XElement : I am creating a lot controls like this and as you can see , too much repetition is going on . Is there some way to avoid this repetition ? Thanks in advance for ideas . public static UIElement CreateElement ( XElement element ) { var name = element.Attribute ( `` Name '' ) .Value ; var text = element.Attribute ( `` Value '' ) .Value ; var width = Convert.ToDouble ( element.Attribute ( `` Width '' ) .Value ) ; var height = Convert.ToDouble ( element.Attribute ( `` Height '' ) .Value ) ; // ... switch ( element.Attribute ( `` Type '' ) .Value ) { case `` System.Windows.Forms.Label '' : return new System.Windows.Controls.Label ( ) { Name = name , Content = text , Width = width , Height = height } ; case `` System.Windows.Forms.Button '' : return new System.Windows.Controls.Button ( ) { Name = name , Content = text , Width = width , Height = height } ; // ... default : return null ; } }",Optimizing large switch statement "C_sharp : Could you please tell me if the following is a good way to securely hash a password to be stored in a database : Many Thanks in advance . public string CreateStrongHash ( string textToHash ) { byte [ ] salt =System.Text.Encoding.ASCII.GetBytes ( `` TeStSaLt '' ) ; Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes ( textToHash , salt , 1000 ) ; var encryptor = SHA512.Create ( ) ; var hash = encryptor.ComputeHash ( k1.GetBytes ( 16 ) ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < hash.Length ; i++ ) { sb.Append ( hash [ i ] .ToString ( `` x2 '' ) ) ; } return sb.ToString ( ) ; }",Is this a secure way to hash a password ? "C_sharp : I 'm using WinForms and on my Form I have a RichTextBox . When my form is out of focus but visible and I try to highlight/select text , it does not allow me to until the form or textbox itself has focus.I 've tried : but to no avail and I ca n't seem to find anything online about this issue.When testing with another program like Notepad , it does possess the desired behavior . txtInput.MouseDown += ( s , e ) = > { txtInput.Focus ( ) ; }",RichTextBox does n't start selection on mouse down when the form has not focus "C_sharp : There is ( or there has been ) a lot of talk about wether it 's good or bad to use the Thread.Sleep ( ) method . From what I understand it is mainly to be used for debugging purposes.Now I wonder : is it bad to use for my specific purpose , that is , constantly looping it to be able to pause/resume the thread ? I do this because I want to pause a thread that performs I/O operations and be able to resume it in a simple way.The I/O operations are basically just writing blocks of 4096 bytes to a file until all the data has been written to it . Since the file might be large and take a long time I want to be able to pause the operation ( in case it would start eating much system resources ) .My code , VB.NET version : C # equivalent : I have heard about ResetEvents and I know a little bit about what they do , but I have never really looked much into them . 'Class level.Private BytesWritten As Long = 0Private Pause As Boolean = False'Method ( thread ) level.While BytesWritten < [ target file size ] ... write 4096 byte buffer to file ... While Pause = True Thread.Sleep ( 250 ) End While ... do some more stuff ... End While //Class level.long bytesWritten = 0 ; bool pause = false ; //Method ( thread ) level.while ( bytesWritten < [ target file size ] ) { ... write 4096 byte buffer to file ... while ( pause == true ) { Thread.Sleep ( 250 ) ; } ... do some more stuff ... }",Would looping Thread.Sleep ( ) be bad for performance when used to pause a thread ? "C_sharp : Is it possible in ASP.NET MVC to display a downtime page when publishing a project out to a server ? Right now , if I hit the page while I am publishing I get an error : It would be awesome if we could setup a downtime page so that users know to come back at a later time , instead of thinking that the app is busted . Could not load type `` App.MvcApplication ''",Display downtime page when publishing application "C_sharp : I understand this has something to do with the way processors treat overflows , but I fail to see it . Multiplication with different negative numbers gives either zero or -2^63 : In C # Interactive : In F # Interactive : I came to this because it surprised me in F # until I realized that F # by default operates in unchecked contexts . Still , I could n't readily explain the behavior.I do understand why 9223372036854775807L + 1L == -9223372036854775808L , I just do n't get it for multiplication with a negative number and why it alternates between 0 ( binary all zeroes ) and -2^63 ( binary most significant bit 1 , rest zeroes ) .Interestingly , this holds with the rule of multiplicative identity , i.e. , since -1L * -9223372036854775808L == -9223372036854775808L , it follows that -1L * -1L * -9223372036854775808L == -9223372036854775808L and since -1L * -1L = 1L , it shows that the identity law still holds . > return unchecked ( -1L * -9223372036854775808L ) ; -9223372036854775808 > return unchecked ( -2L * -9223372036854775808L ) ; 0 > return unchecked ( -3L * -9223372036854775808L ) ; -9223372036854775808 > return unchecked ( -4L * -9223372036854775808L ) ; 0 > return unchecked ( -5L * -9223372036854775808L ) ; -9223372036854775808 > -1L * -9223372036854775808L ; ; val it : int64 = -9223372036854775808L > -2L * -9223372036854775808L ; ; val it : int64 = 0L > -3L * -9223372036854775808L ; ; val it : int64 = -9223372036854775808L > -4L * -9223372036854775808L ; ; val it : int64 = 0L",Why is -1L * -9223372036854775808L == -9223372036854775808L "C_sharp : I added a method to my controllers to get the user-id from the JWT token in the HttpContext . In my unit tests the HttpContext is null , so I get an exception . How can I solve the problem ? Is there a way to moq the HttpContext ? Here is the method to get the user in my base controllerOne of my tests look like this protected string GetUserId ( ) { if ( HttpContext.User.Identity is ClaimsIdentity identity ) { IEnumerable < Claim > claims = identity.Claims ; return claims.ToList ( ) [ 0 ] .Value ; } return `` '' ; } [ Theory ] [ MemberData ( nameof ( TestCreateUsergroupItemData ) ) ] public async Task TestPostUsergroupItem ( Usergroup usergroup ) { // Arrange UsergroupController controller = new UsergroupController ( context , mapper ) ; // Act var controllerResult = await controller.Post ( usergroup ) .ConfigureAwait ( false ) ; // Assert // ... . }",xunit - how to get HttpContext.User.Identity in unit tests "C_sharp : Is there a way in .NET to replace a code where intervals are compared likeby something more elegant like a switch statement ( I think in Javascript `` case ( < 10 ) '' works , but in c # ) ? Does anyone else find this code is ugly as well ? if ( compare < 10 ) { // Do one thing } else if ( 10 < = compare & & compare < 20 ) { // Do another thing } else if ( 20 < = compare & & compare < 30 ) { // Do yet another thing } else { // Do nothing }",Is there an elegant way to replace if by something like switch when dealing with intervals ? "C_sharp : The existing Roslyn documentation is very thin so I 'm hoping someone knows how to do this , or at least point me in the right direction . I tried a number of things , including the following to format the sourceCode but it did n't work : Any help in this regard would be greatly appreciated ... . var tree = CSharpSyntaxTree.ParseText ( soureCode ) ; var root = ( CSharpSyntaxNode ) tree.GetRoot ( ) ; return root.ToFullString ( ) ;",What 's the best way to format a SyntaxTree in memory ? "C_sharp : I 've set the OutputCache to include 'VaryByContentEncodings= '' gzip '' ' in my ASP.net ASPX page . I want the page to serve different css files , a gzipped if the browser support it and the regular non compressed if the browser does n't support compression.Example : When I run the code I get the following error : The 'varybycontentencodings ' attribute is not supported by the 'outputcache ' directive in a page.I do n't know what 's the problem and why it does n't work . Second , do you think that by serving different gzip/non-compressed CSS I 'm doing the right thing . Just note that the files are served from Amazon S3 , so I ca n't rely on IIS or .NET engine to return the compressed files automatically . That 's why I want to serve to separate cached version of the page.In this it seems to be ok , but it does n't work ( using ASP.NET 4.5 ) : http : //msdn.microsoft.com/en-us/library/system.web.httpcachevarybycontentencodings.aspxHelp would be greatly appreciated . < % @ OutputCache Duration= '' 320 '' VaryByParam= '' none '' VaryByContentEncodings= '' gzip '' % >",OutputCache VaryByContentEncodings gzip does n't work "C_sharp : The post is specific to C # 8 . Let 's assume I want to have this method : If my .csproj looks like this ( i.e . C # 8 and nullable types are enabled , all warnings are errors ) : This code will produce the following build-time error : DictionaryEx.cs ( 28 , 78 ) : [ CS8714 ] The type 'TKey ' can not be used as type parameter 'TKey ' in the generic type or method 'Dictionary ' . Nullability of type argument 'TKey ' does n't match 'notnull ' constraint.Is there any way to specify that TKey has to be a non-nullable type ? public static TValue Get < TKey , TValue > ( this Dictionary < TKey , TValue > src , TKey key , TValue @ default ) = > src.TryGetValue ( key , out var value ) ? value : @ default ; < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup > < TargetFramework > netcoreapp3.0 < /TargetFramework > < LangVersion > 8 < /LangVersion > < Nullable > enable < /Nullable > < WarningsAsErrors > true < /WarningsAsErrors > < /PropertyGroup > … < /Project >",How do I specify `` any non-nullable type '' as a generic type parameter constraint ? "C_sharp : I have problem ( in reality not one but a lot of problems ) , I 'm developing Windows Phone 8 App that use BackgroundTransferService for transfer recorded wav file , on HTC 8S working almost fine , but on Nokia Lumia 920 seem strange behaviour , it has some not understandable upload limit equal to 0.5MB exactly 512 KB , with WiFi it seem working fine , but this problem is over cellular.when I reach TotalBytesSent = 512KB it stop uploadingI check this too and everything seems fineEDIT : on server-side is income only 380000 Bytes +/-5 KBAnd sometimes , after 10 failed starts ( when send only 380KB etc . ) of uploading file its suddenly upload it : D. Sometime where I am out of office it work perfectly on first time and other time never send it . Its totally unpredictable thingSOLUTION : Problem was Server-Side ... I had generic handler for saving this file without support of Range headers ( I think ) . When I change my project to `` Asp.NET Web Api Project '' inspired/copied by this tutorial Its does n't work yesterday , but today its unexpectedly start working : D Crazy Nokia and .NET.We will see tomorrow what happens next . var transferRequest = new BackgroundTransferRequest ( new Uri ( url , UriKind.Absolute ) ) ; transferRequest.Tag = DateTime.Now.ToString ( CultureInfo.InvariantCulture ) ; transferRequest.Method = `` POST '' ; transferRequest.UploadLocation = new Uri ( defect.VoiceRecordFileName , UriKind.Relative ) ; transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery ; transferRequest.Headers.Add ( `` Content-Type '' , `` audio/wav '' ) ; transferRequest.TransferStatusChanged += new EventHandler < BackgroundTransferEventArgs > ( transferRequest_TransferStatusChanged ) ; transferRequest.TransferProgressChanged += new EventHandler < BackgroundTransferEventArgs > ( transferRequest_TransferProgressChanged ) ; BackgroundTransferService.Add ( transferRequest ) ; var tmp = NetworkInformation.GetInternetConnectionProfile ( ) ; var cost = tmp.GetConnectionCost ( ) ; var type = cost.NetworkCostType ;",BackgroundTransferService/Request "C_sharp : I have Visual Studio 2010 and ReSharper installed and after looking for about an hour , I ca n't find this formatting setting anywhere.I 'd like it to look like this : and it keeps removing my space between Model.Something and % > to look like this : < div > < % : Model.Something % > < /div > < div > < % : Model.Something % > < /div >","How can I get VisualStudio 2010 with ReSharper to preserve my spaces between ' < % : ' , content , and ' % > ' ?" "C_sharp : ContextI 've been trying out jbEvain 's powerful Mono.Cecil library for just about two weeks now . I 've created the following function : GoalThe goal is to determine whether pCodeFunction and pMethodDefinition are refering to the same function definition or not . So far , I am able to compare the functions ' names and the number of parameters they have . I am well aware that it 's not enough to certify that they really are refering to the same function . I need help on improving my comparison . For instance , I believe one should always compare the parameter types in order to take potential function overrides into account.Previous attemptsI have tried comparing the parameter types but none of my attempts prevailed . Allow me to demonstrate.I thought I could compare the types as strings so I added abit of code like so : Given that pCodeFunction was refering to the following VB.Net function at runtimeI got the following outputI would prefer not to mess around with these two output values and try to parse them so that they match because this does n't seem like a very `` reliable '' way to compare types . What is be the most reliable way to compare the parameter types ? Bonus NotesThis function must be able to seek a function 's definition so long as the source code is either VB or C # .I am currently using the latest Mono.Cecil build ( 3.12.1 ) which you can download hereIf you want to use my function and insert it in a test class that you 've made , you will need the following imports : /// < summary > /// Returns true only if they match . /// < /summary > private bool CompareMethodDefinitionWithCodeFunction ( EnvDTE.CodeFunction pCodeFunction , Mono.Cecil.MethodDefinition pMethodDefintion ) { return pMethodDefintion.Name.Equals ( pCodeFunction.Name ) & & pMethodDefintion.Parameters.Count == pCodeFunction.Parameters.Count ; } /// < summary > /// Returns true only if they match . /// < /summary > private bool CompareMethodDefinitionWithCodeFunction ( EnvDTE.CodeFunction pCodeFunction , Mono.Cecil.MethodDefinition pMethodDefintion ) { foreach ( ParameterDefinition paramDef in pMethodDefintion.Parameters ) { Debug.WriteLine ( paramDef.ParameterType.FullName ) ; } foreach ( CodeElement ce in pCodeFunction.Parameters ) { CodeParameter codeParameter = ce as CodeParameter ; Debug.WriteLine ( codeParameter.Type.AsFullName ) ; } return pMethodDefintion.Name.Equals ( pCodeFunction.Name ) & & pMethodDefintion.Parameters.Count == pCodeFunction.Parameters.Count ; } Public Function SomeFunction ( ByVal arg As List ( Of String ) ) As Object Return New Object ( ) End Function System.Collections.Generic.List ` 1 < System.String > System.Collections.Generic.List ( Of System.String ) using EnvDTE ; using Mono.Cecil ;",Determining if a Mono.Cecil.MethodDefinition is refering to the same function as a given EnvDTE.CodeFunction "C_sharp : I have a string similar to this one : The boy said to his mother , `` Can I have some candy ? `` If I do a normal String.Split on it , I get : I want an array like so : Obviously , I could just loop through character by character and keep track of whether I 'm in a string or not and all that ... but is there a better way ? With Regexs perhaps ? { 'The ' , 'boy ' , 'said ' , 'to ' , 'his ' , 'mother ' , ' '' Can ' , ' I ' , 'have ' , 'some ' , 'candy ? '' ' } { 'The ' , 'boy ' , 'said ' , 'to ' , 'his ' , 'mother ' , 'Can I have some candy ? ' }",C # advanced String.Split C_sharp : There is an excellent post on how to map return values for a stored procedure call here : http : //elegantcode.com/2008/11/23/populating-entities-from-stored-procedures-with-nhibernate/The mapping in this example has been done through hbm files.I am trying to use the latest version of Nhibernate ( 3.2 ) where we can do mapping through code . I really want to find out the C # code that would create a mapping like below : < sql-query name= '' GetProductsByCategoryId '' > < return class= '' Product '' > < return-property column= '' ProductID '' name= '' Id '' / > < return-property column= '' ProductName '' name= '' Name '' / > < return-property column= '' SupplierID '' name= '' Supplier '' / > < return-property column= '' CategoryID '' name= '' Category '' / > < return-property column= '' QuantityPerUnit '' name= '' QuantityPerUnit '' / > < return-property column= '' UnitPrice '' name= '' UnitPrice '' / > < return-property column= '' UnitsInStock '' name= '' UnitsInStock '' / > < return-property column= '' UnitsOnOrder '' name= '' UnitsOnOrder '' / > < return-property column= '' ReorderLevel '' name= '' ReorderLevel '' / > < return-property column= '' Discontinued '' name= '' Discontinued '' / > < /return > exec dbo.GetProductsByCategoryId : CategoryId < /sql-query >,How to write mappings for a stored procedure "C_sharp : I 'm writing application with WPF WebBrowser control . It 's source is result of xml/xslt sourse from database . In the window that contains WebBrowser there is button for printing with handler : but in this case there is no background in printed document . I 've researched this issue , and it 's trouble with property in Internet Explorer page setup dialog - Allow the printing of background colors and images.I 've tried to change this by this code : but this is bad code . I do n't want to change registry values for one simple bool parameter.So , my question is : how can I change this parameter programmatically via code-behind without registry modification ? Thank you ! mshtml.IHTMLDocument2 doc = WBrowser.Document as mshtml.IHTMLDocument2 ; doc.execCommand ( `` Print '' , true , 0 ) ; RegistryKey regKey = Registry.CurrentUser .OpenSubKey ( `` Software '' , true ) .OpenSubKey ( `` Microsoft '' , true ) .OpenSubKey ( `` Internet Explorer '' , true ) .OpenSubKey ( `` PageSetup '' , true ) ; var defaultValue = regKey.GetValue ( `` Print_Background '' ) ; regKey.SetValue ( `` Print_Background '' , `` yes '' ) ;",WPF WebBrowser : changing IE print dialog properties programmatically C_sharp : I could write the following to convert an object to an integer.But I could also writeIs there any difference ? Which one should I be using ? Thanks in advance . Convert.ToInt32 ( myObject ) ; Int.Parse ( myObject.ToString ( ) ) ;,What is the difference between Convert and Parse ? "C_sharp : I was trying to mock an interface which takes a DateTimeOffset ? as one of its parameters . All of a sudden , Visual Studio started reporting an 'Internal Compiler Error ' and that it has 'stopped working ' . After a lot of trials , I started removing files one by one , and then code line by line . This reduced to the below code , which reproduces this error : The issue seems to be the line : If I comment it , the compiler works fine . Also , the issues is that I am setting up a new DateTime ( ) , which fits in a DateTimeOffset.Is this a bug in Moq , or VS2012 ? Anyone ever got this error before ? UPDATEThe following code sample also results in a compile error , both with the regular Visual Studio 2012 compiler and with Roslyn CTP September 2012 : The error : 1 > CSC : error CS0583 : Internal Compiler Error ( 0xc0000005 at address 00D77AFB ) : likely culprit is 'BIND'.This code has nothing to do with Moq . public class testClass { public interface ITest { void Test ( DateTimeOffset ? date ) ; } public void test2 ( ) { var mock = new Mock < ITest > ( ) ; mock.Setup ( x = > x.Test ( new DateTime ( 2012 , 1 , 1 ) ) ) ; } } mock.Setup ( x = > x.Test ( new DateTime ( 2012 , 1 , 1 ) ) ) ; using System ; using System.Linq.Expressions ; public interface ITest { void Test ( DateTimeOffset ? date ) ; } public class TestClass { Expression < Action < ITest > > t = x = > x.Test ( new DateTime ( 2012 , 1 , 1 ) ) ; }",Expression that takes a DateTimeOffset causes Visual Studio Internal Compiler Error "C_sharp : I wrote a method that returns CommandType is of Type enumMy issue is that the value in the KeyValuePair sometimes is an enum , and sometimes it is a list of strings , but I need to keep all the KeyValuePair in one list . currently , I pass the value as an object in the keyvaluepair and when the method returns the list and an iterate through it , based on the key , I cast the value back to its original type . Is there a better way to implement this ? here is a sample code List < KeyValuePair < CommandType , List < string > > > public enum CommandType { Programmed , Manual } public enum ProgrammedCommands { Sntp , Snmp , } private List < KeyValuePair < CommandType , object > > GetCommandsFromTemplate ( string [ ] templateLines ) { var list = new List < KeyValuePair < CommandType , object > > ( ) ; if ( templateLines ! = null ) for ( int lineIndex = 0 ; lineIndex < templateLines.Length ; lineIndex++ ) { if ( templateLines [ lineIndex ] .Contains ( `` ! * '' ) & & templateLines [ lineIndex ] .Contains ( `` * ! '' ) ) { KeyValuePair < CommandType , object > ProgrammedSetting ; List < string > programmedCommandList ; if ( templateLines [ lineIndex ] .Contains ( `` SNTP - SNTP Server Commands '' ) ) { ProgrammedSetting = new KeyValuePair < CommandType , object > ( CommandType.Programmed , ProgrammedCommands.Sntp ) ; list.Add ( ProgrammedSetting ) ; } else if ( templateLines [ lineIndex ] .Contains ( `` MANUAL '' ) ) { lineIndex++ ; List < string > manual = new List < string > ( ) ; while ( true ) { if ( lineIndex > = templateLines.Length ) break ; if ( templateLines [ lineIndex ] .Contains ( `` ! ! [ `` ) ) lineIndex++ ; else if ( templateLines [ lineIndex ] .Contains ( `` ] ! ! '' ) ) break ; else { manual.Add ( templateLines [ lineIndex ] ) ; lineIndex++ ; } } ProgrammedSetting = new KeyValuePair < CommandType , object > ( CommandType.Manual , manual ) ; list.Add ( ProgrammedSetting ) ; } } } return list ; }",How can I create a keyvaluepair with a value two different data types ? "C_sharp : I have been reading a lot of literature lately surrounding Value Types & Reference Types , and their differences . This question surrounds the topic of mutability and immutability of value types.Based on what I have read , it seems that value types in .NET should be written in such a fashion that they are immutable ; that is , once they have been assigned a value , the value of that type in memory never changes . Only subsequent copies of the type may construct new instances in memory with new values based off the original . It would seem that mutability in .NET is evil.To clarify the understanding of immutability ( for my own sanity , and for others ) , I have demonstrated this below : DateTime and TimeSpan are examples of immutable structs because once a value has been assigned to an instance , that instances value can not change , this is evident through readonly properties : Immutability can however be confusing when looking ar primitive types such as Int32 , Double or Char , because the types appear to be mutable , but my gut feeling is that actually , immutability is handled transparently via the CLR ; take for example the following operations ( I 've commented in some very basic x86 equivalent to understand how immutability is handled in terms of a primitive type ) All well and good so far ; Microsoft appear to be doing a good job of implementing immutability into their value types ; but then we begin to find the bad apples , and suble nuances which make mutability look okay and lul developers into a false sense of security ! I 'm talking about Point , Size , Rectangle ( and a few others ) in the System.Drawing namespace.All of a sudden we 're given the ability to mutate a value type by it 's properties , and I have a theory as to why this is possible ; take for example the following codeHowever as stated I had a theory as to why these structures are mutable : Microsoft just wanted to make it easier to work with these structures.They are interoperable with native GDI/GDI+ calls , so their behavior was designed around their native C/C++ counterparts.So finally my questions : Have I fully covered and understood immutability and mutability ? Should developers aim to build immutable structs as a rule ? When is it acceptable to build mutable structs ? DateTime dt = new DateTime ( ) ; DateTime newdt = dt.AddDays ( 2 ) ; // Okay , new value stored in newdtnewdt.Year = 1945 ; // Error , can not write to readonly property int x = 0 ; // xor eax , eax ; 'clear register to 0// push eax ; 'push eax ( 0 ) onto the stackx = 5 ; // pop eax ; 'pop stack ( 0 ) into eax// mov eax , 5 ; 'eax = 5// push eax ; 'push eax ( 5 ) onto the stackx++ ; // pop eax ; 'pop stack ( 5 ) into eax// add eax , 1 ; 'eax = 5 + 1// push eax ; 'push eax ( 6 ) onto the stack Point p = new Point ( ) ; p.X = 100 ; p.Y = 200 ; // Immutability ( had it been implemented here ) might infer the following usagePoint p = new Point ( 100 , 200 ) ; Point p2 = p.AddXY ( 200 , 300 ) ;","Value Types , Immutability ( Good ) & Mutability ( Evil ) in .NET" "C_sharp : I 'm using Reflection.Emit to define a new type , and I 'd like the type to implement IComparable ( T ) , where T would be the newly defined type . It seems to me like I have a chicken-and-egg problem.As a fallback , I can always just implement IComparable , but if possible I 'd like the generic interface ; I just ca n't see how I can do it using Emit , because the type does n't exist before I define it . class DefinedType : IComparable < DefinedType > { // ... }",Using Reflection.Emit to implement generic interface "C_sharp : I want to make a Cordova phone app and a web application . Both the application and the app share the same database.On the mobile app , the user actions send requests to a web service ( over https ) that writes to the database . On the mobile app , I use https : //oauth.io to let the user register and log in with multiple open auth providers . Trying to make it work for facebook , for now.I just ca n't figure how to use the Identity user management in that context . Most of the examples I find are in the context of a web app where the user clicks and it calls the account controller . In my case , the oauth.io lib calls facebook , returns an access token , which I pass to my service . The cordova app passes the accessToken to this method to my server side web service.I tried this : Does n't work because the usermanagement object inside the account controller is null.There is an overload of the AccountController constructor but I have a feeling I 'm doing this whole thing the wrong way.Let 's say the server side receives a facebook access token . How do use OWIN and Identity user management system from there ? var client = new FacebookClient ( accessToken ) ; if ( client ! = null ) { dynamic fbresult = client.Get ( `` me '' ) ; if ( fbresult [ `` id '' ] ! = null ) { var fbid = fbresult [ `` id '' ] .ToString ( ) ; and where do we go from now ? how do I insert a new user var user = new ApplicationUser ( ) { UserName = fbresult [ `` id '' ] } ; Backend.Controllers.AccountController ac = new Controllers.AccountController ( ) ; ac.UserManager.CreateAsync ( user ) ;",How to use Identity user managament with Cordova and OAuth.io ? "C_sharp : I was looking through the sample LINQ queries provided with LINQPad taken from the C # 4.0 in a Nutshell book , and ran across something I have never used in LINQ to SQL ... Compiled Queries.Here is the exact exmaple : What does precompiling a LINQ to SQL query like this actually buy me ? Would I get a performance boost from a query slightly more complex than this one ? Is this even used in actual practice ? // LINQ to SQL lets you precompile queries so that you pay the cost of translating// the query from LINQ into SQL only once . In LINQPad the typed DataContext is// called TypeDataContext , so we proceed as follows : var cc = CompiledQuery.Compile ( ( TypedDataContext dc , decimal minPrice ) = > from c in Customers where c.Purchases.Any ( p = > p.Price > minPrice ) select c ) ; cc ( this , 100 ) .Dump ( `` Customers who spend more than $ 100 '' ) ; cc ( this , 1000 ) .Dump ( `` Customers who spend more than $ 1000 '' ) ;",LinqToSql Precompiling queries benefit ? "C_sharp : Is it possible to automatically return from a function using a Breakpoint/Tracepoint ? I do n't want to drag the execution point or set it with CTRL+SHIFT+F10 every time the breakpoint is hit.I tried `` printing '' the following `` messages '' When Hit , but the executions continue without change.Note that I need to return from the function without actually changing code.To clarify what a Tracepoint is : `` A tracepoint is a breakpoint with a custom action associated with it . When a tracepoint is hit , the debugger performs the specified tracepoint action instead of , or in addition to , breaking program execution . '' From MSDN.If you do n't know what I mean with `` printing messages '' , you might want to read this AltDevBlogADay post about Tracepoints . It 's good . { return ; } { return null ; }",Return from a function using a breakpoint "C_sharp : In code , say we have : The cn.close is not technically required as garbage collection will take care of the connection for us.However , I always like to close it anyway and to not rely on garbage collection . Is this bad ? A waste of time ? Or considered good practise to not rely on automation ? Thanks for your thoughts and opinions in advance . I 'll mark this as community wiki as it 's probably subjective . using ( SqlConnection cn = new SqlConnection ( ConfigurationManager.ConnectionStrings [ `` LocalSqlServer '' ] .ToString ( ) ) ) { cn.Open ( ) ; // Set all previous settings to inactive using ( SqlCommand cmd = new SqlCommand ( `` UPDATE tblSiteSettings SET isActive = 0 '' , cn ) ) { cmd.ExecuteNonQuery ( ) ; } cn.Close ( ) ; }","Garbage collection , should we rely on it ?" "C_sharp : The better way to ask this question would be an example as followsWhat are the pros and cons of the 2 approaches ? Is one always better than the other or under specific circumstances ? If using Approach1 , using an interface would be moot right ? since anyone can access the public methods anyway ? OR public interface IDoSomething { void Method1 ( string operation , User user , string category ) void Method2 ( string operation , User user ) void Method3 ( string operation ) } //Approach1Class A : IDoSomething { public void Method1 ( string operation , User user , string category ) { //do some db logic here ... } public void Method2 ( string operation , User user ) { Method1 ( operation , user , `` General '' ) ; } public void Method3 ( string operation ) { Method1 ( operation , User.GetDefaultUser ( ) , `` General '' ) ; } } //Approach2Class A : IDoSomething { void IDoSomething.Method1 ( string operation , User user , string category ) { //do some logic here ... } void IDoSomething.Method2 ( string operation , User user ) { ( this as IDoSomething ) .Method1 ( operation , user , `` General '' ) ; } void IDoSomething.Method3 ( string operation ) { ( this as IDoSomething ) .Method1 ( operation , User.GetDefaultUser ( ) , `` General '' ) ; } }",if using an interface should a class always strictly implement an interface "C_sharp : I 'm trying to find all the builds and releases that are configured to use a specific agent pool , using the .NET Client Libraries.Assuming agentPoolId , I can get all the build definitions like this : But I could n't find a way to find the release definitions that have one or more environments configured to use a particular agent . Any suggestion ? // _connection is of type VssConnectionusing ( var buildClient = _connection.GetClient < BuildHttpClient > ( ) ) { List < BuildDefinitionReference > allBuilds = await buildClient.GetDefinitionsAsync ( projectName , top : 1000 , queryOrder : DefinitionQueryOrder.DefinitionNameAscending ) ; List < BuildDefinitionReference > builds = allBuilds.Where ( x = > HasAgentPoolId ( x , agentPoolId ) ) .ToList ( ) ; } private bool HasAgentPoolId ( BuildDefinitionReference buildDefinition , int agentPoolId ) { TaskAgentPoolReference pool = buildDefinition ? .Queue ? .Pool ; if ( pool == null ) { return false ; } return pool.Id.Equals ( agentPoolId ) ; }",Azure Devops - Get release definitions by agent pool ID "C_sharp : While browsing the MSDN documentations on Equals overrides , one point grabbed my attention.On the examples of this specific page , some null checks are made , and the objects are casted to the System.Object type when doing the comparison : Is there a specific reason to use this cast , or is it just some `` useless '' code forgotten in this example ? public override bool Equals ( System.Object obj ) { // If parameter is null return false . if ( obj == null ) { return false ; } // If parameter can not be cast to Point return false . TwoDPoint p = obj as TwoDPoint ; if ( ( System.Object ) p == null ) { return false ; } // Return true if the fields match : return ( x == p.x ) & & ( y == p.y ) ; }",Why casting to object when comparing to null ? "C_sharp : When I power my APIs with Swagger , I follow one of those guids and I always put the MVC injections before Swagger injections like this.A friend of mine asked why I apply that order and not handle the Swagger related lines first , before MVC . I discovered that I could n't explain that to him nor motivate it ( other than a very embarrassed well ... that 's the way it is ... ) . That tells me that I should dig a bit into that matter.Short googling revealed nothing of relevance as far I 've noticed , so I 'm asking here . services.AddMvc ( ) ; services.AddSwaggerGen ( _ = > { ... } ) ; app.UseMvc ( ) ; app.UseSwagger ( ) ; app.UseSwaggerUI ( c = > { ... } ) ;",The order between AddMvc/AddSwaggerGen and UseMvc/UseSwagger ( UI ) "C_sharp : Here 's what I mean : Above method can be awaited and I think it closely resembles to what the Task-based Asynchronous Pattern suggests doing ? ( The other patterns I know of are the APM and EAP patterns . ) Now , what about the following code : The key differences here are that the method is async and it utilizes the await keywords - so what does this change in contrast to the previously written method ? I know it can too - be awaited . Any method returning Task can for that matter , unless I 'm mistaken.I 'm aware of the state machine created with those switch statements whenever a method is labeled as async , and I 'm aware that await itself uses no thread - it does n't block at all , the thread simply goes to do other things , until it 's called back to continue execution of the above code . But what 's the underlying difference between the two methods , when we invoke them using the await keyword ? Is there any difference at all , and if there is - which is preferred ? EDIT : I feel like the first code snippet is preferred , because we effectively elide the async/await keywords , without any repercussions - we return a task that will continue its execution synchronously , or an already completed task on the hot path ( which can be cached ) . public Task < SomeObject > GetSomeObjectByTokenAsync ( int id ) { string token = repository.GetTokenById ( id ) ; if ( string.IsNullOrEmpty ( token ) ) { return Task.FromResult ( new SomeObject ( ) { IsAuthorized = false } ) ; } else { return repository.GetSomeObjectByTokenAsync ( token ) .ContinueWith ( t = > { t.Result.IsAuthorized = true ; return t.Result ; } ) ; } } public async Task < SomeObject > GetSomeObjectByToken ( int id ) { string token = repository.GetTokenById ( id ) ; if ( string.IsNullOrEmpty ( token ) ) { return new SomeObject ( ) { IsAuthorized = false } ; } else { SomeObject result = await repository.GetSomeObjectByTokenAsync ( token ) ; result.IsAuthorized = true ; return result ; } }",How does using await differ from using ContinueWith when processing async tasks ? "C_sharp : I have a button , and I use Process.Start when clicking it , although I select data from textBox1.Text.Although this data on textBox1.Text does not come out properly if there are spaces in textBox1.Texte.g . textBox1.Text = testing_123 worksalthough textBox1.Text = testing 1 2 3 does n't work ( it will only include `` testing '' ) The code is below : private void button19_Click ( object sender , EventArgs e ) { Process.Start ( `` test.exe '' , textBox1.Text ) ; }",How to handle values with spaces in Process.Start in C # "C_sharp : I made very simple C # and F # test programs.c # 71 msf # 1797 msI made second version from F # which work similar than c # but the result not not changed significantly ( 1650ms ) I do n't understand the big difference in speed between the two languages.The two programs have very similar IL code , both use IEnumerable , moreover the F # replace the function call with operation.I rewrote c # code based on f # IL code.The IL code of two programs are same but the speed still very different.I found the IL difference thanks for Foggy FinderThe slow codeThe fast code using System ; using System.Collections.Generic ; using System.Diagnostics ; using System.Linq ; namespace ConsoleApplication2 { class Program { static int Remainder ( int num ) { return num % 2 ; } static int SumOfremainders ( IEnumerable < int > list ) { var sum = 0 ; foreach ( var num in list ) { sum += Remainder ( num ) ; } return sum ; } static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; var nums = Enumerable.Range ( 1 , 10000000 ) ; sw.Start ( ) ; var a = SumOfremainders ( nums ) ; sw.Stop ( ) ; Console.WriteLine ( `` Duration `` + ( sw.ElapsedMilliseconds ) ) ; Console.WriteLine ( `` Sum of remainders : { 0 } '' , a ) ; } } } let remainder x = x % 2 let sumORemainders n = n | > Seq.map ( fun n- > remainder n ) | > Seq.sumlet seqb = Seq.init 10000000 ( fun n- > n ) let timer =System.Diagnostics.Stopwatch ( ) timer.Start ( ) let a = ( sumORemainders seqb ) timer.Stop ( ) printfn `` Elapsed Time : `` System.Console.WriteLine timer.ElapsedMillisecondsprintfn `` Sum of squares of 1-100 : % d '' a [ < EntryPoint > ] let main argv = 0 // return an integer exit code let remainder x = x % 2 let sumORemainders ( input : seq < int > ) = let mutable sum = 0 let en = input.GetEnumerator ( ) while ( en.MoveNext ( ) ) do sum < - sum + remainder en.Current sumlet seqb = Seq.init 10000000 ( fun n- > n ) let timer =System.Diagnostics.Stopwatch ( ) timer.Start ( ) let a = ( sumORemainders seqb ) timer.Stop ( ) printfn `` Elapsed Time : `` System.Console.WriteLine timer.ElapsedMillisecondsprintfn `` Sum of squares of 1-100 : % d '' a [ < EntryPoint > ] let main argv = 0 // return an integer exit code static int SumOfremainders ( IEnumerable < int > list ) { var sum = 0 ; IEnumerator < int > e = list.GetEnumerator ( ) ; while ( e.MoveNext ( ) ) { sum += e.Current % 2 ; } return sum ; } [ CompilationMapping ( SourceConstructFlags.Module ) ] public static class Program { [ Serializable ] internal class seqb @ 18 : FSharpFunc < int , int > { internal seqb @ 18 ( ) { } public override int Invoke ( int n ) { return n ; } } [ CompilationMapping ( SourceConstructFlags.Value ) ] public static IEnumerable < int > seqb { get { return $ Program.seqb @ 18 ; } } [ CompilationMapping ( SourceConstructFlags.Module ) ] public static class Program { [ CompilationMapping ( SourceConstructFlags.Value ) ] public static int [ ] seqb { get { return $ Program.seqb @ 20 ; } }",Why is there a performance difference between LINQ ( c # ) vs Seq ( f # ) "C_sharp : Consider the following interface : Trying to implement that withdoes not work , the compiler complains the M is missing a new ( ) constraint.When I add the constraint as inthis still does not do the trick , as the constraints of Foo.Bar do not match the constraints of the interface method now ( and I 'm not able to change that ) .The documentation for the compiler error CS0425 says To avoid this error , make sure the where clause is identical in both declarations , or implement the interface explicitly.If `` implementing the interface explicitly '' is the solution : How do I do it ? public interface IFoo { M Bar < M > ( ) ; } class Foo : IFoo { public M Bar < M > ( ) { return new M ( ) ; } } class Foo : IFoo { public M Bar < M > ( ) where M : new ( ) { return new M ( ) ; } }",Implement a generic interface missing new constraint "C_sharp : I 've added a determinant progress bar to a Windows 8.1 phone app but I do n't see a method of increasing the thickness of the progress bar.I tried to change the thickness by increasing the height property but this has no effect on it 's size.Does anyone have any idea how to increase the height/thickness of the red progress bar ? This is the declaration of the progress bar in my xaml : < ProgressBar IsIndeterminate= '' False '' Maximum= '' 100 '' Value= '' 30 '' Width= '' 200 '' Margin= '' 128,240,128,262 '' / >",How to increase the thickness of a determinant progress bar ? "C_sharp : I am working on a windows phone 7 application that uses the FluidMoveBehavior in some of my ListBoxes . For some reason , the FluidMoveBehavior animation seems to want to activate at inappropriate times . I currently have a ListBox on my main page , and I use the following ItemsPanelTemplate which is just a basic StackPanel with a FluidMoveBehavior attached to it : This works fine when I add/remove items while on the same screen . The animation plays perfectly . However , when I navigate to a new page from my main page , then navigate back , the fluid move animation is triggered as if all of the items were added at once . Is there any way to disable this behavior so it only triggers the animation when the list actually changes ? < ItemsPanelTemplate x : Key= '' fancyListBoxItemsPanelTemplate '' > < StackPanel > < Custom : Interaction.Behaviors > < il : FluidMoveBehavior AppliesTo= '' Children '' > < il : FluidMoveBehavior.EaseX > < ExponentialEase EasingMode= '' EaseInOut '' / > < /il : FluidMoveBehavior.EaseX > < il : FluidMoveBehavior.EaseY > < ExponentialEase EasingMode= '' EaseInOut '' / > < /il : FluidMoveBehavior.EaseY > < /il : FluidMoveBehavior > < /Custom : Interaction.Behaviors > < /StackPanel > < /ItemsPanelTemplate >",FluidMoveBehavior triggering on Back navigation "C_sharp : String.Compare ( ) with Hungarian CultureInfo works not correct for specific strings : Of course I suppose to get `` Equal '' answer , but it 's not.If I change the string it works properly ( for example for `` abc '' and `` ABC '' it prints `` Equal '' ) It seems a problem with specific symbols . if ( 0 == String.Compare ( @ '' ny '' , @ '' nY '' , true , new CultureInfo ( `` hu-HU '' ) ) ) Console.WriteLine ( `` Equal '' ) ; else Console.WriteLine ( `` Not equal '' ) ;",String.Compare ( ) with Hungarian CultureInfo works not correct for specific strings "C_sharp : * Despite the edit to my title by another user , I am seeking a solution that uses JSON.NET 's library from C # *A reply containing psuedocode is fine ! : ) I 'm trying to work with hierarchical data provided by a JSON dataset . I 'm using C # and JSON.NET . I 'm open to using Linq in general and Linq for JSON.NET in particular if it would help ; otherwise , using non-Linq C # /JSON.NET is fine.Ideally , I am trying to accomplish two things elegantly : I want to extract JSON that represents each branch and that branch 's own properties -- not its child ( nested ) branch objects ( I will explain more in a moment ) .I want to track the parent node as I create my branch objects . For further consideration , please refer to the following JSON excerpt : Related to Goal 1 ( from above ) : Given JSON that is composed of nested JSON objects , I want to pick out only the simple ( string ) properties for each branch . For instance , I would like to extract the JSON for Branch1 that would contain only Prop1A , Prop1B , and Prop1C properties . I would then like to extract the JSON for Branch2 that would contain only Prop2A , Prop2B , and Prop2C properties , etc . I realize that I can represent the entire JSON as a JSON.NET JToken object then iterate through its Children ( ) and look only for JTokenType.Property types , but perhaps there is a more elegant way to quickly pick out just the property types using Linq ... ? In the end , I would have three separate JSON objects that would look like this : JSON Object 1 : JSON Object 2 : JSON Object 3 : { `` Prop3A '' : `` 3A '' , `` Prop3B '' : `` 3B '' , `` Prop3C '' : `` 3C '' } Related to Goal 2 ( from above ) : Ideally , each extracted JSON above would also have a property indicating its parent . Thus , the final JSON objects would look something like this : And : And : Any thoughts ? { `` Branch1 '' : { `` Prop1A '' : `` 1A '' , `` Prop1B '' : `` 1B '' , `` Prop1C '' : `` 1C '' , `` Branch2 '' : { `` Prop2A '' : `` 2A '' , `` Prop2B '' : `` 2B '' , `` Prop2C '' : `` 2C '' , `` Branch3 '' : { `` Prop3A '' : `` 3A '' , `` Prop3B '' : `` 3B '' , `` Prop3C '' : `` 3C '' } } } } { `` Prop1A '' : `` 1A '' , `` Prop1B '' : `` 1B '' , `` Prop1C '' : `` 1C '' } { `` Prop2A '' : `` 2A '' , `` Prop2B '' : `` 2B '' , `` Prop2C '' : `` 2C '' } { `` Prop1A '' : `` 1A '' , `` Prop1B '' : `` 1B '' , `` Prop1C '' : `` 1C '' , `` Parent '' : `` '' } { `` Prop2A '' : `` 2A '' , `` Prop2B '' : `` 2B '' , `` Prop2C '' : `` 2C '' , `` Parent '' : `` Branch1 '' } { `` Prop3A '' : `` 3A '' , `` Prop3B '' : `` 3B '' , `` Prop3C '' : `` 3C '' , `` Parent '' : `` Branch2 '' }",Picking Out Simple Properties from Hierarchical JSON "C_sharp : Yesterday I found this strange behavior in my C # code : I assumed the program would print 1|2|0 but in fact it printed 1|2|3|0.Looking at the generated IL code ( via ILSpy ) you can see that s.Pop ( ) * 0 is optimized to simply 0 : ILSpy decompilation : First I tested this initially under Windows 7 with Visual Studio 2015 Update 3 with both Release mode ( /optimize ) and Debug mode and with various target frameworks ( 4.0 , 4.5 , 4.6 and 4.6.1 ) . In all 8 cases the result was the same ( 1|2|3|0 ) .Then I tested it under Windows 7 with Visual Studio 2013 Update 5 ( again with all the combinations of Release/Debug mode and target framework ) . To my surprise the statement is here not optimized away and yields the expected result 1|2|0.So I can conclude that this behavior is neither dependent on /optimize nor the target framework flag but rather on the used compiler version.Out of interest I wrote a similar code in C++ and compiled it with the current gcc version . Here a function call multiplied with zero is not optimized away and the function is properly executed.I think such an optimization would only be valid if stack.Pop ( ) were a pure function ( which it definitely is n't ) . But I 'm hesitant to call this a bug , I assume it 's just a feature unknown to me ? Is this `` feature '' anywhere documented and is there an ( easy ) way to disable this optimization ? Stack < long > s = new Stack < long > ( ) ; s.Push ( 1 ) ; // stack contains [ 1 ] s.Push ( 2 ) ; // stack contains [ 1|2 ] s.Push ( 3 ) ; // stack contains [ 1|2|3 ] s.Push ( s.Pop ( ) * 0 ) ; // stack should contain [ 1|2|0 ] Console.WriteLine ( string.Join ( `` | '' , s.Reverse ( ) ) ) ; // ... IL_0022 : ldloc.0IL_0023 : ldc.i4.0IL_0024 : conv.i8IL_0025 : callvirt instance void class [ System ] System.Collections.Generic.Stack ` 1 < int64 > : :Push ( ! 0 ) // ... Stack < long > s = new Stack < long > ( ) ; s.Push ( 1L ) ; s.Push ( 2L ) ; s.Push ( 3L ) ; s.Push ( 0L ) ; // < - the offending lineConsole.WriteLine ( string.Join < long > ( `` | '' , s.Reverse < long > ( ) ) ) ;",Roslyn compiler optimizing away function call multiplication with zero C_sharp : Is it worth to write this piece of code : instead of just returning new object every time : From what I know command getters are used pretty rarely and RelayCommand 's constructor is pretty quick . Is it better to write longer code ? RelayCommand _saveCommand ; public ICommand SaveCommand { get { if ( _saveCommand == null ) { _saveCommand = new RelayCommand ( this.Save ) ; } return _saveCommand ; } } public ICommand SaveCommand { get { return new RelayCommand ( this.Save ) ; } },Is it bad to return new ICommand every time in property getter ? "C_sharp : Update : I 'm sorry if maybe my question is n't clear enough . I 've read about the command pattern , but unfortunately have not used it myself . I 'm trying to figure out how I could use it ( or some other pattern ) to make game events abstract enough that the server can process them using a single Process ( ) method . My main hang up here is making sure the game events receive enough information to actually DO what they need to do ( e.g. , log in a user and add them to the active user list , send map data , move a player , etc. ) . A relevant example would be very much appreciated.I 'm pretty new to game development but have decided to start working on a ( relatively ) simple , 2D MMORPG in my spare time . I would consider myself to be a very capable programmer and I have a good foundation of skills , but I 'm still grappling with some of the design related to a client-server game . Specifically , I 'm having a hard time thinking of an extensible way to process commands . Let me provide a functional example : Log In RequestStart the gameClick `` Continue '' Type a user name and passwordClick `` Log In '' See the character wherever you were when you logged outFrom a client-server architecture perspective , here 's what I 'm doing right now : [ Client ] Send a SimpleTextNetworkMessage to the server - { LogInRequest , UN : [ UserName ] |PW : [ Password ] } Darken the UI and wait for a response ( timeout : 10 seconds ) Receive a SimpleTextNetworkMessage from the server - { LogInSuccessResponse , [ Player ID ] } Send a SimpleTextNetworkMessage to the server - { GetPlayerInfoRequest , [ Player ID ] } Receive a SimpleDataNetworkMessage from the server - { GetPlayerInfoResponse , [ Player Info ] } Send a SimpleTextNetworkMessage to the server - { GetMapInfoRequest , [ Player ID ] } Receive a SimpleDataNetworkMessage from the server - { GetMapInfoResponse , [ MapData ] } Draw the screenMy example identifies three key events that occur : Process Log InValidate the information the user provided , download the player information from the database ( HP , MP , last location , etc . ) , and associate the player with a map and a connection.Get Player InfoSend back information about the player 's stats , equipment , experience , current map ID , and anything else that needs to be displayed on the UI.Get Map InfoSend information to the player about all the tiles within a 50 tile radius ... this should include tile information for a three-layer map and the locations and names of NPCs/monsters/players ; when the player moves , more map information will be requested/updated.You can see that each of these processes is different and requires different information . On the server-side , how can I do something like : while ( ServerIsRunning ) { foreach ( Client c in clients ) { eventQueue.AddList ( c.ReceiveAll ( ) ) ; } foreach ( GameEvent event in eventQueue ) { event.Process ( ) ; } int [ ] keys = messageQueue.Keys ; foreach ( int key in keys ) { Client c = clients.Get ( key ) ; foreach ( NetworkMessage message in messageQueue [ key ] ) { c.Send ( message ) ; } } }",What 's an extensible way of implementing server-side command processing in an MMORPG ? "C_sharp : I am trying to use Parse in my Unity game in order to implement high scores . My problem is that when I try to put the game on my android device to test it , the name of the app comes up different . It comes up as `` ParseUnityPushSample '' even though I have not changed anything besides adding the files that Parse gives me to use it . The build settings have not changed and it even shows that my package name is the same , yet testing it on a device has this result . Testing it in Unity 5 works fine . The game loads as it should . This only happens when I try to put it on a device for testing.Along with it changing the app name , it also crashes when opening . I get a prompt that says `` ParseUnityPushSample '' has failed anytime I try to open it on an android device.EDIT : Okay so I figured out a way to view some errors that occur when testing on a device . I get this error : `` Unable to find unity activity in manifest . You need to make sure orientation attribute is set to sensorLandscape manually.UnityEditor.BuildPlayerWindow : BuildPlayerAndRun ( ) '' I have no idea what the issue is though since I have manually set the orientation for the activity to sensorLandscape in the Android Manifest.8/10/15I have come to learn that this may be an issue with Parse v1.5.2 although changing to v1.3.2 did not help with the issue I am facing either . I will update as soon as I learn anything more.8/11/15Updating to v1.5.4 did not fix the issue either . Still having problems with the android manifest with the same error message . If anyone has any idea please let me know ! < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' com.laserdeflector.sab '' android : versionName= '' 1.0.1 '' android : versionCode= '' 1 '' android : installLocation= '' preferExternal '' > < uses-sdk android : minSdkVersion= '' 10 '' android : targetSdkVersion= '' 22 '' / > < uses-permission android : name= '' android.permission.INTERNET '' / > < uses-permission android : name= '' android.permission.ACCESS_NETWORK_STATE '' / > < uses-permission android : name= '' android.permission.WAKE_LOCK '' / > < uses-permission android : name= '' android.permission.VIBRATE '' / > < uses-permission android : name= '' android.permission.GET_ACCOUNTS '' / > < uses-permission android : name= '' com.google.android.c2dm.permission.RECEIVE '' / > < permission android : protectionLevel= '' signature '' android : name= '' com.laserdeflector.sab.permission.C2D_MESSAGE '' / > < uses-permission android : name= '' com.laserdeflector.sab.permission.C2D_MESSAGE '' / > < uses-permission android : name= '' com.android.vending.BILLING '' / > < application android : label= '' Laser Deflector '' android : icon= '' @ drawable/app_icon '' android : screenOrientation= '' sensorLandscape '' android : name= '' com.soomla.SoomlaApp '' android : debuggable= '' false '' android : isGame= '' true '' > < activity android : name= '' .UnityPlayerActivity '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < category android : name= '' android.intent.category.LEANBACK_LAUNCHER '' / > < /intent-filter > < /activity > < receiver android : name= '' com.parse.ParsePushBroadcastReceiver '' android : permission= '' com.google.android.c2dm.permission.SEND '' > < intent-filter > < action android : name= '' com.google.android.c2dm.intent.RECEIVE '' / > < action android : name= '' com.google.android.c2dm.intent.REGISTRATION '' / > < category android : name= '' com.laserdeflector.sab '' / > < /intent-filter > < /receiver > < service android : name= '' com.parse.ParsePushService '' / > < activity android : name= '' com.soomla.store.billing.google.GooglePlayIabService $ IabActivity '' android : theme= '' @ android : style/Theme.Translucent.NoTitleBar.Fullscreen '' / > < meta-data android : name= '' billing.service '' android : value= '' google.GooglePlayIabService '' / > < /application > < uses-feature android : glEsVersion= '' 0x00020000 '' / > < uses-permission android : name= '' android.permission.READ_PHONE_STATE '' / > < uses-feature android : name= '' android.hardware.touchscreen '' android : required= '' false '' / > < uses-feature android : name= '' android.hardware.touchscreen.multitouch '' android : required= '' false '' / > < uses-feature android : name= '' android.hardware.touchscreen.multitouch.distinct '' android : required= '' false '' / > < /manifest >",App implementing Parse Unity Plugin crashes on android device but works fine in editor "C_sharp : I have following appDomainManager codeand following unmanaged code for starting the runtime hostthe call to runtimeHost- > Start ( ) fails with error code -2146233054 , cansomeone point out what should i do to fix this ? public class HostAppDomainManager : AppDomainManager { public override void InitializeNewDomain ( AppDomainSetup appDomainInfo ) { this.InitializationFlags = AppDomainManagerInitializationOptions.RegisterWithHost ; } } int _tmain ( int argc , _TCHAR* argv [ ] ) { ICLRMetaHost *pMetaHost = NULL ; HRESULT hr ; ICLRRuntimeInfo *runtimeInfo = NULL ; __try { hr = CLRCreateInstance ( CLSID_CLRMetaHost , IID_ICLRMetaHost , ( LPVOID* ) & pMetaHost ) ; hr = pMetaHost- > GetRuntime ( L '' v4.0.30319 '' , IID_ICLRRuntimeInfo , ( LPVOID* ) & runtimeInfo ) ; ICLRRuntimeHost *runtimeHost = NULL ; hr = runtimeInfo- > GetInterface ( CLSID_CLRRuntimeHost , IID_ICLRRuntimeHost , ( LPVOID* ) & runtimeHost ) ; ICLRControl* clrControl = NULL ; hr = runtimeHost- > GetCLRControl ( & clrControl ) ; hr = clrControl- > SetAppDomainManagerType ( L '' ExceptionThrower.dll '' , L '' ExceptionThrower.HostAppDomainManager '' ) ; hr = runtimeHost- > Start ( ) ; } __except ( 1 ) { wprintf ( L '' \n Error thrown % d '' , e ) ; } return 0 ; }",Custom AppDomainManager fails to start runtimeHost "C_sharp : I 'm looking to have a error raise to prevent a build if there are duplicate keys in my static Dictionary . My current Dictionary below But lets say someone accidentally changes Sobeys to be Nofrills , I would like a compiler error to be raised to prevent anything to be done until that duplicate key is resolved . May I ask is that possible ? If so how abouts would I do that ? public static readonly Dictionary < string , string > Fruits = new Dictionary < string , string > { { `` Sobeys '' , `` Apples '' } , { `` NoFrills '' , `` Oranges '' } } public static readonly Dictionary < string , string > Fruits = new Dictionary < string , string > { { `` NoFrills '' , `` Apples '' } , { `` NoFrills '' , `` Oranges '' } }",Compiler to check if keys in dictionary are Unique "C_sharp : I am trying to create a customization that allows me to specify that the properties of types that are not in a certain namespace should not be populated.Basically , I am trying to change this : to this : How to achieve this ? I actually only care for the result , not for the fictious API shown here , so implementing my own ISpecimenBuilder or ICustomization is not a problem . fixture.Customize < Window > ( c = > c.OmitAutoProperties ( ) ) ; fixture.Customize < ContentControl > ( c = > c.OmitAutoProperties ( ) ) ; fixture.Customize < TextBlock > ( c = > c.OmitAutoProperties ( ) ) ; // Many many more ... fixture.Customize ( t = > ! t.Namespace.StartsWith ( `` MyProject '' ) , c = > c.OmitAutoProperties ( ) ) ;",How to create a customization that omits the auto properties for a whole range of types ? "C_sharp : We believe this example exhibits a bug in the C # compiler ( do make fun of me if we are wrong ) . This bug may be well-known : After all , our example is a simple modification of what is described in this blog post.The idea is simply to create a class Base < T , S > with two virtual methods whose signatures will become identical after an 'evil ' choice of T and S. The class Conflict overloads only one of the virtual methods , and because of the existence of Intermediate < , > , it should be well-defined which one ! But when the program is run , the output seems to show that the wrong overload was overridden.When we read Sam Ng 's follow-up post we get the expression that that bug was not fixed because they believed a type-load exception would always be thrown . But in our example the code compiles and runs with no errors ( just unexpected output ) .Addition in 2020 : This was corrected in later versions of the C # compiler ( Roslyn ? ) . When I asked this question , the output was : As of 2020 , tio.run gives this output : using System ; namespace GenericConflict { class Base < T , S > { public virtual int Foo ( T t ) { return 1 ; } public virtual int Foo ( S s ) { return 2 ; } public int CallFooOfT ( T t ) { return Foo ( t ) ; } public int CallFooOfS ( S s ) { return Foo ( s ) ; } } class Intermediate < T , S > : Base < T , S > { public override int Foo ( T t ) { return 11 ; } } class Conflict : Intermediate < string , string > { public override int Foo ( string t ) { return 101 ; } } static class Program { static void Main ( ) { var conflict = new Conflict ( ) ; Console.WriteLine ( conflict.CallFooOfT ( `` Hello mum '' ) ) ; Console.WriteLine ( conflict.CallFooOfS ( `` Hello mum '' ) ) ; } } } 11101 1012",Wrong overload is overridden when two methods have identical signatures after substitution of type arguments "C_sharp : I might be trying to do something impossible or really hard , but I wanted to try it out anyway . I have been working on writing a program that can automatically downvote Stack Overflow posts for me.So , my logical first step was to find out what went on behind the scenes when I pressed the downvote button . I used a HTTP network analyzer to see how the browser communicates to the server that I want to downvote . This is what it showed me.Then I figured I should be able to remotely downvote it if I write a C # program that sends an HTTP request identical to the one I sent when I pressed the downvote button . So I came up with this : There were some headers that it would not let me write . For the headers Accept , Referer , User-Agent and Connection , it threw an error like this : This header must be modified using the appropriate property or method.and the Host header caused this error : The 'Host ' header can not be modified directly.I just commented out the headers that were causing trouble , optimistically hoping that it would still work anyway , but I got back this message from the server { `` Success '' : false , '' Warning '' : false , '' NewScore '' :0 , '' Message '' : '' '' , '' Refresh '' : false } The `` Success '' : false seemed to indicate that it was not successful in downvoting the post , and I went to the page and it had the same vote count as it did before I ran the program . In other words , my program did n't work.Does anybody know if I 'm on the right path , what I can do to make it work , or if it 's even possible to make it work ? WebRequest req = WebRequest.Create ( `` http : //stackoverflow.com/posts/3905734/vote/3 '' ) ; req.Method = `` POST '' ; req.ContentType = `` application/x-www-form-urlencoded '' ; req.ContentLength = 37 ; req.Headers.Add ( `` Request '' , `` POST /posts/3905734/vote/3 HTTP/1.1 '' ) ; req.Headers.Add ( `` Accept '' , `` application/json , text/javascript , */* ; q=0.01 '' ) ; req.Headers.Add ( `` X-Requested-With '' , `` XMLHttpRequest '' ) ; req.Headers.Add ( `` Referer '' , `` http : //stackoverflow.com/questions/3905734/how-to-send-100-000-emails-weekly '' ) ; req.Headers.Add ( `` Accept-Language '' , `` en-us '' ) ; req.Headers.Add ( `` Accept-Encoding '' , `` gzip , deflate '' ) ; req.Headers.Add ( `` User-Agent '' , `` Mozilla/5.0 ( compatible ; MSIE 9.0 ; Windows NT 6.1 ; WOW64 ; Trident/5.0 ; MAAU ) '' ) ; req.Headers.Add ( `` Host '' , `` stackoverflow.com '' ) ; req.Headers.Add ( `` Connection '' , `` Keep-Alive '' ) ; req.Headers.Add ( `` Cache-Control '' , `` no-cache '' ) ; req.Headers.Add ( `` Cookie '' , `` __utmc=140029553 ; __utma=140029553.1661295586.1330352934.1331336368.1331402208.44 ; __utmz=140029553.1331159433.33.7.utmcsr=meta.stackoverflow.com|utmccn= ( referral ) |utmcmd=referral|utmcct=/users/153008/cody-gray ; __qca=P0-1737884911-1330352934366 ; usr=t=TJUTES9CakOu & s=f3MgHSwW2EWk ; km_ai=91003 ; km_uq= ; km_lv=x ; km_ni=91003 ; __utmb=140029553.17.10.1331402208 '' ) ; var requestMessage = Encoding.UTF8.GetBytes ( `` fkey=abfd538253d7ca1e988f306ea992eda0 '' ) ; var strm = req.GetRequestStream ( ) ; strm.Write ( requestMessage , 0 , requestMessage.Length ) ; strm.Close ( ) ; var rep = req.GetResponse ( ) ; strm = rep.GetResponseStream ( ) ; var rdr = new StreamReader ( strm ) ; string responseFromServer = rdr.ReadToEnd ( ) ; Console.WriteLine ( responseFromServer ) ; rdr.Close ( ) ; strm.Close ( ) ; Console.Read ( ) ;",How can I remotely downvote a Stack Overflow post with C # ? "C_sharp : In ReSharper 8 , when a class was missing interface members ( properties ) , I would Alt+Enter and select `` Implement Missing Members '' , which would generate autoproperties like this : However , in ReSharper 9 , the following is generated : I have set R # to create automatic properties under `` Member Generation '' , still no effect.Is this a bug , or am I missing something ? public class MyClass : IHasId { public int Id { get ; set ; } } public class MyClass : IHasId { public int Id { get { throw new System.NotImplementedException ( ) ; } set { throw new System.NotImplementedException ( ) ; } } }","In ReSharper 9 , how to generate autoproperties from missing members ?" "C_sharp : I have a simple smtpClient : I can have a different host : smtp.gmail.com , smtp.yandex.ru etc.When smtp.Send ( message ) ; executed I have different exception ( depends on the host ) due to the same problem - 2-factor verification is off.For gmail its System.Net.Mail.SmtpException : The SMTP server requires a secure connection or the client was not authenticated . The server response was : 5.5.1 Authentication Required . For yahoo and yandex itsSystem.Net.Mail.SmtpException depth 0 : The operation has timed out . ( 0x80131500 ) I do n't now about others mail providers exception but how to correctly throw exception ( `` you need to enable 2-factor verification '' ) just once ? Is it possible ? Or how to minimize code duplication ? var smtp = new SmtpClient { Host = host , ... } ; smtp.Send ( message ) ;",How to correctly handle System.Net.Mail.SmtpException ? "C_sharp : I found this code on the MSDN site here http : //msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open.aspx : My Question is ... the site also notes that .Open ( ) can throw InvalidOperationExceptions and SqlExceptions , but this example does n't look like it handles them.Is this just because they were being brief with the code , or is there a reason they 're not worth handling here ? are they possibly handld by the using construct in some way ? private static void OpenSqlConnection ( string connectionString ) { using ( SqlConnection connection = new SqlConnection ( connectionString ) ) { connection.Open ( ) ; Console.WriteLine ( `` ServerVersion : { 0 } '' , connection.ServerVersion ) ; Console.WriteLine ( `` State : { 0 } '' , connection.State ) ; } }",SqlConnection in C # - Safe programming practice "C_sharp : In ASP.NET MVC , is it possible to define routes that can determine which controller to use based on the data type of part of the URL ? For example : Essentially , I want the following URLs to be handled by different controllers even though they have the same number of parts : mydomain/123mydomain/ABCP.S . The above code does n't work but it 's indicative of what I want to acheive . routes.MapRoute ( `` Integer '' , `` { myInteger } '' , new { controller = `` Integer '' , action = `` ProcessInteger '' , myInteger = `` '' } ) ; routes.MapRoute ( `` String '' , `` { myString } '' , new { controller = `` String '' , action = `` ProcessString '' , myString = `` '' } ) ;",ASP.NET MVC URL Routes "C_sharp : A code sample : Can anybody explain , why this method call : targets Bar < T > ( T source ) ( and , hence , does n't compile ) ? Does compiler take into account type parameter constraints at all , when resolving overloads ? UPD.To avoid confusion with arrays . This happens with any implementation of IEnumerable < T > , e.g . : UPD 2 . @ ken2k mentioned covariance.But let 's forget about FooImpl . This : produces the same error.I 'm sure , that implicit conversion between List < IFoo > and IEnumerable < IFoo > exists , since I can easily write something like this : and pass value into it : interface IFoo { } class FooImpl : IFoo { } static void Bar < T > ( IEnumerable < T > value ) where T : IFoo { } static void Bar < T > ( T source ) where T : IFoo { } var value = new FooImpl [ 0 ] ; Bar ( value ) ; var value = new List < FooImpl > ( ) ; var value = new List < IFoo > ( ) ; Bar ( value ) ; static void SomeMethod ( IEnumerable < IFoo > sequence ) { } SomeMethod ( value ) ;",Overload resolution issue for generic method with constraints "C_sharp : I 'm not sure if this is the correct medium for this question , so if it 's not please inform me and I will correct.As an example to illustrate my point , let 's say I have 30 .NET applications that are published to 2-3 different web servers . Now , these applications are Intranet based , so I have a C # library that I reference in each of those applications . This library is comprised of methods that I use in each application to find out employee information if necessary . Now , the library has one connection string , but then I have to also reference that same connection string in all of the 30 applications ... so if the database changes that the library is referencing , then I have to remember all 30 applications and change each of them individually.Is there a way to put the connection string in some sort of file ( text file , or something ) , and have each web.config in each of the 30 applications reference that specific file , so if the connection string needs to be changed , I can just change it in the file and then all 30 applications are still okay , or is there not something like that ? UPDATEOkay , I now know how to reference a text file for connection string purposes.. but , it seems as though I only can do one of two options ... either reference my primary connection string and library connection string individually within the web.config like so : OPTION ONEThis option would require me to change the LibraryCS connection string in each of the 30 applications if it were ever to be changed ( NOT WHAT I WANT ) OPTION TWOThis option forces me to put both connection strings in the MyConfig.config file and not just the LibraryCS file.. so this would result in me having to change the LibraryCS connection string in every MyConfig.config file for each of the 30 applications ( AGAIN , NOT WHAT I WANT ) .WHAT I 'M LOOKING FORI am looking for a mixture of the two options , but it seems this ca n't be done , so I 'm hoping someone on this medium knows a work-aroundI want the MyConfig.config file to only hold the LibraryCS connection string and then have the main PrimaryCS connection string be separate.. so that if the LibraryCS connection string were ever needed to be changed , then I only have to do it in one place . < connectionStrings > < add name= '' PrimaryCS '' // more data / > < add name= '' LibraryCS '' // more data / > < /connectionStrings > < connectionStrings configSource= '' MyConfig.config '' > < /connectionStrings > < connectionStrings configSource= '' MyConfig.config '' > < add name= '' PrimaryCS '' // more data / > < /connectionStrings >",Reference same Connection String in Multiple .NET Applications "C_sharp : The following code works fine until I upgrade to .NET 4 ( x64 ) Did I just uncover a runtime bug , or is there some issue with my usage ? namespace CrashME { class Program { private static volatile bool testCrash = false ; private static void Crash ( ) { try { } finally { HttpRuntime.Cache.Insert ( `` xxx '' , testCrash ) ; } } static void Main ( string [ ] args ) { Crash ( ) ; // Works on .NET 3.5 , crash on .NET 4 } } }",StackOverflowException in .NET 4 "C_sharp : I ’ m developing a WPF application with the help MVVM Light Toolkit 4.1.24 . Here is my ViewModel Locator class.Where IService1 - is a WCF service interface DesignDataService – Implementation of IService1 for design purpose Service1Client – WCF proxy class that implement IService1I have two questions:1 ) While run the App , I got an error like this `` Can not register : Multiple constructors found in Service1Client but none marked with PreferredConstructor. '' . For that I have added `` [ PreferredConstructorAttribute ] '' attribute to the Service1Client default constructor and the application run as expected . I know it 's not a good method for two reasonsit will result a dependency to SimpleIoc Whenever I update service reference I have to manually add thisattribute to the default constructor.So is there any better method ? 2 ) I want to pass the endpoint address to Service1Client manually . How can I do that ? Thanks in advance ... public class ViewModelLocator { /// < summary > /// Initializes a new instance of the ViewModelLocator class . /// < /summary > public ViewModelLocator ( ) { ServiceLocator.SetLocatorProvider ( ( ) = > SimpleIoc.Default ) ; if ( ViewModelBase.IsInDesignModeStatic ) { // Create design time view services and models SimpleIoc.Default.Register < IService1 , DesignDataService > ( ) ; } else { // Create run time view services and models SimpleIoc.Default.Register < IService1 , Service1Client > ( ) ; } SimpleIoc.Default.Register < MainViewModel > ( ) ; } public MainViewModel Main { get { return ServiceLocator.Current.GetInstance < MainViewModel > ( ) ; } } public static void Cleanup ( ) { // TODO Clear the ViewModels ServiceLocator.Current.GetInstance < MainViewModel > ( ) .Cleanup ( ) ; } }",Can not supply endpoint address while registering WCF service client with SimpleIOC in ViewModel Locator "C_sharp : Update : As Marc noted below , my fundamental question is : What happens when Read ( ) gets called more times than there are record sets when using QueryMultiple ( ) ? I 'm working on converting an existing DB call from using SqlDataReader to Dapper.Having problems with it though . I call a sproc , which conditionally can call 1-4 more sprocs . So I an potentially have many results sets.To simplify my explanation , lets assume I only have 1-2 result set ( s ) . If the first sproc is n't called , but the second sproc IS called then my first Read ( ) call eats up the first and only result set . Then I have a bunch of useless TeamItem objects that were supposed to be ProjectItem objects . Then of course it blows up on the second call to Read ( ) because there is n't another result set.Am I missing something about Dapper , or is this an extreme case that Dapper just wo n't be able to support feasibly ? if ( _searchParams.WillSearchTeams ) { var teams = multi.Read < TeamItem > ( ) .ToList ( ) ; } var projects = multi.Read < ProjectItem > ( ) .ToList ( ) ;",Does Dapper support an unknown number of result sets ? "C_sharp : It is possible to test if a method has been called using Moq and dependency injection . However , is it possible to test if one method in a class calls another within the same class ? For example , I want to test that if I log a certain exception , that an information message is logged as well.The method is : This was my attempt at unit testing it . The test fails , is there any way that it can it be done ? Since the Info and Error methods are in the same class ( ClassA ) , I do n't believe I can pass ClassA as a dependency into ClassA . So does it not need tested ? public void Error ( string message , Exception exception , long logId = 0 ) { var int32 = ( int ) logId ; Info ( `` Id was converted to an int so that it would fit in the log : `` + logId , int32 ) ; Error ( message , exception , int32 ) ; } void logging_an_error_with_a_long_id_also_logs_info ( ) { var mock = new Mock < ILogger > ( ) ; var testedClass = new Logger ( ) ; var counter = 0 ; testedClass.Error ( `` test '' + counter++ , new Exception ( `` test '' + counter ) , Int64.MaxValue ) ; mock.Verify ( m = > m.Info ( It.IsAny < string > ( ) , It.IsAny < int > ( ) ) ) ; }",Test if method in ClassA has been called from another method in ClassA "C_sharp : Probably something really easy , but I just ca n't see it ... I am replicating an MS Access query in LINQ . I wrote it in C # first to test it , because I prefer C # , then I translated it to VB.Net syntax.As far as I can tell the two queries should be identical , but whilst the C # query returns the correct results , the VB.NET one returns zero results . Can anybody see where the difference might be ? The C # query : The VB.NET query : In both C # and VB.Net table1 and table2 are the same , so it must be the Join which fails.EDITI just changed the Join in VB.Net to query syntax , like this : Which gives the correct result . But I really do n't get how this is different from the extension method Join syntax ? var table1 = dc.MainTable.Where ( o = > o.Year == 423 ) .ToList ( ) .Select ( o = > new { Key_ID = o.Key_ID.Value , CropID = o.CropID.Value , GroupID = o.GroupID.Value , Surface1 = o.Surface1.Value , Surface2 = o.Surface2.Value } ) ; var table2 = dc.OtherTable.Where ( o = > o.Year == 423 ) .ToList ( ) .Select ( o = > new { Key_ID = o.Key_ID.Value , CropID = int.Parse ( o.SAKU_CD ) , GroupID = int.Parse ( o.SAN_DAN_NO ) , Surface1 = Convert.ToDouble ( o.KEIHAN_MEN.Value ) , Surface2 = Convert.ToDouble ( o.SAKU_MEN.Value ) } ) ; var output = table1.Join ( table2 , t1 = > new { t1.Key_ID , t1.CropID , t1.GroupID , t1.Surface1 , t1.Surface2 } , t2 = > new { t2.Key_ID , t2.CropID , t2.GroupID , t2.Surface1 , t2.Surface2 } , ( t1 , t2 ) = > new OutputDataType ( ) { Key_ID = t1.Key_ID , Year = 423 } ) .ToList ( ) ; Dim table1 = MainTable.Where ( Function ( o ) o.Year.Value = 423 ) .ToList ( ) .Select ( Function ( o ) New With { .Key_ID = o.Key_ID.Value , .CropID = o.CropID.Value , .GroupID = o.GroupID.Value , .Surface1 = o.Surface1.Value , .Surface2 = o.Surface2.Value } ) .ToList ( ) Dim table2 = OtherTable.Where ( Function ( o ) o.Year.Value = 423 ) .ToList ( ) .Select ( Function ( o ) New With { .Key_ID = o.Key_ID.Value , .CropID = Convert.ToInt32 ( o.SAKU_CD ) , .GroupID = Convert.ToInt32 ( o.SAN_DAN_NO ) , .Surface1 = Convert.ToDouble ( o.KEIHAN_MEN.Value ) , .Surface2 = Convert.ToDouble ( o.SAKU_MEN.Value ) } ) .ToList ( ) Dim output = table1.Join ( table2 , Function ( t1 ) New With { t1.Key_ID , t1.CropID , t1.GroupID , t1.Surface1 , t1.Surface2 } , Function ( t2 ) New With { t2.Key_ID , t2.CropID , t2.GroupID , t2.Surface1 , t2.Surface2 } , Function ( t1 , t2 ) New OutputDataType With { .Key_ID = t1.Key_ID , .Year = 423 } ) .ToList ( ) Dim output = From t1 In MainTable Join t2 In OtherTable On t1.Key_ID Equals t2.Key_ID And t1.GroupID Equals t2.GroupID And t1.CropID Equals t2.CropID And t1.Surface1 Equals t2.Surface1 And t1.Surface2 Equals t2.Surface2 Select New OutputDataTypeData With { .Key_ID = t1.Key_ID , .Year = 423 }",Identical ( ? ) C # and VB.NET LINQ queries return different results "C_sharp : I would like to test a method that I am expecting to block in a specific situation.I tried a combination of the TimeoutAttribute and ExpectedExceptionAttribute : Unfortunately this does not work as the ThreadAbortException I was reading about here seems to get caught by NUnit itself.Is there a way to expect timeouts ( with NUnit ) ? [ Test ] [ Timeout ( 50 ) , ExpectedException ( typeof ( ThreadAbortException ) ) ] public void BlockingCallShouldBlock ( ) { this.SomeBlockingCall ( ) ; }",Can NUnit expect a timeout ? "C_sharp : The Mongodump documentation specifies you can dump using a specific queryi.e.I 'm storing _ids fields as BinData , is it possible to query on this ? I 've triedWith no luck . mongodump -- host localhost -- db mydb -- collection testCollection -- query `` { SomeKey : 'some value ' } '' mongodump -- host localhost -- db mydb -- collection testCollection -- query `` { _id : 'BinData ( 3 , ryBRQ+Px0kGRsZofJhHgqg== ) ' } ''",MongoDump query with BinData "C_sharp : In Visual Studio 2015 , when I go to write an interpolated string in a variable by typing an opening curly bracket ' { ' , to achieve the following : a second ending bracket is automatically inserted , colored red or pink , as soAfter inserting a variable inside of the brackets ' { } ' and trying to compile , Visual Studio throws an error : `` CS8086 : A ' } ' character must be escaped ( by doubling ) in an interpolated string. '' . This makes sense , but does n't at all explain why the second ' } ' appeared in the first place ! I did n't want to write a ' } ' literal character ; I just wanted to write a regular interpolated string - one ' } ' for one ' { ' . Every time I go to use interpolated strings I 'm forced to manually remove this anomalous second closing bracket in order to compile successfully.Most curiously , it does n't appear to happen all the time . If you remove the ' { } } ' from your interpolated string and type a single ' { ' again , you will end up with ' { } ' - just as you would have expected in the first place.What 's up with this behavior ? var a = $ '' { } '' ; var a = $ '' { } } ''",Why does Visual Studio create double closing brackets for C # 6 interpolated strings ? "C_sharp : Some background : my C # code calls into some unmanaged code ( C++ ) that does a blocking wait . The blocking wait , however , is alertable ( like Thread.Sleep - I suppose it calls WaitForSingleObjectEx with bAlertable TRUE under the cover ) ; I know for sure it is alertable , as it can be `` waked up '' by QueueUserAPC.If I could simply use managed Threads , I would just call the blocking method , and then use Thread.Interrupt to `` wake '' the thread when I need it to exit ; something like this : ( NOTE : I am not using this code , but it is something that , to the top of my knowledge , could work for this peculiar situation ( alertable wait in unmanaged code out of my control ) . What I 'm looking for is the best equivalent ( or a better alternative ! ) to this in TPL ) .But I have to use the TPL ( Tasks instead of managed Threads ) , and the unmanaged method is out of my control ( I can not modify it to call WaitForMultipleObjectEx and make it return when I signal en Event , for example ) .I am looking for a Thread.Interrupt equivalent for Tasks ( something that will post an APC on the underlying thread ) . AFAIK , CancellationTokens require the code to be `` Task aware '' , and do not use this technique , but I 'm not sure : what happens , I wonder , if a task does a Thread.Sleep ( I know there is a Task.Wait , but it 's just for having an example of a non-task wait which is alertable ) , can it be cancelled ? Is my assumption wrong ( I mean , could I just use a CT and everything will work ? But how ? ) .If there is no such method ... I 'm open to suggestions . I 'd really like to avoid to mix Threads and Tasks , or use P/Invoke , but if there is no other way , I would still like to do it in the `` cleanest '' way possible ( which means : no rude aborts , and something `` Tasky '' : ) ) Edit : For those who are curious , I have `` confirmed '' that Thread.Interrupt could work in my case because it calls QueueUserAPC.It calls InterruptInternal , then Thread : :UserInterrupt , then Alert , which queues the APC . It is actually quite clever , as it allows you to sleep/wait and then wake a thread without the need to use another synchronization primitive.I just need to find a TPL primitive that follows the same flow void ThreadFunc ( ) { try { Message message ; comObject.GetMessage ( out message ) ; // ... . } catch ( ThreadInterruptedException ) { // We need to exit return ; } } var t - new Thread ( ThreadFunc ) ; // ... .t.Interrupt ( ) ;",Thread.Interrupt equivalent for Task TPL C_sharp : Will the above also load all the references/dependencies `` MyAssembly '' needs ? Assembly assembly = Assembly.Load ( `` MyAssembly '' ) ;,Does Assembly.Load also load its references ? "C_sharp : I have a powershell script which has a string [ ] parameter and try to pass value to this from batch filePowerShell ScriptBatch File ( 3 Quotes - For escaping/showing 1 quote ) But no matter what I do Write-Host $ ScriptArgs.Count prints 1I want the variable to receive 2 elements [ 0 ] will be -versn= '' 1.0.0.0 '' [ 1 ] will be -pattern= '' FooBar . * '' In batch file , I even tried setting variables individuallybut the console somehow runs as if the variable is not created and run it asand throws error Missing an argument for parameter 'ScriptArgs ' . Specify a parameter of type System.String [ ] and try againWhat should I change to achieve this ? [ string [ ] ] $ ScriptArgs powershell -File Foobar.ps1 -ScriptArgs -versn= '' '' '' 1.0.0.0 '' '' '' , pattern= '' '' '' FooBar . * '' '' '' set @ sArgs = -versn= '' '' '' 1.0.0.0 '' '' '' set @ sArgs = % sArgs % ; -pattern= '' '' '' FooBar . * '' '' '' powershell -File Foobar.ps1 -ScriptArgs % sArgs % powershell -File Foobar.ps1 -ScriptArgs",Passing string [ ] from batch file ( which contains double quotes `` ) to powershell script "C_sharp : Is one considered better standard ? Is one quicker than the other ? Or , is just mainly preference ? GetOrdinal is nice because you can call the column name out itself and not have to worry about counting the index of the fields in SQL , but I would like to know if there are benefits using one over the other . Reading by Index : Reader.GetOrdinal : while ( reader.Read ( ) ) { Column1 = reader.GetValue ( 0 ) .ToString ( ) .Trim ( ) ; Column2 = reader.GetValue ( 1 ) .ToString ( ) .Trim ( ) ; } while ( reader.Read ( ) ) { data.Column1 = reader.GetValue ( reader.GetOrdinal ( `` COLUMN1 '' ) ) .ToString ( ) ; data.Column2 = reader.GetValue ( reader.GetOrdinal ( `` COLUMN2 '' ) ) .ToString ( ) ; data.Column3 = reader.GetDateTime ( reader.GetOrdinal ( `` COLUMN3 '' ) ) ; }",C # - SQLDataReader by Index vs. SQLDataReader.GetOrdinal ( ColumnName ) "C_sharp : I am adding date and image to the database . I want to add the date as the footer to the uploaded image.HTML for image uploadHTML for datepickerScript for Upload < div class= '' form-group '' > @ Html.Label ( `` Photo '' , htmlAttributes : new { @ class = `` control-label '' } ) < div class= '' col-md-10 '' > < img id= '' DocImg '' src= '' ~/Upload/DoctorImage/doc-default.png '' style= '' cursor : pointer ; '' accesskeyclass= '' edtImg '' width= '' 100 '' height= '' 100 '' / > < input type= '' file '' id= '' fileUpload '' name= '' Photo '' accept= '' image/* '' / > < /div > < /div > < div class= '' col-6 '' > @ Html.ValidationSummary ( true , `` '' , new { @ class = `` text-danger '' } ) < div class= '' form-group '' > @ Html.Label ( `` Joining Date '' , htmlAttributes : new { @ class = `` control-label col-md-2 '' , @ required = `` required '' } ) < div class= '' col-md-10 '' > @ ( Html.Kendo ( ) .DatePicker ( ) .Name ( `` JoiningDate '' ) .Value ( `` '' ) .HtmlAttributes ( new { style = `` width : 100 % '' , required = `` true '' } ) ) @ Html.ValidationMessageFor ( model = > model.JoiningDate , `` '' , new { @ class = `` text-danger '' } ) < /div > < /div > < /div > $ ( document ) .ready ( function ( ) { $ ( `` # fileUpload '' ) .hide ( ) ; } ) ; $ ( `` # DocImg '' ) .click ( function ( ) { $ ( `` # fileUpload '' ) .trigger ( 'click ' ) ; } ) ;",Add date on image while uploading in c # "C_sharp : I have the following enumeration type : used in the following class : I want to persist instances of this type in a database using NHibernate . And to avoid writing boilerplate code , I 'm trying to use auto mapping feature as follows : where MyAutoMappingConfiguration looks like this : When I use the schema generated from this configuration to create the database : the following script is being generated and executed : Why is the property EnumProperty ignored ? When I add an explicit mapping for X , or ( what seems equivalent ) an override for auto-mapping like this : the script is generated correctly : This shows that there seems to be nothing wrong with NHibernate 's ability to map the presented enum correctly . Why ca n't auto-mapping cope with this ? When I add the following method to MyAutoMappingConfiguration : and place the breakpoint , the result is true for the EnumProperty member , which somehow gets ignored later . public enum EnumType { E1 , E2 } public class X { public virtual int ? Id { get ; set ; } public virtual EnumType EnumProperty { get ; set ; } public virtual string S { get ; set ; } } private ISessionFactory CreateSessionFactory ( ) { var mappings = AutoMap .AssemblyOf < Domain.X > ( new MyAutoMappingConfiguration ( ) ) ; this.NHibernateConfiguration = Fluently .Configure ( ) .Database ( FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2012.ConnectionString ( b = > b.FromConnectionStringWithKey ( `` x '' ) ) ) .Mappings ( m = > m.AutoMappings.Add ( mappings ) ) .BuildConfiguration ( ) ; return this.NHibernateConfiguration.BuildSessionFactory ( ) ; } public class MyAutoMappingConfiguration : FluentNHibernate.Automapping.DefaultAutomappingConfiguration { public override bool ShouldMap ( Type type ) { return type.Namespace == `` Domain '' ; } public override bool IsComponent ( Type type ) { return type.Name == `` EnumType '' ; } } new SchemaExport ( this.sessionProvider.NHibernateConfiguration ) .Execute ( true , true , false ) ; if exists ( select * from dbo.sysobjects where id = object_id ( N ' [ X ] ' ) and OBJECTPROPERTY ( id , N'IsUserTable ' ) = 1 ) drop table [ X ] create table [ X ] ( Id INT not null , S NVARCHAR ( 255 ) null , primary key ( Id ) ) var mappings = AutoMap .AssemblyOf < Domain.X > ( new MyAutoMappingConfiguration ( ) ) .Override < Domain.X > ( m = > { m.Table ( `` X '' ) ; m.Id ( x = > x.Id ) ; m.Map ( x = > x.EnumProperty ) ; // this works m.Map ( x = > x.S ) ; } ) ; if exists ( select * from dbo.sysobjects where id = object_id ( N ' [ X ] ' ) and OBJECTPROPERTY ( id , N'IsUserTable ' ) = 1 ) drop table [ X ] create table [ X ] ( Id INT not null , EnumProperty NVARCHAR ( 255 ) null , S NVARCHAR ( 255 ) null , primary key ( Id ) ) public override bool ShouldMap ( Member member ) { var result = base.ShouldMap ( member ) ; return result ; }",Why does AutoMapping from Fluent 's NHibernate ignore an enum type ? "C_sharp : I 'm having trouble with VS2012 designer . I have a user control that I designed and in it is a text box ( among other things ) where the user is meant to enter an IPv4 , IPv6 , or DNS . I needed to validate that text as valid ( TextChanged event ) report back to the main program . Consider the following code : Then I add the event handler to the main program designer ( control name is `` Com '' ) : The problem I have is that although the code works exactly as I wanted it to , the designer thinks there is no ErrorChanged event . The exact message it reports is `` The type 'ModbusCom.Communications ' has no event named 'ErrorChanged ' . `` I can ignore the error and the designer displays the form ok . I can run the program and everything is fine , but it 's a bit annoying to have to keep telling it to ignore the problem . Is there anything I can do to resolve this ? Help is appreciated ! private bool addressError ; public EventHandler ErrorChanged ; public bool Error { get { return addressError ; } set { if ( this.Error ! = value ) { addressError = value ; OnErrorChanged ( this , EventArgs.Empty ) ; } } } protected virtual void OnErrorChanged ( object sender , EventArgs e ) { if ( ErrorChanged ! = null ) { ErrorChanged ( sender , e ) ; } } this.Com.ErrorChanged += new System.EventHandler ( this.Com_ErrorChanged ) ;",C # Designed does n't recognize custom event in custom user control "C_sharp : I 'm using the ScinctillaNET editor , and , the problem I have is that it does not show the `` [ + ] '' and the `` [ - ] folding symbols for methods , at least for the Vb.Net lexer as shown in this image : ( notice the missing symbol in line number 6 and 32 ) I 'm not sure I ' f its a design issue in the wrapper by the author , or its my fault , this is the style that I 'm building , written in Vb.Net : Public Shared Sub SetVbNetStyle ( ByVal editor As Scintilla ) Dim keywords As String = `` # const # debug # else # elseif # end # if # release `` & _ `` addhandler addressof aggregate alias and andalso ansi as assembly auto `` & _ `` binary boolean byref byte byval `` & _ `` call case catch cbool cbyte cchar cdate cdbl cdec char cint class clng cobj compare const continue csbyte cshort csng cstr ctype cuint culng cushort custom `` & _ `` date decimal declare default delegate dim directcast distinct do double `` & _ `` each else elseif end endif enum equals erase error event exit explicit `` & _ `` false finally for friend from function `` & _ `` get gettype getxmlnamespace global gosub goto group `` & _ `` handles `` & _ `` if implements imports in inherits int16 int32 int64 integer interface into is isfalse isnot istrue `` & _ `` join `` & _ `` key `` & _ `` let lib like long loop `` & _ `` me mid mod module mustinherit mustoverride mybase myclass `` & _ `` namespace narrowing new next not nothing notinheritable notoverridable `` & _ `` object of off on operator option optional or order orelse overloads overridable overrides `` & _ `` paramarray partial preserve private property protected public `` & _ `` raiseevent readonly redim rem removehandler resume return `` & _ `` sbyte select set shadows shared short single skip static step stop strict string structure sub synclock `` & _ `` take text then throw to true try trycast typeof `` & _ `` uint16 uint32 uint64 uinteger ulong unicode until ushort using `` & _ `` variant `` & _ `` wend when where while widening with withevents writeonly `` & _ `` xor '' ' Reset the styles . editor.StyleResetDefault ( ) editor.StyleClearAll ( ) ' editor.Styles ( Style . [ Default ] ) .Font = `` Consolas '' ' editor.Styles ( Style . [ Default ] ) .Size = 10 ' Set the Vb.Net lexer . editor.Lexer = Lexer.Vb ' Set folding properties . editor.SetProperty ( `` tab.timmy.whinge.level '' , `` 1 '' ) editor.SetProperty ( `` fold '' , `` 1 '' ) ' Set the margin for fold markers . With editor .Margins ( 2 ) .Type = MarginType.Symbol .Margins ( 2 ) .Mask = Marker.MaskFolders .Margins ( 2 ) .Sensitive = True .Margins ( 2 ) .Width = 20 End With ' Reset folder markers . For i As Integer = Marker.FolderEnd To Marker.FolderOpen editor.Markers ( i ) .SetForeColor ( SystemColors.ControlLightLight ) editor.Markers ( i ) .SetBackColor ( SystemColors.ControlDark ) Next ' Set the style of the folder markers . With editor .Markers ( Marker.Folder ) .Symbol = MarkerSymbol.BoxPlus .Markers ( Marker.Folder ) .SetBackColor ( SystemColors.ControlText ) .Markers ( Marker.FolderOpen ) .Symbol = MarkerSymbol.BoxMinus .Markers ( Marker.FolderEnd ) .Symbol = MarkerSymbol.BoxPlusConnected .Markers ( Marker.FolderEnd ) .SetBackColor ( SystemColors.ControlText ) .Markers ( Marker.FolderMidTail ) .Symbol = MarkerSymbol.TCorner .Markers ( Marker.FolderOpenMid ) .Symbol = MarkerSymbol.BoxMinusConnected .Markers ( Marker.FolderSub ) .Symbol = MarkerSymbol.VLine .Markers ( Marker.FolderTail ) .Symbol = MarkerSymbol.LCorner End With ' Enable automatic folding editor.AutomaticFold = ( AutomaticFold.Show Or AutomaticFold.Click Or AutomaticFold.Change ) ' Disable whitespaces visibility . editor.ViewWhitespace = WhitespaceMode.Invisible ' Set the style of the Vb.Net language . With editor .Styles ( Style.Default ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Comment ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Comment ) .ForeColor = Color.FromArgb ( 255 , 87 , 159 , 56 ) .Styles ( Style.Vb.Comment ) .Italic = False .Styles ( Style.Vb.CommentBlock ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.CommentBlock ) .ForeColor = Color.FromArgb ( 127 , 127 , 127 ) .Styles ( Style.Vb.CommentBlock ) .Italic = True .Styles ( Style.Vb.Default ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Default ) .ForeColor = Color.FromArgb ( 128 , 128 , 128 ) .Styles ( Style.Vb.HexNumber ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.HexNumber ) .Bold = True .Styles ( Style.Vb.HexNumber ) .ForeColor = Color.FromArgb ( 255 , 181 , 206 , 168 ) .Styles ( Style.Vb.Identifier ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Identifier ) .ForeColor = Color.Gainsboro .Styles ( Style.Vb.Keyword ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Keyword ) .Bold = False .Styles ( Style.Vb.Keyword ) .ForeColor = Color.FromArgb ( 255 , 54 , 139 , 214 ) .Styles ( Style.Vb.Keyword2 ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Keyword2 ) .Bold = False .Styles ( Style.Vb.Keyword2 ) .ForeColor = Color.FromArgb ( 255 , 54 , 139 , 214 ) .Styles ( Style.Vb.Keyword3 ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Keyword3 ) .Bold = False .Styles ( Style.Vb.Keyword3 ) .ForeColor = Color.FromArgb ( 255 , 54 , 139 , 214 ) .Styles ( Style.Vb.Keyword4 ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Keyword4 ) .Bold = False .Styles ( Style.Vb.Keyword4 ) .ForeColor = Color.FromArgb ( 255 , 54 , 139 , 214 ) .Styles ( Style.Vb.Number ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Number ) .Bold = True .Styles ( Style.Vb.Number ) .ForeColor = Color.FromArgb ( 255 , 181 , 206 , 168 ) .Styles ( Style.Vb.Operator ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Operator ) .Bold = True .Styles ( Style.Vb.Operator ) .ForeColor = Color.Silver .Styles ( Style.Vb.Preprocessor ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.Preprocessor ) .ForeColor = Color.MediumOrchid .Styles ( Style.Vb.String ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.String ) .ForeColor = Color.FromArgb ( 255 , 214 , 157 , 133 ) .Styles ( Style.Vb.StringEol ) .BackColor = Color.FromArgb ( 255 , 30 , 30 , 30 ) .Styles ( Style.Vb.StringEol ) .FillLine = True .Styles ( Style.Vb.StringEol ) .ForeColor = Color.Gainsboro End With ' Set the Vb.Net keywords . editor.SetKeywords ( 1 , keywords ) End Sub",ScintillaNET not showing folding for method blocks "C_sharp : Given the following classes : The output isThis makes sense , according to the spec : A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.But I 'm curious why the static constructor is not invoked when the type is referenced as a generic type parameter . public class Foo { static Foo ( ) { Console.WriteLine ( `` Foo is being constructed '' ) ; } } public class Bar { public void ReferenceFooAsGenericTypeParameter < T > ( ) { Console.WriteLine ( `` Foo is being referenced as a generic type parameter '' ) ; } } public class SampleClass { public static void Main ( ) { new Bar ( ) .ReferenceFooAsGenericTypeParameter < Foo > ( ) ; } } Foo is being referenced as a generic type parameter",Why is n't a static constructor invoked on a class used as a generic type parameter ? "C_sharp : I have create testing application that has 3 classesCarRadioSportCar : Car ( has a Radio ) As the serialize process when I create instance of XmlSerializer object I use 2 object to testingandThe result of this 2 approach is identical , so I want to know what is the difference between these 2 constructor or critical point that need to use # 2 constructor ? XmlSerializer xmlSerializer = new XmlSerializer ( typeof ( SportCar ) ) ; XmlSerializer xmlSerializer = new XmlSerializer ( typeof ( SportCar ) , new Type [ ] { typeof ( Car ) , typeof ( Radio ) } ) ;",XmlSerializer.Serialize ambiguous "C_sharp : How would you solve the concurrency issue with the following code ? In this example , we 'd like to know why the user failed authentication . The problem is that this code makes two separate calls to the database , but we 'd like the whole method to happen inside of a conceptual transaction . Specifically we 're interested in isolation . We do n't want concurrent writes during the execution of this method to affect our reads before we 've determined the reason for the authentication failure . A few solutions come to mind : Thread Locking , TransactionScope and Optimistic Locking . I really like the idea of Optimistic Locking , since I think conflicts are likely to be rare , but there 's nothing built into .NET to do this , right ? Also - is this something to REALLY be concerned about in this case ? When are concurrency issues like this important to consider and when are n't they ? What needs to be considered in implementing a solution ? Performance ? The duration of the lock ? How likely conflicts are to occur ? Edit : After reviewing Aristos ' answer , I think what I 'm really after is some sort of `` snapshot '' isolation level for the Authenticate method . public MembershipStatus Authenticate ( string username , string password ) { MembershipUser user = Membership.GetUser ( username ) ; if ( user == null ) { // user did not exist as of Membership.GetUser return MembershipStatus.InvalidUsername ; } if ( user.IsLockedOut ) { // user was locked out as of Membership.GetUser return MembershipStatus.AccountLockedOut ; } if ( Membership.ValidateUser ( username , password ) ) { // user was valid as of Membership.ValidateUser return MembershipStatus.Valid ; } // user was not valid as of Membership.ValidateUser BUT we do n't really // know why because we do n't have ISOLATION . The user 's status may have changed // between the call to Membership.GetUser and Membership.ValidateUser . return MembershipStatus.InvalidPassword ; }","Concurrency issues with multiple , independent database transactions ?" "C_sharp : In an ASP.NET application in which users ( `` User A '' ) can set up their own web service connections using SOAP , I let them insert their own envelope , which , for example , could be something along these lines : At the same time I a `` User B '' that sends an array of data , passed down from Javascript as json that looks a little something like this : This array enters the fray as a string before being deserialized ( dynamic JsonObject = JsonConvert.DeserializeObject ( stringifiedJson ) ; ) .Now , I would like to be able to insert the corresponding values into the envelope , preferably with a degree of security that wo n't allow people to do funky stuff by inserting weird values in the array ( a regex would probably be my last resort ) .So far I 'm aware of the concept to build the string like so ( With the { } 's in the soap message being replaced by { 0 } , { 1 } & { 2 } ) : But the amount of values in this array as well as the might change according to the user 's input as well as a shifting order of references , so I need something more flexible . I 'm very new to making SOAP calls , so as dumb an answer as possible would be appreciated . //Formatted for Claritystring soapMessage = `` < soap : Envelope //StandardStuff > < soap : Header //StandardStuff > < wsse : UsernameToken > < wsse : Username > { F1 } < /wsse : Username > < wsse : Password Type '' > { F2 } < /wsse : Password > < /wsse : UsernameToken > < /soap : Header > < soap : Body > < ref : GetStuff > < ref : IsActive > { F3 } < /ref : IsActive > < /ref : GetStuff > < /soap : Body > < /soap : Envelope > '' [ { key : `` F1 '' , value : `` A '' } , { key : `` F2 '' , value : `` B '' } , { key : `` F3 '' , value : `` C '' } ] ; string value1 = `` A '' ; string value2 = `` B '' ; string value3 = `` C '' ; var body = string.Format ( @ soapMessage , value1 , value2 , value3 ) ; request.ContentType = `` application/soap+xml ; charset=utf-8 '' ; request.ContentLength = body.Length ; request.Accept = `` text/xml '' ; request.GetRequestStream ( ) .Write ( Encoding.UTF8.GetBytes ( body ) , 0 , body.Length ) ;",Inserting Values from an Array into a SOAP Message based on Key "C_sharp : In WindowsForms I just added event handlers as follows : And the output is : You can see that all events occurs in the same location , So my question is why is there a MouseMove event after MouseUp event ? Also I tried similar code in WPF and MouseMove event NOT occurred.And I tried similar code in C++ and MouseMove event NOT occurred : private void Form1_MouseDown ( object sender , MouseEventArgs e ) { Debug.WriteLine ( $ '' = > Form1_MouseDown , Clicks : { e.Clicks } , Location : { e.Location } '' ) ; } private void Form1_MouseUp ( object sender , MouseEventArgs e ) { Debug.WriteLine ( $ '' = > Form1_MouseUp , Clicks : { e.Clicks } , Location : { e.Location } '' ) ; } private void Form1_MouseMove ( object sender , MouseEventArgs e ) { Debug.WriteLine ( $ '' = > Form1_MouseMove , Clicks : { e.Clicks } , Location : { e.Location } '' ) ; } = > Form1_MouseMove , Clicks : 0 , Location : { X=17 , Y=21 } = > Form1_MouseDown , Clicks : 1 , Location : { X=17 , Y=21 } = > Form1_MouseUp , Clicks : 1 , Location : { X=17 , Y=21 } = > Form1_MouseMove , Clicks : 0 , Location : { X=17 , Y=21 } LRESULT CALLBACK WndProc ( HWND hWnd , UINT message , WPARAM wParam , LPARAM lParam ) { switch ( message ) { ... case WM_MOUSEMOVE : OutputDebugString ( L '' WM_MOUSEMOVE\n '' ) ; break ; case WM_LBUTTONDOWN : OutputDebugString ( L '' WM_LBUTTONDOWN\n '' ) ; break ; case WM_LBUTTONUP : OutputDebugString ( L '' WM_LBUTTONUP\n '' ) ; break ; default : return DefWindowProc ( hWnd , message , wParam , lParam ) ; } return 0 ; }",Why MouseMove event occurs after MouseUp event ? "C_sharp : What is the equivalent of PHP 's preg_quote ? This is as far as I have gotten for creating a method that extracts text from a string : public static string f_get_string_between ( string text , string start , string end ) { //both these attempts below throw an unrecognized escape sequence error //start = `` \Q '' +start+ '' \E '' ; //end = `` \Q '' +end+ '' \E '' ; Regex regex = new Regex ( start + `` ( .* ? ) '' + end ) ; var v = regex.Match ( text ) ; text = v.Groups [ 1 ] .ToString ( ) ; return text ; }",What is the equivalent of PHP 's preg_quote ? "C_sharp : This is likely a simple syntax question , but I ca n't figure it out.Normally , I would do this : But instead of a list , I want to use an array - like this : The IEnumerator IEnumerable.GetEnumerator ( ) seems to compile fine - but the public IEnumerator < PriceLevel > says that I need some kind of cast - what is the best way of doing this ? William public class OrderBook : IEnumerable < PriceLevel > { private readonly List < PriceLevel > PriceLevels = new List < PriceLevel > ( ) ; public IEnumerator < PriceLevel > GetEnumerator ( ) { return PriceLevels.GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return PriceLevels.GetEnumerator ( ) ; } } public class ArrayOrderBook : IEnumerable < PriceLevel > { private PriceLevel [ ] PriceLevels = new PriceLevel [ 500 ] ; public IEnumerator < PriceLevel > GetEnumerator ( ) { return PriceLevels.GetEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return PriceLevels.GetEnumerator ( ) ; } }",Implementing IEnumerable with an Array "C_sharp : I have a table column defined like this : And in my EntityFramework class the respective field is defined like this : When checking the value to get an entry it works perfectly fine : But when I check the order entity after this statement it is always zero : What went wrong here with my definitions ? How do I fix this ? ENTRY_STATUS NUMBER ( 2 , 0 ) [ Column ( `` ENTRY_STATUS '' ) ] public int Status { get ; set ; } var order = testDbContext.Orders.FirstOrDefault ( o = > o.Status > 1 ) ; if ( order ! = null ) { if ( order.Status == 3 ) //Always Zero ! ! ! { //Do something ... } }","Oracle DB to EF not working correctly for NUMBER ( 2,0 )" "C_sharp : I have to create a real time report . For that , I have to write conditions for each and every hour of a given day . In the code below , the condition checks for the current day of week and then check for the current time and based on that a report has to be generated.The code above is only for Monday and I have to do the same thing for the other six days of week too . When I add the queries inside each conditions , it would be like hundreds of lines.Is there a better way to get this done without having to write hundreds of lines of code ? protected void sample ( ) { TimeSpan zerothHour = new TimeSpan ( 00 , 0 , 0 ) ; TimeSpan firstHour = new TimeSpan ( 01 , 0 , 0 ) ; TimeSpan secondHour = new TimeSpan ( 02 , 0 , 0 ) ; TimeSpan thirdHour = new TimeSpan ( 03 , 0 , 0 ) ; TimeSpan fourthHour = new TimeSpan ( 04 , 0 , 0 ) ; TimeSpan fifthHour = new TimeSpan ( 05 , 0 , 0 ) ; TimeSpan sixthHour = new TimeSpan ( 06 , 0 , 0 ) ; // and so on until the twentyfourth hour if ( DateTime.Today.DayOfWeek == DayOfWeek.Monday ) { if ( DateTime.Now.TimeOfDay > = sixthHour & & DateTime.Now.TimeOfDay < = seventhHour ) { //MySql query here string MyConString = ConfigurationManager.ConnectionStrings [ `` connStr '' ] .ConnectionString ; MySqlConnection connection = new MySqlConnection ( MyConString ) ; string agentlogin = `` SELECT agentlogin FROM agentdetails WHERE location = 'PNQ10-Pune ' AND shift IN ( ' 6:00-15-00 ' , '22:00-7:00 ' ) AND Mon = ' W ' '' ; MySqlCommand cmd = new MySqlCommand ( agentlogin , connection ) ; connection.Open ( ) ; MySqlDataReader rdr = cmd.ExecuteReader ( ) ; while ( rdr.Read ( ) ) { //lblagentlogin.Text += rdr [ `` agentlogin '' ] + Environment.NewLine ; sqlList.Add ( Convert.ToString ( rdr [ `` agentlogin '' ] ) ) ; } } else if ( DateTime.Now.TimeOfDay > = seventhHour & & DateTime.Now.TimeOfDay < = eigthHour ) { } else if ( DateTime.Now.TimeOfDay > = eigthHour & & DateTime.Now.TimeOfDay < = ninthHour ) { } else if ( DateTime.Now.TimeOfDay > = ninthHour & & DateTime.Now.TimeOfDay < = tenthHour ) { } else if ( DateTime.Now.TimeOfDay > = tenthHour & & DateTime.Now.TimeOfDay < = eleventhHour ) { } // and so on for the entire cycle of time } }",Simplify if else condition using timespan in C # "C_sharp : I have a simple clean room example of this possible bug.If compiled in x64 or AnyCPU ( when prefer 32bit is set to false in VS2012 ) the if you put a breakpoint in the if block , it is always hit.We tried it in VS2012 , VS2010 and VS2008 and they all fired the if block when compiled in 64bit , yet in 32bit it does not fire the if block.We looked at the IL for 32 bit and 64 bit versions and they look the same.We found this in production code because the if block was being ran and the exception was being thrown no matter what the value of the boolean variable , though in the simple example we can not seem to throw the exception , it is happening in production code.Since it is happening in production code , it is not just a debugger issue.Very strange behavior , but seems to not be acutally running any code in the if block . Developer jumped the gun in assuming that was the exception he was seeing . ( All debugging is in debug mode - production is in release ) If the throw is commented out - the if block is not reached . static void Main ( string [ ] args ) { bool MyFalse = false ; if ( MyFalse ) { throw new Exception ( ) ; } try { int i = 0 ; } catch ( Exception e ) { Console.Write ( e ) ; } Console.Read ( ) ; }","I think my team found a bug in 64bit compiler , can others either confirm or tell my why this is correct ?" "C_sharp : I 've read various questions similar to mine but none of them seem address my issue.I 've a type like this : When T is a scalar as MyObject < int > equality works correctly , but when I defined somethinglike MyObject < IEnumerable < int > > equality fails.The reason is that when T is IEnumerable < T > I should call this.Value.SequenceEqual ( other.Value ) .Handling this difference bloats Equals ( MyObject < T > ) with too LOC of type check and reflection ( for me , leading to a violation of SOLID/SRP ) .I was not able to found this specific case in MSDN guidelines , so if anyone already faced this problem ; it would be great if this knowledge can be shared.Edit : AlternativeTo K.I.S.S. , I 'm wondering to doing something similar : In this way the implementation of Equal will be a lot simple . And when I need just one value I 've a collection of 1 item.Obviously T will not be an enumerable ( but the data structure is private so there 's no problem ) . class MyObject < T > : IEquatable < MyObject < T > > { // no generic constraints private readonly string otherProp ; private readonly T value ; public MyObject ( string otherProp , T value ) { this.otherProp = otherProp ; this.value = value ; } public string OtherProp { get { return this.otherProp ; } } public T Value { get { return this.value ; } } // ... public bool Equals ( MyObject < T > other ) { if ( other == null ) { return false ; } return this.OtherProp.Equals ( other.OtherProp ) & & this.Value.Equals ( other.Value ) ; } } class MyObject < T > : IEquatable < MyObject < T > > { private readonly IEnumerable < T > value ; // remainder omitted }",Implement IEquatable < T > when T could be IEnumerable < T > "C_sharp : I have the following function in C # , a hashing function which I need converted into PHP . I 've tried a few things in PHP but I do n't get the same results ( I 'm not at all good with .NET ) One ( wrong ) attempt in PHP is this : The ANSWERA slight variation of what was suggested below by DampeS8N worked for me . Please also not the fourth parameter of hash_hmac - now set to true for raw output as binary data private static string GetSignature ( string args , string privatekey ) { var encoding = new System.Text.ASCIIEncoding ( ) ; byte [ ] key = encoding.GetBytes ( privatekey ) ; var myhmacsha256 = new HMACSHA256 ( key ) ; byte [ ] hashValue = myhmacsha256.ComputeHash ( encoding.GetBytes ( args ) ) ; string hmac64 = Convert.ToBase64String ( hashValue ) ; myhmacsha256.Clear ( ) ; return hmac64 ; } function encode ( $ data , $ key ) { return base64_encode ( hash_hmac ( 'sha256 ' , $ data , $ key ) ) ; } function encode ( $ data , $ key ) { iconv_set_encoding ( `` input_encoding '' , `` ASCII '' ) ; iconv_set_encoding ( `` internal_encoding '' , `` ASCII '' ) ; iconv_set_encoding ( `` output_encoding '' , `` ASCII '' ) ; return base64_encode ( hash_hmac ( 'sha256 ' , $ data , $ key , true ) ) ; }",Convert C # hashing function into PHP C_sharp : I notice that the following will compile and execute even though the local variables are not initialized . Is this a feature of Span ? void Uninitialized ( ) { Span < char > s1 ; var l1 = s1.Length ; Span < char > s2 ; UninitializedOut ( out s2 ) ; var l2 = s2.Length ; } void UninitializedOut ( out Span < char > s ) { },Span < T > does not require local variable assignment . Is that a feature ? "C_sharp : I 'm using .NET Core 2.1 and language standard 7.3 . I wish to reference a fixed buffer without obtaining a pointer to it . Is it currently possible ? I know Span is currently able to track a managed array through garbage collections , so I do n't see anything preventing it from tracking fixed buffers in a similar fashion.If its not possible , what would happen if I did use a fixed statement like such : Would the garbage collector become a problem if the struct is wrapped inside an object or class on the heap ? public unsafe struct InteropStruct { private fixed byte dataField [ 32 ] ; public Span < byte > Data { get { //return a span referencing the private field without a fixed statement } } } public unsafe struct InteropStruct { private fixed byte dataField [ 32 ] ; public Span < byte > Data { get { fixed ( byte* ptr = dataField ) { return new Span < byte > ( ptr , 32 ) ; } } } }",Is a Span < T > pointing to Fixed Sized Buffers without a fixed expression possible ? "C_sharp : I am trying to use NGit to connect to Github ( ie using a private key as well as a password ) .Can someone walk me through it ? My normal fetch would be : how would I do this with a private key ? var git = Git.CloneRepository ( ) .SetDirectory ( _properties.OutputPath ) .SetURI ( _properties.SourceUrlPath ) .SetBranchesToClone ( new Collection < string > ( ) { `` master '' } ) .SetCredentialsProvider ( new UsernamePasswordCredentialsProvider ( `` username '' , '' password '' ) ) .SetTimeout ( 3600 ) .Call ( ) ;",NGit making a connection with a private key file "C_sharp : I am experimenting with compiler performance . I have a very small piece of code , just a few floating point multiplications and additions . The code gets executed in a loop several million times . I am trying to compile the code in C++ , c # , java , perl , python ... and then I run the result while measuring execution time.I am quite dissatisfied with c # performance . My c # code is about 60 % slower than equivalent C++ or java . I am sure , there must be a bug in my experiment . I would like to disassemble the resulting binary to learn why.Is there such a option with MSIL code ? Can the result of the c # JIT compiler be examined on the machine instruction level ( x86 instructions , not MSIL instructions ) ? Update the code ( u , v , g* are double ; steps is integer ) stopwatch.Start ( ) ; for ( int i = 0 ; i < steps ; i++ ) { double uu = g11 * u + g12 * v ; v = g21 * u + g22 * v ; u = uu ; } stopwatch.Stop ( ) ;",disassemble c # code to machine instructions C_sharp : I have a very strange situation I do n't understand . Below is the case simplified : I do n't understand why one expression will net me true and another false . They seem identical . double ? d = 2 ; int ? i = 2 ; Console.WriteLine ( d.Equals ( ( 2 ) ) ) ; // falseConsole.WriteLine ( i.Equals ( ( 2 ) ) ) ; // true,What is the difference between double ? and int ? for .Equals comparisons ? "C_sharp : I am working on optimizing a physics simulation program using Red Gate 's Performance Profiler . One part of the code dealing with collision detection had around 52 of the following little checks , dealing with cells in 26 directions in 3 dimensions , under two cases.As an extremely tight loop of the program , all of this had to be in the same method , but I found that , suddenly , after I had extended the area from two dimensions to three dimensions ( rising the count to 52 checks from 16 ) , suddenly cell.Count was no longer being inlined , even though it is a simple getter.public int Count { get { return count ; } } This caused a humongous performance hit , and it took me a considerable time to find that , when cell.Count appeared in the method 28 times or less , it was inlined every time , but once cell.Count appeared in the method 29 times or more , it was not inlined a single time ( even though the vast majority of calls were from worst-case scenario parts of the code that were rarely executed . ) So back to my question , does anybody have any idea to get around this limit ? I think the easy solution is just to make the count field internal and not private , but I would like a better solution than this , or at least just a better understanding of the situation . I wish this sort of thing would have been mentioned on Microsoft 's Writing High-Performance Managed Applications page at http : //msdn.microsoft.com/en-us/library/ms973858.aspx but sadly it is not ( possibly because of how arbitrary the 28 count limit is ? ) I am using .NET 4.0.EDIT : It looks like I misinterpreted my little testing . I found that the failure to inline was caused not by the methods themselves being called some 28+ times , but because the the method they ought to be inlined into is `` too long '' by some standard . This still confuses me , because I do n't see how a simple getter could be rationally not inlined ( and performance is significantly better with them inlined as my profiler clearly shows me ) , but apparently the CLI JIT compiler is refusing to inline anything just because the method is already large ( playing around with slight variations showed me that this limit is a code size ( from idasm ) of 1500 , above which no inlining is done , even in the case of my getters , which some testing showed add no additional code overhead to be inlined ) .Thank you . CollisionPrimitiveList cell = innerGrid [ cellIndex + 1 ] ; if ( cell.Count > 0 ) contactsMade += collideWithCell ( obj , cell , data , ref attemptedContacts ) ; cell = innerGrid [ cellIndex + grid.XExtent ] ; if ( cell.Count > 0 ) contactsMade += collideWithCell ( obj , cell , data , ref attemptedContacts ) ; cell = innerGrid [ cellIndex + grid.XzLayerSize ] ; if ( cell.Count > 0 ) contactsMade += collideWithCell ( obj , cell , data , ref attemptedContacts ) ;",Is there a workaround to the C # 28-time inline limit ? "C_sharp : I was thinking of implementing an enum that defines the state of a game object , and I wanted to know if I could directly use flags within the enum 's definition , instead of defining the object 's state as a collection of flags with no easy , pre-defined , global name for the states used in the state machine.For example , let 's say there are 5 states : PreActivation ( Created but not started ; i.e . an enemy in a future wave ) , Active ( Currently in use ; i.e . an enemy on the screen , attacking you ) , Paused ( No longer active , but may reactivate ; i.e . an enemy if the player uses a time-freezing power ) , DeActivated ( An object whose finished use but is still in the game world ; i.e . an enemy whose body is left after death like in Doom 1 & 2 ) , and ToRemove ( An object slated for removal from the game ; i.e . an enemy after you clear a level and move to the next one ) .What I want to do is define the enum so the states hold all applicable flags ; for instance , a DeActivated enemy : 1 . Has been previously activated , and 2 . Is n't currently active . My current thinking is doing something like this : As far as I know , this should work correctly , but I have a few main concerns : Are there any problems likely to come from this ? Is this bad practice ? Is this bad practice ? And , if it is ; A . What 's wrong with it ? B . What should I do instead ? I 'd just make the object 's state a collection of these flags , but I 'd like a shorthand enum for specific states , as this allows for complexity for specific instances and simplicity when it 's needed . Is there a more acceptable way to achieve this ? Sorry if this is a repeat or I broke some other rule , but I just created an account today ; this is my 1st post . Plus , I 'm not sure what you would call this when searching , and I did n't get any similar hits from here or Google . public enum ObjectState { // The first section are the flags BeenActivated = 0b0000001 , // Previously activated CurrentlyActive = 0b0000010 , // Currently activated IsSuspended = 0b0000100 , // It may be reactivated ShouldRemove = 0b0001000 , // It should be removed // These are the states PreActivation = 0b0000100 , // Mot currently active , nor has it ever been active , but it will get activated Active = 0b0000011 , // Currently active , and it 's been active Paused = 0b0000101 , // Not currently active , but it 's been active before DeActivated = 0b0000001 , // Not currently active , but it 's been active before , and it should n't get reactivated , but do n't remove yet ToRemove = 0b0001001 // Not currently active , but it 's been active before , and it should n't get reactivated , it should be removed }",Explicitly defining flag combinations in an enum "C_sharp : At the moment I have a grid and I 'm trying to have a cell with validation rules . To validate it , I require the row 's min and max value . Validation Class : User Control : FeeType Class : I 've tried this solution here WPF ValidationRule with dependency property and it works great . But now I come across the issue that the proxy ca n't be instantiated through the viewmodel . It 's based on the row 's selected ComboBox Value 's Min and Max property . For example , that combo box sample values are belowSince a grid can have virtually as many rows as it wants , I ca n't see how creating proxies would work in my situation . If I can get some tips of guidance , would be greatly appreciated . public decimal Max { get ; set ; } public decimal Min { get ; set ; } public override ValidationResult Validate ( object value , System.Globalization.CultureInfo cultureInfo ) { var test = i < Min ; var test2 = i > Max ; if ( test || test2 ) return new ValidationResult ( false , String.Format ( `` Fee out of range Min : $ { 0 } Max : $ { 1 } '' , Min , Max ) ) ; else return new ValidationResult ( true , null ) ; } < telerik : RadGridView SelectedItem = '' { Binding SelectedScript } '' ItemsSource= '' { Binding ScheduleScripts } '' > < telerik : RadGridView.Columns > < telerik : GridViewDataColumn DataMemberBinding= '' { Binding Amount } '' Header= '' Amount '' CellTemplate= '' { StaticResource AmountDataTemplate } '' CellEditTemplate= '' { StaticResource AmountDataTemplate } '' / > < telerik : GridViewComboBoxColumn Header= '' Fee Type '' Style= '' { StaticResource FeeTypeScriptStyle } '' CellTemplate= '' { StaticResource FeeTypeTemplate } '' / > < /telerik : RadGridView.Columns > < /telerik : RadGridView > public class FeeType { public decimal Min { get ; set ; } public decimal Max { get ; set ; } public string Name { get ; set ; } } Admin Min : $ 75 Max $ 500Late Min : $ 0 Max $ 50",WPF Grid With Validation Rule And Dependency Property "C_sharp : I wonder why this code does n't end up in endless recursion . I guess it 's connected to the automatic initialization of static members to default values , but can someone tell me `` step by step '' how does ' a ' get the value of 2 and ' b ' of 1 ? public class A { public static int a = B.b + 1 ; } public class B { public static int b = A.a + 1 ; } static void Main ( string [ ] args ) { Console.WriteLine ( `` A.a= { 0 } , B.b= { 1 } '' , A.a , B.b ) ; //A.a=2 , B.b=1 Console.Read ( ) ; }",C # two classes with static members referring to each other "C_sharp : I am using Microsoft.Web.Administration.dll to check states of my sites by using following code . It works fine with IIS but when it 's used in IIS Expresss , then 'State ' property throws 'NotImplementedException ' . Has anyone faced this issue ? ServerManager manager = new ServerManager ( ) foreach ( Site site in manager.Sites ) { If ( site.State == ObjectState.Started ) { ... .. } }",State property of Site throwing `` NotImplementedException '' in IIS Express "C_sharp : For memory performance reasons I have an array of structures since the number of items is large and the items get tossed regularly and hence thrashing the GC heap . This is not a question of whether I should use large structures ; I have already determined GC trashing is causing performance problems . My question is when I need to process this array of structures , should I avoid using LINQ ? Since the structure is not small it is not wise to pass it around by value , and I have no idea if the LINQ code generator is smart enough to do this or not . The structure looks like this : So let 's say we have an array of these values and I want to extract a dictionary of custom slugs to manufacturers ID 's . Before I changed this to a structure it was a class , so the original code was written with a simple LINQ query : My concern is I want to understand how LINQ is going to generate the actual code to build this dictionary . My suspicion is that internally the LINQ code is going to end up something like this naive implementation : which would be bad , because the third line is going to create a local copy of the structure , which will be slow because the structure is large and will instead thrash the memory bus . We also do not need anything but the ID and custom slug from it so it will copy a lot of useless information on every iteration . Rather if I coded it efficiently myself , I would write it like this : So does anyone know if the code generator is smart enough to use simple array indexing like the second example when generator code to run over arrays of structures , or will it implement the more naive but slower first implementation ? What is the best way to decompile this kind of code to find out what the code generator would actually do for this ? UPDATEThese changes are now in production . As it turns out in the process of re-writing the code and using the Dot Memory profiler to identify how much memory was being used and where , I found two memory leaks in the Phalanger PHP compiler code . That was one of the reasons the amount of memory our processes were using kept growing , and one of the memory leaks was really nasty and actually caused by the Microsoft Async code ( probably worth a blog or a stack overflow question/answer to help others avoid it ) .Anyway , once I found the memory leaks and fixed them I pushed that code live without any of the memory optimizations to convert from classes to structures , and oddly enough this actually caused the GC to thrash even more . I was seeing periods of time when the GC would be using up to 27 % of the CPU according to the performance counters . Most likely these big blocks were previously not getting GC'ed due to the memory leaks , so they simply hung around . Once the code was fixed the GC started behaving even worse than before.Finally we finished up the code to convert these classes to structures using the feedback in this question , and now our total memory usage at peak is about 50 % of what it was , it rapidly drops down when the load on the server goes away and more importantly we are seeing only 0.05 % of the CPU being used for GC , if even that . So if anyone is wondering whether these changes can have an impact on the real world , they really can , especially if you have objects that normally hang around for a while so get stuck in the 2nd gen heap and then need to get tossed and garbage collected . public struct ManufacturerValue { public int ManufacturerID ; public string Name ; public string CustomSlug ; public string Title ; public string Description ; public string Image ; public string SearchFilters ; public int TopZoneProduction ; public int TopZoneTesting ; public int ActiveProducts ; } ManufacturerValue [ ] = GetManufacturerValues ( ) ; var dict = values.Where ( p = > ! string.IsNullOrEmpty ( p.CustomSlug ) ) .ToDictionary ( p = > p.CustomSlug , p = > p.ManufacturerID ) ; var dict = new Dictionary < string , int > ( ) ; for ( var i = 0 ; i < values.Length ; i++ ) { var value = values [ i ] ; if ( ! string.IsNullOrEmpty ( value.CustomSlug ) ) { dict.Add ( value.CustomSlug , value.ManufacturerID ) ; } } var dict = new Dictionary < string , int > ( ) ; for ( var i = 0 ; i < values.Length ; i++ ) { if ( ! string.IsNullOrEmpty ( values [ i ] .CustomSlug ) ) { dict.Add ( values [ i ] .CustomSlug , values [ i ] .ManufacturerID ) ; } }",Is Where on an Array ( of a struct type ) optimized to avoid needless copying of struct values ? "C_sharp : I am getting a warning on the line noted in the comment in the code below . I am using Visual Studio 2015 . I have 2 tables in a database , and querying them using Linq-2-Sql . The Linq Code performs a left join between the two tables on the companyID . When run , the left join runs as expected , and I get all the values in TestTable1 , but only records in TestTable2 where the companyIds match.If the warning below were correct and the expression were always false , then the string `` NULL '' would never be assigned to value1 . This is not the case , as when I run this I get `` NULL '' exactly when would be expected when doing a Left Join . I use this pattern in many places in my code , and these warnings are everywhere , yet my code works fine with the NULL check I 'm doing . The warning seems wrong to me . Am I missing something here ? t2.CompanyId is a database field of type INT . and also an int datatype in the linq-2-sql class , but somehow is still assigned null within the query.Here is the warningBelow is the generated SQL var db = new SandBoxDataContext ( ) ; var result = ( from t1 in db.TestTable1s from t2 in db.TestTable2s .Where ( x = > x.CompanyId == t1.CompanyId ) .DefaultIfEmpty ( ) select new { //t2.CompanyId == null in line below is underlined with the warning ! value1 = t2.CompanyId == null ? `` NULL '' : `` INT '' } ) .ToList ( ) ; foreach ( var rec in result ) { Response.Write ( `` value1 = `` + rec.value1 + `` < br > '' ) ; } CS0472 The result of the expression is always 'false ' since a value of type 'int ' is never equal to 'null ' of type 'int ? ' SELECT ( CASE WHEN ( [ t1 ] . [ CompanyId ] ) IS NULL THEN 'NULL ' ELSE CONVERT ( NVarChar ( 4 ) , 'INT ' ) END ) AS [ value1 ] FROM [ dbo ] . [ TestTable1 ] AS [ t0 ] LEFT OUTER JOIN [ dbo ] . [ TestTable2 ] AS [ t1 ] ON [ t1 ] . [ CompanyId ] = [ t0 ] . [ CompanyId ]","Warning says Linq-To-Sql Expression is always false , but this is incorrect , why ?" "C_sharp : FormatterServices.GetSerializableMembers returns protected and internal fields twice for derived types . Once as an instance of SerializationFieldInfo and once as RtFieldInfo.I find this very confusing ! Can anyone help me understand why Microsoft decided to implement it this way ? I have written a sample program that re-produce my problem : I would expect that privateField and protectedField are reported once each . However this is the actual output when running the program : As you can see protectedField appear twice , with different names but with the same metadata token so it is indeed the very same field.Can anyone explain why ? class Program { [ Serializable ] public class BaseA { private int privateField ; } [ Serializable ] public class DerivedA : BaseA { } [ Serializable ] public class BaseB { protected int protectedField ; } [ Serializable ] public class DerivedB : BaseB { } static void Main ( string [ ] args ) { Program.PrintMemberInfo ( typeof ( DerivedA ) ) ; Program.PrintMemberInfo ( typeof ( DerivedB ) ) ; Console.ReadKey ( ) ; } static void PrintMemberInfo ( Type t ) { Console.WriteLine ( t.Name ) ; foreach ( var mbr in FormatterServices.GetSerializableMembers ( t ) ) { Console.WriteLine ( `` { 0 } ( { 1 } ) '' , mbr.Name , mbr.MetadataToken ) ; } Console.WriteLine ( ) ; } } DerivedA BaseA+privateField ( 67108865 ) DerivedB protectedField ( 67108866 ) BaseB+protectedField ( 67108866 )",GetSerializableMembers ( FormatterServices ) returns the same field twice ! Why ? "C_sharp : I 'm trying to use ISpannable in a Monodroid project but am having problems with GetSpans . What I 'm ultimately after is a Rich Text editor such as at : https : //code.google.com/p/android-richtexteditor/source/browse/ ? r=4 # svn/trunk/src/net/sgoliverHowever , the Xamarin documentation for GetSpans is n't particularly helpful . The line I 'm trying to convert from Java to C # is : However , I do n't know what to pass for the last parameter as writing StyleSpan.class in C # gives a compile error of `` } expected '' . What can I pass in to the last parameter to get all spans , or all spans of a particular type ? StyleSpan [ ] ss = s.getSpans ( styleStart , position , StyleSpan.class ) ;",MonoDroid GetSpans last parameter "C_sharp : The following combination of object and collection initializers does not give compilation error , but it is fundamentally wrong ( https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers # examples ) , because the Add method will be used in the initialization : So you 'll get NullReferenceException . What is the reason for making such an unsafe decision while developing the syntax of the language ? Why not to use initialization of a new collection for example ? public class Foo { public List < string > Bar { get ; set ; } } static void Main ( ) { var foo = new Foo { Bar = { `` one '' , `` two '' } } ; }",Why does a combination of object and collection initializers use Add method ? "C_sharp : A legacy app is in an endless loop at startup ; I do n't know why/how yet ( code obfuscation contest candidate ) , but regarding the method that 's being called over and over ( which is called from several other methods ) , I thought , `` I wonder if one of the methods that calls this is also calling another method that also calls it ? `` I thought : `` Nah , the compiler would be able to figure that out , and not allow it , or at least emit a warning ! `` So I created a simple app to prove that would be the case : ... but no ! It compiles just fine . Why would n't the compiler flag this code as questionable at best ? If either button is mashed , you are in never-never land ! Okay , sometimes you may want an endless loop ( pacemaker code , etc . ) , but still I think a warning should be emitted . public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } private void button1_Click ( object sender , EventArgs e ) { method1 ( ) ; } private void button2_Click ( object sender , EventArgs e ) { method2 ( ) ; } private void method1 ( ) { MessageBox.Show ( `` method1 called , which will now call method2 '' ) ; method2 ( ) ; } private void method2 ( ) { MessageBox.Show ( `` method2 called , which will now call method1 '' ) ; // Note to self : Write an article entitled , `` Copy-and-Paste Considered Harmful '' method1 ( ) ; } }",Why does the C # compiler not even warn about endless recursion ? "C_sharp : I want to generate Types via reflection at runtime that reference each other.With static code I would do thisI can sucessfully generate my Order and my OrderDetails Type with the value type properties.The code looks like thisNow I am stuck at this line : I am required to pass the type of the property to the DefineProperty method but the type does not exist at this point.Now I could just create a type builder for customer at this point and use tb.CreateType ( ) to get the type but that would not help since Customer needs a reference to Order , too . public class Order { public int Id { get ; set ; } public Customer Customer { get ; set ; } } public class Customer { public int Id { get ; set ; } public Order Order { get ; set ; } } var aName = new System.Reflection.AssemblyName ( `` DynamicAssembly '' ) ; var ab = AppDomain.CurrentDomain.DefineDynamicAssembly ( aName , System.Reflection.Emit.AssemblyBuilderAccess.Run ) ; var mb = ab.DefineDynamicModule ( aName.Name ) ; var tb = mb.DefineType ( `` Order '' , System.Reflection.TypeAttributes.Public , typeof ( Object ) ) ; var pbId = tb.DefineProperty ( `` Id '' , PropertyAttributes.None , typeof ( int ) , null ) ; var pbCustomer = tb.DefineProperty ( `` Customer '' , PropertyAttributes.None , ? ? ? , null ) ;",Use Reflection.Emit to generate Types that reference each other "C_sharp : msdn says that the sizeof operator can be used only in unsafe code blocks . Although you can use the Marshal.SizeOf method , the value returned by this method is not always the same as the value returned by sizeof.and Marshal.SizeOf returns the size after the type has been marshaled , whereas sizeof returns the size as it has been allocated by the common language runtime , including any ** padding **.once ive read in the book : c # via clr ( page 522 ) that : questions : 1 ) does the padding mentioned in here : is the same as mentioned in the book ? AND2 ) if i have object type of Person - how can i know its TRUE SIZE in MEMORY ? edit - why do i need that ? please notice this : they have a sample of reading records : if the size being reported by MARSHAL.sizeOF is not the size as sizeOF so - which should i choose ? it has to be accurate ! ! according to this sample , they dont consider the padding , and they should ... ( or not ... ) using ( var accessor = mmf.CreateViewAccessor ( offset , length ) ) { int colorSize = Marshal.SizeOf ( typeof ( MyColor ) ) ; // < -- -- -- -- HERE MyColor color ; for ( long i = 0 ; i < length ; i += colorSize ) { accessor.Read ( i , out color ) ; color.Brighten ( 10 ) ; accessor.Write ( i , ref color ) ; } } }",.net object size padding ? C_sharp : I 'm facing this exception when I 'm using String.Split with random strings . List < string > linhas = new List < string > ( ) ; linhas.Add ( `` 123 ; abc '' ) ; linhas.Add ( `` 456 ; def '' ) ; linhas.Add ( `` 789 ; ghi '' ) ; linhas.Add ( `` chocolate '' ) ; var novas = linhas.Where ( l = > l.ToString ( ) .Split ( ' ; ' ) [ 1 ] == '' def '' ) ;,How to prevent a System.IndexOutOfRangeException in a LINQ WHERE ? "C_sharp : lets say , i have the following code in c # does this internally does a boxing of x ? Is there a way to see this happening from visual studio ? int x = 0 ; x.ToString ( ) ;",does valueType.ToString ( ) does a cast on the valueType ? "C_sharp : C # 7 allows us to declare functions that return named tuples , so a declaration like the one illustrated below is now ok.I have need to process the response from an HTTP Client request and extract two values from it , and I want to do so asynchronously . The following is allowedMy simple question is , is it possible to name the output strings in the same way that I could were the function to operate synchronously along the lines as illustrated below ? ( int quotient , int remainder ) = GetDivisionResults ( 17 , 5 ) ; public static async Task < < Tuple < string , string > > GetRequiredReturnValuesFromResponse ( string response ) public static async Task < Tuple < string OrderNumber , string OriginalId > > GetRequiredReturnValuesFromResponse ( string response )",Can I declare named async tuple functions in C # ? "C_sharp : I often want to do this : Because if I change the name of Foo the IDE will refactor my error message too , what wo n't happen if I put the name of the method ( or any other kind of member identifier ) inside a string literal . The only way I know of implementing `` name '' is by using reflection , but I think the performance loss outweighs the mantainability gain and it wo n't cover all kinds of identifiers.The value of the expression between parenthesis could be computed at compile time ( like typeof ) and optimized to become one string literal by changing the language specification . Do you think this is a worthy feature ? PS : The first example made it look like the question is related only to exceptions , but it is not . Think of every situation you may want to reference a type member identifier . You 'll have to do it through a string literal , right ? Another example : UPDATE : this question was posted before C # 6 , but may still be relevant for those who are using previous versions of the language . If you are using C # 6 check out the nameof operator , which does pretty much the same thing as the name operator in the examples above . public void Foo ( Bar arg ) { throw new ArgumentException ( `` Argument is incompatible with `` + name ( Foo ) ) ; } [ RuntimeAcessibleDocumentation ( Description= '' The class `` + name ( Baz ) + `` does its job . See method `` + name ( DoItsJob ) + `` for more info . `` ) ] public class Baz { [ RuntimeAcessibleDocumentation ( Description= '' This method will just pretend `` + `` doing its job if the argument `` + name ( DoItsJob.Arguments.justPretend ) + `` is true . '' ) ] public void DoItsJob ( bool justPretend ) { if ( justPretend ) Logger.log ( name ( justPretend ) + `` was true . Nothing done . `` ) ; } }",How to refer to an identifier without writing it into a string literal in C # ? "C_sharp : I just saw a weird result while I tried to concatenate two null strings : it returns an empty one ! I can not imagine if it have some utility or why this occurs.Example : Can someone tell me why it returns a String.Empty instead of null ? string sns = null ; sns = sns + sns ; // It results in a String.Emptystring snss = null ; snss = String.Concat ( snss , snss ) ; // It results in a String.Empty too !",Why concatenating two null string results an empty string ? "C_sharp : Inspired by this question I began wondering why the following examples are all illegal in c # : and I 'm just wondering if anyone knew the exact reason why the language was designed this way ? Is it to discourage bad programming practice , and if so why not just issue a warning ? , for performance reasons ( compiling and when running ) or what is the reason ? VoidFunction t = delegate { int i = 0 ; } ; int i = 1 ; { int i = 0 ; } int i = 1 ;",Why is the scope of if and delegates this way in c # "C_sharp : C # 7.2 introduces the in modifier for parameters which makes perfect sense for structs and in particular for readonly structs.It is also allowed to use it for a reference typeAs reference types are passed by reference by default , is the in in the example above just a redundant modifier ? value = null is forbidden when you use in , does it mean that it spares also the copy of the reference address by just passing the original reference to the heap location and blocking changes ? void Method ( in StringBuilder value ) { }",What is the point of the in modifier for classes "C_sharp : This has me extremely baffled . Why am I getting duplicate replace strings in the following code : This outputs to the console : I understand that regex gets weird matching end line characters but there should be none . I also understand that the pattern can match nothing , but clearly the input is not nothing . This happens in .Net 3.5 and 4.0 and I get the same thing with SingleLine and MultiLine.I know there are several alternatives that will do what I 'm expecting but I 'm wondering more about what other match . * thinks its finding . static void Main ( string [ ] args ) { String input = `` test '' ; String pattern = `` . * '' ; String replacement = `` replace '' ; Console.WriteLine ( Regex.Replace ( input , pattern , replacement ) ) ; Console.Read ( ) ; } replacereplace",.NET Regex Replace Single Line Matching Unknown Character "C_sharp : Consider the following C # code : result1 should always equal result2 right ? The thing is , it does n't . result1 is 3.3 and result2 is 3.3000000000000003 . The only difference is the order of the constants.I know that doubles are implemented in such a way that rounding issues can occur . I 'm aware that I can use decimals instead if I need absolute precision . Or that I can use Math.Round ( ) in my if statement . I 'm just a nerd who wants to understand what the C # compiler is doing . Can anyone tell me ? Edit : Thanks to everyone who 's so far suggested reading up on floating point arithmetic and/or talked about the inherent inaccuracy of how the CPU handles doubles . But I feel the main thrust of my question is still unanswered . Which is my fault for not phrasing it correctly . Let me put it like this : Breaking down the above code , I would expect the following operations to be happening : Let 's assume that each of the above additions had a rounding error ( numbered e1..e4 ) . So r1 contains rounding error e1 , r2 includes rounding errors e1 + e2 , r3 contains e3 and r4 contains e3 + e4.Now , I do n't know how exactly how the rounding errors happen but I would have expected e1+e2 to equal e3+e4 . Clearly it does n't , but that seems somehow wrong to me . Another thing is that when I run the above code , I do n't get any rounding errors . That 's what makes me think it 's the C # compiler that 's doing something weird rather than the CPU.I know I 'm asking a lot and maybe the best answer anyone can give is to go and do a PHD in CPU design , but I just thought I 'd ask.Edit 2Looking at the IL from my original code sample , it 's clear that it 's the compiler not the CPU that 's doing this : The compiler is adding up the numbers for me ! double result1 = 1.0 + 1.1 + 1.2 ; double result2 = 1.2 + 1.0 + 1.1 ; if ( result1 == result2 ) { ... } double r1 = 1.1 + 1.2 ; double r2 = 1.0 + r1double r3 = 1.0 + 1.1double r4 = 1.2 + r3 .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint .maxstack 1 .locals init ( [ 0 ] float64 result1 , [ 1 ] float64 result2 ) L_0000 : nop L_0001 : ldc.r8 3.3 L_000a : stloc.0 L_000b : ldc.r8 3.3000000000000003 L_0014 : stloc.1 L_0015 : ret }",Why does the order affect the rounding when adding multiple doubles in C # C_sharp : Assuming class A { } class B : A { } covariance is not supported for generic class.Meaning - we cant do something like this : Thats fine and understood.From my reading - i understand that Covariance will be available : `` If you use a backing Generic Interface Being implemented on a Generic Class - so that access to the T type object instance will be available through those interfaces `` .I have just one problem.Ive seen many examples of the `` converter '' class as a form of Stack .But never understood `` what if I want to use only 1 instance of B from a reference of A ? `` so Ive tried some code : Create B object + values -- - > use Generic Converter for B -- - > use the covariance flow to get its A reference -- - > now you can use it either as A or as B.My question : Is That the correct way of doing this ( for using covariance for 1 object only ) ? p.s.The code is working and compiled ok. http : //i.stack.imgur.com/PJ6QO.pngIve been asking /reading a lot about this topic lately - I dive into things in order to understand them the best I can . MyConverter < B > x1= new MyConverter < B > ( ) ; MyConverter < A > x2= x1 ;,C # covariance structure understanding ? "C_sharp : I 'm using the new nullable reference types from C # 8 and I was wondering if it is possible to indicate that a parameter passed in is not null if the method returns at all.I 've found [ NotNullIf ] and [ DoesNotReturnIf ] but these appear to trigger off a method 's return value and a specific bool parameter respectively.Here is what I currently have : This seems good , but then when I call it - I still see warnings . ( I also tried RaiseIfNull ( [ NotNullIfNotNull ( `` thing '' ) ] object ? thing ) and that did n't work . ) Am I missing something obvious ? public static bool RaiseIfNull ( [ NotNullWhen ( true ) ] object ? thing ) = > RaiseIf ( ( ) = > thing is null ) ; public static bool RaiseIf ( Func < bool > predicate ) { if ( predicate ( ) ) throw new HttpException ( 400 ) ; return true ; } [ HttpPost ( `` { id } '' ) ] public async Task Etc ( string id , [ FromBody ] Dto data ) { HttpException.RaiseIfNull ( data ? .property ) ; await DoEtc ( id , data.property ) ) ; // warning here }",Specify NotNull If Method Returns At All "C_sharp : I want to add a common callback function to all the methods of an object . I found this SO question but in that aproach , I would have to modify every function of the class . I would like to define some beforeFilter method that get trigered before every method call . I know I could use Action delegates for that but I do n't know how . UPDATE : As an example , what I want would be something like thisAs you can see , the ideal would be to add a simple ( or more than one ) method to get trigered before all the rest of the methods . Maybe with some base class or an interface , I do n't know ( that 's why I ask for ) .Some other option that I think it might be posible is to clone the object and define a new class instead to add code to the existing one . So in that Class use the Object to get access to the methods trhough the TypeI 'm just guessing , maybe some of my option are even unviable , so please help my on this Closest approachWhat I have for now , is this method ( This means a lot of overloads for the RunWithCallback to manage Sub 's and Functions with Actions and Funcs delegates , with different number of parameters ) To use this , I would have to run this Sub instead of calling any of the Object methods ( passing ByRef parameter to catch returning value in functions ) . Something like thisI think there should be a better solution to this , something that allow to avoid calling the same sub , and avoid the overloads , some kind of dynamic extension method for the object Class Class MyClass Sub MyCallback 'callback code ... End Sub 'Rest of tyhe codeEnd Class Class NewClass Sub AddCallback ( Obj As Object , Callback As Action ) 'Add the callback here End SubEnd Class Sub RunWithCallback ( beforFilter As Action , f As Action ) beforeFilter ( ) f ( ) End Sub Public Sub DoNothing ( ) Debug.WriteLine ( `` Callback working ! `` ) End SubPublic Sub BeforeFilter ( ) Debug.WriteLine ( `` Testing callback ... '' ) End Sub'To run the above function RunWithCallback ( AddressOf BeforeFilter , AddressOf DoNothing )",How to add a callback to a webform Project "C_sharp : I am using the latest C # -driver for MongoDB . I added the following code to my program to serialize in camelcase : However , I get issues when trying to query documents after using the serialization . For example : returns the following : i.e , all properties seem to be null except for the id . The object is serialized correctly , the field names are in camel case ( `` name '' and `` time '' ) and each document contains the correct data ( `` name '' : Test 1 '' and `` time '' : 2014 ) .It seems like the problem is that the query function does n't realize that the fields are in camelcase and therefore returns null . Therefore I am unable to deserialize any objects.Is there any way to avoid this error ? var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention ( ) } ; ConventionRegistry.Register ( `` CamelCase '' , camelCaseConvention , type = > true ) ; var query = _collection.AsQueryable < TimeSeries > ( ) ; Console.WriteLine ( query.ToJson ( ) ) ; { `` _id '' : ObjectId ( `` 54af0e848c27be15fc47a0d9 '' ) , `` Name '' : null , `` Time '' : null }",Deserialization errors after adding Camelcase convention pack "C_sharp : Using Visual Studio Async CTP ( Version 3 ) I am struggling to understand how I can `` wrap '' existing code using this framework.For exampleUsing the OpenPop.NET library I am trying to establish a connection with a pop3 server and confirm I have a valid username and password.So lets say I have some code like this.And now I want to make it Async my understanding from what I have been reading and piecing together is that I would end up with a method signature along the lines of I believe this is the correct signature because it will be a task that returns a boolean ( ? ) and my guess is that I will need to utilize the TaskEx.Run ( ) method ? but that 's as far as I can seem to get my head around . Could anyone point in the right direction ? public bool ConnectSync ( ) { bool success = true ; Pop3Client client = new Pop3Client ( ) ; try { client.Connect ( `` mail.server.com '' , 110 , false ) ; client.Authenticate ( `` username '' , `` password '' ) ; } catch { success = false ; } return success ; } public async Task < bool > ConnectAsync ( ) { }",Basics of using the Microsoft Async Framework "C_sharp : I know what you think : It is 2017 , please do n't come up with this again , but I really can not find any valueable explanation for this.Please have a look at the ActiveNotes property in this XAML-Code.I have this TwoWay binding in my XAML , which works perfectly . It is ALWAYS updated , if the PropertyChanged event for ScaleNotes is fired and if the binding is set to TwoWay.The ScaleNotes property in the ViewModel looks like this . Whenever it changes , the PropertyChanged event is guaranteed to be fired . I checked and double checked it . The business logic in the ViewModel works.Up to here everything is ok . Whenever the ScaleNotes property in the VM is changed , the target property ActiveNotes is updated.Now the problem : If I only change the binding in the XAML to OneWay and the business logic in the VM stays 100 % the same , the ActivesNotes property in the target object is updated only once even if the PropertyChanged event is fired . I checked and double checked it . The PropertyChanged event for the ScaleNotes property is always fired.Just to make this complete , here is DP in the target object.I do n't understand this . From my knowledge , OneWay and TwoWay only define in which direction the values are updated and not how often they can be updated.I can not understand , that everything works fine with TwoWay , the business logic stays 100 % the same and OneWay is a deal breaker.If you ask yourself , why I want to know this : This binding was planned as a OneWay binding . It makes no sense to update the source in any way . I only changed it to TwoWay , because OneWay does n't work as expected.SOLUTION with the help of @ MikeStrobel : ( see comments ) The code needs be changed this way : Using a OneWay binding , the assignment in the OnActiveNotesChanged event handler method deletes or clears out the binding . Mike is correct saying , that the assingment is completely unnecessary , because at this point of time the value is already set before in the property . So it makes no sense at all , no matter if I use OneWay or TwoWay binding . < c : Keyboard Grid.Row= '' 2 '' Grid.Column= '' 0 '' PlayCommand= '' { Binding PlayCommand } '' StopCommand= '' { Binding StopCommand } '' ActiveNotes= '' { Binding ScaleNotes , Mode=TwoWay , UpdateSourceTrigger=PropertyChanged } '' / > private ReadOnlyCollection < eNote > _ScaleNotes ; public ReadOnlyCollection < eNote > ScaleNotes { get { return _ScaleNotes ; } set { SetField ( ref _ScaleNotes , value ) ; } } [ DebuggerStepThrough ] protected virtual void OnPropertyChanged ( [ CallerMemberName ] string propertyName = null ) { PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } [ DebuggerStepThrough ] protected bool SetField < T > ( ref T field , T value , [ CallerMemberName ] string propertyName = null ) { if ( EqualityComparer < T > .Default.Equals ( field , value ) ) return false ; field = value ; OnPropertyChanged ( propertyName ) ; return true ; } < c : Keyboard Grid.Row= '' 2 '' Grid.Column= '' 0 '' PlayCommand= '' { Binding PlayCommand } '' StopCommand= '' { Binding StopCommand } '' ActiveNotes= '' { Binding ScaleNotes , Mode=OneWay , UpdateSourceTrigger=PropertyChanged } '' / > public static DependencyProperty ActiveNotesProperty = DependencyProperty.Register ( `` ActiveNotes '' , typeof ( ReadOnlyCollection < eNote > ) , typeof ( Keyboard ) , new PropertyMetadata ( OnActiveNotesChanged ) ) ; public ReadOnlyCollection < eNote > ActiveNotes { get { return ( ReadOnlyCollection < eNote > ) GetValue ( ActiveNotesProperty ) ; } set { SetValue ( ActiveNotesProperty , value ) ; } } private static void OnActiveNotesChanged ( DependencyObject d , DependencyPropertyChangedEventArgs e ) { Keyboard keyboard = ( Keyboard ) d ; keyboard.ActiveNotes = ( ReadOnlyCollection < eNote > ) e.NewValue ; if ( ( keyboard.ActiveNotes ! = null ) & & ( keyboard.ActiveNotes.Count > 0 ) ) { keyboard.AllKeys.ForEach ( k = > { if ( k.Note ! = eNote.Undefined ) k.IsActiveKey = true ; } ) ; keyboard.AllKeys.ForEach ( k = > { if ( ( k.Note ! = eNote.Undefined ) & & ( ! keyboard.ActiveNotes.Contains ( k.Note ) ) ) k.IsActiveKey = false ; } ) ; } else { keyboard.AllKeys.ForEach ( k = > { if ( k.Note ! = eNote.Undefined ) k.IsActiveKey = true ; } ) ; } } private static void OnActiveNotesChanged ( DependencyObject d , DependencyPropertyChangedEventArgs e ) { Keyboard keyboard = ( Keyboard ) d ; //THIS LINE BREAKED THE CODE , WHEN USING OneWay binding BUT NOT WITH TwoWay binding //keyboard.ActiveNotes = ( ReadOnlyCollection < eNote > ) e.NewValue ; if ( ( keyboard.ActiveNotes ! = null ) & & ( keyboard.ActiveNotes.Count > 0 ) ) { keyboard.AllKeys.ForEach ( k = > { if ( k.Note ! = eNote.Undefined ) k.IsActiveKey = true ; } ) ; keyboard.AllKeys.ForEach ( k = > { if ( ( k.Note ! = eNote.Undefined ) & & ( ! keyboard.ActiveNotes.Contains ( k.Note ) ) ) k.IsActiveKey = false ; } ) ; } else { keyboard.AllKeys.ForEach ( k = > { if ( k.Note ! = eNote.Undefined ) k.IsActiveKey = true ; } ) ; } }",WPF : TwoWay binding is ALWAYS updated - OneWay binding is ONLY ONCE updated "C_sharp : Like this : The example is a bit simple ( it 's from the Jira API - RemoteStatus has 4 properties ) , but imagine the base class had 30 properties . I do n't want to manually set all those values , especially if my inherited class only has a couple of extra properties.Reflection seems to hint at an answer.I saw at Using inheritance in constructor ( publix X ( ) : y ) that I can call the base class constructor ( I think ? correct me if I 'm wrong ) , but my base class does n't have a constructor - it 's derived from the jira wsdleditI can imagine 2 valid solutions : the one outlined above , and some sort of keyword like this.baseClass that is of type ( baseclass ) and manipulated as such , acting as a sort of pointer to this . So , this.baseClass.name = `` Johnny '' would be the exact same thing as this.name = `` Johnny '' For all intents and purposes , let 's assume the baseclass has a copy constructor - that is , this is valid code : edit2This question is more of a thought exercise than a practial one - for my purposes , I could 've just as easily done this : ( assuming my `` baseclass '' can make copies ) public class remoteStatusCounts : RemoteStatus { public int statusCount ; public remoteStatusCounts ( RemoteStatus r ) { Type t = r.GetType ( ) ; foreach ( PropertyInfo p in t.GetProperties ( ) ) { this.property ( p ) = p.GetValue ( ) ; //example pseudocode } } } public remoteStatusCounts ( RemoteStatus r ) : base ( r ) { //do stuff } public remoteStatusCounts ( RemoteStatus r ) { RemoteStatus mBase = r ; //do work } public class remoteStatusCounts { public int statusCount ; public RemoteStatus rStatus ; public remoteStatusCounts ( RemoteStatus r ) { rStatus = r ; statusCount = getStatusCount ( ) ; } }",Can reflection be used to instantiate an objects base class properties ? "C_sharp : I 'm reviewing some code with an object initialisation pattern that I do n't recognise - can anyone tell me what this pattern is called ( and where to find documentation on usage ) ? In case it matters , the specific use-case is as follows ; obj.myType = ( myVar = new MyType ( ) ) ; protected MyType myVar ; protected readonly MyComplexType myComplexType ; protected void Page_Init ( object sender , EventArgs e ) ) { ... myComplexType.myType = ( myVar = new MyType ( ) ) ; ... }",What is this object initialiser pattern called ? "C_sharp : While reading C # code I found a rather curious snippet : I 'd rather expect that being done either like this : or like this : I mean as is like a cast , but returns null on failure . In the second snippet it ca n't fail ( since there 's a is check before ) .What 's the point in writing code like in the first snippet instead of like in the second or in the third ? if ( whatever is IDisposable ) { ( whatever as IDisposable ) .Dispose ( ) ; } if ( whatever is IDisposable ) { //check ( ( IDisposable ) whatever ) .Dispose ( ) ; //cast - wo n't fail } IDisposable whateverDisposable = whatever as IDisposable ; if ( whateverDisposable ! = null ) { whateverDisposable.Dispose ( ) ; }",What 's the point in using `` is '' followed by `` as '' instead of `` as '' followed by a null check in C # ? "C_sharp : I have read that when you override Equals on an class/object you need to override GetHashCode.Now given the following : Will not overridding the GetHashCode affect both of the Dictionary 's above ? What I am basically asking is how is GetHashCode generated ? IF I still look for an object in PKDic will I be able to find it just based of the PK . If I wanted to override the GetHashCode how would one go about doing that ? public class Person : IEquatable < Person > { public int PersonId { get ; set ; } public string FirstName { get ; set ; } public string LastName { get ; set ; } public Person ( int personId , string firstName , string lastName ) { PersonId = personId ; FirstName = firstName ; LastName = lastName ; } public bool Equals ( Person obj ) { Person p = obj as Person ; if ( ReferenceEquals ( null , p ) ) return false ; if ( ReferenceEquals ( this , p ) ) return true ; return Equals ( p.FirstName , FirstName ) & & Equals ( p.LastName , LastName ) ; } } public static Dictionary < Person , Person > ObjDic= new Dictionary < Person , Person > ( ) ; public static Dictionary < int , Person > PKDic = new Dictionary < int , Person > ( ) ;",Overridding Equals and GetHash "C_sharp : I have read on MSDN that : The null keyword is a literal that represents a null reference , one that does not refer to any object.But I 've seen the following code running without throwing any exception : So if the variable i is null , why can I execute it 's method ? int ? i = null ; var s = i.ToString ( ) ;",How is it that can I execute method on int ? set to null without NullReferenceException ? "C_sharp : I have been struggling to set up a simple automated test on an angular ( 5 ) app using atata as the framework which simply wraps the selenium web driver to do its tests . For the life of me I ca n't get it to find the elements i need in a log on page . I 've tried finding by xpath , css , id , and name . None of which work . Please could someone help me understand if I 'm doing something wrong ? I have made sure that id 's are in place for the controls i 'm trying to manage and they display when i inspect the element . Is there something that I should be doing so that the webdriver accesses the dom and not the websites html source ( as there is a difference due to it being an spa ) ? I have also tried waiting 10 seconds before continuing to search for the control.Versions of all packages are up to date.AtataSettings.csSignInPage.csSignInTests.csEdit : I managed to get it to find the element if I use the plain selenium setup as follows . Why would this work but Atata 's wrapping does n't ? edit 2 : I found someone that had a similar issue but it was constrained to a file input field . Can someone maybe confirm if there is a lingering bug with regards to the setup I 'm using ? https : //github.com/atata-framework/atata/issues/188edit 3 : Html snippet of the email field input control : using Atata ; [ assembly : Culture ( `` en-us '' ) ] [ assembly : VerifyTitleSettings ( Format = `` Login '' ) ] using Atata ; namespace PortalTests2 { using _ = SignInPage ; [ Url ( `` auth/login '' ) ] [ VerifyTitle ] public class SignInPage : Page < _ > { [ FindById ( `` email '' ) ] public TextInput < _ > Email { get ; set ; } [ FindById ( `` password '' ) ] public TextInput < _ > Password { get ; set ; } [ FindById ( `` login_button '' ) ] public Button < _ > SignIn { get ; set ; } [ FindById ] public Select < _ > selectedClientId { get ; set ; } [ FindById ( `` continue_button '' ) ] public Button < _ > ContinueButton { get ; set ; } } } using Atata ; using NUnit.Framework ; namespace PortalTests2 { [ TestFixture ] public class SignInTests { [ SetUp ] public void SetUp ( ) { AtataContext.Configure ( ) . UseChrome ( ) . WithFixOfCommandExecutionDelay ( ) . WithLocalDriverPath ( ) . UseBaseUrl ( $ '' http : //localhost:4300/ '' ) . UseNUnitTestName ( ) . AddNUnitTestContextLogging ( ) . AddScreenshotFileSaving ( ) . LogNUnitError ( ) . TakeScreenshotOnNUnitError ( ) . Build ( ) ; } [ TearDown ] public void TearDown ( ) { AtataContext.Current ? .CleanUp ( ) ; } [ Test ] public void SignIn ( ) { Go.To < SignInPage > ( ) . Email.Set ( `` root '' ) . Password.Set ( `` r00t '' ) . SignIn.Click ( ) ; } } } using ( var driver = new ChromeDriver ( Path.GetDirectoryName ( Assembly.GetExecutingAssembly ( ) .Location ) ) ) { driver.Navigate ( ) .GoToUrl ( @ '' http : //localhost:4300/ '' ) ; var link = driver.FindElement ( By.Id ( `` email '' ) ) ; link.SendKeys ( `` hello '' ) ; } < input autocomplete= '' off '' class= '' form-control ng-pristine ng-valid ng-touched '' id= '' email '' name= '' email '' placeholder= '' Email address '' type= '' email '' ng-reflect-name= '' email '' ng-reflect-is-disabled= '' false '' style= '' background-image : url ( & quot ; data : image/png ; base64 , iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAAXNSR0IArs4c6QAAAPhJREFUOBHlU70KgzAQPlMhEvoQTg6OPoOjT+JWOnRqkUKHgqWP4OQbOPokTk6OTkVULNSLVc62oJmbIdzd95NcuGjX2/3YVI/Ts+t0WLE2ut5xsQ0O+90F6UxFjAI8qNcEGONia08e6MNONYwCS7EQAizLmtGUDEzTBNd1fxsYhjEBnHPQNG3KKTYV34F8ec/zwHEciOMYyrIE3/ehKAqIoggo9inGXKmFXwbyBkmSQJqmUNe15IRhCG3byphitm1/eUzDM4qR0TTNjEixGdAnSi3keS5vSk2UDKqqgizLqB4YzvassiKhGtZ/jDMtLOnHz7TE+yf8BaDZXA509yeBAAAAAElFTkSuQmCC & quot ; ) ; background-repeat : no-repeat ; background-attachment : scroll ; background-size : 16px 18px ; background-position : 98 % 50 % ; cursor : auto ; '' xpath= '' 1 '' >",Atata selenium web driver ca n't find controls by id on angular app "C_sharp : The question is very technical , and it sits deeply between F # / C # differences . It is quite likely that I might ’ ve missed something . If you find a conceptual error , please , comment and I will update the question.Let ’ s start from C # world . Suppose that I have a simple business object , call it Person ( but , please , keep in mind that there are 100+ objects far more complicated than that in the business domain that we work with ) : and I use DI / IOC and so that I never actually pass a Person around . Rather , I would always use an interface ( mentioned above ) , call it IPerson : The business requirement is that the person can be serialized to / deserialized from the database . Let ’ s say that I choose to use Entity Framework for that , but the actual implementation seems irrelevant to the question . At this point I have an option to introduce “ database ” related class ( es ) , e.g . EFPerson : along with the relevant database related attributes and code , which I will skip for brevity , and then use Reflection to copy properties of IPerson interface between Person and EFPerson OR just use EFPerson ( passed as IPerson ) directly OR do something else . This is fairly irrelevant , as the consumers will always see IPerson and so the implementation can be changed at any time without the consumers knowing anything about it . If I need to add a property , then I would update the interface IPerson first ( let ’ s say I add a property DateTime DateOfBirth { get ; set ; } ) and then the compiler will tell me what to fix . However , if I remove the property from the interface ( let ’ s say that I no longer need LastName ) , then the compiler won ’ t help me . However , I can write a Reflection-based test , which would ensure that the properties of IPerson , Person , EFPerson , etc . are identical . This is not really needed , but it can be done and then it will work like magic ( and yes , we do have such tests and they do work like magic ) .Now , let ’ s get to F # world . Here we have the type providers , which completely remove the need to create database objects in the code : they are created automatically by the type providers ! Cool ! But is it ? First , somebody has to create / update the database objects and if there is more than one developer involved , then it is natural that the database may and will be upgraded / downgraded in different branches . So far , from my experience , this is an extreme pain on the neck when F # type providers are involved . Even if C # EF Code First is used to handle migrations , some “ extensive shaman dancing ” is required to make F # type providers “ happy ” .Second , everything is immutable in F # world by default ( unless we make it mutable ) , so we clearly don ’ t want to pass mutable database objects upstream . Which means that once we load a mutable row from the database , we want to convert it into a “ native ” F # immutable structure as soon as possible so that to work only with pure functions upstream . After all , using pure functions decreases the number of required tests in , I guess , 5 – 50 times , depending on the domain . Let ’ s get back to our Person . I will skip any possible re-mapping for now ( e.g . database integer into F # DU case and similar stuff ) . So , our F # Person would look like that : So , if “ tomorrow ” I need to add dateOfBirth : DateTime to this type , then the compiler will tell me about all places where this needs to be fixed . This is great because C # compiler will not tell me where I need to add that date of birth , … except the database . The F # compiler will not tell me that I need to go and add a database column to the table Person . However , in C # , since I would have to update the interface first , the compiler will tell me which objects must be fixed , including the database one ( s ) .Apparently , I want the best from both worlds in F # . And while this can be achieved using interfaces , it just does not feel the F # way . After all , the analog of DI / IOC is done very differently in F # and it is usually achieved by passing functions rather than interfaces.So , here are two questions.How can I easily manage database up / down migrations in F # world ? And , to start from , what is the proper way to actually do the database migrations in F # world when many developers are involved ? What is the F # way to achieve “ the best of C # world ” as described above : when I update F # type Person and then fix all places where I need to add / remove properties to the record , what would be the most appropriate F # way to “ fail ” either at compile time or at least at test time when I have not updated the database to match the business object ( s ) ? public class Person : IPerson { public int PersonId { get ; set ; } public string Name { get ; set ; } public string LastName { get ; set ; } } public interface IPerson { int PersonId { get ; set ; } string Name { get ; set ; } string LastName { get ; set ; } } public class EFPerson : IPerson { public int PersonId { get ; set ; } public string Name { get ; set ; } public string LastName { get ; set ; } } type Person = { personId : int name : string lastName : string }",F # type providers vs C # interfaces + Entity Framework "C_sharp : I would expect the compiler to attempt to cast x as an int , but apparently it does not.Edit by 280Z28 : Changed NullReferenceException to InvalidOperationException , which is what Nullable < T > .Value throws when HasValue is false . int ? x = null ; x = x + 1 ; // Works , but x remains null",Why does n't attempting to add to a null value throw an InvalidOperationException ? "C_sharp : In my application , I have code similar to following : As expected , running this code calls the second overload of 'Method ' , the one expecting a function delegate that returns a task . However , if i change the code to avoid using the anonymous method in Main : The C # compiler now complains that my call to 'Method ' is ambiguous . What am i missing ? class Program { static void Main ( string [ ] args ) { Method ( uri = > Task.FromResult ( uri ) ) ; } static void Method ( Func < Uri , Uri > transformer ) { throw new NotImplementedException ( ) ; } static void Method ( Func < Uri , Task < Uri > > transformer ) { throw new NotImplementedException ( ) ; } } class Program { static void Main ( string [ ] args ) { Method ( Method2 ) ; } static Task < Uri > Method2 ( Uri uri ) { return Task.FromResult ( uri ) ; } static void Method ( Func < Uri , Uri > transformer ) { throw new NotImplementedException ( ) ; } static void Method ( Func < Uri , Task < Uri > > transformer ) { throw new NotImplementedException ( ) ; } }",Ambiguous C # method call with delegates "C_sharp : I 've been looking at some code in a debugger associated with Razor View engine and I noticed that some of the types appear in Debugger with a trailing dot character at the end of the type name e.g. : { Nancy.ViewEngines.Razor.RazorViewEngine . } Does anyone know what this indicates ? It 's not valid syntax to use it when specifying a cast on an object so I 'm intrigued as to what it indicates within the debugger.EDIT : As requested by @ Damien_The_Unbeliever , screenshot of the variable in debugger : And the code that I 'm looking at : To give a little more background , we 're trying to add logging to our Nancy View Cache to investigate an intermittent issue with Razor Views throwing compilation errors , but that is n't really relevant to the question . public TCompiledView GetOrAdd < TCompiledView > ( ViewLocationResult viewLocationResult , Func < ViewLocationResult , TCompiledView > valueFactory ) { TCompiledView compiledView = default ( TCompiledView ) ; compiledView = ( TCompiledView ) this.cache.GetOrAdd ( viewLocationResult , x = > valueFactory ( x ) ) ;",What does the trailing dot on a C # type indicate ? "C_sharp : I 'm currently working on upgrading a windows 8.1 universal app to a windows 10 UWP app . There is a part of code that was working perfectly before that does n't work anymore in my Windows 10 UWP app . I have an enum that looks like this : When I try to get the attribute for any of the enum values , it always returns an empty array . I use the following code : GetCustomAttributes always returns an empty array , so attributes.Length is always 0 , so the function returns null ; Has something changed in Windows 10 that prevent this from working ? Thanks a lot ! public enum EStaticFile { [ StringValue ( `` Path of a file '' ) ] CONFIG_FILE_1 , [ StringValue ( `` Path of a file '' ) ] CONFIG_FILE_2 } public static StringValue GetStringValueAttribute ( this Enum aEnumValue ) { Type type = aEnumValue.GetType ( ) ; FieldInfo fieldInfo = type.GetRuntimeField ( aEnumValue.ToString ( ) ) ; StringValue [ ] attributes = fieldInfo.GetCustomAttributes ( typeof ( StringValue ) , false ) as StringValue [ ] ; if ( attributes.Length > 0 ) { return attributes [ 0 ] ; } return null ; }",GetCustomAttributes for an enum value return an empty Array "C_sharp : I am using EF 6 with a UoW pattern . I have multiple contexts defined in my UoW since I 'm using data from multiple databases . Everything seems to be working correctly except the CommitAsync function I have defined . Here 's the code I have : When I run this code saving changes in both contexts I get : The transaction manager has disabled its support for remote/network transactions . ( Exception from HRESULT : 0x8004D024 ) The await _context2.SaveChangesAsync ( ) ; is where the error happens . If I remove the TransactionScope from this function , the code seems to work without error . I am hesitant to remove the scope for multiple contexts.Just in case it 'll help , here 's the code I use to call this function : Thanks ! public async Task CommitAsync ( ) { try { using ( var scope = new TransactionScope ( TransactionScopeAsyncFlowOption.Enabled ) ) { if ( _context1 ! = null ) await _context1.SaveChangesAsync ( ) ; if ( _context2 ! = null ) await _context2.SaveChangesAsync ( ) ; scope.Complete ( ) ; } } catch ( DbEntityValidationException ex ) { //.. } } state.Name = `` Texas '' ; _uow.StateRepository.Update ( state ) ; user.FirstName = `` John '' ; _uow.UserRepository.Update ( user ) ; await _uow.CommitAsync ( ) ;",Using asynchronous save changes on Entity Framework with multiple contexts "C_sharp : Lets say we have following sample code in C # : When I ildasmed the following code : However , csc.exe converted derived.HelloWorld ( ) ; -- > callvirt instance void EnumReflection.BaseClass : :HelloWorld ( ) . Why is that ? I did n't mention BaseClass anywhere in the Main method.And also if it is calling BaseClass : :HelloWorld ( ) then I would expect call instead of callvirt since it looks direct calling to BaseClass : :HelloWorld ( ) method . class BaseClass { public virtual void HelloWorld ( ) { Console.WriteLine ( `` Hello Tarik '' ) ; } } class DerivedClass : BaseClass { public override void HelloWorld ( ) { base.HelloWorld ( ) ; } } class Program { static void Main ( string [ ] args ) { DerivedClass derived = new DerivedClass ( ) ; derived.HelloWorld ( ) ; } } .method private hidebysig static void Main ( string [ ] args ) cil managed { .entrypoint // Code size 15 ( 0xf ) .maxstack 1 .locals init ( [ 0 ] class EnumReflection.DerivedClass derived ) IL_0000 : nop IL_0001 : newobj instance void EnumReflection.DerivedClass : :.ctor ( ) IL_0006 : stloc.0 IL_0007 : ldloc.0 IL_0008 : callvirt instance void EnumReflection.BaseClass : :HelloWorld ( ) IL_000d : nop IL_000e : ret } // end of method Program : :Main",Why does C # compiler produce method call to call BaseClass method in IL "C_sharp : Firstly here 's the link to my minimal version project.I am trying to create a tinder swipe card kind of effect inside my Pivot Page.After referring Lightstone Carousel Was able to create one in C # and XAML which works inside a Grid . Now my problem is that custom control should come inside a Pivot element . As pivot 's default manipulation overrides my control 's swipe Manipulation on TOUCH devices . How can I bubble down to my custom control.Was n't able to find Touchin Win 10 app as per @ Romasz answer.Any other control suggestion with similar effect would also be appreciated.XAML As per @ Chris W. query following two show the Tinder swipe effect1 ) Web Version2 ) Objective C CodeTo see similar effect in app remove the encasing pivot control and pivot items and it would work fine.EDITAs per @ Romasz comment have uploaded a new sample . There are two upper one being my custom control where left and right swipe now works but vertical swipe does n't . Below is default ListView where scroll swipe everything works but there is no Tinder kind effect . The only reason of creating the control is to add effect . < Pivot > < PivotItem > < Grid Background= '' White '' > < Grid.RowDefinitions > < RowDefinition Height= '' * '' / > < RowDefinition Height= '' 3* '' / > < RowDefinition Height= '' * '' / > < /Grid.RowDefinitions > < Grid Grid.Row= '' 0 '' Background= '' LightBlue '' / > < Grid Grid.Row= '' 1 '' > < ctrl : Carrousel Grid.Row= '' 0 '' Background= '' Green '' ItemsSource= '' { Binding Datas } '' SelectedIndex= '' 0 '' TransitionDuration= '' 2500 '' Depth= '' 700 '' MaxVisibleItems= '' 15 '' x : Name= '' CarrouselElement '' Rotation= '' 50 '' TranslateY= '' 0 '' TranslateX = '' 1200 '' > < ctrl : Carrousel.EasingFunction > < CubicEase EasingMode= '' EaseOut '' / > < /ctrl : Carrousel.EasingFunction > < ctrl : Carrousel.ItemTemplate > < DataTemplate > < Grid Background= '' Red '' > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' Auto '' / > < /Grid.RowDefinitions > < Border BorderBrush= '' # bfbfbf '' BorderThickness= '' 1 '' > < Grid HorizontalAlignment= '' Stretch '' > < Grid.RowDefinitions > < RowDefinition Height= '' Auto '' / > < RowDefinition Height= '' Auto '' / > < /Grid.RowDefinitions > < Image Source= '' { Binding BitmapImage } '' Stretch= '' Fill '' > < /Image > < Border Grid.Row= '' 1 '' Background= '' White '' > < TextBlock Text= '' { Binding Title } '' FontSize= '' 16 '' Margin= '' 4 '' / > < /Border > < /Grid > < /Border > < Rectangle Grid.Row= '' 1 '' Height= '' 12 '' Margin= '' 0,0,0,0 '' VerticalAlignment= '' Bottom '' > < Rectangle.Fill > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' # bfbfbf '' / > < GradientStop Color= '' Transparent '' Offset= '' 1 '' / > < /LinearGradientBrush > < /Rectangle.Fill > < /Rectangle > < /Grid > < /DataTemplate > < /ctrl : Carrousel.ItemTemplate > < /ctrl : Carrousel > < /Grid > < /Grid > < /PivotItem > < PivotItem > < /PivotItem > < /Pivot >",UWP Win 10 Tinder swipe card inside Pivot ? "C_sharp : How do I fix my routing ? I have a C # project with an Angular front-end . If I go to a c # View which calls an Angular component everything breaks . If I call an Angular view ( directly from the URL ) everything works fine.C # routing to a c # viewIf I route properly in startup.cs I go to : xxx/Home/index which is simply a View that calls an Angular component ( which throws a bunch of 500 errors ) Manually routing to AngularIf I manually add /anything to the url ( xxx/Home/Index/anything ) the Angular routing takes over and everything loads fine.Index method callIndexAng.cshtmlerrors when calling the c # routing : Configure method from Startup.csscreenshot of trying to navigate to main-client.js public class HomeController : Controller { public IActionResult Index ( ) { return View ( `` IndexAng '' ) ; } } @ { ViewData [ `` Title '' ] = `` Home Page '' ; } @ * < script src= '' https : //npmcdn.com/tether @ 1.2.4/dist/js/tether.min.js '' > < /script > * @ @ * < app asp-prerender-module= '' ClientApp/dist/main-server '' > Loading ... < /app > * @ < h3 > Loading Ang App root : < /h3 > < app-root > < /app-root > < script src= '' ~/dist/vendor.js '' asp-append-version= '' true '' > < /script > @ section scripts { < script src= '' ~/dist/main-client.js '' asp-append-version= '' true '' > < /script > } public void Configure ( IApplicationBuilder app , IHostingEnvironment env , ApplicationDbContext identityContext , UserManager < ApplicationUser > userManager , RoleManager < IdentityRole > roleManager ) { # if DEBUG if ( env.IsDevelopment ( ) ) { app.UseDeveloperExceptionPage ( ) ; app.UseWebpackDevMiddleware ( new WebpackDevMiddlewareOptions { HotModuleReplacement = true } ) ; } else { app.UseExceptionHandler ( `` /Home/Error '' ) ; } # else app.UseExceptionHandler ( `` /Home/Error '' ) ; # endif app.UseStaticFiles ( ) ; //app.UseSession ( ) ; app.UseAuthentication ( ) ; app.UseMvc ( routes = > { routes.MapRoute ( name : `` default '' , template : `` { controller=Home } / { action=Index } / { id ? } '' ) ; routes.MapSpaFallbackRoute ( name : `` spa-fallback '' , defaults : new { controller = `` Home '' , action = `` Index '' } ) ; } ) ; }","c # View calling Angular component breaks , but calling Angular directly works fine" "C_sharp : I have this C # extension method that will extend any dictionary where the Value type is an IList . When I write the equivalent code in VB.Net I get the following compile error : `` Extension method 'Add ' has some type constraints that can never be satisfied '' .I find this really puzzling as the same type constraints can be satisfied in C # .So my question is this : Why does this not work in VB ? Is there a way to make these same type constraints work in VB ? Have I made a mistake converting the code ? I hope somebody can shed some light on this as I have been scratching my head on this one for a while . : ) ( Incase you are curious the extension method is intended to make it simple to add multiple values into a dictionary under a single key ( such as multiple orders under one customer ) . But this is unimportant , I am solely concerned about the puzzling behaviour I am observing in VB ) .Here is the C # Version that works : Here is the VB version that does n't compile : /// < summary > /// Adds the specified value to the multi value dictionary./// < /summary > /// < param name= '' key '' > The key of the element to add. < /param > /// < param name= '' value '' > The value of the element to add . The value can be null for reference types. < /param > public static void Add < KeyType , ListType , ValueType > ( this Dictionary < KeyType , ListType > thisDictionary , KeyType key , ValueType value ) where ListType : IList < ValueType > , new ( ) { //if the dictionary does n't contain the key , make a new list under the key if ( ! thisDictionary.ContainsKey ( key ) ) { thisDictionary.Add ( key , new ListType ( ) ) ; } //add the value to the list at the key index thisDictionary [ key ] .Add ( value ) ; } `` ' < summary > `` ' Adds the specified value to the multi value dictionary. `` ' < /summary > `` ' < param name= '' key '' > The key of the element to add. < /param > `` ' < param name= '' value '' > The value of the element to add . The value can be null for reference types. < /param > < System.Runtime.CompilerServices.Extension ( ) > _Public Sub Add ( Of KeyType , ListType As { IList ( Of ValueType ) , New } , ValueType ) _ ( ByVal thisDictionary As Dictionary ( Of KeyType , ListType ) , ByVal key As KeyType , ByVal value As ValueType ) 'if the dictionary does n't contain the key , make a new list under the key If Not thisDictionary.ContainsKey ( key ) Then thisDictionary.Add ( key , New ListType ( ) ) End If 'add the value to the list at the key index thisDictionary ( key ) .Add ( value ) End Sub",C # to VB.Net : Why does this fail to compile when converted to VB ? "C_sharp : What is wrong withCompile Error : Can not implicitly convert type 'int ? ' to 'bool'Just trying to get the flavour of adding two nullable integers in the C # 6.0 way.I know the other ways too ( like hasvalue etc . ) , but I am experimenting with this new operator . public int Add ( int ? a , int ? b ) { return ( a ? .0 + b ? .0 ) ; }",What is wrong with the below Null-Conditional Operator ? "C_sharp : I have created a view `` Supplier '' that shows columns from a table `` T_ADDRESS '' . The view is declared as ( I know , the '* ' is a no-go in views ) In EF , I want to use the view as it is more readable than the ugly `` T_ADRESSEN '' . So far so easy.Now comes the tricky part ( for me ) . The table T_ADDRESS has a self referencing foreign key `` MainAddressId '' which points to T_ADDRESS.Creating a DB-first ( or CodeFirst from DB ) will create the FK relationship for the table T_ADDRESS ( and the navigational properties ) , but not for the view 'Supplier ' . Of course not : EF does not know anything about the FK relationship ( although the view exposes the same columns ) . Now I tried to use the 'ForeignKey ' and 'InverseProperty ' attributes in my code first model on the Supplier-class but this gives me an ModelValidationException . Also clear : There is no such FK-relationship.How can I tell EF to treat a field just like a foreign key although the constraint does not exist ? What I am trying to do is to have 'Suppliers ' in my EF model ( as a subset of T_ADDRESS ) . If there is another way to do it , I would be happy to receive a hint . create View Supplier as select * from T_ADRESSEN where IsSupplier = 1",Create a pseudo foreign key on a view using entity framework "C_sharp : Background ExplanationOkay so I 'm currently binding a ContextMenu ItemsSource to an ObservableCollection of lets say TypeAThe following code is within the singleton class DataStoreNow I 've already successfully bound an ItemsControl to GetTypeACollection with the following XAML code : The following code is within the MainWindow.xamlThis works as expected , showing the TypeAUserControl , correctly formatted as intended with the data from TypeANow when i try to repeat this on a ContextMenu MenuItem by binding the ItemsSource to GetFirstFiveTypeACollection i initially see the expected results however upon deleting a TypeA object the MainWindow ItemsControl is updated where the ContextMenu is not.I believe this is due to the fact that the binding itself is between the ContextMenu and a 'new ' ObservableCollection < TypeA > ( as seen in GetFirstFiveTypeAColletion ) . I have also attempted this through use of an IValueConverterThe following code is within the class ValueConvertersThe XAML code I have tried.Using IValueConverterUsing GetFirstFiveTypeACollectionI 've no idea what to try and do next or how i should be doing this , Any help would be greatly appreciated ! EditOkay so I have changed the followingDataStore.csMainWindow.xamlMainWindow.xaml.csNotifyIcon.xamlNotifyIcon.xaml.csSo everything binds correctly at start but when a TimerType is deleted the PropertyChangedEventHandler is always NULL . I thought this was a DataContext issue but I 'm pretty sure I have the DataContext and all of the Bindings correct now ? Singleton Instance Creation private ObservableCollection < TypeA > TypeACollection = new ObservableCollection < TypeA > ( ) ; public ObservableCollection < TypeA > GetTypeACollection { get { return TypeACollection ; } } public ObservableCollection < TypeA > GetFirstFiveTypeACollection { get { return TypeACollection.Take ( 5 ) ; } } < ItemsControl x : Name= '' TypeAList '' ItemsSource= '' { Binding GetTypeACollection , Source= { StaticResource DataStore } , UpdateSourceTrigger=PropertyChanged } '' > < ItemsControl.ItemsPanel > < ItemsPanelTemplate > < VirtualizingStackPanel / > < /ItemsPanelTemplate > < /ItemsControl.ItemsPanel > < ItemsControl.ItemTemplate > < DataTemplate > < User_Controls : TypeAUserControl Type= '' { Binding } '' / > < /DataTemplate > < /ItemsControl.ItemTemplate > < /ItemsControl > public class ObservableCollectionTypeAResizeConverter : IValueConverter { public object Convert ( object value , Type targetType , object parameter , CultureInfo culture ) { ObservableCollection < TypeA > TypeACollection = value as ObservableCollection < TypeA > ; return TypeACollection.Take ( System.Convert.ToInt32 ( parameter ) ) ; } public object ConvertBack ( object value , Type targetType , object parameter , CultureInfo culture ) { return null ; } } < MenuItem Header= '' First 5 Type A '' Name= '' MI_FirstFiveTypeA '' ItemsSource= '' { Binding DATA_STORE.GetTypeACollection , ConverterParameter=5 , Converter= { StaticResource ObservableCollectionTypeAResizeConverter } , Source= { StaticResource DataStore } } '' / > < MenuItem Header= '' First 5 Type A '' Name= '' MI_FirstFiveTypeA '' ItemsSource= '' { Binding DATA_STORE.RecentTimers , Source= { StaticResource DataStore } , UpdateSourceTrigger=PropertyChanged } '' / > private ObservableCollection < TimerType > TimerTypes = new ObservableCollection < TimerType > ( ) ; public ObservableCollection < TimerType > getTimerTypes { get { return new ObservableCollection < TimerType > ( TimerTypes.OrderByDescending ( t = > t.LastUsed ) ) ; } } public ObservableCollection < TimerType > RecentTimers { get { return new ObservableCollection < TimerType > ( TimerTypes.OrderByDescending ( t = > t.LastUsed ) .Take ( 5 ) ) ; } } public event PropertyChangedEventHandler PropertyChanged ; // Create the OnPropertyChanged method to raise the eventprivate void NotifyPropertyChanged ( [ CallerMemberName ] String propertyName = `` '' ) { if ( PropertyChanged ! = null ) { PropertyChanged ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } } //THIS IS IN THE ADD METHODTimerTypes.Add ( timer ) ; NotifyPropertyChanged ( `` getTimerTypes '' ) ; NotifyPropertyChanged ( `` RecentTimers '' ) ; NotifyPropertyChanged ( `` TimerTypes '' ) ; //THIS IS IN THE REMOVE METHODTimerTypes.Remove ( Timer ) ; NotifyPropertyChanged ( `` getTimerTypes '' ) ; NotifyPropertyChanged ( `` RecentTimers '' ) ; NotifyPropertyChanged ( `` TimerTypes '' ) ; < ItemsControl x : Name= '' TimersList '' ItemsSource= '' { Binding Path=getTimerTypes , UpdateSourceTrigger=PropertyChanged } '' > //Lists are populated in DataStore.cs before this.DataContext = DataStore.DATA_STORE ; InitializeComponent ( ) ; < MenuItem Header= '' Recent Timers '' Name= '' MIRecent '' ItemsSource= '' { Binding RecentTimers , UpdateSourceTrigger=PropertyChanged } '' / > DataContext = DataStore.DATA_STORE ; InitializeComponent ( ) ; private static readonly DataStore Instance = new DataStore ( ) ; private DataStore ( ) { } public static DataStore DATA_STORE { get { return Instance ; } set { } }",Binding to an ObservableCollection to show the first X number of items c # WPF "C_sharp : I am running dot quick start project locally perfectly with following connection . However i do n't the location on which its creating the mdf file.I have checked app_data its empty.Anyways when i upload this project on remote server as soon as I click Accept button displaying on google authorization page it throws following exception.To solve above I did try to modify connectionstring with same name `` DefaultConnection '' but with integrated security . But exception stays the same . Local copy which is not giving exception and seems to work also confuses me because i dont know the database location it used to store user credentials . < add name= '' DefaultConnection '' providerName= '' System.Data.SqlClient '' connectionString= '' Data Source= ( LocalDb ) \v11.0 ; Initial Catalog=aspnet-mirror-quickstart-dotnet-20130523105156 ; Integrated Security=SSPI ; AttachDBFilename=|DataDirectory|\aspnet-mirror-quickstart-dotnet-20130523105156.mdf '' / > [ Win32Exception ( 0x80004005 ) : The system can not find the file specified ] [ SqlException ( 0x80131904 ) : A network-related or instance-specific error occurred while establishing a connection to SQL Server . The server was not found or was not accessible . Verify that the instance name is correct and that SQL Server is configured to allow remote connections . ( provider : SQL Network Interfaces , error : 52 - Unable to locate a Local Database Runtime installation . Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled . ) ] System.Data.SqlClient.SqlInternalConnection.OnError ( SqlException exception , Boolean breakConnection , Action ` 1 wrapCloseInAction ) +6676046 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning ( TdsParserStateObject stateObj , Boolean callerHasConnectionLock , Boolean asyncClose ) +810 System.Data.SqlClient.TdsParser.Connect ( ServerInfo serverInfo , SqlInternalConnectionTds connHandler , Boolean ignoreSniOpenTimeout , Int64 timerExpire , Boolean encrypt , Boolean trustServerCert , Boolean integratedSecurity , Boolean withFailover ) +6702720 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin ( ServerInfo serverInfo , String newPassword , SecureString newSecurePassword , Boolean ignoreSniOpenTimeout , TimeoutTimer timeout , Boolean withFailover ) +219 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover ( ServerInfo serverInfo , String newPassword , SecureString newSecurePassword , Boolean redirectedUserInstance , SqlConnectionString connectionOptions , SqlCredential credential , TimeoutTimer timeout ) +6704856 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist ( TimeoutTimer timeout , SqlConnectionString connectionOptions , SqlCredential credential , String newPassword , SecureString newSecurePassword , Boolean redirectedUserInstance ) +6705315 System.Data.SqlClient.SqlInternalConnectionTds..ctor ( DbConnectionPoolIdentity identity , SqlConnectionString connectionOptions , SqlCredential credential , Object providerInfo , String newPassword , SecureString newSecurePassword , Boolean redirectedUserInstance , SqlConnectionString userConnectionOptions ) +610 System.Data.SqlClient.SqlConnectionFactory.CreateConnection ( DbConnectionOptions options , DbConnectionPoolKey poolKey , Object poolGroupProviderInfo , DbConnectionPool pool , DbConnection owningConnection , DbConnectionOptions userOptions ) +1049 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection ( DbConnectionPool pool , DbConnectionOptions options , DbConnectionPoolKey poolKey , DbConnectionOptions userOptions ) +74 System.Data.ProviderBase.DbConnectionPool.CreateObject ( DbConnectionOptions userOptions ) +6707883 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest ( DbConnectionOptions userOptions ) +78 System.Data.ProviderBase.DbConnectionPool.TryGetConnection ( DbConnection owningObject , UInt32 waitForMultipleObjectsTimeout , Boolean allowCreate , Boolean onlyOneCheckConnection , DbConnectionOptions userOptions , DbConnectionInternal & connection ) +2192 System.Data.ProviderBase.DbConnectionPool.TryGetConnection ( DbConnection owningObject , TaskCompletionSource ` 1 retry , DbConnectionOptions userOptions , DbConnectionInternal & connection ) +116 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection ( DbConnection owningConnection , TaskCompletionSource ` 1 retry , DbConnectionOptions userOptions , DbConnectionInternal & connection ) +1012 System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection ( DbConnection outerConnection , DbConnectionFactory connectionFactory , TaskCompletionSource ` 1 retry , DbConnectionOptions userOptions ) +6712511 System.Data.SqlClient.SqlConnection.TryOpen ( TaskCompletionSource ` 1 retry ) +152 System.Data.SqlClient.SqlConnection.Open ( ) +229 System.Data.Entity.SqlServer. < > c__DisplayClass1. < Execute > b__0 ( ) +15 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute ( Func ` 1 operation ) +263 System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection ( DbConnection sqlConnection , Action ` 1 act ) +334 System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection ( DbConnection sqlConnection , Action ` 1 act ) +582 System.Data.Entity.SqlServer.SqlProviderServices.GetDbProviderManifestToken ( DbConnection connection ) +373 System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken ( DbConnection connection ) +115 [ ProviderIncompatibleException : The provider did not return a ProviderManifestToken string . ] System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken ( DbConnection connection ) +451 System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked ( DbProviderServices providerServices , DbConnection connection ) +48 [ ProviderIncompatibleException : An error occurred while getting provider information from the database . This can be caused by Entity Framework using an incorrect connection string . Check the inner exceptions for details and ensure that the connection string is correct . ] System.Data.Entity.Utilities.DbProviderServicesExtensions.GetProviderManifestTokenChecked ( DbProviderServices providerServices , DbConnection connection ) +242 System.Collections.Concurrent.ConcurrentDictionary ` 2.GetOrAdd ( TKey key , Func ` 2 valueFactory ) +83 System.Data.Entity.Infrastructure.DefaultManifestTokenResolver.ResolveManifestToken ( DbConnection connection ) +229 System.Data.Entity.DbModelBuilder.Build ( DbConnection providerConnection ) +118 System.Data.Entity.Internal.LazyInternalContext.CreateModel ( LazyInternalContext internalContext ) +94 System.Data.Entity.Internal.RetryLazy ` 2.GetValue ( TInput input ) +248 System.Data.Entity.Internal.LazyInternalContext.InitializeContext ( ) +618 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType ( Type entityType ) +26 System.Data.Entity.Internal.Linq.InternalSet ` 1.Initialize ( ) +72 System.Data.Entity.Internal.Linq.InternalSet ` 1.get_InternalContext ( ) +21 System.Data.Entity.Infrastructure.DbQuery ` 1.System.Linq.IQueryable.get_Provider ( ) +68 System.Linq.Queryable.FirstOrDefault ( IQueryable ` 1 source , Expression ` 1 predicate ) +85 MirrorQuickstart.Models.Utils.StoreCredentials ( String userId , IAuthorizationState credentials ) +377 MirrorQuickstart.Controllers.AuthController.OAuth2Callback ( String code ) +277 lambda_method ( Closure , ControllerBase , Object [ ] ) +127 System.Web.Mvc.ReflectedActionDescriptor.Execute ( ControllerContext controllerContext , IDictionary ` 2 parameters ) +274 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod ( ControllerContext controllerContext , ActionDescriptor actionDescriptor , IDictionary ` 2 parameters ) +39 System.Web.Mvc. < > c__DisplayClass15. < InvokeActionMethodWithFilters > b__12 ( ) +120 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter ( IActionFilter filter , ActionExecutingContext preContext , Func ` 1 continuation ) +637 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters ( ControllerContext controllerContext , IList ` 1 filters , ActionDescriptor actionDescriptor , IDictionary ` 2 parameters ) +307 System.Web.Mvc.ControllerActionInvoker.InvokeAction ( ControllerContext controllerContext , String actionName ) +720 System.Web.Mvc.Controller.ExecuteCore ( ) +162 System.Web.Mvc.ControllerBase.Execute ( RequestContext requestContext ) +305 System.Web.Mvc. < > c__DisplayClassb. < BeginProcessRequest > b__5 ( ) +62 System.Web.Mvc.Async. < > c__DisplayClass1. < MakeVoidDelegate > b__0 ( ) +15 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute ( ) +606 System.Web.HttpApplication.ExecuteStep ( IExecutionStep step , Boolean & completedSynchronously ) +288",.NET Quick Start project and local database/MDF working on localhost but giving exceptions on remote server ? "C_sharp : Well , I use visual studio 2015 CE , update 2.One productivity hack I usually do is that I create empty model classes like : and then use them in a select expression like : Then I go to the yet non-existing properties Id and Name , ... and press Control+ . to ask visual studio to generate property Id for me.All great , but it will create : and if I use the same method in an asp.net webapi model binding , the binding will fail silently and give me Id = 0.So my question is : is there any option to ask VS to create public setter , i.e . : public class PersonModel { } db.People.Where ( p = > someCondition ) .Select ( p = > new PersonModel { Id = p.Id , Name = p.Name , //set other properties } ) .ToList ( ) ; public int Id { get ; internal set ; } public int Id { get ; set ; }",Prevent visual studio from limiting the setter method to internal "C_sharp : I 'm reviewing someone 's code and came across this private class : CustomType is then used all over the parent class . This is neat of course , since CustomType is shorter thanMy question is , what are the performance/memory implications of having an inner class just for a shortcut ? In a performance sensitive application , does this contribute ( even slightly ) to higher memory and/or CPU usage ? class CustomType : Dictionary < int , SomeOtherCustomType > { // This is empty ; nothing omitted here } Dictionary < int , SomeOtherCustomType >",Using a private class in place of a field - performance/memory penalty ? "C_sharp : I 've been looking for an answer on the internet but all I 've found was : Edit : Added some items in response to the answersFor IEquatableI 'm supposed to overload Equals ( ) , GetHashCode ( ) , == and ! = together.I 'm supposed to reduce redundancy via implementing ! = via ==.I 'm supposed to seal the classFor IComparableI 'm supposed to overload Equals ( ) , GetHashCode ( ) , < , > , < = and > = together.In fact it is recommend to implement IEquatable when doing soOverload the non-generic version of IComparableCompareTo ( ) == 0 should mean Equals ( ) == trueSo I 've been thinking about this : Am I overlooking something or is this ok ? public bool Equals ( T other ) { if ( ( object ) other == null ) { return false ; } return CompareTo ( other ) == 0 ; }",Should be IEquatable < T > 's Equals ( ) be implemented via IComparable < T > 's CompareTo ( ) ? "C_sharp : I ran the following methods in C # .Here , if I call Add ( 1,1 ) , it gives ambiguity.Now let me swap position of float and long in the first method as follows : Now it prints `` method 2 '' as output . What is the reason behind the ambiguity in first case ? And if I write following two methods in my code : On calling Add ( 1,1 ) , it gives ambiguity error . Why does it not go for best match , which is the second method ( having int and float ) ? According to me , it should have given method 2 as output . public float Add ( float num1 , long num2 ) { Console.WriteLine ( `` method 1 '' ) ; return 0 ; } public float Add ( int num1 , float num2 ) { Console.WriteLine ( `` method 2 '' ) ; return 0 ; } public float Add ( long num1 , float num2 ) { Console.WriteLine ( `` method 1 '' ) ; return 0 ; } public float Add ( int num1 , float num2 ) { Console.WriteLine ( `` method 2 '' ) ; return 0 ; } public float Add ( long num1 , long num2 ) { Console.WriteLine ( `` method 1 '' ) ; return 0 ; } public float Add ( int num1 , float num2 ) { Console.WriteLine ( `` method 2 '' ) ; return 0 ; }",Method overloading in C # and Java "C_sharp : We have an ashx image handler which has performed fairly well over the last few years , but we 've recently noticed some odd intermittent behaviour in IE8 and IE9 . We have a gallery page which calls the image handler multiple times as part of an image 's src attribute , this page is opened in a pop up window . The page works fine when but when the window is opened and closed in quick succession ( before all the images on the page have finished loading ) it causes the browser to hang and subsequently has to be restarted.Following is a sample of our image handler code , I have a suspicion that the request to the image is n't 'ending ' when the window is closed and the connection between the browser and the server is still running and causing it to crash.Looking at the logs there are multiple attempts to GET the same image via the handler so it looks like the browser is retrying as it thinks it has failed to complete the request.Are there any changes I could make to the handler ( or the client code ) to ensure the browser does n't continue requesting the images after the window is closed or is this a baked-in intricacy of IE ? Safari , Firefox and Chrome handle this type of behaviour fine.Alos note : The page displaying the images has an update panel around the grid - but I do n't think this is related . Response.Clear ( ) ; Response.ContentType = `` image/jpeg '' ; System.Drawing.Image returnImage = System.Drawing.Image.FromFile ( completeImageFilePath ) ; using ( MemoryStream stream = new MemoryStream ( ) ) { returnImage.Save ( stream , ImageFormat.Jpeg ) ; stream.WriteTo ( Response.OutputStream ) ; } returnImage.Dispose ( ) ; if ( Response.IsClientConnected ) { Response.Flush ( ) ; } Response.End ( ) ;",Multiple image handler calls causing IE to hang in pop-up window "C_sharp : This is how I have always written event raisers ; for example PropertyChanged : In the latest Visual Studio , however , the light bulb thingamabob suggested simplifying the code to this : Although I 'm always in favor of simplification , I wanted to be sure this was safe . In my original code , I assign the handler to a variable to prevent a race condition in which the subscriber could become disposed in between the null check and the invocation . It seems to me that the new simplified form would suffer this condition , but I wanted to see if anyone could confirm or deny this . public event PropertyChangedEventHandler PropertyChanged ; private void RaisePropertyChanged ( string name ) { var handler = PropertyChanged ; if ( handler ! = null ) handler ( this , new PropertyChangedEventArgs ( name ) ) ; } private void RaisePropertyChanged ( string name ) { PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( name ) ) ; }",Is C # 's null-conditional delegate invocation thread safe ? "C_sharp : As a hobby project ( and to immerse myself more deeply in generics/extension methods ) , I 'm writing a parameter checking library ! I have a model called Argument that describes a parameter and looks like this : When validation for a parameter begins , an instance of this object is created , and individual validations are performed by invoking extension methods ( that contain the actual logic ) that hang off of it.One such extension method verifies that a collection contains at least one item , and currently looks like this : But it does n't appear to work . If I were , say , to write this unit test : HasItems does n't show up in Intellisense , and I get this compile error : 'Validation.Argument < System.Collections.Generic.List < int > > ' does not contain a definition for 'HasItems ' and no extension method 'HasItems ' accepting a first argument of type 'Validation.Argument < System.Collections.Generic.List < int > > ' could be found ( are you missing a using directive or an assembly reference ? ) And if I try passing the value directly into the extension method , like so : I get this : The best overloaded method match for 'Validation.CollectionTypeExtensions.HasItems < int > ( Validation.Argument < System.Collections.Generic.IEnumerable < int > > ) ' has some invalid argumentsBased on my research , what I 'd need for this to work is called `` variance , '' and applies to interfaces and delegates , but not to classes ( ie : all classes are invariant . ) That said , it might work another way . One that comes to mind is to rewrite it to go straight to T , like so : ..But that does n't work either because it requires TElement to be specified explicitly when the method is invoked . I could also fall back to using the non-generic IEnumerable interface in the type constraint , but then I 'd have to either find a way to coerce the IEnumerable into IEnumerable ( which would require knowing what T is in that context ) , or duplicating the functionality of Any ( ) in order to test for the existence of any items , and there 's another extension method ( All ) that that would be very , very messy for , so I 'd rather avoid it.So ultimately , I guess my question is : how do I get my extension method to attach properly ? public class Argument < T > { internal Argument ( string name , T value ) { Name = name ; Value = value ; } public string Name { get ; private set ; } public T Value { get ; private set ; } } public static Argument < IEnumerable < T > > HasItems < T > ( this Argument < IEnumerable < T > > argument ) { if ( ! argument.Value.Any ( ) ) throw Error.Generic ( argument.Name , `` Collection contains no items . `` ) ; return argument ; } [ TestMethod ] public void TestMethod1 ( ) { var argument = new List < int > ( ) { 1 , 2 , 6 , 3 , -1 , 5 , 0 } ; Validate.Argument ( `` argument '' , argument ) .IsNotNull ( ) .HasItems ( ) .All ( v = > v.IsGreaterThan ( 0 ) ) ; } CollectionTypeExtensions.HasItems ( Validate.Argument ( `` argument '' , argument ) ) ; public static Argument < T > HasItems < T , TElement > ( this Argument < T > argument ) where T : IEnumerable < TElement > { if ( ! argument.Value.Any ( ) ) throw Error.Generic ( argument.Name , `` Collection contains no items . `` ) ; return argument ; }",How could an extension method be attached to a generic class when the type argument is IEnumerable < T > ? "C_sharp : I have an application that I want to display multiple PDF documents . If I define the control at design time I can load a document and display it , but when I dynamically create the control during run time I can not get it to display . The document is being displayed in a tab.Here is my code ... How do I get the PDF to display ? AxAcroPDF newPDF = new AxAcroPDF ( ) ; newPDF.CreateControl ( ) ; newPDF.Width = selectedTab.Width ; newPDF.Height = selectedTab.Height ; newPDF.LoadFile ( filePath ) ; selectedTab.Controls.Add ( newPDF ) ; newPDF.Show ( ) ; newPDF.Visible = true ;",PDF Document does not display when creating control dynamically "C_sharp : I 'm building a Windows Store App including a local folder of Images . I want to protect all the Images so they ca n't be accessed from : I know I should encrypt and decrypt the Images using the DataProtectionProvider class , but the documentation only shows how to encrypt/decrypt strings ... How should I convert a Bitmap image into a byte array ? or should I encode it with Base64 ? Is there any tutorial or sample using this process ? C : \Users [ username ] \AppData\Local\Packages\LocalState\Settings\settings.dat",Encrypt & Decrypt Local Images in Windows Store App "C_sharp : Summing up the problem in a single line for clarity as suggested : I want to find all the things that have different values for some field and are less than a week apart ( based on another field ) Let 's say I have a Users table and a User class.Each User has the following fields : SignUpDate a non-null DateTime fieldUserType an int field , for this question let 's say it 's either 1 or 0I 'd like to select all the couples of users that signed up less than 7 days apart and have a different user type.My current ( miserable ) attempt included an OrderBy ( r= > r.SignUpDate ) and a .ToList which was n't a big deal since the number of users for every 2 weeks is not large . ( I grabbed all the users from that with overlapping weeks and compared the data ) .However , I find my current solution pretty poor . I have no idea what 's the correct way to approach this.I think the core problem here is that I do n't know how to address the concept of 'selecting every two corresponding records ' in LINQ to Entities after an ordering.Any help much appreciated , I 'm interested in how I would be able to solve this sort of problem without starting my own question in the future.Example inputExample outputAny meaningful way to indicate that the problematic pairs were : ( Different by a day and different type ) And ( Different by two days and different type ) Here is a related SQL solution I found . SignUpDate UserType -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 2008-11-11 1 2008-11-12 0 2008-11-13 0 2008-12-13 0 2008-12-15 1 2008-11-11 1 2008-11-12 0 2008-12-13 0 2008-12-15 1",Get Difference between Following Entities Linq to Entities "C_sharp : Referencesjquery commentsThe jquery comments documentationthis issue in githubAttachmentscomments-data.js is test data : Download herejquery-comments.js creates the whole comments system : Download herejquery-comments.min.js if you require it : Download hereDescriptionI have a view with a list of `` articles '' with a `` read more '' button on each `` article '' in the list . When I click on the read more button a modal opens up with a partial view with the jquery comments in it . However , when I search for the pinged users ( using the @ sign ) , the list of users do n't show by the textarea , but instead higher up in the modal ( far from the textarea ) .Below is an image , then below that is my code . You will see at the bottom of the image I have put the ' @ ' sign and the list of users is displayed on the top , it should be by the textarea . It also seems that when I click on the articles lower in the list , the higher the list of users display when I push the ' @ ' sign : MVC ViewBelow is the part populating the `` Articles '' from where the Modal is being called from : ModalThis is placed at the top of the page ( Under the @ model appname.ViewModels.VM ) : Jquery CodeMVC Partial ViewAt the bottom of the partial view is this div where it is populated : EDITAfter spending quite some time running through the jquery-comments.js file , I found that displaying of the pinged users its happening here : This seems to be taking the css ( 'top ' ) of View , which causes the problem on the pinging of the users on the partialview . @ { int iGroupNameId = 0 ; int iTotalArticles = 0 ; foreach ( var groupItems in Model.ArticleGroups ) { iTotalArticles = Model.ArticlesList.Where ( x = > x.fkiGroupNameId == groupItems.pkiKnowledgeSharingCenterGroupsId ) .Count ( ) ; if ( iTotalArticles > 0 ) { < div style= '' background : linear-gradient ( # B5012E , darkred ) ; margin : 10px ; padding : 10px ; font-weight : bold ; color : white ; text-transform : uppercase ; '' > @ groupItems.GroupName < /div > < div class= '' container '' style= '' width:100 % '' > @ if ( groupItems.pkiKnowledgeSharingCenterGroupsId ! = iGroupNameId ) { foreach ( var item in Model.ArticlesList.Where ( x = > x.fkiGroupNameId == groupItems.pkiKnowledgeSharingCenterGroupsId ) ) { < div class= '' row '' > < div class= '' col-md-4 '' > @ if ( User.IsInRole ( `` Administrator '' ) ) { < div class= '' pull-right '' > < div class= '' btn-group '' > < button class= '' btn dropdown-toggle btn-xs btn-info '' data-toggle= '' dropdown '' > < i class= '' fa fa-gear '' > < /i > < i class= '' fa fa-caret-down '' > < /i > < /button > < ul class= '' dropdown-menu pull-right '' > < li > < a href= '' @ Url.Action ( `` EditArticle '' , `` ILearn '' , new { id = item.KnowledgeSharingArticlesId } ) '' > Edit < /a > < /li > < li class= '' divider '' > < /li > < li > < a href= '' @ Url.Action ( `` DeleteArticle '' , `` ILearn '' , new { id = item.KnowledgeSharingArticlesId } ) '' > Delete < /a > < /li > < /ul > < /div > < /div > } < img src= '' @ item.ArticleImage '' class= '' img-responsive '' alt= '' img '' style= '' width:350px ; height:200px '' > < ul class= '' list-inline padding-10 '' > < li > < i class= '' fa fa-calendar '' > < /i > @ item.DateTimeStamp.ToLongDateString ( ) < /li > < li > < i class= '' fa fa-comments '' > < /i > @ item.ArticleComments < /li > < li > < i class= '' fa fa-eye '' > < /i > @ item.ArticleViews < /li > < /ul > < /div > < div class= '' col-md-8 padding-left-0 '' > < h6 class= '' margin-top-0 '' > < span style= '' font-size : large '' > @ item.Title < /span > < br > < small class= '' font-xs '' > < i > Published by < a href= '' @ Url.Action ( `` GetProfileData '' , '' UserProfile '' , new { userid = item.fkiUserId } ) '' > @ item.User_FullName < /a > < /i > < /small > < /h6 > < p > @ Html.Raw ( item.Description ) < /p > @ * < a class= '' btn btn-danger '' href= '' @ Url.Action ( `` ShowArticleDetails '' , `` ILearn '' , new { id = item.KnowledgeSharingArticlesId } ) '' > Read more < /a > * @ < button type= '' button '' onclick= '' showArticle ( ' @ item.KnowledgeSharingArticlesId ' ) '' class= '' btn btn-danger '' data-target= '' # show-details-modal '' data-toggle= '' modal '' > Read more < /button > < /div > < /div > < hr > } } < /div > } } } < ! -- Loading Panel -- > < div id= '' loadingPanel '' style= '' display : none ; '' > < div class= '' progress progress-striped active '' > < div class= '' progress-bar progress-bar-info '' style= '' width : 100 % '' > ... LOADING ... < /div > < /div > < /div > < ! -- Show details modal -- > < div id= '' show-details-modal '' class= '' modal fade '' style= '' width:100 % '' > < div class= '' modal-dialog modal-xl '' > < div class= '' modal-content '' > < div class= '' modal-header '' > < button type= '' button '' class= '' close '' data-dismiss= '' modal '' aria-hidden= '' true '' > & times ; < /button > < h4 class= '' modal-title '' > < /h4 > < div id= '' loadingPanelShowDetails '' class= '' col-md-12 text-center '' style= '' display : none ; '' > < br / > < div class= '' progress progress-striped active '' > < div class= '' progress-bar progress-bar-info '' style= '' width : 100 % '' > ... LOADING ... < /div > < /div > < /div > < div id= '' target-show-details '' > < /div > < /div > < /div > < /div > < /div > function showArticle ( id ) { $ ( `` # target-show-details '' ) .html ( `` ) ; $ ( ' # loadingPanelShowDetails ' ) .show ( ) ; $ .ajax ( { type : 'get ' , url : ' @ Url.Action ( `` ShowArticleDetails '' , `` ILearn '' ) ' , contentType : 'application/json ; charset=utf-8 ' , dataType : 'html ' , data : { `` id '' : id } , success : function ( result ) { $ ( `` # target-show-details '' ) .html ( result ) ; $ ( ' # loadingPanelShowDetails ' ) .hide ( ) ; var saveComment = function ( data ) { $ ( data.pings ) .each ( function ( index , id ) { var user = usersArray.filter ( function ( user ) { return user.id == id } ) [ 0 ] ; alert ( user.fullname ) ; data.content = data.content.replace ( ' @ @ ' + id , ' @ @ ' + user.fullname ) ; } ) ; return data ; } $ ( ' # articlecomments-container ' ) .comments ( { profilePictureURL : 'https : //viima-app.s3.amazonaws.com/media/public/defaults/user-icon.png ' , currentUserId : 1 , roundProfilePictures : true , textareaRows : 1 , enableAttachments : true , enableHashtags : true , enablePinging : true , getUsers : function ( success , error ) { $ .ajax ( { type : 'get ' , traditional : true , url : ' @ Url.Action ( `` GetPinnedUsers '' , `` ILearn '' ) ' , success : function ( usersArray ) { success ( usersArray ) } , error : error } ) ; } , getComments : function ( success , error ) { $ .ajax ( { type : 'get ' , traditional : true , data : { `` id '' : id } , url : ' @ Url.Action ( `` GetArticleComments '' , `` ILearn '' ) ' , success : function ( commentsArray ) { success ( saveComment ( commentsArray ) ) } , error : error } ) ; } , postComment : function ( data , success , error ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` PostArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( comment ) { success ( comment ) ; } , error : error } ) ; } , putComment : function ( data , success , error ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` PutArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( comment ) { success ( comment ) ; } , error : error } ) ; } , deleteComment : function ( data , success , error ) { $ .SmartMessageBox ( { title : `` Deleting Comment ? `` , content : `` Are you sure that you want to delete this comment ? `` , buttons : ' [ No ] [ Yes ] ' } , function ( ButtonPressed ) { if ( ButtonPressed === `` Yes '' ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` DeleteArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( data ) { if ( data.status === `` usersuccess '' ) { $ .smallBox ( { title : `` < strong > Comment Deleted < /strong > '' , content : `` < i class='fa fa-clock-o ' > < /i > < i > Comment was successfully deleted ! < strong < /strong > < /i > '' , color : `` # 659265 '' , iconSmall : `` fa fa-check fa-2x fadeInRight animated '' , timeout : 4000 } ) ; success ( ) ; } else { success ( ) ; } } } ) ; } if ( ButtonPressed === `` No '' ) { $ .smallBox ( { title : `` < strong > Comment not deleted < /strong > '' , content : `` < i class='fa fa-clock-o ' > < /i > < i > This comment has not been deleted. < /i > '' , color : `` # C46A69 '' , iconSmall : `` fa fa-times fa-2x fadeInRight animated '' , timeout : 4000 } ) ; } } ) ; e.preventDefault ( ) ; } , upvoteComment : function ( data , success , error ) { if ( data.user_has_upvoted ) { $ .ajax ( { type : 'post ' , dataType : `` json '' , url : ' @ Url.Action ( `` UpVoteArticleComment '' , `` ILearn '' ) ' , data : { `` CVM '' : data , `` articleId '' : id } , success : function ( ) { success ( data ) } , error : error } ) ; } else { $ .ajax ( { type : 'post ' , url : ' @ Url.Action ( `` DeleteArticleCommentUpvote '' , `` ILearn '' ) ' , data : { `` commentId '' : data.id } , success : function ( ) { success ( commentJSON ) } , error : error } ) ; } } , uploadAttachments : function ( commentArray , success , error ) { var responses = 0 ; var successfulUploads = [ ] ; var serverResponded = function ( ) { responses++ ; // Check if all requests have finished if ( responses == commentArray.length ) { // Case : all failed if ( successfulUploads.length == 0 ) { error ( ) ; // Case : some succeeded } else { success ( successfulUploads ) } } } $ ( commentArray ) .each ( function ( index , commentJSON ) { // Create form data var formData = new FormData ( ) ; $ ( Object.keys ( commentJSON ) ) .each ( function ( index , key ) { var value = commentJSON [ key ] ; if ( value ) formData.append ( key , value ) ; } ) ; formData.append ( 'fkiKnowledgeSharingArticlesId ' , id ) ; $ .ajax ( { url : ' @ Url.Action ( `` UploadToArticleComments '' , `` ILearn '' ) ' , type : 'POST ' , data : formData , cache : false , contentType : false , processData : false , success : function ( commentJSON ) { successfulUploads.push ( commentJSON ) ; serverResponded ( ) ; } , error : function ( data ) { serverResponded ( ) ; } , } ) ; } ) ; } } ) ; } , error : function ( xhr , textStatus , errorThrown ) { alert ( xhr.responseText ) ; } } ) ; } @ model Innovation_Cafe.Models.KnowledgeSharingArticles < div class= '' col-lg-12 '' > < div class= '' margin-top-10 '' > < div style= '' text-align : center ; border : solid ; border-style : solid '' > < img src= '' @ Model.ArticleImage '' class= '' img-responsive '' alt= '' img '' style= '' width:100 % ; '' > < /div > < ul class= '' list-inline padding-10 '' > < li > < i class= '' fa fa-calendar '' > < /i > @ Model.DateTimeStamp.ToLongDateString ( ) < /li > < li > < i class= '' fa fa-comments '' > < /i > @ Model.ArticleComments < /li > < li > < i class= '' fa fa-eye '' > < /i > @ Model.ArticleViews < /li > < /ul > < /div > < /div > < div class= '' col-lg-12 '' > < h6 class= '' margin-top-0 '' > @ Model.Title < br > < small class= '' font-xs '' > < i > Published by < a href= '' @ Url.Action ( `` GetProfileData '' , '' UserProfile '' , new { userid=Model.fkiUserId } ) '' > @ Model.User_FullName < /a > < /i > < /small > < /h6 > < br / > < p > @ Html.Raw ( Model.Description ) < /p > < p > @ if ( Model.FileType == `` .mp4 '' ) { < div style= '' text-align : center ; border-style : solid '' > < video controls width= '' 100 % '' > < source src= '' @ Model.FilePath '' type= '' video/mp4 '' / > < /video > < /div > } else { if ( Model.FilePath ! =null ) { < p > Click here to view file : < a href= '' @ Model.FilePath '' target= '' _blank '' > Click here < /a > < /p > } } < /div > < div class= '' col-md-12 '' > < p > & nbsp ; < /p > < hr style= '' border : solid '' / > < /div > < div class= '' row col-md-12 '' > < div class= '' col-md-12 '' id= '' articlecomments-container '' > < /div > < /div > < div class= '' row col-md-12 '' > < div class= '' col-md-12 '' id= '' articlecomments-container '' > < /div > < /div > // CUSTOM CODE // ======================================================================================================================================================================================== // Adjust vertical position var top = parseInt ( this. $ el.css ( 'top ' ) ) + self.options.scrollContainer.scrollTop ( ) ; this. $ el.css ( 'top ' , top ) ;",Viima JQuery Comments - GetUsers ( Pinged users ) displaying incorrectly in partialview "C_sharp : I 'm trying to understand why this cast does n't work : This generates a runtime error : InvalidCastException : Unable to cast object of type 'System.Collections.Generic.List ` 1 [ CastTest.Foo ] ' to type 'CastTest.FooList'.Can anyone explain why this does n't work , and whether I can get around this somehow ? using System ; using System.Collections.Generic ; using System.Linq ; using System.Text ; namespace CastTest { class Foo { } // I want to use this kind of like a typedef , to avoid writing List < Foo > everywhere . class FooList : List < Foo > { } class Program { static void Main ( string [ ] args ) { FooList list = ( FooList ) Program.GetFooList ( ) ; } // Suppose this is some library method , and i do n't have control over the return type static List < Foo > GetFooList ( ) { return new List < Foo > ( ) ; } } }",Why does n't this C # casting example work ? "C_sharp : So I have a C API with the following struct It gets passed as a parameter to one of my API functions : I am exporting this function to C # in Unity using a dll : My question is , what should I make the corresponding C # struct be ? Right now I have the following : and use try to use the function as follows : Is this the correct thing to do ? Is there a better way to do this ? typedef struct mat4f_ { float m [ 4 ] [ 4 ] ; } mat4f ; void myFunction ( const mat4f matrix ) ; [ DllImport ( `` mylib '' ) ] private static extern void myFunction ( mat4f matrix ) ; [ StructLayout ( LayoutKind.Sequential ) ] public struct mat4f { public float [ , ] m ; } //Just make an identity matrixmat4f matrix ; matrix.m = new float [ 4 , 4 ] { { 1 , 0 , 0 , 0 } , { 0 , 1 , 0 , 0 } , { 0 , 0 , 1 , 0 } , { 0 , 0 , 0 , 1 } } ; myFunction ( matrix ) ; //Call dll function",How to use C struct with 2D array in C # Unity "C_sharp : I have a list ( simplified ) I need { E , L } - > Items where their Kind==null and the next Kind==null tooAssume that there is an ID that is increasing and in order.Is this forward looking possible in Linq ? [ Kind ] [ Name ] null Enull W4 T5 G6 Qnull Lnull V7 K2 Z0 F",Linq : forward looking condition "C_sharp : For example : [ TestFixtureSetUp ] in this example , what does it do ? From my experience , [ ] usually refers to lists . [ TestFixtureSetUp ] public void Init ( ) { GetTestRepo ( false ) ; }",What are [ ] in C # ? "C_sharp : I am busy reading , and enjoying , Dependency Injection in .Net by Mark Seemann.It is quite difficult for me to explain the exact context , so please only bother with this question if you are familiar with the book.My question has to do with the two Product classes in chapter 2 pg 49 . There is one in the Domain layer and one in the data access layer . It is explained that Product class in the data access layer was created by the Linq to Entity wizard . I am working with Linq to SQL , and I could adorn my model class with Ling to SQL attributes , so that I do n't have to have a second class . E.g.However I feel this is mixing concerns and it will in effect tightly couple my domain layer to the Linq to SQL data access layer . Do you agree with this ? Let 's assume I create two 'Customer ' classes , for the domain and data access layer . Let 's say City is a required field . When saving , this rule needs to be checked . Should this be done in the domain layer or the data access layer , or both ? Thanks , Daryn [ Table ( Name= '' Customers '' ) ] public class Customer { [ Column ( IsPrimaryKey=true ) ] public string CustomerID ; [ Column ] public string City ; }",Domain logic vs data validation "C_sharp : I am fairly positive that I am creating a deadlock in my application and I am not sure how to resolve the issue . I have a few moving parts and am new to async and await so please bear with me.I have a client that uploads a file as follows : The piece receiving the file : It is all kicked off with the following : Everything appears to be working except that the PostAsync never recognizes that task has been returned . I can see that the status of the await ... PostAsync ... task is WaitingForActivation but I 'm not entirely sure what that means ( remember , I 'm a n00b to this stuff ) . My file is saved to the correct location but the application never recognizes the response from my service.If someone could point me in the right direction , it would be much appreciated . public static async Task < string > UploadToService ( HttpPostedFile file , string authCode , int id ) { var memoryStream = new MemoryStream ( ) ; file.InputStream.CopyTo ( memoryStream ) ; var requestContent = new MultipartFormDataContent ( ) ; var fileContent = new ByteArrayContent ( memoryStream.ToArray ( ) ) ; fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse ( file.ContentType ) ; requestContent.Add ( fileContent , `` file '' , file.FileName ) ; using ( var httpClient = new HttpClient ( ) ) { httpClient.BaseAddress = new Uri ( BaseUrl ) ; httpClient.DefaultRequestHeaders.Accept.Clear ( ) ; var message = await httpClient.PostAsync ( string.Format ( `` Upload ? authCode= { 0 } & id= { 1 } '' , authCode , id ) , requestContent ) ; return await message.Content.ReadAsStringAsync ( ) ; } } [ HttpPost ] public Task < HttpResponseMessage > Upload ( string authCode , int id ) { var request = Request ; var provider = new CustomMultipartFormDataStreamProvider ( root ) ; var task = request.Content.ReadAsMultipartAsync ( provider ) .ContinueWith ( o = > { // ... // Save file // ... return new HttpResponseMessage ( ) { Content = new StringContent ( `` File uploaded successfully '' ) , StatusCode = HttpStatusCode.OK } ; } ) ; return task ; } protected void Page_Load ( object sender , EventArgs e ) { if ( IsPostBack ) { var file = HttpContext.Current.Request.Files [ 0 ] ; var response = UploadToService ( file , hiddenAuthCode.Value , int.Parse ( hiddenId.Value ) ) ; } }",Async Deadlock ? "C_sharp : Is it possible to define your keywords in C # ? I mean something like where important would be the new keyword . It would mean something like , for example , that if the type is null when compiling an error occurrs . So the example would produce an error . An example with no error would be public important Form newform ; public important Form newform = form1 ;",Define own keywords and meanings "C_sharp : I am trying to group a list by 2 fields ( Category , then Vendor ) , but at different values . If the category is `` 01 '' , sum all the cost . If the category is not `` 01 '' , group by the category , and then by the vendor.Some demo data : What I currently am doing : What I am trying to do ( aka my best guess ) : Desired Result : List < MyItem > myItemList = new List < MyItem > ( ) ; myItemList.Add ( new MyItem { Vendor= '' Ven1 '' , Cost=100 , Category= '' 01 '' } ) ; myItemList.Add ( new MyItem { Vendor= '' Ven2 '' , Cost=10 , Category= '' 02 '' } ) ; myItemList.Add ( new MyItem { Vendor= '' Ven3 '' , Cost=50 , Category= '' 02 '' } ) ) ; myItemList.Add ( new MyItem { Vendor= '' Ven2 '' , Cost=40 , Category= '' 01 '' } ) ; myItemList.Add ( new MyItem { Vendor= '' Ven2 '' , Cost=20 , Category= '' 01 '' } ) ; myItemList.Add ( new MyItem { Vendor= '' Ven3 '' , Cost=30 , Category= '' 02 '' } ) ; myItemList.Add ( new MyItem { Vendor= '' Ven1 '' , Cost=10 , Category= '' 03 '' } ) ; List < MyItem > groupedItems = myItemList.GroupBy ( a= > new { a.Category , a.Vendor } ) .Select ( b= > new MyItem { Vendor = b.First ( ) .Vendor , Cost = b.Sum ( c = > c.Cost ) , Category = b.First ( ) .Category } ) .ToList ( ) ; List < MyItem > groupedItems = myItemList.GroupBy ( a= > new { a.Category.Where ( z= > z.Category.Equals ( `` 01 : ) ) , a.Vendor } ) .Select ( b= > new MyItem { Vendor = b.First ( ) .Vendor , Cost = b.Sum ( c = > c.Cost ) , Category = b.First ( ) .Category } ) .ToList ( ) ; Category = `` 01 '' , Vendor = `` N/A `` , Cost = 160Category = `` 02 '' , Vendor = `` Ven2 '' , Cost = 10Category = `` 02 '' , Vendor = `` Ven3 '' , Cost = 80Category = `` 03 '' , Vendor = `` Ven1 '' , Cost = 10",LINQ grouping multiple fields only if one of the fields is a specific value "C_sharp : Create a console app to reproduce : It is compilable , but we will have the following at run time : An unhandled exception of type 'System.TypeLoadException ' occurred in mscorlib.dll . Additional information : Could not load type 'ConsoleApplication17.Test ' from assembly 'ConsoleApplication17 , Version=1.0.0.0 , Culture=neutral , PublicKeyToken=null'.This approach solves the problem : struct Test { public static readonly Test ? Null = null ; } class Program { static void Main ( string [ ] args ) { var t = Test.Null ; } } struct Test { public static Test ? Null = > null ; }",Does it look like a C # bug for you ? "C_sharp : As part of our internship we 've been tasked with creating a business application using Unity WebGL . After reading on interactions between JS and the C # code we 're in a corner.We 're trying to get back a list from C # to populate a Select on our webpage and we just do n't know how to do it . We 've followed the Unity documentation and can easily communicate and get back data to use in our C # from our webpage.We ca n't however access C # data in our browser . SendMessage ( ) method does not allow returns.Here 's our code so far index.htmljsfileC # code finallyYes we did check https : //docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html and I 've made numerous research and found some interesting resources that I ca n't wrap my head around being too inexperienced , for example http : //tips.hecomi.com/entry/2014/12/08/002719 To conclude , I would like to point out it 's our first `` real world '' project and Unity-WebGL is quite an experience to play with seeing the lack of documentation . < select id= '' wallsSelect '' > < /select > function getWallsList ( ) { //function is called at the creation of our object var wallsSelect = document.getElementById ( `` wallsSelect '' ) ; index = 0 ; var wallsList = gameInstance.SendMessage ( 'WallCreator ' , 'GetGameObjects ' ) ; //would like to get back our list of walls and populate our Select with it for ( item in wallsList ) { var newOption = document.createElement ( `` option '' ) ; newOption.value = index ; newOption.innerHTML = item ; wallsSelect.appendChild ( newOption ) ; index++ ; } public List < string > GetGameObjects ( ) { List < string > goNames = new List < string > ( ) ; foreach ( var item in goList ) { goNames.Add ( item.name ) ; } Debug.Log ( `` Accessed GetGameObjects method . GameObject count = `` + goNames.Count.ToString ( ) ) ; //The object is instanciated and return the right count number so it does work without a problem return goNames ; }",Access C # List from JavaScript "C_sharp : Probably a trivial question , but I 'm trying to get up to date with modern C # and I am overwhelmed with all the new features like pattern matching etc.With C # 8 , is there a new way to simplify the following common pattern , were I check a property for being non null and if so , store it in a var for use within the if scope ? That is : I could think of this : And this : Between these , I 'd still pick the 1st snippet . var item = _data.Item ; if ( item ! = null ) { // use item } if ( _data.Item is var item & & item ! = null ) { // use item } if ( _data.Item is Item item ) { // use item }",Check for null and assign to a variable at once in C # 8 "C_sharp : I work for a company that does ETL work on various databases . I am tasked with creating a patch for two full historical data sets on the client machine , which would then be sent over to our servers . This patch needs to be programmatic so that it can be called from our software.The datasets are simple text files . We have extraction software running on our client 's systems to perform the extraction . Extraction files range in size , up to 3GB+ . I have implemented a solution using Microsoft 's FC.exe , but it has limitations.I 'm using FC to produce the comparison file , then parsing it in perl on our side to extract the records that have been removed/updated , and those that have been added.FC works perfectly fine for me as long as the line of text does not exceed 128 characters . When that happens the output is put on to the next line of the comparison file , and so appears as an added/deleted record . I know that I could probably pre-process the files , but this will add a tremendous amount of time , probably defeating the purpose.I have tried using diffutils , but it complains about large files.I also toyed with some c # code to implement the patch process myself . This worked fine for small files , but was horribly inefficient when dealing with the big ones ( tested it on a 2.8 GB extract ) Are there any good command-line utilities or c # libraries that I can utilize to create this patch file ? Barring that , is there an algorithm that I can use to implement this myself ? Keep in mind that records may be updated , added , and deleted ( I know , it irks me too that the clients DELETE records , rather than marking them inactive . This is out of my control . ) Edit for clarity : I need to compare two separate database extracts from two different times . Usually these will be about one day apart.Given the below files : ( these will obviously be much longer and much wider ) Old.txtNew.txtThe expected output would be : abcde1f25 a3bc4de1fg 3 added4 added2 removedg added5 removed",Comparing HUGE ASCII Files "C_sharp : I have been working on a private project where i wanted to learn how to program on a windows phone , and at a point i started to fiddle with sockets and the camera , and a great idea came to mind video feed ( dumb me to even attempt ) . but now I 'm here , I have something that well , it works like a charm but a Lumia 800 can not chug through the for-loop fast enough . It sends a frame per lets say 7-8 seconds something i think is strange since well , it should be strong enough . It feels and looks like watching porn on a 56k modem without the porn.I also realized that a frame is 317000 pixels and that would sum up to roughly 1MB per frame I 'm also sending xy coordinates so mine takes up 2.3MB per frame still working on a different way to solve this to keep it down . so I 'm guessing i would need to do dome magic to make both position and pixel values of an acceptable size . because atm would i get5 it up at an acceptable speed it would require at least 60MB/s to get something like 30fps but thats a problem for another day.i have tried for simplicity to just send the pixels induvidialy using instead of the string parsing mess i have created ( to be fixed just wanted a proof of concept ) but to do the simple BitConverter did not speed it up to much.so now im on my last idea the UDP sender socket witch is rhoughly identical to the one on msdn 's library.All in all i have ended up on 3 solutionsAccept defeat ( but that wont happen so lets look at 2 ) Work down the amount of data sent ( destroys quality 640x480 is small enough i think ) Find the obvious problem ( Google and friend 's ran out of good ideas , thats why I 'm here ) //How many pixels to send per burst ( 1000 seems to be the best ) const int PixelPerSend = 1000 ; int bSize = 7 * PixelPerSend ; //Comunication thread UDP feed private void EthernetComUDP ( ) //Runs in own thread { //Connect to Server clientUDP = new SocketClientUDP ( ) ; int [ ] ImageContent = new int [ ( int ) cam.PreviewResolution.Height * ( int ) cam.PreviewResolution.Width ] ; byte [ ] PacketContent = new byte [ bSize ] ; string Pixel , l ; while ( SendingData ) { cam.GetPreviewBufferArgb32 ( ImageContent ) ; int x = 1 , y = 1 , SenderCount = 0 ; //In dire need of a speedup for ( int a = 0 ; a < ImageContent.Length ; a++ ) //this loop { Pixel = Convert.ToString ( ImageContent [ a ] , 2 ) .PadLeft ( 32 , ' 0 ' ) ; //A - removed to conserve bandwidth //PacketContent [ SenderCount ] = Convert.ToByte ( Pixel.Substring ( 0 , 8 ) , 2 ) ; //0 //R PacketContent [ SenderCount ] = Convert.ToByte ( Pixel.Substring ( 8 , 8 ) , 2 ) ; //8 //G PacketContent [ SenderCount + 1 ] = Convert.ToByte ( Pixel.Substring ( 16 , 8 ) , 2 ) ; //16 //B PacketContent [ SenderCount + 2 ] = Convert.ToByte ( Pixel.Substring ( 24 , 8 ) , 2 ) ; //24 //Coordinates //X l = Convert.ToString ( x , 2 ) .PadLeft ( 16 , ' 0 ' ) ; //X bit ( 1-8 ) PacketContent [ SenderCount + 3 ] = Convert.ToByte ( l.Substring ( 0 , 8 ) , 2 ) ; //X bit ( 9-16 ) PacketContent [ SenderCount + 4 ] = Convert.ToByte ( l.Substring ( 8 , 8 ) , 2 ) ; //Y l = Convert.ToString ( y , 2 ) .PadLeft ( 16 , ' 0 ' ) ; //Y bit ( 1-8 ) PacketContent [ SenderCount + 5 ] = Convert.ToByte ( l.Substring ( 0 , 8 ) , 2 ) ; //Y bit ( 9-16 ) PacketContent [ SenderCount + 6 ] = Convert.ToByte ( l.Substring ( 8 , 8 ) , 2 ) ; x++ ; if ( x == cam.PreviewResolution.Width ) { y++ ; x = 1 ; } SenderCount += 7 ; if ( SenderCount == bSize ) { clientUDP.Send ( ConnectToIP , PORT + 1 , PacketContent ) ; SenderCount = 0 ; } } } //Close on finish clientUDP.Close ( ) ; } BitConverter.GetBytes ( ImageContent [ a ] ) ; public string Send ( string serverName , int portNumber , byte [ ] payload ) { string response = `` Operation Timeout '' ; // We are re-using the _socket object that was initialized in the Connect method if ( _socket ! = null ) { // Create SocketAsyncEventArgs context object SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs ( ) ; // Set properties on context object socketEventArg.RemoteEndPoint = new DnsEndPoint ( serverName , portNumber ) ; // Inline event handler for the Completed event . // Note : This event handler was implemented inline in order to make this method self-contained . socketEventArg.Completed += new EventHandler < SocketAsyncEventArgs > ( delegate ( object s , SocketAsyncEventArgs e ) { response = e.SocketError.ToString ( ) ; // Unblock the UI thread _clientDone.Set ( ) ; } ) ; socketEventArg.SetBuffer ( payload , 0 , payload.Length ) ; // Sets the state of the event to nonsignaled , causing threads to block _clientDone.Reset ( ) ; // Make an asynchronous Send request over the socket _socket.SendToAsync ( socketEventArg ) ; // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds . // If no response comes back within this time then proceed _clientDone.WaitOne ( TIMEOUT_MILLISECONDS ) ; } else { response = `` Socket is not initialized '' ; } return response ; }",Windows Phone camera feed over UDP is `` horribly '' slow "C_sharp : I was digging around in MSDN and found this article which had one interesting bit of advice : Do not have public members that can either throw or not throw exceptions based on some option.For example : Now of course I can see that in 99 % of cases this would be horrible , but is its occasional use justified ? One case I have seen it used is with an `` AllowEmpty '' parameter when accessing data in the database or a configuration file . For example : In this case , the alternative would be to return null . But then the calling code would be littered with null references check . ( And the method would also preclude the ability to actually allow null as a specifically configurable value , if you were so inclined ) .What are your thoughts ? Why would this be a big problem ? Uri ParseUri ( string uriValue , bool throwOnError ) object LoadConfigSetting ( string key , bool allowEmpty ) ;",Throw/do-not-throw an exception based on a parameter - why is this not a good idea ? "C_sharp : Given the two methods : Why the M1 IL code use callvirt : and the M2 IL use call : I just can guess that it because in M2 we know that p is n't null and its likeIs it true ? If it is , what if p will be null in other thread ? static void M1 ( Person p ) { if ( p ! = null ) { var p1 = p.Name ; } } static void M2 ( Person p ) { var p1 = p ? .Name ; } IL_0007 : brfalse.s IL_0012IL_0009 : nopIL_000a : ldarg.0IL_000b : callvirt instance string ConsoleApplication4.Person : :get_Name ( ) brtrue.s IL_0007IL_0004 : ldnullIL_0005 : br.s IL_000dIL_0007 : ldarg.0IL_0008 : call instance string ConsoleApplication4.Person : :get_Name ( ) new MyClass ( ) .MyMethod ( ) ;",call instead of callvirt in case of the new c # 6 `` ? '' null check "C_sharp : I have the following method and am looking to write effective unit tests that also give me good coverage of the code paths : The Service and Logger objects used by the method are injected into the class constructor ( not shown ) . BeginRequest and EndRequest are implemented in a base class ( not shown ) . And Mapper is the AutoMapper class used for object-to-object mapping.My question is what are good , effective ways to write unit tests for a method such as this that also provides complete ( or what makes sense ) code coverage ? I am a believer in the one-test-one-assertion principal and use Moq for a mocking framework in VS-Test ( although I 'm not hung up on that part for this discusion ) . While some of the tests ( like making sure passing null results in an exception ) are obvious , I find myself wondering whether others that come to mind make sense or not ; especially when they are exercising the same code in different ways . public TheResponse DoSomething ( TheRequest request ) { if ( request == null ) throw new ArgumentNullException ( `` request '' ) ; BeginRequest ( request ) ; try { var result = Service.DoTheWork ( request.Data ) ; var response = Mapper.Map < TheResult , TheResponse > ( result ) ; return response ; } catch ( Exception ex ) { Logger.LogError ( `` This method failed . `` , ex ) ; throw ; } finally { EndRequest ( ) ; } }",Need help identifying what unit tests to write C_sharp : I know that it may sound like a weird question but this has been going on in my mind for a while . I know that the System.String type in C # is actually a class with a constructor that has a character array parameter . For example the following code is legal and causes no error : My question is that what makes is possible for the System.String class to accept an array of characters simply this way : System.String s = new System.String ( `` Hello '' .toCharArray ( ) ) ; System.String s = `` Hello '' ;,System.String Type in C # "C_sharp : This question has been puzzling me for a long time now . I come from a heavy and long C++ background , and since I started programming in C # and dealing with garbage collection I always had the feeling that such 'magic ' would come at a cost . I recently started working in a big MMO project written in Java ( server side ) . My main task is to optimize memory comsumption and CPU usage . Hundreds of thousands of messages per second are being sent and the same amount of objects are created as well . After a lot of profiling we discovered that the VM garbage collector was eating a lot of CPU time ( due to constant collections ) and decided to try to minimize object creation , using pools where applicable and reusing everything we can . This has proven to be a really good optimization so far.So , from what I 've learned , having a garbage collector is awesome , but you ca n't just pretend it does not exist , and you still need to take care about object creation and what it implies ( at least in Java and a big application like this ) .So , is this also true for .NET ? if it is , to what extent ? I often write pairs of functions like these : A second function is provided in case someone has an already made Envelope that may be reused to store the result , but I find this a little odd.I also sometimes write structs when I 'd rather use classes , just because I know there 'll be tens of thousands of instances being constantly created and disposed , and this feels really odd to me.I know that as a .NET developer I should n't be worrying about this kind of issues , but my experience with Java and common sense tells me that I should.Any light and thoughts on this matter would be much appreciated . Thanks in advance . // Combines two envelopes and the result is stored in a new envelope.public static Envelope Combine ( Envelope a , Envelope b ) { var envelope = new Envelope ( _a.Length , 0 , 1 , 1 ) ; Combine ( _a , _b , _operation , envelope ) ; return envelope ; } // Combines two envelopes and the result is 'written ' to the specified envelopepublic static void Combine ( Envelope a , Envelope b , Envelope result ) { result.Clear ( ) ; ... }",Should a programmer really care about how many and/or how often objects are created in .NET ? C_sharp : Assume that I have these two overloaded functions.Why will the compiler choose the float function ? public static void Main ( string [ ] args ) { int x=3 ; fn ( x ) ; } static void fn ( double x ) { Console.WriteLine ( `` Double '' ) ; } static void fn ( float x ) { Console.WriteLine ( `` Float '' ) ; },Method overloading . How does it work ? "C_sharp : Lets say I have a List < IEnumerable < double > > containing variable number of infinite sources of double numbers . Lets say they are all wave generator functions and I need to superimpose them into a single wave generator represented by IEnumerable < double > simply by taking the next number out of each and suming them . I know I can do this through iterator methods , something like this : however , it seems rather `` pedestrian '' . Is there a LINQ-ish way to achieve this ? public IEnumerable < double > Generator ( List < IEnumerable < double > > wfuncs ) { var funcs = from wfunc in wfuncs select wfunc.GetEnumerator ( ) ; while ( true ) { yield return funcs.Sum ( s = > s.Current ) ; foreach ( var i in funcs ) i.MoveNext ( ) ; } }",LINQ merge List < IEnumerable < T > > into one IEnumerable < T > by some rule "C_sharp : I am developing a Web API that in some cases will respond with 500 ( ugly design , I know , but ca n't do anything about it ) . In tests there 's an ApiFixture that contains AspNetCore.TestHost : When I am calling API endpoint with HttpClient from this fixture it should respond with 500 , instead I am getting exception that is being raised in the tested controller . I know that in tests it might be a nice feature , but I do n't want that - I want to test actual behavior of controller , which is returning internal server error . Is there a way to reconfigure TestServer to return response ? Code in controller action is irrelevant , can be throw new Exception ( ) ; public class ApiFixture { public TestServer ApiServer { get ; } public HttpClient HttpClient { get ; } public ApiFixture ( ) { var config = new ConfigurationBuilder ( ) .AddEnvironmentVariables ( ) .Build ( ) ; var path = Assembly.GetAssembly ( typeof ( ApiFixture ) ) .Location ; var hostBuilder = new WebHostBuilder ( ) .UseContentRoot ( Path.GetDirectoryName ( path ) ) .UseConfiguration ( config ) .UseStartup < Startup > ( ) ; ApiServer = new TestServer ( hostBuilder ) ; HttpClient = ApiServer.CreateClient ( ) ; } }",Configure AspNetCore TestServer to return 500 instead of throwing exception "C_sharp : The issue appears is when I have a class implementing an interface , and extending a class which implements an interface : Since typeof ( Some ) .GetInterfaces ( ) returns and array with ISome and ISomeBase , i 'm not able to distinguish if ISome is implemented or inherited ( as ISomeBase ) . As MSDN I ca n't assume the order of the interfaces in the array , hence I 'm lost . The method typeof ( Some ) .GetInterfaceMap ( ) does not distinguish them either . class Some : SomeBase , ISome { } class SomeBase : ISomeBase { } interface ISome { } interface ISomeBase { }",How do I know when an interface is directly implemented in a type ignoring inherited ones ? "C_sharp : I 'm having a struggle understanding these two concepts . But I think after many videos and SO QA 's , I have it distilled down to its simplest form : Covariant - Assumes a sub-type can do what its base-type does.Contravariant - Assumes you can treat a sub-type the same way you would treat its base-type . Supposing these three classes : CovariantAny animal can do what animals do.Assumes a sub-type can do what its base-type does.ContravariantAnything you can do to an animal , you can do to any animal.Assumes you can treat a sub-type the same way you would treat its base-type.Is this correct ? It seems like at the end of the day , what covariance and contravariance allow you to do is simply use behavior you would naturally expect , i.e . every type of animal has all animal characteristics , or more generally - all sub-types implement all features of their base-type . Seems like it 's just allowing for the obvious - they just support different mechanisms that allow you to get at that inherited behavior in different ways - one converts from sub-type to base-type ( Covariance ) and the other converts from base-type to sub-type ( Contravariance ) , but at its very core , both are just allowing behavior of the base class to be invoked.For example in the cases above , you were just allowing for the fact that the Cat and the Dog sub-types of Animal both have the methods Live and Die - which they very naturally inherited from their base class Animal.In both cases - covariance and contravariance - we are allowing for invocation of general behavior that is guaranteed because we have made sure that the target the behavior is being invoked on inherits from a specific base class.In the case of Covariance , we are implicitly casting a sub-type to its base-type and calling the base-type behavior ( does n't matter if the base-type behavior is overridden by the sub-type ... the point is , we know it exists ) .In the case of Contravariance , we are taking a sub-type and passing it to a function we know only invokes base-type behavior ( because the base-type is the formal parameter type ) , so we are safe to cast the base-type to a sub-type . class Animal { void Live ( Animal animal ) { //born ! } void Die ( Animal animal ) { //dead ! } } class Cat : Animal { } class Dog : Animal { } Animal anAnimal = new Cat ( ) ; anAnimal.Live ( ) ; anAnimal.Die ( ) ; Animal anotherAnimal = new Dog ( ) ; anotherAnimal.Live ( ) ; anotherAnimal.Die ( ) ; Action < Animal > kill = KillTheAnimal ; Cat aCat = new Cat ( ) ; KillTheCat ( kill , aCat ) ; Dog = new Dog ( ) ; KillTheDog ( kill , aDog ) ; KillTheCat ( Action < Cat > action , Cat aCat ) { action ( aCat ) ; } KillTheDog ( Action < Dog > action , Dog aDog ) { action ( aDog ) ; } void KillTheAnimal ( Animal anAnimal ) { anAnimal.Die ( ) ; }",Covariance and Contravariance - Just different mechanisms for invoking guaranteed base class behavior ? "C_sharp : I am trying to make a ( very ) simple Data Binding test , but it does n't work as I expected ... Say I have the following classes : I did n't add the designer code , but its there , and the form holds a TextBox object and a CheckBox object . As you can understand , I am trying to make the Textbox Text property change as the user checks \ unchecks the CheckBox . But this code does n't update the TextBox Text property . Can someone please explain me what am I missing ? // this class represents some kind of data producerpublic class DataSourceClass { public string Data { get ; set ; } public DataSourceClass ( ) { } } //this form holds the TextBox control as the Data consumerpublic partial class DatabindingTestForm : Form { public DataSourceClass ds { get ; set ; } public DatabindingTestForm ( ) { InitializeComponent ( ) ; ds = new DataSourceClass ( ) ; textBox.DataBindings.Add ( `` Text '' , ds , `` Data '' ) ; } private void checkBox_CheckedChanged ( object sender , EventArgs e ) { if ( checkBox.Checked ) ds.Data = `` CHECKED '' ; else ds.Data = `` NOT CHECKED '' ; } }",Simple DataBinding "C_sharp : I was looking at a code in an application ( Someone else wrote it ) , on some cases it worked fine and on some cases it gave exceptions , it was actually converting strings in datetime , here is the codeA Confusing thoughtHow does this string `` 3.5000 '' ( it matches the 1.5000 pattern ) evaluates , does this means 3-3-5000 or 1-3-5000 , the format is ambiguous its unclear and confusing ! My questions are , What kind of formats can DateTime.Parse expects ? Whats happening in the code above ? Suggestions to improve the code ? //5000 is the year , but what about `` 1 '' is it month or day ? , if its month//then what about the day ? DateTime time = DateTime.Parse ( `` 1.5000 '' ) ; //1.5000 does n't looks a date to me ? time.ToString ( ) ; //returns `` 1/1/5000 12:00:00 AM '' //where as if I give this string to DateTime.Parse ( ) ; time = DateTime.Parse ( `` 2341.70 '' ) ; //FormatException was unhandled//String was not recognized as a valid DateTime .",DateTime.Parse can format unusual format strings ? "C_sharp : As the title suggests , is this test name just a little of the top ? Any suggestions on how to improve this ? or is it fine as it is ? Below is the whole test fixture as it stands so you can get some context : ) WhenChargeIsGreaterThanRestingChargeButLessThanChargeRestApproachStep_OnUpdate_ChargeIsSetToRestingCharge public class NeuronTests { [ Fact ] public void OnUpdate_NeuronFiresWhenChargeIsEqualToThreshold ( ) { Neuron neuron = new Neuron ( ) ; bool fired = false ; neuron.Fired += ( s , e ) = > fired = true ; neuron.Charge = Neuron.ChargeThreshold ; neuron.Update ( ) ; Assert.True ( fired , `` Neuron did n't fire '' ) ; } [ Fact ] public void OnUpdate_NeuronDoesntFireWhenChargeIsLessThanThreshold ( ) { Neuron neuron = new Neuron ( ) ; bool fired = false ; neuron.Fired += ( s , e ) = > fired = true ; neuron.Charge = Neuron.ChargeThreshold - 1f ; neuron.Update ( ) ; Assert.False ( fired , `` Neuron fired ! `` ) ; } [ Fact ] public void OnUpdate_NeuronFiresWhenChargeIsGreaterThanThreshold ( ) { Neuron neuron = new Neuron ( ) ; bool fired = false ; neuron.Fired += ( s , e ) = > fired = true ; neuron.Charge = Neuron.ChargeThreshold + 1f ; neuron.Update ( ) ; Assert.True ( fired , `` Neuron did n't fire '' ) ; } [ Fact ] public void WhenNeuronFires_ChargeResetsToRestingCharge ( ) { Neuron neuron = new Neuron ( ) ; neuron.Charge = Neuron.ChargeThreshold ; neuron.Update ( ) ; Assert.Equal ( Neuron.RestingCharge , neuron.Charge ) ; } [ Fact ] public void AfterFiring_OnUpdate_NeuronWontFire ( ) { Neuron neuron = new Neuron ( ) ; int fireCount = 0 ; neuron.Fired += ( s , e ) = > fireCount++ ; neuron.Charge = Neuron.ChargeThreshold ; neuron.Update ( ) ; neuron.Charge = Neuron.ChargeThreshold ; neuron.Update ( ) ; Assert.Equal ( 1 , fireCount ) ; } [ Fact ] public void WhenResting_OnUpdate_NeuronWillFire ( ) { Neuron neuron = new Neuron ( ) ; int fireCount = 0 ; neuron.Fired += ( s , e ) = > fireCount++ ; neuron.Charge = Neuron.ChargeThreshold ; neuron.Update ( ) ; neuron.Charge = Neuron.ChargeThreshold ; neuron.Update ( ) ; neuron.Charge = Neuron.ChargeThreshold ; neuron.Update ( ) ; Assert.Equal ( 2 , fireCount ) ; } [ Fact ] public void WhenChargeIsGreaterThanRestingCharge_OnUpdate_ChargeDecreasesTowardsRestingCharge ( ) { Neuron neuron = new Neuron ( ) ; neuron.Charge = Neuron.RestingCharge + ( 2 * Neuron.ChargeRestApproachStep ) ; neuron.Update ( ) ; Assert.Equal ( Neuron.RestingCharge + Neuron.ChargeRestApproachStep , neuron.Charge ) ; } [ Fact ] public void WhenChargeIsGreaterThanRestingChargeButLessThanChargeRestApproachStep_OnUpdate_ChargeIsSetToRestingCharge ( ) { Neuron neuron = new Neuron ( ) ; neuron.Charge = Neuron.RestingCharge + ( Neuron.ChargeRestApproachStep * 0.5f ) ; neuron.Update ( ) ; Assert.Equal ( Neuron.RestingCharge , neuron.Charge ) ; } }",Is this test name just a bit over the top "C_sharp : Why creating struct with constructor more slower than direct assignment ? In code below I get 10 second with custom constructor and 6 second without ! Pure cycle take a 5 second . Custom constructor five ( ! sic ) times slower than direct access.Is there any hack or something to speed up a custom constructor ? class Program { public struct Point { public int x , y ; public Point ( int x , int y ) { this.x = x ; this.y = y ; } } static void Main ( string [ ] args ) { Stopwatch sw = new Stopwatch ( ) ; sw.Start ( ) ; for ( int i =0 ; i < int.MaxValue ; i++ ) { var a = new Point ( i , i ) ; } sw.Stop ( ) ; Console.WriteLine ( sw.ElapsedMilliseconds ) ; sw.Restart ( ) ; for ( int i = 0 ; i < int.MaxValue ; i++ ) { var a = new Point ( ) ; a.x = i ; a.y = i ; } sw.Stop ( ) ; Console.WriteLine ( sw.ElapsedMilliseconds ) ; Console.ReadLine ( ) ; } }",C # : struct constructor performance "C_sharp : Hello here is how i get value from dictionary myage value after C # 7 Okey result is:20But Before C # 7 how can i get myage value from dictionary . I could't find any other way.Just i found declare myage in trygetvalue method . static void Main ( string [ ] args ) { List < User > userlist = new List < User > ( ) ; User a = new User ( ) ; a.name = `` a '' ; a.surname = `` asur '' ; a.age = 19 ; User b = new User ( ) ; b.name = `` b '' ; b.surname = `` bsur '' ; b.age = 20 ; userlist.Add ( a ) ; userlist.Add ( b ) ; var userlistdict = userlist.ToDictionary ( x = > x.name , x= > new { x.surname , x.age } ) ; if ( userlistdict.TryGetValue ( `` b '' , out var myage ) ) //myage Console.WriteLine ( myage.age ) ; } } public class User { public string name { get ; set ; } public string surname { get ; set ; } public int age { get ; set ; } }",C # ToDictionary get Anonymous Type value before C # 7 "C_sharp : Does this give any code smell or violate SOLID principles ? As you can see , my Summarize ( ) is tied to implementation classes such as Human , Animal , etc . Is this code violating LSP ? ( Any other SOLID principles ? ) public string Summarize ( ) { IList < IDisplayable > displayableItems = getAllDisplayableItems ( ) ; StringBuilder summary = new StringBuilder ( ) ; foreach ( IDisplayable item in displayableItems ) { if ( item is Human ) summary.Append ( `` The person is `` + item.GetInfo ( ) ) ; else if ( item is Animal ) summary.Append ( `` The animal is `` + item.GetInfo ( ) ) ; else if ( item is Building ) summary.Append ( `` The building is `` + item.GetInfo ( ) ) ; else if ( item is Machine ) summary.Append ( `` The machine is `` + item.GetInfo ( ) ) ; } return summary.ToString ( ) ; }",Tying a method to implementation classes "C_sharp : I have written the following resizing algorithm which can correctly scale an image up or down . It 's far too slow though due to the inner iteration through the array of weights on each loop . I 'm fairly certain I should be able to split out the algorithm into two passes much like you would with a two pass Gaussian blur which would vastly reduce the operational complexity and speed up performance . Unfortunately I ca n't get it to work . Would anyone be able to help ? Weights and indices are calculated as follows . One for each dimension : Each IResampler provides the appropriate series of weights based on the given index . the bicubic resampler works as follows.Here 's an example of an image resized by the existing algorithm . The output is correct ( note the silvery sheen is preserved ) .Original imageImage halved in size using the bicubic resampler.The code is part of a much larger library that I am writing to add image processing to corefx . Parallel.For ( startY , endY , y = > { if ( y > = targetY & & y < targetBottom ) { Weight [ ] verticalValues = this.verticalWeights [ y ] .Values ; for ( int x = startX ; x < endX ; x++ ) { Weight [ ] horizontalValues = this.horizontalWeights [ x ] .Values ; // Destination color components Color destination = new Color ( ) ; // This is where there is too much operation complexity . foreach ( Weight yw in verticalValues ) { int originY = yw.Index ; foreach ( Weight xw in horizontalValues ) { int originX = xw.Index ; Color sourceColor = Color.Expand ( source [ originX , originY ] ) ; float weight = yw.Value * xw.Value ; destination += sourceColor * weight ; } } destination = Color.Compress ( destination ) ; target [ x , y ] = destination ; } } } ) ; /// < summary > /// Computes the weights to apply at each pixel when resizing./// < /summary > /// < param name= '' destinationSize '' > The destination section size. < /param > /// < param name= '' sourceSize '' > The source section size. < /param > /// < returns > /// The < see cref= '' T : Weights [ ] '' / > ./// < /returns > private Weights [ ] PrecomputeWeights ( int destinationSize , int sourceSize ) { IResampler sampler = this.Sampler ; float ratio = sourceSize / ( float ) destinationSize ; float scale = ratio ; // When shrinking , broaden the effective kernel support so that we still // visit every source pixel . if ( scale < 1 ) { scale = 1 ; } float scaledRadius = ( float ) Math.Ceiling ( scale * sampler.Radius ) ; Weights [ ] result = new Weights [ destinationSize ] ; // Make the weights slices , one source for each column or row . Parallel.For ( 0 , destinationSize , i = > { float center = ( ( i + .5f ) * ratio ) - 0.5f ; int start = ( int ) Math.Ceiling ( center - scaledRadius ) ; if ( start < 0 ) { start = 0 ; } int end = ( int ) Math.Floor ( center + scaledRadius ) ; if ( end > sourceSize ) { end = sourceSize ; if ( end < start ) { end = start ; } } float sum = 0 ; result [ i ] = new Weights ( ) ; List < Weight > builder = new List < Weight > ( ) ; for ( int a = start ; a < end ; a++ ) { float w = sampler.GetValue ( ( a - center ) / scale ) ; if ( w < 0 || w > 0 ) { sum += w ; builder.Add ( new Weight ( a , w ) ) ; } } // Normalise the values if ( sum > 0 || sum < 0 ) { builder.ForEach ( w = > w.Value /= sum ) ; } result [ i ] .Values = builder.ToArray ( ) ; result [ i ] .Sum = sum ; } ) ; return result ; } /// < summary > /// Represents the weight to be added to a scaled pixel./// < /summary > protected class Weight { /// < summary > /// The pixel index . /// < /summary > public readonly int Index ; /// < summary > /// Initializes a new instance of the < see cref= '' Weight '' / > class . /// < /summary > /// < param name= '' index '' > The index. < /param > /// < param name= '' value '' > The value. < /param > public Weight ( int index , float value ) { this.Index = index ; this.Value = value ; } /// < summary > /// Gets or sets the result of the interpolation algorithm . /// < /summary > public float Value { get ; set ; } } /// < summary > /// Represents a collection of weights and their sum./// < /summary > protected class Weights { /// < summary > /// Gets or sets the values . /// < /summary > public Weight [ ] Values { get ; set ; } /// < summary > /// Gets or sets the sum . /// < /summary > public float Sum { get ; set ; } } /// < summary > /// The function implements the bicubic kernel algorithm W ( x ) as described on/// < see href= '' https : //en.wikipedia.org/wiki/Bicubic_interpolation # Bicubic_convolution_algorithm '' > Wikipedia < /see > /// A commonly used algorithm within imageprocessing that preserves sharpness better than triangle interpolation./// < /summary > public class BicubicResampler : IResampler { /// < inheritdoc/ > public float Radius = > 2 ; /// < inheritdoc/ > public float GetValue ( float x ) { // The coefficient . float a = -0.5f ; if ( x < 0 ) { x = -x ; } float result = 0 ; if ( x < = 1 ) { result = ( ( ( 1.5f * x ) - 2.5f ) * x * x ) + 1 ; } else if ( x < 2 ) { result = ( ( ( ( ( a * x ) + 2.5f ) * x ) - 4 ) * x ) + 2 ; } return result ; } }",Split resize algorithm into two passes "C_sharp : In class we have being dealing with generics and were asked to complete an assignment.We created an Account < T > class with one property private T _balance ; and then had to write methods to credit and debit _balance.Credit method ( partial ) called from Main by e.g . acc1.Credit ( 4.6 ) ; : I had to condition check and cast as I can not _balance += ( T ) balanceObject ; as this will give the error `` Operator '+ ' can not be applied to operand of type 'T ' '' During my reading on the subject I discovered the dynamic type . In my new Account class I added a new method and changed the Credit method to : ( called from Main by e.g . acc1.Credit ( 4.6 ) ; ) This is what I do n't understand . The credit method takes in the object as type dynamic and the ConvertType ( object input ) returns it as type T. Why does using dynamic type allow me to use operators on generics ? public void Credit ( T credit ) { Object creditObject = credit ; Object balanceObject = _balance ; Type creditType = creditObject.GetType ( ) ; Type balanceType = balanceObject.GetType ( ) ; if ( creditType.Equals ( balanceType ) ) { if ( creditType.Equals ( typeof ( double ) ) ) { balanceObject= ( double ) balanceObject + ( double ) creditObject ; } ... WITH more else if 's on int , float and decimal . } _balance = ( T ) balanceObject ; } public void Credit ( dynamic credit ) { _balance += ConvertType ( credit ) ; } public T ConvertType ( object input ) { return ( T ) Convert.ChangeType ( input , typeof ( T ) ) ; }","In C # , why does using dynamic type allow me to use operators on generics ?" "C_sharp : I am using c # .I have following string My aim is to fill the following list from the above string.class1 has two properties , It should fill P1 in parent and P11 , P12 , P13 , P14 in children , and make a list of them.Any suggestion will be helpful.Edit Samplethe values are hard coded here , but it would be dynamic . < li > < a href= '' abc '' > P1 < /a > < ul > < li > < a href = `` bcd '' > P11 < /a > < /li > < li > < a href = `` bcd '' > P12 < /a > < /li > < li > < a href = `` bcd '' > P13 < /a > < /li > < li > < a href = `` bcd '' > P14 < /a > < /li > < /ul > < /li > < li > < a href= '' abc '' > P2 < /a > < ul > < li > < a href = `` bcd '' > P21 < /a > < /li > < li > < a href = `` bcd '' > P22 < /a > < /li > < li > < a href = `` bcd '' > P23 < /a > < /li > < /ul > < /li > < li > < a href= '' abc '' > P3 < /a > < ul > < li > < a href = `` bcd '' > P31 < /a > < /li > < li > < a href = `` bcd '' > P32 < /a > < /li > < li > < a href = `` bcd '' > P33 < /a > < /li > < li > < a href = `` bcd '' > P34 < /a > < /li > < /ul > < /li > < li > < a href= '' abc '' > P4 < /a > < ul > < li > < a href = `` bcd '' > P41 < /a > < /li > < li > < a href = `` bcd '' > P42 < /a > < /li > < /ul > < /li > List < class1 > string parent ; List < string > children ; public List < class1 > getElements ( ) { List < class1 > temp = new List < class1 > ( ) ; foreach ( // < a > element in string ) { //in the recursive loop List < string > str = new List < string > ( ) ; str.add ( `` P11 '' ) ; str.add ( `` P12 '' ) ; str.add ( `` P13 '' ) ; str.add ( `` P14 '' ) ; class1 obj = new class1 ( `` P1 '' , str ) ; temp.add ( obj ) ; } return temp ; }",Recursive searching a pattern in a string "C_sharp : I created SubCtrl inheriting UserControl . It has no code.I created then Ctrl , which also inherits UserControl . It has a SubCtrl in it and its only code means to expose it publicly so it appears in the property list of Ctrl : Then I created a simple Form project which only has a Ctrl in it and no code.As I wanted , SUBCTRL appears in the property list of Ctrl so I can change things . I changed the background color ( say , to red ) , and the subctrl turned red in the designer.But magically , when I run the project , it turns back to the standard gray . It appears that no code is generated in Form1.Designer.cs to change SUBCTRL 's back color to red . If I write it by hand , it works , but that 's not what I want . It should be automatic , obviously.The Ctrl , on the other hand , behaves normally . The code is generated and everything works happily.What 's wrong with the subcontrol ? public subctrl.SubCtrl SUBCTRL { get { return this.subCtrl1 ; } }",Designer does not generate code for a property of a subcontrol . Why ? "C_sharp : I 've been experimenting with C # script ( *.csx ) to do some data processing with the results of service calls to some internal APIs . It 's been pretty smooth thus far , but I 'm now trying to call some methods from a C # project I have access to . The C # project does n't have a published nuget package , which means referencing the dll directly using # r. However in order to access the necessary functions , I 've found I also need to add references to the top of my script for any of that projects dependencies and any nuget packages that dependency uses.I 'm new to the C # scripting world , and did n't find anything directly addressing this question so hopefully I 'm not asking something super obvious here . Some projects depend on a pretty large number of nuget packages , is there a way to reference a csproj from a C # script that does n't require explicitly referencing all of the dependencies for the project ? Let me know if there 's any additional information I can provide . # r `` PATH_TO_SOLUTION\Project\bin\Debug\netstandard2.0\binary.dll '' # r `` PATH_TO_SOLUTION\ProjectDependency\bin\Debug\netstandard2.0\dependent.dll '' # r `` nuget : Some.Dependency , 11.0.2 '' # r `` nuget : Some.Other.Dependency , 10.0.2 '' # r `` nuget : Some.Third.Dependency , 9.0.2 '' using Project ;",Referencing a local csproj from a C # script "C_sharp : Given a very basic LINQ that is returned to a MVC view , at what exact point does the deferred execution fire ? In the controller : In the model : The query is not executed when we call _fooService.GetAll ( ) of course , but is deferred to some later point - but at which exact point is it executed ? The return View ( model ) ; statement in the controller ( does n't look like it ) ? The @ foreach ( var item in Model ) line in the view ? The first time the @ item.Bar line in the view is hit ? Something else that occurs in between return View ( model ) ; and the view being rendered ? public ActionResult Index ( ) { var model = _fooService.GetAll ( ) ; return View ( model ) ; } @ foreach ( var item in Model ) { < tr > < td > @ item.Bar < /td > < /tr > }","Does LINQ deferred execution occur when rendering the view , or earlier ?" "C_sharp : ReSharper has trouble resolving a name of the collection if it appears in a method description , referenced by cref attributed.For instance in this signature ReSharper underlines the word Dictionary : When I hover over highlighted area it says Can not resolve symbol 'Dictionary ' . The file has a reference to System.Collections.Generic . The same happens for IEnumerable and for List.It does n't have any influence on code , does n't prevent compiling or anything . Still I prefer to keep my files cleaned and I do n't think ReSharper should have problems resolving names in comments in the first place.I 'm using ReSharper 8.0 . Any suggestion how to fix this or how to change my comments to get rid of this `` unresolved '' warning highly appreciated . /// < summary > /// The reconstruct in single account./// < /summary > /// < param name= '' programId '' > /// The program id./// < /param > /// < returns > /// The < see cref= '' Dictionary '' / > . // < -- here the `` Dictionary '' is underlined/// < /returns > Dictionary < long , Account > ReconstructInSingleAccount ( long programId ) { }",ReSharper can not resolve collection type in comments "C_sharp : My understanding of a factory is that it encapsulates instantiation of concrete classes that all inherit a common abstract class or interface . This allows the client to be decoupled from the process of determining which concrete class to create , which in turn means you can add or remove concrete classes from your program without having to change the client 's code . You might have to change the factory , but the factory is `` purpose built '' and really only has one reason to change -- a concrete class has been added/removed.I have built some classes that do in fact encapsulate object instantiation but for a different reason : the objects are hard to instantiate . For the moment , I 'm calling these classes `` factories '' , but I 'm concerned that might be a misnomer and would confuse other programmers who might look at my code . My `` factory '' classes do n't decide which concrete class to instantiate , they guarantee that a series of objects will be instantiated in the correct order and that the right classes will be passed into the right constructors when I call new ( ) .For example , for an MVVM project I 'm working on , I wrote a class to ensure that my SetupView gets instantiated properly . It looks something like this : Is it confusing to call this a `` factory '' ? It does n't decide among several possible concrete classes , and its return type is not an interface or abstract type , but it does encapsulate object instantiation.If it 's not a `` factory '' , what is it ? EditA number of people have suggested that this is actually the Builder Pattern.The definition of the Builder Pattern from dofactory is as follows : Separate the construction of a complex object from its representation so that the same construction process can create different representations.This seems like a little bit of a stretch also . The thing that bothers me is the `` different representations '' . My purpose is not to abstract the process of building a View ( not that that is n't a worthy goal ) . I 'm simply trying to put the logic for creating a specific view in one place , so that if any of the ingredients or the process for creating that view change , I only have to change this one class . The builder pattern really seems to be saying , `` Let 's create a general process for making Views , then you can follow that same basic process for any View you create . '' Nice , but that 's just not what I 'm doing here.Edit 2I just found an interesting example in a Wikipedia article on Dependency Injection.Under `` Manually Injected Dependency '' , it contains the following class : This is almost exactly the usage I have ( and , no , I did not write the wiki article : ) ) .Interestingly , this is the comment following this code : In the code above , the factory takes responsibility for assembling the car , and injects the engine into the car . This frees the car from knowing about how to create an engine , though now the CarFactory has to know about the engine 's construction . One could create an EngineFactory , but that merely creates dependencies among factories . So the problem remains , but has at least been shifted into factories , or builder objects . [ my emphasis ] So , this tells me that at least I 'm not the only one who 's thought of creating a class to help with injecting stuff into another class , and I 'm not the only one who attempted to name this class a factory . public class SetupViewFactory { public SetupView CreateView ( DatabaseModel databaseModel , SettingsModel settingsModel , ViewUtilities viewUtilities ) { var setupViewModel = new SetupViewModel ( databaseModel , settingsModel , viewUtilities ) ; var setupView = new SetupView ( ) ; setupView.DataContext = setupViewModel ; return setupView ; } } public class CarFactory { public static Car buildCar ( ) { return new Car ( new SimpleEngine ( ) ) ; } }",Is it confusing to call this class a `` factory '' ? C_sharp : I 'm using [ EnableQuery ] ( System.Web.Http.OData ) in ASP.NET API 2 controllers to enable OData v3 filtering/sorting/paging . I 've noticed that using the $ orderby clause returns data that is sorted as follows ( here are some examples - they are strings and do n't necessarily have a pattern to them ) : When I need natural sorting : How can I enable this kind of sorting ? Are there any extension points that I could use to provide my own sort logic ? LoadTest1000_1LoadTest1000_10LoadTest1000_1000LoadTest1000_2LoadTest1000_20 [ etc ] LoadTest1000_1LoadTest1000_2LoadTest1000_10LoadTest1000_20LoadTest1000_1000LoadTest1000_2000 [ etc ],Natural Sorting in OData $ orderby Query "C_sharp : I 've got code like this : I need to wrap similar code around a lot more objects and their methods to do some performance profiling . I 'm not allowed to use 3rd party plugins or software , etc . I 'd really rather not write this same code around all of these method calls this all of this logging code . How would you refactor this to eliminate some of my coding effort ? If I 'm not being very clear , please ask questions in the comments and I will try to clarify.Thanks for any help ! ! Logger logger = new Logger ( ) ; System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch ( ) ; logger.LogInformation ( `` Calling SomeObject.SomeMethod at `` + DateTime.Now.ToString ( ) ) ; stopWatch.Start ( ) ; // This is the method I 'm interested in.SomeResponse response = someObject.SomeMethod ( someParam ) ; stopWatch.Stop ( ) ; logger.LogInformation ( `` SomeObject.SomeMethod returned at `` + DateTime.Now.ToString ( ) ) ; logger.LogInformation ( `` SomeObject.SomeMethod took `` + stopWatch.ElapsedMilliseconds + `` milliseconds . `` ) ;","How would you refactor this smelly code ? ( Logging , Copy and Paste , .Net 3.5 )" "C_sharp : Refactoring is good , but sometimes it is not so easy to work out how to refactor and indeed whether something can actually be refactored ! I have a number of methods which are almost identical - I can refactor them but one part of the refactoring is beyond my logic.Here are two un-refactored methods : With Refactoring I would get a method like this that the previously un-refactored methods would callSo what we have an almost completely refactored method - with one problem , How can I tell which form I wish to instantiate from the frmName variable ? private void projectToolStripMenuItem_Click ( object sender , EventArgs e ) { if ( projectToolStripMenuItem.Checked ) { projectToolStripMenuItem.Checked = false ; if ( ! projectForm.IsDisposed ) projectForm.Hide ( ) ; } else { if ( projectForm.IsDisposed ) projectForm = new frmProject ( ) ; projectForm.Show ( dockPanel , DockState.DockRight ) ; projectToolStripMenuItem.Checked = true ; } } private void logginToolStripMenuItem_Click ( object sender , EventArgs e ) { if ( logginToolStripMenuItem.Checked ) { logginToolStripMenuItem.Checked = false ; if ( ! outputForm.IsDisposed ) outputForm.Hide ( ) ; } else { if ( outputForm.IsDisposed ) outputForm = new frmOutput ( ) ; outputForm.Show ( dockPanel , DockState.DockBottom ) ; logginToolStripMenuItem.Checked = true ; } } private void refactoredMethod ( TooStripMenuItem menuItem , DockContent frmName ) { if ( menuItem.Checked ) { menuItem.Checked = false ; if ( ! frmName.IsDisposed ) frmName.Hide ( ) ; } else { if ( frmName.IsDisposed ) frmName= new frmProject ( ) ; // Still Problematic frmName.Show ( dockPanel , DockState.DockRight ) ; menuItem.Checked = true ; } }",c # Refactoring two nearly identical Methods "C_sharp : I want to programmatically find out what the default binding mode of a property will be.For example , if I check it against TextBox.TextProperty it should be BindingMode.TwoWay , but if it is ItemsControl.ItemsSourceProperty it should be BindingMode.OneWay.I implemented a custom MarkupExtension and have gotten this far in my code so far : public override object ProvideValue ( IServiceProvider provider ) { var service = provider.GetService ( typeof ( IProvideValueTarget ) ) as IProvideValueTarget ; if ( service ! = null ) { var target = service.TargetObject as DependencyObject ; var property = service.TargetProperty as DependencyProperty ; // Not sure what to do with the target and propery here ... } }",How do you get the default binding mode of a dependency property ? "C_sharp : What is the difference between the nuget packages HangFire.AspNetCore and HangFire and HangFire.core ? It seems I am able to use hangfire with a ASP .NET MVC Core project with only the HangFire 1.6.21 package alone . See below packages used in my project : What is then the package HangFire.AspNetCore for ? I am working with Visual Studio Code on Ubuntu , and I added the packages using : dotnet add package Hangfiredotnet add package Hangfire.AspNetCore",What is the difference between the nuget packages hangfire.aspnetcore and hangfire and hangfire.core ? "C_sharp : I want to know if I can tell what appdomain a object was created in . This is for a unit test but also useful general knowledge . I have the following pieces of code ( this is example code for illustration ) .I then callWhat I would like to be able to do is find out what AppDomain method on myFoo will be called in , to test that the Create method had actually created a new AppDomain . I realise that I can add a method on Foo like This would provide me the appdomain that Foo is running in . I do n't think this is an elegant solution just for a unit test . It would be great if someone could help define a method like.EDIT : Thanks for the responses and comments . The question I have asked has been answered and the comments have helped me realised where I was going wrong . What I really was trying to achieve is to test that a new AppDomain is created . public Foo Create ( ) { AppDomainSetup appDomainSetup = new AppDomainSet { ApplicationBase = @ '' z : \SomePath '' } AppDomain appDomain = AppDomain.CreateDomain ( `` DomainName '' , null , appDomainSetup ) ; return ( Foo ) appDomain.CreateInstanceAndUnwrap ( `` MyAssembly '' , `` MyClass '' ) ; } Foo myFoo = Create ( ) ; public class Foo { public string appDomainName { get { return AppDomain.CurrentDomain.FriendlyName ; } } } public string GetAppDomainNameWithDotNetWitchcraft ( Foo myFoo ) { // Insert voodoo here . }",Is it possible to tell if an object is running in a different AppDomain ? "C_sharp : I 'm currently creating an application in C # 4.0 with EntityFramework 6.0.I 'm trying to retrieve a list of item from the database but the problem is that the SQL query generated by the EF framework does n't include the where clause.So , the entire table/view is loaded in memory and it takes about 10 seconds to get just 2 or 3 items.Below , the method from my GenericRepostitory : And I call it like this : The return result is good but it takes around 10 seconds to be retrieved.And when the debug writes the generated SQL query , the where clause is nowhereHow can I modify my function GetList to include the where clause ? I hope I was enough clear with these informations and I 'm sorry for my english.It 's not my native language : /Anyway , thank your for your help public IList < TEntity > GetList ( Func < TEntity , bool > where , params Expression < Func < TEntity , object > > [ ] navigationProperties ) { using ( var dbContextScope = contextScopeFactory.CreateReadOnly ( ) ) { IQueryable < TEntity > dbQuery = Context.Set < TEntity > ( ) .AsQueryable ( ) ; foreach ( Expression < Func < TEntity , object > > navigationProperty in navigationProperties ) dbQuery = dbQuery.Include < TEntity , object > ( navigationProperty ) ; var list = dbQuery .AsNoTracking ( ) .Where ( where ) ; Context.Database.Log = s = > Debug.WriteLine ( s ) ; return list.ToList < TEntity > ( ) ; } } var repository = repositoryFactory.Get < Context , Entity > ( ) ; var items = repository.GetList ( x = > x.FakeID < = 10 ) ;",Where clause not included in SQL query "C_sharp : I have two servers connecting to a PostgresSQL 9.6 db hosted on Azure . The servers are doing one thing - hitting the Postgres db with a SELECT 1 query every 5 seconds.Typical time to connect to db and get data : Node : 25 MS.NET Core 3.1 using Npsql 4.1.1 ( I have tried 4.1.2 too , no diff ) : 500 MSMy problem is that my .NET Core app is 20x slower than Node in getting data . I believe .NET Core is not pooling connections for some reason . This slowness occurs with both running the app locally and while running it on Azure App Services - no difference . I want to solve the .NET -- > Postgres slowness.Please only skim the relevant details and do n't read the whole thing past this point - I believe only the .NET Core code is relevant.A PsPing to the db from my machine ( on which both the Node and the .NET Core apps are running : For sake of completeness , a sample of NODE times look like this ( note that the first time it establishes a connection , it is also `` slow '' ) : Connection times for .NET Core look like this : Note the super-slow initial connection time and a long time to establish a connection on subsequent requests.Anyway , because I am desperate , I am going to dump all my code now , with explanations . The connection string looks like this : It is my understanding that I should get connection pooling out of the box if I use this connection string . Note that I have tried turning of SSL on both the db and taking that line out - it did not help.My health check controller looks like this : My health check repo method looks like this : Note the timers here - await conn.OpenAsync ( ) ; is what takes the bulk of the time by far , the queries themselves are fast . Also , for sake of saving time - I have run this code WITHOUT async before , no difference.Finally , in case there are dependency injection concerns , the repository is in a class library , the API project references it , and : services.AddSingleton < IHealthCheckRepository , HealthCheckRepository > ( ) ; This is how it sees it.I believe this is all the relevant information - I have been on the phone with Azure support and they found no issues with the db config . The .NET Core app is super light , so it 's not like it 's overloaded and it 's in testing , so no traffic besides my tests . Extra : For the sake of completeness , here is my WHOLE node app which hits the db and gets the performance posted ( conn data taken out ) .EDIT : For posterity , here are the times in .NET Core after fixing the connection pool timeout - it 's faster than node , except on that initial connection , which seems to take a while , but I have n't checked some defaults : Connecting to foobarPostGres:5432 ( warmup ) : from someIp : 19.98msConnecting to foobarPostGres:5432 : from someIp : 1.65msConnecting to foobarPostGres:5432 from someIp : 1.18msConnecting to foobarPostGres:5432 : from someIp : 1.23msConnecting to foobarPostGres:5432 : from someIp : 1.06ms Attempting to establish a connection ... Elapsed ms : 644.1334999799728RESP : { ' ? column ? ' : 1 } Elapsed ms : 22.76109904050827RESP : { ' ? column ? ' : 1 } Elapsed ms : 21.984400033950806RESP : { ' ? column ? ' : 1 } Elapsed ms : 26.043799996376038RESP : { ' ? column ? ' : 1 } Elapsed ms : 22.538798987865448RESP : { ' ? column ? ' : 1 } 5:13:32 PM : SLOW QUERY , CONN TIME : 4153 , QUERY TIME : 18 5:13:53 PM : SLOW QUERY , CONN TIME : 707 , QUERY TIME : 17 5:14:14 PM : SLOW QUERY , CONN TIME : 589 , QUERY TIME : 165:14:35 PM : SLOW QUERY , CONN TIME : 663 , QUERY TIME : 18 5:14:56 PM : SLOW QUERY , CONN TIME : 705 , QUERY TIME : 16 public static string CONNECTION_STRING { get { return $ '' Server= { HOST } ; User Id= { USER } ; Database= { DB_NAME } ; Port= { PORT } ; Password= { PWD } ; SSLMode=Prefer '' ; } } // GET api/health/getdbhealthselectone [ HttpGet ] [ Route ( `` getdbhealthselectone '' ) ] public async Task < IActionResult > GetDbHealthSelectOne ( ) { int testData = await _healthCheckRepo.RunHealthCheckSelectOne ( ) ; return Ok ( testData ) ; } public async Task < int > RunHealthCheckSelectOne ( ) { await using var conn = new NpgsqlConnection ( AzureDbConnectionInfo.CONNECTION_STRING ) ; var connTimer = System.Diagnostics.Stopwatch.StartNew ( ) ; // TODO : Remove this testing line await conn.OpenAsync ( ) ; connTimer.Stop ( ) ; // TODO : Remove this testing line var msToConnect = connTimer.ElapsedMilliseconds ; // TODO : Remove this testing line int testData = 999 ; var jobsQueryTimer = System.Diagnostics.Stopwatch.StartNew ( ) ; // TODO : Remove this testing line0 await using ( var cmd = new NpgsqlCommand ( `` SELECT 1 '' , conn ) ) await using ( var reader = await cmd.ExecuteReaderAsync ( ) ) while ( await reader.ReadAsync ( ) ) { testData = reader.GetInt32 ( 0 ) ; } ; jobsQueryTimer.Stop ( ) ; // TODO : Remove this testing line var msToQuery = jobsQueryTimer.ElapsedMilliseconds ; // TODO : Remove this testing line LogQueryIfSlow ( msToConnect , msToQuery , _logger ) ; // TODO : Remove this testing line return testData ; } const { Pool , Client } = require ( 'pg ' ) ; const { performance } = require ( 'perf_hooks ' ) ; const pool = new Pool ( { user : 'SECRET ' , host : 'SECRET ' , database : 'SECRET ' , password : 'SECRET ' , port : 5432 , } ) function runQuery ( pool ) { var t0 = performance.now ( ) ; pool.query ( 'SELECT 1 ' , ( err , res ) = > { if ( err ) { console.log ( 'ERROR : ' , err.stack ) } else { console.log ( 'RESP : ' , res.rows [ 0 ] ) } var t1 = performance.now ( ) ; console.log ( 'Elapsed ms : ' , t1-t0 ) ; //pool.end ( ) } ) ; } setInterval ( ( ) = > { runQuery ( pool ) } , 5000 ) ; CONN : 1710 QUERY : 18CONN : 0 QUERY : 16CONN : 0 QUERY : 16CONN : 0 QUERY : 17CONN : 0 QUERY : 16CONN : 0 QUERY : 23CONN : 0 QUERY : 16CONN : 0 QUERY : 16CONN : 0 QUERY : 23CONN : 0 QUERY : 16CONN : 0 QUERY : 16",Node is 20x faster Than .NET Core in Connecting to Postgres "C_sharp : I am using ASPNetCore and Angular 7 . My Angular app is getting quite big , so re-compiling both the C # code and the angular code every time I run is getting cumbersome.I have this line in my Startup.cs file . Is it possible to A. either keep this running when I terminate the ASPNet application , or B , run it separately and still route requests through the same SSL port that the aspnet app is using ? Since angular has hot module replacement , I want to just keep that running 99 % of the time and just re-compile my backend when I make changes to C # code . if ( env.IsDevelopment ( ) ) { spa.UseAngularCliServer ( npmScript : `` start '' ) ; }",how to keep the AngularCLIServer running between builds on asp.net core with Angular 7 "C_sharp : There is an application ( executor.exe ) that invokes methods from class library ( lib.dll ) using reflection.executor.exe has assembly Newtonsoft.Json version 8.0 as embedded resource.lib.dll has reference to Newtonsoft.Json version 9.0.lib.dll has reference to system.net.http.formatting version 4.0.0.21112 , which in turn refers to Newtonsoft.Json 4.5.I do n't have the opportunity to modify executor.exe.config ( except for testing ) .What do I want to get : Invoked from lib.dll . But it fails with : Method not found : 'Newtonsoft.Json.JsonSerializerSettings System.Net.Http.Formatting.JsonMediaTypeFormatter.get_SerializerSettings ( ) 'What I was trying to do : Handling AppDomain.CurrentDomain.AssemblyResolve ( subscribed correctly , using ModuleInitializer ) . But it does n't rise . After crash have 2 Newtonsoft.Json ( with different versions ) loaded to AppDomain.Binding in app config : Yes , it works . But I ca n't use this solution . After passing have 2 Newtonsoft.Json ( with different versions ) loaded to AppDomain.I do n't understand why this works ( oldVersion= '' 8.0.0.0-9.0.0.0 '' ) but : exception `` Method not found '' does n't throw . After passing have 1 Newtonsoft.Json ( 9.0 ) loaded to AppDomain . But not suitable for me.Why AppDomain.CurrentDomain.AssemblyResolve does n't work ? I guess the problem is in 2 loaded assemblies but I can not change this behavior . new JsonMediaTypeFormatter ( ) .SerializerSettings ; < assemblyIdentity name= '' Newtonsoft.Json '' publicKeyToken= '' 30ad4fe6b2a6aeed '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 4.0.0.0-5.0.0.0 '' newVersion= '' 9.0.0.0 '' / > < assemblyIdentity name= '' Newtonsoft.Json '' publicKeyToken= '' 30ad4fe6b2a6aeed '' culture= '' neutral '' / > < bindingRedirect oldVersion= '' 8.0.0.0-9.0.0.0 '' newVersion= '' 9.0.0.0 '' / >",`` Method not found '' exception . Why AppDomain.CurrentDomain.AssemblyResolve does n't work ? "C_sharp : Is there a way to get this code to automatically overwrite files ? This is from MSDNThanks // Requires project reference to Microsoft.VisualBasicusing Microsoft.VisualBasic.FileIO ; class FileProgress { static void Main ( ) { string sourcePath = @ '' C : \Users\public\documents\ '' ; string destinationPath = @ '' C : \testFolder '' ; FileSystem.CopyDirectory ( sourcePath , destinationPath , UIOption.AllDialogs ) ; } }",Is there a way to get this C # code to automatically overwrite files ? "C_sharp : Assume two classes , both descendants of the same superclass , like this : Then this assignment wo n't pass the compiler : The compiler complains that A and B are not compatible ( Type of conditional expression can not be determined because there is no implicit conversion between ' A ' and ' B ' [ CS0173 ] ) . But they are both of type MySuperClass , so in my opinion this should work . Not that it 's a big deal ; a simple cast is all it takes to enlighten the compiler . But surely it 's a snag in the C # compiler ? Do n't you agree ? class MySuperClass { } class A : MySuperClass { } class B : MySuperClass { } MySuperClass p = myCondition ? new A ( ) : new B ( ) ;","The conditional operator gets confused , but why ?" "C_sharp : While coding in C # , I by mistake added a strudel sign before a variable in if statement ( instead of exclamation mark ) .I surprised it compiled successfully without any error.I wonder : What is the meaning of the above code ? bool b = false ; if ( @ b ) { }",C # strudel sign "C_sharp : Suppose I have a number of countries , each of which has a number of cities . I can represent this using the following models : Entity Framework correctly identifies the foreign keys and generates the tables.However , if I now try to seed some test data : The first time this is run , all is fine , and the CountryId field in the database is set properly . However , when I run it a second time , db.SaveChanges ( ) attemps to set the CountryId of Paris to 0 , which violates the non-nullable foreign key constraint.The problem seems to be that despite city and country being change-tracking proxies , the CountryId property is never updating . Updating it manually does n't help this , though.Is this the intended behaviour , and if so , how can I use AddOrUpdate without changing like this ? Doing everything by setting foreign keys does n't seem to be an option , as those are n't available the first time the code runs . public class Country { public virtual int Id { get ; set ; } [ Required ] public virtual string Name { get ; set ; } public virtual ICollection < City > Cities { get ; set ; } } public class City { public virtual int Id { get ; set ; } [ Required ] public virtual string Name { get ; set ; } public virtual Country Country { get ; set ; } public virtual int CountryId { get ; set ; } } class TestContext : DbContext { public DbSet < City > Cities { get ; set ; } public DbSet < Country > Countries { get ; set ; } } static class Program { static void Main ( ) { Database.SetInitializer ( new DropCreateDatabaseIfModelChanges < TestContext > ( ) ) ; using ( var db = new TestContext ( ) ) { db.Database.Initialize ( true ) ; db.Database.Log = Console.Write ; var country = db.Countries.Create ( ) ; country.Name = `` France '' ; db.Countries.AddOrUpdate ( a = > a.Name , country ) ; var city = db.Cities.Create ( ) ; city.Name = `` Paris '' ; city.Country = country ; db.Cities.AddOrUpdate ( q = > q.Name , city ) ; db.SaveChanges ( ) ; } } }",EntityFramework 's AddOrUpdate leads to incorrect foreign key update "C_sharp : i am using Dapper for accessing sqlite database and getting 'String was not recognized as a valid DateTime. ' . Any help is appreciated.Query code : Query to insert data : Error Message : Inner Exception Message : StackTrace : Mapping item class : Database schema and entries can be seen from following example taken from DB SQLite browser // Create table schemaCREATE TABLE `` mytable '' ( `` field1 '' TEXT , `` field2 '' TEXT , `` field3 '' TEXT , `` field4 '' TEXT , `` field5 '' TEXT , `` field6 '' bit , `` field7 '' TEXT , `` field8 '' TEXT , `` field9 '' TEXT , `` field10 '' TEXT , `` field11 '' DateTime ) var result= sqliteConnection.Query < TestItem > ( `` Select * from mytable '' ) ; INSERT INTO `` main '' . `` mytable '' ( `` field1 '' , `` field2 '' , `` field3 '' , `` field4 '' , `` field5 '' , `` field6 '' , `` field7 '' , `` field8 '' , `` field9 '' , `` field10 '' , `` field11 '' ) VALUES ( '750eb223-2993-4d85-9d4f-3e8689e9baa7 ' , 'some value ' , `` , 'some value ' , 'some value ' , ' 1 ' , '84 ' , 'ae35e1e1-dd4c-4e49-a76c-d577f417bf9a ' , 'some value ' , 'HOME.aspx ' , '2020/01/20 17:38 ' ) ; INSERT INTO `` main '' . `` mytable '' ( `` field1 '' , `` field2 '' , `` field3 '' , `` field4 '' , `` field5 '' , `` field6 '' , `` field7 '' , `` field8 '' , `` field9 '' , `` field10 '' , `` field11 '' ) VALUES ( '750eb223-2993-4d85-9d4f-3e8689e9baa7 ' , 'some value ' , 'asdf ' , 'some value ' , 'some value ' , ' 1 ' , '32 ' , 'a1cd1b8f-95f6-4b03-8d54-f904c21749ac ' , 'HOME.aspx ' , 'HOME.aspx ' , '2020/01/20 17:38 ' ) ; INSERT INTO `` main '' . `` mytable '' ( `` field1 '' , `` field2 '' , `` field3 '' , `` field4 '' , `` field5 '' , `` field6 '' , `` field7 '' , `` field8 '' , `` field9 '' , `` field10 '' , `` field11 '' ) VALUES ( '750eb223-2993-4d85-9d4f-3e8689e9baa7 ' , 'some value ' , 'some value ' , 'some value ' , 'some value ' , ' 1 ' , '99 ' , 'b9e63bfd-c73e-4e9a-b3e7-30ae49d8a002 ' , 'CALLSS.aspx ' , 'CALLSS.aspx ' , '2020/01/20 17:38 ' ) ; Error parsing column 10 ( field11=HOME.aspx - String ) String was not recognized as a valid DateTime . at Dapper.SqlMapper.ThrowDataException ( Exception ex , Int32 index , IDataReader reader , Object value ) in C : \projects\dapper\Dapper\SqlMapper.cs : line 3609 at Dapper.SqlMapper. < QueryImpl > d__138 ` 1.MoveNext ( ) in C : \projects\dapper\Dapper\SqlMapper.cs : line 1100 at System.Collections.Generic.List ` 1..ctor ( IEnumerable ` 1 collection ) at System.Linq.Enumerable.ToList [ TSource ] ( IEnumerable ` 1 source ) at Dapper.SqlMapper.Query [ T ] ( IDbConnection cnn , String sql , Object param , IDbTransaction transaction , Boolean buffered , Nullable ` 1 commandTimeout , Nullable ` 1 commandType ) in C : \projects\dapper\Dapper\SqlMapper.cs : line 723 at Tzunami.LinkResolver.DatabaseMigration.Models.DBMigrator. < MigrateDeploymentListItemAsync > d__5.MoveNext ( ) in C : \Users\surendra\source\repos\Tzunami.LinkResolver.MigrationTool\Tzunami.LinkResolver.DatabaseMigration\Models\DBMigrator.cs : line 77 public class TestItem { public string Field1 { get ; set ; } public string Field2 { get ; set ; } public string Field3 { get ; set ; } public string Field4 { get ; set ; } public string Field5 { get ; set ; } public string Field6 { get ; set ; } public string Field7 { get ; set ; } public string Field8 { get ; set ; } public string Field9 { get ; set ; } public string Field10 { get ; set ; } public string Field11 { get ; set ; } }",Dapper : String was not recognized as a valid DateTime "C_sharp : I 'm looking at the controllers in my website , and most of their constructors look like this : In other words , it 's very hairy and makes refactoring difficult . Some controllers have around 8 dependencies.Is there any way i can somehow `` group '' these dependencies into one of more buckets ? For example , ILoggingService is required in every controller , IGeospatialService is required by controllers who do spatial stuff , and IServiceOne and IServiceTwo is only required in certain cases.I would like to see something like this : I 'm thinking it would be good to introduce some OO techniques , such as having a `` base '' depedency class , which takes a ILoggingService in it 's protected ctor . Then you might have another child dependency which inherits , etc . Has anyone done this before ? Is this something StructureMap can do for me , or is it simply me rolling my own basic code ? public SomeController ( IServiceOne serviceOne , IServiceTwo serviceTwo , ILoggingService loggingService , IGeospatialService geoSpatialService ) { // copy to class variables . } public SomeController ( ICoreServicesGroup coreGroup , ISomeNameForServicesGroup serviceGroup ) { // copy to class variables . }",Consolidating ASP.NET MVC Controller Dependencies ( StructureMap ) C_sharp : Filter by criterion onlyBut how could you make it so that you get the criterion value and n values after the criterion is fulfilled ( and these n values do not have to match the evaluation criterion ) ? e.g . i would like to subscribe to a stream that returns on Evaluate ( p ) and one value after that ( and then starts to evaluate p again ) changes.Where ( p = > Evaluate ( p ) ) .Subscribe ( p = > { // Do something } ) ;,Rx filter by criterion and n values after criterion "C_sharp : My Entity Framework model is generated from SQL Server database . Since I need to access database from Silverlight , I generated a DomainService for RIAServices against the EF model . Product is one of the autogenerated EntityObject corresponding to the table Product . I am attempting to pass the custom class CompositeData across to the Silverlight client as shown . The problem is that CurrentProduct field is not accessible in the client but the other string/int fields are accessible . How can make CurrentProduct accessible from client ? Following is the Domain Service method : From the Silverlight client , EDIT : Product class is autogenerated in Model1.Designer.cs It gets generated in the client project also ( in SilverlightProject.g.cs ) public class CompositeData { [ Key ] public Guid PKey { get ; set ; } public string CompositeName { get ; set ; } public string Identity { get ; set ; } public Product CurrentProduct { get ; set ; } //Product is an auto-generated EntityObject class public CompositeData ( ) { PKey = Guid.NewGuid ( ) ; } } [ EnableClientAccess ( ) ] public class LocalDomainService : DomainService { public IEnumerable < CompositeData > GetData ( ) { List < CompositeData > listData = new List < CompositeData > ( ) ; // ... return listData ; } } domService.Load ( domService.GetDataQuery ( ) , GetDataCompleted , null ) ; private void GetDataCompleted ( LoadOperation < CompositeData > compData ) { foreach ( CompositeData cdItem in compData.Entities ) { // cdItem.CompositeName is accessible // cdItem.CurrentProduct is not accessible ! } } [ EdmEntityTypeAttribute ( NamespaceName= '' MyDBModel '' , Name= '' Product '' ) ] [ Serializable ( ) ] [ DataContractAttribute ( IsReference=true ) ] public partial class Product : EntityObject { //.. } /// < summary > /// The 'Product ' entity class . /// < /summary > [ DataContract ( Namespace= '' http : //schemas.datacontract.org/2004/07/SilverlightProject '' ) ] public sealed partial class Product : Entity { //.. }",Can not access EntityObject type via RIA services "C_sharp : If I create csv file ( I 'm doing it from C # ) , which contains text `` ID '' in first cell in first row , MS Excel 2010 fails to open it , it says , file is not a valid csv file.I spend a half of an hour , before I realized that problem is with that `` ID '' .Most interesting thing in this situation is , that if `` ID '' is moved to any other cell , everything works just fine.Steps to reproduce : Create text file with following content : Save it.Change extension to csv.That 's all , MS Excel 2010 will tell you that this file is not a csv and will fail to open it ! What I am doing wrong ? I googled for some info , but it seems , ID is not some kind of reserved word.I 'm running Win7Enterprisex64 and using MS Excel 2010 , as I mentioned.P.S depending on your culture settings , csv separator may be , or ; ( maybe some other characters ) ID , Name1 , Unnamed",CSV first cell restrictions "C_sharp : If I have a set of string constants that I want to store similar to an enum , is it best to use a struct or a static class ? For example : public struct Roman { public const string One = `` I '' ; public const string Five = `` V '' ; public const string Ten = `` X '' ; } public static class Roman { public const string One = `` I '' ; public const string Five = `` V '' ; public const string Ten = `` X '' ; }",Store consts in a struct or a static class "C_sharp : In C # you can do : I 'm trying to learn all the Ruby enumerable methods , but I do n't see an equivalent for skip ( n ) So , what 's the `` best '' Ruby way to do it ? all of these work , but they 're pretty ugly . var list = new List < int > ( ) { 1,2,3,4,5 } ; list.skip ( 2 ) .take ( 2 ) ; // returns ( 3,4 ) a = [ 1,2,3,4,5 ] a.skip ( 2 ) .take ( 2 ) # take exists , skip does n't a.last ( a.length - 2 ) .take ( 2 ) ( a - a.first ( 2 ) ) .take ( 2 ) a [ 2 ... a.length ] .take ( 2 )",Does Ruby have Skip ( n ) like C # ? "C_sharp : I have a Pivot with several PivotItems , one of which contains a canvas that places its items in dynamic locations ( depending on the data ) . I get the data , and I can place the items in their place before the user can choose this item ( this is n't the first pivot ) . However , only when I select the PivotItem , the canvas renders itself , so you can see it flicker before it 's shown as it should.Is there a way to force the canvas to render before it 's shown , so everything 's prepared by the time the user sees it ? My code looks something like this : In the page.xaml.cs : The canvas is n't the stock canvas . I created a new canvas that displays items according to their relative position ( I get the positions in a scale of 0-99 ) .The logic happens in the OverrideArrange method : Thanks . private async void GameCenterView_OnDataContextChanged ( object sender , EventArgs e ) { // Load data ... // Handle other pivots // This is the problem pivot if ( ViewModel.CurrentGame.SportTypeId == 1 ) { _hasLineups = ViewModel.CurrentGame.HasLineups.GetValueOrDefault ( ) ; HasFieldPositions = ViewModel.CurrentGame.HasFieldPositions.GetValueOrDefault ( ) ; // I only add the pivot when I need it , otherwise , it wo n't be shown if ( _hasLineups ) { if ( MainPivot.Items ! = null ) MainPivot.Items.Add ( LineupPivotItem ) ; } if ( HasFieldPositions ) { // Here I place all the items in their proper place on the canvas ArrangeLineup ( ViewModel.TeamOneLineup , TeamOneCanvas ) ; ArrangeLineup ( ViewModel.TeamTwoLineup , TeamTwoCanvas ) ; } } // Handle other pivots } private void ArrangeLineup ( ObservableCollection < PlayerInLineupViewModel > teamLineup , RationalCanvas canvas ) { if ( teamLineup == null ) return ; foreach ( var player in teamLineup ) { var control = new ContentControl { Content = player , ContentTemplate = LinupPlayerInFieldDataTemplate } ; control.SetValue ( RationalCanvas.RationalTopProperty , player.Player.FieldPositionLine ) ; control.SetValue ( RationalCanvas.RationalLeftProperty , player.Player.FieldPositionSide ) ; canvas.Children.Add ( control ) ; } } protected override Size ArrangeOverride ( Size finalSize ) { if ( finalSize.Height == 0 || finalSize.Width == 0 ) { return base.ArrangeOverride ( finalSize ) ; } var yRatio = finalSize.Height/100.0 ; var xRatio = finalSize.Width/100.0 ; foreach ( var child in Children ) { var top = ( double ) child.GetValue ( TopProperty ) ; var left = ( double ) child.GetValue ( LeftProperty ) ; if ( top > 0 || left > 0 ) continue ; var rationalTop = ( int ) child.GetValue ( RationalTopProperty ) ; var rationalLeft = ( int ) child.GetValue ( RationalLeftProperty ) ; if ( InvertY ) rationalTop = 100 - rationalTop ; if ( InvertX ) rationalLeft = 100 - rationalLeft ; child.SetValue ( TopProperty , rationalTop*yRatio ) ; child.SetValue ( LeftProperty , rationalLeft*xRatio ) ; } return base.ArrangeOverride ( finalSize ) ; }",Force pivot item to preload before it 's shown "C_sharp : I just had one of these `` What the ... '' moments . Is the following intended and is there some obscure reasoning behind the `` non-natural '' declaration of arrays in C # ? I would have expected the other way around . int [ , ] [ ] declares an 1-dimensional array where each element is a two dimensional array.Funny though , the type 's Name is reversed : Can someone explain this ? Is this intentionally ? ( Using .NET 4.5 under Windows . ) int [ , ] [ ] i ; // declares an 2D - array where each element is an int [ ] ! // you have to use it like this : i = new int [ 2,3 ] [ ] ; i [ 1,2 ] = new int [ 0 ] ; Console.WriteLine ( typeof ( int [ , ] [ ] ) .Name ) ; // prints `` Int32 [ ] [ , ] ''",C # jagged array type declaration in reverse C_sharp : I 'll best just show with a code example what I would like to accomplish ? ( The string passed to Contract.Ensures ( ) is of course just a placeholder for the real post-condition expression . ) How can I do this ? Would Contract.OldValue < > ( ) be of any use here ? class SomeClass { public int SomeProperty ; public void SomeOperation ( ) { Contract.Ensures ( `` SomeProperty 's value has not changed . '' ) ; // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // How can I write this post-condition ? } } ;,Code Contracts : How do I state in a post-condition that a field/property 's value has not changed ? C_sharp : After upgrading to VS 2017 I got the following error from this code ( which has always been working perfectly ) Exception : the solution was to surround the expression by parentheses.But that made me wonder is this a bug or a new functionality ? Thanks . byte [ ] HexStringToByteArray ( string hex ) { if ( hex.Length % 2 == 1 ) throw new Exception ( `` The binary key can not have an odd number of digits '' ) ; byte [ ] arr = new byte [ hex.Length > > 1 ] ; for ( int i = 0 ; i < hex.Length > > 1 ; ++i ) // Error in this line { arr [ i ] = ( byte ) ( ( GetHexVal ( hex [ i < < 1 ] ) < < 4 ) + ( GetHexVal ( hex [ ( i < < 1 ) + 1 ] ) ) ) ; } return arr ; } Error 1 : The variable ' i ' can not be used with type argumentsError 2 : 'hex ' is a variable but is used like a type for ( int i = 0 ; i < ( hex.Length > > 1 ) ; ++i ),VS 2017 Bug or new features ? "C_sharp : I have some string with text , I want to count all occurrences of Environment.NewLine.I thought to something in a way like But c is only one char so it will not work .Any better suggestions ? MyString.Where ( c = > c == Environment.NewLine ) .Count ( ) ;",counting occurrences of end of line "C_sharp : I have the following c # code , it does a check on permissions . I 'm wondering if , when converted to f # , would computational expressions be a way to factor out the null checks.I would like to note that the ISecurityService API currently returns false if any of the items are null . However it makes a database call , so the code here checks for null and then does the id check , because in most cases this will return false and avoid a database call . bool ShouldGrantPermission ( ISecurityService security , User user , Item item ) { return user ! = null & & item ! = null & & user.Id == item.AuthorId & & security.Does ( user ) .Have ( MyPermission ) .On ( item ) ; }",Is this a candidate for computational expressions ? "C_sharp : This question and its answers explain the concept of implicitly captured closures very well . However , I occasionally see code that seems like it should generate the warning in question that in fact does not . For example : My expectation was that I 'd be warned that a1 implicitly captures rnd2 , and a2 implicitly captures rnd1 . However , I get no warning at all ( the code in the linked question does generate it for me though ) . Is this a bug on ReSharper 's part ( v9.2 ) , or does implicit capture not occur here for some reason ? public static void F ( ) { var rnd1 = new Random ( ) ; var rnd2 = new Random ( ) ; Action a1 = ( ) = > G ( rnd1 ) ; Action a2 = ( ) = > G ( rnd2 ) ; } private static void G ( Random r ) { }",Why *doesn't* ReSharper tell me “ implicitly captured closure ” ? "C_sharp : I have the following code : I do n't want to allow people to read the data while it 's being loaded from the database , thus I put a lock in ReadData . However , right now if multiple people call ReadData at the same time , only one call can run at once.Is there a way I can allow simultaneous calls to ReadData but block readers when LoadData is being run ? private static object _dbLock = new object ( ) ; public static void LoadData ( ) { lock ( _dbLock ) { //Load data from the database } } public static string ReadData ( Guid key ) { lock ( _dbLock ) { //Lookup key in data and return value } }",Lock that will allow multiple readers in C # "C_sharp : Let 's say I create these two methods : Which one of these methods gets call by the code below , and why ? How does the compiler determine which method to call ? public void AddScriptToPage ( params string [ ] scripts ) { /* ... */ } public void AddScriptToPage ( string href , string elementId ) { /* ... */ } AddScriptToPage ( `` dork.js '' , `` foobar.js '' ) ;",C # : Method signatures ? "C_sharp : I 've got some very large XML files which I read using a System.Xml.Serialization.XmlSerializer . It 's pretty fast ( well , fast enough ) , but I want it to pool strings , as some long strings occur very many times . The XML looks somewhat like this : And the classes the XML is deserialized into look somewhat like this : When the data is imported , a new string is allocated for every column name . I can see why that is so , but according to my calculations , that means a few duplicated strings make up some ~50 % of the memory used by the imported data . I 'd consider it a very good trade-off to spend some extra CPU cycles to cut memory consumption in half . Is there some way to have the XmlSerializer pool strings , so that duplicates are discarded and can be reclaimed the next time a gen0 GC occurs ? Also , some final notes : I ca n't change the XML schema . It 's an exported file from a third-party vendor.I know could ( theoretically ) make a faster parser using an XmlReader instead , and it would not only allow me to do my own string pooling , but also to process data during mid-import so that not all 200k lines have to be saved in RAM until I 've read the entire file . Still , I 'd rather not spend the time writing and debugging a custom parser . The real XML is a bit more complicated than the example , so it 's quite a non-trivial task . And as mentioned above - the XmlSerializer really does perform well enough for my purposes , I 'm just wondering if there is an easy way to tweak it a little.I could write a string pool of my own and use it in the Column.Name setter , but I 'd rather not as ( 1 ) that means fiddling with auto-generated code , and ( 2 ) it opens up for a slew of problems related to concurrency and memory leaks.And no , by `` pooling '' , I do n't mean `` interning '' as that can cause memory leaks . < Report > < Row > < Column name= '' A long column name ! `` > hey < /Column > < Column name= '' Another long column name ! ! `` > 7 < /Column > < Column name= '' A third freaking long column name ! ! ! `` > hax < /Column > < Column name= '' Holy cow , can column names really be this long ! ? `` > true < /Column > < /Row > < Row > < Column name= '' A long column name ! `` > yo < /Column > < Column name= '' Another long column name ! ! `` > 53 < /Column > < Column name= '' A third freaking long column name ! ! ! `` > omg < /Column > < Column name= '' Holy cow , can column names really be this long ! ? `` > true < /Column > < /Row > < ! -- ... ~200k more rows go here ... -- > < /Report > class Report { public Row [ ] Rows { get ; set ; } } class Row { public Column [ ] Columns { get ; set ; } } class Column { public string Name { get ; set ; } public string Value { get ; set ; } }",Can an XmlSerializer pool strings to avoid large duplicate strings ? "C_sharp : I am trying to post some data to a WCF service I do n't own . I am using XmlSerializer to format the message , which creates issues with data containing single quotes.Having a node like thisCauses service to throw `` 400 bad request '' exception . If I manually construct request in Fiddler like thisthen it works just fine.I am confused as to why would this be needed . Various online XML validators claim my original XML is valid , but WCF does n't like it ? Any way to fix/workaround ? Here is my code just in case : ... < FirstName > D'Arcy < /FirstName > ... ... < FirstName > D & quot ; Arcy < /FirstName > ... static XmlSerializer RequestSerializer = new XmlSerializer ( typeof ( Message ) ) ; static XmlSerializer ResponseSerializer = new XmlSerializer ( typeof ( int ) , new XmlRootAttribute ( `` int '' ) { Namespace = `` http : //schemas.microsoft.com/2003/10/Serialization/ '' } ) ; static XmlWriterSettings WriterSettings = new XmlWriterSettings { OmitXmlDeclaration = true , CloseOutput = false , Encoding = new UTF8Encoding ( false ) } ; private static int PostData ( Message msg ) { var request = ( HttpWebRequest ) WebRequest.Create ( `` https : // ... '' ) ; request.ContentType = `` text/xml ; charset=UTF-8 '' ; request.Method = `` POST '' ; using ( var writer = XmlWriter.Create ( request.GetRequestStream ( ) , WriterSettings ) ) RequestSerializer.Serialize ( writer , msg ) ; using ( var response = ( HttpWebResponse ) request.GetResponse ( ) ) using ( var responseStream = response.GetResponseStream ( ) ) { return ( int ) ResponseSerializer.Deserialize ( responseStream ) ; } } [ XmlRoot ( `` Order '' , Namespace = `` http : // ... '' ) ] public class Message { public string City ; public string Coupon ; public DateTime CreateDate ; public string Email ; public string FirstName ; public string Language ; public string LastName ; public int OrderID ; public string PostalCode ; public string ProductID ; public string Province ; public string StreetAddress1 ; public string StreetAddress2 ; }",WCF service does n't like single quotes "C_sharp : I have the following code in aspx code . I wanted to add ListItem check boxes to ColumnsList and Find all the checked one 's on button click.But when I try to get the selected items on button click the ColumnsList count becomes 0.In code behind I add data to my ColumnsList as follows// Here is the button click listenerNote : The application is Deployed in share point 2010 . < asp : checkboxlist runat= '' server '' EnableViewState= '' true '' id= '' ColumnsList '' / > public override void OnLoad ( ) { if ( ! this.IsPostBack ) { this.ColumnsList.Items.Add ( new ListItem { Text= `` Text1 '' , Value = `` value1 '' } ) ; this.ColumnsList.Items.Add ( new ListItem { Text= `` Text2 '' , Value = `` value2 '' } ) ; } } private void Button_Click ( object sender , EventArgs eventArgs ) { // Count is 0 instead of 2 var count = this.ColumnsList.Items.Count ; foreach ( ListItem item in this.ColumnsList.Items ) { var selected = item.Selected ; // add selected to a list..etc } }",CheckBoxList ListItem Count always 0 after adding data dynamically "C_sharp : What I want to do : Use Activator to dynamically create an object ( which could be any type ) and pass it to a method for serializing JSON . Note : I have already looked at No type inference with generic extension method but that did n't really give me any useful information on how I could solve this problem.Edit : Using .NET 3.5 FrameworkProblem : The object I receive could be an array ( such as int [ ] ) and when I use generics to type the received object , I get an object [ ] instead of an int [ ] .Code sample : class Program { static void Main ( string [ ] args ) { object objArr = new int [ 0 ] ; int [ ] intArr = new int [ 0 ] ; string arrS = `` [ 1,2 ] '' ; object objThatIsObjectArray = Serialize ( objArr , arrS ) ; //I want this to evaluate as int [ ] object objThatIsIntArray = Serialize ( intArr , arrS ) ; //this evaluates as int [ ] Console.Read ( ) ; } public static object Serialize < T > ( T targetFieldForSerialization , string value ) { return value.FromJson < T > ( ) ; } } public static class JSONExtensions { public static TType FromJson < TType > ( this string json ) { using ( var ms = new MemoryStream ( Encoding.Default.GetBytes ( json ) ) ) { var ser = new DataContractJsonSerializer ( typeof ( TType ) ) ; var target = ( TType ) ser.ReadObject ( ms ) ; ms.Close ( ) ; return target ; } } }",Can I use generics to infer actual type over known type ? "C_sharp : I am trying to replicate the outcome of this link using linear convolution in spatial-domain . Images are first converted to 2d double arrays and then convolved . Image and kernel are of the same size . The image is padded before convolution and cropped accordingly after the convolution . As compared to the FFT-based convolution , the output is weird and incorrect . How can I solve the issue ? Note that I obtained the following image output from Matlab which matches my C # FFT output : . Update-1 : Following @ Ben Voigt 's comment , I changed the Rescale ( ) function to replace 255.0 with 1 and thus the output is improved substantially . But , still , the output does n't match the FFT output ( which is the correct one ) . . Update-2 : Following @ Cris Luengo 's comment , I have padded the image by stitching and then performed spatial convolution . The outcome has been as follows : So , the output is worse than the previous one . But , this has a similarity with the 2nd output of the linked answer which means a circular convolution is not the solution . . Update-3 : I have used the Sum ( ) function proposed by @ Cris Luengo 's answer . The result is a more improved version of **Update-1** : But , it is still not 100 % similar to the FFT version . . Update-4 : Following @ Cris Luengo 's comment , I have subtracted the two outcomes to see the difference : , 1. spatial minus frequency domain 2. frequency minus spatial domain Looks like , the difference is substantial which means , spatial convolution is not being done correctly . . Source Code : ( Notify me if you need more source code to see . ) public static double [ , ] LinearConvolutionSpatial ( double [ , ] image , double [ , ] mask ) { int maskWidth = mask.GetLength ( 0 ) ; int maskHeight = mask.GetLength ( 1 ) ; double [ , ] paddedImage = ImagePadder.Pad ( image , maskWidth ) ; double [ , ] conv = Convolution.ConvolutionSpatial ( paddedImage , mask ) ; int cropSize = ( maskWidth/2 ) ; double [ , ] cropped = ImageCropper.Crop ( conv , cropSize ) ; return conv ; } static double [ , ] ConvolutionSpatial ( double [ , ] paddedImage1 , double [ , ] mask1 ) { int imageWidth = paddedImage1.GetLength ( 0 ) ; int imageHeight = paddedImage1.GetLength ( 1 ) ; int maskWidth = mask1.GetLength ( 0 ) ; int maskHeight = mask1.GetLength ( 1 ) ; int convWidth = imageWidth - ( ( maskWidth / 2 ) * 2 ) ; int convHeight = imageHeight - ( ( maskHeight / 2 ) * 2 ) ; double [ , ] convolve = new double [ convWidth , convHeight ] ; for ( int y = 0 ; y < convHeight ; y++ ) { for ( int x = 0 ; x < convWidth ; x++ ) { int startX = x ; int startY = y ; convolve [ x , y ] = Sum ( paddedImage1 , mask1 , startX , startY ) ; } } Rescale ( convolve ) ; return convolve ; } static double Sum ( double [ , ] paddedImage1 , double [ , ] mask1 , int startX , int startY ) { double sum = 0 ; int maskWidth = mask1.GetLength ( 0 ) ; int maskHeight = mask1.GetLength ( 1 ) ; for ( int y = startY ; y < ( startY + maskHeight ) ; y++ ) { for ( int x = startX ; x < ( startX + maskWidth ) ; x++ ) { double img = paddedImage1 [ x , y ] ; double msk = mask1 [ x - startX , y - startY ] ; sum = sum + ( img * msk ) ; } } return sum ; } static void Rescale ( double [ , ] convolve ) { int imageWidth = convolve.GetLength ( 0 ) ; int imageHeight = convolve.GetLength ( 1 ) ; double maxAmp = 0.0 ; for ( int j = 0 ; j < imageHeight ; j++ ) { for ( int i = 0 ; i < imageWidth ; i++ ) { maxAmp = Math.Max ( maxAmp , convolve [ i , j ] ) ; } } double scale = 1.0 / maxAmp ; for ( int j = 0 ; j < imageHeight ; j++ ) { for ( int i = 0 ; i < imageWidth ; i++ ) { double d = convolve [ i , j ] * scale ; convolve [ i , j ] = d ; } } } public static Bitmap ConvolveInFrequencyDomain ( Bitmap image1 , Bitmap kernel1 ) { Bitmap outcome = null ; Bitmap image = ( Bitmap ) image1.Clone ( ) ; Bitmap kernel = ( Bitmap ) kernel1.Clone ( ) ; //linear convolution : sum . //circular convolution : max uint paddedWidth = Tools.ToNextPow2 ( ( uint ) ( image.Width + kernel.Width ) ) ; uint paddedHeight = Tools.ToNextPow2 ( ( uint ) ( image.Height + kernel.Height ) ) ; Bitmap paddedImage = ImagePadder.Pad ( image , ( int ) paddedWidth , ( int ) paddedHeight ) ; Bitmap paddedKernel = ImagePadder.Pad ( kernel , ( int ) paddedWidth , ( int ) paddedHeight ) ; Complex [ , ] cpxImage = ImageDataConverter.ToComplex ( paddedImage ) ; Complex [ , ] cpxKernel = ImageDataConverter.ToComplex ( paddedKernel ) ; // call the complex function Complex [ , ] convolve = Convolve ( cpxImage , cpxKernel ) ; outcome = ImageDataConverter.ToBitmap ( convolve ) ; outcome = ImageCropper.Crop ( outcome , ( kernel.Width/2 ) +1 ) ; return outcome ; }",Image convolution in spatial domain "C_sharp : I 've made a netstandard class library . I target netstandard 1.6 . My csproj is like : And I have a WPF-Project , in which I reference this dll . I can use the classes of the netstandard dll in c # . I can use them in xaml , too . I get even intellicence for them . But xaml designer says , my xaml is invalid . I can compile the solution , I can run the application . At runtime is everything ok . But the designer can not work with it.The Person class looks like : Do you know a workaround , or do you have an idea , how can I correct it ? < Project Sdk= '' Microsoft.NET.Sdk '' > < PropertyGroup Label= '' Globals '' > < SccProjectName > SAK < /SccProjectName > < SccProvider > SAK < /SccProvider > < SccAuxPath > SAK < /SccAuxPath > < SccLocalPath > SAK < /SccLocalPath > < /PropertyGroup > < PropertyGroup > < TargetFramework > netstandard1.6 < /TargetFramework > < /PropertyGroup > < ItemGroup > < PackageReference Include= '' System.Runtime '' Version= '' 4.3.0 '' / > < PackageReference Include= '' System.Runtime.Serialization.Primitives '' Version= '' 4.3.0 '' / > < PackageReference Include= '' System.Runtime.Serialization.Xml '' Version= '' 4.3.0 '' / > < /ItemGroup > < /Project > using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Runtime.CompilerServices ; using System.Runtime.Serialization ; using System.Text ; namespace DS.Publications.Common { [ DataContract ( Namespace = Constants.NamespaceConstants.DataContractNamespace ) ] public class Person : INotifyPropertyChanged { private string _Title = string.Empty ; [ DataMember ] public string Title { get { return _Title ; } set { Set ( ref _Title , value ) ; } } private string _ForeName ; [ DataMember ] public string ForeName { get { return _ForeName ; } set { Set ( ref _ForeName , value ) ; } } private string _LastName ; [ DataMember ] public string LastName { get { return _LastName ; } set { Set ( ref _LastName , value ) ; } } public event PropertyChangedEventHandler PropertyChanged ; private void OnPropertyChanged ( string propertyName ) { this.PropertyChanged ? .Invoke ( this , new PropertyChangedEventArgs ( propertyName ) ) ; } private bool Set < T > ( ref T field , T value , [ CallerMemberName ] string propertyName = null ) { if ( field == null || ! field.Equals ( value ) ) { field = value ; this.OnPropertyChanged ( propertyName ) ; return true ; } return false ; } } }",.NET Standard class library referenced in WPF - sign error in XAML at design time "C_sharp : I have a list of object that has two properties , let 's say a and b. a is an Enum like : b is an unsigned integer , which is a mask ( combination of the MyEnum flags ) .now i need to sum every object by their a - meaning an object can be summed twice if obj.a = first | third and i ca n't seem to do a groupBy to them . is there a different way to sum them ? I 'm sorry i do n't share my code , but i ca n't . i can tell you i did it using foreach in just some if - else blocks but i think i should learn how to do it in LinqEDIT : I think i was n't clear . i want to sum the object by the Enum , meaning if i have : then the output will be [ Flags ] enum MyEnum { first = 1 , second = 2 , third = 4 , fourth = 8 } ; obj1.a = first , obj1.b = 5obj2.a = first | second , obj2.b = 3 first sum = 8second sum = 3",LINQ - groupBy with items in several Group "C_sharp : I am searching for a way that will automate adding declarations of Win32 API functions in C # code . For example , I currently have to add : when I want to call LoadLibrary . And similar for every other function that I want to call.Is there some list of all these Win32 declarations already so that I do n't have to keep adding them myself ? Or some other `` correct '' way of doing this ? [ DllImport ( `` kernel32.dll '' ) ] public static extern IntPtr LoadLibrary ( string path ) ;",How to automatically pull in Win32 API declarations in C # ? "C_sharp : I have written a LINQ to XML query that does what I want , but it looks pretty ugly . I am wondering , how would you guys format the following query in a way that does n't look quite so garish ? Apologies if my example is a bit verbose.The XML documents I am querying have the following structure : And corresponding LINQ query : Thanks ! < ? xml version= '' 1.0 '' encoding= '' iso-8859-1 '' ? > < newsitem itemid= '' 1 '' id= '' root '' date= '' 1996-08-20 '' xml : lang= '' en '' > < title > A title < /title > < headline > A headline < /headline > < dateline > A dateline < /dateline > < text > Some text < /text > < metadata > < codes class= '' '' > < code code= '' '' > < editdetail attribution= '' '' / > < /code > < /codes > < dc element= '' dc.date.created '' value= '' '' / > < dc element= '' dc.publisher '' value= '' '' / > < dc element= '' dc.date.published '' value= '' '' / > < dc element= '' dc.source '' value= '' '' / > < dc element= '' dc.creator.location '' value= '' '' / > < dc element= '' dc.creator.location.country.name '' value= '' '' / > < dc element= '' dc.source '' value= '' '' / > < /metadata > < /newsitem > XElement dummy = new XElement ( `` dummy '' ) ; var query = from article in newsdoc.Elements ( `` newsitem '' ) .DefaultIfEmpty ( dummy ) select new { NewsItemID = ( int ) article.Attribute ( `` itemid '' ) , Date = ( DateTime ) article.Attribute ( `` date '' ) , Title = ( string ) article.Element ( `` title '' ) , Headline = ( string ) article.Element ( `` headline '' ) , ByLine = ( string ) article.Element ( `` byline '' ) , DateLine = ( string ) article.Element ( `` dateline '' ) , NewsText = ( string ) article.Element ( `` text '' ) , Publisher = ( string ) article.Elements ( `` metadata '' ) .Elements ( `` dc '' ) .Where ( x = > ( string ) x.Attribute ( `` element '' ) == `` dc.publisher '' ) .Attributes ( `` value '' ) .DefaultIfEmpty ( ) .ElementAt ( 0 ) , DatePublished = ( DateTime ) article.Elements ( `` metadata '' ) .Elements ( `` dc '' ) .Where ( x = > ( string ) x.Attribute ( `` element '' ) == `` dc.date.published '' ) .Attributes ( `` value '' ) .DefaultIfEmpty ( ) .ElementAt ( 0 ) , Source = ( string ) article.Elements ( `` metadata '' ) .Elements ( `` dc '' ) .Where ( x = > ( string ) x.Attribute ( `` element '' ) == `` dc.source '' ) .Attributes ( `` value '' ) .DefaultIfEmpty ( ) .ElementAt ( 0 ) , CreatorLocation = ( string ) article.Elements ( `` metadata '' ) .Elements ( `` dc '' ) .Where ( x = > ( string ) x.Attribute ( `` element '' ) == `` dc.creator.location '' ) .Attributes ( `` value '' ) .DefaultIfEmpty ( ) .ElementAt ( 0 ) , CreatorLocationCountryName = ( string ) article.Elements ( `` metadata '' ) .Elements ( `` dc '' ) .Where ( x = > ( string ) x.Attribute ( `` element '' ) == `` dc.creator.location.country.name '' ) .Attributes ( `` value '' ) .DefaultIfEmpty ( ) .ElementAt ( 0 ) , Codes = article.Elements ( `` metadata '' ) .Elements ( `` codes '' ) .Elements ( `` code '' ) .Attributes ( `` code '' ) .DefaultIfEmpty ( ) } ;",Advice on the best way to structure/format a LINQ to XML query ? C_sharp : If I have a method like the following can I omit the catch block here to achieve the same results ? : private ClassInstance GetMeANumber ( ) { Resource a = null ; try { Resource a = new Resource ( ) ; return a.GetClassInstance ( ) ; } catch { throw ; } finally { if ( a ! = null ) a.Dispose ( ) ; } },Try Finally or Try Catch Finally "C_sharp : I have a c # control that I use inside of VB6 , which is basically a panel with rounded corners . I 'd like to know if there is a way to make that control a container , sort of like a Frame is a container . Basically I want to be able to place things inside it so they all move together , and most importantly place things In Front of it . Right now if I place , say , a label or a command on top of it , it goes behind my COM control and using Bring to Front and Send to Back does nothing.Do I need to declare it as a container in vb6 ? Does the code have to come from c # ? Edit : I have signed an NDA so I ca n't post the whole code here , but I 'll post some and explain some.There 's some other stuff to define a region with rounded corners as well , but it 's basically just a panel . I have a class that extends AzPanel , AzPanelCOM with the following attributes : As well as an interface , IAzPanelCOM , to expose it to VB6.On build I use `` regasm.exe '' to create a type library ( tlb ) that I import in VB6 on a virtual machine running Windows xp and vs2010 ( .net framework 4.0 ) .I can then instantiate AzPanels , resize them and move them even at design time , and I can add commands ( buttons ) to them with no problems . When it comes to shapes or labels , however , they seem to appear behind the panel and I ca n't bring them to the front . public class AzPanel : Panel { protected const int BORDER_WIDTH = 3 ; protected int BORDER_RADIUS = 4 ; private object _lock = new object ( ) ; private bool regionNeedsRefresh = false ; public AzPanel ( ) : base ( ) { this.SetStyle ( ControlStyles.DoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint , true ) ; this.SetStyle ( ControlStyles.SupportsTransparentBackColor , true ) ; this.SetStyle ( ControlStyles.Selectable , false ) ; base.BackColor = Color.Transparent ; this.BorderColor = Color.DarkRed ; this.ContentColor = Color.DarkGoldenrod ; this.DoubleBuffered = true ; base.Padding = new Padding ( 3 , 3 , 4 , 4 ) ; } } [ Guid ( `` ... '' ) ] [ ProgId ... ] [ ComVisible ( true ) ] [ ComdefaultInterface ... ] [ ClassInterface ( ClassInterfaceType.AutoDispatch ) ] [ Guid ( `` ... '' ) ] [ ComVisible ( true ) ] public interface IAzPanelCOM { void DesignTimeReload ( ) ; //some other things }",COM control in VB6 : Make a container out of the control "C_sharp : I am trying to calculate memory . I have calculated Available , InUse , Free , and Cached with the following codeHow can I calculate Standby , Hardware Reserved , and Modified memory as shown in Resource Monitor in windows ? ObjectQuery wql = new ObjectQuery ( `` SELECT * FROM Win32_OperatingSystem '' ) ; ManagementObjectSearcher searcher = new ManagementObjectSearcher ( wql ) ; ManagementObjectCollection results = searcher.Get ( ) ; //total amount of free physical memory in bytes var Available = new ComputerInfo ( ) .AvailablePhysicalMemory ; //total amount of physical memory in bytes var Total = new ComputerInfo ( ) .TotalPhysicalMemory ; var PhysicalMemoryInUse = Total - Available ; Object Free = new object ( ) ; foreach ( var result in results ) { //Free amount Free = result [ `` FreePhysicalMemory '' ] ; } var Cached = Total - PhysicalMemoryInUse - UInt64.Parse ( Free.ToString ( ) ) ;",Algorithm To Calculate Different Types Of Memory "C_sharp : I have a referenced library , inside there I want to perform a different action if the assembly that references it is in DEBUG/RELEASE mode . Is it possible to switch on the condition that the calling assembly is in DEBUG/RELEASE mode ? Is there a way to do this without resorting to something like : The referencing assembly will always be the starting point of the application ( i.e . web application . bool debug = false ; # if DEBUGdebug = true ; # endifreferencedlib.someclass.debug = debug ;",How to tell if calling assembly is in DEBUG mode from compiled referenced lib "C_sharp : The reason this code works is due to the fact that the Enumerator can not modify the collection : If we try to do the same thing with a List < object > , instead of IEnumerable < object > , we would get a compiler error telling us that we can not implicitly convert type List < string > to List < object > . Alright , that one makes sense and it was a good decision by Microsoft , in my opinion , as a lesson learned from arrays . However , what I ca n't figure out is why in the world is this hardline rule applicable to something like ReadOnlyCollection ? We wo n't be able to modify the elements in the ReadOnlyCollection , so what is the safety concern that caused Microsoft to prevent us from using covariance with something that 's read-only ? Is there a possible way of modifying that type of collection that Microsoft was trying to account for , such as through pointers ? var roList = new List < string > ( ) { `` One '' , `` Two '' , `` Three '' } ; IEnumerable < object > objEnum = roList ;",Why is covariance not allowed with ReadOnlyCollection ? "C_sharp : I have experienced a very strange issue which I can not find the cause of.In my Asp.Net MVC app ( .net4.0/MVC4 ) I am rending html data attributes within some html element to then be used within the JavaScript.So in the app I have a Model , e.g.I am then passing this model through onto a simple MVC view page and rendering the boolean value into the html data attribute , e.g.Now when running the project locally the html is rendered as : However when running on the server , the html is rendered as : At first I thought that maybe the boolean was not being set somehow , so I added this to the element Click Me @ Model.MyFlag which renders as Click Me True . Now I suspected that this has maybe something to do with Debug vs Release mode , however after playing about with this it made no difference.My fix to this was to change the code to output the boolean value as a string value , e.g . data-is-flagged= '' @ Model.MyFlag.ToString ( ) '' which then renders the same locally and on the server.Any ideas what is the cause of this ? public class MyModel { public bool MyFlag { get ; set ; } } @ model MyProject.MyModel < a href= '' # '' data-is-flagged= '' @ Model.MyFlag '' > Click Me < /a > < a href= '' # '' data-is-flagged= '' True '' > Click Me < /a > < a href= '' # '' data-is-flagged= '' data-is-flagged '' > Click Me < /a >",MVC Html data attribute rendering difference "C_sharp : How can I enable visual studio to 'Go to implementation ' for library code that is exposed with SourceLink ? We recently began using SourceLink in our .NETcore library in an attempt to debug the library while consuming it . We enabled SourceLink using this project : ctaggart/SourceLink by adding the following line to our csproj : This has worked great in that I are now able to step into the library code with the debugger , but I am unable to jump to implementation/definition of any of this library code . Is there a way I can get visual studio to do this ? < PackageReference Include= '' SourceLink.Embed.AllSourceFiles '' Version= '' 2.6.0 '' PrivateAssets= '' All '' / >",Go to Implementation with sourcelink "C_sharp : I 'm sorry if this is a silly question ( or a duplicate ) .I have a function A : the I have another function B , calling A but not using the return value : Note that B is not declared async and is not awaiting the call to A . The call to A is not a fire-and-forget call - B is called by C like so : Notice that at # 1 , there 's no await . I have a coworker that claims that this makes the call to A synchronous and he keeps coming up with Console.WriteLine logs that seemingly prove his point . I tried pointing out that just because we do n't wait for the results inside B , the task chain is awaited and the nature of the code inside A does n't change just because we do n't await it . Since the return value from A is not needed , there 's no need to await the task at the call site , as long as someone up the chain awaits it ( which happens in C ) .My coworker is very insistent and I began to doubt myself . Is my understanding wrong ? public async Task < int > A ( /* some parameters */ ) { var result = await SomeOtherFuncAsync ( /* some other parameters */ ) ; return ( result ) ; } public Task B ( /* some parameters */ ) { var taskA = A ( /* parameters */ ) ; // # 1 return ( taskA ) ; } public async Task C ( ) { await B ( /* parameters */ ) ; }","Not awaiting an async call is still async , right ?" "C_sharp : It seems that AspNet.Core starts sending response that is IEnumerable right away without iterating over the whole collection . E.g . : Now there is an exception that happens during mapping of one of the elements , so I would assume a 500 response , but in reality what happens is that I get a 200 with only partial ( and incorrect ) Json.I assume it 's a feature and not a bug in Asp.Net Core that provides this behavior and it is additionally relatively easy to fix by calling e.g . ToList ( ) , but I am wondering if there is some kind of flag that can prevent this situation from happening since it does not really make sense for e.g . API project and standard JSON response.I was not able to find anything in documentation that describes this behavior and how to prevent it.P.S . I have verified that calling ToList ( ) fixes the issue and the response is 500 with correct exception ( with UseDeveloperExceptionPage ) [ HttpGet ( `` '' ) ] public async Task < IActionResult > GetData ( ) { IEnumerable < MyData > result = await _service.GetData ( ) ; return Ok ( result.Select ( _mapper.MapMyDataToMyDataWeb ) ) ; }",AspNet.Core returns 200 OK and invalid Json if there is an exception while iterating an IEnumerable ( returned from controller ) "C_sharp : In a code sample I saw a foreach loop going over the matches of a regex . Inside the loop there was a check for match.Success . But would n't all these matches be a success ? Otherwise they would n't be matches , would they ? Am I wrong to think that ( in this situation ) the check is redundant ? var regex = new Regex ( pattern ) ; var matches = regex.Matches ( input ) ; var list = new List < string > ( ) ; foreach ( Match m in matches ) { if ( m.Success ) { list.Add ( m.Value ) ; } }",Why check for Match.Success "C_sharp : I found this statement is some old code and it took me a second to figure out ... Please correct me if I 'm wrong but is n't this the same as this one ? : If it is , why would you ever want to use the first ? Which one is more readable ? ( I think the latter , but I 'd like to see what others think . ) IsTestActive = ( TestStateID == 1 ? true : false ) ; IsTestActive = ( TestStateID == 1 ) ;",Setting a boolean value based on an integer "C_sharp : Please help understand this behavior . When I use this : The result is falseBut when I use thisThe result is trueSo , why a1 ! = a2 ? bool a1 = ( object ) ( `` string '' + 1 ) == ( `` string '' + 1 ) ; bool a2 = ( object ) ( `` string '' + `` 1 '' ) == ( `` string '' + `` 1 '' ) ;",C # concatenation strings while compiling "C_sharp : I have the following Expander defined for a DataGrid . I need to display the item name in the left and the sum in the right end of the group header . However what I get is this : How can I move the 'Total ' to the right end of the header ? < Expander IsExpanded= '' True '' HorizontalAlignment= '' Stretch '' Background= '' Blue '' > < Expander.Header > < Grid HorizontalAlignment= '' Stretch '' Background= '' BurlyWood '' > < Grid.ColumnDefinitions > < ColumnDefinition Width= '' 3* '' / > < ColumnDefinition Width= '' * '' / > < /Grid.ColumnDefinitions > < TextBlock Text= '' { Binding Path=Name , StringFormat=\ { 0 : D\ } } '' FontWeight= '' Bold '' / > < StackPanel Orientation= '' Horizontal '' HorizontalAlignment= '' Right '' Grid.Column= '' 1 '' > < TextBlock Text= '' Total : `` / > < TextBlock Text= '' { Binding Path=Items , Converter= { StaticResource sumConverter } } '' FontWeight= '' Bold '' / > < /StackPanel > < /Grid > < /Expander.Header > < ItemsPresenter / > < /Expander >",Grid expander header - ca n't get arrangement right "C_sharp : I want to enforce on my code base immutable rule with following testIt passes for : but does n't for this : And here goes the question `` WTF ? '' [ TestFixture ] public class TestEntityIf { [ Test ] public void IsImmutable ( ) { var setterCount = ( from s in typeof ( Entity ) .GetProperties ( BindingFlags.Public | BindingFlags.Instance ) where s.CanWrite select s ) .Count ( ) ; Assert.That ( setterCount == 0 , Is.True , `` Immutable rule is broken '' ) ; } } public class Entity { private int ID1 ; public int ID { get { return ID1 ; } } } public class Entity { public int ID { get ; private set ; } }",.net Immutable objects "C_sharp : I want to make an interface in C # that defines a method that always returns an object of the implementing class , thus : Can I force an implementing class to return an object of its own type ? If possible , then how ? Or is generics the answer here ? NB : The code is just an illustration , not something that 's supposed to run . public interface IParser { IParser Parse ( string s ) ; } public class Parser : IParser { public Parser Parse ( string s ) { return new Parser ( s ) ; } }",Can I force an implementing class to return an object of its own type ? "C_sharp : I am struggeling with the Kinect for Windows SDK to create an application for conducting ( with C # ) .Basically I need to track one hand ( usually the right one ) of a conductor and recognize his speed in directing ( BPM ) to send this value to another application via MIDI.What I started with is the SkeletonFramesReadyEvent adding the JointType.HandRight with a DateTime.Now.Ticks timestamp to a history List which is updated and removes the first entry . I keep the history of 60 frames ( 2 seconds ) .I calculate the BPM by searching for the last low and high of the Joint.Position.Y and then calculate the difference and divide bpm = 60*ticksPerSecond/diff . However the result is wrong . Is there another way of doing this ? What am I missing ? This is what I am using so far : public int DetectBPM ( JointType type ) { // we have not history yet if ( ! HasHistory ( ) ) return 0 ; // only calculate every second var detectTime = DateTime.Now.Second ; if ( _lastBPM ! = 0 & & _lastBPMDectect == detectTime ) return _lastBPM ; // search last high/low boundaries var index = ( int ) type ; var list = History [ index ] ; var i = list.Count - 1 ; var lastHigh = list [ i ] ; var lastLow = list [ i ] ; // shift to last peak first while ( i > 0 & & list [ i ] .Joint.Position.Y > = list [ i - 1 ] .Joint.Position.Y ) i -- ; // find last low while ( i > = 0 & & lastLow.Joint.Position.Y > = list [ i ] .Joint.Position.Y ) lastLow = list [ i -- ] ; // find last high while ( i > = 0 & & lastHigh.Joint.Position.Y < = list [ i ] .Joint.Position.Y ) lastHigh = list [ i -- ] ; var ticks = lastLow.Timestamp - lastHigh.Timestamp ; var elapsedTime = new TimeSpan ( ticks ) ; var bpm = ( int ) ( 60000/elapsedTime.TotalMilliseconds ) ; Console.WriteLine ( `` DEBUG : BPM = `` + _lastBPM + `` , elapsedMS : `` + elapsedTime.TotalMilliseconds ) ; _lastBPMDectect = detectTime ; _lastBPM = bpm ; return _lastBPM ; }",Calculate BPM from Kinect sensor data C_sharp : Will the following code work if resource does n't implement IDisposable ? T resource = new T ( ) ; using ( resource as IDisposable ) { ... },Will using work on null ? C_sharp : I 'm trying to remove multiple nodes that a particular element ( path ) contains a value but I 'm receiving a System.NullReferenceException any help where I 'm going wrong would I'be much appreciated.My xml looks like this : My code looks like this : I 'm not sure where I 'm going wrong . < ? xml version= '' 1.0 '' encoding= '' utf-8 '' standalone= '' yes '' ? > < ApplicationData Version= '' 12.5.1 '' RootPath= '' FireFox-FILES '' > < RegistrySystem > < DIR Operation= '' + '' Path= '' C : \Temp\Microsoft\MediaPlayer\ShimInclusionList '' / > < DIR Operation= '' + '' Path= '' C : \Temp\MediaPlayer\ShimInclusionList\MM.EXE '' / > < DIR Operation= '' + '' Path= '' C : \Temp\MediaPlayer\ShimInclusionList\plugin-container.exe '' / > < DIR Operation= '' + '' Path= '' C : \Temp\Microsoft\MediaPlayer '' > < ENTRY Name= '' '' Value= '' 43.0.4 '' Type= '' 1 '' / > < ENTRY Name= '' CurrentVersion '' Value= '' 43.0.4 ( x86 en-GB ) '' Type= '' 1 '' / > < /DIR > < DIR Operation= '' + '' Path= '' C : \Program Files\Microsoft\MediaPlayer\ShimInclusionList\plugin-container.exe '' / > < DIR Operation= '' + '' Path= '' C : \Program Files\Microsoft\MediaPlayer\ShimInclusionList2\plugin.exe '' / > < DIR Operation= '' + '' Path= '' C : \Program Files\Microsoft\MediaPlayer\ShimInclusionList2\container.exe '' / > < DIR Operation= '' + '' Path= '' C : \Program Files\Microsoft\MediaPlayer\ShimInclusionList4 '' > < ENTRY Name= '' '' Value= '' 43.0.4 '' Type= '' 1 '' / > < ENTRY Name= '' CurrentVersion '' Value= '' 43.0.4 ( x86 en-GB ) '' Type= '' 1 '' / > < /DIR > < /RegistrySystem > < /ApplicationData > XDocument xdoc = XDocument.Load ( XmlFile ) ; foreach ( var node in xdoc.Descendants ( `` DIR '' ) .Where ( status = > status.Attribute ( `` Path '' ) .Value.Contains ( @ '' C : \Temp\ '' ) ) ) { node.Remove ( ) ; } xdoc.Save ( XmlFile ) ;,Delete multiple XML nodes in C # using Linq "C_sharp : I have a gridview used to display records based on a selected value in a drop down.Within the gridview , there are a dynamic number of bound field columns added in code behind , followed by a drop down list in a template field and a button in a second template field.The problem is , when I click on the button , the template fields disappear.GRID VIEWCODE BEHINDMethod GridViewTools.CreateBoundField is a custom method that sets my default boundfield attributes and returns the BoundField object . In testing it , the gridview populates as desired on the initial load . However , the RowCommand event does not fire and both template fields disappear when the button is clicked . The next gridview.RowDataBound event then throws a null object error because the drop down list is no longer found in the row . If I remove lines adding the bound fields [ Columns.Insert ] , the RowCommand fires as expected when btnSave is clicked and the template fields persist . If I add even a single bound field column again , the RowCommand does not fire and the template fields disappear.Any suggestions ? Why would adding a new column to a gridview invalidate the RowCommand event for a pre-existing button and make the template fields disappear ? UPDATESI 've removed the template fields from the Grid View declaration and added the controls to a bound field instead , but still get the same result . The show on the initial load , but disappear once clicked . I 've also looked at the grid view in the Page_Unload event , and it still contains the columns at that point , even though they do n't show on screen . Is there any event I can capture after Page_Unload ? < asp : UpdatePanel ID= '' upnlDetail '' runat= '' server '' UpdateMode= '' Conditional '' > < ContentTemplate > < asp : GridView ID= '' gvDetails '' runat= '' server '' AutoGenerateColumns= '' false '' SkinID= '' gridviewGray '' CellPadding= '' 3 '' OnRowCommand= '' gvDetails_RowCommand '' OnRowDataBound= '' gvDetails_RowDataBound '' AllowSorting= '' true '' > < Columns > < asp : TemplateField > < ItemTemplate > < asp : DropDownList ID= '' ddlStatus '' runat= '' server '' AutoPostBack= '' true '' OnSelectedIndexChanged= '' ddlStatus_SelectedIndexChanged '' > < /asp : DropDownList > < /ItemTemplate > < /asp : TemplateField > < asp : TemplateField > < ItemTemplate > < asp : Button ID= '' btnSave '' runat= '' server '' CommandName= '' Save '' CommandArgument= '' < % # ( ( GridViewRow ) Container ) .RowIndex % > '' Text= '' Save '' / > < /ItemTemplate > < /asp : TemplateField > < /Columns > < /asp : GridView > < /ContentTemplate > < /asp : UpdatePanel > while ( gvDetails.Columns.Count > 2 ) //Do n't remove the rightmost columns { gvDetails.Columns.RemoveAt ( 0 ) ; } gvDetails.Columns.Insert ( 0 , GridViewTools.CreateBoundField ( `` Request.Amount '' , `` Amount '' , `` Money '' , 50 ) ) ; gvDetails.Columns.Insert ( 0 , GridViewTools.CreateBoundField ( `` Request.CustomerName '' , `` Customer '' , `` comment '' , 200 ) ) ; gvDetails.Columns.Insert ( 0 , GridViewTools.CreateBoundField ( `` Request.BillAccountFormatted '' , `` Account '' , `` text '' , 100 ) ) ; gvDetails.Columns.Insert ( 0 , GridViewTools.CreateBoundField ( `` Request.Id '' , `` Request '' , `` int '' , 50 ) ) ; gvDetails.DataSource = dt ; gvDetails.DataBind ( ) ; public static BoundField CreateBoundField ( ... ) { ... }",Template field disappears "C_sharp : Hey all - I have an app where I 'm authenticating the user . They pass username and password . I pass the username and password to a class that has a static method . For example it 'm calling a method with the signature below : If I have 1000 people hitting this at once , will I have any problems with the returns of the method bleeding into others ? I mean , since the methods are static , will there be issues with the a person getting authenticated when in fact they should n't be but the person before them was successfully authenticated ASP.Net returns a mismatched result due to the method being static ? I 've read of issues with static properties vs viewstate but am a bit confused on static methods . If this is a bad way of doing this , what 's the prefered way ? public class Security { public static bool Security.Member_Authenticate ( string username , string password ) { //do stuff } }",Static methods in a class - okay in this situation ? "C_sharp : Note : This is not a duplicate of `` Use of IsAssignableFrom and “ is ” keyword in C # '' . That other question asks about typeof ( T ) .IsAssignableFrom ( type ) ) , where type is not an object but a Type . This seems trivial — I can hear you saying , `` Just call x.GetType ( ) ! '' — but due to the COM-related corner case mentioned below , that call causes problems , which is why I 'm asking about the rewrite.… or are there rare special cases where the two might give different results ? I stumbled upon a type check of the form : where TValue is a generic type parameter ( without any constraints ) and value is an object.I am not entirely sure whether it is safe to rewrite the above simply as : To my current knowledge , the two tests are equivalent with the exception of COM objects . is should trigger a proper QueryInterface , while IsAssignableFrom might get confused by the __ComObject RCW wrapper type and report a false negative.Are there any other differences between is and the shown use of IsAssignableFrom ? typeof ( TValue ) .IsAssignableFrom ( value.GetType ( ) ) value is TValue",Can ` typeof ( T ) .IsAssignableFrom ( x.GetType ( ) ) ` be safely rewritten as ` x is T ` ? "C_sharp : I worked a little with StructureMap and I managed to inject in my controller ( through constructor injection ) a concrete type repository for an interface.Now , I need to inject a repository type into my custom membership provider . But how ? My custom membership provider is created through Membership.Provider.ValidateUser ( for example ) .For controller I created a class like this : and in Global.asax , in Application_Start ( ) : But how inject an concrete type in my custom membership provider with StructureMap ? public class IocControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance ( System.Web.Routing.RequestContext requestContext , Type controllerType ) { return ( Controller ) ObjectFactory.GetInstance ( controllerType ) ; } } // ... ObjectFactory.Initialize ( x = > { x.AddRegistry ( new ArticleRegistry ( ) ) ; } ) ; ControllerBuilder.Current.SetControllerFactory ( new IocControllerFactory ( ) ) ; // ...",Inject in custom membership provider with StructureMap "C_sharp : I 'm about 15 minutes into my first play with the async CTP ... ( nice ) .Here 's a really simple server I 've knocked together : As can be seen , the async method Go calls itself . In classic non-async world , this would cause a stack overflow . I assume that this is n't the case with an async method , but I 'd like to be sure , one way or the other . Anyone ? internal class Server { private HttpListener listener ; public Server ( ) { listener = new HttpListener ( ) ; listener.Prefixes.Add ( `` http : //*:80/asynctest/ '' ) ; listener.Start ( ) ; Go ( ) ; } async void Go ( ) { HttpListenerContext context = await listener.GetContextAsync ( ) ; Go ( ) ; using ( var httpListenerResponse = context.Response ) using ( var outputStream = httpListenerResponse.OutputStream ) using ( var sw = new StreamWriter ( outputStream ) ) { await sw.WriteAsync ( `` hello world '' ) ; } } }",async ctp recursion "C_sharp : According to the MSDN the DbSet : A DbSet represents the collection of all entities in the context , or that can be queried from the database , of a given type . DbSet objects are created from a DbContext using the DbContext.Set method.And according to the MSDN the DbContext : A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit . DbContext is conceptually similar to ObjectContext.So that the EF use the repository pattern and the UOW internally . DbSet < -- -- > Repository DbContext < -- -- > Unit Of WorkWhy should I build a repository pattern with a unit of work on the top of my EF ? DbSet < TEntity > Class DbContext Class",Why should i build a repository pattern with a unit of work on the top of my EF ? "C_sharp : I 'm no expert at async despite having written C # for many years , but AFAICT after reading some MSDN blog posts : Awaitables ( such as Task ) may either capture or not capture the current SynchronizationContext.A SynchronizationContext roughly corresponds to a thread : if I 'm on the UI thread and call await task , which 'flows context ' , the continuation is run on the UI thread . If I call await task.ConfigureAwait ( false ) , the continuation is run on some random threadpool thread which may/may not be the UI thread.For awaiters : OnCompleted flows context , and UnsafeOnCompleted does not flow context.OK , with that established , let 's take a look at the code Roslyn generates for await Task.Yield ( ) . This : Results in this compiler-generated code ( you may verify yourself here ) : Notice that AwaitUnsafeOnCompleted is being called with the awaiter , instead of AwaitOnCompleted . AwaitUnsafeOnCompleted , in turn , calls UnsafeOnCompleted on the awaiter . YieldAwaiter does not flow the current context in UnsafeOnCompleted.This really confuses me because this question seems to imply that Task.Yield does capture the current context ; the asker is frustrated that at the lack of a version that does n't . So I 'm confused : does or does n't Yield capture the current context ? If it does n't , how can I force it to ? I 'm calling this method on the UI thread , and I really need the continuation to run on the UI thread , too . YieldAwaitable lacks a ConfigureAwait ( ) method , so I ca n't write await Task.Yield ( ) .ConfigureAwait ( true ) .Thanks ! using System ; using System.Threading.Tasks ; public class C { public async void M ( ) { await Task.Yield ( ) ; } } public class C { [ CompilerGenerated ] [ StructLayout ( LayoutKind.Auto ) ] private struct < M > d__0 : IAsyncStateMachine { public int < > 1__state ; public AsyncVoidMethodBuilder < > t__builder ; private YieldAwaitable.YieldAwaiter < > u__1 ; void IAsyncStateMachine.MoveNext ( ) { int num = this. < > 1__state ; try { YieldAwaitable.YieldAwaiter yieldAwaiter ; if ( num ! = 0 ) { yieldAwaiter = Task.Yield ( ) .GetAwaiter ( ) ; if ( ! yieldAwaiter.IsCompleted ) { num = ( this. < > 1__state = 0 ) ; this. < > u__1 = yieldAwaiter ; this. < > t__builder.AwaitUnsafeOnCompleted < YieldAwaitable.YieldAwaiter , C. < M > d__0 > ( ref yieldAwaiter , ref this ) ; return ; } } else { yieldAwaiter = this. < > u__1 ; this. < > u__1 = default ( YieldAwaitable.YieldAwaiter ) ; num = ( this. < > 1__state = -1 ) ; } yieldAwaiter.GetResult ( ) ; yieldAwaiter = default ( YieldAwaitable.YieldAwaiter ) ; } catch ( Exception arg_6E_0 ) { Exception exception = arg_6E_0 ; this. < > 1__state = -2 ; this. < > t__builder.SetException ( exception ) ; return ; } this. < > 1__state = -2 ; this. < > t__builder.SetResult ( ) ; } [ DebuggerHidden ] void IAsyncStateMachine.SetStateMachine ( IAsyncStateMachine stateMachine ) { this. < > t__builder.SetStateMachine ( stateMachine ) ; } } [ AsyncStateMachine ( typeof ( C. < M > d__0 ) ) ] public void M ( ) { C. < M > d__0 < M > d__ ; < M > d__. < > t__builder = AsyncVoidMethodBuilder.Create ( ) ; < M > d__. < > 1__state = -1 ; AsyncVoidMethodBuilder < > t__builder = < M > d__. < > t__builder ; < > t__builder.Start < C. < M > d__0 > ( ref < M > d__ ) ; } }",Does Task.Yield really run the continuation on the current context ? "C_sharp : For example : To me , that reads `` a method that can be accessed by anyone , regardless of assembly living inside a class that can only be accessed from code in the same assembly '' .My experience with the compiler tells me that if I do something like that and do not get a warning , there is probably a valid reason to have it.So , I suppose eitherSomething is lacking in my understanding of protection levels.There could be a warning but there is n't one . ( if 2 , this is not an attempt to complain about it - I just want to understand ) internal class C { public void M ( ) { Console.WriteLine ( `` foo '' ) ; } }",What is the meaning of a public member of an internal class ? "C_sharp : I am abstracting the history tracking portion of a class of mine so that it looks like this : My problem is that I would like to unit test that Remove will return the last Added object.AddObjectToHistoryRemoveObjectToHistory - > returns what was put in via AddObjectToHistoryHowever , it is n't really a unit test if I have to call Add first ? But , the only way that I can see to do this in a true unit test way is to pass in the Stack object in the constructor OR mock out IsAnyHistory ... but mocking my SUT is odd also . So , my question is , from a dogmatic view is this a unit test ? If not , how do I clean it up ... is constructor injection my only way ? It just seems like a stretch to have to pass in a simple object ? Is it ok to push even this simple object out to be injected ? private readonly Stack < MyObject > _pastHistory = new Stack < MyObject > ( ) ; internal virtual Boolean IsAnyHistory { get { return _pastHistory.Any ( ) ; } } internal virtual void AddObjectToHistory ( MyObject myObject ) { if ( myObject == null ) throw new ArgumentNullException ( `` myObject '' ) ; _pastHistory.Push ( myObject ) ; } internal virtual MyObject RemoveLastObject ( ) { if ( ! IsAnyHistory ) throw new InvalidOperationException ( `` There is no previous history . `` ) ; return _pastHistory.Pop ( ) ; }",Unit testing a class that tracks state "C_sharp : recently I have seen this codebut i could n't know how to make my code look like this one using visual c # 2010 , do you know any shortcut or tool to do that automatically ? .EDITi have also another related question , if i want to align declarations like this-it seems that it ca n't be done using prductivity power tools extension-do you have any idea how to do it ? thanks alot for your help ! arrMove = new List < int [ ] > ( 4 ) ; m_pppiCaseMoveDiagLine = new int [ 64 ] [ ] [ ] ; m_pppiCaseMoveDiagonal = new int [ 64 ] [ ] [ ] ; m_pppiCaseMoveLine = new int [ 64 ] [ ] [ ] ; m_ppiCaseMoveKnight = new int [ 64 ] [ ] ; m_ppiCaseMoveKing = new int [ 64 ] [ ] ; m_ppiCaseWhitePawnCanAttackFrom = new int [ 64 ] [ ] ; m_ppiCaseBlackPawnCanAttackFrom = new int [ 64 ] [ ] ; private PlayerColorE m_eNextMoveColor ; private int [ ] m_piPiecesCount ; private Random m_rnd ; private int m_iAttackedPieces ;",How to refine code in visual c # ? "C_sharp : What is the easiest way to get an ISymbol from a ClassDeclaration that I just created ? Consider the following code : The last line throws an exception saying `` Syntax node is not within syntax tree '' .I assume I need to get the ClassDeclarationSyntax that I just created again from the new SyntaxTree . But what is the easiest way to find it in the new SyntaxTree given that I only have the old ClassDeclarationSyntax ? In the example above the class is the only class in the SyntaxTree and is the first child of the CompilationUnit , so it would be easy to find in this simple case . But imagine a situation where the syntax tree contains a lot of declarations , that may be nested , and the sought after class declaration is nested deep within ? Is there some way to use the old ClassDeclarationSyntax to find the new one ? ( Or am I going about things all wrong here ? ) AdhocWorkspace workspace = new AdhocWorkspace ( ) ; Project project = workspace.AddProject ( `` Test '' , LanguageNames.CSharp ) ; ClassDeclarationSyntax classDeclaration = SyntaxFactory.ClassDeclaration ( `` MyClass '' ) ; CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit ( ) .AddMembers ( classDeclaration ) ; Document document = project.AddDocument ( `` Test.cs '' , compilationUnit ) ; SemanticModel semanticModel = await document.GetSemanticModelAsync ( ) ; ISymbol symbol = semanticModel.GetDeclaredSymbol ( classDeclaration ) ; // < -- Throws Exception",How to get declared symbol from SemanticModel for newly created class ? "C_sharp : I have the following C # code : How many string objects are created ? I think 7 string objects are created : `` String 1 '' , `` String 2 '' , `` String 3 '' , stg1 + stg3 , stg4 + stg2 + stg3 , `` '' , and `` '' . I was n't sure if the 4th statement ( string stg4 ; ) creates a string object and I read somewhere that assigning a string the empty string `` '' does n't create an object but I do n't think that 's true . What do you guys think ? string stg1 = `` String 1 '' ; string stg2 = `` String 2 '' ; string stg3 = `` String 3 '' ; string stg4 ; stg4 = stg1 + stg3 ; stg4 = stg4 + stg2 + stg3 ; stg4 = `` '' ; stg3 = `` '' ;",How many string objects are created ? "C_sharp : There have been many threads started over the confusion in the way that Math.Round works . For the most part , those are answered by cluing people in to the MidpointRounding parameter and that most people are expecting MidpointRounding.AwayFromZero . I have a further question though about the actual algorithm implemented by AwayFromZero.Given the following number ( the result of a number of calculations ) : 13.398749999999999999999999999Mour users are expecting to see the same result that Excel would give them 13.39875 . As they are currently rounding that number to 4 using Math.Round ( num , 4 , MidpointRounding.AwayFromZero ) , the result is off by .0001 from what they expect . Presumably , the reason for this is that the algorithm just looks at the fifth digit ( 4 ) , and then rounds accordingly . If you were to start rounding at the last 9 , the real mathematical answer would in fact give you the same number as excel . So the question is ... is there a way to emulate this behavior rather than the current ? I 've written a recursive function that we could use in the meantime . But before we put it in production I wanted to see what SO thought about the problem : - ) Edit : just for clarity , I should have been clearer in my original post . The position of rounding methodology being asked for here is what I 'm being presented by the business analysts and users who are reporting the `` rounding error '' . Despite being told numerous times that it 's not incorrect , just different than what they are expecting ... this report keeps coming in . So I am just on a data gathering stint to gather as much information as I can on this topic to report back to the users.In this case , it seems that any other system used to generate these average prices ( which we must match ) are using a different level precision ( 10 in the database , and excel seems to default to 15 or something ) . Given that everyone has a different level of precision , I 'm stuck in the middle with the question of moving to a lower precision , some weird rounding rules ( as described above ) , or just having different results than the users expect . private decimal Round ( decimal num , int precision ) { return Round ( num , precision , 28 ) ; } private decimal Round ( decimal num , int precision , int fullPrecision ) { if ( precision > = fullPrecision ) return Math.Round ( num , precision ) ; return Round ( Math.Round ( num , fullPrecision ) , precision , -- fullPrecision ) ; }","Math.Round methodology , starting at the smallest decimal" "C_sharp : So far I 've been using this code to find my documents and then sort them : I have a class that has Metadata field with path and type fields , also the class has a Filename field . I want all documents with a given path inside the metadata sorted by type and then by Filename.An example result would be a list of documents ordered by the Name field like this : Unfortunately , I get something like this : And that 's because MongoDB sorts the data with a simple binary comparison , where ' A ' < ' a ' because of their ASCII codes.So my question is : Is there a way to make a case insensitive sort and keep using the `` $ hint '' ? That options I pass to the Find method should tell MongoDB which index to use . I found this post : MongoDB and C # : Case insensitive search but the method here does n't work for sorting and I could n't tell MongoDB which index to use . var options = new FindOptions { Modifiers = new BsonDocument ( `` $ hint '' , `` PathTypeFilenameIndex '' ) } ; return await Collection .Find ( f = > f.Metadata [ `` path '' ] == path , options ) .SortBy ( f = > f.Metadata [ `` type '' ] ) .ThenBy ( f = > f.Filename ) .ToListAsync ( ) ; a , Ab , B , c , D Ab , B , D , a , c",MongoDB C # Case Insensitive Sort and Index "C_sharp : I 've been toying around with some .NET features ( namely Pipelines , Memory , and Array Pools ) for high speed file reading/parsing . I came across something interesting while playing around with Array.Copy , Buffer.BlockCopy and ReadOnlySequence.CopyTo . The IO Pipeline reads data as byte and I 'm attempting to efficiently turn it into char.While playing around with Array.Copy I found that I am able to copy from byte [ ] to char [ ] and the compiler ( and runtime ) are more than happy to do it.This code runs as expected , though I 'm sure there are some UTF edge cases not properly handled here.My curiosity comes with Buffer.BlockCopyThe resulting contents of outputBuffer are garbage . For example , with the example contents of buffer asThe contents of outputBuffer after the copy isI 'm just curious what is happening `` under the hood '' inside the CLR that is causing these 2 commands to output such different results . char [ ] outputBuffer = ArrayPool < char > .Shared.Rent ( inputBuffer.Length ) ; Array.Copy ( buffer , 0 , outputBuffer , 0 , buffer.Length ) ; char [ ] outputBuffer = ArrayPool < char > .Shared.Rent ( inputBuffer.Length ) ; Buffer.BlockCopy ( buffer , 0 , outputBuffer , 0 , buffer.Length ) ; { 50 , 48 , 49 , 56 , 45 } { 12338 , 14385 , 12333 , 11575 , 14385 }",Buffer.BlockCopy vs Array.Copy curiosity "C_sharp : Looking at this code : This is a GUI ( windows forms ) application , which means that there is only one thread executing each line of code.All BBB ( data ) invocations are invoked very quick without waiting.Each BBB invocation get 's into the BBB method , sees await which does n't complete and returns ( to AAA ) .Now , when one second ( approx ) is elapsed , all continuations are happening in the GUI thread.QuestionContinuations does n't happen simultaneously because it 's a GUI thread .So a previous statement of : Must have occurred.In other words , I know that all BBBs are invoked with the same initial value of data , but the continuations does n't happens concurrentlyThe GUI thread must run eventually : continuation # 1continuation # 2 continuation # 3It looks like the continuations are scheduled not as a whole but as shared quanta ? public class SharedData { public int Value { get ; set ; } } void button1_Click ( object sender , EventArgs e ) { AAA ( ) ; } async Task BBB ( SharedData data ) { await Task.Delay ( TimeSpan.FromSeconds ( 1 ) ) ; MessageBox.Show ( data.Value.ToString ( ) ) ; // < -- -- I always see 0 here , data.Value = data.Value + 1 ; } async Task < int > AAA ( ) { SharedData data = new SharedData ( ) ; var task1 = BBB ( data ) ; var task2 = BBB ( data ) ; var task3 = BBB ( data ) ; await Task.WhenAll ( task1 , task2 , task3 ) ; MessageBox.Show ( data.Value.ToString ( ) ) ; // < -- - this does show 3 return data.Value ; } data.Value = data.Value + 1 ; MessageBox.Show ( data.Value.ToString ( ) ) ; data.Value = data.Value + 1 ; //So this basically should do 0 -- > 1 ... . MessageBox.Show ( data.Value.ToString ( ) ) ; // Why data.Value still `` 0 '' ? ? data.Value = data.Value + 1 ; ... . MessageBox.Show ( data.Value.ToString ( ) ) ; // Why data.Value still `` 0 '' ? ? data.Value = data.Value + 1 ;",Value is not updating after async method resume "C_sharp : I 'm passing a System.Action as a parameter to a method which does some lengthy operation and want to add more stuff to the invocation list after the Action has been passed : However , only the the stuff that was added with += before passing the Action as parameter is invoked . So , in this example , it will only print `` a '' but not `` b '' .This makes me think that System.Action is copied when it 's passed as parameter ( like a primitive type e.g . int would ) . So , when += is done later , it has no effect on the local copy of action inside SomeAsyncOperation.I thought of passing System.Action with ref . However , I need to store it as member variable inside Class1 , and I ca n't make a member variable a ref ! So , basically , the question is : how do you add more stuff to the invocation list of a callback after that callback has been passed and the lengthy operation is long on its way but has n't ended yet.EDIT : Ended up replacingwith class Class1 { private System.Action onDoneCallback ; void StartAsyncOperation ( System.Action onDoneCallback ) { this.onDoneCallback = onDoneCallback ; // do lengthy stuff } void MuchLater ( ) { this.onDoneCallBack ? .Invoke ( ) ; } } class Class2 { public System.Action action ; void DoStuff ( ) { action += ( ) = > print ( `` a '' ) ; new Class1 ( ) .StartAsyncOperation ( action ) ; } { // ... much later in another place but still before StartAsyncOperation ends action += ( ) = > print ( `` b '' ) ; } } new Class1 ( ) .StartAsyncOperation ( action ) ; new Class1 ( ) .StartAsyncOperation ( ( ) = > action ? .Invoke ( ) ) ;",How to pass a System.Action by reference ? "C_sharp : Method TryParseExact in code block below returns true.I would like to know why.I think this date `` 2013.03.12 '' is invalid because this is not separated by slash but dot.After I changed the CultureInfo `` de-De '' to `` en-US '' , the method returns false . This could be a hint but I still do n't know why this happens . var format = new string [ ] { `` yyyy/MM/dd '' } ; var parsed = new DateTime ( ) ; var result = DateTime.TryParseExact ( `` 2013.03.12 '' , format , new CultureInfo ( `` de-DE '' ) , DateTimeStyles.None , out parsed ) ;","TryParseExact returns false , though I do n't know why" "C_sharp : Say you have following C++ code : I want to access this in my C # project using DllImport : This works perfectly fine for testA , but testB fails throwing an EntryPointNotFoundException . Can I access testB from my C # code ? How ? extern `` C '' { void testA ( int a , float b ) { } static void testB ( int a , float b ) { } } class PlatformInvokeTest { [ DllImport ( `` test.so '' ) ] public static extern void testA ( int a , float b ) ; [ DllImport ( `` test.so '' ) ] internal static extern void testB ( int a , float b ) ; public static void Main ( ) { testA ( 0 , 1.0f ) ; testB ( 0 , 1.0f ) ; } }",Access C++ static methods from C # "C_sharp : For the last couple of days , I 've been trying to compile my .NET Core console application , and upload it to a VPS running `` Windows Server 2012 R2 '' . The reason I am using .NET Core is because this is needed for the library - Discord.Net 1.0.The first thing I tried was simply taking my release DLL file and data , with the following file structure : This worked fine for execution on the PC I developed it on , however I then went into my server , ran `` dotnet LeveledStudios.dll '' , and was faced with the errorNoticing this fitted the structure of the .nuget folder on my development PC . I copied it across and faced the same issue , and tried to copy it into the same folder as leveledstudios.dll , only to run into some .dll 's which refused to work . This also included missing system DLL files , like System.Net.Http , etc.I did some googling , and saw information about self contained .NET Core applications . This sounds perfect because clearly my problem was that it was not compiling with all my additional libraries . I was a little confused because I did not have a project.json file , as mentioned in all the documentation I read on it.However when running : I get a host of errors , suggesting none of the system libraries are compiled : ErrorsThe contents of LeveledStudios.csproj : How can I fix this ? LeveledStudios.depsLeveledStudios.dllLeveledStudios.pdbLeveledStudios.runtimeconfig.devLeveledStdios.runtimeconfig Error : assembly specified in the dependencies manifest was not found -- package : 'discord.net.commands ' , version ' 1.0.0-rc-00546 ' , path : 'lib/netstandard1.3/Discord.Net.Commands.dll ` dotnet restoredotnet build -r win10-x64 < Project Sdk= '' Microsoft.NET.Sdk '' ToolsVersion= '' 15.0 '' > < PropertyGroup > < OutputType > Exe < /OutputType > < TargetFramework > netcoreapp1.0 < /TargetFramework > < /PropertyGroup > < ItemGroup > < Compile Include= '' **\*.cs '' / > < EmbeddedResource Include= '' **\*.resx '' / > < /ItemGroup > < ItemGroup > < PackageReference Include= '' Discord.Net '' Version= '' 1.0.0-rc-00546 '' / > < PackageReference Include= '' Discord.Net.Commands '' Version= '' 1.0.0-rc-00546 '' / > < PackageReference Include= '' Discord.Net.Core '' Version= '' 1.0.0-rc-00546 '' / > < PackageReference Include= '' Discord.Net.WebSocket '' Version= '' 1.0.0-rc-00546 '' / > < PackageReference Include= '' Microsoft.NETCore.App '' Version= '' 1.0.1 '' / > < PackageReference Include= '' Newtonsoft.Json '' Version= '' 9.0.2-beta2 '' / > < /ItemGroup > < /Project >",Compiling .NET Core VS17 "C_sharp : I 'm having some problems trying to figure out how to solve a problem without being able to have static method in an abstract class or interface . Consider the following code . I have many Wizards that inherit from AbsWizard . Each wizard has a method GetMagic ( string spell ) that only returns magic for certain magic words , yet all instances of a specific type of wizard respond to the same set of magic words.I want the user to be able to first choose the type of wizard , and then be presented with a list of the spells that type of wizard can cast . Then when they choose a spell the program will find all , if any , existing wizards of the selected type and have them cast the selected spell . All wizards of a specific type will always have the same available spells , and I need a way to determine the spells a specific type of wizard can cast with out actually having access to an instance of the selected type of wizard.In addition I do n't want to have to depend on a separate list of possible wizard types or spells . Instead I would rather just infer everything through GetAvalibleSpells ( ) and reflection . For example I plan to cast magic as follows : public abstract class AbsWizard { public abstract Magic GetMagic ( String magicword ) ; public abstract string [ ] GetAvalibleSpells ( ) ; } public class WhiteWizard : AbsWizard { public override Magic GetMagic ( string magicword ) { //returns some magic based on the magic word } public override string [ ] GetAvalibleSpells ( ) { string [ ] spells = { `` booblah '' , '' zoombar '' } ; return spells ; } } public class BlackWizard : AbsWizard { public override Magic GetMagic ( string magicword ) { //returns some magic based on the magic word } public override string [ ] GetAvalibleSpells ( ) { string [ ] spells = { `` zoogle '' , `` xclondon '' } ; return spells ; } } public static void CastMagic ( ) { Type [ ] types = System.Reflection.Assembly.GetExecutingAssembly ( ) .GetTypes ( ) ; List < Type > wizardTypes = new List < Type > ( ) ; List < string > avalibleSpells = new List < string > ( ) ; Type selectedWizardType ; string selectedSpell ; foreach ( Type t in types ) { if ( typeof ( AbsWizard ) .IsAssignableFrom ( t ) ) { wizardTypes.Add ( t ) ; } } //Allow user to pick a wizard type ( assign a value to selectedWizardType ) //find the spells the selected type of wizard can cast ( populate availibleSpells ) //Alow user to pick the spell ( assign a value to selectedSpell ) //Find all instances , if any exsist , of wizards of type selectedWizardType and call GetMagic ( selectedSpell ) ; }",What is an alternative to having static abstract methods ? "C_sharp : I have custom-made wizard system which so far has been quite suitable . For most wizards , the pages can be constructed in a fairly generic fashion , so only one class implements those types of pages . However , some need to be custom-designed , so there is an abstract base class for those kinds of pages . Due to some deficiencies in the VS designer , the page ca n't itself be a UI control and also be an abstract class with generic parameters ( those exist for fluent programming ) . So one option I 've followed is to implement the page across two classes , one for the UI ( which derives from UserControl and can be designed ) and one for the page . The page contains an instance of the UI control and embeds that in itself for display . Not optimal , but it works.Now , a problem arises from this set up : there is a tight coupling between the UI control class and the page class . This would n't normally be that much of an issue except that pages can be derived from to create specialized versions of the pages . So the derived control and page classes are also tightly coupled with themselves . So when I have member variables , properties and methods on the control and page classes that are typed for the control or page class , respectively ( i.e. , the control class will have a property Page which points to the page the control is embedded in ) , we run into a big problem with derived classes . Each derived class must somehow change the type of these members . What I had thought of doing was including a generic type parameter that would allow those members to be generically typed : Obviously , this is the kind of C++-style garbage that I 'd like to avoid . Besides the ugliness , it creates an actual problem wherein one must create sealed `` leaf '' classes to work around the infinite recursion problem that CRTP brings us.And yet the alternatives are also unappealing . I could have those members have a fixed type of the base type and do casting everywhere . This does n't enforce type safety and it requires pointless casts ( I already know that the type will be such-and-such , but the compiler does n't ) . I could suck it up and combine the page and the control class into one , with no abstract or generic type parameters . That ruins the fluent programming system , or makes it much harder to implement , with much repetition ( I 'll explain if needed , but let 's just assume that that part of my design is legitimate ) .As such , I 'm a bit at a loss for how to do this in a sane manner . Everything I 've considered so far can be made to work , but the code smell is horrible . Is there something I 'm missing , some way of doing this that has so far eluded me ? public class BaseControl < TControl , TPage > where TPage : BasePage < TPage , TControl > where TControl : BaseControl < TControl , TPage > { public TPage Page { get { ... } set { ... } } ... } public class BasePage < TPage , TControl > where TPage : BasePage < TPage , TControl > where TControl : BaseControl < TControl , TPage > { public TControl Control { get { ... } set { ... } ... } public class DerivedControl < TControl , TPage > : BaseControl < TControl , TPage > where TControl : DerivedControl < TControl , TPage > where TPage : DerivedPage < TPage , TControl > { } public class DerivedPage < TPage , TControl > : BasePage < TPage , TControl > where TControl : DerivedControl < TControl , TPage > where TPage : DerivedPage < TPage , TControl > { }",Tight coupling with related classes ? "C_sharp : I have a class that exposes a fluent interface style that I also want to be thread safe.At the moment , calling chainable methods on an instance of the class sets up various collections with operations ( Func < T > 's ) .When the result is requested the real work happens . This allows for users to chain the method calls in any order such that : ( Here , 5 is the number of times to re-try a failied service call . ) Obviously this is n't threadsafe or reentrant.What are some common design patterns that solve this problem ? If the Execute method had to be called first I could simply returned a new instance of the class to work with each time however since any method can be called at any point in the chain , how would you solve this problem ? I 'm more interested in understanding various ways to solve this rather than a single answer just to `` get it working right '' .I 've put the full code on GitHub incase anyone needs a wider context on what I 'm aiming to achieve : https : //github.com/JamieDixon/ServiceManager var result = myFluentThing.Execute ( ( ) = > serviceCall.ExecHttp ( ) , 5 ) .IfExecFails ( ( ) = > DoSomeShizzle ( ) ) .Result < TheResultType > ( ) ;",Fluent Interfaces - Ensuring a new instance "C_sharp : When I saw Darins suggestion here .. ( process.getprocessesbyname ( ) ) .. I was a bit intrigued and I tried it in VS2008 with .NET 3.5 - and it did not compiling unless I changed it to ..Having read some Darins answers before I suspected that it was me that were the problem , and when I later got my hands on a VS2010 with.NET 4.0 - as expected - the original suggestion worked beautifully.My question is : What have happened from 3.5 to 4.0 that makes this ( new syntax ) possible ? Is it the extensionmethods that have been extended ( hmm ) or new rules for lambda syntax or ? IEnumerable < Process > processes = new [ ] { `` process1 '' , `` process2 '' } .SelectMany ( Process.GetProcessesByName ) ; IEnumerable < Process > res = new string [ ] { `` notepad '' , `` firefox '' , `` outlook '' } .SelectMany ( s = > Process.GetProcessesByName ( s ) ) ;",LINQ extension SelectMany in 3.5 vs 4.0 ? "C_sharp : I am facing serious performance issues ... My query is supposed to filter Products with SQL directly in database . When I execute this code , it does n't , and it returns all products and filters them in C # .I 've noticed that the products variable is of type TakeIterator . When I change the code slightly , I get the filtering OK , but it forces me to put the query logic directly in the same method , which is what I want to avoid.This second version is of an undisclosed type by the Visual Studio debugger , but it shows as the query I am trying to end with , which is good ! I need to figure out how to get a Func passed as an argument and execute the query in the same fashion as the first C # code excerpt , but with optimisations of the second . MyContext context = new MyContext ( ) ; Func < Product , bool > query = ( p = > p.UPC.StartsWith ( `` 817 '' ) ) ; var products = context.Products.Where ( query ) .Take ( 10 ) ; MyContext context = new MyContext ( ) ; var products = context.Products.Where ( p = > p.UPC.StartsWith ( `` 817 '' ) ) .Take ( 10 ) ; { SELECT TOP ( 10 ) [ Extent1 ] . [ Id ] AS [ Id ] , [ Extent1 ] . [ Brand ] AS [ Brand ] , [ Extent1 ] . [ Description ] AS [ Description ] , [ Extent1 ] . [ UPC ] AS [ UPC ] FROM [ dbo ] . [ Products ] AS [ Extent1 ] WHERE [ Extent1 ] . [ UPC ] LIKE N'817 % ' }",Entity Framework 5 and SQL Queries "C_sharp : I 'm trying to create an instance of a generic class using a Type object . Basically , I 'll have a collection of objects of varying types at runtime , and since there 's no way for sure to know what types they exactly will be , I 'm thinking that I 'll have to use Reflection.I was working on something like : Which is well and good . ^___^The problem is , I 'd like to access a method of my GenericType < > instance , which I ca n't because it 's typed as an object class . I ca n't find a way to cast it obj into the specific GenericType < > , because that was the problem in the first place ( i.e. , I just ca n't put in something like : ) How should one go about tackling this problem ? Many thanks ! ^___^ Type elType = Type.GetType ( obj ) ; Type genType = typeof ( GenericType < > ) .MakeGenericType ( elType ) ; object obj = Activator.CreateInstance ( genType ) ; ( ( GenericType < elType > ) obj ) .MyMethod ( ) ;",Using a Type object to create a generic "C_sharp : I 'm trying to read my compiled C # code.this is my code : But ! We all know that a using gets translated to this : ( since OleDbCommand is a reference type ) .But when I decompile my assembly ( compiled with .NET 2.0 ) I get this in Resharper : I 'm talking about this line : if ( ( insertCommand == null ) ! = null ) .Let 's say insertCommand IS null . Then the first part returns true . ( true ! = null ) returns true . So Then the disposing is still skipped ? Weird , very weird.If I paste this in Visual Studio , Resharper already warns me : Expression is always true ... Thanks ! -Kristof using ( OleDbCommand insertCommand = new OleDbCommand ( `` ... '' , connection ) ) { // do super stuff } { OleDbCommand insertCommand = new OleDbCommand ( `` ... '' , connection ) try { //do super stuff } finally { if ( insertCommand ! = null ) ( ( IDisposable ) insertCommand ) .Dispose ( ) ; } } try { insertCommand = new OleDbCommand ( `` '' , connection ) ; Label_0017 : try { //do super stuff } finally { Label_0111 : if ( ( insertCommand == null ) ! = null ) { goto Label_0122 ; } insertCommand.Dispose ( ) ; Label_0122 : ; }","C # , weird optimization" "C_sharp : I noticed that the fully qualified name of an object I had written was coming back funny . While stepping through my ToString ( ) method , I noticed that when it came to concatenating the string , a character object was consistently being left out of that process.Here 's a step through of what 's happeningBeforeAfterWhere Char seperator = ' : ' ; Here 's the code of my tostring function : Where you haveAnd one case may look like this : Already , looking in the locals panel , it seems like VS is getting a string other than what I think it would.I put in another ToString function to handle a call without parameters ( which it does by calling the parametrized function with Representation.Colons ) : Can anyone tell why I 'm not getting what I think I should be getting ? ( Expected result : kuid2:72938:40175:2 ) public String ToString ( Representaion rep ) { String toReturn = `` kuid '' ; Char separator = ' : ' ; switch ( rep ) { case Representaion.Colons : break ; case Representaion.Underscores : separator = ' _ ' ; break ; case Representaion.UCROnly : toReturn = userID + `` : '' + contentID ; toReturn += revision == 0 ? `` '' : `` : '' + revision ; return toReturn ; } toReturn += version == 0 ? `` '' : version.ToString ( ) ; toReturn += separator + userID + separator + contentID ; toReturn += revision == 0 ? `` '' : separator + revision.ToString ( ) ; return toReturn ; } private byte version ; private int userID ; private int contentID ; private byte revision ; public override string ToString ( ) { return this.ToString ( KUID.Representaion.Colons ) ; }",Char object is ignored in string concatenation "C_sharp : Is anybody able to enlighten me on how to use LINQ ( or something more appropriate if necessary ) to create a list of lists of integers that are grouped by the the proximity from each other.Basically , I want to create groups where the numbers are within 5 of any other number . So , given : Produce the following list : Thanks ! 3 27 53 79 113 129 134 140 141 142 145 174 191 214 284 284 3 275379113129 134 140 141 142 145174194214284 284",LINQ ( Or pseudocode ) to group items by proximity "C_sharp : I am remotely selecting results from a custom production database with a criteria of around three minutes from a C # application . Every time the select command is executed , the server PC that I am using CPU goes up to around 50 % . But surely , the load should be on the database that I am connecting to ? Why would the C # application rocket to 50 % until the data is retrieved for reading ? Some backgroundI have worked out from debugging that the Select statement on theremote database takes around 30-40 seconds , baring in mind I am selecting with a criteria that uses the indexed column.At the same time of selecting data from the remote DB , I have monitored the TaskManager and the CPU sits at 50 % until the select as complete.. this can last around 30-40 seconds each loop.If I select in the native sql engine for the remote DB , there is no lag on the select , the data ( if any ) is returned immediately.I know its not the parsing of result set that is taking up the CPU load as some selects will return nothing.Here is some code I am using.I ran a performance and diagnostic test on the application and it yielded this result.How , if any , can I reduce this CPU load or even eradicate it completely . It is completely out of the ordinary and I have no clue on how to go about it.Thanks OdbcConnection remoteConn = new OdbcConnection ( ConfigurationManager.ConnectionStrings [ `` remoteConnectionString '' ] .ToString ( ) ) ; remoteConn.Open ( ) ; OdbcCommand remoteCommand = new OdbcCommand ( ) ; remoteCommand.Connection = remoteConn ; using ( remoteConn ) { string localSql = `` '' ; string remoteSql = `` select * from tracking where last_update > 212316247440000000 '' ; // Julian No = 2015-07-12 11:24:00 remoteCommand.CommandText = remoteSql ; OdbcDataReader remoteReader ; remoteReader = remoteCommand.ExecuteReader ( ) ; while ( remoteReader.Read ( ) ) { for ( int i = 0 ; i < 68 ; i++ ) { localSql += `` , ' '' + remoteReader [ i ] .ToString ( ) + `` ' '' ; } } }",Reducing CPU Load on a remote select from a database "C_sharp : For Example : I have installed an application called `` RivaTuner Statistics Server v6.6.0 '' which has made for gamers to show FPS mark on games , since WPF apps are using DirectX , this program attaches a module to my WPF app by mistake which makes it crash ( without giving any exceptions ) before my app gets loaded , and when I close that program , my app works just fine ! I 've fixed this problem by setting RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnlyI also have the same problem with BitDefender antivirus , my program is a VPN Connection software that uses Proxifier app to set global proxy.. When my app begins to start Proxifier process , my app crashes without any exceptions.. by the way BitDefender does n't detect Proxifier or my app as a virus or threat , it just makes my app crash and Proxifier continues to work without any problem . ( Which whitelisting my app got the problem solved ) . What I want to know generally , is there any way to prevent DLL injection or stopping it after it attached ? Here is the provided information by EventViewer : If you take a look , you can see the attached module LoadedModule [ 29 ] =C : \Program Files ( x86 ) \RivaTuner Statistics Server\RTSSHooks64.dll Version=1EventType=APPCRASHEventTime=131414331835897163ReportType=2Consent=1UploadTime=131414331849773927ReportStatus=393ReportIdentifier=c52be1e0-6378-4555-bddc-cd49f22e98d4IntegratorReportIdentifier=e415e187-7b4d-4689-92a7-5522957c6300Wow64Host=34404NsAppName=TurboVPN.exeAppSessionGuid=000037d0-0001-0015-6d89-3176a3e0d201TargetAppId=W:00065bd30e4a6caee77eb9ec126f39eeb11200000000 ! 000072443a77ce17608085aa75f649187cf7129fd9a8 ! TurboVPN.exeTargetAppVer=2017//06//08:20:58:47 ! 0 ! TurboVPN.exeBootId=4294967295TargetAsId=3395Response.BucketId=c2e6858b6015d605f3dea6f209e5a680Response.BucketTable=4Response.LegacyBucketId=120776215139Response.type=4Sig [ 0 ] .Name=Application NameSig [ 0 ] .Value=TurboVPN.exeSig [ 1 ] .Name=Application VersionSig [ 1 ] .Value=8.0.0.0Sig [ 2 ] .Name=Application TimestampSig [ 2 ] .Value=5939ba87Sig [ 3 ] .Name=Fault Module NameSig [ 3 ] .Value=d3d9.dllSig [ 4 ] .Name=Fault Module VersionSig [ 4 ] .Value=10.0.15063.0Sig [ 5 ] .Name=Fault Module TimestampSig [ 5 ] .Value=631de416Sig [ 6 ] .Name=Exception CodeSig [ 6 ] .Value=c0000005Sig [ 7 ] .Name=Exception OffsetSig [ 7 ] .Value=000000000000fd0cDynamicSig [ 1 ] .Name=OS VersionDynamicSig [ 1 ] .Value=10.0.15063.2.0.0.256.4DynamicSig [ 2 ] .Name=Locale IDDynamicSig [ 2 ] .Value=1033DynamicSig [ 22 ] .Name=Additional Information 1DynamicSig [ 22 ] .Value=9b4fDynamicSig [ 23 ] .Name=Additional Information 2DynamicSig [ 23 ] .Value=9b4f78d83ca7cfa07fe4d1531372a428DynamicSig [ 24 ] .Name=Additional Information 3DynamicSig [ 24 ] .Value=9991DynamicSig [ 25 ] .Name=Additional Information 4DynamicSig [ 25 ] .Value=99915f8f3f68939dc06e64d116ece58aUI [ 2 ] =C : \Users\Mr\Documents\Visual Studio 2015\Projects\TurboVPN\TurboVPN\bin\Release\TurboVPN.exeUI [ 3 ] =TurboVPN has stopped workingUI [ 4 ] =Windows can check online for a solution to the problem.UI [ 5 ] =Check online for a solution and close the programUI [ 6 ] =Check online for a solution later and close the programUI [ 7 ] =Close the programLoadedModule [ 0 ] =C : \Users\Mr\Documents\Visual Studio 2015\Projects\TurboVPN\TurboVPN\bin\Release\TurboVPN.exeLoadedModule [ 1 ] =C : \WINDOWS\SYSTEM32\ntdll.dllLoadedModule [ 2 ] =C : \WINDOWS\SYSTEM32\MSCOREE.DLLLoadedModule [ 3 ] =C : \WINDOWS\System32\KERNEL32.dllLoadedModule [ 4 ] =C : \WINDOWS\System32\KERNELBASE.dllLoadedModule [ 5 ] =C : \Program Files\Bitdefender\Bitdefender 2017\Active Virus Control\Avc3_00125_004\avcuf64.dllLoadedModule [ 6 ] =C : \WINDOWS\SYSTEM32\apphelp.dllLoadedModule [ 7 ] =C : \WINDOWS\System32\ADVAPI32.dllLoadedModule [ 8 ] =C : \WINDOWS\System32\msvcrt.dllLoadedModule [ 9 ] =C : \WINDOWS\System32\sechost.dllLoadedModule [ 10 ] =C : \WINDOWS\System32\RPCRT4.dllLoadedModule [ 11 ] =C : \Windows\Microsoft.NET\Framework64\v4.0.30319\mscoreei.dllLoadedModule [ 12 ] =C : \WINDOWS\System32\SHLWAPI.dllLoadedModule [ 13 ] =C : \WINDOWS\System32\combase.dllLoadedModule [ 14 ] =C : \WINDOWS\System32\ucrtbase.dllLoadedModule [ 15 ] =C : \WINDOWS\System32\bcryptPrimitives.dllLoadedModule [ 16 ] =C : \WINDOWS\System32\GDI32.dllLoadedModule [ 17 ] =C : \WINDOWS\System32\gdi32full.dllLoadedModule [ 18 ] =C : \WINDOWS\System32\msvcp_win.dllLoadedModule [ 19 ] =C : \WINDOWS\System32\USER32.dllLoadedModule [ 20 ] =C : \WINDOWS\System32\win32u.dllLoadedModule [ 21 ] =C : \WINDOWS\System32\IMM32.DLLLoadedModule [ 22 ] =C : \WINDOWS\System32\kernel.appcore.dllLoadedModule [ 23 ] =C : \WINDOWS\SYSTEM32\VERSION.dllLoadedModule [ 24 ] =C : \Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dllLoadedModule [ 25 ] =C : \WINDOWS\SYSTEM32\MSVCR120_CLR0400.dllLoadedModule [ 26 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\mscorlib\59ea37125345a946fbfb8868aa11ed27\mscorlib.ni.dllLoadedModule [ 27 ] =C : \WINDOWS\System32\ole32.dllLoadedModule [ 28 ] =C : \WINDOWS\system32\uxtheme.dllLoadedModule [ 29 ] =C : \Program Files ( x86 ) \RivaTuner Statistics Server\RTSSHooks64.dllLoadedModule [ 30 ] =C : \WINDOWS\SYSTEM32\WINMM.dllLoadedModule [ 31 ] =C : \WINDOWS\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9279_none_08e667efa83ba076\MSVCR90.dllLoadedModule [ 32 ] =C : \WINDOWS\SYSTEM32\WINMMBASE.dllLoadedModule [ 33 ] =C : \WINDOWS\System32\cfgmgr32.dllLoadedModule [ 34 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System\4b4b69a2aa9b596c8b8e7a32267eac35\System.ni.dllLoadedModule [ 35 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Core\d4035216edd875be919d339859343a6c\System.Core.ni.dllLoadedModule [ 36 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\WindowsBase\d6053a0b7badab04868dc6e51ab4c02e\WindowsBase.ni.dllLoadedModule [ 37 ] =C : \WINDOWS\SYSTEM32\CRYPTSP.dllLoadedModule [ 38 ] =C : \WINDOWS\system32\rsaenh.dllLoadedModule [ 39 ] =C : \WINDOWS\SYSTEM32\bcrypt.dllLoadedModule [ 40 ] =C : \WINDOWS\SYSTEM32\CRYPTBASE.dllLoadedModule [ 41 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\PresentationCore\b5bfbcf78210cf783ff665fea098ebfa\PresentationCore.ni.dllLoadedModule [ 42 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\Presentatio5ae0f00f # \73dece296df0b44862aa59e1f73825c3\PresentationFramework.ni.dllLoadedModule [ 43 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Xaml\44f34f029c456762dba3d085d6b9fa9c\System.Xaml.ni.dllLoadedModule [ 44 ] =C : \WINDOWS\SYSTEM32\dwrite.dllLoadedModule [ 45 ] =C : \Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\wpfgfx_v0400.dllLoadedModule [ 46 ] =C : \WINDOWS\System32\OLEAUT32.dllLoadedModule [ 47 ] =C : \WINDOWS\SYSTEM32\MSVCP120_CLR0400.dllLoadedModule [ 48 ] =C : \WINDOWS\SYSTEM32\D3DCOMPILER_47.dllLoadedModule [ 49 ] =C : \Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\PresentationNative_v0400.dllLoadedModule [ 50 ] =C : \Windows\Microsoft.NET\Framework64\v4.0.30319\clrjit.dllLoadedModule [ 51 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Configuration\9f298b9fdf9d3d88c051ba8d0cfcdd98\System.Configuration.ni.dllLoadedModule [ 52 ] =C : \WINDOWS\SYSTEM32\urlmon.dllLoadedModule [ 53 ] =C : \WINDOWS\System32\shcore.dllLoadedModule [ 54 ] =C : \WINDOWS\System32\windows.storage.dllLoadedModule [ 55 ] =C : \WINDOWS\System32\powrprof.dllLoadedModule [ 56 ] =C : \WINDOWS\System32\profapi.dllLoadedModule [ 57 ] =C : \WINDOWS\SYSTEM32\iertutil.dllLoadedModule [ 58 ] =C : \WINDOWS\SYSTEM32\SspiCli.dllLoadedModule [ 59 ] =C : \WINDOWS\SYSTEM32\msiso.dllLoadedModule [ 60 ] =C : \WINDOWS\SYSTEM32\PROPSYS.dllLoadedModule [ 61 ] =C : \WINDOWS\System32\shell32.dllLoadedModule [ 62 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Xml\246b8fa70f43db970414bb4119fe629f\System.Xml.ni.dllLoadedModule [ 63 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Runt73a1fc9d # \9ed83e5a61548d2d78bc4b7a667e9139\System.Runtime.Remoting.ni.dllLoadedModule [ 64 ] =C : \WINDOWS\System32\ws2_32.dllLoadedModule [ 65 ] =C : \WINDOWS\system32\mswsock.dllLoadedModule [ 66 ] =C : \WINDOWS\system32\dwmapi.dllLoadedModule [ 67 ] =C : \WINDOWS\System32\MSCTF.dllLoadedModule [ 68 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Drawing\763d0ca89a77cfd983874efe156a9296\System.Drawing.ni.dllLoadedModule [ 69 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Windows.Forms\d63d7f874bb64e51ee0ef09cc99218f6\System.Windows.Forms.ni.dllLoadedModule [ 70 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Security\35f9d2604274a3e8fbf814e10789dc51\System.Security.ni.dllLoadedModule [ 71 ] =C : \WINDOWS\System32\crypt32.dllLoadedModule [ 72 ] =C : \WINDOWS\System32\MSASN1.dllLoadedModule [ 73 ] =C : \WINDOWS\SYSTEM32\DPAPI.dllLoadedModule [ 74 ] =C : \WINDOWS\SYSTEM32\WindowsCodecs.dllLoadedModule [ 75 ] =C : \WINDOWS\SYSTEM32\d3d9.dllLoadedModule [ 76 ] =C : \WINDOWS\SYSTEM32\igdumdim64.dllLoadedModule [ 77 ] =C : \WINDOWS\System32\SETUPAPI.dllLoadedModule [ 78 ] =C : \WINDOWS\assembly\NativeImages_v4.0.30319_64\Presentatioaec034ca # \248dd0bba3037acdc2ab60513b34c3f2\PresentationFramework.Aero2.ni.dllLoadedModule [ 79 ] =C : \WINDOWS\SYSTEM32\WtsApi32.dllLoadedModule [ 80 ] =C : \WINDOWS\SYSTEM32\WINSTA.dllLoadedModule [ 81 ] =C : \WINDOWS\System32\clbcatq.dllLoadedModule [ 82 ] =C : \WINDOWS\system32\dataexchange.dllLoadedModule [ 83 ] =C : \WINDOWS\system32\d3d11.dllLoadedModule [ 84 ] =C : \WINDOWS\system32\dcomp.dllLoadedModule [ 85 ] =C : \WINDOWS\system32\dxgi.dllLoadedModule [ 86 ] =C : \WINDOWS\system32\twinapi.appcore.dllLoadedModule [ 87 ] =C : \WINDOWS\SYSTEM32\igdusc64.dllState [ 0 ] .Key=Transport.DoneStage1State [ 0 ] .Value=1File [ 0 ] .CabName=Report.zipFile [ 0 ] .Path=Report.zipFile [ 0 ] .Flags=196608File [ 0 ] .Type=11File [ 0 ] .Original.Path=\\ ? \C : \WINDOWS\system32\Report.zipFriendlyEventName=Stopped workingConsentKey=APPCRASHAppName=TurboVPNAppPath=C : \Users\Mr\Documents\Visual Studio 2015\Projects\TurboVPN\TurboVPN\bin\Release\TurboVPN.exeNsPartner=windowsNsGroup=windows8ApplicationIdentity=ED5A83A5552697FBE579A0CAAEF2FF9EMetadataHash=1411986728",How to prevent modules from getting attached to my application process ? C # "C_sharp : I 'm creating a Database using the Microsoft Entity Framework and CodeFirst in C # . I want to use the Database in a WPF-Application , so the Entity-Classes should implement `` INotifyPropertyChanged '' . This can be done very elegantly using a PostSharp aspect , which triggers the PropertyChanged event automatically every time a property changes . If I create such an aspect and use it on my entity classes , I get the following exeption when trying to create the Database : Obviously PostSharp creates a property called `` k__BackingField '' which causes the database creation to fail , because it 's an invalid name from the EntityFramework 's point of view . Is there any way to circumvent this error without manually implementing `` INotifyPropertyChanged '' in every single Entity-Class ? P.S : English is not my native language , I would be very thankful if you informed me about possible mistakes in my postings.Thank you in advance \tSystem.Data.Entity.Edm.EdmNavigationProperty : Name : The specified name is not allowed : ' < Name > k__BackingField ' .","PostSharp inserting k__Backing Field into Entity Class , causing Database generation to fail" "C_sharp : I currently have a Visual Studio Deployment project for creating an MSI for my applicaiton , and I 'm porting over to a WiX installer . The VS Installer used a library with Custom Install Actions that inherited from System.Configuration.Install.Installer , e.g . : How do these equate to Wix actions ? I figure that in general , WiX allows you to run custom actions after an install . Are these just executables ? In my case , the custom Install Actions I have are classes in a DLL , not an EXE . How can I execute these from my WiX configuration ? [ RunInstaller ( true ) ] public partial class MyCustomInstaller : Installer { }",Porting Custom Install Actions to Wix "C_sharp : Just stumbled over this one today and I ca n't find any information about it . So that 's why I ask here . Perhaps someone knows why.I added a custom WCF behavior extension to my web.config . It looks like this : ( No space in there : MyNs.TracingErrorBehaviorElement , MyNs ) It works perfectly fine on my development machine , on our staging server , on our live server , etc.Today we installed the product on a customer server and got the following exception : System.Configuration.ConfigurationErrorsException : An error occurred creating the configuration section handler for system.serviceModel/behaviors : Extension element 'errorBehavior ' can not be added to this element . Verify that the extension is registered in the extension collection at system.serviceModel/extensions/behaviorExtensions ... After spending half an hour searching the web for possible causes I added spaces to the fully qualified assembly name . So I changed it to : ( See the space : MyNs.TracingErrorBehaviorElement , MyNs ) and it worked.Does anyone know why it works without a space on some machines and not on others ? I checked the .Net-versions . They matched . Could it be caused by regional settings ? Edit says : I checked the used .Net versions on all machines and they are all the same : .Net 4.0But I found a difference between the machine where I get the error with a missing blank and the others machines where it works : All machines where it works without the blank have installed .Net Framework 4.5 . So it could be one of those bugs that were fixed in 4.0 and deployed with 4.5 , right ? < behaviorExtensions > < add name= '' errorBehavior '' type= '' MyNs.TracingErrorBehaviorElement , MyNs , Version=1.0.6.0 , Culture=neutral , PublicKeyToken=null '' / > < /behaviorExtensions > < behaviorExtensions > < add name= '' errorBehavior '' type= '' MyNs.TracingErrorBehaviorElement , MyNs , Version=1.0.6.0 , Culture=neutral , PublicKeyToken=null '' / > < /behaviorExtensions >",Why do fully qualified assembly names sometimes require spaces ? "C_sharp : My InputMy CodeMy QuestionDo I have to add ns every time I am doing node.Element ( ) ? or is there any other way ? < A xmlns= '' http : //abc.com '' > < B > '' b '' < /B > < C > '' c '' < /C > < /A > XNamespace ns = XNamespace.Get ( `` http : //abc.com '' ) ; var query= from node in doc.Descendants ( ns+ `` A '' ) select new ( B = ( string ) node.Element ( ns+ '' B '' ) , C = ( string ) node.Element ( ns+ `` C '' ) ) ;",Parsing of XML string ( with namespace ) using LINQ "C_sharp : I am using a Silverlight 5 Business Application using RIA services to return a POCO class from the service side to populate a hierarchical menu . The original problem I had with the POCO class was that the SubMenuItems property was not getting passed over RIA services although it was populated on the service side.Original POCOService callFollowing some further investigation I found that the [ Include ] and [ Association ] attributes were required on the SubMenuItems to pass the data over . Doing this the first time with the Association of ID = > ID did not give the desired results so I added the ParentID property and changed my loading code to populate the Foreign Key as below . I also changed the Associate to map from ID to Parent ID.Updated POCO classOn the server side I am loading two levels of the menu at the moment so the top level item contains a collection of SubItems but there are no further SubItems below that.The problem I have is that when RIA services sends the collection over the wire the hierarchy is being jumbled . I have confirmed that what I am returned is correctly structured but it does not arrive on the client side correctly . The top level is OK but the second level ( SubMenuItems ) is mixed up and two furter SubMenuItems levels have appeared.Any idea what I am doing wrong ? I assume that the problem is with the Association or the fact that the same POCO object ( BusinessModelMenuDto ) is being used for the multiple levels . public class BusinessModelMenuDto { [ Key ] [ Required ] public int ID { get ; set ; } public string TextToDisplay { get ; set ; } public string ImageSource { get ; set ; } public IEnumerable < BusinessModelMenuDto > SubMenuItems { get ; set ; } } public IEnumerable < BusinessModelMenuDto > GetCabsHeirarchy ( ) public class BusinessModelMenuDto { [ Key ] [ Required ] public int ID { get ; set ; } public int ? ParentID { get ; set ; } public string TextToDisplay { get ; set ; } public string ImageSource { get ; set ; } [ Include ] [ Association ( `` SubItems '' , `` ID '' , `` ParentID '' ) ] public IEnumerable < BusinessModelMenuDto > SubMenuItems { get ; set ; } }",Silverlight POCO returned by RIA services "C_sharp : During insert a float number like 0.0001 into sql from my code , the result is a 0.0000 in database . here is definition of my table column : Here is the definition of class field : How can I solve this problem ? I am using EF Code first approach like this : decimal ( 20,15 ) public decimal Rate { get ; set ; } Class1 obj = new Class1 ( ) ; obj.Rate = 0.000001 ; ClassDbSet.Add ( obj ) ; DbContext.SaveChange ( ) ;",Inserting a decimal into sql cause inserting a zero number Instead of a decimal number near zero "C_sharp : I have what I think should be a very simple test case , but every time I run it QTAgent32 dies . Running the test case in Debug mode shows a System.StackOverflowException being thrown in 'Unknown Module ' . I 've narrowed it down to the most basic implementation that exhibits this behavior ( .NET 4 and VS 2010 Ultimate ) : I feel like I 'm missing something important about closures or maybe Moq , but it seems like this should work . Things I have tried , attempting to understand the issue , but have only confused me more : I tried replacing the Equals ( ) setup with mockMyType.Setup ( m = > m.Equals ( m ) ) .Returns ( true ) ; but that causes Moq to throw an NotSupportedExceptionIf I make CallBase true instead of setting up Equals ( ) , everything worksFinally , if the MyType class does n't override Equals ( ) , everything works.Can anyone point me in the direction of what might be happening ? I 'm completely at a loss.Edit : I believe I have a couple of options for making this work ( including Lanorkin 's response below ) , but I 'd really like to know why this is happening . Am I doing something wrong or is there a bug in Moq or Visual Studio that I should be submitting ? Update : I ended up going with a version of Denys solution below and filing a bug report to Moq . My setup now looks like : [ TestClass ] public class StackOverflow { [ TestMethod ] public void CreateStackOverflow ( ) { var mockMyType1 = new Mock < MyType > ( ) ; mockMyType1.Setup ( m = > m.Equals ( mockMyType1.Object ) ) .Returns ( true ) ; var mockMyType2 = new Mock < MyType > ( ) ; // Real test is for a filtering routine and the Assert is using // Contains ( ) , but it uses Equals ( ) internally so it has the same problem Assert.IsTrue ( mockMyType1.Object.Equals ( mockMyType1.Object ) ) ; // returns true Assert.IsFalse ( mockMyType1.Object.Equals ( mockMyType2.Object ) ) ; // explodes } } public class MyType { public virtual bool IsActive { get ; set ; } public override bool Equals ( object obj ) { return false ; // Not the real implementation but irrelevant to this issue } } mockMyType1.Setup ( m = > m.Equals ( It.Is < MyType > ( x = > ReferenceEquals ( x , mockMyType1.Object ) ) ) ) .Returns ( true ) ;",Combination of Moq and Equals ( ) crashing the MS Testing framework C_sharp : I 've searched around a bit for this and tried a few things and ca n't get it to work without turning some stuff off that I want on.Normally I let Resharper have its way with namespace optimizations . In a Service implementation that 's mapping DTO 's to Domain Model objects it 's a nice visual to create an alias for each . That way when it 's late and you 're sleep deprived seeing Dtos.Customer and DomainModel.Customer helps.When I run code cleanup it changes those to : Does anyone do this or something similar and keep R # from whacking it ? using DomainModel = MyProduct.Core.Domain.Model ; using Dtos = MyProduct.ServiceModel.Dtos ; using DomainModel = MyProduct.Core.Domain.Model ; using Customer = MyProduct.Core.Domain.Model.Customer ;,Resharper and Namespace alias qualifier "C_sharp : What is the best way to separate the individual characters in an array of strings strArr into an array of those characters charArr , as depicted below ? This is what I am currently doing , but I do not think that it is very elegant : string [ ] strArr = { `` 123 '' , `` 456 '' , `` 789 '' } ; char [ ] chrArr = { ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' } ; int characterCount = 0 ; for ( int i = 0 ; i < strArr.Length ; i++ ) { characterCount += strArr [ i ] .Length ; } int indexCount = 0 ; char [ ] chrArr = new char [ characterCount ] ; for ( int i = 0 ; i < strArr.Length ; i++ ) { for ( int j = 0 ; j < strArr [ i ] .Length ; j++ ) { chrArr [ indexCount ] = strArr [ i ] [ j ] ; indexCount++ ; } }",How can I divide a set of strings into their constituent characters in C # ? "C_sharp : If I understand meaning of volatile and MemoryBarrier correctly than the program below has never to be able to show any result.It catches reordering of write operations every time I run it . It does not matter if I run it in Debug or Release . It also does not matter if I run it as 32bit or 64bit application.Why does it happen ? using System ; using System.Threading ; using System.Threading.Tasks ; namespace FlipFlop { class Program { //Declaring these variables as volatile should instruct compiler to //flush all caches from registers into the memory . static volatile int a ; static volatile int b ; //Track a number of iteration that it took to detect operation reordering . static long iterations = 0 ; static object locker = new object ( ) ; //Indicates that operation reordering is not found yet . static volatile bool continueTrying = true ; //Indicates that Check method should continue . static volatile bool continueChecking = true ; static void Main ( string [ ] args ) { //Restarting test until able to catch reordering . while ( continueTrying ) { iterations++ ; var checker = new Task ( Check ) ; var writter = new Task ( Write ) ; lock ( locker ) { continueChecking = true ; checker.Start ( ) ; } writter.Start ( ) ; checker.Wait ( ) ; writter.Wait ( ) ; } Console.ReadKey ( ) ; } static void Write ( ) { //Writing is locked until Main will start Check ( ) method . lock ( locker ) { //Using memory barrier should prevent opration reordering . a = 1 ; Thread.MemoryBarrier ( ) ; b = 10 ; Thread.MemoryBarrier ( ) ; b = 20 ; Thread.MemoryBarrier ( ) ; a = 2 ; //Stops spinning in the Check method . continueChecking = false ; } } static void Check ( ) { //Spins until finds operation reordering or stopped by Write method . while ( continueChecking ) { int tempA = a ; int tempB = b ; if ( tempB == 10 & & tempA == 2 ) { continueTrying = false ; Console.WriteLine ( `` Caught when a = { 0 } and b = { 1 } '' , tempA , tempB ) ; Console.WriteLine ( `` In `` + iterations + `` iterations . `` ) ; break ; } } } } }",Why volatile and MemoryBarrier do not prevent operations reordering ? "C_sharp : So far I 've managed to implement Dolby 's Matrix Decoder based on the following specifications : Left RightCenter 0.707 0.707Left 1 0Right 0 1SLeft 0.871 0.489SRight 0.489 0.871But after testing my matrix I 've discovered there 's a lot clipping , and it sounds nothing like Dolby 's decoder . I 'm relatively new to DSP , although I 'm pretty sure I understand most of the basics ; but I 'm still left clueless as to what 's causing this to happen , am I missing something in the specifications , or is it just my code ? My current matrix decoder , private static void DolbyProLogicII ( List < float > leftSamples , List < float > rightSamples , int sampleRate , string outputDirectory ) { // WavFileWrite is a wrapper class for NAudio to create Wav files . var meta = new WaveFormat ( sampleRate , 16 , 1 ) ; var c = new WavFileWrite { MetaData = meta , FileName = Path.Combine ( outputDirectory , `` c.wav '' ) } ; var l = new WavFileWrite { MetaData = meta , FileName = Path.Combine ( outputDirectory , `` l.wav '' ) } ; var r = new WavFileWrite { MetaData = meta , FileName = Path.Combine ( outputDirectory , `` r.wav '' ) } ; var sl = new WavFileWrite { MetaData = meta , FileName = Path.Combine ( outputDirectory , `` sl.wav '' ) } ; var sr = new WavFileWrite { MetaData = meta , FileName = Path.Combine ( outputDirectory , `` sr.wav '' ) } ; var ii = ( leftSamples.Count > rightSamples.Count ? rightSamples.Count : leftSamples.Count ) ; // Process center channel . for ( var i = 0 ; i < ii ; i++ ) { c.MonoChannelAudioData.Add ( ( leftSamples [ i ] * 0.707 ) + ( rightSamples [ i ] * 0.707 ) ) ; } c.Flush ( ) ; // Process left channel . l.MonoChannelAudioData = leftSamples ; l.Flush ( ) ; // Process right channel . r.MonoChannelAudioData = rightSamples ; r.Flush ( ) ; // Process surround left channel . for ( var i = 0 ; i < ii - 1 ; i++ ) { sl.MonoChannelAudioData.Add ( ( leftSamples [ i ] * 0.871 ) + ( rightSamples [ i ] * 0.489 ) ) ; } sl.Flush ( ) ; // Process surround right channel . for ( var i = 0 ; i < ii - 1 ; i++ ) { sr.MonoChannelAudioData.Add ( ( leftSamples [ i ] * 0.489 ) + ( rightSamples [ i ] * 0.871 ) ) ; } sr.Flush ( ) ; }",Correctly implementing Dolby Pro Logic II "C_sharp : A blackboard is an object that stores and fetches generic key-value pairs at runtime . It could be implemented by a Dictionary < object , object > . Some subsystem writes to the blackboard to let other subsystems read from it . The system storing the blackboard has no idea what type of object is in it , and when . The writers and readers to a particular key always know and agree on the type of the key-value pair . Compile-time checking is sacrificed for ease of implementation - there are numerous writers and readers and they are constantly iterated on.My blackboard interface looks like this : Writers create and return blackboards , so SetValue ( key , value ) can be an implementation detail.My initial implementation used Dictionary < object , object > and everything was fine . However , this blackboard must be quick and alloc-free . This is non-negotiable . If a writer pushes a float value into the blackboard , the naive implementation boxes the int to put into the dictionary.I ca n't use a generic type on the implementation class , BlackboardImpl < ValueType > : Blackboard , because the value type is not constant across blackboards . I can use multiple internal dictionaries , Dictionary < object , float > , Dictionary < object , int > etc with a fallback Dictionary < object , object > , and many SetValue functions , so now I do n't box on insertion . However since the GetValue function comes from the interface , I ca n't put constraints on it , so I 'm still boxing on exit : Is there any syntactical trick I 'm missing here , including changing the blackboard interface , to avoid boxing ? Any reflection hacks are going to violate the `` quick '' requirement , even if you can implement it without allocations . Cheers . interface Blackboard { bool HasKey ( object key ) ; T GetValue < T > ( object key ) ; } T GetValue < T > ( object key ) { if ( typeof ( T ) == typeof ( int ) ) { // return intStore [ key ] ; // does n't compile return ( T ) ( object ) intStore [ key ] ; // boxes , allocates , bad . } // ... }",Avoiding boxing in generic blackboard "C_sharp : Json.NET defines a JConstructor type . This is confusing , because ( to the best of my knowledge ) constructors are not part of JSON . I double-checked the JSON spec and browsed json.org but could n't find anything . There also does n't seem to be much documentation about this type anywhere on the web.Because Json.NET is so widely used ( it is even cosigned by Microsoft ) I assume there has to be some reasonable motivation for including this representation in the object model . The problem is , any attempt on my part to determine that motivation is nothing but speculation.I tested out the type and its serialization , and the apparent behavior is to just wrap JavaScript code such as new constructorName ( ... ) , e.g . : outputsSo , what is the JConstructor type intended to represent and why does it exist ? new JConstructor ( `` ctorExample '' , new JValue ( `` value '' ) , new JObject ( new JProperty ( `` prop1 '' , new JValue ( 1 ) ) , new JProperty ( `` prop2 '' , new JValue ( 2 ) ) ) ) .ToString ( ) new ctorExample ( `` value '' , { `` prop1 '' : 1 , `` prop2 '' : 2 } )",Why is there a JConstructor ? "C_sharp : I have been using a WCF ( .svc ) service for a while for which request format is JSON and response format is XML in an Android application which is working fine . Couple of days ago , I implemented a certificate for SSL purpose on the WCF service from DigiCert ( using my wildcard capabilities ) . The service is accessible from browser and shows no error . Below is the WebConfigSo now while using the same Android code , the response is alwaysI have tried using SSL Factory and without it as well . < ? xml version= '' 1.0 '' ? > < configuration > < configSections > < sectionGroup name= '' applicationSettings '' type= '' System.Configuration.ApplicationSettingsGroup , System , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' > < section name= '' IntermediateWebService.Properties.Settings '' type= '' System.Configuration.ClientSettingsSection , System , Version=4.0.0.0 , Culture=neutral , PublicKeyToken=b77a5c561934e089 '' requirePermission= '' false '' / > < /sectionGroup > < /configSections > < system.web > < compilation debug= '' true '' targetFramework= '' 4.0 '' / > < customErrors mode= '' Off '' / > < /system.web > < system.serviceModel > < behaviors > < serviceBehaviors > < behavior name= '' IntermediateWebService.WebBehavior '' > < serviceMetadata httpsGetEnabled= '' true '' / > < serviceDebug includeExceptionDetailInFaults= '' true '' / > < /behavior > < behavior > < ! -- To avoid disclosing metadata information , set the value below to false and remove the metadata endpoint above before deployment -- > < serviceMetadata httpsGetEnabled= '' true '' / > < ! -- To receive exception details in faults for debugging purposes , set the value below to true . Set to false before deployment to avoid disclosing exception information -- > < serviceDebug includeExceptionDetailInFaults= '' false '' / > < /behavior > < /serviceBehaviors > < endpointBehaviors > < behavior name= '' WebBehavior '' > < /behavior > < /endpointBehaviors > < /behaviors > < bindings > < basicHttpBinding > < binding name= '' secureHttpBinding '' maxBufferPoolSize= '' 524288 '' maxReceivedMessageSize= '' 999999999 '' > < security mode= '' Transport '' > < transport clientCredentialType= '' None '' / > < /security > < /binding > < /basicHttpBinding > < webHttpBinding > < binding name= '' webHttpBindingConfig '' > < readerQuotas maxStringContentLength= '' 2048000 '' / > < /binding > < /webHttpBinding > < /bindings > < services > < service behaviorConfiguration= '' IntermediateWebService.WebBehavior '' name= '' IntermediateWebService.Service1 '' > < host > < baseAddresses > < add baseAddress= '' https : //myurl:4445/ '' / > < /baseAddresses > < /host > < endpoint address= '' '' binding= '' basicHttpBinding '' contract= '' IntermediateWebService.IService1 '' behaviorConfiguration= '' WebBehavior '' bindingConfiguration= '' secureHttpBinding '' / > < /service > < ! -- < service name= '' IntermediateWebService.Service1 '' > < endpoint address= '' '' binding= '' basicHttpBinding '' bindingConfiguration= '' secureHttpBinding '' contract= '' IntermediateWebService.IService1 '' / > < /service > -- > < /services > < serviceHostingEnvironment multipleSiteBindingsEnabled= '' false '' / > < /system.serviceModel > < system.webServer > < validation validateIntegratedModeConfiguration= '' false '' / > < modules runAllManagedModulesForAllRequests= '' true '' / > < /system.webServer > < /configuration > The server can not service the request because the media type is unsupported . HttpClient client = getHttpsClient ( new DefaultHttpClient ( ) ) ; //new DefaultHttpClient ( ) ; HttpPost get = null ; commandType = params [ 0 ] .toString ( ) ; if ( `` Login '' .equals ( params [ 0 ] ) ) { JSONStringer img = new JSONStringer ( ) .object ( ) .key ( `` value '' ) .object ( ) .key ( `` username '' ) .value ( params [ 1 ] .toString ( ) ) .key ( `` pwd '' ) .value ( params [ 2 ] .toString ( ) ) .key ( `` channelID '' ) .value ( params [ 3 ] .toString ( ) ) .endObject ( ) .endObject ( ) ; StringEntity se = new StringEntity ( img.toString ( ) ) ; get = new HttpPost ( `` https : // '' + serverIP + `` : '' + serverPort + `` /Service1.svc/auth '' ) ; //get.setHeader ( `` User-Agent '' , `` com.app.new '' ) ; get.setHeader ( `` Accept '' , `` application/json '' ) ; get.setHeader ( `` Content-Type '' , `` application/json '' ) ; get.setEntity ( se ) ;",Consume WCF Service over SSL in Android "C_sharp : In C # you can make a block inside of a method that is not attached to any other statement.This code compiles and runs just as if the braces inside the main method were n't there . Also notice the block inside of a block.Is there a scenario where this would be valuable ? I have n't found any yet , but am curious to hear of other people 's findings . public void TestMethod ( ) { { string x = `` test '' ; string y = x ; { int z = 42 ; int zz = z ; } } }",What is the value of an anonymous unattached block in C # ? "C_sharp : I am looking for some class structure help . Lets say I have a class called Dog holds information about the dog ( name , weight , type ) but because there could be multiple dogs , I would also like a class to hold all of these dogs , for use throughout my entire project . Whats the best way to go about doing this ? Just to have a DogList class , that stores the Dog class information into a public list ? Allowing me to retrieve it at will ? Or should the list be a static within the original dog class ? maybe in the constructor , any time someone creates a new dog , the dog gets put into the static list ? Edit : Sorry question was a bit miss leadingHere is the structure I have so far , wondering if there is a better way to implement . public class Dog { public string name { get ; set ; } public int weight { get ; set ; } } public class DogFactory //not sure if thats the correct wording { public List < dog > lstDogs = new List < dog > ( ) ; public void setDogs ( ) { Animal.Retrieve ( `` Dog '' ) ; //will retrieve a list of all dogs , with details , though this is costly to use foreach ( Animal.Dog pet in Animal._Dogs ) { Dog doggie = new doggie ( ) ; doggie.Name = pet.Name ; ... etc lstDog.add ( doggie ) ; } } }",Class Structure for a list Class ? "C_sharp : I 'm trying to have a strongly typed Id class , which now holds 'long ' internally . Implementation below.The problem I 'm having the using this in my entities is that Entity Framework gives me a message that the property Id is already mapped onto it . See my IEntityTypeConfiguration below.Note : I am not aiming to have a rigid DDD implementation . So please keep this in mind when commenting or answering . The whole id behind the typed Id is for developers coming to the project they 're strongly typed to use Id in all of their entities , of course translated to long ( or BIGINT ) - but it is clear then for others.Below the class & configuration , which does n't work.The repo can be found at https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31 , Id class at ( commented out now ) : https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/blob/master/Source/Common/Kf.CANetCore31/DomainDrivenDesign/Id.csEntity and ValueObject classes ( where for an Entity the property Id was of the type Id.cs ( above ) : https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Common/Kf.CANetCore31/DomainDrivenDesignConfigurations at : https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Infrastructure/Persistence/Kf.CANetCore31.Infrastructure.Persistence.Ef/EntityTypeConfigurationsId class implementation ( marked obsolete now , because I abandoned the idea until I found a solution for this ) EntityTypeConfiguration I was using when Id not marked obsolete for entity Person Unfortunately though , when of type Id , EfCore did n't want to map it ... when of type long it was no problem ... Other owned types , as you see ( with Name ) work fine.Entity base class ( when I was still using Id , so when it was n't marked obsolete ) Person ( the domain and references to the other ValueObjects can be found at https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Core/Domain/Kf.CANetCore31.Core.Domain/People ) namespace Kf.CANetCore31.DomainDrivenDesign { [ DebuggerDisplay ( `` { DebuggerDisplayString , nq } '' ) ] [ Obsolete ] public sealed class Id : ValueObject { public static implicit operator Id ( long value ) = > new Id ( value ) ; public static implicit operator long ( Id value ) = > value.Value ; public static implicit operator Id ( ulong value ) = > new Id ( ( long ) value ) ; public static implicit operator ulong ( Id value ) = > ( ulong ) value.Value ; public static implicit operator Id ( int value ) = > new Id ( value ) ; public static Id Empty = > new Id ( ) ; public static Id Create ( long value ) = > new Id ( value ) ; private Id ( long id ) = > Value = id ; private Id ( ) : this ( 0 ) { } public long Value { get ; } public override string DebuggerDisplayString = > this.CreateDebugString ( x = > x.Value ) ; public override string ToString ( ) = > DebuggerDisplayString ; protected override IEnumerable < object > EquatableValues = > new object [ ] { Value } ; } } public sealed class PersonEntityTypeConfiguration : IEntityTypeConfiguration < Person > { public void Configure ( EntityTypeBuilder < Person > builder ) { // this would be wrapped in either a base class or an extenion method on // EntityTypeBuilder < TEntity > where TEntity : Entity // to not repeated the code over each EntityTypeConfiguration // but expanded here for clarity builder .HasKey ( e = > e.Id ) ; builder .OwnsOne ( e = > e.Id , id = > { id.Property ( e = > e.Id ) .HasColumnName ( `` firstName '' ) .UseIdentityColumn ( 1 , 1 ) .HasColumnType ( SqlServerColumnTypes.Int64_BIGINT ) ; } builder.OwnsOne ( e = > e.Name , name = > { name.Property ( p = > p.FirstName ) .HasColumnName ( `` firstName '' ) .HasMaxLength ( 150 ) ; name.Property ( p = > p.LastName ) .HasColumnName ( `` lastName '' ) .HasMaxLength ( 150 ) ; } ) ; builder.Ignore ( e = > e.Number ) ; } } namespace Kf.CANetCore31.DomainDrivenDesign { /// < summary > /// Defines an entity . /// < /summary > [ DebuggerDisplay ( `` { DebuggerDisplayString , nq } '' ) ] public abstract class Entity : IDebuggerDisplayString , IEquatable < Entity > { public static bool operator == ( Entity a , Entity b ) { if ( ReferenceEquals ( a , null ) & & ReferenceEquals ( b , null ) ) return true ; if ( ReferenceEquals ( a , null ) || ReferenceEquals ( b , null ) ) return false ; return a.Equals ( b ) ; } public static bool operator ! = ( Entity a , Entity b ) = > ! ( a == b ) ; protected Entity ( Id id ) = > Id = id ; public Id Id { get ; } public override bool Equals ( object @ object ) { if ( @ object == null ) return false ; if ( @ object is Entity entity ) return Equals ( entity ) ; return false ; } public bool Equals ( Entity other ) { if ( other == null ) return false ; if ( ReferenceEquals ( this , other ) ) return true ; if ( GetType ( ) ! = other.GetType ( ) ) return false ; return Id == other.Id ; } public override int GetHashCode ( ) = > $ '' { GetType ( ) } { Id } '' .GetHashCode ( ) ; public virtual string DebuggerDisplayString = > this.CreateDebugString ( x = > x.Id ) ; public override string ToString ( ) = > DebuggerDisplayString ; } } namespace Kf.CANetCore31.Core.Domain.People { [ DebuggerDisplay ( `` { DebuggerDisplayString , nq } '' ) ] public sealed class Person : Entity { public static Person Empty = > new Person ( ) ; public static Person Create ( Name name ) = > new Person ( name ) ; public static Person Create ( Id id , Name name ) = > new Person ( id , name ) ; private Person ( Id id , Name name ) : base ( id ) = > Name = name ; private Person ( Name name ) : this ( Id.Empty , name ) { } private Person ( ) : this ( Name.Empty ) { } public Number Number = > Number.For ( this ) ; public Name Name { get ; } public override string DebuggerDisplayString = > this.CreateDebugString ( x = > x.Number.Value , x = > x.Name ) ; } }",Strongly Typed Ids in Entity Framework Core "C_sharp : I am doing analysis on the time spend in a critical section of code.And sometime I have some values clearly higher than others.I suspect that it is Garbage collection , so I want to correlate the high values with the fact that a Garbage collection occured during the process.I tryed this so far : I take the counter before : Am I doing it in the good way ? //Take a timestamp beforevar before = DateTime.UtcNow ; DoCriticalMethod ( ) ; //Take a timestamp aftervar after = DateTime.UtcNow ; //Take the number beforeint gc2CountBefore = GC.CollectionCount ( 2 ) ; ... //Take the number afterbool hasgc2occured = ( GC.CollectionCount ( 2 ) - gc2CountBefore ) ! = 0 ;",How to know if a gen full garbage collection has been triggered between two checkpoints ? "C_sharp : The documentation for converting delegates to unmanaged code states that I am responsible for preventing it 's collection myself . I wish to know if the delegate can not be collected whilst the unmanaged call is live . For example , if I dowhere UnmanagedFunction does not store the function pointer beyond it 's invocation . This should be legal , right ? The CLR ca n't collect whilst the UnmanagedFunction is executing . UnmanagedFunction ( arg = > somebody ) ;",Preventing unmanaged function pointer garbage collection "C_sharp : Is it a code smell to inject a dependency and set one of its properties to your current instance ? I set my code in this manner so I could completely isolate the service implementation . I have a series of test which all pass ( including setting the StreamingSubscriber instance in the logic class ) .For exampleIf this is a code smell how do you go about to fix it ? EditThe reason I chose this implementation is because I wanted to be able to test that when streamingConnection from ExchangeLogic was called that it would consumer the email . The current design , while not perfect , allow me to write tests similar such as this . Now , this is obviously not achievable without doing full blown integration tests If I told my ExchangeLogic to consume the email . public class StreamingSubscriber { private readonly ILogic _logic ; public StreamingSubscriber ( ILogic logic ) { _logic = logic ; // Not sure I like this ... _logic.StreamingSubscriber = this ; } public void OnNotificationEvent ( object sender , NotificationEventArgs args ) { // Do something with _logic var email = _logic.FetchEmail ( args ) ; // consume the email ( omitted for brevity ) } } public class ExchangeLogic : ILogic { public StreamingSubscriber StreamingSubscriber { get ; set ; } public void Subscribe ( ) { // Here is where I use StreamingSubscriber streamingConnection.OnNotificationEvent += StreamingSubscriber.OnNotificationEvent ; } public IEmail FetchEmail ( NotificationEventArgs notificationEventArgs ) { // Fetch email from Exchange } } [ Test ] public void FiringOnNotificationEvent_WillConsumeEmail ( ) { // Arrange var subscriber = new StreamingSubscriber ( ConsumerMock.Object , ExchangeLogicMock.Object ) ; // Act subscriber.OnNotificationEvent ( It.IsAny < object > ( ) , It.IsAny < NotificationEventArgs > ( ) ) ; // Assert ConsumerMock.Verify ( x = > x.Consume ( It.IsAny < IEmail > ( ) ) , Times.Once ( ) ) ; }",Is it a code smell to inject a dependency and set one of its members to ` this ` ? "C_sharp : Question about threading to satisfy my curiosity ... Let 's say I have static variable _status ( ProgressStatus ) and many threads are reading from this . To update this static variable I use an immutable object ProgressStatus , create a new instance and then swap out the reference . Here 's the reader codeWhat 's the worst that could happen if I do n't apply the lock ? var status = new ProgressStatus ( 50 , `` Working on it '' ) ; //plus many more fields in constructorlock ( _statusLocker ) _status = status ; // Very brief lock public GetProgressStatus ( ) { var status = new ProgressStatus ( _status.ID , _status.Description ) ; return status }",.NET C # Multithreading "C_sharp : Possible Duplicate : Child Scope & CS0136 C # Variable Scoping Though I have been using C # for quite some time , I have just stumbled upon this error.If I have the following : I get an error that says : A local variable named ' x ' can not be declared in this scope because it would give a different meaning to ' x ' , which is already used in a child scope to denote something else.And if I do this : I get an error that says : The name ' x ' does not exist in the current context.I can understand having one or the other , but why do both of these errors exist ? Is there a way around the first option ? I find it very annoying.Thanks . if ( true ) { int x = 0 ; } int x = 0 ; if ( true ) { int x = 0 ; } x = 0 ;",How Does Local-Scope Work in C # "C_sharp : For this question consider ( create ) the interface : Then run the following code : In all seven cases we make an expression tree where the TakeInt64 gets an int ( Int32 ) instead of a long ( Int64 ) . However , as is well known , there exists an implicit conversion from int to long which will be present in the expression tree ( except in expr1 where the compiler converts the constant for us ) .How come the cases s4 and s5 above wo n't work ? Curiously , as you can see , if we add 0 or multuply by 1 as in cases s6 and s7 , that works ( even if the type is still int , implicitly converted to long ) ? Please answer before year 3000 because of case expr2 . public interface ITestMe { string TakeInt64 ( long x ) ; } public void Test ( ) { var mock1 = new Mock < ITestMe > ( MockBehavior.Strict ) ; Expression < Func < ITestMe , string > > expr1 = x = > x.TakeInt64 ( 2 ) ; Console.WriteLine ( expr1 ) ; mock1.Setup ( expr1 ) .Returns ( `` OK '' ) ; var s1 = mock1.Object.TakeInt64 ( 2L ) ; // OK var mock2 = new Mock < ITestMe > ( MockBehavior.Strict ) ; Expression < Func < ITestMe , string > > expr2 = x = > x.TakeInt64 ( DateTime.Today.Year / 1000 ) ; Console.WriteLine ( expr2 ) ; mock2.Setup ( expr2 ) .Returns ( `` OK '' ) ; var s2 = mock2.Object.TakeInt64 ( 2L ) ; // OK var mock3 = new Mock < ITestMe > ( MockBehavior.Strict ) ; Expression < Func < ITestMe , string > > expr3 = x = > x.TakeInt64 ( ( int ) ( DayOfWeek ) Enum.Parse ( typeof ( DayOfWeek ) , `` Tuesday '' ) ) ; Console.WriteLine ( expr3 ) ; mock3.Setup ( expr3 ) .Returns ( `` OK '' ) ; var s3 = mock3.Object.TakeInt64 ( 2L ) ; // OK var mock4 = new Mock < ITestMe > ( MockBehavior.Strict ) ; Expression < Func < ITestMe , string > > expr4 = x = > x.TakeInt64 ( GetInt32 ( ) ) ; Console.WriteLine ( expr4 ) ; mock4.Setup ( expr4 ) .Returns ( `` OK '' ) ; //var s4 = mock4.Object.TakeInt64 ( 2L ) ; // MockException , All invocations on the mock must have a corresponding setup . var mock5 = new Mock < ITestMe > ( MockBehavior.Strict ) ; Expression < Func < ITestMe , string > > expr5 = x = > x.TakeInt64 ( int.Parse ( `` 2 '' ) ) ; Console.WriteLine ( expr5 ) ; mock5.Setup ( expr5 ) .Returns ( `` OK '' ) ; //var s5 = mock5.Object.TakeInt64 ( 2L ) ; // MockException , All invocations on the mock must have a corresponding setup . var mock6 = new Mock < ITestMe > ( MockBehavior.Strict ) ; Expression < Func < ITestMe , string > > expr6 = x = > x.TakeInt64 ( GetInt32 ( ) + 0 ) ; Console.WriteLine ( expr6 ) ; mock6.Setup ( expr6 ) .Returns ( `` OK '' ) ; var s6 = mock6.Object.TakeInt64 ( 2L ) ; // OK var mock7 = new Mock < ITestMe > ( MockBehavior.Strict ) ; Expression < Func < ITestMe , string > > expr7 = x = > x.TakeInt64 ( 1 * int.Parse ( `` 2 '' ) ) ; Console.WriteLine ( expr7 ) ; mock7.Setup ( expr7 ) .Returns ( `` OK '' ) ; var s7 = mock7.Object.TakeInt64 ( 2L ) ; // OK } static int GetInt32 ( ) { return 2 ; }",Moq setup wo n't work for a method call followed by an implicit conversion "C_sharp : I have a class Product to hold a specific instance of a given product.This class has a list of related products that are similar to main product.I want to define a method within Product class to get top N ( best rated ) related products . This method should take into consideration that elements in RelatedProducts list are of type Product and they also have their own RelatedProducts list . So I should keep navigating nested object until all related products were reached and after that , take the top N product . I mean , the solution would not be simply this.RelatedProducts.OrderByDescending ( x = > x.Rating ) .Take ( N ) ; One more thing to keep in mind : Two products can be mutually related . Which means a product A can belong to RelatedProducts list of a product B and B also can belong to RelatedProducts list of product A.Any suggestion how to solve this issue in optimal way ? Imagine , I have millions of products to maintain . How can I navigate all related products recursively and recognize already visited ones ? I tagged this as both C # and Java , as the same logic could be applied to both languages class Product { public string Name ; public double Rating ; public List < Product > RelatedProducts ; // ... public List < Product > GetTopRelatedProducts ( int N ) { // How to implement this method // What I did so far ( Bad code ) // 1- INFINITE RECURSION // 2- Can not remember visited objects var myList = new List < Product > ( ) ; foreach ( Product prod in RelatedProducts ) { myList.AddRange ( prod.GetTopRelatedProducts ( N ) ) ; } return myList.Distinct ( ) .OrderByDescending ( x = > x.Rating ) .Take ( N ) .ToList ( ) ; } }",Select top N elements of related objects "C_sharp : We have an application ( console application `` server '' self hosting a bunch of WCF services and a few WPF clients ) written in .NET 3.5 . I wanted to have a go at upgrading the `` server '' app to .NET 4.6 . For testing I was just going to change the runtime and add some child projects in 4.6 , leaving the rest of the projects at 3.5 . In the top level project I changed the target to 4.6 and made sure the app.config file had this in it : The WCF services and other support projects are in the solution and I did not modify them in anyway.I also did not modify the WPF client.In some of our services we implement the asynchronous begin/end pattern on the server . This is new to me as I learned WCF with the async/await pattern ( though I 'm familiar with begin/end in general ) . Any asynchronous requirements on the client are left up to the calling code.ServiceClient ( As generated by Visual Studio `` Add Service Reference '' ) On the client we have a few generic classes that wrap and expose our services , calls can happen on the main thread but usually are on background threads via background workers . By simply upgrading the server app from .NET 3.5 to 4+ and not making any changes , the End methods on the server are no longer called . I 've confirmed that the Begin methods return and that the workers call .Complete ( ) and invoke the callback , but nothing happens after that . After 1 minute the client will throw a timeout exception on the call.Our codebase is fairly large and complex and I was n't expecting any changes in behaviour after reading the .NET 4 migration notes.EDIT : I 've included a screenshot of the microsoft service trace utility showing the same call to FetchProductVersion before the update ( top , 3.5 ) and after ( bottom , 4.6 ) .EDIT 2/3 : The failures seem inconsistent in some cases . < startup useLegacyV2RuntimeActivationPolicy= '' true '' > < supportedRuntime version= '' v4.0 '' sku= '' .NETFramework , Version=v4.6 '' / > < /startup > public interface IMyServiceCallback { void UnrelatedNotifyClientsMethod ( Notification message ) ; } [ ServiceContract ( CallbackContract = typeof ( IMyServiceCallback ) ) ] public interface IMyService { // ... [ OperationContract ( AsyncPattern = true ) ] IAsyncResult BeginFetchSomething ( int howMany , AsyncCallback callback , object state ) ; FetchSomethingResult EndFetchSomething ( IAsyncResult result ) ; // ... } [ ServiceBehavior ( InstanceContextMode = InstanceContextMode.Single , ConcurrencyMode = ConcurrencyMode.Multiple ) ] public class MyService : IMyService { // ... [ PermissionSetAttribute ( SecurityAction.LinkDemand , Name = `` FullTrust '' ) ] public IAsyncResult BeginFetchSomething ( int howMany , AsyncCallback callback , object state ) { AsyncResult < FetchSomethingResult > something = new AsyncResult < FetchSomethingResult > ( callback , state ) ; BackgroundWorker backgroundWorker = new BackgroundWorker ( ) ; backgroundWorker.DoWork += new DoWorkEventHandler ( ( sender , args ) = > { try { FetchSomethingResult resultData = Database.FetchSomethingQuery ( howMany ) ; something.Result = resultData ; something.Complete ( true ) ; } catch ( Exception e ) { Log ( e ) ; something.HandleException ( e , false ) ; } backgroundWorker.Dispose ( ) ; } ) ; backgroundWorker.RunWorkerAsync ( ) ; return something ; } public FetchSomethingResult EndFetchSomething ( IAsyncResult result ) { AsyncResult < FetchSomethingResult > something = result as AsyncResult < FetchSomethingResult > ; something.AsyncWaitHandle.WaitOne ( ) ; return something.Result ; } // ... // other similar methods // ... } public class AsyncResult : IAsyncResult { // ... public void Complete ( bool completedSynchronously ) { lock ( this.Mutex ) { this.IsCompleted = true ; this.CompletedSynchronously = completedSynchronously ; } this.SignalCompletion ( ) ; } protected void SignalCompletion ( ) { ( this.AsyncWaitHandle as ManualResetEvent ) .Set ( ) ; ThreadPool.QueueUserWorkItem ( d = > { this.InvokeCallback ( ) ; } ) ; } protected void InvokeCallback ( ) { if ( this.Callback ! = null ) { this.Callback ( this ) ; } } public void HandleException ( Exception e , bool completedSynchronously ) { lock ( this.Mutex ) { this.IsCompleted = true ; this.CompletedSynchronously = completedSynchronously ; this.Exception = e ; } this.SignalCompletion ( ) ; } // ... } [ System.CodeDom.Compiler.GeneratedCodeAttribute ( `` System.ServiceModel '' , `` 4.0.0.0 '' ) ] public partial class MyServiceClient : System.ServiceModel.DuplexClientBase < NameSpace.ServiceClients.IMyServiceClient > , NameSpace.ServiceClients.IMyServiceCliene { // ... public NameSpace.ServiceClients.FetchSomethingResult FetchSomething ( int howMany ) { return base.Channel.FetchSomething ( howMany ) ; } // ... }",WCF Asynchronous 'End ' method not called after upgrading .NET C_sharp : let 's say I have a big ListAnd I want to do the following query : Is there a way to use PLinq for that to let each thread search just a little part of the list ? I know that using a Dictionary or a HashMap would be better in this case . It is just something I want to know regarding PLinq and this example was very handy . List < long > longList = new List < long > ( 10000000 ) bool found = longList.Contains ( 4345235234524245124L ) ;,List Contains ( ) with PLinq ? C_sharp : Consider this code : Why does the code run into an infinite loop ? Why does n't the compiler throw any exception ? double d = 9000000000000000000d ; while ( d == 9000000000000000000d ) { d += 500 ; Console.WriteLine ( d ) ; },d == 9000000000000000000d infinite loop "C_sharp : When I look at list populated with single item in debugger its _items field contains 4 elements . Can you explain the behavior ? I 've found that while debugging my console application to learn about Distinct and ToList and result confuses me . Code : distinctNums has 4 elements in _items : ( 6 , 0 , 0 , 0 ) which is clearly wrong.distinctNums2 has 1 item ( 6 ) which is correct . List < int > nums = new List < int > ( ) { 6 , 6 , 6 , 6 , 6 , 6 , 6 , 6 } ; List < int > distinctNums = nums.Distinct ( ) .ToList ( ) ; int [ ] distinctNums2 = nums.Distinct ( ) .ToArray ( ) ;",List shows 4 items in debugger even if filled with exactly one element "C_sharp : I have a legacy code , and I have a problem with reconstructor it.At start of my application I load from WCF to property on App ( this is SL application ) list of users.Then every control ( for sending emails , view calendar and assigning tasks ) use this property as Now , I 'm trying to create Unit Test for one of controls that use this lists , and I 'm stuck.Should I make a Constructor Injection ( I 'm using Unity ) with App as parameter ? Or maybe introduce some class to hold this list ? ( App.Current as App ) .Users",Where to keep dictionaries in app using Dependency Injection "C_sharp : Observation : If text is null , this method returns True . I expected False.When I reflect the above line using ILSpy ( or inspect the IL ) , this is the generated code : Here is what I really need to meet my expectation : Question : Does someone have a good explanation about why the Null Conditional code generated the OR expression ? Full Sample at : https : //dotnetfiddle.net/T1iI1c return text ? .IndexOf ( ' A ' ) ! = -1 ; return text == null || text.IndexOf ( ' A ' ) ! = -1 ; return text ! = null & & text.IndexOf ( ' A ' ) ! = -1 ;","When text is null , text ? .IndexOf ( ch ) ! = -1 is True ?" "C_sharp : I 'm trying to run some setup code in one of my xUnit.net test classes , but although the tests are running it does n't appear the constructor is.Here 's some of my code : I 'm using the SampleValues as a MemberData , so I can use them in tests like thisHowever , I 'm consistently getting an error saying that `` no data was found for [ method ] '' , for all the methods that use SampleValues . After I investigated further , I found out the LeaseTests constructor was n't even being run ; when I set a breakpoint on the call to AssignToSampleValues , it was n't hit.Why is this happening , and what can I do to fix it ? Thanks . public abstract class LeaseTests < T > { private static readonly object s_lock = new object ( ) ; private static IEnumerable < T > s_sampleValues = Array.Empty < T > ( ) ; private static void AssignToSampleValues ( Func < IEnumerable < T > , IEnumerable < T > > func ) { lock ( s_lock ) { s_sampleValues = func ( s_sampleValues ) ; } } public LeaseTests ( ) { AssignToSampleValues ( s = > s.Concat ( CreateSampleValues ( ) ) ) ; } public static IEnumerable < object [ ] > SampleValues ( ) { foreach ( T value in s_sampleValues ) { yield return new object [ ] { value } ; } } protected abstract IEnumerable < T > CreateSampleValues ( ) ; } // Specialize the test class for different typespublic class IntLeaseTests : LeaseTests < int > { protected override IEnumerable < int > CreateSampleValues ( ) { yield return 3 ; yield return 0 ; yield return int.MaxValue ; yield return int.MinValue ; } } [ Theory ] [ MemberData ( nameof ( SampleValues ) ) ] public void ItemShouldBeSameAsPassedInFromConstructor ( T value ) { var lease = CreateLease ( value ) ; Assert.Equal ( value , lease.Item ) ; }",xUnit.net : Test class constructors not being run ? "C_sharp : Say I have a C # struct : And then I create and array of Foo 's : What happens when I do this ? If Foo was a class , the Foo [ ] would hold a pointer to a Foo object on the heap , and that pointer would be changed to the new Foo object ( the old one being left for recycling ) . But since structs are value types , would the new Foo ( 20 , 10 ) just physically overwrite the same memory location previously held by foos [ 1 ] ? struct Foo { int mA ; public int A { get { return mA ; } } int mB ; public int B { get { return mB ; } } public Foo ( int a , int b ) { mA = a ; mB = b ; } } Foo [ ] foos = new Foo [ 10 ] ; foos [ 1 ] = new Foo ( 20 , 10 ) ;",What happens when assign new struct to array in C # ? C_sharp : Suppose I have defined two unrelated types and two extension methods with the same signature but different type filters : Then when I write new Foo ( ) .Frob ( ) ; I get an error error CS0121 : The call is ambiguous between the following methods or properties : 'FooExtensions.Frob < TFoo > ( TFoo ) ' and 'BarExtensions.Frob < TBar > ( TBar ) 'Could someone explain why this fails and how to avoid it ? EDIT : This happens in VS2015 Update 3 and VS2017 RC.EDIT2 : The idea here is to have fluent API that works on a class hierarchy : public class Foo { } public class Bar { } public static class FooExtensions { public static TFoo Frob < TFoo > ( this TFoo foo ) where TFoo : Foo { } public static TFoo Brob < TFoo > ( this TFoo foo ) where TFoo : Foo { } } public static class BarExtensions { public static TBar Frob < TBar > ( this TBar bar ) where TBar : Bar { } } new Foo ( ) .Frob ( ) .Brob ( ),C # generic method resolution fails with an ambiguous call error "C_sharp : It 's a bit hard to explain what I really want ( better title suggestions are appreciated so people can find this easily in the future ) .Suppose I have this : I want to matchi.e . match everything from the last { before $ myTagThing $ until the first } after $ myTagThing $ .So I thought I 'd need this \ { .*\ $ myTagThing\ $ . *\ } , but it will also match the first { and last } in the string ( i.e . the whole example ) . Then I tried using a lookahead and a lookbehind ( both negative ) \ { ( .* ( ? ! \ { ) ) \ $ myTagThing\ $ .* ( ? < ! \ } ) \ } ( https : //regex101.com/r/RfdHUH/1/ ) . But this still does n't work.My theory is that I might be using lookahead and lookbehind the wrong way since this is the first time I use them.Any ideas ? EDIT : flags are \gms . { { $ myTagThing $ } } { $ myTagThing $ }",Regex : match everything inside closest opening and closing curly braces around expression "C_sharp : I 've got a List < MyClass > : Now , the data can ( and does ) look like this : One : 1 , Two : 9One : 2 , Two : 9One : 1 , Two : 8One : 3 , Two : 7See how `` One '' appears twice ? I want to project this flat sequence into a grouped Dictionary < int , ICollection < int > > : KeyValuePairOne : { Key : 1 , Value : { 9 , 8 } } KeyValuePairTwo : { Key : 2 , Value : { 9 } } KeyValuePairThree : { Key : 3 , Value : { 7 } } I 'm guessing i need to do a combination of .GroupBy and .ToDictionary ? public int MyClass { public int One { get ; set ; } public int Two { get ; set ; } }","C # Expand Flat List < T > to Dictionary < T , ICollection < int > >" C_sharp : Does it matter which order I put conditions in Entity framework ? I know that EF does some optimizations before running the SQL query . So does it matter what condtion I put first ? For example ( just a subset of the real query in our application ) . CaseNumber is a string and OrganizationId is a guid.Or context.Evaluation.Where ( e = > e.Case.CaseNumber.Contains ( inputModel.CaseNumber ) & & e.Case.OrganizationId == inputModel.OrganizationId ) context.Evaluation.Where ( e = > e.Case.OrganizationId == inputModel.OrganizationId ) & & e.Case.CaseNumber.Contains ( inputModel.CaseNumber ),Does it matter which order I put conditions in Entity framework "C_sharp : Linq allows you to create new object inside of a query expression . This is useful when you have classes that encapsulate generation of a list . I ’ m wondering how you dispose of objects that are created that need it ? Example : This will create 3 Generator objects that will be garbage collected at some point . If Generator was IDisposable how would I get the Dispose ( ) call ? class Generator { public IEnumerable < int > Gen ( int size ) { return Enumerable.Range ( 0 , size ) ; } } class bar { public void doit ( ) { var foo = from r in Enumerable.Range ( 1 , 3 ) from g in new Generator ( ) .Gen ( r ) select g ; } }",How do you dispose of IDisposableobject create inside of a Linq expression ? "C_sharp : I must be missing something ... How can an exception be thrown , yet the code following the exception still gets hit in the debugger ? private UpdaterManifest GetUpdaterManifest ( ) { string filePathAndName = Path.Combine ( this._sourceBinaryPath , this._appName + `` .UpdaterManifest '' ) ; if ( ! File.Exists ( filePathAndName ) ) { // This line of code gets executed : throw new FileNotFoundException ( `` The updater manifest file was not found . This file is necessary for the program to run . `` , filePathAndName ) ; } UpdaterManifest updaterManifest ; using ( FileStream fileStream = new FileStream ( filePathAndName , FileMode.Open ) ) { // ... so how is it that the debugger stops here and the call stack shows // this line of code as the current line ? How can we throw an exception // above and still get here ? XmlSerializer xmlSerializer = new XmlSerializer ( typeof ( UpdaterManifest ) ) ; updaterManifest = xmlSerializer.Deserialize ( fileStream ) as UpdaterManifest ; } return updaterManifest ; }",How is code executing after an exception ? "C_sharp : Jon Skeet suggests in his singleton implementation that if you require the maximum laziness for your singleton you should add a static constructor which will make the compiler mark the type as beforefieldinit.However , I did some testing and it seems that it 's more lazy without the beforefieldinit.Code sample ( the private constructor call outputs to console and verifies that the fields were initialized : When I call Singleton.Stub ( ) the private constructor is not being hit , and when I uncomment the static constructor , the private constructor is always called.This is the only difference I could track made by the static constructor.In my attempts to understand what difference will the beforefieldinit do I 've also read Skeet 's answer in this post tried it with passing false to DoSomething ( ) - with or without the static constructor the private constructor is not being called . public sealed class Singleton { private static readonly Singleton instance = new Singleton ( ) ; public static string Stub ( ) { return `` 123 '' ; } // Explicit static constructor to tell C # compiler // not to mark type as beforefieldinit //static Singleton ( ) // { // } private Singleton ( ) { Console.WriteLine ( `` private ctor '' ) ; } public static Singleton Instance { get { return instance ; } } } public static void DoSomething ( bool which ) { if ( which ) { var a = Singleton.Stub ( ) ; } else { Faketon.Stub ( ) ; } }",Singleton implementation laziness with static constructor "C_sharp : A class contains an attribute that should be created only one time . The creation process is via a Func < T > which is pass in argument . This is a part of a caching scenario.The test take care that no matter how many threads try to access the element , the creation occurs only once.The mechanism of the unit test is to launch a great number of threads around the accessor , and count how many times the creation function is called.This is not deterministic at all , nothing guaranteed that this is effectively testing a multithread access . Maybe there will be only one thread at a time that will hit the lock . ( In reality , getFunctionExecuteCount is between 7 and 9 if the lock is not there ... On my machine , nothing guaranteed that on the CI server it 's going to be the same ) How the unit test can be rewritten in a deterministic way ? How to be sure that the lock is triggered multiple times by multiple thread ? The worst scenario is if someone break the lock code , and the testing server had some lag . This test should n't pass : using Microsoft.VisualStudio.TestTools.UnitTesting ; using System ; using System.Linq ; using System.Threading ; using System.Threading.Tasks ; namespace Example.Test { public class MyObject < T > where T : class { private readonly object _lock = new object ( ) ; private T _value = null ; public T Get ( Func < T > creator ) { if ( _value == null ) { lock ( _lock ) { if ( _value == null ) { _value = creator ( ) ; } } } return _value ; } } [ TestClass ] public class UnitTest1 { [ TestMethod ] public void MultipleParallelGetShouldLaunchGetFunctionOnlyOnce ( ) { int getFunctionExecuteCount = 0 ; var cache = new MyObject < string > ( ) ; Func < string > creator = ( ) = > { Interlocked.Increment ( ref getFunctionExecuteCount ) ; return `` Hello World ! `` ; } ; // Launch a very big number of thread to be sure Parallel.ForEach ( Enumerable.Range ( 0 , 100 ) , _ = > { cache.Get ( creator ) ; } ) ; Assert.AreEqual ( 1 , getFunctionExecuteCount ) ; } } } using NUnit.Framework ; using System ; using System.Linq ; using System.Threading ; using System.Threading.Tasks ; namespace Example.Test { public class MyObject < T > where T : class { private readonly object _lock = new object ( ) ; private T _value = null ; public T Get ( Func < T > creator ) { if ( _value == null ) { // oups , some intern broke the code //lock ( _lock ) { if ( _value == null ) { _value = creator ( ) ; } } } return _value ; } } [ TestFixture ] public class UnitTest1 { [ Test ] public void MultipleParallelGetShouldLaunchGetFunctionOnlyOnce ( ) { int getFunctionExecuteCount = 0 ; var cache = new MyObject < string > ( ) ; Func < string > creator = ( ) = > { Interlocked.Increment ( ref getFunctionExecuteCount ) ; return `` Hello World ! `` ; } ; Parallel.ForEach ( Enumerable.Range ( 0 , 2 ) , threadIndex = > { // testing server has lag Thread.Sleep ( threadIndex * 1000 ) ; cache.Get ( creator ) ; } ) ; // 1 test passed : ' ( Assert.AreEqual ( 1 , getFunctionExecuteCount ) ; } } }",How to unit test code that should execute only once in a MultiThread scenario ? "C_sharp : I 'm looking for a method to convert instance of MemberInfo to `` Func '' type ( to use it through lambda expression later ) .Lets , say I have a member function of typeUsing reflection , I somehow get instance of MemberInfo `` mi '' , now i want to convert it to Func < int , bool > ; type . something like : Is there a way to do it ? ps . Marc Grawell 's answer resolves my issue , no need for further comments public bool func ( int ) ; Func < int , bool f = myType.GetMember ( mi.Name ) ;","Reflection MemberInfo to Func < T1 , T2 >" "C_sharp : Inside a linq query to an anonymous select I want to concatenate strings from two properties.For instance to find the full name of the oldest person in some grouping of persons.Do I have to write the full aggregation again to get the LastName after the firstname and whitespace ? var personsAndOldest = db.Persons.GroupBy ( person = > person.SomeThingThatCanBeGroupedForPerson ) .Select ( a = > new { FirstName = a.FirstOrDefault ( ) .FirstName , LastName = a.FirstOrDefault ( ) .LastName , BirthDate = a.FirstOrDefault ( ) .BirthDate , FullnameOfOldes = a.Aggregate ( ( pers1 , pers2 ) = > pers1.BirthDate > pers2.BirthDate ? pers1 : pers2 ) .FirstName + `` `` //How do I get LastName of the old one ( without using the full aggregate again ) } ) ;",Linq Lambda get two properties as string from aggretation "C_sharp : A very simple sample application ( .NET 4.6.2 ) produces a StackOverflowException at a recursion depth of 12737 , which reduces to a recursion depth of 10243 , if the most inner function call throws an exception , which is expected and OK.If i use a Lazy < T > to shortly hold an intermediate result , the StackOverflowException already occurs at a recursion depth of 2207 , if no exception is thrown and at a recursion depth of 105 , if an exception is thrown.Note : The StackOverflowException at a depth of 105 is only observable if compiled to x64 . With x86 ( 32-Bit ) , the effect first occurs at a depth of 4272 . Mono ( like used at https : //repl.it ) works without problems up to a depth of 74200.The StackOverflowException does not occur within the deep recursion , but while ascending back to the main routine . The finally block is processed up some depth , then the program dies : or within the debugger : Who might be able to explain this ? Update : The problem can be reproduced without the usage of Lazy < T > , just by having a try-catch-throw block in the recursive method . Exception System.InvalidOperationException at 105Finally at 105 ... Exception System.InvalidOperationException at 55Finally at 55Exception System.InvalidOperationException at 54Finally at 54Process is terminated due to StackOverflowException . The program ' [ xxxxx ] Test.vshost.exe ' has exited with code -2147023895 ( 0x800703e9 ) . public class Program { private class Test { private int maxDepth ; private int CalculateWithLazy ( int depth ) { try { var lazy = new Lazy < int > ( ( ) = > this.Calculate ( depth ) ) ; return lazy.Value ; } catch ( Exception e ) { Console.WriteLine ( `` Exception `` + e.GetType ( ) + `` at `` + depth ) ; throw ; } finally { Console.WriteLine ( `` Finally at `` + depth ) ; } } private int Calculate ( int depth ) { if ( depth > = this.maxDepth ) throw new InvalidOperationException ( `` Max . recursion depth reached . `` ) ; return this.CalculateWithLazy ( depth + 1 ) ; } public void Run ( ) { for ( int i = 1 ; i < 100000 ; i++ ) { this.maxDepth = i ; try { Console.WriteLine ( `` MaxDepth : `` + i ) ; this.CalculateWithLazy ( 0 ) ; } catch { /* ignore */ } } } } public static void Main ( string [ ] args ) { var test = new Test ( ) ; test.Run ( ) ; Console.Read ( ) ; } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private int Calculate ( int depth ) { try { if ( depth > = this.maxDepth ) throw new InvalidOperationException ( `` Max . recursion depth reached . `` ) ; return this.Calculate2 ( depth + 1 ) ; } catch { throw ; } } [ MethodImpl ( MethodImplOptions.NoInlining ) ] private int Calculate2 ( int depth ) // just to prevent the compiler from tail-recursion-optimization { return this.Calculate ( depth ) ; } public void Run ( ) { for ( int i = 1 ; i < 100000 ; i++ ) { this.maxDepth = i ; try { Console.WriteLine ( `` MaxDepth : `` + i ) ; this.Calculate ( 0 ) ; } catch ( Exception e ) { Console.WriteLine ( `` Finished with `` + e.GetType ( ) ) ; } } }",StackOverflowException with Lazy < T > when throwing Exception "C_sharp : I have the following code : I was just wandering , considering the function within the lock accesses some global resources , ( an open socket among them ) whether all global resources within the object are also locked . ( I am aware that any other function that accesses these same variables must implement a lock on them also for the locking mechanism to be valid . I just have n't gotten round to locking them yet : ) ) locker = new object ( ) ; lock ( locker ) { for ( int i = 0 ; i < 3 ; i++ ) ver_store [ i ] = atomic_Poll ( power ) ; }",How deep does a lock go ? "C_sharp : According to MSDN , a reference to System.Threading.Timer should be kept otherwise it will get garbage-collected . So if I run this code , it does n't write any message ( which is the expected behavior ) : However , if I modify the code slightly by storing the timer in a temporary local variable , it survives and writes the message : During garbage collection , there is apparently no way how to access the timer from root or static objects . So can you please explain why the timer survives ? Where is the reference preserved ? static void Main ( string [ ] args ) { RunTimer ( ) ; GC.Collect ( ) ; Console.ReadKey ( ) ; } public static void RunTimer ( ) { new Timer ( s = > Console.WriteLine ( `` Hello '' ) , null , TimeSpan.FromSeconds ( 1 ) , TimeSpan.Zero ) ; } public static void RunTimer ( ) { var timer = new Timer ( s = > Console.WriteLine ( `` Hello '' ) ) ; timer.Change ( TimeSpan.FromSeconds ( 1 ) , TimeSpan.Zero ) ; }",C # Timers and Garbage Collection "C_sharp : I am using this queries below to validate a user.This query works perfectly fine in SQL Server and in my Asp.Net website.However when I put it in Asp.net/ C # code as : This does not match so not sure how to assign the password parameter so it works , just to confirm password entered is correct . And Password datatype in SQL Server table is VarBinary.Any suggestions ? SELECT * FROM AdminUsers WHERE username = 'admin ' COLLATE SQL_Latin1_General_CP1_CS_AS AND Password = ( SELECT HASHBYTES ( 'SHA1 ' , 'admin123 ' ) ) dbManager.Command.CommandText = @ '' SELECT * FROM AdminUsers WHERE username= @ UserName COLLATE SQL_Latin1_General_CP1_CS_AS ANDPassword = ( SELECT HASHBYTES ( 'SHA1 ' , @ Password ) ) '' ; dbManager.Command.Parameters.AddWithValue ( `` @ userName '' , username ) ; dbManager.Command.Parameters.AddWithValue ( `` @ Password '' , password ) ; reader = dbManager.GetDataReader ( ) ; if ( reader.Read ( ) == true ) { //USER VALIDATED }",SQL Server query not matching for a varbinary type column "C_sharp : I 'm currently developing a 2D game with C # /XNA . The game 's core feature are bullets with vastly different behaviors ( it will be kind of a bullet hell game ) .Updating all the bullets can take quite some time since they can be infinitely complex with their behaviors . And all of them have to do 1 collision check.Originally I just stored them in a List and updated and drew all of them , removing inactive bullets from the list each frame.This however quickly proved to slow the game down when there where 8k bullets on the screen , so I decided to implement multithreading and using LINQ to help performance.Thing is it 's still slowing down at around 16k bullets . I was told I could achieve up to 7 MILLION active bullets if I did it right , so I 'm not satisfied with 16k ... Is there anything else I could do to improve performance here ? Additional information before code : My bullets have fields for velocity , direction , angular velocity , acceleration , a speedlimit and a Behavior.The only special thing as mentioned is the behavior . It can modify any of the bullets fields at any time or spawn more bullets and even plant itself in them , therefore I 'm having a hard time applying a Data-Driven Solution and just storing all these fields in arrays instead of having a list of bullets . internal class BulletManager : GameComponent { public static float CurrentDrawDepth = .82f ; private readonly List < Bullet > _bullets = new List < Bullet > ( ) ; private readonly int _processorCount ; private int _counter ; private readonly Task [ ] _tasks ; public BulletManager ( Game game ) : base ( game ) { _processorCount = VariableProvider.ProcessorCount ; _tasks = new Task [ _processorCount ] ; } public void ClearAllBullets ( ) { _bullets.Clear ( ) ; } public void AddBullet ( Bullet bullet ) { _bullets.Add ( bullet ) ; } public override void Update ( GameTime gameTime ) { if ( StateManager.GameState ! = GameStates.Ingame & & ( StateManager.GameState ! = GameStates.Editor || EngineStates.GameStates ! = EEngineStates.Running ) ) return ; var bulletCount = _bullets.Count ; var bulletsToProcess = bulletCount / _processorCount ; //Split up the bullets to update among all available cores using Tasks and a lambda expression for ( var i = 0 ; i < _processorCount ; ++i ) { var x = i ; _tasks [ i ] = Task.Factory.StartNew ( ( ) = > { for ( var j = bulletsToProcess * x ; j < bulletsToProcess * x + bulletsToProcess ; ++j ) { if ( _bullets [ j ] .Active ) _bullets [ j ] .Update ( ) ; } } ) ; } //Update the remaining bullets ( if any ) for ( var i = bulletsToProcess * _processorCount ; i < bulletCount ; ++i ) { if ( _bullets [ i ] .Active ) _bullets [ i ] .Update ( ) ; } //Wait for all tasks to finish Task.WaitAll ( _tasks ) ; //This is an attempt to reduce the load per frame , originally _bullets.RemoveAll ( s = > ! s.Active ) ran every frame . ++_counter ; if ( _counter ! = 300 ) return ; _counter = 0 ; _bullets.RemoveAll ( s = > ! s.Active ) ; } public void Draw ( SpriteBatch spriteBatch ) { if ( StateManager.GameState ! = GameStates.Ingame & & StateManager.GameState ! = GameStates.Editor ) return ; spriteBatch.DrawString ( FontProvider.GetFont ( `` Mono14 '' ) , _bullets.Count.ToString ( ) , new Vector2 ( 100 , 20 ) , Color.White ) ; //Using some LINQ to only draw bullets in the viewport foreach ( var bullet in _bullets.Where ( bullet = > Camera.ViewPort.Contains ( bullet.CircleCollisionCenter.ToPoint ( ) ) ) ) { bullet.Draw ( spriteBatch ) ; CurrentDrawDepth -= .82e-5f ; } CurrentDrawDepth = .82f ; } }",What more can I do to improve performance on this class ? "C_sharp : I am having trouble creating indented items in a Razor MultiSelectBox.It works perfectly when I manually write the HTML : Razor 's HTML helpers , however , literally display the preceeding non-breaking space in the form . As expected , literal space ' ' characters for indentation are completely ignored.The code I am using to generate the multi-select box follows : < select name= '' testfoo123 '' multiple= '' multiple '' size= '' 15 '' > < option value= '' PARENT1 '' > Parent < /option > < option value= '' CHILD1 '' > & nbsp ; I am indented < /option > < option value= '' CHILD2 '' > & nbsp ; I am indented < /option > < option value= '' PARENT1 '' > Parent2 < /option > < option value= '' CHILD1 '' > & nbsp ; I am indented < /option > < option value= '' CHILD2 '' > & nbsp ; I am indented < /option > < /select > @ Html.ListBoxFor ( model = > mySelectedValues , new MultiSelectList ( myValues ) , new { size = `` 15 '' } )",How do I indent values in a MultiSelectBox ? "C_sharp : Suppose multiple threads execute periodically the DoWork ( ) method below . Suppose that at some point two threads begin the execution of this method almost simultaneously , so that one of the two local timestamp object is one tick larger than the other.If the thread A is characterized by a timestamp equal to t1 , while the thread B is characterized by a timestamp t2 equal to t1 + 1 tick , then the thread A will require first the access to the critical section.How does .NET manage the access to the critical section by multiple threads ? Does it put access requests in a queue , so that they are in chronological order ? In other words , is the access to the critical section guaranteed according to the order of thread access requests ? ICollection collection = // ... public void DoWork ( ) { DateTime timestamp = DateTime.Now ; lock ( collection.SyncRoot ) { // critical section } }",Which thread will be the first to enter the critical section ? "C_sharp : I have a TextBox that is eventually saved in a xml node . I am using the SecurityElement.Escape ( string2Escape ) to escape the invalid characters before saving the xml.Problem : I tried using the IsValidText to test if i need to run the escape method , but it returns `` ' and ' & ' as valid but then when you save the xml the system barfs because they are , in fact , not valid . It seems to only return false on ' < ' or ' > '.Simple solution , remove the check , but my question is why would this be the case ? The following is my failing code : private string EscapeXML ( string nodeText ) { if ( ! SecurityElement.IsValidText ( nodeText ) ) { return SecurityElement.Escape ( nodeText ) ; } return nodeText ; }",SecurityElement.IsValidText returns true on `` & '' ... why ? "C_sharp : I like to write enum or integer to pass option to my methods . Is there a pattern or a method in C # to check if an ( int 1,2,4,8 , ... ) option is true or false . I think it should easily be possible via binary functions.EDITAm I limited the number of options that I can create like this ? class Program { public enum Option { Option_A = 1 , Option_B = 2 , Option_C = 4 , Option_D = 8 , } static void Main ( string [ ] args ) { int activeOption = 5 ; // Means I activeted the Option_A and Option_C if ( IsOption ( activeOption , Option.Option_A ) ) { /*do work*/ } if ( IsOption ( activeOption , Option.Option_B ) ) { /*do work*/ } if ( IsOption ( activeOption , Option.Option_C ) ) { /*do work*/ } if ( IsOption ( activeOption , Option.Option_D ) ) { /*do work*/ } } private static bool IsOption ( int activeOption , Option option ) { /*Evaluate if IsOption is true or false*/ throw new NotImplementedException ( ) ; } }","Is there a pattern or a method in C # to check if an ( int 1,2,4,8 , ... ) option is true or false" C_sharp : I have this line of code which Resharper prompts me to change to Why ? Anyone enlighten me on what the benefits of changing are ? var count = materials.Where ( i = > i.MaterialType1 == MaterialType.Major ) .Count ( ) ; var count = materials.Count ( i = > i.MateriakType1 == MaterialType.Major ) ;,Best way to use Count ( ) in LINQ ? "C_sharp : What is the correct way to check a variable 's type in a Roslyn code analyzer ? I am registering for a ObjectCreationExpressionSyntax node and I can get the type , but I am not certain the correct way to check that it is a type I care about.I found a way to do it by checking the display string , but I am wondering if there is a more correct way to accomplish this . For example , here is code that is trying to check for an ArrayList creation . private static void SyntaxValidator ( SyntaxNodeAnalysisContext context ) { var creation = ( ObjectCreationExpressionSyntax ) context.Node ; var variableType = creation.Type as IdentifierNameSyntax ; if ( variableType == null ) return ; var variableTypeInfo = context.SemanticModel.GetTypeInfo ( context.Node ) ; if ( variableTypeInfo.Type ! = null & & variableTypeInfo.Type.ToDisplayString ( ) .Equals ( `` System.Collections.ArrayList '' ) ) { context.ReportDiagnostic ( Diagnostic.Create ( Rule , creations.GetLocation ( ) , `` '' ) ) ; } }",Checking a Variable Type For Code Analysis "C_sharp : I have created a type like this : Then lots of ilgenerating code follows for constructors , methods etc . When I start using the class I noticed something strange . I want to check whether the type 'myname ' that i created really implements the ImyInterface . I would expect that both of the following statements return true : So I have created a class that implements ImyInterface but which is not assignable to an object of type ImyInterface , what am I missing ? By the way , there are no generics involved and the Interface is just a basic one to test the concept : TypeBuilder tb = moduleBuilder.DefineType ( myname , TypeAttributes.Class | TypeAttributes.Public , typeof ( BaseClass ) , new Type [ ] { typeof ( ImyInterface ) } ) ; // t is Type 'myName'Type baseInterface = t.GetInterface ( typeof ( ImyInterface ) .name ) ; if ( baseType ! = null ) { // this is actually true , as I expected } if ( typeof ( ImyInterface ) .isAssignableFrom ( t ) ) { // the if clause is false , but I do n't have a clue why ? ? } public interface ITestInterface { int CalcSquaredInteger ( int number ) ; }",Why do IsAssignableFrom and GetInterface give different results "C_sharp : I have been reading Effective C # and a few other such books/blogs recently and when talking about the standard Dispose pattern ( which I 'm already using ) they all recommend using the class ' dispose variable ( as defined in that MSDN sample code ) at the beginning of every method . Essentially to insure that once Dispose has been called , any attempt to use the object would result in ObjectDisposedException . This makes sense , but is an enormous amount of manual labor in a large enough code base and relies on humans remembering to do it . So I am looking for a better way.I recently came across and started using the notifypropertyweaver that automatically fills out all the boilerplate code of calling the PropertyChanged handlers ( works as an msbuild task , thus requiring no additional shipping dependency ) . I wonder if anyone knows of a similar solution for the standard dispose pattern . What it would essentially do is accept a variable name as config ( the bool disposed in MSDN 's sample case ) , and add the following code to every method that is n't the Finalizer or named Dispose in every class that implements IDisposable : Does such a thing exist ? Alternatively what do people do to achieve this in their code , manually add the if-statement ? Clarification of PurposeThe greater need for this is not some `` best practice '' drive , but that we do have users managing the life-cycles of our objects improperly . Right now they just get a NullReference or some other such thing from underlying resource , which could mean we have a bug in our library , I want to communicate to them that they are the ones creating the issue and how they are crating it ( considering I 'm in position to know ) . So suggestions that the users of our Types are the ones who should be taking care of this , is n't really productive here . if ( disposed ) throw new ObjectDisposedException ( ) ;",Code weave helper for the standard Dispose pattern ? "C_sharp : Im trying to convert GregorianCalendar into persian calender this is my method : problem is , its not working for all dates like this : and it gives this error : but for other dates it works , like this one : public static DateTime GetFdate ( string _Edate ) { DateTime fdate = Convert.ToDateTime ( _Edate ) ; GregorianCalendar gcalendar = new GregorianCalendar ( ) ; PersianCalendar pcalendar = new PersianCalendar ( ) ; DateTime fDate = gcalendar.ToDateTime ( pcalendar.GetYear ( fdate ) , pcalendar.GetMonth ( fdate ) , pcalendar.GetDayOfMonth ( fdate ) , pcalendar.GetHour ( fdate ) , pcalendar.GetMinute ( fdate ) , pcalendar.GetSecond ( fdate ) , 0 ) ; return fDate ; } DateTime dt = GetFdate ( `` 2015-07-22 00:00:00.000 '' ) ; An unhandled exception of type 'System.ArgumentOutOfRangeException ' occurred in mscorlib.dllAdditional information : Year , Month , and Day parameters describe an un-representable DateTime . DateTime dt = GetFdate ( `` 2015-06-29 00:00:00.000 '' ) ;",C # calender conversion returns System.ArgumentOutOfRangeException "C_sharp : I have a method that needs to process an incoming sequence of commands and split the results into different buckets depending on some properties of the result . For example : The underlying model is perfectly capable of handling the entire sequence of PetRequest elements at once , and also the PetRequest is mostly generic information like an ID , so it makes no sense to try to split the requests at the input . But the provider does n't actually give back Cat and Dog instances , just a generic data structure : I 've named the response type PetData instead of Pet to clearly indicate that it is not a superclass of Cat or Dog - in other words , conversion to Cat or Dog is a mapping process . The other thing to keep in mind is that HandleAllRequests is expensive , e.g . a database query , so I really do n't want to repeat it , and I would prefer to avoid caching the results in memory using ToArray ( ) or the like , because there might be thousands or millions of results ( I have a lot of pets ) .So far I 've been able to throw together this clumsy hack : This technically works , in the sense that it does n't cause the PetData results to be enumerated twice , but it has two major problems : It looks like a giant pimple on the code ; it smacks of the awful imperative style we always used to have to employ in the pre-LINQ framework 2.0.It ends up being a thoroughly pointless exercise , because the GroupBy method is just caching all those results in memory , which means I 'm really no better off than if I 'd just been lazy and done a ToList ( ) in the first place and attached a few predicates.So to restate the question : Is it possible to split a single deferred IEnumerable < T > instance into two IEnumerable < ? > instances , without performing any eager evaluations , caching results in memory , or having to re-evaluate the original IEnumerable < T > a second time ? Basically , this would be the reverse of a Concat operation . The fact that there is n't already one in the .NET framework is a strong indication that this may not even be possible , but I thought it would n't hurt to ask anyway.P.S . Please do n't tell me to create a Pet superclass and just return an IEnumerable < Pet > . I used Cat and Dog as fun examples , but in reality the result types are more like Item and Error - they are both derived from the same generic data but otherwise have nothing in common at all . class Pets { public IEnumerable < Cat > Cats { get ; set ; } public IEnumerable < Dog > Dogs { get ; set ; } } Pets GetPets ( IEnumerable < PetRequest > requests ) { ... } class PetProvider { IEnumerable < PetData > GetPets ( IEnumerable < PetRequest > requests ) { return HandleAllRequests ( requests ) ; } } Pets GetPets ( IEnumerable < PetRequest > requests ) { var data = petProvider.GetPets ( requests ) ; var dataGroups = from d in data group d by d.Sound into g select new { Sound = g.Key , PetData = g } ; IEnumerable < Cat > cats = null ; IEnumerable < Dog > dogs = null ; foreach ( var g in dataGroups ) if ( g.Sound == `` Bark '' ) dogs = g.PetData.Select ( d = > ConvertDog ( d ) ) ; else if ( g.Sound == `` Meow '' ) cats = g.PetData.Select ( d = > ConvertCat ( d ) ) ; return new Pets { Cats = cats , Dogs = dogs } ; }",Splitting a deferred IEnumerable < T > into two sequences without re-evaluation ? "C_sharp : example to illustrate : Inside the static constructor , is there a syntax that can be used to distinguish between the local variable called `` number '' , and the static variable of the same name ? public class Something { private static int number ; static Something ( ) { int number = 10 ; // Syntax to distingish between local variable and static variable ? } }",how to distingish between local and static variables of same name C_sharp : Based on this solution i tried to call a JavaScript function located in my WebBrowser - control . The .xaml looks like thisBut neither this code Error Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : `` mshtml.HTMLDocumentClass ' does not contain a definition for 'myfunc '' nor this CodeError System.Runtime.InteropServices.COMException : 'Unknown name . ( Exception from HRESULT : 0x80020006 ( DISP_E_UNKNOWNNAME ) ) 'do work.What am I missing ? < Grid > < WebBrowser x : Name= '' browser '' / > < /Grid > public MainWindow ( ) { InitializeComponent ( ) ; browser.NavigateToString ( `` < html > < script > function callMe ( ) { alert ( 'Hello ' ) ; } document.myfunc = callMe ; < /script > < body > Hello World < /body > < /html > '' ) ; dynamic doc = browser.Document ; doc.myfunc ( ) ; } public MainWindow ( ) { InitializeComponent ( ) ; browser.NavigateToString ( `` < html > < script > function callMe ( ) { alert ( 'Hallo ' ) ; } < /script > < body > Hello World < /body > < /html > '' ) ; browser.InvokeScript ( `` callMe '' ) ; },Error when calling Javascript function located in WPF WebBrowser Control from C # code "C_sharp : Say I have a controller CatController with actions for GET , POST and PUT . They all use the same Cat resource which could look like this : However , the Name and IsFriendly properties should only be required when creating a new cat ( POST ) , but optional when updating it ( PUT ) to allow updating only a single property.The way I 've handled this until now is simply having two classes , a CreateCat and UpdateCat which have the same properties but different data annotations . However I do n't want to have to maintain two almost identical classes . I could of course validate the model manually in each action , but data annotations are very useful for things like global model validators and automatic generation of Swagger schemas.I 'm also using the Swagger schema to automatically generate SDK 's ( using ApiMatic ) , and that results in having two duplicate classes generated ( CreateCat and UpdateCat ) for what really should only be a single resource ( Cat ) .Is there an alternative way to achieve what I 'm trying to do with only a single class ? public class CatDto { public int Id { get ; set ; } [ Required ] public string Name { get ; set ; } [ Required ] public bool IsFriendly { get ; set ; } }",Different model requirements for POST and PUT "C_sharp : I have a string array with the following items : The alternating1 variable has nothing in it and I think I understand why . After the Skip then Take it returns 1 item in it so it then tries to Skip ( 1 ) and Take ( 1 ) but there is nothing there.Is there a way I can do this alternating pattern ? string s = `` M , k , m , S,3 , a,5 , E,2 , Q,7 , E,8 , J,4 , Y,1 , m,8 , N,3 , P,5 , H '' ; var items = s.split ( ' , ' ) ; var topThree = items.Take ( 3 ) ; var alternating1 = items.Skip ( 3 ) .Take ( 1 ) .Skip ( 1 ) .Take ( 1 ) .Skip ( 1 ) .Take ( 1 ) .Skip ( 1 ) .Take ( 1 ) ;",Using Skip and Take to pick up alternate items in an array "C_sharp : I was not lucky in my 15 minutes googling . Maybe bad luck with good keyword ? Why does the Resharper suggest spliting a string in function parameter ? Example : From this : To this : I checked documentation here : linkAnd it says : Split string literal - Splits string literal into two literals.I want to discover why is this a good practice , what are the fundamental idealogic behind the scenes that achieved this practice.I do n't want to do it without knowing why ... return PartialView ( `` Categorias '' , lista ) ; return PartialView ( `` Cat '' + `` egorias '' , lista ) ;",Resharper Split String literal "C_sharp : I have a TestFixture marked class which is Unit testing the functionality of a class named 'HideCurrentTitleBarMessageTask'.In this class I use a substitute to mock an interface in the [ Setup ] method , and in SOME tests in the test class I setup a return result from one of that mocked interfaces members.HideCurrentTitleBarMessageTask 's Execute function looks like thisNotice that only in Test_B , do I setup a return value with model.currentlyDisplayedMessage.If I breakpoint in line 1 of Test_A , I see in the debugger that model.currentlyDisplayedMessage is not null , but in fact assigned . When it should n't be . Even though presumably , the method SetUp was called prior , and the linewas executed , effectively reassigning a new mocked instance to the model.This causes Test_A to fail.Now , notice the commented out line in the SetUp method . Uncommenting this , fixes the issue by explicitly setting the reference in model to null . ( I 'm also assuming the same result could be achieved in a [ TearDown ] marked method ) .Does NUnit not wipe out the TestClass and start from scratch in between tests ? If not , can anybody tell me why my call toin the SetUp ( ) method has n't provided me with a clean mocked instance of the model , to start my test with ? [ TestFixture ] public class TestClass_A { private ITitleBarMessageModel model ; private ITitleBarMessage message ; private HideCurrentTitleBarMessageTask task ; private bool taskCompleteFired ; [ SetUp ] public void SetUp ( ) { taskCompleteFired = false ; model = Substitute.For < ITitleBarMessageModel > ( ) ; message = Substitute.For < ITitleBarMessage > ( ) ; //model.currentlyDisplayedMessage = null ; task = new HideCurrentTitleBarMessageTask ( ) ; task.Init ( model ) ; task.Completed += ( t ) = > { taskCompleteFired = true ; } ; } [ Test ] public void Test_A ( ) { task.Execute ( ) ; Assert.That ( taskCompleteFired , Is.True ) ; } [ Test ] public void Test_B ( ) { model.currentlyDisplayedMessage.Returns ( message ) ; task.Execute ( ) ; message.Received ( 1 ) .Hide ( ) ; Assert.That ( taskCompleteFired , Is.False ) ; } } public override void Execute ( ) { if ( model.currentlyDisplayedMessage ! = null ) { //Some irrelevant stuff } else { Completed ( this ) ; } } model = Substitute.For < ITitleBarMessageModel > ( ) ; //model.curentlyDisplayedMessage = null ; model = Substitute.For < ITitleBarMessageModel > ( ) ;",Does NUnit re-instantiate classes marked as TestFixtures between each test ? C_sharp : I have stumbled upon one issue with interpolated strings for a several times now.Consider the following case : A little surprising at first but once you realize how the curly brackets are paired it makes sense . Two following curly brackets are an escape sequence for a single curly in the interpolated string . So the opening bracket of the interpolated expression is paired with the last curly in the string.Now you could do the following to break the escape sequence : Notice the space character this approach adds to the output . ( Not ideal ) My question : Lets say I want to use a single interpolated string to get exactly the output `` { 123.45 } '' Is this at all possible without doing something hackish like the following ? double number = 123.4567 ; var str = $ '' { { { number : F2 } } } '' ; //I want to get `` { 123.45 } '' Console.WriteLine ( str ) ; // Will print `` { F2 } '' ___pair____ | | $ '' { { { number : F2 } } } '' ; var str = $ '' { { { number : F2 } } } '' ; // This will be `` { 123.45 } '' var s = $ '' { { { number : F2 } { ' } ' } '' ;,Interpolated string formatting issue "C_sharp : Consider this code.I know that the second foreach prints 768 3 times because of the closure variable captured by the lambda . why does it not happen in the first case ? How does foreach keyword different from the method Foreach ? Is it beacuse the expression is evaluated when i do values.ForEach var values = new List < int > { 123 , 432 , 768 } ; var funcs = new List < Func < int > > ( ) ; values.ForEach ( v= > funcs.Add ( ( ) = > v ) ) ; funcs.ForEach ( f= > Console.WriteLine ( f ( ) ) ) ; //prints 123,432,768 funcs.Clear ( ) ; foreach ( var v1 in values ) { funcs.Add ( ( ) = > v1 ) ; } foreach ( var func in funcs ) { Console.WriteLine ( func ( ) ) ; //prints 768,768,768 }",How do closures differ between foreach and list.ForEach ( ) ? "C_sharp : I have a standard ASP.NET Core 2 Web App acting as a REST/WebApi . For one of my endpoints I return an HTTP 400 when the user provides bad search/filter querystring arguments.Works great with POSTMAN . But when I try and test this with my SPA app ( which in effect is now crossing domains and thus doing a CORS request ) , I get a failure in Chrome.When doing a CORS request to an endpoint that returns an HTTP 200 response , all works fine.It looks like my error handling is NOT taking into consideration the CORS stuff ( i.e . not adding any CORS headers ) and is n't including that.I 'm guessing I 'm messing up the response payload pipeline stuff.Q : Is there a way to correct return any CORS header information in a custom Error Handling without hardcoding the header but instead using the headers stuff that was setup in the Configure/ConfigureServices methods in Startup.cs ? Pseduo code..Cheers ! public void ConfigureServices ( IServiceCollection services ) { ... snip ... services.AddMvcCore ( ) .AddAuthorization ( ) .AddFormatterMappings ( ) .AddJsonFormatters ( options = > { options.ContractResolver = new CamelCasePropertyNamesContractResolver ( ) ; options.Formatting = Formatting.Indented ; options.DateFormatHandling = DateFormatHandling.IsoDateFormat ; options.NullValueHandling = NullValueHandling.Ignore ; options.Converters.Add ( new StringEnumConverter ( ) ) ; } ) .AddCors ( ) ; // REF : https : //docs.microsoft.com/en-us/aspnet/core/security/cors # setting-up-cors ... snip ... } public void Configure ( IApplicationBuilder app , IHostingEnvironment env ) { ... snip ... app.UseExceptionHandler ( options = > options.Run ( async httpContext = > await ExceptionResponseAsync ( httpContext , true ) ) ) ; app.UseCors ( builder = > builder//.WithOrigins ( `` http : //localhost:52383 '' , `` http : //localhost:49497 '' ) .AllowAnyOrigin ( ) .AllowAnyHeader ( ) .AllowAnyMethod ( ) ) ; ... snip ... } private static async Task ExceptionResponseAsync ( HttpContext httpContext , bool isDevelopmentEnvironment ) { var exceptionFeature = httpContext.Features.Get < IExceptionHandlerPathFeature > ( ) ; if ( exceptionFeature == null ) { // An unknow and unhandled exception occured . So this is like a fallback . exceptionFeature = new ExceptionHandlerFeature { Error = new Exception ( `` An unhandled and unexpected error has occured . Ro-roh : ~ ( . '' ) } ; } await ConvertExceptionToJsonResponseAsyn ( exceptionFeature , httpContext.Response , isDevelopmentEnvironment ) ; } private static Task ConvertExceptionToJsonResponseAsyn ( IExceptionHandlerPathFeature exceptionFeature , HttpResponse response , bool isDevelopmentEnvironment ) { if ( exceptionFeature == null ) { throw new ArgumentNullException ( nameof ( exceptionFeature ) ) ; } if ( response == null ) { throw new ArgumentNullException ( nameof ( response ) ) ; } var exception = exceptionFeature.Error ; var includeStackTrace = false ; var statusCode = HttpStatusCode.InternalServerError ; var error = new ApiError ( ) ; if ( exception is ValidationException ) { statusCode = HttpStatusCode.BadRequest ; foreach ( var validationError in ( ( ValidationException ) exception ) .Errors ) { error.AddError ( validationError.PropertyName , validationError.ErrorMessage ) ; } } else { // Final fallback . includeStackTrace = true ; error.AddError ( exception.Message ) ; } if ( includeStackTrace & & isDevelopmentEnvironment ) { error.StackTrace = exception.StackTrace ; } var json = JsonConvert.SerializeObject ( error , JsonSerializerSettings ) ; response.StatusCode = ( int ) statusCode ; response.ContentType = JsonContentType ; // response.Headers.Add ( `` Access-Control-Allow-Origin '' , `` * '' ) ; < -- Do n't want to hard code this . return response.WriteAsync ( json ) ; }",How to send an HTTP 4xx-5xx response with CORS headers in an ASPNET.Core web app ? "C_sharp : It 's .NET 3.5 SP1Can anyone can tell me why this test fails ? Edit : Thanks stusmith You have a reference to a string , which since it is a constant , is probably interned ( ie not dynamically allocated ) , and will never be collected.That was it . Changed first line to and the test passes : - ) [ TestMethod ] public void Memory ( ) { var wr = new WeakReference ( `` aaabbb '' ) ; Assert.IsTrue ( wr.IsAlive ) ; GC.Collect ( ) ; GC.Collect ( ) ; GC.Collect ( ) ; GC.Collect ( ) ; GC.Collect ( ) ; Assert.IsFalse ( wr.IsAlive ) ; // < -- fails here } var wr = new WeakReference ( new object ( ) ) ;",WeakReference Bug ? "C_sharp : The immediate problemCame across this problem when working with a different library that uses Json.NET . We 've been making heavy use of TypeNameHandling.Arrays when serializing C # objects into JSON , as well as deserializing them on the other end of the wire in our client app.However , it seems that Json.NET 's XmlNodeConverter does not play nice with this setting , throwing errors when deserializing JSON such as : The causeException is thrown because Json.NET tries to interpret $ values as a string attribute and not as child nodes . We get a null reference exception when .ToString ( ) is called on a null value around XmlNodeConverter.cs:1367.ElaborationThe real issue here might stem in the way Json.NET handles arrays in XML : it does not produce a wrapper such as the one below : ... where it would be able to add the custom json : type attribute , but instead relies on implicitly grouping elements sharing the same tag : This behaviour seems a little unintuitive to my untrained eye - I 'd expect to have a parent element included in the XML rather than silently dropped . ( This is likely also the reason why empty and one-element arrays need extra work as docuemented in many threads here and Json.NET forums. ) Solutions.. ? Here I turn to the community.. ! Do you know of any workarounds , perhaps some setting that makes the two play nicely ? Is it the consensus that dropping the parent node is the right way to go about serializing arrays ? { 'people ' : { ' $ type ' : 'System.Collections.Generic.List ` 1 [ [ MyNamespace.Person , MyDll ] ] , mscorlib ' , ' $ values ' : [ { 'name ' : 'Alan ' } , { 'name ' : 'Bob ' } ] } } < people json : type= '' System.Collections.Generic.List ` 1 [ [ MyNamespace.Person , MyDll ] ] , mscorlib '' > < person > < name > Alan < /name > < /person > < person > < name > Bob < /name > < /person > < /people > < person > < name > Alan < /name > < /item > < person > < name > Bob < /name > < /item >",Json.NET XML conversion and TypeNameHandling.Arrays "C_sharp : I tried writing a culture-aware string replacement method : However , it chokes on Unicode combining characters : To fix my code , I need to know that in the second example , String.IndexOf matched only one character ( é ) even though it searched for two ( e\u0301 ) . Similarly , I need to know that in the third example , String.IndexOf matched two characters ( e\u0301 ) even though it only searched for one ( é ) .How can I determine the actual length of the substring matched by String.IndexOf ? NOTE : Performing Unicode normalization on text and oldValue ( as suggested by James Keesey ) would accommodate combining characters , but ligatures would still be a problem : public static string Replace ( string text , string oldValue , string newValue ) { int index = text.IndexOf ( oldValue , StringComparison.CurrentCulture ) ; return index > = 0 ? text.Substring ( 0 , index ) + newValue + text.Substring ( index + oldValue.Length ) : text ; } // \u0301 is Combining Acute AccentConsole.WriteLine ( Replace ( `` déf '' , `` é '' , `` o '' ) ) ; // 1 . CORRECT : dofConsole.WriteLine ( Replace ( `` déf '' , `` e\u0301 '' , `` o '' ) ) ; // 2 . INCORRECT : doConsole.WriteLine ( Replace ( `` de\u0301f '' , `` é '' , `` o '' ) ) ; // 3 . INCORRECT : dóf Console.WriteLine ( Replace ( `` œf '' , `` œ '' , `` i '' ) ) ; // 4 . CORRECT : ifConsole.WriteLine ( Replace ( `` œf '' , `` oe '' , `` i '' ) ) ; // 5 . INCORRECT : iConsole.WriteLine ( Replace ( `` oef '' , `` œ '' , `` i '' ) ) ; // 6 . INCORRECT : ief",Length of substring matched by culture-sensitive String.IndexOf method "C_sharp : My question is , in the below code , can I be sure that the instance methods will be accessing the variables I think they will , or can they be changed by another thread while I 'm still working ? Do closures have anything to do with this , i.e . will I be working on a local copy of the IEnumerable < T > so enumeration is safe ? To paraphrase my question , do I need any locks if I 'm never writing to shared variables ? public class CustomerClass { private Config cfg = ( Config ) ConfigurationManager.GetSection ( `` Customer '' ) ; public void Run ( ) { var serviceGroups = this.cfg.ServiceDeskGroups.Select ( n = > n.Group ) .ToList ( ) ; var groupedData = DataReader.GetSourceData ( ) .AsEnumerable ( ) .GroupBy ( n = > n.Field < int > ( `` ID '' ) ) ; Parallel.ForEach < IGrouping < int , DataRow > , CustomerDataContext > ( groupedData , ( ) = > new CustomerDataContext ( ) , ( g , _ , ctx ) = > { var inter = this.FindOrCreateInteraction ( ctx , g.Key ) ; inter.ID = g.Key ; inter.Title = g.First ( ) .Field < string > ( `` Title '' ) ; this.CalculateSomeProperty ( ref inter , serviceGroups ) ; return ctx ; } , ctx = > ctx.SubmitAllChanges ( ) ) ; } private Interaction FindOrCreateInteraction ( CustomerDataContext ctx , int ID ) { var inter = ctx.Interactions.Where ( n = > n.Id = ID ) .SingleOrDefault ( ) ; if ( inter == null ) { inter = new Interaction ( ) ; ctx.InsertOnSubmit ( inter ) ; } return inter ; } private void CalculateSomeProperty ( ref Interaction inter , IEnumerable < string > serviceDeskGroups ) { // Reads from the List < T > class instance variable . Changes the state of the ref 'd object . if ( serviceGroups.Contains ( inter.Group ) ) { inter.Ours = true ; } } }","Multithreading , lambdas and local variables" "C_sharp : I 'm using MiniProfiler to profile my sql commands.One issue I 'm dealing with now is repeated INSERT statements generated by linq.I 've converted them into a SqlBulkCopy command , however now it does n't appear to record it in the sql view in MiniProfiler.Would there even be an associated command string for a SqlBulkCopy ? Is it possible to get the bulk copy to appear in the list of sql commands ? Can I at least make it counted in the % sql bit ? I 'm aware I could use MiniProfiler.Current.Step ( `` Doing Bulk Copy '' ) but that would n't count as SQL , and would n't show in the listing with any detail.Current code below : public static void BulkInsertAll < T > ( this DataContext dc , IEnumerable < T > entities ) { var conn = ( dc.Connection as ProfiledDbConnection ) .InnerConnection as SqlConnection ; conn.Open ( ) ; Type t = typeof ( T ) ; var tableAttribute = ( TableAttribute ) t.GetCustomAttributes ( typeof ( TableAttribute ) , false ) .Single ( ) ; var bulkCopy = new SqlBulkCopy ( conn ) { DestinationTableName = tableAttribute.Name } ; // ... . bulkCopy.WriteToServer ( table ) ; }",Getting SqlBulkCopy to show up as sql in MiniProfiler "C_sharp : I 'm trying to start a few applications for the current user only when Windows starts up.I can accomplish this with the following : But I 'm trying to run this as part of a Visual Studio Installer Project . I 've added my custom action , the program starts like it should , and the installer works great in XP.In Windows 7 , the installer gets elevated privileges , and does everything but insert the entries into the registry for the current user . How ever , it does insert the registry entries when ran as a standalone application ( outside of the installer project ) and it does not get elevated privileges.The only thing I can figure is that with the elevated privileges , it 's trying to insert the entries into the Administrators account instead of the current user ? or is there something else I 'm missing ? and is there another way I can achieve my goal here ? RegistryKey oKey = Registry.CurrentUser.OpenSubKey ( `` Software '' , true ) ; oKey = oKey.OpenSubKey ( `` Microsoft '' , true ) ; oKey = oKey.OpenSubKey ( `` Windows '' , true ) ; oKey = oKey.OpenSubKey ( `` CurrentVersion '' , true ) ; oKey = oKey.OpenSubKey ( `` Run '' , true ) ; oKey.SetValue ( `` Application 1 '' , `` C : \\path\\to\\ap1.exe '' ) ; oKey.SetValue ( `` Application 2 '' , `` C : \\path\\to\\ap2.exe '' ) ;",Run C # Application on Windows Start up "C_sharp : I have written a website that utilizes a SHA-256 hash to validate a user 's password . This is a relatively unsecure setup to start with , as most users will have the same username/password . To try and protect it at least a little bit , I do the following : The client requests a new salt from the serverThe client hashes the password with this saltThe client sends the hashed password with the salt back to the serverThe server hashes the actual password and compares the twoHere is my code : C # JavascriptThis code works fine on Google Chrome , but not on Internet Explorer 11 . The problem ( as seen in the debugger ) is that the hash generated by the javascript is different than that generated by C # .I suspect this has something to do with character encoding , but have n't found much on the web to prove/disprove this theory ( or help with the problem in general ) . If there is a better way to accomplish this problem , I 'm happy to hear about it but would like understanding as to the cause of the original error as well.Why are the hashes different , and what can I do to fix it ? //Just for testing ! private static Dictionary < string , string > users = new Dictionary < string , string > ( ) { { `` User '' , `` Password '' } } ; [ HttpGet ] public HttpResponseMessage GetSalt ( ) { RNGCryptoServiceProvider secureRNG = new RNGCryptoServiceProvider ( ) ; byte [ ] saltData = new byte [ 64 ] ; secureRNG.GetBytes ( saltData ) ; HttpResponseMessage response = new HttpResponseMessage ( ) ; response.Content = new StringContent ( System.Text.Encoding.Unicode.GetString ( saltData ) , System.Text.Encoding.Unicode ) ; return response ; } [ HttpGet ] public bool ValidateUser ( string userName , string hashedPassword , string salt ) { SHA256Managed hash = new SHA256Managed ( ) ; if ( users.ContainsKey ( userName ) ) { string fullPassword = salt + users [ userName ] ; byte [ ] correctHash = hash.ComputeHash ( System.Text.Encoding.UTF8.GetBytes ( fullPassword ) ) ; if ( hashedPassword.ToUpper ( ) == BitConverter.ToString ( correctHash ) .Replace ( `` - '' , '' '' ) ) { return true ; } } return false ; } $ scope.login = function ( ) { $ http.get ( 'api/Login ' ) .success ( function ( salt ) { //Hash the password with the salt and validate var hashedPassword = sjcl.hash.sha256.hash ( salt.toString ( ) .concat ( $ scope.password ) ) ; var hashString = sjcl.codec.hex.fromBits ( hashedPassword ) ; $ http.get ( 'api/Login ? userName= ' + $ scope.userName + ' & hashedPassword= ' + hashString + ' & salt= ' + salt ) .success ( function ( validated ) { $ scope.loggedIn = validated ; } ) ; } ) ;",Chrome and IE return different SHA hashes "C_sharp : The code below is designed to take a string in and remove any of a set of arbitrary words that are considered non-essential to a search phrase.I did n't write the code , but need to incorporate it into something else . It works , and that 's good , but it just feels wrong to me . However , I ca n't seem to get my head outside the box that this method has created to think of another approach.Maybe I 'm just making it more complicated than it needs to be , but I feel like this might be cleaner with a different technique , perhaps by using LINQ.I would welcome any suggestions ; including the suggestion that I 'm over thinking it and that the existing code is perfectly clear , concise and performant.So , here 's the code : Thanks in advance for your help.Cheers , Steve private string RemoveNonEssentialWords ( string phrase ) { //This array is being created manually for demo purposes . In production code it 's passed in from elsewhere . string [ ] nonessentials = { `` left '' , `` right '' , `` acute '' , `` chronic '' , `` excessive '' , `` extensive '' , `` upper '' , `` lower '' , `` complete '' , `` partial '' , `` subacute '' , `` severe '' , `` moderate '' , `` total '' , `` small '' , `` large '' , `` minor '' , `` multiple '' , `` early '' , `` major '' , `` bilateral '' , `` progressive '' } ; int index = -1 ; for ( int i = 0 ; i < nonessentials.Length ; i++ ) { index = phrase.ToLower ( ) .IndexOf ( nonessentials [ i ] ) ; while ( index > = 0 ) { phrase = phrase.Remove ( index , nonessentials [ i ] .Length ) ; phrase = phrase.Trim ( ) .Replace ( `` `` , `` `` ) ; index = phrase.IndexOf ( nonessentials [ i ] ) ; } } return phrase ; }",.NET String parsing performance improvement - Possible Code Smell "C_sharp : I am setting NullDisplayText in the DisplayFormat from resource through the following codeMy default culture used is `` en-US '' , Once I change the culture to es-AR and load the pages its working fine , but when I change the culture back to en-US fields are not getting converted back . I change the culture throught the following wayI use DisplayFormat attribute in ViewModel as public class LocalizedDisplayFormatAttribute : DisplayFormatAttribute { private readonly PropertyInfo _propertyInfo ; public LocalizedDisplayFormatAttribute ( string resourceKey , Type resourceType ) : base ( ) { this._propertyInfo = resourceType.GetProperty ( resourceKey , BindingFlags.Static | BindingFlags.Public ) ; if ( this._propertyInfo == null ) { return ; } base.NullDisplayText = ( string ) this._propertyInfo.GetValue ( this._propertyInfo.DeclaringType , null ) ; } public new string NullDisplayText { get { return base.NullDisplayText ; } set { base.NullDisplayText = value ; } } } protected void Application_AcquireRequestState ( object sender , EventArgs e ) { try { HttpCookie cookie = HttpContext.Current.Request.Cookies.Get ( `` CurrentCulture '' ) ; string culutureCode = cookie ! = null & & ! string.IsNullOrEmpty ( cookie.Value ) ? cookie.Value : `` en '' ; CultureInfo ci = new CultureInfo ( culutureCode ) ; System.Threading.Thread.CurrentThread.CurrentUICulture = ci ; System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture ( ci.Name ) ; } catch { } } public class AlarmCodeDetailsViewModel { /// < summary > /// Gets or sets the alarm code ID /// < /summary > public int AlarmCodeID { get ; set ; } /// < summary > /// Gets or sets the alarm code /// < /summary > [ LocalizedDisplayName ( `` Label_AlarmCode '' ) ] [ LocalizedDisplayFormatAttribute ( `` Warning_NullDisplayText '' , typeof ( Properties.Resources ) , HtmlEncode = false ) ] public string Code { get ; set ; } /// < summary > /// Gets or sets the Description /// < /summary > [ LocalizedDisplayName ( `` Label_Description '' ) ] [ LocalizedDisplayFormatAttribute ( `` Warning_NullDisplayText '' , typeof ( Properties.Resources ) , HtmlEncode = false ) ] public string Description { get ; set ; } /// < summary > /// Gets or sets the Notes /// < /summary > [ LocalizedDisplayName ( `` Label_Notes '' ) ] [ LocalizedDisplayFormatAttribute ( `` Warning_NullDisplayText '' , typeof ( Properties.Resources ) , HtmlEncode = false ) ] public string Notes { get ; set ; } }",Customized DisplayFormatAttribute only setting once "C_sharp : I 'm working on a Geometry library . There are 200+ unit tests.There 's a particularly stubborn test that fails whenever I select `` Run All '' , but the test passes when I run that test individually , or use the debugger on it . I do believe the issue showed up about when I shifted over from visual studio '13 to the '15 edition.Now some notes about the geometry library : The objects are immutable.The tests have no shared objects between them.So my Question : What are the possible causes for this odd behavior ? Edit : [ Test ( ) ] public void Plane_IntersectionWithPlane_IdenticalPlane ( ) { Plane testPlane = new Plane ( new Direction ( Point.MakePointWithInches ( 2 , -1 , 1 ) ) , Point.MakePointWithInches ( 2 , 1 , 2 ) ) ; Line found = ( testPlane.Intersection ( testPlane ) ) ; Line expected = new Line ( new Direction ( Point.MakePointWithInches ( 0 , -1 , -1 ) ) , Point.MakePointWithInches ( 2 , 1 , 2 ) ) ; Assert.IsTrue ( found.Equals ( expected ) ) ; }",NUnit Test Debugging "C_sharp : I use windbg , to debug a simple c # application , which consits just of empty form like this : I compile , run this app , attach to it with windbg , then run in windbg : And thein i load SOS extension and verify that its loaded : Then i set the debugging symbols path to the folder where .pdb located , and sources folder.But when i open the source file and set the breakpoint on a source line , and then continue the process i get error in windbg : I expected it would break , and show me the .net assembler instructions , but it fails all the time . How do you breakpoint the .net application using windbg then ? using System ; using System.Collections.Generic ; using System.ComponentModel ; using System.Data ; using System.Drawing ; using System.Text ; using System.Windows.Forms ; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1 ( ) { InitializeComponent ( ) ; } private void Form1_Load ( object sender , EventArgs e ) { } } } 0:009 > .cordll -ve -u -lAutomatically loaded SOS ExtensionCLRDLL : Loaded DLL C : \Windows\Microsoft.NET\Framework64\v2.0.50727\mscordacwks.dllCLR DLL status : Loaded DLL C : \Windows\Microsoft.NET\Framework64\v2.0.50727\mscordacwks.dll 0:009 > .loadby sos mscorwks0:009 > .chainExtension DLL search Path : C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\WINXP ; C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\winext ; C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\winext\arcade ; C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\pri ; C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64 ; C : \Users\username\AppData\Local\Dbg\EngineExtensions ; C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64 ; C : \WINDOWS\system32 ; C : \WINDOWS ; C : \WINDOWS\System32\Wbem ; C : \WINDOWS\System32\WindowsPowerShell\v1.0\ ; C : \Program Files\PuTTY\ ; C : \Program Files ( x86 ) \Bitvise SSH Client ; C : \Program Files\nodejs\ ; C : \Program Files\Microsoft SQL Server\130\Tools\Binn\ ; C : \Program Files\Git\cmd ; C : \Users\username\AppData\Local\Android\sdk\platform-tools ; C : \Program Files ( x86 ) \Nox\bin\ ; C : \Users\username\AppData\Local\Microsoft\WindowsApps ; C : \Users\username\AppData\Roaming\npm ; C : \Program Files ( x86 ) \Nmap ; C : \Program Files ( x86 ) \mitmproxy\binExtension DLL chain : C : \Windows\Microsoft.NET\Framework64\v2.0.50727\sos : image 2.0.50727.8794 , API 1.0.0 , built Tue Jun 20 23:15:41 2017 [ path : C : \Windows\Microsoft.NET\Framework64\v2.0.50727\SOS.dll ] C : \Windows\Microsoft.NET\Framework64\v2.0.50727\SOS.dll : image 2.0.50727.8794 , API 1.0.0 , built Tue Jun 20 23:15:41 2017 [ path : C : \Windows\Microsoft.NET\Framework64\v2.0.50727\SOS.dll ] dbghelp : image 10.0.15063.468 , API 10.0.6 , built Thu Jan 1 03:00:00 1970 [ path : C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\dbghelp.dll ] ext : image 10.0.15063.468 , API 1.0.0 , built Thu Jan 1 03:00:00 1970 [ path : C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\winext\ext.dll ] exts : image 10.0.15063.468 , API 1.0.0 , built Thu Jan 1 03:00:00 1970 [ path : C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\WINXP\exts.dll ] uext : image 10.0.15063.468 , API 1.0.0 , built Thu Jan 1 03:00:00 1970 [ path : C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\winext\uext.dll ] ntsdexts : image 10.0.15063.468 , API 1.0.0 , built Thu Jan 1 03:00:00 1970 [ path : C : \Program Files ( x86 ) \Windows Kits\10\Debuggers\x64\WINXP\ntsdexts.dll ] 0:009 > gUnable to insert breakpoint 3 at 00000000 ` 008f001a , Win32 error 0n998 `` Invalid access to memory . `` bp3 at 00000000 ` 008f001a failedWaitForEvent failed","Debugging .net application with windbg , can not insert breakpoints" "C_sharp : I have a WinForms application that was written in C # .NET 3.5 . This application interacts with a SQL Server 2008 . Whenever I add a record into the database , I have a DateAdd column that I insert DateTime.Now into . For whatever reason , I have 4 records with odd dates : The records before and after these all have proper dates of '2011-05-29 XX : XX : XX.XXX ' . Users have no access to modify the date fields in any application . Is there any reason that the dates would change like this ? Users have no access to modify their system time , which I 'm assuming is where DateTime.Now gathers the date from . Basically , I 've come to the conclusion that there is either a bug , or a user has a Delorean fully equipped with a flux capacitor ... '1980-01-03 23:08:43.970 ' '1980-01-03 23:08:44.157 ' '1980-01-03 23:08:44.530 ' '1980-01-03 23:08:45.547 '",DateTime.Now Returned Weird Date "C_sharp : I have repeatedly test this # blankety-blank # stored procedure on SQL Server , and it returns either 0 or number of rows , but in C # I am always getting -1 . I have been debugging this # blank # thing for hours and always -1 . Here 's the stored procedure code . And here 's a C # code Can anyone have a look at this problem please ? I used try and catch block as well , it 's absolutely useless in this case . Thanks . Create procedure [ dbo ] . [ sp_enter_new_student ] @ Prenom_detudiant [ varchar ] ( 50 ) = NULL , @ nom_detudiant [ varchar ] ( 50 ) = NULL , @ nationalite_detudiant [ varchar ] ( 40 ) = NULL , @ langue_parle [ varchar ] ( 15 ) = NULL , @ nombre_denfants [ int ] = NULL , @ sexe_detudiant [ char ] ( 1 ) = NULL , @ program_pk [ int ] = NULL , @ Numero_detudiant int = NULLAs Declare @ numOfRowsBefore int = 0 ; declare @ numOfRowsAfter int = 0 ; declare @ Error int = -100 ; BEGIN SET NOCOUNT ON ; select @ numOfRowsBefore = COUNT ( * ) from tbl_students where Numero_detudiant = @ Numero_detudiant ; if ( @ numOfRowsBefore > 0 ) begin Print `` Student already exists , Insertion will fail ! `` ; Print `` Insertion Failure ! `` + CONVERT ( varchar ( 10 ) , @ numOfRowsBefore ) ; return @ numOfRowsBefore ; -- > -1 indicates insertion failure End else if ( @ numOfRowsBefore = 0 ) begin Print `` Student does n't exists , Insertion will be Success ! `` ; Print `` Insertion Success ! `` + CONVERT ( varchar ( 10 ) , @ numOfRowsBefore ) ; return @ numOfRowsBefore ; -- > -1 indicates insertion failure EndEND public int enregistreNouveauEtudiant ( string Prenom_detudiant , string nom_detudiant , string nationalite_detudiant , string langue_parle , string nombre_denfants , string sexe_detudiant , string program_pk , string Numero_detudiant ) { int numberOfRowsInserted = 0 ; //try // { SqlConnection connection = this.GetConnection ( ) ; SqlCommand insertStudentCommand = new SqlCommand ( `` sp_enter_new_student '' , connection ) ; connection.Open ( ) ; insertStudentCommand.CommandType = CommandType.StoredProcedure ; //insertStudentCommand.Parameters.Add ( `` @ ID '' , SqlDbType.Int ) ; //insertStudentCommand.Parameters [ `` @ ID '' ] .Direction = ParameterDirection.Output ; insertStudentCommand.Parameters.Add ( `` @ Prenom_detudiant '' , SqlDbType.VarChar , 50 ) .Value = Prenom_detudiant ; insertStudentCommand.Parameters.Add ( `` @ nom_detudiant '' , SqlDbType.VarChar , 50 ) .Value = nom_detudiant ; insertStudentCommand.Parameters.Add ( `` @ nationalite_detudiant '' , SqlDbType.VarChar , 40 ) .Value = nationalite_detudiant ; insertStudentCommand.Parameters.Add ( `` @ langue_parle '' , SqlDbType.VarChar , 15 ) .Value = langue_parle ; insertStudentCommand.Parameters.Add ( `` @ nombre_denfants '' , SqlDbType.Int ) .Value = nombre_denfants ; insertStudentCommand.Parameters.Add ( `` @ sexe_detudiant '' , SqlDbType.Char , 1 ) .Value = sexe_detudiant ; insertStudentCommand.Parameters.Add ( `` @ program_pk '' , SqlDbType.Int ) .Value = program_pk ; insertStudentCommand.Parameters.Add ( `` @ Numero_detudiant '' , SqlDbType.Int ) .Value = Numero_detudiant ; numberOfRowsInserted = insertStudentCommand.ExecuteNonQuery ( ) ; connection.Close ( ) ; return numberOfRowsInserted ; }",C # stored procedure returning -1 Repeatedly "C_sharp : I 've got a Problem with the automatisation of WebBrowsing in an C # -Program.I 've used the code before for a BHO and there it was working . But within a pure c # Program there seems to be some kind of deadlock . I 've instructed my program to click on a search button and then wait ( via a manualresetevent ) for documentcomplete to signal . But now it seems that the click on the search button is n't processed until the ManualResetEvent signals a timeout . Thereafter the click is made and also the DocumentComplete-Event is fired.For the structure of that programm : The WebBrowser-Control is part of a WindowsForm . The WebBrowser Control is passed to a Class which runs a Thread . This Class again passed the control to another class where the concrete behaviour according to the loaded webbrowser is programmed.So in Code this lookes this way : Setup of the threadProcessing of withingthe Runner-MethodThe PlaceTipp-MethodThe SearchTipp-Method where the Deadlock is happening : Has anybody an Idea what 's happens here ? Thankslichtbringer _runner = new Thread ( runner ) ; _runner.SetApartmentState ( ApartmentState.STA ) ; _runner.IsBackground = true ; _runner.Start ( ) ; b.placeTipp ( workStructure ) ; public void placeTipp ( ref OverallTippStructure tipp ) { _expectedUrl = String.Empty ; _betUrl = String.Empty ; _status = BookieStatusType.CHECKLOGIN ; while ( true ) { _mreWaitForAction.Reset ( ) ; checkIETab ( ) ; switch ( _status ) { case BookieStatusType.REQUESTWEBSITE : ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Keine IE-Tab vorhanden . Fordere eine an '' , this.BookieName ) ) ; //if ( RequestIETabEvent ! = null ) // RequestIETabEvent ( this , new EventArgs ( ) ) ; _status = BookieStatusType.NAVIGATETOWEBSITE ; _mreWaitForAction.Set ( ) ; break ; case BookieStatusType.NAVIGATETOWEBSITE : _webBrowser.Navigate ( @ '' http : //www.nordicbet.com '' ) ; break ; case BookieStatusType.CHECKLOGIN : checkLogin ( ) ; break ; case BookieStatusType.LOGINNEEDED : doLogin ( ) ; break ; case BookieStatusType.LOGGEDIN : _status = BookieStatusType.SEARCHTIPP ; _mreWaitForAction.Set ( ) ; break ; case BookieStatusType.SEARCHTIPP : searchTipp ( tipp ) ; break ; case BookieStatusType.NAVTOSB : NavToSB ( ) ; break ; case BookieStatusType.GETMARKET : getMarket ( tipp ) ; break ; case BookieStatusType.PLACEBET : placeBet ( tipp ) ; break ; case BookieStatusType.CONFIRMBET : confirmBet ( ) ; break ; case BookieStatusType.EXTRACTBETDATA : extractBetId ( ref tipp ) ; break ; case BookieStatusType.FINISHED : return ; } if ( ! _mreWaitForAction.WaitOne ( 60000 ) ) { //Sonderüberpüfung be LoginNeeded if ( _status == BookieStatusType.LOGINNEEDED ) { //checkLogin ( ) ; throw new BookieLoginFailedExcpetion ( ) ; } //TIMEOUT ! ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Timeout bei warten auf nächsten Schritt . Status war { 1 } '' , this.BookieName , this._status.ToString ( ) ) ) ; throw new BookieTimeoutExcpetion ( String.Format ( `` Bookie { 0 } : Timeout bei dem Warten auf Ereignis '' , this.BookieName ) ) ; } } } private void searchTipp ( OverallTippStructure tipp ) { if ( _webBrowser.InvokeRequired ) { _webBrowser.Invoke ( new delegatePlaceBet ( searchTipp ) , new object [ ] { tipp } ) ; } else { ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Suche Tipp { 1 } '' , this.BookieName , tipp.BookieMatchName ) ) ; _expectedUrl = String.Empty ; if ( ! _webBrowser.Url.ToString ( ) .StartsWith ( `` https : //www.nordicbet.com/eng/sportsbook '' ) ) { ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Nicht auf Sportsbookseite . Navigiere '' , this.BookieName ) ) ; _status = BookieStatusType.NAVTOSB ; _mreWaitForAction.Set ( ) ; return ; } _searchCompleted = false ; HtmlDocument doc = _webBrowser.Document ; if ( doc ! = null ) { mshtml.IHTMLInputElement elemSearch = ( mshtml.IHTMLInputElement ) doc.GetElementById ( `` query '' ) .DomElement ; if ( elemSearch ! = null ) { Thread.Sleep ( Delayer.delay ( 2000 , 10000 ) ) ; elemSearch.value = tipp.BookieMatchName ; mshtml.IHTMLElement elemSearchButton = ( mshtml.IHTMLElement ) doc.GetElementById ( `` search_button '' ) .DomElement ; if ( elemSearchButton ! = null ) { Thread.Sleep ( Delayer.delay ( 900 , 4000 ) ) ; elemSearchButton.click ( ) ; //elemSearchButton.InvokeMember ( `` click '' ) ; if ( ! _mreWaitForAction.WaitOne ( 10000 ) ) //Here The Deadlock happens { //Now the click event and therefor the search will be executed ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Suche ist auf Timeout gelaufen '' , this.BookieName ) ) ; throw new BookieTimeoutExcpetion ( String.Format ( `` Bookie { 0 } : Suche ist auf Timeout gelaufen '' , this.BookieName ) ) ; } _mreWaitForAction.Reset ( ) ; HtmlElement spanResult = doc.GetElementById ( `` total_ocs_count '' ) ; while ( spanResult == null ) { Thread.Sleep ( 500 ) ; spanResult = doc.GetElementById ( `` total_ocs_count '' ) ; } int total_ocs_count = 0 ; if ( ! Int32.TryParse ( spanResult.InnerHtml , out total_ocs_count ) ) { ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Tip { 1 } nicht gefunden '' , this.BookieName , tipp.BookieMatchName ) ) ; throw new BookieTippNotFoundExcpetion ( String.Format ( `` Bookie { 0 } : Tip { 1 } nicht gefunden '' , this.BookieName , tipp.BookieMatchName ) ) ; } if ( total_ocs_count < = 0 ) { ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Tip { 1 } nicht gefunden '' , this.BookieName , tipp.BookieMatchName ) ) ; throw new BookieTippNotFoundExcpetion ( String.Format ( `` Bookie { 0 } : Tip { 1 } nicht gefunden '' , this.BookieName , tipp.BookieMatchName ) ) ; } /* else if ( total_ocs_count > 1 ) { throw new BookieMoreThanOneFoundExcpetion ( String.Format ( `` Bookie { 0 } : Tipp { 1 } nicht eindeutig '' , this.BookieName , tipp.BookieMatchName ) ) ; } */ ConsoleWriter.writeToConsole ( String.Format ( `` Bookie { 0 } : Tip { 1 } gefunden '' , this.BookieName , tipp.BookieMatchName ) ) ; _status = BookieStatusType.GETMARKET ; } } } _mreWaitForAction.Set ( ) ; } }",EventHandle.WaitOne + WebBrowser = Deadlock when waiting for DocumentComplete "C_sharp : I am using NHibernate for my database management.In one class I am calculating a property using this formula : The generated query looks like this : Obviously the name in the AS statement is renamed to this_.x , which causes the error.It seems to be a known bug : NHibernate JIRA # NH-2878Does enyone have a solution for this ? ( SELECT MIN ( x.timestamp ) FROM ( SELECT MAX ( r.Timestamp ) AS timestamp , r.Meter_Id FROM Reading r , Meter m WHERE r.Meter_Id = m.Id AND m.Store_Id = Id GROUP BY r.Meter_Id ) AS x ) ( SELECT MIN ( x.timestamp ) FROM ( SELECT MAX ( r.Timestamp ) AS timestamp , r.Meter_Id FROM Reading r , Meter m WHERE r.Meter_Id = m.Id AND m.Store_Id = this_.Id GROUP BY r.Meter_Id ) AS this_.x )",Bug in NHibernate Aliasing "C_sharp : While attempting to implement my own Queue by wrapping the generic Queue , I noticed that Queue implements ICollection . However , the method signature of ICollection.CopyTo is as followsWhereas the method signature of the generic Queue.CopyTo is This is the same as the signature of the generic version of ICollection.CopyTo . My confusion comes from the fact that the generic queue does n't seem to implement the generic ICollection , but instead implements the standard ICollection . So what exactly is going on here ? void CopyTo ( Array array , int index ) public void CopyTo ( T [ ] array , int arrayIndex )",What does Queue < T > actually implement "C_sharp : I 'm working in C # . I have an unsigned 32-bit integer i that is incremented gradually in response to an outside user controlled event . The number is displayed in hexadecimal as a unique ID for the user to be able to enter and look up later . I need i to display a very different 8 character string if it is incremented or two integers are otherwise close together in value ( say , distance < 256 ) . So for example , if i = 5 and j = 6 then : The limitations on this are : I do n't want an obvious pattern in how the string changes in each increment.The process needs to be reversible , so if given the string I can generate the original number.Each generated string needs to be unique for the entire range of a 32-bit unsigned integers , so that two numbers do n't ever produce the same string.The algorithm to produce the string should be fairly easy to implement and maintain for both encoding and decoding ( maybe 30 lines each or less ) .However : The algorithm does not need to be cryptographically secure . The goal is obfuscation more than encryption . The number itself is not secret , it just needs to not obviously be an incrementing number.It is alright if looking at a large list of incremented numbers a human can discern a pattern in how the strings are changing . I just do n't want it to be obvious if they are `` close '' .I recognize that a Minimal Perfect Hash Function meets these requirements , but I have n't been able to find one that will do what I need or learn how to derive one that will.I have seen this question , and while it is along similar lines , I believe my question is more specific and precise in its requirements . The answer given for that question ( as of this writing ) references 3 links for possible implementations , but not being familiar with Ruby I 'm not sure how to get at the code for the `` obfuscate_id '' ( first link ) , Skipjack feels like overkill for what I need ( 2nd link ) , and Base64 does not use the character set I 'm interested in ( hex ) . string a = Encoded ( i ) ; // = `` AF293E5B '' string b = Encoded ( j ) ; // = `` CD2429A4 ''",How to I encode a number so that small changes result in very different encodings ? "C_sharp : One use for the var type in c # seems to be shortcuts/simplifying/save unnecessary typing . One thing that I 've considered is this : MyApp.Properties.Settings.Default.Value=1 ; That 's a ton of unnecessary code . An alternative to this is declaring : -- or -- leading to : appsettings.Default.Value=1 or Settings.Default.Value=1Abit better , but I 'd like it shorter still : Finally , it 's short enough , and it could be used for other annoyingly long calls too but is this an accepted way of doing it ? I 'm considering whether the `` shortcut var '' will always be pointing to the existing instance of whatever I 'm making a shortcut too ? ( obviously not just the settings as in this example ) using MyApp.Properties ; using appsettings = MyAppp.Properties.Settings ; var appsettings = MyFirstCSharpApp.Properties.Settings.Default ; appsettings.Value=1 ;",Is it considered accepted using var 's as `` shortcuts '' in c # ? "C_sharp : Here is the situation . In some cases I find myself wanting a class , let 's call it class C that has the same functionalities as class A , but with the addition that it has interface B implemented . For now I do it like this : The problem will come if class A happens to be sealed . Is there a way I can make class A implement interface B without having to define class C ( with extension methods or something ) class C : A , B { //code that implements interface B , and nothing else }",Can you attach an interface to a defined class "C_sharp : I 've read Eric 's article here about foreach enumeration and about the different scenarios where foreach can workIn order to prevent the old C # version to do boxing , the C # team enabled duck typing for foreach to run on a non- Ienumerable collection . ( A public GetEnumerator that return something that has public MoveNext and Current property is sufficient ( .So , Eric wrote a sample : But I believe it has some typos ( missing get accessor at Current property implementation ) which prevent it from compiling ( I 've already Emailed him ) . Anyway here is a working version : Ok.According to MSDN : A type C is said to be a collection type if it implements the System.Collections.IEnumerable interface or implements the collection pattern by meeting all of the following criteria : C contains a public instance method with the signature GetEnumerator ( ) that returns a struct-type , class-type , or interface-type , which is called E in the following text.E contains a public instance method with the signature MoveNext ( ) and the return type bool.E contains a public instance property named Current that permits reading the current value . The type of this property is said to be the element type of the collection type.OK . Let 's match the docs to Eric 's sampleEric 's sample is said to be a collection type because it does implements the System.Collections.IEnumerable interface ( explicitly though ) . But it is not ( ! ) a collection pattern because of bullet 3 : MyEnumerator does not public instance property named Current.MSDN says : If the collection expression is of a type that implements the collection pattern ( as defined above ) , the expansion of the foreach statement is : Otherwise , The collection expression is of a type that implements System.IEnumerable ( ! ) , and the expansion of the foreach statement is : Question # 1It seems that Eric 's sample neither implements the collection pattern nor System.IEnumerable - so it 's not supposed to match any of the condition specified above . So how come I can still iterate it via : Question # 2Why do I have to mention new MyIntegers ( ) as IEnumerable ? it 's already Ienumerable ( ! ! ) and even after that , Is n't the compiler is already doing the job by itself via casting : It is right here : So why it still wants me to mention as Ienumerable ? class MyIntegers : IEnumerable { public class MyEnumerator : IEnumerator { private int index = 0 ; object IEnumerator.Current { return this.Current ; } int Current { return index * index ; } public bool MoveNext ( ) { if ( index > 10 ) return false ; ++index ; return true ; } } public MyEnumerator GetEnumerator ( ) { return new MyEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return this.GetEnumerator ( ) ; } } class MyIntegers : IEnumerable { public class MyEnumerator : IEnumerator { private int index = 0 ; public void Reset ( ) { throw new NotImplementedException ( ) ; } object IEnumerator.Current { get { return this.Current ; } } int Current { get { return index*index ; } } public bool MoveNext ( ) { if ( index > 10 ) return false ; ++index ; return true ; } } public MyEnumerator GetEnumerator ( ) { return new MyEnumerator ( ) ; } IEnumerator IEnumerable.GetEnumerator ( ) { return this.GetEnumerator ( ) ; } } E enumerator = ( collection ) .GetEnumerator ( ) ; try { while ( enumerator.MoveNext ( ) ) { ElementType element = ( ElementType ) enumerator.Current ; statement ; } } finally { IDisposable disposable = enumerator as System.IDisposable ; if ( disposable ! = null ) disposable.Dispose ( ) ; } IEnumerator enumerator = ( ( System.Collections.IEnumerable ) ( collection ) ) .GetEnumerator ( ) ; try { while ( enumerator.MoveNext ( ) ) { ElementType element = ( ElementType ) enumerator.Current ; statement ; } } finally { IDisposable disposable = enumerator as System.IDisposable ; if ( disposable ! = null ) disposable.Dispose ( ) ; } foreach ( var element in ( new MyIntegers ( ) as IEnumerable ) ) { Console.WriteLine ( element ) ; } ( ( System.Collections.IEnumerable ) ( collection ) ) .GetEnumerator ( ) ? IEnumerator enumerator = ( ( System.Collections.IEnumerable ) ( collection ) ) .GetEnumerator ( ) ; try { while ( enumerator.MoveNext ( ) ) { ...",C # ` foreach ` behaviour — Clarification ? "C_sharp : I am learning DI in .Net Core and I do not get the idea about the benefit of using IOptions.Why do we need IOptions if we can do without it ? With IOptionsWithout IOptions interface IService { void Print ( string str ) ; } class Service : IService { readonly ServiceOption options ; public Service ( IOptions < ServiceOption > options ) = > this.options = options.Value ; void Print ( string str ) = > Console.WriteLine ( $ '' { str } with color : { options.Color } '' ) ; } class ServiceOption { public bool Color { get ; set ; } } class Program { static void Main ( ) { using ( ServiceProvider sp = RegisterServices ( ) ) { // } } static ServiceProvider RegisterServices ( ) { IServiceCollection isc = new ServiceCollection ( ) ; isc.Configure < ServiceOption > ( _ = > _.Color = true ) ; isc.AddTransient < IService , Service > ( ) ; return isc.BuildServiceProvider ( ) ; } } interface IService { void Print ( string str ) ; } class Service : IService { readonly ServiceOption options ; public Service ( ServiceOption options ) = > this.options = options ; public void Print ( string str ) = > Console.WriteLine ( $ '' { str } with color : { options.Color } '' ) ; } class ServiceOption { public bool Color { get ; set ; } } class Program { static void Main ( ) { using ( ServiceProvider sp = RegisterServices ( ) ) { // } } static ServiceProvider RegisterServices ( ) { IServiceCollection isc = new ServiceCollection ( ) ; isc.AddSingleton ( _ = > new ServiceOption { Color = true } ) ; isc.AddTransient < IService , Service > ( ) ; return isc.BuildServiceProvider ( ) ; } }",When do we need IOptions ? "C_sharp : When you use LINQ to define an enumerable collection , either by using the LINQ extension methods or by using query operators , the application does not actually build the collection at the time that the LINQ extension method is executed ; the collection is enumerated only when you iterate over it . This means that the data in the original collection can change between executing a LINQ query and retrieving the data that the query identifies ; you will always fetch the most up-to-date data . Microsoft Visual C # 2013 step by step written by John SharpI have written the following code : The result of the above code is shown bellow : 1 , 2 , 3 , 4 , 5 , Why is that going like this ? I know about Func , Action and Predicate but I can not figure out what is going on here . Based on the above definition the code is not rational . List < int > numbers = new List < int > ( ) { 1 , 2 , 3 , 4 , 5 } ; IEnumerable < int > res = numbers.FindAll ( a = > a > 0 ) .Select ( b = > b ) .ToList ( ) ; numbers.Add ( 99 ) ; foreach ( int item in res ) Console.Write ( item + `` , `` ) ;",Linq and deferred evaluation "C_sharp : Currently in my console application , I do the following to delete files in fire and forget style.I was wondering if there is any performance gain in setting ConfigureAwait ( false ) for each of these Task.Run calls ? ( My assumption is no , since I am not awaiting the call but I am not sure ) for ( var file in files ) ' ' // Check for certain file condition and decide to delete it . ' ' if ( shouldDeleteFile ) { Task.Run ( ( ) = > File.Delete ( file ) ) ; }",Configure.Await ( false ) with fire and forget async calls "C_sharp : In C # , consider we have a generic class and a concrete classis it necessary to mark ConcreteUser as [ Serializable ] or inheritance will take care of it ? [ Serializable ] public class GenericUser { ... [ Serializable ] public class ConcreteUser : GenericUser { ...",Is serializable attribute needed in concrete C # class ? "C_sharp : I 'm tackling the Project Euler problems again ( did the 23 first ones before when I was learning C # ) and I 'm quite baffled at the subpar performance of my solution to problem 5.It reads as follow : 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder . What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20 ? Now my incredibly primitive brute-force solution of C # tugs through this problem in roughly 25 seconds.Now my F # solution uses brute forcing as well but at least it does a bit more discrimination and such so that it `` should '' in my mind run faster but it clocks out at ~45 secs so it 's nearly twice as slow as the C # one.P.S - I know that my solution could be better , in this case I am simply wondering how it could be that a better brute-force solution can be so much slower than a primitive one . var numbers = Enumerable.Range ( 1 , 20 ) ; int start = 1 ; int result ; while ( true ) { if ( numbers.All ( n = > start % n == 0 ) ) { result = start ; break ; } start++ ; } let p5BruteForce = let divisors = List.toSeq ( [ 3..20 ] | > List.rev ) let isDivOneToTwenty n = let dividesBy = divisors | > Seq.takeWhile ( fun x - > n % x = 0 ) Seq.length dividesBy = Seq.length divisors let findNum n = let rec loop n = match isDivOneToTwenty n with | true - > n | false - > loop ( n + 2 ) loop n findNum 2520",Why is this F # code slower than the C # equivalent ? "C_sharp : I want to combine two LambdaExpressions without compiling them.This is what it looks like if I do compile them : That 's obviously not the fastest way to get the target expression from the provided arguments . Also , it makes it incompatible with query providers like LINQ to SQL that do not support C # method calls . From what I 've read it seems like the best approach is to build an ExpressionVisitor class . However , this seems like it could be a pretty common task . Does anyone know of an existing open source code base that provides this kind of functionality ? If not , what is the best way to approach the ExpressionVisitor to make it as generic as possible ? public Expression < Func < TContainer , bool > > CreatePredicate < TContainer , TMember > ( Expression < Func < TContainer , TMember > > getMemberExpression , Expression < Func < TMember , bool > > memberPredicateExpression ) { return x = > memberPredicateExpression.Compile ( ) ( getMemberExpression.Compile ( ) ( x ) ) ; }",How to build a LambdaExpression from an existing LambdaExpression Without Compiling "C_sharp : Here 's my example : I have read some tutorials and they say that we should use only one mock per test.But look at my test , it use 3 mocks , to check if my Action is working the right way I need to check these 3 mocks , do not agree ? How do I make this test in the correct way ? [ TestMethod ] public void NewAction_should_return_IndexAction ( ) { NewViewModel viewModel = new NewViewModel ( ) { Name = `` José Inácio Santos Silva '' , Email = `` joseinacio @ joseinacio.com '' , Username = `` joseinacio '' } ; //IsUserRegistered is used to validate Username , Username is unique . _mockAuthenticationService.Setup ( x = > x.IsUserRegistered ( viewModel.Username ) ) .Returns ( false ) ; //IsUserRegistered is used to validate Email , Email is unique . _mockUsuarioRepository.Setup ( x = > x.GetUserByEmail ( viewModel.Email ) ) ; _mockDbContext.Setup ( x = > x.SaveChanges ( ) ) ; _mockUsuarioRepository.Setup ( x = > x.Add ( It.IsAny < User > ( ) ) ) ; _userController = new UserController ( _mockUsuarioRepository.Object , _mockDbContext.Object , _mockAuthenticationService.Object ) ; ActionResult result = _userController.New ( viewModel ) ; result.AssertActionRedirect ( ) .ToAction ( `` Index '' ) ; _mockAuthenticationService.VerifyAll ( ) ; _mockUsuarioRepository.VerifyAll ( ) ; _mockDbContext.VerifyAll ( ) ; }",What 's the correct way to use Stubs and Mocks ? "C_sharp : I am developing a .NET Core project where I send Razor pages as e-mail templates . I followed this tutorial : https : //scottsauber.com/2018/07/07/walkthrough-creating-an-html-email-template-with-razor-and-razor-class-libraries-and-rendering-it-from-a-net-standard-class-library/The only thing I could n't find was how to send a localized e-mail by passing the needed language as a parameter ( example ) : I found some stuff online about POs and resx files but everything required a Startup implementation . The razor pages is not the main project , the main project is just an API , while the front-end is handled by another Angular project.How can I implement localization in a Razor Class Library without a Startup file ? This is the project files public async Task < string > RenderViewToStringAsync < TModel > ( string viewName , TModel model , string lang )",Use localized Razor pages as e-mail templates C_sharp : In WPF application I use Textbox with custom style in which ContextMenu is overriden like this : This works perfectly until I 'll run window with TextBox in different threads like this : But this causes InvalidOperationException `` The calling thread can not access this object because a different thread owns it . `` .How to avoid this problem ? < Style TargetType= '' { x : Type TextBox } '' > < Setter Property= '' ContextMenu '' > < ContextMenu > < MenuItem Header= '' Copy '' / > < /ContextMenu > < /Setter > < /Style > Thread thread = new Thread ( ( ) = > { TestWindow wnd = new TestWindow ( ) ; wnd.ShowDialog ( ) ; } ) ; thread.SetApartmentState ( ApartmentState.STA ) ; thread.IsBackground = true ; thread.Start ( ) ;,"TextBox custom ContextMenu in Style , multithreading error" "C_sharp : Iam writing an app that shows a list of the remaining time a user has on a course.I want the list to dynamically update every second so the user has the full overview.As you can see above the idea is that the model knows when the customer entered the circuit and the time the have left.As you can see iam thinking of using the INotifyPropertyChanged interface and then actually having a timer on every viewmodel.However this is my concern . Adding a Timer on every viewmodel seems very bloated , is this really the best way to achieve this ? Second concern is that if the timer is never stopped would n't this result in a memory leak since the timer would never stop and keep the viewmodel alive ? If this is the case my Viewmodel would also need to implement IDisposable and i would need to remember to run through all viewmodels and dispose them to make sure that these are garbage collected . Are my concerns correct ? Thanks.Yes i was thinking of having a timer service to prevent having multiple timers , however having to manually unregister would surely at some point introduce memoery leaks.So the idea with Weak Events is great.Iam thinking of doing it something like this : Do you have any comments ? I Know i could use a singleton GetInstance ( or IoC ) however this would just make it more inconvinient to use.Iam using the WeakEvent implementation that Daniel Grunwald wrote on codeproject . ( it gives a very clean class and not much overhead ) .http : //www.codeproject.com/KB/cs/WeakEvents.aspx public class ReservationCustomerList : INotifyPropertyChanged { public int UnitsLeft { get ; set ; } public DateTime ? OnCircuitSince { get ; set ; } public TimeSpan ? TimeLeftDate { get { if ( OnCircuitSince.HasValue ) return TimeSpan.FromSeconds ( ( OnCircuitSince.Value - DateTime.Now ) .TotalSeconds - UnitsLeft ) ; return TimeSpan.FromSeconds ( UnitsLeft ) ; } } private void FireEverySecond ( ) { PropertyChanged.Fire ( this , x = > x.TimeLeftDate ) ; } } public class TimerService { static Timer Timer ; static FastSmartWeakEvent < EventHandler > _secondEvent = new FastSmartWeakEvent < EventHandler > ( ) ; static FastSmartWeakEvent < EventHandler > _minuteEvent = new FastSmartWeakEvent < EventHandler > ( ) ; static DateTime LastTime ; public static event EventHandler SecondEvent { add { _secondEvent.Add ( value ) ; } remove { _secondEvent.Remove ( value ) ; } } public static event EventHandler MinuteEvent { add { _minuteEvent.Add ( value ) ; } remove { _minuteEvent.Remove ( value ) ; } } static TimerService ( ) { Timer = new Timer ( TimerFire , null , 1000 , 1000 ) ; } static void TimerFire ( object state ) { _secondEvent.Raise ( null , EventArgs.Empty ) ; if ( LastTime.Minute ! = DateTime.Now.Minute ) _minuteEvent.Raise ( null , EventArgs.Empty ) ; LastTime = DateTime.Now ; } }",ViewModel updates every second ? "C_sharp : I have a Visual Studio extension that show red error squiggles . I also like to provide squiggles with other colors , for example yellow for warnings.Creating red squiggles can be done by extending the ITagger class , along the lines : What I have tried : My intuition ( incorrectly ) says that returning an ErrorTag with an different errorType may yield a different type of tag , but whatever string you pass it , the squiggles remain red . Eg . new ErrorTag ( `` Warning '' ) gives red squiggles . The MSDN documentation is almost nonexistent . See ErrorTag.In the Tagging namespace there is no mention of a different Tag class implementing ITag . I hoped a WarningTag or InfoTag existed.Asked a question on MSDN forum here.Question : how to create green ( or blue or yellow ) squiggle adornments ? Sadly , even arcane or convoluted solutions are appreciated ... I 'm targeting VS2015 and VS2017.Edit : While typing this question someone at the MSDN forum replied that it can not be done with the current API . Is it really impossible to make yellow squiggles in Visual Studio ? ! internal sealed class MySquigglesTagger : ITagger < IErrorTag > { public IEnumerable < ITagSpan < IErrorTag > > GetTags ( NormalizedSnapshotSpanCollection spans ) { foreach ( IMappingTagSpan < MyTokenTag > myTokenTag in this._aggregator.GetTags ( spans ) ) SnapshotSpan tagSpan = myTokenTag.Span.GetSpans ( this._sourceBuffer ) [ 0 ] ; yield return new TagSpan < IErrorTag > ( tagSpan , new ErrorTag ( `` Error '' , `` some info about the error '' ) ) ; } } }",How to create green ( or blue ) squiggle adornments with a Visual Studio extension "C_sharp : For example , I have an immutable typeAnd I hope I can use object initializer syntax to create a ContactBut I can not . Any possible way to make use of the powerful object initializer syntax in this case ? class Contact { // Read-only properties . public string Name { get ; } public string Address { get ; } } Contact a = new Contact { Name = `` John '' , Address = `` 23 Tennis RD '' } ;",Immutable types with object initializer syntax "C_sharp : Version : Visual Studio Professional 2013 Update 4 Build param : Prefer 32-bit is trueI do n't understand the error in the following C # code : Adding a short to an int casted to a short results in the following error : Can not implicitly convert type 'int ' to 'short ' . An explicit conversion exists ( are you missing a cast ? ) The above error , also seen in the following case , is perfectly valid here : The following workaround removes the error : So addition in the form `` short + Int32 constant '' apparently works and the result is Int32 , which needs to be cast to a short.Is there an explanation why the first code sample fails or is this a compiler bug ? ( which I can hardly believe after 4 Updates ) short iCount = 20 ; short iValue = iCount + ( short ) 1 ; short iCount = 20 ; short iValue = iCount + 1 ; short iCount = 20 ; short iValue = ( short ) ( iCount + 1 ) ;",short + short ! = short ? "C_sharp : In C # there is a string interpolation support like this : which will format this string using in-scope variable Value.But the following wo n't compile in current C # syntax.Say , I have a static Dictionary < string , string > of templates : And then on every run of this method I want to fill in the placeholders : Is it achievable without implementing Regex parsing of those placeholders and then a replace callback on that Regex ? What are the most performant options that can suit this method as being a hot path ? For example , it is easily achievable in Python : $ '' Constant with { Value } '' templates = new Dictionary < string , string > { { `` Key1 '' , $ '' { Value1 } '' } , { `` Key2 '' , $ '' Constant with { Value2 } '' } } public IDictionary < string , string > FillTemplate ( IDictionary < string , string > placeholderValues ) { return templates.ToDictionary ( t = > t.Key , t = > string.FormatByNames ( t.Value , placeholderValues ) ) ; } > > > templates = { `` Key1 '' : `` { Value1 } '' , `` Key2 '' : `` Constant with { Value2 } '' } > > > values = { `` Value1 '' : `` 1 '' , `` Value2 '' : `` example 2 '' } > > > result = dict ( ( ( k , v.format ( **values ) ) for k , v in templates.items ( ) ) ) > > > result { 'Key2 ' : 'Constant with example 2 ' , 'Key1 ' : ' 1 ' } > > > values2 = { `` Value1 '' : `` another '' , `` Value2 '' : `` different '' } > > > result2 = dict ( ( ( k , v.format ( **values2 ) ) for k , v in templates.items ( ) ) ) > > > result2 { 'Key2 ' : 'Constant with different ' , 'Key1 ' : 'another ' }",Deferred template string interpolation "C_sharp : While studying C # I found it really strange , that dynamically typed Python will rise an error in the following code : whereas statically typed C # will normally proceed the similar code : I would expect other way around ( in python I would be able to do this without any casting , but C # would require me to cast int to string or string to int ) .Just to highlight , I am not asking what language is better , I am curious what was the reason behind implementing the language this way . i = 5print i + `` `` int i = 5 ; Console.Write ( i + `` `` ) ;",Why is `` int + string '' possible in statically-typed C # but not in dynamically-typed Python ? "C_sharp : In C # , classes and interfaces can have events : This facilitates a push-based notification with minimal boilerplate code , and enables a multiple-subscriber model so that many observers can listen to the event : Is there an equivalent idiom in Scala ? What I 'm looking for is : Minimal boilerplate codeSingle publisher , multiple subscribersAttach/detach subscribersExamples of its use in Scala documentation would be wonderful . I 'm not looking for an implementation of C # events in Scala . Rather , I 'm looking for the equivalent idiom in Scala . public class Foo { public event Action SomethingHappened ; public void DoSomething ( ) { // yes , i 'm aware of the potential NRE this.SomethingHappened ( ) ; } } var foo = new Foo ( ) ; foo.SomethingHappened += ( ) = > Console.WriteLine ( `` Yay ! `` ) ; foo.DoSomething ( ) ; // `` Yay ! '' appears on console .",What 's the idiomatic equivalent in Scala for C # 's event "C_sharp : The f # code goes literally 500 times slower than the c # code . What am I doing wrong ? I tried to make the code basically the same for both languages . It does n't make sense that SetPixel would be that much slower in f # .F # : C # : module Imagingopen System.Drawing ; # lighttype Image ( width : int , height : int ) = class member z.Pixels = Array2D.create width height Color.White member z.Width with get ( ) = z.Pixels.GetLength 0 member z.Height with get ( ) = z.Pixels.GetLength 1 member z.Save ( filename : string ) = let bitmap = new Bitmap ( z.Width , z.Height ) let xmax = bitmap.Width-1 let ymax = bitmap.Height-1 let mutable bob = 0 ; for x in 0..xmax do for y in 0..ymax do bitmap.SetPixel ( x , y , z.Pixels . [ x , y ] ) bitmap.Save ( filename ) new ( ) = Image ( 1280 , 720 ) endlet bob = new Image ( 500,500 ) bob.Save @ '' C : \Users\White\Desktop\TestImage2.bmp '' using System.Drawing ; namespace TestProject { public class Image { public Color [ , ] Pixels ; public int Width { get { return Pixels.GetLength ( 0 ) ; } } public int Height { get { return Pixels.GetLength ( 1 ) ; } } public Image ( int width , int height ) { Pixels = new Color [ width , height ] ; for ( int x = 0 ; x < Width ; x++ ) { for ( int y = 0 ; y < Height ; y++ ) { Pixels [ x , y ] = Color.White ; } } } public void Save ( string filename ) { Bitmap bitmap = new Bitmap ( Width , Height ) ; for ( int x = 0 ; x < bitmap.Width ; x++ ) { for ( int y = 0 ; y < bitmap.Height ; y++ ) { bitmap.SetPixel ( x , y , Pixels [ x , y ] ) ; } } bitmap.Save ( filename ) ; } } class Program { static void Main ( string [ ] args ) { Image i = new Image ( 500 , 500 ) ; i.Save ( @ '' C : \Users\White\Desktop\TestImage2.bmp '' ) ; } } }",Bitmap.SetPixel acts slower in f # than in c # "C_sharp : I have implemented endpoint with this signaturethis generates following entry in swagger.json ( the relevant part ) but , I also need specify encoding , like in the specs ( v3 ) . So for my task , that JSON should look like this , I think ... But how can I do that from code ? I thought about SwaggerParameter attribute , but it contains only description and required flag ... I 'm using Swashbuckle.AspNetCore NuGeT package ( version 5.0.0-rc2 ) on .NET Core 2.2 . [ HttpPost ( `` Test '' ) ] public IActionResult MyTest ( [ Required ] IFormFile pdf , [ Required ] IFormFile image ) { // some stuff ... return Ok ( ) ; } `` content '' : { `` multipart/form-data '' : { `` schema '' : { `` required '' : [ `` image '' , `` pdf '' ] , `` type '' : `` object '' , `` properties '' : { `` pdf '' : { `` type '' : `` string '' , `` format '' : `` binary '' } , `` image '' : { `` type '' : `` string '' , `` format '' : `` binary '' } } } , `` encoding '' : { `` pdf '' : { `` style '' : `` form '' } , `` image '' : { `` style '' : `` form '' } } } } `` encoding '' : { `` pdf '' : { `` style '' : `` form '' , `` contentType '' : `` application/pdf '' } , `` image '' : { `` style '' : `` form '' , `` contentType '' : `` image/png , image/jpeg '' } }",Specify content-type for files in multipart/form-data for Swagger "C_sharp : My gut reaction is no , because managed and unmanaged memory are distinct , but I 'm not sure if the .NET Framework is doing something with Marshaling behind the scenes.What I believe happens is : When getting a struct from my unmanaged DLL , it is the same as making that call gets an IntPtr and then uses it and the Marshal class to copy the struct into managed memory ( and changes made to the struct in managed memory do not bubble up ) .I ca n't seem to find this documented anywhere on MSDN . Any links would be appreciated.Here is what my code looks like : [ DllImport ( `` mydll.dll '' , BestFitMapping=false , CharSet=CharSet.Ansi ) ] private static extern int GetStruct ( ref MyStruct s ) ; [ StructLayout ( LayoutKind.Sequential , Pack=0 ) ] struct MyStruct { public int Field1 ; public IntPtr Field2 ; } public void DoSomething ( ) { MyStruct s = new MyStruct ( ) ; GetStruct ( ref s ) ; s.Field1 = 100 ; //does unmanaged memory now have 100 in Field1 as well ? s.Field2 = IntPtr.Zero ; //does unmanaged memory now have a NULL pointer in field Field2 as well ? }",Will struct modifications in C # affect unmanaged memory ? "C_sharp : In my quest to write a stock market trader IObserver I 've encountered three errors mostly thrown from within the Reactive Extensions library.I have the following CompanyInfo class : And an IObservable < CompanyInfo > called StockMarket : My Observer looks like the following : I run the following code : One of three errors occur : The following ArgumentException is thrown from within the Reactive Extensions : System.ArgumentException : An item with the same key has already been added . at System.ThrowHelper.ThrowArgumentException ( ExceptionResource resource ) at System.Collections.Generic.Dictionary ` 2.Insert ( TKey key , TValue value , Boolean add ) at System.Reactive.Linq.Observable.GroupBy ' 3._.OnNext ( TSource value ) The following IndexOutOfRangeException : Parameter name : index at System.ThrowHelper.ThrowArgumentOutOfRangeException ( ExceptionArgument argument , ExceptionResource resource ) at System.Collections.Generic.List ' 1.get_Item ( Int32 index ) at StockMarketTests. < > c__DisplayClass0_0.b__2 ( IList ' 1 y ) at System.Reactive.Linq.Observable.Select ' 2._.OnNext ( TSource value ) The text of the Console tweaks sporadically ( The color should be consistance ) : What could cause those bizzare symptoms ? public class CompanyInfo { public string Name { get ; set ; } public double Value { get ; set ; } } public class StockMarket : IObservable < CompanyInfo > public class StockTrader : IObserver < CompanyInfo > { public void OnCompleted ( ) { Console.WriteLine ( `` Market Closed '' ) ; } public void OnError ( Exception error ) { Console.WriteLine ( error ) ; } public void OnNext ( CompanyInfo value ) { WriteStock ( value ) ; } private void WriteStock ( CompanyInfo value ) { ... } } StockMarket market = GetStockMarket ( ) ; StockTrader trader = new StockTrader ( ) ; IObservable < CompanyInfo > differential = market // [ F , 1 ] , [ S , 5 ] , [ S , 4 ] , [ F , 2 ] .GroupBy ( x = > x.Name ) // [ F , 1 ] , [ F , 2 ] ; [ S , 5 ] , [ S , 4 ] .SelectMany ( x = > x //4 , 8 , 2 , 3 .Buffer ( 2 , 1 ) // ( 4 , 8 ) , ( 8 , 2 ) , ( 2 , 3 ) , ( 3 ) .SkipLast ( 1 ) // ( 4 , 8 ) , ( 8 , 2 ) , ( 2 , 3 ) .Select ( y = > new CompanyInfo // ( +100 % ) , ( -75 % ) , ( +50 % ) { Name = x.Key , Value = ( y [ 1 ] .Value - y [ 0 ] .Value ) / y [ 0 ] .Value } ) // [ F , +100 % ] ; [ S , -20 % ] ) ; using ( IDisposable subscription = differential.Subscribe ( trader ) ) { Observable.Wait ( market ) ; }",Observable LINQ inconsistent exceptions thrown "C_sharp : I 'm using this question as a basis for my question.TL ; DR : If you 're not supposed to wrap synchronous code in an async wrapper , how do you deal with long-running , thread-blocking methods that implement an interface method which expects an asynchronous implementation ? Let 's say I have an application that runs continuously to process a work queue . It 's a server-side application ( running mostly unattended ) but it has a UI client to give a more-fine-grained control over the behavior of the application as required by the business processes : start , stop , tweak parameters during execution , get progress , etc.There 's a business logic layer into which services are injected as dependencies.The BLL defines a set of interfaces for those services.I want to keep the client responsive : allow UI client to interact with the running process , and I also want threads to be used efficiently because the process needs to be scalable : there could be any number of asynchronous database or disk operations depending on the work in the queue . Thus I 'm employing async/await `` all the way '' .To that end , I have methods in the service interfaces that are obviously designed to encourage async/await and support for cancellation because they take a CancellationToken , are named with `` Async '' , and return Tasks.I have a data repository service that performs CRUD operations to persist my domain entities . Let 's say that at the present time , I 'm using an API for this that does n't natively support async . In the future , I may replace this with one that does , but for the time being the data repository service performs the majority of its operations synchronously , many of them long-running operations ( because the API blocks on the database IO ) .Now , I understand that methods returning Tasks can run synchronously . The methods in my service class that implement the interfaces in my BLL will run synchronously as I explained , but the consumer ( my BLL , client , etc ) will assume they are either 1 : running asynchronously or 2 : running synchronously for a very short time . What the methods should n't do is wrap synchronous code inside an async call to Task.Run.I know I could define both sync and async methods in the interface.In this case I do n't want to do that because of the async `` all the way '' semantics I 'm trying to employ and because I 'm not writing an API to be consumed by a customer ; as mentioned above , I do n't want to change my BLL code later from using the sync version to using the async version.Here 's the data service interface : And it 's implementation : The BLL : Presentation and presentation logic : So the question is : how do you deal with long-running , blocking methods that implement an interface method which expects an asynchronous implementation ? Is this an example where it 's preferable to break the `` no async wrapper for sync code '' rule ? public interface IDataRepository { Task < IReadOnlyCollection < Widget > > GetAllWidgetsAsync ( CancellationToken cancellationToken ) ; } public sealed class DataRepository : IDataRepository { public Task < IReadOnlyCollection < Widget > > GetAllWidgetsAsync ( CancellationToken cancellationToken ) { /******* The idea is that this will /******* all be replaced hopefully soon by an ORM tool . */ var ret = new List < Widget > ( ) ; // use synchronous API to load records from DB var ds = Api.GetSqlServerDataSet ( `` SELECT ID , Name , Description FROM Widgets '' , DataResources.ConnectionString ) ; foreach ( DataRow row in ds.Tables [ 0 ] .Rows ) { cancellationToken.ThrowIfCancellationRequested ( ) ; // build a widget for the row , add to return . } // simulate long-running CPU-bound operation . DateTime start = DateTime.Now ; while ( DateTime.Now.Subtract ( start ) .TotalSeconds < 10 ) { } return Task.FromResult ( ( IReadOnlyCollection < Widget > ) ret.AsReadOnly ( ) ) ; } } public sealed class WorkRunner { private readonly IDataRepository _dataRepository ; public WorkRunner ( IDataRepository dataRepository ) = > _dataRepository = dataRepository ; public async Task RunAsync ( CancellationToken cancellationToken ) { var allWidgets = await _dataRepository .GetAllWidgetsAsync ( cancellationToken ) .ConfigureAwait ( false ) ; // I 'm using Task.Run here because I want this on // another thread even if the above runs synchronously . await Task.Run ( async ( ) = > { while ( true ) { cancellationToken.ThrowIfCancellationRequested ( ) ; foreach ( var widget in allWidgets ) { /* do something */ } await Task.Delay ( 2000 , cancellationToken ) ; // wait some arbitrary time . } } ) .ConfigureAwait ( false ) ; } } private async void HandleStartStopButtonClick ( object sender , EventArgs e ) { if ( ! _isRunning ) { await DoStart ( ) ; } else { DoStop ( ) ; } } private async Task DoStart ( ) { _isRunning = true ; var runner = new WorkRunner ( _dependencyContainer.Resolve < IDataRepository > ( ) ) ; _cancellationTokenSource = new CancellationTokenSource ( ) ; try { _startStopButton.Text = `` Stop '' ; _resultsTextBox.Clear ( ) ; await runner.RunAsync ( _cancellationTokenSource.Token ) ; // set results info in UI ( invoking on UI thread ) . } catch ( OperationCanceledException ) { _resultsTextBox.Text = `` Canceled early . `` ; } catch ( Exception ex ) { _resultsTextBox.Text = ex.ToString ( ) ; } finally { _startStopButton.Text = `` Start '' ; } } private void DoStop ( ) { _cancellationTokenSource.Cancel ( ) ; _isRunning = false ; }",Long running synchronous implementation of an interface that returns a Task "C_sharp : I am building a business layer for our large enterprise application , and we 're currently sitting at just under 500 unit tests . The scenario is that we have two public methods , public AddT ( T ) and public UpdateT ( T ) that both make an internal call to private AddOrUpdateT ( T ) since a lot of the core logic is the same between both , but not all ; they are different.Because they are separate public API ( regardless of private implementation ) , I wrote unit tests for each API , even though they are the same . This might look likeCurrently for this particular business object there are around 30 unit tests for adding , and 40 unit tests for updating , where 30 of the update tests are the same as the add tests.Is this normal , or should I be abstracting the common behavior out into a public helper class that is unit tested in isolation , and the two API 's just use that helper class instead of a private method that has the implementation ? What is considered a best practice for these situations ? [ TestMethod ] public void AddT_HasBehaviorA ( ) { } [ TestMethod ] public void UpdateT_HasBehaviorA ( ) { }",Should you have duplicate unit tests for seperate methods that share the same private implementation ? "C_sharp : My first Stack Overflow question.I have always been curious about this.Say you are parsing the following line of code : When parsing , a naive tokenizer will assume that the two right angle brackets are a single `` shift right '' token . I have n't run across this problem with any other language construction in a C-style language.How do modern parsers handle this ? Is there a workaround when using such `` greedy parsing ? `` I have thought about using a stack structure in the parser that handles those tokens specially when parsing generic types . I 'm not sure how well that would work when writing a code editor though.Thanks a ton ! : ) List < Nullable < int > > list = new List < Nullable < int > > ( ) ;",Differentiating between `` > > '' and `` > '' when parsing generic types "C_sharp : This is the initial situation : XAML : ViewModel : My Objects contains a name ( string ) , valid from ( dateTime ) and a displayText ( string only get ) which combine the name and valid from for displaying.In this easy situation I am able to open the combobox an see all entries , after selecting one it also display the right displaytext inside the combobox.Now I open the the dropdown area again and select an other entry.The result is that the slected item switched ( as you can see the highligthed item when open the dropdown entry again ) . But the displayed item inside the combobox does not changed , there is still the DisplayText of the first selection.Does anybody has an idea for me why the combobox does not update ? Thanks in advanceEdit : Thanks all for their help . Problem was a buggy overriding of Equals . < ComboBox Grid.Row= '' 0 '' Grid.Column= '' 1 '' Margin= '' 0,3 '' HorizontalAlignment= '' Stretch '' DisplayMemberPath= '' DisplayText '' ItemsSource= '' { Binding ObjectSource } '' / > public Collection < MyObjects > ObjectSource { get { return this.objectSource ; } set { this.SetProperty ( ref this.objectSource , value ) ; } }",WPF ComboBox : Wrong Item is displayed "C_sharp : For my programming exam I had to defend code I had written . One of the lines are : He asked me whether there was a difference between null and an empty string . I told him that the difference was that null means its not pointing to anything , so it 's not instantiated , but the empty string is.After the exam I walked up to him and asked him if I was correct , since I saw a funny look on his face . He told me that it 's true they 're different , but the order in which I checked the values was incorrect.Now a few days later I believe there 's nothing wrong with the order . Am I correct ? TL ; DRisequivalent to if ( app.Logourl == `` '' || app.Logourl == null ) if ( app.Logourl == `` '' || app.Logourl == null ) if ( app.Logourl == null || app.Logourl == `` '' )",Does the order of checking whether a string is null or empty matter ? "C_sharp : I 'm trying to use a very simple pre-compiled query within an extension method to retrieve data using LINQ to SQL . SytelineRepository is my custom DataContext that uses external mapping files , and I 'm querying the JobOrders table . I 've been using the custom DataContext for a long time without issue and executing the same query with no problem ; I 'm just trying to improve performance . However when I try to use CompiledQuery.Compile I get the ArgumentException below.Here 's the code : As a contrast , this works : Here 's the full error : System.ArgumentException was unhandledMessage=Property 'System.String ItemNumber ' is not defined for type 'System.Linq.IQueryable ` 1 [ Mpicorp.SytelineDataModel.JobOrder ] ' public static class Queries { public static readonly Func < SytelineRepository , String , IQueryable < JobOrder > > GetOpenJobOrdersForItemQuery = CompiledQuery.Compile ( ( SytelineRepository r , String itemNumber ) = > from job in r.JobOrders where job.ItemNumber == itemNumber select job ) ; public static IQueryable < JobOrder > GetOpenJobOrdersForItem ( this SytelineRepository r , System.String itemNumber ) { return GetOpenJobOrdersForItemQuery ( r , itemNumber ) ; } } public static IEnumerable < JobOrder > GetOpenJobOrdersForItem ( this SytelineRepository r , System.String itemNumber ) { return GetOpenJobOrdersForItemUncompiledQuery ( r , itemNumber ) ; } public static IQueryable < JobOrder > GetOpenJobOrdersForItemUncompiledQuery ( SytelineRepository r , String itemNumber ) { return from job in r.JobOrders where job.ItemNumber == itemNumber select job ; } at System.Linq.Expressions.Expression.Property ( Expression expression , PropertyInfo property ) at System.Data.Linq.SqlClient.SqlBinder.Visitor.AccessMember ( SqlMember m , SqlExpression expo ) at System.Data.Linq.SqlClient.SqlVisitor.Visit ( SqlNode node ) at System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitExpression ( SqlExpression expr ) at System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitBinaryOperator ( SqlBinary bo ) at System.Data.Linq.SqlClient.SqlVisitor.Visit ( SqlNode node ) at System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitExpression ( SqlExpression expr ) at System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitSelect ( SqlSelect select ) at System.Data.Linq.SqlClient.SqlVisitor.Visit ( SqlNode node ) at System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitIncludeScope ( SqlIncludeScope scope ) at System.Data.Linq.SqlClient.SqlVisitor.Visit ( SqlNode node ) at System.Data.Linq.SqlClient.SqlBinder.Bind ( SqlNode node ) at System.Data.Linq.SqlClient.SqlProvider.BuildQuery ( ResultShape resultShape , Type resultType , SqlNode node , ReadOnlyCollection ` 1 parentParameters , SqlNodeAnnotations annotations ) at System.Data.Linq.SqlClient.SqlProvider.BuildQuery ( Expression query , SqlNodeAnnotations annotations ) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Compile ( Expression query ) at System.Data.Linq.CompiledQuery.ExecuteQuery ( DataContext context , Object [ ] args ) at System.Data.Linq.CompiledQuery.Invoke [ TArg0 , TArg1 , TResult ] ( TArg0 arg0 , TArg1 arg1 ) at Mpicorp.SytelineDataModel.Queries.GetOpenJobOrdersForItem ( SytelineRepository r , String itemNumber ) in C : \SVN\Mpicorp.SytelineDataModel\trunk\SytelineDataModel\Queries.cs : line 21 at Mpicorp.SytelineDataModel.SytelineRepository.GetTimePhasedInventory ( String itemNumber , Boolean includeForecast ) in C : \SVN\Mpicorp.SytelineDataModel\trunk\SytelineDataModel\SytelineRepository.cs : line 242 at RepriceWorkbench.TimePhasedInventoryForm..ctor ( SytelineRepository repository , String itemNumber ) in C : \SVN\spirepriceutility\trunk\src\POWorkbench\TimePhasedInventoryForm.cs : line 32 at RepriceWorkbench.TimePhasedMenuForm.goBtn_Click ( Object sender , EventArgs e ) in C : \SVN\spirepriceutility\trunk\src\POWorkbench\TimePhasedMenuForm.cs : line 25 at System.Windows.Forms.Button.OnMouseUp ( MouseEventArgs mevent ) at System.Windows.Forms.Control.WmMouseUp ( Message & m , MouseButtons button , Int32 clicks ) at System.Windows.Forms.Control.WndProc ( Message & m ) at System.Windows.Forms.ButtonBase.WndProc ( Message & m ) at System.Windows.Forms.Button.WndProc ( Message & m ) at System.Windows.Forms.NativeWindow.DebuggableCallback ( IntPtr hWnd , Int32 msg , IntPtr wparam , IntPtr lparam ) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW ( MSG & msg ) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop ( IntPtr dwComponentID , Int32 reason , Int32 pvLoopData ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner ( Int32 reason , ApplicationContext context ) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop ( Int32 reason , ApplicationContext context ) at RepriceWorkbench.Program.Main ( ) in C : \SVN\spirepriceutility\trunk\src\POWorkbench\Program.cs : line 66 at System.AppDomain._nExecuteAssembly ( RuntimeAssembly assembly , String [ ] args ) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ( ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state , Boolean ignoreSyncCtx ) at System.Threading.ExecutionContext.Run ( ExecutionContext executionContext , ContextCallback callback , Object state ) at System.Threading.ThreadHelper.ThreadStart ( )",CompiledQuery throws ArgumentException "C_sharp : I have an existing expression of type Expression < Func < T , object > > ; it contains values like cust = > cust.Name.I also have a parent class with a field of type T. I need a method that accepts the above as a parameter and generates a new expression that takes the parent class ( TModel ) as a parameter . This will be used as an expression parameter of an MVC method.Thus , cust = > cust.Name becomes parent = > parent.Customer.Name.Likewise , cust = > cust.Address.State becomes parent = > parent.Customer.Address.State.Here 's my initial version : The error I 'm currently receiving is when I have a field with multiple parts ( i.e . cust.Address.State instead of just cust.Name ) . I get an error on the var member line that the specified member does n't exist -- which is true , since the body at that refers to the parent 's child ( Customer ) and not the item that contains the member ( Address ) .Here 's what I wish I could do : Any help getting to this point would be greatly appreciated.Edit : This was marked as a possible duplicate of this question ; however , the only real similarity is the solution ( which is , in fact , the same ) . Composing expressions is not an intuitive solution to accessing nested properties via expressions ( unless one 's inuition is guided by certain experience , which should not be assumed ) . I also edited the question to note that the solution needs to be suitable for a paramter of an MVC method , which limits the possible solutions . //note : the FieldDefinition object contains the first expression //described above , plus the MemberInfo object for the property/field //in question public Expression < Func < TModel , object > > ExpressionFromField < TModel > ( FieldDefinition < T > field ) where TModel : BaseModel < T > { var param = Expression.Parameter ( typeof ( TModel ) , `` t '' ) ; //Note in the next line `` nameof ( SelectedItem ) '' . This is a reference //to the property in TModel that contains the instance from which //to retrieve the value . It is unqualified because this method //resides within TModel . var body = Expression.PropertyOrField ( param , nameof ( SelectedItem ) ) ; var member = Expression.MakeMemberAccess ( body , field.Member ) ; return Expression.Lambda < Func < TModel , object > > ( member , param ) ; } public Expression < Func < TModel , object > > ExpressionFromField < TModel > ( FieldDefinition < T > field ) where TModel : BaseModel < T > { var param = Expression.Parameter ( typeof ( TModel ) , `` t '' ) ; var body = Expression.PropertyOrField ( param , nameof ( SelectedItem ) ) ; var IWantThis = Expression.ApplyExpressionToField ( field.Expression , body ) ; return Expression.Lambda < Func < TModel , object > > ( IWantThis , param ) ; }",Convert Linq expression `` obj = > obj.Prop '' into `` parent = > parent.obj.Prop '' "C_sharp : As said in the SignalR differences documentation we can use SignalR Core on .NET 4.6.1 and latter ... So I know the code for the startup and configuration for both cases : SignalR Core : ConfigureServicesStartupSignalR : StartupAnd my question is , what I need to do in the .NET 4.6.1 startup to map my SignalR hub and etc ... ? I ca n't find any documentation about this particular case.Update1 : I tried to run the same code and obviously changed the client code to use the SignalR core approach and what I get now is ( not authorized ) during negotiation request . //Add SignalR serviceservices.AddSignalR ( ) ; app.UseSignalR ( routes = > { routes.MapHub < NotificationsHub > ( `` /notification '' ) ; } ) ; app.Map ( `` /signalr '' , map = > { map.UseCors ( CorsOptions.AllowAll ) ; var hubConfiguration = new HubConfiguration { } ; hubConfiguration.EnableDetailedErrors = true ; map.RunSignalR ( hubConfiguration ) ; } ) ;",Using SignalR Core on .NET 4.6.1 "C_sharp : This program compiles and runs in C++ but does n't in a number of different languages , like Java and C # .In Java this gives a compiler error like 'Void methods can not return a value ' . But since the method being called is a void itself , it does n't return a value . I understand that a construct like this is probably prohibited for the sake of readability . Are there any other objections ? Edit : For future reference , I found some a similar question here return-void-type-in-c-and-cIn my humble opinion this question is n't answered yet . The reply 'Because it says so in the specification , move on ' does n't cut it , since someone had to write the specification in the first place . Maybe I should have asked 'What are the pros and cons of allowing returning a void type like C++ ' ? # include < iostream > using namespace std ; void foo2 ( ) { cout < < `` foo 2.\n '' ; } void foo ( ) { return foo2 ( ) ; } int main ( ) { foo ( ) ; return 0 ; }","Why can a void method in C++ return a void value , but in other languages it can not ?" "C_sharp : I will give an example from .NET.Here you can see ConcurrentDictionary implementing dictionary interfaces . However I ca n't access Add < TKey , TValue > method from a ConcurrentDictionary instance . How is this possible ? Update : I know how I can access it but I did n't know explicitly implementing an interface could allow changing access modifiers to internal . It still does n't allow making it private though . Is this correct ? A more detailed explanation about that part would be helpful . Also I would like to know some valid use cases please . ConcurrentDictionary < TKey , TValue > : IDictionary < TKey , TValue > , IDictionary IDictionary < int , int > dictionary = new ConcurrentDictionary < int , int > ( ) ; dictionary.Add ( 3 , 3 ) ; //no errorsConcurrentDictionary < int , int > concurrentDictionary = new ConcurrentDictionary < int , int > ( ) ; concurrentDictionary.Add ( 3 , 3 ) ; // Can not access private method here",How can a concrete class hide a member of the interface that it implements "C_sharp : I have an application that is using basic reflection today to grab classes.I wanted to see how efficient the reflection was running so I generated about 150,000 objects in this manner to see if performance ever degraded and performance was fast and steady.However , this got me thinking : Will the call to Type.GetType ( ) actually slow down depending on the size and complexity of the class being passed into the GetType ( ) method ? For example : Lets say we wanted to use GetType ( ) to retrieve a complex class made up of 30 private variables , 30 private methods and 30 public methods versus a class that has only one very simple public Add ( int , int ) method which sums up two numbers . Would Type.GetType slow down significantly if the class being passed in is a complex class versus a simple class ? thanks Type type = Type.GetType ( mynamespace.myclassname ) ; object o = System.Activator.CreateInstance ( type ) ;",Will Type.GetType ( ) slow down based on the size and complexity of the object you are retrieving ? C_sharp : or ( I would prefer a vb answer as that is what the application is written in but can convert so c # is fine if you dont know vb ) I understand that the above will give me the battery percentage remaining - BUT I have a tablet that is 'hot swappable ' ( it has a main battery then a small 5 minute battery that runs the tablet while you swap batteries on it ) - how would I find the status of the second battery ? I am looking for something like SystemInformation.PowerStatus ( 0 ) but I have NO idea what I am actually trying to find and I must be having a Google block as I can not find anything . Dim power As PowerStatus = SystemInformation.PowerStatus Dim percent As Single = power.BatteryLifePercent PowerStatus power = SystemInformation.PowerStatus ; float percent = power.BatteryLifePercent ;,How to retrieve dual batteries status ? "C_sharp : I have some classes that contain several fields . I need to compare them by value , i.e . two instances of a class are equal if their fields contain the same data . I have overridden the GetHashCode and Equals methods for that.It can happen that these classes contain circular references.Example : We want to model institutions ( like government , sports clubs , whatever ) . An institution has a name . A Club is an institution that has a name and a list of members . Each member is a Person that has a name and a favourite institution . If a member of a certain club has this club as his favourite institution , we have a circular reference.But circular references , in conjunction with value equality , lead to infinite recursion . Here is a code example : c1_and_c2_equal should return true , and in fact we ( humans ) can see that they are value-equal with a little bit of thinking , without running into infinite recursion . However , I ca n't really say how we figure that out . But since it is possible , I hope that there is a way to resolve this problem in code as well ! So the question is : How can I check for value equality without running into infinite recursions ? Note that I need to resolve circular references in general , not only the case from above . I 'll call it a 2-circle since c1 references p1 , and p1 references c1 . There can be other n-circles , e.g . if a club A has a member M whose favourite is club B which has member N whose favourite club is A . That would be a 4-circle . Other object models might also allow n-circles with odd numbers n. I am looking for a way to resolve all these problems at once , since I wo n't know in advance which value n can have . interface IInstitution { string Name { get ; } } class Club : IInstitution { public string Name { get ; set ; } public HashSet < Person > Members { get ; set ; } public override int GetHashCode ( ) { return Name.GetHashCode ( ) + Members.Count ; } public override bool Equals ( object obj ) { Club other = obj as Club ; if ( other == null ) return false ; return Name.Equals ( other.Name ) & & Members.SetEquals ( other.Members ) ; } } class Person { public string Name { get ; set ; } public IInstitution FavouriteInstitution { get ; set ; } public override int GetHashCode ( ) { return Name.GetHashCode ( ) ; } public override bool Equals ( object obj ) { Person other = obj as Person ; if ( other == null ) return false ; return Name.Equals ( other.Name ) & & FavouriteInstitution.Equals ( other.FavouriteInstitution ) ; } } class Program { public static void Main ( ) { Club c1 = new Club { Name = `` myClub '' , Members = new HashSet < Person > ( ) } ; Person p1 = new Person { Name = `` Johnny '' , FavouriteInstitution = c1 } c1.Members.Add ( p1 ) ; Club c2 = new Club { Name = `` myClub '' , Members = new HashSet < Person > ( ) } ; Person p2 = new Person { Name = `` Johnny '' , FavouriteInstitution = c2 } c2.Members.Add ( p2 ) ; bool c1_and_c2_equal = c1.Equals ( c2 ) ; // StackOverflowException ! // c1.Equals ( c2 ) calls Members.SetEquals ( other.Members ) // Members.SetEquals ( other.Members ) calls p1.Equals ( p2 ) // p1.Equals ( p2 ) calls c1.Equals ( c2 ) } }",Value-equals and circular references : how to resolve infinite recursion ? "C_sharp : I have compiled part of boost - the ibeta_inv function - into a .Net 64 bit assembly and it worked great until I started calling it from multiple threads . Then it occationally return wrong results.I complied it using this code ( C++/CLI ) : Has anyone tried this before ? I have NOT tried this outside .Net , so I do n't know if this is the cause , but I really do n't see why , since it works great single threaded.Usage ( C # ) : UPDATE : As can be seen in my comments below - I 'm not sure at all anymore that this is a Boost problem . Maybe it is some weird PLinq to C++/CLI bug ? ? ? I 'm blaffed and will return with more facts later . // Boost.h # pragma once # include < boost/math/special_functions/beta.hpp > using namespace boost : :math ; namespace Boost { public ref class BoostMath { public : double static InverseIncompleteBeta ( double a , double b , double x ) { return ibeta_inv ( a , b , x ) ; } } ; } private void calcBoost ( List < Val > vals ) { //gives WRONG results ( sometimes ) : vals.AsParallel ( ) .ForAll ( v = > v.BoostResult = BoostMath.InverseIncompleteBeta ( v.A , v.B , v.X ) ) ; //gives CORRECT results : vals.ForEach ( v = > v.BoostResult = BoostMath.InverseIncompleteBeta ( v.A , v.B , v.X ) ) ; }",Boost math ( ibeta_inv function ) not thread safe ? "C_sharp : What happens to a local Task reference when it runs out of scope and the garbage collector decides to get rid of it before the task completes ? Basically I 'm asking if it 's safe to make this kind of service call implementation : Will DoWork always complete in this example ? Even if the garbage collector decides to dispose the Task instance variable t ? If not , what is a safer way to implement this kind of functionality ? /// < summary > /// Web service operation to start a large batch asynchronously/// < /summary > public StartBatchResponseMessage StartBatch ( StartBatchRequestMessage request ) { Task t = Task.Factory.StartNew ( DoWork ) ; return new StartBatchResponseMessage ( ) ; } private void DoWork ( ) { // Implement solving world hunger here . }",What happens to a disposed Task ? "C_sharp : I have the following async code : The resul I expected would be to have a different thread id after the await and that new thread id having the unmodified system culture again.This is not happening ; the thread is indeed different from the previous , but the culture is somehow flowing from the previous thread.Why is it keeping the culture if I suggested with ConfigureAwait that I do n't need to keep the SynchronisationContext ? It is my understanding that the culture is not stored on the ExecutionContext therefore I am not sure why this is happening.This is a Console application.Full example code : https : //pastebin.com/raw/rE6vZ9Jm // Main system culture is English hereThread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo ( `` es '' ) ; WriteLine ( $ '' { Thread.CurrentThread.ManagedThreadId } : Culture : { Thread.CurrentThread.CurrentCulture } '' ) ; await Task.Delay ( 1 ) .ConfigureAwait ( false ) ; WriteLine ( $ '' { Thread.CurrentThread.ManagedThreadId } : Culture : { Thread.CurrentThread.CurrentCulture } '' ) ;",Why is the culture kept after ConfigureAwait ( false ) "C_sharp : Has anyone tried to create a new monodroid binding for version 3 of the Facebook sdk ? I 've been using the older version of the Facebook sdk created with Monodroid Facebook Binding . But the new Facebook sdk has almost all of those methods as deprecated.I 'm having trouble setting up the new binding , basically the com.facebook.android.Facebook class is now deprecated and the Facebook.Authorize is replaced with Session . I 'm able to create a jar file of the new facebook sdk , but the Session class is not showing up in the object browser in visual studio when looking at the .dll . The Session class is public and implements java.io.Serializable which is included in the Mono.Android reference . Any help or suggestions would be appreciated.edit : After messing around a few days with this I 'm able to get past this issue with a work around that does n't actually solve my problem , removing the node in Metadata.xml.This brings about other problems , which can be solved by adding some more < attr > tags.After building this attempt I got to a point where I was getting multiple errors in the GraphObject.SectionAndItem class.To get around those issues I removed the nodes associated with these issues.Now the binding is able to be built successfully . You 'd think that I would be able to build and deploy my application now , another issue arises . After adding the .jar file and the .dll file to my application I get these errors when building.I 'm at a loss now as how to proceed here . Any suggestions or comments to any of the steps to get to this spot ? < remove-node path= '' /api/package [ @ name='com.facebook ' ] /class [ @ name='Session.OpenRequest ' ] /method [ @ name='setPermissions ' ] '' / > < remove-node path= '' /api/package [ @ name='com.facebook.model ' ] /class [ @ name='PropertyName ' ] '' / > < attr path= '' /api/package [ @ name='com.facebook.widget ' ] /class [ @ name='GraphObjectAdapter ' ] '' name= '' visibility '' > public < /attr > < attr path= '' /api/package [ @ name='com.facebook.widget ' ] /class [ @ name='GraphObjectPagingLoader ' ] '' name= '' visibility '' > public < /attr > < attr path= '' /api/package [ @ name='com.facebook.widget ' ] /class [ @ name='FacebookFragment ' ] '' name= '' visibility '' > public < /attr > < attr path= '' /api/package [ @ name='com.facebook.widget ' ] /class [ @ name='SimpleGraphObjectCursor ' ] '' name= '' visibility '' > public < /attr > < attr path= '' /api/package [ @ name='com.facebook.widget ' ] /interface [ @ name='GraphObjectCursor ' ] '' name= '' visibility '' > public < /attr > Error 41 Argument 1 : can not convert from 'Com.Facebook.Widget.GraphObjectAdapter.SectionAndItem.Type ' to 'System.IntPtr ' E : \Android\FacebookBinding\FacebookBinding\FacebookBinding\obj\Debug\generated\src\Com.Facebook.Widget.GraphObjectAdapter.cs 345 64 FacebookBindingError 39 Operator ' ! = ' can not be applied to operands of type 'Com.Facebook.Widget.GraphObjectAdapter.SectionAndItem.Type ' and 'System.Type ' E : \Android\FacebookBinding\FacebookBinding\FacebookBinding\obj\Debug\generated\src\Com.Facebook.Widget.GraphObjectAdapter.cs 344 9 FacebookBindingError 47 Operator '== ' can not be applied to operands of type 'Com.Facebook.Widget.GraphObjectAdapter.SectionAndItem.Type ' and 'System.Type ' E : \Android\FacebookBinding\FacebookBinding\FacebookBinding\obj\Debug\generated\src\Com.Facebook.Widget.GraphObjectAdapter.cs 381 9 FacebookBindingError 40 The best overloaded method match for 'Android.Runtime.JNIEnv.CreateInstance ( System.IntPtr , string , params Android.Runtime.JValue [ ] ) ' has some invalid arguments E : \Android\FacebookBinding\FacebookBinding\FacebookBinding\obj\Debug\generated\src\Com.Facebook.Widget.GraphObjectAdapter.cs 345 17 FacebookBinding < remove-node path= '' /api/package [ @ name='com.facebook.widget ' ] /class [ @ name='GraphObjectAdapter.SectionAndItem ' ] '' / > < remove-node path= '' /api/package [ @ name='com.facebook.widget ' ] /class [ @ name='GraphObjectAdapter.SectionAndItem.Type ' ] '' / > Error 62 package com.facebook.widget.GraphObjectAdapter does not exist com.facebook.widget.GraphObjectAdapter.DataNeededListener E : \Android\FacebookBinding\FacebookBinding\FacebookTest\obj\Debug\android\src\mono\com\facebook\widget\GraphObjectAdapter_DataNeededListenerImplementor.java 8 41 FacebookTestError 63 package com.facebook.widget.GraphObjectPagingLoader does not exist com.facebook.widget.GraphObjectPagingLoader.OnErrorListener E : \Android\FacebookBinding\FacebookBinding\FacebookTest\obj\Debug\android\src\mono\com\facebook\widget\GraphObjectPagingLoader_OnErrorListenerImplementor.java 8 46 FacebookTest",Facebook v3 sdk monodroid binding "C_sharp : I 'm about to schedule quite a few tile updates , and noticed that the .Clear ( ) method does n't seem to work . It should 'Removes all updates and reverts to its default content as declared in the app 's manifest ' ( MSDN ) EDIT : Cheeky MS ! Under the documentation for that method it says : 'Note : This method does not stop periodic updates'Say I schedule 3000 updates ( not what I will be doing btw ! ) , after calling clear the count is still 3000 . The same question was asked here : TileUpdater.Clear ( ) not freeing up notifications quota , and the only recommendation was to manually remove each and one of the updates.I decided to test how much time that would take by using the StopWatch class , and it took a bit over 11 seconds , 18 seconds with the max amount of scheduled updates at 4096 , - so that solution seems a bit crazy.Since I wont schedule more than a few days ahead on hourly basis and probably use a background task with a maintenance trigger to add new ones I 'll be fine with the removal-loop . But I still hope I 'm doing something wrong here and that there is a better solution.So , do you know why .Clear ( ) does n't work , and what would the best alternative be ? Here is the code if you want to give this a try : private void Button_Click_1 ( object sender , RoutedEventArgs e ) { var updater = TileUpdateManager.CreateTileUpdaterForApplication ( ) ; updater.Clear ( ) ; var test = updater.GetScheduledTileNotifications ( ) ; var stopWatch = new Stopwatch ( ) ; stopWatch.Start ( ) ; foreach ( var update in test ) { updater.RemoveFromSchedule ( update ) ; } stopWatch.Stop ( ) ; var time = stopWatch.Elapsed ; notify.Text = String.Format ( `` { 0:00 } : { 1:00 } : { 2:00 } . { 3:00 } '' , time.Hours , time.Minutes , time.Seconds , time.Milliseconds / 10 ) ; for ( int i = 0 ; i < 4096 ; i++ ) { var wide = TileContentFactory.CreateTileWideText09 ( ) ; var square = TileContentFactory.CreateTileSquareText04 ( ) ; wide.TextHeading.Text = `` The heading '' ; wide.TextBodyWrap.Text = `` The body text for notification : `` + i ; square.TextBodyWrap.Text = `` The body text for notification : `` + i ; wide.SquareContent = square ; var tileNotification = new ScheduledTileNotification ( wide.GetXml ( ) , DateTime.Now.AddMinutes ( i + 1 ) ) ; updater.AddToSchedule ( tileNotification ) ; } }",Why does n't TileUpdater.Clear ( ) remove all updates ? "C_sharp : I have a c # application set up like so : Basically , most of my interfaces and a few concrete classes are found in the Domain assembly , with many of the concrete implementations found in the FileAccess assembly . The ConsoleApp assembly makes use of the Domain assembly with no references to the FileAccess assembly.I 've created an autofac FileAccess module to wire up FileAccess implementations with the Domain interfaces , along with any concrete classes directly inside the Domain assembly . My question is where to put this module . From a best practices perspective , should the module be in the FileAccess assembly ( which would require me adding a reference/dependency on the autofac assemblies ) or should it go in the ConsoleApp assembly ( which makes use of the module and already has an autofac dependency ) ? Or would a totally separate assembly that just has the given module make sense ? Thanks [ Assembly-ConsoleApp ] -- References -- > [ Assembly-Domain ] / [ Assembly-FileAccess ] -- References -- > -- -- -- -- -/",In which assembly should an customized Autofac module reside ? "C_sharp : Lets say we have the following model : Mapping : I want to get the ReadingOrder which has the orderId equal with 1 ( eg ) .But when I try a FirstOrDefault , the query returns null : If I get all of them and after apply a FirstOrDefault works , but its stupid : The method from repository has the following format : easy stuff , but not working . If I go for a normal property , like Id , all works as expected.Also , if I get the generated query from log and put it in sqlite , it runs successfully and the reading order is returned . Is there a bug in NHibernate ? Is a mapping problem ? Or is it a problem with SQLite ? public class ReadingOrder { public virtual int Id { get ; set ; } public virtual Order Order { get ; set ; } } Table ( `` db_ReadingOrder '' ) ; Id ( o = > o.Id ) .Column ( `` Id '' ) .GeneratedBy.Identity ( ) ; References ( o = > o.Order , `` OrderId '' ) ; var readingO = _repositoryFactory.GetRepository < ReadingOrder > ( ) .FirstOrDefault ( xz = > xz.Order.Id == 1 ) ; var readingOrderList1 = _repositoryFactory.GetRepository < ReadingOrder > ( ) .GetAll ( ) .FirstOrDefault ( xz = > xz.Order.Id == 1 ) ; public T FirstOrDefault ( Expression < Func < T , bool > > predicate ) { return _session.Query < T > ( ) .FirstOrDefault ( predicate ) ; }",FirstOrDefault returns null on foreign key "C_sharp : I have an Employee class which defined as this : This is my class implementation and usage : In the initialization above there is only 1 record that is off : Id = 1 , Name = `` Emp 1 '' and the WorkDate = 4/13/2016Now how can i get the id of an employee which has no day off throughout the week ( from April 11-17 ) ? Which is Id = 2A LINQ solution is far better but i dont know how to do it . UPDATEDTo avoid confusion of the object Employee i changed it to EmployeeScheduleThis is the implementationThe selected answer is still applicable . Employee { public int Id { get ; set ; } public string Name { get ; set ; } public DateTime WorkDate { get ; set ; } public bool isOff { get ; set ; } } List < Employee > workers = new List < Employee > ( ) { new Employee { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/11/2016 '' ) , IsOff = false } , new Employee { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/12/2016 '' ) , IsOff = false } , new Employee { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/13/2016 '' ) , IsOff = true } , new Employee { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/14/2016 '' ) , IsOff = false } , new Employee { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/15/2016 '' ) , IsOff = false } , new Employee { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/16/2016 '' ) , IsOff = false } , new Employee { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/17/2016 '' ) , IsOff = false } , new Employee { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/11/2016 '' ) , IsOff = false } , new Employee { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/12/2016 '' ) , IsOff = false } , new Employee { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/13/2016 '' ) , IsOff = false } , new Employee { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/14/2016 '' ) , IsOff = false } , new Employee { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/15/2016 '' ) , IsOff = false } , new Employee { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/16/2016 '' ) , IsOff = false } , new Employee { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/17/2016 '' ) , IsOff = false } , } ; class EmployeeSchedule { public int Id { get ; set ; } public string Name { get ; set ; } public DateTime WorkDate { get ; set ; } public bool isOff { get ; set ; } } List < EmployeeSchedule > workers = new List < EmployeeSchedule > ( ) { new EmployeeSchedule { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/11/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/12/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/13/2016 '' ) , IsOff = true } , new EmployeeSchedule { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/14/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/15/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/16/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 1 , Name = `` Emp 1 '' , WorkDate = Convert.ToDateTime ( `` 4/17/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/11/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/12/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/13/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/14/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/15/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/16/2016 '' ) , IsOff = false } , new EmployeeSchedule { Id = 2 , Name = `` Emp 2 '' , WorkDate = Convert.ToDateTime ( `` 4/17/2016 '' ) , IsOff = false } , } ;",Select records which has no day-off throughout the week in List < T > - C # "C_sharp : I 'm writing a visitor which transforms IQueryable query . It uses Aggregate method with seed null and then use some func to transform it . My problem is that this null is of type decimal ? . But I get an exceptionAfter some research I found that it 's Aggregate itself which is ruining my query : My problem is with Expression.Constant ( seed ) which is null and Expression.Constant transforms it into constant of type object : Thus my new decimal ? ( ) transforms into ( object ) null and I get this error.Is there any workaround for this ? It seems to be impossible to get fix in .net framework ( and even if it 's possible , it will be fixed in 4.7 or later ) . I ' l create a pull request for this however I 'm sure it wo n't be accepted . Code snippet to reproduce : 'Expression of type 'System.Object ' can not be used for parameter of type 'System.Nullable ` 1 [ System.Decimal ] ' of method 'System.Nullable ` 1 [ System.Decimal ] Aggregate [ Nullable ` 1 , Nullable ` 1 ] ( System.Linq.IQueryable ` 1 [ System.Nullable ` 1 [ System.Decimal ] ] , System.Nullable ` 1 [ System.Decimal ] , System.Linq.Expressions.Expression ` 1 [ System.Func ` 3 [ System.Nullable ` 1 [ System.Decimal ] , System.Nullable ` 1 [ System.Decimal ] , System.Nullable ` 1 [ System.Decimal ] ] ] ) '' public static TAccumulate Aggregate < TSource , TAccumulate > ( this IQueryable < TSource > source , TAccumulate seed , Expression < Func < TAccumulate , TSource , TAccumulate > > func ) { if ( source == null ) throw Error.ArgumentNull ( `` source '' ) ; if ( func == null ) throw Error.ArgumentNull ( `` func '' ) ; return source.Provider.Execute < TAccumulate > ( Expression.Call ( null , GetMethodInfo ( Queryable.Aggregate , source , seed , func ) , new Expression [ ] { source.Expression , Expression.Constant ( seed ) , Expression.Quote ( func ) } ) ) ; } public static ConstantExpression Constant ( object value ) { return ConstantExpression.Make ( value , value == null ? typeof ( object ) : value.GetType ( ) ) ; } var result = new int ? [ ] { 1 } .AsQueryable ( ) .Aggregate ( default ( int ? ) , ( a , b ) = > b ) ;",Queryable.Aggregate is not working with null values "C_sharp : I 'm trying to solve the biggest prime programming praxis problem in C # .The problem is simple , print out or write to file the number:257,885,161 − 1 ( which has 17,425,170 digits ) I have managed to solve it using the amazing GNU Multiple Precision Arithmetic Library through Emil Stevanof .Net wrapperEven if all the currently posted solutions use this library , to me it feels like cheating . Is there a way to solve this in managed code ? Ideas ? Suggestions ? PS : I have already tried using .Net 4.0 BigInteger but it never ends to compute ( I waited 5 minutes but it is already a lot compared to 50 seconds of the GMP solution ) . var num = BigInt.Power ( 2 , 57885161 ) - 1 ; File.WriteAllText ( `` biggestPrime.txt '' , num.ToString ( ) ) ;",Write the biggest prime "C_sharp : The code belows contains a simple LINQ query inside an immutable struct . It does not compile . Anonymous methods , lambda expressions , and query expressions inside structs can not access instance members of 'this ' . Consider copying 'this ' to a local variable outside the anonymous method , lambda expression or query expression and using the local instead.Does any one know why this is not allowed ? The fix the message suggests works fine : But is this standard practice ? Are there reasons for not having queries like this in structs ? ( In the bigger scheme of things making a copy does not worry me performance-wise as such ) . struct Point { static readonly List < /*enum*/ > NeighborIndexes ; //and other readonly fields ! public IEnumerable < FlatRhombPoint > GetEdges ( ) { return from neighborIndex in NeighborIndexes ; select GetEdge ( neighborIndex ) ; } } public IEnumerable < FlatRhombPoint > GetEdges ( ) { var thisCopy = this ; return from neighborIndex in NeighborIndexes ; select thisCopy.GetEdge ( neighborIndex ) ; }",Why do I have to copy `` this '' when using LINQ in a struct ( and is it OK if I do ) ? "C_sharp : I 've read several articles and questions/answers that conclude the best practice is to let the JIT compiler do all the optimization for inline function calls . Makes sense.What about inline variable declarations ? Does the compiler optimize these as well ? That is , will this : Have better performance than this : Of course I prefer the latter because it 's easier to read and debug , but I ca n't afford the performance degradation if it exists.Note : I have already identified this code as a bottleneck -- No need for retorts about premature optimization . : - ) Dim h = ( a + b + c ) / 2 'Half-Perimeter If maxEdgeLength / ( Math.Sqrt ( h * ( h - a ) * ( h - b ) * ( h - c ) ) / h ) < = MaximumTriangleAspectRatio Then 'Do stuff here . End If Dim perimeter = a + b + c 'Perimeter Dim h = perimeter / 2 'Half-Perimeter Dim area = Math.Sqrt ( h * ( h - a ) * ( h - b ) * ( h - c ) ) 'Heron 's forumula . Dim inradius = area / h Dim aspectRatio = maxEdgeLength / inradius If aspectRatio < = MaximumTriangleAspectRatio Then 'Do stuff here . End If",Does the JIT compiler optimize ( inline ) unnecessary variable declarations ? "C_sharp : When we create variable of enumeration type and assign it an enumeration value Since enum is value type so the value of developers is stored on stack which is returned by Members.HighlyQualified.Here we are clear that the value of developers is string which reference to the memory location of characters.Now , 1.If we cast Members.HighlyQualifed to an int then the value returned is 0.How it happens ? 2.What value is really stored on stack for an enumeration type ? enum Members { HighlyQualified , Qualified , Ordinary } class { static void Main ( ) { Members developers = Members.HighlyQualified ; Console.WriteLine ( developers ) ; //write out HighlyQualified } }",Enumeration type in c # "C_sharp : I 'm trying to understand how to build my own Android plugins for Android.I achieve to call static methods on my Java class ( the one created on AndroidStudio ) , but I really CA N'T call non-static methods . I check those links : https : //answers.unity.com/questions/884503/cant-call-non-static-method-in-androidjavaclass.htmlhttp : //leoncvlt.com/blog/a-primer-on-android-plugin-development-in-unity/https : //answers.unity.com/questions/1327186/how-to-get-intent-data-for-unity-to-use.htmlhow to call Non-static method from Unity Android Plugin ? But none works.I 'm trying to get the call from a button from Unity like : And my activity on Android looks like : My ADB is throwing this message : I 've also tried calling instead of UnityPlayer call it like : EDIT : This is my AndroidManifest.xmlBut does n't work either for non-static methods , it works only for static methods if I do pluginClass.CallStatic ( `` '' ) , any idea ? EDIT 2 : Taras Leskiv suggest to change UnityPlayer.Get toUnityPlayer.GetStatic , but then i get the follow error : error : java.lang.NoSuchMethodError : no non-static method with name='SayHi ' signature= ' ( ) V ' in class Ljava.lang.Object ; Proguard is not active . AndroidJavaClass UnityPlayer = new AndroidJavaClass ( `` com.unity3d.player.UnityPlayer '' ) ; AndroidJavaObject currentActivity = UnityPlayer.Get < AndroidJavaObject > ( `` currentActivity '' ) ; currentActivity.Call ( `` SayHi '' ) ; public class MainActivity extends UnityPlayerActivity { private static final String TAG = `` LibraryTest '' ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; Log.d ( TAG , `` Created ! `` ) ; } public void SayHi ( ) { Log.d ( TAG , `` HI_ '' ) ; } } AndroidJavaClass pluginClass = new AndroidJavaClass ( `` com.example.eric.librarytest.MainActivity '' ) ; < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < manifest xmlns : android= '' http : //schemas.android.com/apk/res/android '' package= '' com.example.eric.librarytest '' android : versionCode= '' 1 '' android : versionName= '' 1.0 '' > < uses-sdk android : minSdkVersion= '' 24 '' android : targetSdkVersion= '' 28 '' / > < application android : label= '' @ string/app_name '' > < activity android : name= '' com.example.eric.librarytest.MainActivity '' android : configChanges= '' fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen '' android : label= '' @ string/app_name '' > < intent-filter > < action android : name= '' android.intent.action.MAIN '' / > < category android : name= '' android.intent.category.LAUNCHER '' / > < /intent-filter > < /activity > < /application > < /manifest >",Call non-static methods on custom Unity Android Plugins "C_sharp : I am just wondering if these code blocks gets compiled into .dllI do n't think this one gets compiled at allNow what about these ? 1.2.3.EDIT : Sorry , I was talking about Visual Studio # if SOMETHING_UNDEFINED// some code - this is ignored by the compiler # endif if ( false ) { // some code - is this compiled ? } const bool F = false ; if ( F ) { // some code - is this compiled ? } bool F = false ; if ( F ) { // some code - is this compiled ? }",Does C # compile code inside an if ( false ) block ? "C_sharp : In my mind the ID field of a business object should be read-only ( public get and private set ) as by definition the ID will never change ( as it uniquely identifies a record in the database ) .This creates a problem when you create a new object ( ID not set yet ) , save it in the database through a stored procedure for example which returns the newly created ID then how do you store it back in the object if the ID property is read-only ? Example : How does the Save method ( which actually connects to the database to save the new employee ) update the EmployeeId property in the Employee object if this property is read-only ( which should be as the EmployeeId will never ever change once it 's created ) . It looks like the Id should be writable by the DAL and read-only for the rest of the world . How do you implement this especially if the DAL classes and the Business object ones are in different assemblies ? I do n't want to create a Save method in the Employee class as this class should have nothing to do with the database . Employee employee = new Employee ( ) ; employee.FirstName= '' John '' ; employee.LastName= '' Smith '' ; EmployeeDAL.Save ( employee ) ;",Should the ID in the business object be read-only or not ? "C_sharp : I have 2 assemblies : Assembly 1 : Assembly 2 : I know how to get this to work . I can either ask the MEF ( Managed Extensibility Framework ) for the object , or get it to export the correct IWeapon instead of just the object by name . Can MEF do the `` duck '' typing for me and return a proxy object if all the interface points are implemented ? interface IWeapon { int Might { get ; } } [ Export ( `` sword '' ) ] public class Sword : IWeapon { public int Might { get { return 10 ; } } } interface IWeapon { int Might { get ; } } var catalog = new AssemblyCatalog ( typeof ( Ninja.Sword ) .Assembly ) ; var container = new CompositionContainer ( catalog ) ; // not allowed to use the IWeapon def in assembly 2 var sword = container.GetExportedValue < IWeapon > ( `` sword '' ) ;",Does MEF ( Managed Extensibility Framework ) do `` duck '' typing ? "C_sharp : Simplification — I 've created an empty AWS Lambda project with .net CORE : This is the default empty lambda function project : I want to catch all exception in the app , globally.So I 've created a method that generates an exception , and added a global application handler : Complete code : The problem is that the exception is raised , but it never fires CurrentDomain_UnhandledExceptionQuestion : Is this the right way of catching global exceptions ? and why does n't CurrentDomain_UnhandledException invoked when there is an unhandled exception ? public class Function { void CreateException ( ) { var z = 0 ; var a = 2 / z ; Console.Write ( a ) ; } public Function ( ) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler ( CurrentDomain_UnhandledException ) ; } public void FunctionHandler ( object input , ILambdaContext context ) { CreateException ( ) ; } private void CurrentDomain_UnhandledException ( object sender , UnhandledExceptionEventArgs e ) { // � It never gets here } }",Global exception handler in AWS .net Core Lambda project ? "C_sharp : Consider the following code.Unless you have a fancy IDE ( that is doing all sorts lookups & static analysis behind the scenes ) it 's pretty ambiguous as to where `` Required '' & `` MaxLength '' actually come from . Especially when several namespaces might be imported , with similar meaning.As a relative newbie to C # I am finding myself always having a hard time figuring out where certain things come from . Especially when looking at other code snippets on places like StackOverflow.Now it 's very obvious where `` Required '' & `` MaxLength '' come from . You could take it another step and do something like : This is now very similar to how both PHP & Js ES6 works.I 'm curious as to why this is n't the default for C # ? And why pretty much every other C # dev I have spoken with considers alias 's bad practice ? Is there some underlying performance reason perhaps ? using System.ComponentModel.DataAnnotations ; namespace Foo { public class Bar { [ Required , MaxLength ( 250 ) ] public virtual string Name { get ; set ; } } } using DataAnnotations = System.ComponentModel.DataAnnotations ; namespace Foo { public class Bar { [ DataAnnotations.Required , DataAnnotations.MaxLength ( 250 ) ] public virtual string Name { get ; set ; } } } using Required = System.ComponentModel.DataAnnotations.RequiredAttribute ; using MaxLength = System.ComponentModel.DataAnnotations.MaxLengthAttribute ; namespace Foo { public class Bar { [ Required , MaxLength ( 250 ) ] public virtual string Name { get ; set ; } } }",Why C # `` using aliases '' are not used by default ? "C_sharp : This sentence can swap the value between a and b.I 've tried it with C # and it works.But I just do n't konw how it works.e.g.a = 1 , b = 2I list the steps of it as below : But the value of b may be wrong.Could anyone help me ? It puzzles me a lot . a=b+ ( b=a ) *0 ; b = a - > a = 1 , b = 1b * 0 - > a = 1 , b = 1b + 0 - > a = 1 , b = 1a = b - > a = 1 , b = 1 ?",Swap trick : a=b+ ( b=a ) *0 ; "C_sharp : I am newbie in C # and working for utility to verify topic ID content of help files.Following function is useful for me to launch help file : In case Help.ShowHelp ( ) function failed to launch .CHM ( Help file ) with provided CHM file and topic id , then i need to provide notification to user about launch failure.Following is pseudo code example : I search on web but unable to find function or return type/Parameter from ShowHelp ( ) which will notify failure of showHelp ( ) function.Following things are already tried : Since i am from MFC background i tried to find function related to GetLastError ( ) in C # . As a result getlastwin32error ( ) is suggested but not providing last error in failure conditionparameter or return type of Help.ShowHelp ( ) is not useful to find fail condition.Thanks for reading . Help.ShowHelp ( this , HelpFile.Text , HelpNavigator.TopicId , topicIDStr ) ; If Help.ShowHelp ( ) failed { Messagebox ( `` Failed to launch help '' ) }",ShowHelp function fail notification "C_sharp : The problem : There 's a ton of animals on a farm . Every animal can have any number of animal friends , except for the anti-social animals -- they do n't have friends that belong to them , but they belong to other normal animals as friends . Each animal is exactly as happy as it 's least happiest animal friend , except for the anti-social animals of course . The anti-social animals happiness ' levels can be anything.One morning all the animals wake up and find some of the anti-social animals mood 's have changed . How does the farmer figure out the happiness of each animal ? Here 's as far as the ranch hands got ( they did n't go to farmer school ) : But this will not work because the animal table does not sequentially follow the animal friend hierarchies that have formed . Animals can make friends with each other at any time ! So Animal ( 1 ) might have Animal ( 4000 ) as a friend . Animal ( 1 ) will not show an accurate mood because it will check Animal ( 4000 ) 's mood before Animal ( 4000 ) 's mood has been updated itself . And new animals are being dropped off everyday . I figure the solution might a common algorithm design , but I have n't been able to find it . I do n't believe I have the correct terminology to accurately search for it . Thanks a bunch and sorry if this has already been answered ! Added : Here 's a ghetto Paint chart of possible relationships : The anti-social animals are at the bottom level and have no friends belonging to them . The normal animals are everywhere else above . There is no exact structure to the normal animal friendships , except ( as Sebastian pointed out ) there ca n't be a closed loop ( if designed correctly ) . There will be hundred 's of thousands of animals added weekly and processing speed is a critical element . DataTable animals = Select_All_Animals ( ) ; foreach ( DataRow animal in animals.Rows ) { int worstMood = 10 ; //Super Happy ! DataTable friendRecords = Select_Comp_Animal_AnimalFriend ( ( int ) animal [ `` AnimalID '' ] ) ; foreach ( DataRow friend in friendRecords.Rows ) { DataTable animalFriends = Select_AnimalFriend ( ( int ) friend [ `` AnimalID_Friend '' ] ) ; foreach ( DataRow animalFriend in animalFriends.Rows ) { int animalMood = Get_Animal_Mood ( ( int ) animalFriend [ `` Mood '' ] ) ; if ( animalMood < worstMood ) { worstMood = animalMood ; } } } }",Farmer needs algorithm for looping through self-referencing animal table "C_sharp : First , let me apologize for asking a question that may seem a bit vague ( or badly formalized ) , but I lack experience to ask anything more specific.I 'm building an engine for playing 2D adventure games ( the you-click-on-an-object-and-something-happens sort ) in C # and I 'm considering the best structure for it . As you can imagine , different things can happen when you interact with an object : if it 's a door , you expect to enter another room , if it 's a person , you expect to start talking to them , etc . My idea is to achieve this behaviour with delegates , like this : I find this solution quite elegant , because if I want to create a special object with some behaviour not covered by its class , I can simply do this : But this is also where things get complicated . I want my engine to be capable of playing different games simply by loading different data , without changes to the engine itself , so hard-coding the SpecialMethod somewhere inside the engine is not an option , it must be part of the data . For normal object , it can all be done with ( de ) serialization , but from what I 've read , this is problematic with delegates . Can you suggest a way to do it ? P.S . : Since I 'm still on the concept level and the code above is not yet implemented , you are free to suggest whatever solution you find best , even one that avoids delegates completely . public abstract class GameObject { public delegate void onAction ( ) ; public onAction Click ; } public class Door : GameObject { public Door ( ) { Click = new onAction ( ChangeRoom ) ; } private void ChangeRoom ( ) { //code to change room here } } public class Person : GameObject { public Person ( ) { Click = new onAction ( StartTalking ) ; } private void StartTalking ( ) { //code to display dialogue here } } specialObject.Click += new onAction ( SpecialMethod ) ;",C # Structure for objects in a 2D game "C_sharp : I am having a global Exception handler in my web api project . This works fine except when the exception is raised through a lambda expression . I have provided a sample code below : This is my global Exception HandlerI register it in my WebApiConfig class [ HttpGet ] public IHttpActionResult Test ( ) { //Throw new Exception ( ) ; // this exception is handled by my ExceptionHandler var list = new List < int > ( ) ; list.Add ( 1 ) ; IEnumerable < int > result = list.Select ( a = > GetData ( a ) ) ; return Ok ( result ) ; } private static int GetData ( int a ) { throw new Exception ( ) ; //This is not handled by my global exception handler } public class ExceptionHandlerAttribute : ExceptionFilterAttribute { public override void OnException ( HttpActionExecutedContext context ) { //Do something } } public static class WebApiConfig { public static void Register ( HttpConfiguration config ) { config.Routes.MapHttpRoute ( name : `` DefaultApi '' , routeTemplate : `` api/ { controller } / { action } / { id } '' , defaults : new { action = `` Get '' , id = RouteParameter.Optional } ) ; config.Filters.Add ( new ExceptionHandlerAttribute ( ) ) ; } }",How to globally handle exceptions in asp.net web api when exception is raised through lambda expression "C_sharp : So I 've been told what I 'm doing here is wrong , but I 'm not sure why.I have a webpage that imports a CSV file with document numbers to perform an expensive operation on . I 've put the expensive operation into a background thread to prevent it from blocking the application . Here 's what I have in a nutshell . ( obviously with some error checking & messages for users thrown in ) So my three-fold question is : a ) Is this a bad idea ? b ) Why is this a bad idea ? c ) What would you do instead ? protected void ButtonUpload_Click ( object sender , EventArgs e ) { if ( FileUploadCSV.HasFile ) { string fileText ; using ( var sr = new StreamReader ( FileUploadCSV.FileContent ) ) { fileText = sr.ReadToEnd ( ) ; } var documentNumbers = fileText.Split ( new [ ] { ' , ' , '\n ' , '\r ' } , StringSplitOptions.RemoveEmptyEntries ) ; ThreadStart threadStart = ( ) = > AnotherClass.ExpensiveOperation ( documentNumbers ) ; var thread = new Thread ( threadStart ) { IsBackground = true } ; thread.Start ( ) ; } }",Are background threads a bad idea ? Why ? "C_sharp : Created a simple calculator app in webforms.User enters a number in a text field MainContent_numberTb and clicks on results button . Added a new 'coded UI Test Project ' to my solution . Have tested the UI by adding ' 5 ' , This all works fine . Would now like to compare the actual result against the expected result.All above code works fine , problem occurs when trying to access the labelWhat do I insert beside control type ? It 's not edit as edit is the text field . Then also , what stores the actual result so I can compare AllNumsTB ? UPDATEOK so using the debugger console I was able to get the value of the label using ( ( Microsoft.VisualStudio.TestTools.UITesting.HtmlControls.HtmlSpan ) new System.Collections.ArrayList.ArrayListDebugView ( ( ( System.Collections.CollectionBase ) ( AllNumsTB.FindMatchingControls ( ) ) .List ) .InnerList ) .Items [ 0 ] ) .DisplayTextbut when I use this in the code & ArrayListDebugView are inaccessible due to protection ? ? //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////UPDATEThanks K Scandrett for the answer ... If I may I was wondering could you also please help me with the validation ... If the user enters a letter or a non positive number the error message will fire..This all works fine , however I want to test if the label appears or not ... so far I have triedbut they all return true even when the label is not shown , but it is still on the page just set to invisible . In that case I should check its style..something like then check if the style contains visibility : visible ? BrowserWindow Browser = BrowserWindow.Launch ( `` http : //url '' ) ; UITestControl UiInputField = new UITestControl ( Browser ) ; UiInputField.TechnologyName = `` Web '' ; UiInputField.SearchProperties.Add ( `` ControlType '' , `` Edit '' ) ; UiInputField.SearchProperties.Add ( `` Id '' , `` MainContent_numberTb '' ) ; //Populate input fieldKeyboard.SendKeys ( UiInputField , `` 5 '' ) ; //Results ButtonUITestControl ResultsBtn = new UITestControl ( Browser ) ; ResultsBtn.TechnologyName = `` Web '' ; ResultsBtn.SearchProperties.Add ( `` ControlType '' , `` Button '' ) ; ResultsBtn.SearchProperties.Add ( `` Id '' , `` MainContent_calBtn '' ) ; Mouse.Click ( ResultsBtn ) ; < asp : Label ID= '' AllNumLbl_Res '' runat= '' server '' > < /asp : Label > string expectedAllNums = `` 1 , 2 , 3 , 4 , 5 '' ; UITestControl AllNumsTB = new UITestControl ( Browser ) ; AllNumsTB.TechnologyName = `` Web '' ; AllNumsTB.SearchProperties.Add ( `` ControlType '' , `` ? ? ? ? ? `` ) ; AllNumsTB.SearchProperties.Add ( `` Id '' , `` MainContent_AllNumLbl_Res '' ) ; if ( expectedAllNums ! = AllNumsTB. ? ? ? ? ? ? ) { Assert.Fail ( `` Wrong Answer '' ) ; } < asp : RegularExpressionValidator ID= '' regexpName '' //VALIDATION MESSAGE UITestControl PositiveNumValMsg = new UITestControl ( Browser ) ; PositiveNumValMsg.TechnologyName = `` Web '' ; PositiveNumValMsg.SearchProperties.Add ( `` Id '' , `` MainContent_regexpName '' ) ; //bool visible = false ; //System.Drawing.Point p ; //// If the control is offscreen , bring it into the viewport //PositiveNumValMsg.EnsureClickable ( ) ; // // Now check the coordinates of the clickable point // visible = PositiveNumValMsg.TryGetClickablePoint ( out p ) // & & ( p.X > 0 || p.Y > 0 ) ; var isVisible = PositiveNumValMsg.WaitForControlPropertyNotEqual ( UITestControl.PropertyNames.State , ControlStates.Invisible ) ; //string labelText3 = PositiveNumValMsg.GetProperty ( `` style '' ) .ToString ( ) ;","coded ui test project , obtain value of asp label" C_sharp : We are using the domain events pattern and leaning on our IoC container to locate handlers for a particular type of event : With StructureMap we can scan and register all types implementing the above interface like so : Is there an equivalent with Ninject ? Currently I 'm having to bind each handler individually like so : public interface IHandleEvent < TEvent > where TEvent : IEvent { void Handle ( TEvent evnt ) ; } Scan ( cfg = > { cfg.TheCallingAssembly ( ) ; cfg.ConnectImplementationsToTypesClosing ( typeof ( IHandleEvent < > ) ) ; } ) ; kernel.Bind < IHandleEvent < SomeEvent > > ( ) .To < EventHandler1 > ( ) ; kernel.Bind < IHandleEvent < SomeEvent > > ( ) .To < EventHandler2 > ( ) ; kernel.Bind < IHandleEvent < SomeOtherEvent > > ( ) .To < EventHandler3 > ( ) ;,How to scan for all implementations of a generic type with Ninject "C_sharp : I am trying do create a Textbox in Wpf that has a Label in its top left corner and addiotionally this label shall have a border with a slope on one side.http : //imgur.com/NupbfNow for one or two specific cases that was doable with a workaround where i just used lines for the border . Now that i want to use it a bit more I need to do it the right way , especially in a way where it is scalable.I would be really happy if someone could point me in the right direction.Edit : So the code I am using after taking into account the responses so far , which i created as a user control : It works and the only thing that is still bothering me is the resizability of the label border , which is quite annoying to do but luckily not necessary in my case . < Grid Height= '' 93 '' Width= '' 335 '' > < TextBox TextWrapping= '' Wrap '' Text= '' { Binding TextboxText } '' HorizontalContentAlignment= '' Center '' VerticalContentAlignment= '' Center '' BorderBrush= '' { x : Null } '' Background= '' { x : Null } '' / > < Path Data= '' M384,242 L442.5,242 '' HorizontalAlignment= '' Left '' Height= '' 1 '' Margin= '' 0,28.667,0,0 '' Stretch= '' Fill '' VerticalAlignment= '' Top '' Width= '' 59.5 '' > < Path.Fill > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' # 8EFFFFFF '' / > < GradientStop Color= '' White '' Offset= '' 0.991 '' / > < /LinearGradientBrush > < /Path.Fill > < Path.Stroke > < LinearGradientBrush EndPoint= '' 0.5,1 '' MappingMode= '' RelativeToBoundingBox '' StartPoint= '' 0.5,0 '' > < LinearGradientBrush.RelativeTransform > < TransformGroup > < ScaleTransform CenterY= '' 0.5 '' CenterX= '' 0.5 '' / > < SkewTransform CenterY= '' 0.5 '' CenterX= '' 0.5 '' / > < RotateTransform Angle= '' 90 '' CenterY= '' 0.5 '' CenterX= '' 0.5 '' / > < TranslateTransform/ > < /TransformGroup > < /LinearGradientBrush.RelativeTransform > < GradientStop Color= '' White '' Offset= '' 0.009 '' / > < GradientStop Color= '' # 5FFFFFFF '' Offset= '' 1 '' / > < /LinearGradientBrush > < /Path.Stroke > < /Path > < Label Content= '' { Binding LabelText } '' HorizontalAlignment= '' Left '' Width= '' 113 '' FontSize= '' 16 '' Height= '' 40 '' VerticalAlignment= '' Top '' BorderBrush= '' White '' Margin= '' 0,0.167,0,0 '' / > < Path Data= '' M125.12574,28.672087 L145.37561 , -1.1668457 '' HorizontalAlignment= '' Left '' Height= '' 30.839 '' Margin= '' 58.125 , -1,0,0 '' Stretch= '' Fill '' VerticalAlignment= '' Top '' Width= '' 21.25 '' > < Path.Stroke > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' # 51FFFFFF '' Offset= '' 0 '' / > < GradientStop Color= '' White '' Offset= '' 1 '' / > < /LinearGradientBrush > < /Path.Stroke > < Path.Fill > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' # 49FFFFFF '' Offset= '' 0 '' / > < GradientStop Color= '' White '' Offset= '' 1 '' / > < /LinearGradientBrush > < /Path.Fill > < /Path > < Path Data= '' M0,83 L181.35815,83 '' Fill= '' # FFF4F4F5 '' Height= '' 1 '' Stretch= '' Fill '' VerticalAlignment= '' Bottom '' Width= '' 327 '' StrokeThickness= '' 2 '' Margin= '' 0,0,10,10 '' > < Path.Stroke > < LinearGradientBrush EndPoint= '' 0.5,1 '' StartPoint= '' 0.5,0 '' > < GradientStop Color= '' Black '' Offset= '' 0 '' / > < GradientStop Color= '' White '' Offset= '' 1 '' / > < /LinearGradientBrush > < /Path.Stroke > < /Path > < /Grid >",How to create a Textbox and Label with sloped border ? "C_sharp : I am trying to convert C # email regular expression , which I have taken from MSDN samplewhich is like this : but I am getting error for : ? : Invalid target for qualifier . ? < = : Lookbehind is not supported in JavaScriptI have need help in converting above Regex @ '' ^ ( ? ( `` '' ) ( `` '' .+ ? ( ? < ! \\ ) '' '' @ ) | ( ( [ 0-9a-z ] ( ( \. ( ? ! \ . ) ) | [ - ! # \ $ % & '\*\+/=\ ? \^ ` \ { \ } \|~\w ] ) * ) ( ? < = [ 0-9a-z ] ) @ ) ) ( ? ( \ [ ) ( \ [ ( \d { 1,3 } \. ) { 3 } \d { 1,3 } \ ] ) | ( ( [ 0-9a-z ] [ -\w ] * [ 0-9a-z ] *\ . ) + [ a-z0-9 ] [ \-a-z0-9 ] { 0,22 } [ a-z0-9 ] ) ) $ '' ^ ( ? ( `` ) ( `` .+ ? '' @ ) | ( ( [ 0-9a-zA-Z ] ( ( \. ( ? ! \. ) ) | [ ^ ! # \ $ % & \s'\*/=\ ? \^ ` \ { \ } \|~ ] ) * ) ( ? < = [ -+0-9a-zA-Z_ ] ) @ ) ) ( ? ( \ [ ) ( \ [ ( \d { 1,3 } \. ) { 3 } \d { 1,3 } \ ] ) | ( ( [ 0-9a-zA-Z ] [ -\w ] * [ 0-9a-zA-Z ] *\ . ) + [ a-zA-Z ] { 2,6 } ) ) $",Regex - Invalid target for quantifier which converting C # Regex to JavaScript Regex "C_sharp : I can successfully inject dependencies into my ServiceStack services but now I have a need to inject a dependency into a Request Filter . However this does not appear to work the same way.Here 's my filter ( it simply checks whether the source IP is in an approved list ; it is this list I 'm trying to inject ) : This is what 's in my global.asax : _IPAddresses is always null.I guess I must be missing something basic here . Is there a better way of approaching this ? public class CheckIPFilter : RequestFilterAttribute { private readonly IList < string > _IPAddresses = new List < string > ( ) ; public CheckIPFilter ( ) { } public CheckIPFilter ( IList < string > IPAddresses ) { _IPAddresses = IPAddresses ; } public override void Execute ( ServiceStack.ServiceHost.IHttpRequest req , ServiceStack.ServiceHost.IHttpResponse res , object requestDto ) { if ( ! _IPAddresses.Contains ( req.UserHostAddress ) ) { var errResponse = DtoUtils.CreateErrorResponse ( `` 401 '' , `` Unauthorised '' , null ) ; var responseDto = DtoUtils.CreateResponseDto ( requestDto , new ResponseStatus ( `` 401 '' , `` Unauthorised '' ) ) ; var contentType = req.ResponseContentType ; var serializer = EndpointHost.AppHost.ContentTypeFilters.GetResponseSerializer ( contentType ) ; res.ContentType = contentType ; var serializationContext = new HttpRequestContext ( req , res , responseDto ) ; serializer ( serializationContext , responseDto , res ) ; res.EndRequest ( ) ; //stops further execution of this request return ; } } } var IPAddresses = new List < string > ( ) { `` 99.99.99.99 '' , `` 99.99.99.99 '' , `` 99.99.99.99 '' , `` 99.99.99.99 '' } ; container.Register < IList < string > > ( IPAddresses ) ;",Can I inject a dependency into a ServiceStack Request Filter ? "C_sharp : Given : Is this done synchronously ? ( i.e . can two quick instantiations of MyClass cause CreateDictionary ( ) to be called twice ? public class MyClass { private static readonly Dictionary < string , int > mydict = CreateDictionary ( ) ; private static Dictionary < string , int > CreateDictionary ( ) { ... } }","If a static readonly member calls a static method to get a value , is it done synchronously ?" "C_sharp : I have recently added a window to my WPF application which can be docked to an edge of the desktop as an `` app bar '' . The code I 'm using to do the docking came from this stackoverflow post.The program has three user settings defined related to this window . One is the edge where the window is docked , the other two are the values of the Left & Top properties . The idea is that when the window is closed , or the program is shut down , the window will open back in the same state and location when the program restarts.The problem I 'm having is that when the program opens up , the window is first displayed at a random location on the screen ( probably the coordinates assigned to it by Windows when the window is created ) and then it moves into the docked position . Other programs I 've seen that have the app bar functionality , like Trillian , are drawn in the docked position from the beginning . It 's a little disconcerting to see the window move like that.Here is some code from the window : I have added functions to call SHAppBarrMessage when the window is activated , or when its position and size change , as I read in this acrticle . The calls do n't seem to have any effect on the behavior , so I might remove them.I know that the SourceInitialized and Loading events are called before the window is displayed but after the window handle and the layout & measure passes have been completed . It appears , though , that the window is rendered before the call to AppBarFunctions.SetAppBar is made , which is why I see it appear and then move into place.I 've also tried to move the window into the docked position by setting the Left and Top properties to the values saved in the settings in the window 's constructor . That did n't work , either . In fact , it was worse , as the window was first drawn in the docked position , then apparently was moved away from that desktop edge to make room for it , and then moved back into the docked location.How do I get this window to appear in the docked position upon start up and not move afterward ? Edit : I think I have found the cause of the problem . There is a comment in the AppBarFunctions class code , in the ABSetPos method , just before it schedules a call to the DoResize method on the window 's Dispatcher ( UI thread ) . The comment reads : So apparently WPF or Windows is moving the window out of the space being reserved for the window , and I then move it back in . I added a lot of trace points in my code & I can see that the window is n't rendered until after that move is made ( the one mentioned in the comment in the code ) . After the window is rendered , it is moved into the docked position by my code.The AppBarFunctions class already adds a window procedure hook for wathcing for messages from the shell . If I add a check for WM_WINDOWPOSCHANGED , could I somehow stop the message from being processed ? Or maybe I can change the values for the Left and Top properties for the move done by Windows / WPF so the window ends up where I want it to be ? private void AppBarWindow_Activated ( object sender , EventArgs e ) { if ( Settings.Default.AppBarWindowEdge ! = ABEdge.None ) { AppBarFunctions.SendShellActivated ( this ) ; } } private void AppBarWindow_Closing ( object sender , CancelEventArgs e ) { Settings.Default.AppBarWindowLeft = Left ; Settings.Default.AppBarWindowTop = Top ; Settings.Default.Save ( ) ; AppBarFunctions.SetAppBar ( this , ABEdge.None ) ; // Other , app specific code . . . } private void AppBarWindow_LocationChanged ( object sender , EventArgs e ) { if ( Settings.Default.AppBarWindowEdge ! = ABEdge.None ) { AppBarFunctions.SendShellWindowPosChanged ( this ) ; } } private void AppBarWindow_SourceInitialized ( object sender , EventArgs e ) { if ( Settings.Default.AppBarWindowEdge ! = ABEdge.None ) { SizeWindow ( Settings.Default.AppBarWindowEdge == ABEdge.None ? ABEdge.Left : ABEdge.None ) ; } } private void AppBarWindow_SizeChanged ( object sender , SizeChangedEventArgs e ) { if ( Settings.Default.AppBarWindowEdge ! = ABEdge.None ) { AppBarFunctions.SendShellWindowPosChanged ( this ) ; } } private void SizeWindow ( ABEdge originalEdge ) { // App specific code to compute the window 's size . . . if ( originalEdge ! = Settings.Default.AppBarWindowEdge ) { AppBarFunctions.SetAppBar ( this , Settings.Default.AppBarWindowEdge ) ; } Settings.Default.AppBarWindowLeft = Left ; Settings.Default.AppBarWindowTop = Top ; Settings.Default.Save ( ) ; } // This is done async , because WPF will send a resize after a new appbar is added . // if we size right away , WPFs resize comes last and overrides us .","App Bar Window pops away from docking postion , then moves into the docking position" "C_sharp : So I 'm working on some legacy code that 's heavy on the manual database operations . I 'm trying to maintain some semblance of quality here , so I 'm going TDD as much as possible.The code I 'm working on needs to populate , let 's say a List < Foo > from a DataReader that returns all the fields required for a functioning Foo . However , if I want to verify that the code in fact returns one list item per one database row , I 'm writing test code that looks something like this : Which is rather tedious and rather easily broken , too . How should I be approaching this issue so that the result wo n't be a huge mess of brittle tests ? Btw I 'm currently using Rhino.Mocks for this , but I can change it if the result is convincing enough . Just as long as the alternative is n't TypeMock , because their EULA was a bit too scary for my tastes last I checked.Edit : I 'm also currently limited to C # 2 . Expect.Call ( reader.Read ( ) ) .Return ( true ) ; Expect.Call ( reader [ `` foo_id '' ] ) .Return ( ( long ) 1 ) ; // ... .Expect.Call ( reader.Read ( ) ) .Return ( true ) ; Expect.Call ( reader [ `` foo_id '' ] ) .Return ( ( long ) 2 ) ; // ... .Expect.Call ( reader.Read ( ) ) .Return ( false ) ;",How should I test a method that populates a list from a DataReader ? "C_sharp : I 'm trying to use the GetGroups method of UserPrincipal . If the User account is in an OU that contains a forward slash , the call to GetGroups fails with the COM Unknown Error 0x80005000 . The user account is found just find and I can access other properties . If I remove the slash in the OU name then everything works . I found a reference to escaping the slash in the name but that 's wrapped under the GetGroups method . I also found making sure to use the PrincipalContext ( ContextType , String ) constructor which I 've done . I 've also tried using the FQDN with an escaped slash and get the same results . I have some example code below in C # : I 'm using Visual Studio 2012 . The code is running on Windows 10 Enterprise x64 . The .net Target version is 4.5Ultimately I just replace any of these types of special characters in the OU name because that 's by far the easiest solution . I 'm mainly just curious about making sure the code I 'm writing does n't explode down the road . using System ; using System.Linq ; using System.DirectoryServices.AccountManagement ; string SamAccountName = `` user1 '' ; //The OUs the user is in : //Broken OU : `` OU=Test / Test , DC=contoso , DC=com '' //Working OU : `` OU=Test & Test , DC=contoso , DC=com '' PrincipalContext domainContext = new PrincipalContext ( ContextType.Domain , Environment.UserDomainName ) ; UserPrincipal user = UserPrincipal.FindByIdentity ( domainContext , IdentityType.SamAccountName , SamAccountName ) ; //The user was found so this worksConsole.WriteLine ( `` User Found : { 0 } '' , user.DistinguishedName ) ; //This causes COM Exception : Unknown Error 0x80005000 string output = string.Join ( Environment.NewLine , user.GetGroups ( ) .Select ( x = > x.Name ) .ToArray ( ) ) ; Console.WriteLine ( output ) ;",0x80005000 Unknown Error on UserPrincipal.GetGroups with Special Characters in OU "C_sharp : I have tried to create a switch expression with System.Linq.Expressions : but in the last line I get an ArgumentException : Non-empty collection required . Parameter name : casesWhat is the reason of this exception ? May be this a bug in Expression.Switch ( … ) ? In a C # a switch with `` default '' part only is correct : UPD : I have submitted an issue to the CoreFX repo on GitHub var value = Expression.Parameter ( typeof ( int ) ) ; var defaultBody = Expression.Constant ( 0 ) ; var cases1 = new [ ] { Expression.SwitchCase ( Expression.Constant ( 1 ) , Expression.Constant ( 1 ) ) , } ; var cases2 = new SwitchCase [ 0 ] ; var switch1 = Expression.Switch ( value , defaultBody , cases1 ) ; var switch2 = Expression.Switch ( value , defaultBody , cases2 ) ; switch ( expr ) { default : return 0 ; } //switch",Switch without cases ( but with default ) in System.Linq.Expressions "C_sharp : Refactoring some code again . Seeing some of this in one of the ASP.NET pages : There is no need to dispose txtBox , because it 's just a reference to an existing control . And you do n't want the control disposed at all . I 'm not even sure this is n't harmful - like it would appear to ask for the underlying control to be disposed inappropriately ( although I have not yet seen any ill effects from it being used this way ) . using ( TextBox txtBox = e.Row.Cells [ 1 ] .FindControl ( `` txtBox '' ) as TextBox ) { }",Why would you use the using statement this way in ASP.NET ? C_sharp : so what is the point in this method ? string s = `` string '' ; Console.WriteLine ( s [ 1 ] ) ; // returns tchar [ ] chars = s.ToCharArray ( ) ; Console.WriteLine ( chars [ 1 ] ) ; // also returns t,What 's the point using String.ToCharArray if a string is a char array itself ? "C_sharp : Are these 2 samples the same ? Can old-style raising be replaced with Invoke and null propagation ? OLD : NEW : Null check is important but it is clear . What is about additional variable ? How does null-propogation work internally ? Is it thread-safe with events ? P.S . Regarding thread safety in events you can read here : C # Events and Thread Safety public event EventHandler < MyEventArgs > MyEvent ; protected virtual void OnMyEvent ( MyEventArgs args ) { EventHandler < MyEventArgs > handler = this.MyEvent ; if ( handler ! = null ) handler ( this , args ) ; } public event EventHandler < MyEventArgs > MyEvent ; protected virtual void OnMyEvent ( MyEventArgs args ) { this.MyEvent ? .Invoke ( this , args ) ; }",Thread-safety of event raising with null propagation "C_sharp : I 'm currently working on a small project involving a Kinect with the OpenNI C # wrapper . For this project a depth , image and user node are created using an xml configuration file and the Context.CreateFromXmlFile method . A separate thread is started which does a very simple loop ( based on the UserTracker.net example ) : This works just fine for a while , until the image the camera receives does n't change . After a short while the following exception is shown : After this exception is thrown all subsequent calls to context.WaitAnyUpdateAll will throw the same exception , regardless of what the input is . After a while the error message changes to : How can I deal with no new input using OpenNI ? I understand that we get a timeout exception when no new data is available , but how can we recover from this exception ? private void RunThread ( ) { while ( true ) { try { context.WaitAnyUpdateAll ( ) ; //context is an OpenNI context object . } catch ( Exception ex ) { Console.WriteLine ( ex.ToString ( ) ) ; } //process some data } } A timeout has occured when waiting for new data ! at OpenNI.Context.WaitAnyUpdateAll ( ) at < file described above > OpenNI.StatusException : The server has disconnected ! at OpenNI.Context.WaitAnyUpdateAll ( ) at < file described above >",OpenNI C # wrapper : WaitAnyUpdateAll timeout "C_sharp : When reading a comment to an answer I saw the following construct to declare and initialize a variable : Is this allowed , correct and well defined in C # ? What happens under the hood ? Is the following what happens ? Is variable first initialized to zero ? then passed to int.TryParse ( which assigns a value ) ? then optionally read ( if int.TryParse return true ) ? and then , once again assigned/initialized ? int variable = int.TryParse ( stringValue , out variable ) ? variable : 0 ;",Using a variable as an out argument at point of declaration "C_sharp : I 've recently implemented a QuickSort algorithm in C # . Sorting on an integer array containing millions of items , the code 's performance is approximately 10 % behind .NET 's implementation . On an array of 5 million items , this code is about 60ms slower than .NET's.Subsequently , I created an another method that has the Partition ( ) method inlined into QS ( ) ( eliminating the method call and the return statement ) . This however resulted in a drop in perfomance to about 250ms slower than .NET 's sort method.Why does this happen ? Edit : This is the code the Partition ( ) method . In the inlined version of QS ( ) , the entire content of this method with the exception of the return statement replaces the var pIndex = Partition ( arr , left , right ) ; line.Edit # 2 : In case anyone 's interested in compiling , here 's the code that calls the algorithms : Edit # 3 : New test code from Haymo 's suggestion . private static void QS ( int [ ] arr , int left , int right ) { if ( left > = right ) return ; var pIndex = Partition ( arr , left , right ) ; QS ( arr , left , pIndex ) ; QS ( arr , pIndex + 1 , right ) ; } private static int Partition ( int [ ] arr , int left , int right ) { int pivot = arr [ left ] ; int leftPoint = left - 1 ; int pIndex = right + 1 ; int temp = 0 ; while ( true ) { do { pIndex -- ; } while ( arr [ pIndex ] > pivot ) ; do { leftPoint++ ; } while ( arr [ leftPoint ] < pivot ) ; if ( leftPoint < pIndex ) { temp = arr [ leftPoint ] ; arr [ leftPoint ] = arr [ pIndex ] ; arr [ pIndex ] = temp ; } else { break ; } } return pIndex ; } private static void Main ( string [ ] args ) { const int globalRuns = 10 ; const int localRuns = 1000 ; var source = Enumerable.Range ( 1 , 200000 ) .OrderBy ( n = > Guid.NewGuid ( ) ) .ToArray ( ) ; var a = new int [ source.Length ] ; int start , end , total ; for ( int z = 0 ; z < globalRuns ; z++ ) { Console.WriteLine ( `` Run # { 0 } '' , z+1 ) ; total = 0 ; for ( int i = 0 ; i < localRuns ; i++ ) { Array.Copy ( source , a , source.Length ) ; start = Environment.TickCount ; Array.Sort ( a ) ; end = Environment.TickCount ; total += end - start ; } Console.WriteLine ( `` { 0 } \t\tTtl : { 1 } ms\tAvg : { 2 } ms '' , `` .NET '' , total , total / localRuns ) ; total = 0 ; for ( int i = 0 ; i < localRuns ; i++ ) { Array.Copy ( source , a , source.Length ) ; start = Environment.TickCount ; Quicksort.SortInline ( a ) ; end = Environment.TickCount ; total += end - start ; } Console.WriteLine ( `` { 0 } \t\tTtl : { 1 } ms\tAvg : { 2 } ms '' , `` Inlined '' , total , total / localRuns ) ; total = 0 ; for ( int i = 0 ; i < localRuns ; i++ ) { Array.Copy ( source , a , source.Length ) ; start = Environment.TickCount ; Quicksort.SortNonInline ( a ) ; end = Environment.TickCount ; total += end - start ; } Console.WriteLine ( `` { 0 } \tTtl : { 1 } ms\tAvg : { 2 } ms\n '' , `` Not inlined '' , total , total / localRuns ) ; } }",Cost of inlining methods in C # "C_sharp : I have noticed a following behaviour . Console output messages appear in an incorrect folder when they are populated by IProgress.I am trying to improve my encapsulation , reusability and design skills.So , I have a class called IdRecounter . I want to use it in a console app for now , but later on perhaps in a WPF app or whatever.Therefore , I want the class to be completely unaware of it 's environment - but at the same time I want to report progress of action 'live ' - therefore , I am using the IProgress type , which will allow me to put stuff into console , or into a log file , or update a status label property etc . ( Please let me know if that 's not how you do it ) So , I have noticed that it tends to throw messages into console in an incorrect order , e.g.Processing File 1Processing File 4Processing File 5Processing File 3All done ! Processing File 2When I switched IProgress ( MyProgress.Report ( ) ) with Console.WriteLine ( ) it works as expected.What is the reason of that and how can it be controlled ? Thanks var recounter = new IdRecounter ( filePath , new Progress < string > ( Console.WriteLine ) ) ; recounter.RecalculateIds ( ) ;",Console messages appearing in incorrect order when reporting progress with IProgress.Report ( ) "C_sharp : I am currently writing a program to help write Lore . Every Book Object can be a parent and have children . Which means that every child can have children etc . into infinity . I was working on a ToString ( ) method that could account for this using recursion , but I keep getting a StackOverflowException.I know what it means , but I am in doubt as to how I fix it . I am fairly new to C # but have quite a lot of Java experience , so if you know a trick or something that I 've missed then please let me know ! So my question is : How do I avoid a StackOverflow Exception ? The problem is in GetAllChildren ( ) EDIT : After running a test , I should get something like this : With the code from @ lc . I get the following output : Here is the class : Name : aChildren : bc de Name : aChildren : No Children bce bce bce class Book { private String name ; private Book [ ] children ; private StringBuilder text ; private Boolean isParent ; public Book ( String name , Book [ ] children , StringBuilder text , Boolean isParent ) { this.name = name ; this.children = children ; this.text = text ; this.isParent = isParent ; } /** * Most likely all possible Constructors * */ public Book ( String name , Book [ ] children ) : this ( name , children , new StringBuilder ( `` No Text '' ) , true ) { } public Book ( String name , String text ) : this ( name , new Book [ 0 ] , new StringBuilder ( text ) , false ) { } public Book ( String name , StringBuilder text ) : this ( name , new Book [ 0 ] , text , false ) { } public Book ( String name ) : this ( name , new Book [ 0 ] , new StringBuilder ( `` No Text '' ) , false ) { } public Book ( Book [ ] children , String text ) : this ( `` Unnamed Book '' , children , new StringBuilder ( text ) , true ) { } public Book ( Book [ ] children , StringBuilder text ) : this ( `` Unnamed Book '' , children , text , true ) { } public Book ( Book [ ] children ) : this ( `` Unnamed Book '' , children , new StringBuilder ( `` No Text '' ) , true ) { } public Book ( StringBuilder text ) : this ( `` Unnamed Book '' , new Book [ 0 ] , text , false ) { } public Book ( ) : this ( `` Unnamed Book '' , new Book [ 0 ] , new StringBuilder ( `` No Text '' ) , false ) { } public String Name { get { return name ; } set { name = value ; } } public Book [ ] Children { get { return children ; } set { children = value ; } } /** * Will Return the StringBuilder Object of this Text * */ public StringBuilder Text { get { return text ; } set { text = value ; } } public Boolean IsParent { get { return isParent ; } set { isParent = value ; } } private void GetAllChildren ( Book book , StringBuilder sb ) { if ( book.isParent ) { GetAllChildren ( book , sb ) ; } else { sb.Append ( `` \t '' ) ; foreach ( Book b in children ) { sb.Append ( b.Name + `` \n '' ) ; } } } public override String ToString ( ) { StringBuilder sChildren = new StringBuilder ( `` No Children '' ) ; if ( children.Length ! = 0 ) { GetAllChildren ( this , sChildren ) ; } return `` Name : `` + name + `` \n '' + `` Children : `` + sChildren.ToString ( ) ; } }",StackOverflowException caused by Recursion C_sharp : The following code is supposed to cache the last read . The LastValueCache is a cache that can be accessed by many threads ( this is why I use the shared-memory ) . It is OK for me to have race conditions but I want that other threads would see the changed LastValueCache.The Repository object is used by many threads . I do not want to use locking because it would affect performance which in my case is more important than data consistency . The question is what smallest synchronizing mechanism that will fit my need ? Maybe volatile or single MemoryBarrier in get and set would be enough ? class Repository { public Item LastValueCache { get { Thread.MemoryBarrier ( ) ; SomeType result = field ; Thread.MemoryBarrier ( ) ; return result ; } set { Thread.MemoryBarrier ( ) ; field = value ; Thread.MemoryBarrier ( ) ; } } public void Save ( Item item ) { SaveToDatabase ( item ) ; Item cached = LastValueCache ; if ( cached == null || item.Stamp > cached.Stamp ) { LastValueCache = item ; } } public void Remove ( Timestamp stamp ) { RemoveFromDatabase ( item ) ; Item cached = LastValueCache ; if ( cached ! = null & & cached.Stamp == item.Stamp ) { LastValueCache = null ; } } public Item Get ( Timestamp stamp ) { Item cached = LastValueCache ; if ( cached ! = null & & cached.Stamp == stamp ) { return cached ; } return GetFromDatabase ( stamp ) ; } },High performance caching "C_sharp : So for an assignment we need to have the option to either use the C # -Lock or use a self-implemented TaS-Lock . What I 've read about TaS-Locks is that it uses 1 atomic step to both read and write a value . It was suggested to us that we use the Interlocked class in C # for this.So far this is what I 've got , but it seems to result in inconsistent answers : Does anyone know what I 'm doing wrong here ? Edit : As a response to Kevin : I 've changed it to the following : However this still returns inconsistent results.Edit # 2 : Changes to C # lock : public interface Lock { void Lock ( ) ; void Unlock ( ) ; } public class C_Sharp_Lock : Lock { readonly Object myLock = new object ( ) ; public void Lock ( ) { Monitor.Enter ( myLock ) ; } public void Unlock ( ) { Monitor.Exit ( myLock ) ; } } public class Tas_Lock : Lock { int L = 0 ; public void Lock ( ) { while ( 0 == Interlocked.Exchange ( ref L , 1 ) ) { } ; } public void Unlock ( ) { Interlocked.Exchange ( ref L , 0 ) ; } } public class Tas_Lock : Lock { int L = 0 ; public void Lock ( ) { while ( 0 == Interlocked.CompareExchange ( ref L , 1 , 0 ) ) { } ; } public void Unlock ( ) { Interlocked.Exchange ( ref L , 0 ) ; } } public class C_Sharp_Lock : Lock { readonly Object myLock = new object ( ) ; bool lockTaken = false ; public void Lock ( ) { Monitor.Enter ( myLock , ref lockTaken ) ; } public void Unlock ( ) { if ( lockTaken ) Monitor.Exit ( myLock ) ; } }",How do I implement my own TaS-Lock in C # ? "C_sharp : I wrote some code in C # 6.0 .NET 3.5 CLR assembly with safety level = external_access.Reduced code : What will be happen with warnings_table if wrapper_func will be called from 2 or more different connections / sessions simultaneously ? There are write operations to static field warnings_table . So , I suppose , but am not sure , it will lead to data race-condition here.In other words : Are static read-only variables in SQLCLR unique for every sql connection/sql query/transactions or do they share data between different SQLCLR procedures calls ? Is it possible to have painless global state , safe from other SQLCLR procedures calls ? public static readonly DataTable warnings_table = init_warnings_table ( ) ; public static void set_warning ( string msg ) { var row = warnings_table.NewRow ( ) ; row [ 1 ] = DateTime.Now ; row [ 2 ] = msg ; ... warnings_table.Rows.Add ( row ) ; } [ Microsoft.SqlServer.Server.SqlProcedure ] public static SqlInt32 wrapper_func ( SqlInt32 param ) { return big_func ( Param.Value ) ; } int big_func ( int param ) { SqlBulkCopy bulkcopy ; ... . set_warning ( `` Message '' ) ; ... . write_warnings ( bulkcopy ) ; warnings_table.Clear ( ) ; }",Is it safe to change static readonly variables in C # SQLCLR ? "C_sharp : I 'm trying to control the volume of an AVPlayer in my iPhone app.I seem to receive an `` unrecognized selector sent to instance '' error when trying to simply get the volume value , or even set it , from the AVPlayer.Volume property - Any ideas how to make this work ? AVPlayer myAVPlayer = new AVPlayer ( ) ; var volume = myAVPlayer.Volume ;",C # Monotouch/Xamarin.iOS - AVPlayer Set Volume "C_sharp : I need to make 100,000s of lightweight ( i.e . small Content-Length ) web requests from a C # console app . What is the fastest way I can do this ( i.e . have completed all the requests in the shortest possible time ) and what best practices should I follow ? I ca n't fire and forget because I need to capture the responses.Presumably I 'd want to use the async web requests methods , however I 'm wondering what the impact of the overhead of storing all the Task continuations and marshalling would be . Memory consumption is not an overall concern , the objective is speed.Presumably I 'd also want to make use of all the cores available.So I can do something like this : but that wont make me any faster than just my number of cores ... I can do : but how do I keep my program running after the ForEach . Holding on to all the Tasks and WhenAlling them feels bloated , are there any existing patterns or helpers to have some kind of Task queue ? Is there any way to get any better , and how should I handle throttling/error detection ? For instance , if the remote endpoint is slow to respond I do n't want to continue spamming itI understand I also need to do : Anything else necessary ? Parallel.ForEach ( iterations , i = > { var response = await MakeRequest ( i ) ; // do thing with response } ) ; Parallel.ForEach ( iterations , i = > { var response = MakeRequest ( i ) ; response.GetAwaiter ( ) .OnCompleted ( ( ) = > { // do thing with response } ) ; } ) ; ServicePointManager.DefaultConnectionLimit = int.MaxValue",How to efficiently make 1000s of web requests as quickly as possible "C_sharp : I attach a debugger by passing '-d ' as a command line parameter to my console app . That causes the following code to be called ; After the Visual Studio 2010 JIT window pops up I sometimes change my mind and do n't want to debug , so I dismiss the dialog . If I do n't attach one then the Application exits immediately without anything being written to the console.I know that this it a bit of an edge use case , I should just remove the '-d ' from the command line if I do n't want to debug . The reason for my question is that I wish to understand what 's happening . I thought the finally block is always called , furthermore I would expect my application to continue if we fail to attach a debugger.Why is nothing printed to the consoleif I decline attaching a debugger ? Does Debugger.Launch ( ) callSystem.Exit on failure to attach ? EDIT Thanks @ Moo-Juice I now know that a return value of false implies a debugger was already attached but the questions above remain unresolved . bool attachedDebugger = false ; try { attachedDebugger = System.Diagnostics.Debugger.Launch ( ) ; } catch ( Exception ) { } finally { Console.WriteLine ( attachedDebugger ? `` Debugger Attached '' : `` Failed to attach debugger '' ) ; }",C # - How to continue after failing to attach debugger - System.Diagnostics.Debugger.Launch ( ) C_sharp : When I declare the following simple classes : and now I use Reflection to get the properties of Class2 like this : then Prop2 will be listed once while Prop1 will be listed twice ! This behaviour seems strange to me . Should n't Prop1 and Prop2 be treated as identical ? ? What can I do to have Prop1 only once in hProperties ? I do n't want to use BindingFlags.DeclaredOnly as I also want to get other protected properties of Class1 that are not overridden . class Class1 < T > { protected virtual T Prop1 { get ; set ; } protected virtual string Prop2 { get ; set ; } } class Class2 : Class1 < string > { protected override string Prop1 { get ; set ; } protected override string Prop2 { get ; set ; } } var hProperties = typeof ( Class2 ) .GetProperties ( BindingFlags.NonPublic | BindingFlags.Instance ) ;,Why does GetProperties list a protected property ( declared in a generic base class ) twice ? "C_sharp : Based upon this post Make a Global ViewBag , I 'm trying to implement the following in ASP.NET Core 2.2 . I realize the original post was for MVC 3.I 'm unable to find in what namespace filterContext.Controller.ViewBag would be defined . Is this still available in ASP.NET Core ? public class CompanyFilter : ActionFilterAttribute { public override void OnActionExecuting ( ActionExecutingContext filterContext ) { filterContext.Controller.ViewBag.Company = `` MyCompany '' ; } }",ViewBag inside of Filters of ASP.NET Core C_sharp : I have the following codes and I would like to write it in a way that I have minimum duplication of codes.Please note that Category and priority do not have a common base type or interface that includes ID . if ( Categories ! = null ) { bool flag=false ; foreach ( dynamic usableCat in Category.LoadForProject ( project.ID ) ) { foreach ( dynamic catRow in Categories ) { if ( usableCat.ID == catRow.ID ) flag = true ; } if ( ! flag ) { int id = usableCat.ID ; Category resolution = Category.Load ( id ) ; resolution.Delete ( Services.UserServices.User ) ; } } } if ( Priorities ! = null ) { bool flag = false ; foreach ( dynamic usableCat in Priority.LoadForProject ( project.ID ) ) { foreach ( dynamic catRow in Priorities ) { if ( usableCat.ID == catRow.ID ) flag = true ; } if ( ! flag ) { int id = usableCat.ID ; Priority resolution = Priority.Load ( id ) ; resolution.Delete ( Services.UserServices.User ) ; } } },How to eliminate duplicate code ? "C_sharp : I have a method which should return a snapshot of the current state , and another method which restores that state.The state Snapshot class should be completely opaque to the caller -- no visible methods or properties -- but its properties have to be visible within the MachineModel class . I could obviously do this by downcasting , i.e . have CurrentSnapshot return an object , and have RestoreSnapshot accept an object argument which it casts back to a Snapshot.But forced casting like that makes me feel dirty . What 's the best alternate design that allows me to be both type-safe and opaque ? Update with solution : I wound up doing a combination of the accepted answer and the suggestion about interfaces . The Snapshot class was made a public abstract class , with a private implementation inside MachineModel : Because the constructor and methods of Snapshot are internal , callers from outside the assembly see it as a completely opaque and can not inherit from it . Callers within the assembly could call Snapshot.Restore rather than MachineModel.Restore , but that 's not a big problem . Furthermore , in practice you could never implement Snapshot.Restore without access to MachineModel 's private members , which should dissuade people from trying to do so . public class MachineModel { public Snapshot CurrentSnapshot { get ; } public void RestoreSnapshot ( Snapshot saved ) { /* etc */ } ; } public class MachineModel { public abstract class Snapshot { protected internal Snapshot ( ) { } abstract internal void Restore ( MachineModel model ) ; } private class SnapshotImpl : Snapshot { /* etc */ } public void Restore ( Snapshot state ) { state.Restore ( this ) ; } }",Return an opaque object to the caller without violating type-safety "C_sharp : ( Yet another question from my `` Clearly I 'm the only idiot out here '' series . ) When I need to use a class from the .NET Framework , I dutifully look up the documentation to determine the corresponding namespace and then add a `` using '' directive to my source code : Usually I 'm good to go at this point , but sometimes Intellisense does n't recognize the new class and the project wo n't build . A quick check in the Object Browser confirms that I have the right namespace . Frustration ensues.Using HttpUtility.UrlEncode ( ) involved adding the appropriate directive : But it also required adding a reference to .NET Framework Component for System.Web , i.e . right-click the project in Solution Explorer , select Add Reference and add System.Web from the .NET tab.How might I discern from the documentation whether a .NET namespace is implemented by a .NET Framework Component that must be referenced ? I 'd rather not hunt through the available components every time I use a namespace on the off chance that a reference is needed . ( For those who like to stay after class and clean the erasers : Will Organize Usings > Remove and Sort also remove references to componenents that are not used elsewhere in the project ? How do you clean up unnecessary references ? ) using System.Text.RegularExpressions ; using System.Web ;",When is a .NET namespace implemented by a .NET Framework component ? "C_sharp : I am currently working on an app which has used inheritance in one scenario . But now I have an task where I need to return more than one viewmodel from my model builder . I will describe below : In my controller method we have kept it light and used model builders.This then hits the builder method which inherits from a base class.Then the NewBuilder has the following implementation : What I need to do is return a different VM from the NewBuilder controller but struggling to finding the best way to do this ? I can not return an InvalidVM as I pass in TaskVM . Just to make people aware this is being used by several views to a different VM and entity class would be passed in ? public ViewResult Summary ( ReportArgs args ) { return View < SomeBuilder > ( args ) ; } public class SomeBuilder : NewBuilder < TaskVM , Task > { } public class NewBuilder < TModel , TItem > : ReportBuilder where TModel : SomeReportVM < TItem > , new ( ) where TItem : ReportItem { public override ReportVM Build ( ReportArgs args ) { /* Some code to get roles here */ return new TModel { FeedbackModel = FeedbackBuilder.Build ( inputGrid.Report.Id ) , } ; } }",Working with inheritance "C_sharp : In developing an F # application , I have a type that comprises a property of type Lazy < 'T > .Apparently , one interesting side effect ( pardon the pun ) of the way that F # handles the syntactical sugar of properties ( as opposed to the C # way ) is that the getter and setter of a property may return/accept different types . ( At least , Visual Studio is not complaining as I write code that takes advantage of this observation . ) For example , it is advantageous for me to do this : ... such that Value returns an int , but accepts only a Lazy < int > .What I am wondering about are the theoretical , idiomatic , and practical objections to doing things this way . Is this something at which an F # snob would turn up his nose ? Is there some functional programming rule of thumb that this ( object-oriented implementation ) clearly violates ? Is this an approach that has been demonstrated to cause problems in large-scale applications ? If so , why/how ? let lazyValue = lazy 0member this.Value with get ( ) = lazyValue.Value and set _lazyVal = lazyValue < - _lazyVal",F # properties vs. C # properties "C_sharp : I recenly encountered this problem in a project : There 's a chain of nested objects , e.g . : class A contains an instance variable of class B , which in turns has an instance variable of class C , ... , until we have a node in the tree of class Z.Each class provides getters and setters for its members . The parent A instance is created by an XML parser , and it is legal for any object in the chain to be null.Now imagine that at a certain point in the application , we have a reference to an A instance , and only if it contains a Z object , we must invoke a method on it . Using regular checks , we get this code : I know that exceptions should not be used for ordinary control flow , but instead of the previous code , I have seen some programmers doing this : The problem with this code is that it may be confuse when maintaining it , since it does n't show clearly which objects are allowed to be null . But on the other hand is much more concise and less `` telescopic '' .Is it an acceptable to do this to save development time ? How could the API be redesigned to avoid this problem ? The only thing I can think of to avoid the long null checking is to provide void instances of the nested objects and providing isValid methods for each one of them , but would n't this create a lot of innecesary objects in memory ? ( I 've used Java code , but the same question can apply to C # properties ) Thanks . -- -- - -- -- - -- -- - -- -- - -- -- - | A | -- - > | B | -- - > | C | -- - > | D | -- - > ... -- - > | Z | -- -- - -- -- - -- -- - -- -- - -- -- - A parentObject ; if ( parentObject.getB ( ) ! = null & & parentObject.getB ( ) .getC ( ) ! = null & & parentObject.getB ( ) .getC ( ) .getD ( ) ! = null & & parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) ! = null & & ... parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) .get ... getZ ( ) ! = null ) { parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) .get ... getZ ( ) .doSomething ( ) ; } try { parentObject.getB ( ) .getC ( ) .getD ( ) .getE ( ) .get ... getZ ( ) .doSomething ( ) ; } catch ( NullPointerException e ) { }",Is it acceptable to use exceptions instead of verbose null-checks ? "C_sharp : Here is some code that troubles me every time I think about it.C # simply will not allow converting strings to integers implicitly.Why does VB let us do that ? I 'm trying to have fun with this because I 'm still relatively new here , but I 'm also genuinely curious . I 'm sure there are devs out there with the answer . Option Strict OnModule Module1 Sub Main ( ) For Each i As Integer In New String ( ) { `` why '' , `` is '' , `` this '' , `` tolerated ? '' } ' compiles just fine . Next End SubEnd Module class Program { static void Main ( string [ ] args ) { foreach ( int i in new string [ ] { `` that 's '' , `` better '' } ) { // will not compile , and for good reason . } } }",VB vs C # : Why is this possible ? C_sharp : What are the arguments to use one or another of those two method implementations ( in Example class ) ? PS : If method returns an IInterface or T I would choose the `` generic '' way to avoid further casting in type T if needed . public interface IInterface { void DoIt ( ) ; } public class Example { public void MethodInterface ( IInterface arg ) { arg.DoIt ( ) ; } public void MethodGeneric < T > ( T arg ) where T : IInterface { arg.DoIt ( ) ; } },Method parameter : Interface VS Generic type "C_sharp : In C # , we can do something like : What is the advantage of using a private setter in the property here while we can set _myField inside the class as we want ? Why would we want to use the setter of MyProperty ? private string _myField ; public string MyProperty { get { return _myField ; } private set { _myField = value ; } }",Why use private property setters since member variables can be accessed directly ? "C_sharp : Is there a way to check to see if a string contains any numeric digits in it without using regex ? I was thinking of just splitting it into an array and running a search on that , but something tells me there is an easier way : //pseudocodestring aString = `` The number 4 '' If ( aString contains a number ) Then enter validation loopElse return to main//output '' The string contains a number . Are you sure you want to continue ? ''",C # : Is there a way to search a string for a number without using regex ? "C_sharp : When using the mini profiler , does this mean production code will be 'littered ' with using blocks ? I guess if it is 1-off testing I could remove it , but usually you want to keep these in the codebase for constant profiling . using ( profiler.Step ( `` Set page title '' ) ) { ViewBag.Title = `` Home Page '' ; }",With the mini-profiler "C_sharp : I am using Tridion release 5.3 . Using the business connector I want to find out if a page has been published to a specific publication target.Using the TOM API I can doIf I query Tridion using the business connector the only information I get is if the page has been published , but not to which targets.I have tried querying the publication target itself but this give no information as to which pages it has published.Any ideas ? // using types from Tridion.ContentManager.Interop.TDS// and Tridion.ContentManager.Interop.TDSDefinesTDSE tdse = new TDSE ( ) ; Page page = ( Page ) tdse.GetObject ( itemUri , EnumOpenMode.OpenModeView , `` tcm:0-0-0 '' , XMLReadFilter.XMLReadAll ) ; page.IsPublishedTo ( tcm ) ;",Tridion : How can I find out if a page has been published to a particular publication target using the business connector ? "C_sharp : Is it possible to perform a global reversed-find on NHibernate-managed objects ? Specifically , I have a persistent class called `` Io '' . There are a huge number of fields across multiple tables which can potentially contain an object of that type . Is there a way ( given a specific instance of an Io object ) , to retrieve a list of objects ( of any type ) that actually do reference that specific object ? ( Bonus points if it can identify which specific fields actually contain the reference , but that 's not critical . ) Since the NHibernate mappings define all the links ( and the underlying database has corresponding foreign key links ) , there ought to be some way to do it.Imagine this sort of structure : Given a specific instance of Io , I want to discover that it 's referenced by the ThingTwo with id 12 . Or that it 's referenced by that and also by the ThingOne with id 16 . If possible , also that the first reference is via SensorInput2 , for example . class Io { public int Id { get ; set ; } // other fields specific to the Io type } class ThingOne { public int Id { get ; set ; } public Io SensorInput { get ; set ; } public Io SolenoidOutput { get ; set ; } // other stuff } class ThingTwo { public int Id { get ; set ; } public Io SensorInput1 { get ; set ; } public Io SensorInput2 { get ; set ; } public SubThing Doohickey { get ; set ; } // ... } class SubThing { public int Id { get ; set ; } public Io ControlOutput1 { get ; set ; } // ... }",Global find object references in NHibernate C_sharp : Let 's say we have these checkboxes : FooCheckBoxBarCheckBoxBazCheckBoxAnd these methods : FooBarBazI want to call each method only if the correponding checkbox is checked . The code might look like this : Now consider that instead of 3 checkboxes and 3 methods you have a lot more . How would you rewrite the code above to make it more DRY ? void DoWork ( ) { if ( FooCheckBox.Checked ) { Foo ( ) ; Console.WriteLine ( `` Foo was called '' ) ; } if ( BarCheckBox.Checked ) { Bar ( ) ; Console.WriteLine ( `` Bar was called '' ) ; } if ( BazCheckBox.Checked ) { Baz ( ) ; Console.WriteLine ( `` Baz was called '' ) ; } },How to make this code more DRY ? "C_sharp : I want to separate my solution into at least two parts : Hosting-technology ( Initializing Kestrel and setting up all the middleware , e.g . swashbuckle , authentication ) Business-Logic & UI because I want the hosting configuration to be replacable in later stages of the development process.I tried simply moving all the folders containing controllers , models and views into a separate project , like shown in the image below : Two projects with hosting configuration and business-logic separated : So Imoved those folders to the *.Implementation projectadded a nuget-reference to the package `` Microsoft.AspNetCore.Mvc '' referenced the *.Implementation project from the *.Host projectadded this class to the `` Controllers '' -folder in the *.Implementation project : If I start the application and open http : //localhost:5000/example in my browser , I get the result `` 5 '' in my browser . This shows to me that the hosting technology finds my controller in the separate project.But when I open http : //localhost:5000 in the browser , I get an exception page telling me that the views for the Home-Controller where not found . The Console also shows the exception : Since the webhost finds my controller , I would expect that it finds the views too . It seems not so . How can I tell the webhost where to look for the views instead ? Or do I need to do anything to them instead ? using Microsoft.AspNetCore.Mvc ; namespace MyApp.Implementation.Controllers { public class ExampleController : Controller { public ActionResult < int > Index ( ) { return 5 ; } } } fail : Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware [ 1 ] An unhandled exception has occurred while executing the request.System.InvalidOperationException : The view 'Index ' was not found . The following locations were searched : /Views/Home/Index.cshtml/Views/Shared/Index.cshtml/Pages/Shared/Index.cshtml",asp.net core mvc : split hosting and business-logic/ui into separate projects "C_sharp : In C # .Net , System.Diagnostics.Debug.WriteLine has several overloads , including these two : My intention is to call the first one with : But it appears that I 'm actually calling the second overload , because it is a more exact match.Is there a simple way to indicate that I want the first one ? My best attempts so far are : But neither of these looks very elegant . //http : //msdn.microsoft.com/en-us/library/cc190153.aspxpublic static void WriteLine ( string format , params Object [ ] args ) ; //http : //msdn.microsoft.com/en-us/library/1w33ay0x.aspxpublic static void WriteLine ( string message , string category ) ; Debug.WriteLine ( `` The path is { 0 } '' , myObj.myPath ) ; Debug.WriteLine ( `` The path is { 0 } '' , new object [ ] { myObj.myPath } ) ; Debug.WriteLine ( `` The path is { 0 } '' , myObj.myPath , `` '' ) ;",Debug.WriteLine overloads seem to conflict "C_sharp : In the implementation of ITaskprovider below , as you see the IUserTask and IIdentityTask is being injected from property instead of constructor.The reason is that Windsor automatically instantiates the injected properties on runtime when accessed so that i dont have to put all the must injected dependencies in the constructor.In the controller I am injecting the ITaskProvider in the constructor.And here i call the taskprovider and its methods fine.Up to here , everything works fine . I have been told that this is more like a service locator pattern and is violating dependency injection pattern and i want to know what is violating here . public interface ITaskProvider { T GetTask < T > ( ) ; } public class TaskProvider : ITaskProvider { public IUserTasks UserTasks { get ; set ; } public IIdentityTasks IdentityTasks { get ; set ; } public T GetTask < T > ( ) { Type type = typeof ( T ) ; if ( type == typeof ( IUserTasks ) ) return ( T ) this.UserTasks ; if ( type == typeof ( IIdentityTasks ) ) return ( T ) this.IdentityTasks ; return default ( T ) ; } } public ITaskProvider TaskProvider { get ; set ; } public AuctionsController ( ITaskProvider taskProvider ) { TaskProvider = taskProvider ; } public ActionResult Index ( ) { var userTasks = TaskProvider.GetTask < IUserTasks > ( ) ; var user = userTasks.FindbyId ( guid ) ; }",Dependency Injection C_sharp : Let 's have a code like this ( fragment of App.xaml.xs ) : Why Elvis operator does n't work with async-await ? Am I missing something ? public class MethodClass { public async Task Job ( ) { Debug.WriteLine ( `` Doing some sob '' ) ; await Task.Delay ( 1 ) ; } } public MethodClass MyClass = null ; protected async override void OnLaunched ( LaunchActivatedEventArgs e ) { await MyClass ? .Job ( ) ; // here goes NullreferenceException MyClass ? .Job ( ) ; // works fine - does nothing,Why Elvis ( ? . ) operator does n't work with async-await ? "C_sharp : Using regex , I can check if it is decimal or notBut what I want to control is total length of those digit.But I still can not control it.After 2 days later , my final solution isDebuggex Demo ^\d*\ . ? \d* $ ( ^\d*\ . ? \d* $ ) { 1,10 } ( ? =^\d*\. ? \d* $ ) ^ . { 1,10 } $",Check decimal and total length of number "C_sharp : I am trying to use Robert C. Martin principle of ISP.From Wikipedia , The ISP was first used and formulated by Robert C. Martin while consulting for Xerox . Xerox had created a new printer system that could perform a variety of tasks such as stapling and faxing . The software for this system was created from the ground up . As the software grew , making modification became more and more difficult so that even the smallest change would take a redeployment cycle of an hour , which made development nearly impossible . The design problem was that a single Job class was used by almost all of the tasks . Whenever a print job or a stapling job needed to be performed , a call was made to the Job class . This resulted in a 'fat ' class with multitudes of methods specific to a variety of different clients . Because of this design , a staple job would know about all the methods of the print job , even though there was no use for them . The solution suggested by Martin utilized what is called the Interface Segregation Principle today . Applied to the Xerox software , an interface layer between the Job class and its clients was added using the Dependency Inversion Principle . Instead of having one large Job class , a Staple Job interface or a Print Job interface was created that would be used by the Staple or Print classes , respectively , calling methods of the Job class . Therefore , one interface was created for each job type , which were all implemented by the Job class.What I am trying to understand is how the system functioned and what Martin proposed to change it.I could try up to this point and got stuck up herean interface layer between the Job class and its clients was added using the Dependency Inversion Principle - Wikipedia lines - ( Interface layer ? ) 1Instead of having one large Job class , a Staple Job interface or a Print Job interface was created that would be used by the Staple or Print classes , respectively , calling methods of the Job class - ( then calling methods of the Job class - ok , create separate interface and then why to call the methods of job class ? ) What Martin did next ? ( Some corrected code skeletons would help me understand this ) .Based on the answers , I was able to proceed as below . Thanks Sergey and Christos.Ok Great . What does the IJob interface do , Why is it used ? It can be removed right ? interface IJob { bool DoPrintJob ( ) ; bool DoStaplingJob ( ) ; bool DoJob1 ( ) ; bool DoJob2 ( ) ; bool DoJob3 ( ) ; } class Job : IJob { // implement all IJob methods here . } var printClient = new Job ( ) ; // a class implemeting IJobprintClient.DoPrintJob ( ) ; // but ` printClient ` also knows about DoStaplingJob ( ) , DoJob1 ( ) , DoJob2 ( ) , DoJob3 ( ) also . interface IPrintJob { bool DoPrintJob ( ) ; } interface IStapleJob { bool DoStapleJob ( ) ; } interface IJob : IPrintJob , IStapleJob { bool DoPrintJob ( ) ; bool DoStaplingJob ( ) ; } var printClient = new PrintJob ( ) ; //PrintJob implements the IPrintJob interface var stapleClient = new StableJob ( ) ; // StapleJob implements the IStapleJob interface",Implementing ISP design pattern in C # "C_sharp : I save the file as 1.java , 2.obj and 3.txt.I then use the Visual Studio Command Prompt to compile the file : csc 1.java csc 2.obj csc 3.txtSurprisingly , it compiles all the 3 files into an executable and executes it successfully.Could anyone give me an explanation on this behavior ? using System ; class Program { public static void Main ( ) { Console.WriteLine ( `` Hello World ! `` ) ; Console.ReadLine ( ) ; } }",C # compiler compiles .txt .obj .java files "C_sharp : I 'm currently facing a problem in C # that I think could be solved using existential types . However , I do n't really know if they can be created in C # , or simulated ( using some other construct ) .Basically I want to have some code like this : Next I want to be able to iterate through a list of objects that implement this interface , but without caring what type parameter it has . Something like this : This does n't compile because the T used by MyIntClass and the one used by MyStringClass are different.I was thinking that something like this could do the trick , but I do n't know if there 's a valid way to do so in C # : public interface MyInterface < T > { T GetSomething ( ) ; void DoSomething ( T something ) ; } public class MyIntClass : MyInterface < int > { int GetSomething ( ) { return 42 ; } void DoSomething ( int something ) { Console.Write ( something ) ; } } public class MyStringClass : MyInterface < string > { string GetSomething ( ) { return `` Something '' ; } void DoSomething ( string something ) { SomeStaticClass.DoSomethingWithString ( something ) ; } } public static void DoALotOfThingsTwice ( ) { var listOfThings = new List < MyInterface < T > > ( ) { new MyIntClass ( ) , new MyStringClass ( ) ; } ; foreach ( MyInterface < T > thingDoer in listOfThings ) { T something = thingDoer.GetSomething ( ) ; thingDoer.DoSomething ( something ) ; thingDoer.DoSomething ( something ) ; } } public static void DoALotOfThingsTwice ( ) { var listOfThings = new List < ∃T.MyInterface < T > > ( ) { new MyIntClass ( ) , new MyStringClass ( ) ; } ; foreach ( ∃T.MyInterface < T > thingDoer in listOfThings ) { T something = thingDoer.GetSomething ( ) ; thingDoer.DoSomething ( something ) ; thingDoer.DoSomething ( something ) ; } }",Existential types in C # ? "C_sharp : I saw a C # class SomeClass that was defined likeand I 'm wondering how to translate that into English . The way I understand it seems logically impossible . How can a class inherit from a parameterized version of itself ? Also , is this a common design pattern ? public class SomeClass : IComparable < SomeClass > , IEquatable < SomeClass > { // ... }",How can a class inherit from a parameterized version of itself ? "C_sharp : The question raised in my mind after Is it possible to access a reference of a struct from a List to make changes ? thread by reza . So , consider the following struct and interface ( definetely not very useful , but just to show the issue ) : MyStruct implements IChangeStruct , so we can change a boxed copy of it right in the heap without unboxing and replacing with a new one . This can be demostrated with the following code : Now , let 's change array to List < T > , i.e . : As far as I understood , in the first case l1 [ 0 ] returned the referense to the boxed struct , while in the second - it was smth else.I also tried to disassemble this and found:1 ) For MyStruct [ ] :2 ) For List < MyStruct > : But I appeared to be not ready to interpret it well.So , what did the List < T > return ? Or how do array and List < T > return elements by index ? Or is this only the case with value types and has nothing to do with reference types ? P.S . : I do understand that one must not change a value type instance , but the described issue made me understand , I never realized how List < T > and array work . public interface IChangeStruct { int Value { get ; } void Change ( int value ) ; } public struct MyStruct : IChangeStruct { int value ; public MyStruct ( int _value ) { value = _value ; } public int Value { get { return value ; } } public void Change ( int value ) { this.value = value ; } } MyStruct [ ] l1 = new MyStruct [ ] { new MyStruct ( 0 ) } ; Console.WriteLine ( l1 [ 0 ] .Value ) ; //0l1 [ 0 ] .Change ( 10 ) ; Console.WriteLine ( l1 [ 0 ] .Value ) ; //10 List < MyStruct > l2 = new List < MyStruct > { new MyStruct ( 0 ) } ; Console.WriteLine ( l2 [ 0 ] .Value ) ; //0l2 [ 0 ] .Change ( 10 ) ; Console.WriteLine ( l2 [ 0 ] .Value ) ; //also 0 IL_0030 : ldelema Utils.MyStructIL_0035 : ldc.i4.s 10IL_0037 : call instance void Utils.MyStruct : :Change ( int32 ) IL_007c : callvirt instance ! 0 class [ mscorlib ] System.Collections.Generic.List ` 1 < valuetype Utils.MyStruct > : :get_Item ( int32 ) IL_0081 : stloc.s CS $ 0 $ 0001 IL_0083 : ldloca.s CS $ 0 $ 0001 IL_0085 : ldc.i4.s 10 IL_0087 : call instance void Utils.MyStruct : :Change ( int32 )",What is the difference between List < T > and array indexers ? "C_sharp : I have a C # 4.0 application and inside this application I have lots of unnecessary variables . Like _foo variable inside the below code : As I mentioned , situations like this one occur inside lots of methods . Would lots of unnecessary variables ( like the ones I explained in this case ) cause performance problem in C # ? Edit : I am not asking any advice if I should remove them or not . My question is all about performance effect . In fact , the app is not written by me and I am new to this project . I just saw and wonder if it has any perf . effect besides the fact that it has a effect on the quality of the code . public string Foo ( ) { var _foo = `` foo bar '' ; return _foo ; }",Would lots of unnecessary variables cause performance issues in C # ? "C_sharp : I currently have two scripts set up in Unity to handle some UI Audio . One is a manager and the other is there to play a sound for a specific UI element . A simplified version of what I have is this : What I 'm trying to achieve here is to have the specifiedUISound field use the sound that it is assigned to it in the inspector . If no sound is assigned then use the generic sound from the UI manager . This saves me assigning the same sound to millions of buttons that require the same sound but gives me the option of having a specific sound for one button if I want to . However , the null-coalessing operator is asigning null to specifiedUISound even though it is null and the audioUIManager 's sound is not . Also , I can get this to work if I use the ternary operator to check for null like so : Am I misunderstanding the null coalescing operator ? Why does this happen ? Edit : Jerry Switalski has pointed out that this only happens when the specifiedUISound is serialized . ( if it is public or if it has the [ SerializeField ] attribute ) . Can anyone shed some light on what is going on here ? public class AudioUIManager : MonoBehaviour //Only one of these in the scene { public AudioClip genericUISound ; //This is set in the inspector . } public class AudioUITextAnimation : MonoBehaviour { [ SerializeField ] private AudioClip specifiedUISound ; //This is not set in the inspector [ SerializeField ] private AudioUIManager audioUIManager ; // I get a reference to this elsewhere void Start ( ) { //Use generic sounds from audio manager if nothing is specified . specifiedUISound = specifiedUISound ? ? audioUIManager.genericUISound ; print ( specifiedUISound ) ; } } specifiedUISound = specifiedUIsound == null ? audioUIManager.genericUISound : specifiedUISound ;",null coalescing operator assignment to self "C_sharp : I ran into some singleton code today in our codebase and I was n't sure if the following was thread-safe : This statement is equivalent to : I believe that ? ? is just a compiler trick and that the resulting code is still NOT atomic . In other words , two or more threads could find _sentence to be null before setting _sentence to a new Sentence and returning it . To guarantee atomicity , we 'd have to lock that bit of code : Is that all correct ? public static IContentStructure Sentence { get { return _sentence ? ? ( _sentence = new Sentence ( ) ) ; } } if ( _sentence ! = null ) { return _sentence ; } else { return ( _sentence = new Sentence ( ) ) ; } public static IContentStructure Sentence { get { lock ( _sentence ) { return _sentence ? ? ( _sentence = new Sentence ( ) ) ; } } }",Atomicity of C # Coalescing Operator "C_sharp : First of all , I 'm very new to C # and Json.I wanted to plot a graph from mysql table data in a C # GUI . I made a PHP file to select the data from mysql database table and echoed the selected contents in json array using echo json_encode ( array ( `` result '' = > $ result ) ) here is my PHP : using the link , I can see the json array clearly between the datetime gap.All I wanted is to plot the graph of temperature values ( temp1 , temp2 , .. ) , p-pairs values and others with the date_time in a line graph to read the historical data . All I get when I access the PHP page is : NOTE : some datetime is set as default here . I just wanted to show this array . The correct one will be perfect to plot the graph.I can can take these array in a string using a web request from C # . using the bellow code : It 'll be a big help If someone can help me to plot this in a line graph as date_time Vs temp1 , temp2 or p_pairs and like that in C # GUI ... This is going to be a big help for me.Thanking you in advance . < ? phpdefine ( 'HOST ' , '********************* ' ) ; define ( 'USER ' , '********************* ' ) ; define ( 'PASS ' , '********************* ' ) ; define ( 'DB ' , '*********************** ' ) ; if ( $ _SERVER [ 'REQUEST_METHOD ' ] =='GET ' ) { $ start = $ _GET [ 'start ' ] ; $ ending = $ _GET [ 'ending ' ] ; } $ con = mysqli_connect ( HOST , USER , PASS , DB ) ; $ sql = `` SELECT * FROM table WHERE date_time BETWEEN ' $ start ' and ' $ ending ' '' ; $ res = mysqli_query ( $ con , $ sql ) ; $ result = array ( ) ; while ( $ row = mysqli_fetch_array ( $ res ) ) { array_push ( $ result , array ( 'id'= > $ row [ 0 ] , 'p_pairs'= > $ row [ 1 ] , 'temp1'= > $ row [ 2 ] , 'temp2'= > $ row [ 3 ] , 'temp3'= > $ row [ 4 ] , 'temp4'= > $ row [ 5 ] , 'temp5'= > $ row [ 6 ] , 'avg_current'= > $ row [ 7 ] , 'avg_voltage'= > $ row [ 8 ] , 'kw'= > $ row [ 9 ] , 'kwh'= > $ row [ 10 ] ) ) ; } echo json_encode ( array ( $ result ) ) ; mysqli_close ( $ con ) ; ? > [ [ { `` id '' : '' 1 '' , '' p_pairs '' : '' 0000-00-00 00:00:00 '' , '' temp1 '' : '' 2 '' , '' temp2 '' : '' 100 '' , '' temp3 '' : '' 100 '' , '' temp4 '' : '' 100 '' , '' temp5 '' : '' 100 '' , '' avg_current '' : '' 100 '' , '' avg_voltage '' : '' 300 '' , '' kw '' : '' 300 '' , '' kwh '' : '' 300 '' } , { `` id '' : '' 2 '' , '' p_pairs '' : '' 0000-00-00 00:00:00 '' , '' temp1 '' : '' 45 '' , '' temp2 '' : '' 105 '' , '' temp3 '' : '' 230 '' , '' temp4 '' : '' 100 '' , '' temp5 '' : '' 2500 '' , '' avg_current '' : '' 570 '' , '' avg_voltage '' : '' 100 '' , '' kw '' : '' 250 '' , '' kwh '' : '' 1000 '' } , { `` id '' : '' 3 '' , '' p_pairs '' : '' 2016-01-07 21:10:00 '' , '' temp1 '' : '' 45 '' , '' temp2 '' : '' 105 '' , '' temp3 '' : '' 230 '' , '' temp4 '' : '' 100 '' , '' temp5 '' : '' 2500 '' , '' avg_current '' : '' 570 '' , '' avg_voltage '' : '' 100 '' , '' kw '' : '' 250 '' , '' kwh '' : '' 1000 '' } , { `` id '' : '' 4 '' , '' p_pairs '' : '' 2016-01-07 21:10:00 '' , '' temp1 '' : '' 45 '' , '' temp2 '' : '' 105 '' , '' temp3 '' : '' 230 '' , '' temp4 '' : '' 100 '' , '' temp5 '' : '' 2500 '' , '' avg_current '' : '' 570 '' , '' avg_voltage '' : '' 100 '' , '' kw '' : '' 250 '' , '' kwh '' : '' 1000 '' } ] ] System.Net.WebClient wc = new System.Net.WebClient ( ) ; byte [ ] raw = wc.DownloadData ( `` url to php '' ) ; string webData = System.Text.Encoding.UTF8.GetString ( raw ) ;",How to plot a line graph using Json array using webrequest "C_sharp : My question is concerning SQL connection status , load , etc . based on the following code : I can see this possibly being a problem if there are many processes running similar code with long execution times between iterations of the IEnumerable object , because the connections will be open longer , etc . However , it also seems plausible that this will reduce the CPU usage on the SQL server because it only returns data when the IEnumerable object is used . It also lowers memory usage on the client because the client only has to load one instance of MyType while it works rather than loading all occurrences of MyType ( by iterating through the entire DataReader and returning a List or something ) .Are there any instances you can think of where you would not want to use IEnumerable in this manner , or any instances you think it fits perfectly ? What kind of load does this put on the SQL server ? Is this something you would use in your own code ( barring any mention of NHibernate , Subsonic , etc ) ? - public IEnumberable < MyType > GetMyTypeObjects ( ) { string cmdTxt = `` select * from MyObjectTable '' ; using ( SqlConnection conn = new SqlConnection ( connString ) ) { using ( SqlCommand cmd = new SqlCommand ( cmdTxt , conn ) ) { conn.Open ( ) ; using ( SqlDataReader reader = cmd.ExecuteReader ( ) ) { while ( reader.Read ( ) ) { yield return Mapper.MapTo < MyType > ( reader ) ; } } } } yield break ; }",Are there any pitfalls to using an IEnumerable < T > return type for SQL data ? "C_sharp : I 'm fairly new to UnitTesting and just encountered a situation I do n't know how to handle and I 'd appreciate any hints : ) The situation is as follows , imagine two methods : HelperMethod functions without dependencies , ActualMethod however depends on HelperMethod and therefore its UnitTest will fail if HelperMethod 's one does . Actually , if I 'm not mistaken , this is where mocking/dependency injection should come to rescue . But in this specific case , I 'd like to test several ( arbitrary large ) edge-cases ( which may not be necessary for the code above , but the actual ActualMethod implementation is a part of fairly complex syntax parser ) . Since HelperMethod is called multiple times in each ActualMethod call , I would have to mock hundreds of HelperMethod calls for my test which just seems unbearable ( now just imagine the number of needed HelperMethod calls would be quadratic to the input.. ) .My question is : how could one elegantly test a method that delegates a huge number of calls to another method ? Should I really mock all these delegate calls ? Or am I maybe allowed to make the method test depend on the other method 's test ( sth . like Assert ( HelperMethodPassed ) ? Or is there no way around changing the design of the implementation ? Unfortunately inlining HelperMethod in the ActualMethod is n't possible because other methods rely on it as well.Thanks in advance , I 'd really appreciate any help ! : ) PS : The project that is being tested is written in C # and I 'm currently using the MSTest framework ( but I 'm open for switching to another framework if this solves the problematic ) .Edit : explicitly marked HelperMethod and ActualMethod as public . // simple standalone methodpublic bool HelperMethod ( string substr ) { return substr.Equals ( `` abc '' ) ; } // complex method making ( multiple ) use of HelperMethodpublic bool ActualMethod ( string str ) { for ( var i=0 ; i < str.Length ; i++ ) { var substr = str.Substring ( i , 3 ) ; if ( HelperMethod ( substr ) ) return true ; } return false ; }",UnitTests : how to test dependent methods where mocking is unfeasible ? "C_sharp : The program below generates different JSON when run in a .NET Core project vs a .NET Framework app.Code.Net Framework : [ { `` Label '' : '' A '' , '' Metric '' :10.0 } , { `` Label '' : '' B '' , '' Metric '' :20.0 } ] .Net Core : Can someone illuminate me on the cause of this , and whether it is an intentional difference ? class Program { internal static readonly MediaTypeFormatter DefaultFormatter = new JsonMediaTypeFormatter { UseDataContractJsonSerializer = false , SerializerSettings = { NullValueHandling = NullValueHandling.Ignore , DateTimeZoneHandling = DateTimeZoneHandling.Utc , DateFormatHandling = DateFormatHandling.IsoDateFormat } } ; private static DataTable BuildTestDataTable ( ) { var testDataTable = new DataTable ( ) ; testDataTable.Columns.Add ( `` Label '' , typeof ( string ) ) ; testDataTable.Columns.Add ( `` Metric '' , typeof ( decimal ) ) ; testDataTable.Rows.Add ( `` A '' , 10 ) ; testDataTable.Rows.Add ( `` B '' , 20 ) ; return testDataTable ; } static void Main ( string [ ] args ) { DataTable table = BuildTestDataTable ( ) ; ObjectContent oc = new ObjectContent ( table.GetType ( ) , table , DefaultFormatter ) ; Console.WriteLine ( oc.ReadAsStringAsync ( ) .Result ) ; Console.ReadKey ( ) ; } } { `` DataTable.RemotingVersion '' : { `` _Major '' : 2 , `` _Minor '' : 0 , `` _Build '' : -1 , `` _Revision '' : -1 } , `` XmlSchema '' : `` < ? xml version=\ '' 1.0\ '' encoding=\ '' utf-16\ '' ? > \r\n < xs : schema xmlns=\ '' \ '' xmlns : xs=\ '' http : //www.w3.org/2001/XMLSchema\ '' xmlns : msdata=\ '' urn : schemas-microsoft-com : xml-msdata\ '' > \r\n < xs : element name=\ '' Table1\ '' > \r\n < xs : complexType > \r\n < xs : sequence > \r\n < xs : element name=\ '' Label\ '' type=\ '' xs : string\ '' msdata : targetNamespace=\ '' \ '' minOccurs=\ '' 0\ '' / > \r\n < xs : element name=\ '' Metric\ '' type=\ '' xs : decimal\ '' msdata : targetNamespace=\ '' \ '' minOccurs=\ '' 0\ '' / > \r\n < /xs : sequence > \r\n < /xs : complexType > \r\n < /xs : element > \r\n < xs : element name=\ '' tmpDataSet\ '' msdata : IsDataSet=\ '' true\ '' msdata : MainDataTable=\ '' Table1\ '' msdata : UseCurrentLocale=\ '' true\ '' > \r\n < xs : complexType > \r\n < xs : choice minOccurs=\ '' 0\ '' maxOccurs=\ '' unbounded\ '' / > \r\n < /xs : complexType > \r\n < /xs : element > \r\n < /xs : schema > '' , `` XmlDiffGram '' : `` < diffgr : diffgram xmlns : msdata=\ '' urn : schemas-microsoft-com : xml-msdata\ '' xmlns : diffgr=\ '' urn : schemas-microsoft-com : xml-diffgram-v1\ '' > \r\n < tmpDataSet > \r\n < Table1 diffgr : id=\ '' Table11\ '' msdata : rowOrder=\ '' 0\ '' diffgr : hasChanges=\ '' inserted\ '' > \r\n < Label > A < /Label > \r\n < Metric > 10 < /Metric > \r\n < /Table1 > \r\n < Table1 diffgr : id=\ '' Table12\ '' msdata : rowOrder=\ '' 1\ '' diffgr : hasChanges=\ '' inserted\ '' > \r\n < Label > B < /Label > \r\n < Metric > 20 < /Metric > \r\n < /Table1 > \r\n < /tmpDataSet > \r\n < /diffgr : diffgram > '' }",Change in JSON generated for a System.Data.DataTable in a .NET Core project vs .NET Framework "C_sharp : How does inheritance work with extension methods in C # .Say you have an interfaces IA , IB : IA and IC , and a class Foo : IB , IC , now one defines extension methods : How does a compiler determines the behavior of Foo.Bar ( ) ? Based on empirical tests , the compiler always selects the most specific instance ( like a normal call ) and without using dynamical binding ( since the this annotation ) is more `` syntactical '' sugar I suppose ... In case two or more classes define a method from different branches in the inheritance hierarchy , the call is ambiguous . Is there a way to define priority of one method over another in such cases ? Are the claims above correct ? public static class Extensions { public static void Bar ( this IA instance ) { //Some code } public static void Bar ( this IB instance ) { //Some code } public static void Bar ( this IC instance ) { //Some code } public static void Bar ( this Foo instance ) { //Some code } }",Inheritance for extension methods C_sharp : So I 've always assumed that casting and converting in c # are basically the same thing : Two different ways to go from one data type to another . Clearly this is incorrect though since they often will output different results.My question is what is the primary difference between the two and why do they return different results ? What is the 'appropriate ' time to use one over the other ? Personally I find myself using the Convert.To method as that seems cleaner to me . I know that it also throws the System.InvalidCastException . Can anyone provide a straightforward explanation ? Convert.ToInt32 ( 1.6 ) //outputs 2 ( Int32 ) 1.6 //outputs 1 ( DateTime ) ( `` 10/29/2013 '' ) //wo n't compile - can not convert type 'string ' to type 'system.date.time'Convert.ToDateTime ( `` 10/29/2013 '' ) //outputs 10/29/2013 12:00:00 AM,Proper time to cast vs. convert in c # "C_sharp : The issue is I am reading a text file full of variables back through a GUI , like replaying a video . As the code is shown , it works and I can control the timer tick to change the replay speed . The issue is the file is in use , so I ca n't write to or delete the text while the file is in use , without closing it first . I would like to either be able to find a workaround of the Streamreader , or use the Filestream to Streamreader code that will allow me to edit the file while it is in use . The issue there is , I ca n't figure out how to make it work with the timer , it just reads the entire file very quickly . Any help or ideas are greatly appreciated.The issue here is how to have the commented out code to : read a line of the text file , have the timer to tickthen read the next line of the text file , and so on . Obviously handling the data as it arrives . StreamReader sr = new StreamReader ( `` C : /CR EZ Test/Log.txt '' ) ; //use with IFprivate void timer2_Tick ( object sender , EventArgs e ) { if ( ( line = sr.ReadLine ( ) ) ! = null ) { //FileStream fs = File.Open ( `` C : /CR EZ Test/Log.txt '' , FileMode.Open , FileAccess.Read , FileShare.ReadWrite ) ; //StreamReader sr = new StreamReader ( fs ) ; //use with While ca n't use with } else { //while ( ( line = sr.ReadLine ( ) ) ! = null ) // { string [ ] dataLog = line.Split ( new [ ] { ' , ' } , StringSplitOptions.None ) ; mpa = ( dataLog [ 1 ] ) ; ml = ( dataLog [ 2 ] ) ; lph = ( dataLog [ 3 ] ) ; elapsedTime = float.Parse ( dataLog [ 4 ] ) / 1000 ; if ( testStatus > 0 ) time = elapsedTime.ToString ( `` 0.0 '' ) ; tb2.Value = int.Parse ( dataLog [ 6 ] ) ; if ( chart1.Series [ 0 ] .Points.Count > tb1.Value & & tb1.Value > 0 ) { chart1.Series [ 0 ] .Points.RemoveAt ( 0 ) ; chart1.Series [ 1 ] .Points.RemoveAt ( 0 ) ; } chart1.Series [ 0 ] .Points.AddXY ( dataLog [ 5 ] , int.Parse ( dataLog [ 1 ] ) ) ; chart1.Series [ 1 ] .Points.AddXY ( dataLog [ 5 ] , int.Parse ( dataLog [ 6 ] ) ) ; // } } else { sr.DiscardBufferedData ( ) ; sr.BaseStream.Seek ( 0 , SeekOrigin.Begin ) ; sr.BaseStream.Position = 0 ; //sr.Close ( ) ; //alertTB.Text = `` '' ; timer2.Enabled = false ; } alertTB.ForeColor = Color.Red ; alertTB.Text = `` Data Log Viewing In Progress '' ; }",Read text file line by line using timer "C_sharp : I 'm trying to load some native linux libraries using mono.I 've run mono with the debug flag : There are lots of lookup positions but at least one of them SHOULD match.This is how my directory looks like : As you can see , the libavformat.57 is there.So is mono telling me that it could not be found ? The following code demonstrates what is done : Declaration of some DllImport methods : The project contains also a file with the name `` { name of the output assembly } .config '' : As you can see above , the mapping works fine . Mono takes `` avformat-57 '' and translates it to `` libavformat.57 '' . Now mono searches for a library with the name `` libavformat.57 '' or some related names like `` libavformat.57.so '' .Mono searches within the directory of the executing assembly.But , it does not manage to find the file it is looking for ( according to the log posted above ) . So why ? Thanks ! Regards Mono : DllImport attempting to load : 'libavformat.57'.Mono : DllImport error loading library '/home/filoe/Desktop/cscore/cscore/Samples/LinuxSample/bin/Debug/libavformat.57 ' : '/home/filoe/Desktop/cscore/cscore/Samples/LinuxSample/bin/Debug/libavformat.57 : can not open shared object file : No such file or directory'.Mono : DllImport error loading library '/home/filoe/Desktop/cscore/cscore/Samples/LinuxSample/bin/Debug/libavformat.57.so ' : 'libavcodec.so.57 : can not open shared object file : No such file or directory'.Mono : DllImport error loading library '/usr/lib/libavformat.57 ' : '/usr/lib/libavformat.57 : can not open shared object file : No such file or directory'.Mono : DllImport error loading library '/usr/lib/libavformat.57.so ' : '/usr/lib/libavformat.57.so : can not open shared object file : No such file or directory'.Mono : DllImport error loading library 'libavformat.57 ' : 'libavformat.57 : can not open shared object file : No such file or directory'.Mono : DllImport error loading library 'libavformat.57.so ' : 'libavformat.57.so : can not open shared object file : No such file or directory'.Mono : DllImport error loading library 'libavformat.57 ' : 'libavformat.57 : can not open shared object file : No such file or directory'.Mono : DllImport unable to load library 'libavformat.57 : can not open shared object file : No such file or directory'.Mono : DllImport attempting to load : 'libavformat.57 ' . filoe @ ubuntu : ~/Desktop/cscore/cscore/Samples/LinuxSample/bin/Debug $ dirCSCore.Ffmpeg.dll CSCore.Ffmpeg.dll.mdb CSCore.Linux.dll.config FFmpeg libavformat.57 libswresample.2 LinuxSample.exe.mdbCSCore.Ffmpeg.dll.config CSCore.Linux.dll CSCore.Linux.dll.mdb libavcodec.57 libavutil.55 LinuxSample.exe log.txtfiloe @ ubuntu : ~/Desktop/cscore/cscore/Samples/LinuxSample/bin/Debug $ [ DllImport ( `` avformat-57 '' , EntryPoint = `` av_register_all '' , CallingConvention = CallingConvention.Cdecl , CharSet = CharSet.Ansi ) ] internal static extern void av_register_all ( ) ; [ DllImport ( `` avcodec-57 '' , EntryPoint = `` avcodec_register_all '' , CallingConvention = CallingConvention.Cdecl , CharSet = CharSet.Ansi ) ] internal static extern void avcodec_register_all ( ) ; < configuration > < dllmap os= '' linux '' dll= '' avcodec-57 '' target= '' libavcodec.57 '' / > < dllmap os= '' linux '' dll= '' avformat-57 '' target= '' libavformat.57 '' / > < /configuration >",Native P/Invoke with Mono on Linux : DllNotFound "C_sharp : I 'm parsing a CSV file and placing the data in a struct . I 'm using the TextFieldParser from this question and it 's working like a charm except that it returns a String [ ] . Currently I have the ugly process of : The struct consists of all those fields being Strings except for AccountID being an int . It annoys me that they 're not strongly typed , but let 's over look that for now . Given that parser.ReadFields ( ) returns a String [ ] is there a more efficient way to fill a struct ( possibly converting some values such as row [ 0 ] needing to become an int ) with the values in the array ? **EDIT : **One restriction I forgot to mention that may impact what kind of solutions will work is that this struct is [ Serializable ] and will be sent Tcp somewhere else . String [ ] row = parser.ReadFields ( ) ; DispatchCall call = new DispatchCall ( ) ; if ( ! int.TryParse ( row [ 0 ] , out call.AccountID ) ) { Console.WriteLine ( `` Invalid Row : `` + parser.LineNumber ) ; continue ; } call.WorkOrder = row [ 1 ] ; call.Description = row [ 2 ] ; call.Date = row [ 3 ] ; call.RequestedDate = row [ 4 ] ; call.EstStartDate = row [ 5 ] ; call.CustomerID = row [ 6 ] ; call.CustomerName = row [ 7 ] ; call.Caller = row [ 8 ] ; call.EquipmentID = row [ 9 ] ; call.Item = row [ 10 ] ; call.TerritoryDesc = row [ 11 ] ; call.Technician = row [ 12 ] ; call.BillCode = row [ 13 ] ; call.CallType = row [ 14 ] ; call.Priority = row [ 15 ] ; call.Status = row [ 16 ] ; call.Comment = row [ 17 ] ; call.Street = row [ 18 ] ; call.City = row [ 19 ] ; call.State = row [ 20 ] ; call.Zip = row [ 21 ] ; call.EquipRemarks = row [ 22 ] ; call.Contact = row [ 23 ] ; call.ContactPhone = row [ 24 ] ; call.Lat = row [ 25 ] ; call.Lon = row [ 26 ] ; call.FlagColor = row [ 27 ] ; call.TextColor = row [ 28 ] ; call.MarkerName = row [ 29 ] ;",Fill struct with String [ ] ? C_sharp : Possible Duplicate : ? ( nullable ) operator in C # In System.Windows.Media.Animation I see the code as follows : What does the ? operator do here ? Does anyone know ? I 've tried to google this but it 's hard to search for the operator if you do n't know what its called by name . I 've checked the page on Operators ( http : //msdn.microsoft.com/en-us/library/6a71f45d ( v=vs.80 ) .aspx ) but the ? operator is not listed there.Thanks ! public double ? By { get ; set ; },Meaning of the ? operator in C # for Properties "C_sharp : I write simple math tokenizer and try to use new C # pattern matching feature.Tokenizer is quite simple : I 'm using case var _ because I want to match by condition without using if-else if chain , but I 'm unable to write case when without specifying var variableName . Is there any fancy way to perform such operation ? Or it is recommended way to do these things ? public IEnumerable < IToken > Tokenize ( string input ) { const char decimalSeparator = ' . ' ; string inputWithoutSpaces = input.Replace ( `` `` , string.Empty ) ; var numberBuffer = new StringBuilder ( ) ; var letterBuffer = new StringBuilder ( ) ; foreach ( char c in inputWithoutSpaces ) { switch ( c ) { case var _ when IsTerm ( c , letterBuffer ) : if ( numberBuffer.Length > 0 ) { yield return EmptyNumberBufferAsLiteral ( numberBuffer ) ; yield return new Operator ( '* ' ) ; } letterBuffer.Append ( c ) ; break ; case decimalSeparator : case var _ when IsDigit ( c ) : numberBuffer.Append ( c ) ; break ; case var _ when IsOperator ( c ) : if ( numberBuffer.Length > 0 ) { yield return EmptyNumberBufferAsLiteral ( numberBuffer ) ; } if ( letterBuffer.Length > 0 ) { yield return EmptyLetterBufferAsTerm ( letterBuffer ) ; } yield return new Operator ( c ) ; break ; } } if ( numberBuffer.Length > 0 ) { yield return EmptyNumberBufferAsLiteral ( numberBuffer ) ; } if ( letterBuffer.Length > 0 ) { yield return EmptyLetterBufferAsTerm ( letterBuffer ) ; } }",Pattern matching case when "C_sharp : In an event handler I 'm responding to the change of a value . I have access to the old value and the new value and want to do certain things depending on what the change is.Each different outcome will do some combination of actions/functions X , Y , or Z . Z accepts a parameter between -1 and 1 . Order of performing these is not important.Look at the following logic grid . The old value is the leftmost column of labels , and the new value is the top row of labels : What would be a good way to represent this ? I 'm working in C # but will accept answers in any language since it 's not really a language question—I can translate whatever.Example : I suppose that looks pretty good , but there are other ways it could be done.This is actually a slightly simpler case than what I 'm dealing with . In the case that oldvalue and newvalue are nonzero and equal to each other , treat newvalue as if it was 0.Feel free to answer as given or with this additional constraint . There 's still a little bit more but I think it 's too much to start off with . If things seem interesting afterward , I 'll present the rest either here or in a new question.I guess I 'm asking the question because I end up with these logic grid things often , and they are n't always 2x2 , sometimes they 're a bit bigger . It 's nice to notice that I can handle some responses with entire `` stripes '' like noticing that X is done every time the oldvalue ! = 0 , but it seems like I 'm starting to run into a pattern that begs for some expressive logic to handle it more generally instead of laboriously turning it into if then else statements . I mean , it would be really cool if I could provide a sort of grid of logic and let the compiler figure out the best way to handle it.Just doing some wild brainstorming : What are your ideas ? I 'll reward any material involvement at all . New : 0 ! =0 -- -- -- -- -- -- -- -Old : 0 | nothing Y , Z ( 1 ) ! =0 | X , Z ( -1 ) X , Y -- Z ( 0 ) is okay but not required for this quadrant if ( oldvalue == 0 & & newvalue == 0 ) return ; if ( oldvalue ! = 0 ) X ( ) ; if ( newvalue ! = 0 ) Y ( ) ; Z ( oldvalue ! = 0 ? -1 : 0 + newvalue ! = 0 ? 1 : 0 ) ; int which = ( oldvalue == 0 ? 0 : 1 ) + ( newvalue == 0 ? 0 : 2 ) switch ( which ) { case 1 : X ( ) ; Z ( -1 ) ; break ; case 2 : Y ( ) ; Z ( 1 ) ; break ; case 3 : X ( ) ; Y ( ) ; break ; } Conditions : oldvalue == 0 ? 0 : 1newvalue == 0 ? 0 : 2Actions : X = { false , true , false , true } Y = { false , false , true , true } Z ( -1 ) = true where condition = 1Z ( 1 ) = true where condition = 2",Expressing 2x2 Logic Grid in Code Efficiently "C_sharp : I have defined my struct like this : but it gives me the following error : `` Error 13 Backing field for automatically implemented property 'EnterResults.frmApplication.Test.NewUnitName ' must be fully assigned before control is returned to the caller . Consider calling the default constructor from a constructor initializer . '' struct Test { private string assayName ; public string AssayName { get ; set ; } private string oldUnitName ; public string OldUnitName { get ; set ; } private string newUnitName ; public string NewUnitName { get ; set ; } public Test ( string name , string oldValue , string newValue ) { assayName = name ; oldUnitName = oldValue ; newUnitName = newValue ; } }",What is wrong with the definition of this Struct type "C_sharp : Let 's suppose I have the following class : Based on this information , my goal is to create a lambda expression like this : lang and name are local variables I would like to add as constant values when creating the expression.As you can see , the compiled function would be of type Func < Genre , bool > To help you understand more clearly , I would like to achieve something similar to this : I am aware of the existence of expression trees but I 'm pretty much new to this topic so I do n't even know how to start.Can this problem be solved ? How can I create such expression dynamically ? public class Show { public string Language { get ; set ; } public string Name { get ; set ; } } g = > g.Language == lang & & g.Name == name string lang = `` en '' ; string name = `` comedy '' ; Genre genre = new Genre { Language = `` en '' , Name = `` comedy '' } ; Expression < Func < Genre , bool > > expression = CreateExpression ( genre , lang , name ) ; // expression = ( g = > g.Language == `` en '' & & g.Name == `` comedy '' )",How to dynamically create a lambda expression C_sharp : How can I check if a WinRT app runs inside the simulator ? For Windows Phone I use following piece of code : But I can not find the solution fot WinRT . Boolean isOnEmulator = ( Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator ) ;,Check if app runs on Simulator "C_sharp : a little while ago i was reading an article about a series of class that were created that handled the conversion of strings into a generic type . Below is a mock class structure . Basically if you set the StringValue it will perform some conversion into type TI can not remember the article that i was reading , or the name of the class i was reading about . Is this already implemented in the framework ? Or shall i create my own ? public class MyClass < T > { public string StringValue { get ; set ; } public T Value { get ; set ; } }",Generic structure for performing string conversion when data binding "C_sharp : Following this site : http : //www.csharp411.com/c-object-clone-wars/I decided to manually create a deep copy of my class ( following site 1 . Clone Manually ) . I implemented the clone interface and any necessary properties . I executed my program and checked if my clone was indeed equal too the original instance . This was correct.However , my new instance still referenced to the original one . So any changes in my copy where reflected into the original instance.So if this does n't create a deep copy , then what does ? What could have gone wrong ? ( I want to make a deep copy manually to increase my performance , so I do not want to use the ObjectCopier class . ( even if it works great , it takes 90 % of my code run time ) .Code Snippets : Class implements : Clone method : Clone method call : I did the same ( implementing and setting clone method ) in all my other classes . ( Field + Coordinate ) public class SudokuAlgorithmNorvig : ICloneable { public object Clone ( ) { SudokuAlgorithmNorvig sudokuClone = new SudokuAlgorithmNorvig ( this.BlockRows , this.BlockColumns ) ; sudokuClone.IsSucces = this.IsSucces ; if ( this.Grid ! = null ) sudokuClone.Grid = ( Field [ , ] ) this.Grid ; if ( this.Peers ! = null ) sudokuClone.Peers = ( Hashtable ) this.Peers ; if ( this.Units ! = null ) sudokuClone.Units = ( Hashtable ) this.Units ; return sudokuClone ; } SudokuAlgorithmNorvig sudokuCopy = ( SudokuAlgorithmNorvig ) sudoku.Clone ( )",How to manually create a deep copy "C_sharp : Is there any way I can get the PropertyInfo for a property from its getter ? Like this : I want to avoid having to hard code the name of the property as a string , as that 's tricky to maintain.I 'm using .NET 2.0 , so I 'm hoping for a linq-less solution . public object Foo { get { PropertyInfo propertyInfoForFoo = xxx ; ... } }",Is there any way to get the PropertyInfo from the getter of that property ? "C_sharp : I wrote this today and I 'm ashamed . What do I need to do to make this chaotic stuff more accurate and readable amongst others ? switch ( ( RequestReportsCalculatingStoredProcedures.RequestReportStoredProcedureType ) Enum.Parse ( typeof ( RequestReportsCalculatingStoredProcedures.RequestReportStoredProcedureType ) , ihdType.Value ) ) { //REF : This can ( but should it ? ) be refactored through strategy pattern case RequestReportsCalculatingStoredProcedures.RequestReportStoredProcedureType.ReportPlanWithEffects : grvEconomicCriteria.DataSource = RequestReportsCalculatingStoredProcedures.ReportsDataParser ( RequestReportsCalculatingStoredProcedures.ReportPlanWithEffects ( requestNo , RequestReportsCalculatingStoredProcedures.GetAlgorithmNoByRequestNo ( requestNo ) ) ) ; break ; case RequestReportsCalculatingStoredProcedures.RequestReportStoredProcedureType.ReportPlanWithEffectsForFacts : DateTime factDate ; try { factDate = Convert.ToDateTime ( ihdDate.Value ) ; } catch ( FormatException ) { grvEconomicCriteria.DataSource = RequestReportsCalculatingStoredProcedures.ReportsDataParser ( RequestReportsCalculatingStoredProcedures.ReportPlanWithEffectsForFacts ( requestNo , RequestReportsCalculatingStoredProcedures.GetAlgorithmNoByRequestNo ( requestNo ) , DateTime.MinValue ) ) ; break ; } grvEconomicCriteria.DataSource = RequestReportsCalculatingStoredProcedures.ReportsDataParser ( RequestReportsCalculatingStoredProcedures.ReportPlanWithEffectsForFacts ( requestNo , RequestReportsCalculatingStoredProcedures.GetAlgorithmNoByRequestNo ( requestNo ) , factDate ) ) ; break ; default : break ; }",How do I make this code more readable ? "C_sharp : Update - The answer is apparently that DbLinq does n't implement Dispose ( ) properly . D'oh ! The below is all sort of misleading - Bottom line : DbLinq is not ( yet ) equivalent to LinqToSql , as I assumed when I originally asked this question . Use it with caution ! I 'm using the Repository Pattern with DbLinq . My repository objects implement IDisposable , and the Dispose ( ) method does only thing -- calls Dispose ( ) on the DataContext . Whenever I use a repository , I wrap it in a using block , like this : This method returns an IEnumerable < Person > , so if my understanding is correct , no querying of the database actually takes place until Enumerable < Person > is traversed ( e.g. , by converting it to a list or array or by using it in a foreach loop ) , as in this example : In this example , Dispose ( ) gets called immediately after setting persons , which is an IEnumerable < Person > , and that 's the only time it gets called.So , three questions : How does this work ? How can a disposed DataContext still query the database for results after the DataContext has been disposed ? What does Dispose ( ) actually do ? I 've heard that it is not necessary ( e.g. , see this question ) to dispose of a DataContext , but my impression was that it 's not a bad idea . Is there any reason not to dispose of a DbLinq DataContext ? public IEnumerable < Person > SelectPersons ( ) { using ( var repository = _repositorySource.GetPersonRepository ( ) ) { return repository.GetAll ( ) ; // returns DataContext.Person as an IQueryable < Person > } } var persons = gateway.SelectPersons ( ) ; // Dispose ( ) is fired herevar personViewModels = ( from b in persons select new PersonViewModel { Id = b.Id , Name = b.Name , Age = b.Age , OrdersCount = b.Order.Count ( ) } ) .ToList ( ) ; // executes queries",Why is it possible to enumerate a DbLinq query after calling Dispose ( ) on the DataContext ?